2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.netconf.it;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.anyString;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
20 import com.google.common.collect.Lists;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import io.netty.channel.EventLoopGroup;
25 import io.netty.channel.local.LocalAddress;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.util.concurrent.GlobalEventExecutor;
28 import java.io.IOException;
29 import java.net.InetSocketAddress;
30 import java.nio.file.Files;
31 import java.util.List;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import org.apache.sshd.server.PasswordAuthenticator;
39 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
40 import org.apache.sshd.server.session.ServerSession;
41 import org.junit.After;
42 import org.junit.Before;
43 import org.junit.Test;
44 import org.opendaylight.controller.netconf.api.NetconfMessage;
45 import org.opendaylight.controller.netconf.auth.AuthProvider;
46 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
47 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
48 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
49 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
50 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
51 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
52 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
53 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
54 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
55 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
56 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
57 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
58 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
59 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
60 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
61 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
62 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
63 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
64 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.RpcResult;
67 import org.xml.sax.SAXException;
69 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
71 public static final int PORT = 12024;
72 private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
74 public static final String USERNAME = "user";
75 public static final String PASSWORD = "pwd";
77 private SshProxyServer sshProxyServer;
79 private ExecutorService nioExec;
80 private EventLoopGroup clientGroup;
81 private ScheduledExecutorService minaTimerEx;
84 public void setUp() throws Exception {
85 nioExec = Executors.newFixedThreadPool(1);
86 clientGroup = new NioEventLoopGroup();
87 minaTimerEx = Executors.newScheduledThreadPool(1);
88 sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
90 new SshProxyServerConfigurationBuilder()
91 .setBindingAddress(TLS_ADDRESS)
92 .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
93 .setAuthenticator(new PasswordAuthenticator() {
95 public boolean authenticate(final String username, final String password, final ServerSession session) {
100 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
101 .setIdleTimeout(Integer.MAX_VALUE)
102 .createSshProxyServerConfiguration());
106 public void tearDown() throws Exception {
107 sshProxyServer.close();
108 clientGroup.shutdownGracefully();
109 minaTimerEx.shutdownNow();
110 nioExec.shutdownNow();
113 @Test(timeout = 2*60*1000)
114 public void testSecure() throws Exception {
115 final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
116 try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(new SimpleNetconfClientSessionListener(), TLS_ADDRESS))) {
117 NetconfMessage response = netconfClient.sendMessage(getGetConfig());
118 assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
119 NetconfMessageUtil.isErrorMessage(response));
121 final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
122 " xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
123 " <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
124 " <identifier>config</identifier>\n" +
128 response = netconfClient.sendMessage(gs);
129 assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
130 NetconfMessageUtil.isErrorMessage(response));
135 * Test all requests are handled properly and no mismatch occurs in listener
137 @Test(timeout = 6*60*1000)
138 public void testSecureStress() throws Exception {
139 final int requests = 4000;
141 final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
142 final NetconfDeviceCommunicator sessionListener = getSessionListener();
143 try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(sessionListener, TLS_ADDRESS))) {
145 final AtomicInteger responseCounter = new AtomicInteger(0);
146 final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
148 for (int i = 0; i < requests; i++) {
149 NetconfMessage getConfig = getGetConfig();
150 getConfig = changeMessageId(getConfig, i);
151 final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
152 futures.add(netconfMessageFuture);
153 Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
155 public void onSuccess(final RpcResult<NetconfMessage> result) {
156 responseCounter.incrementAndGet();
160 public void onFailure(final Throwable t) {
161 throw new RuntimeException(t);
166 // Wait for every future
167 for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
169 future.get(3, TimeUnit.MINUTES);
170 } catch (final TimeoutException e) {
171 fail("Request " + futures.indexOf(future) + " is not responding");
175 // Give future listeners some time to finish counter incrementation
178 assertEquals(requests, responseCounter.get());
182 public static NetconfMessage changeMessageId(final NetconfMessage getConfig, final int i) throws IOException, SAXException {
183 String s = XmlUtil.toString(getConfig.getDocument(), false);
184 s = s.replace("101", Integer.toString(i));
185 return new NetconfMessage(XmlUtil.readXmlToDocument(s));
188 static NetconfClientConfiguration getClientConfiguration(final NetconfClientSessionListener sessionListener,final InetSocketAddress tlsAddress) throws IOException {
189 final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
190 b.withAddress(tlsAddress);
191 // Using session listener from sal-netconf-connector since stress test cannot be performed with simple listener
192 b.withSessionListener(sessionListener);
193 b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
194 b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
195 b.withConnectionTimeoutMillis(5000);
196 b.withAuthHandler(getAuthHandler());
200 static NetconfDeviceCommunicator getSessionListener() {
201 RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> mockedRemoteDevice = mock(RemoteDevice.class);
202 doNothing().when(mockedRemoteDevice).onRemoteSessionUp(any(NetconfSessionPreferences.class), any(NetconfDeviceCommunicator.class));
203 doNothing().when(mockedRemoteDevice).onRemoteSessionDown();
204 return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test"), mockedRemoteDevice);
207 public AuthProvider getAuthProvider() throws Exception {
208 final AuthProvider mockAuth = mock(AuthProvider.class);
209 doReturn("mockedAuth").when(mockAuth).toString();
210 doReturn(true).when(mockAuth).authenticated(anyString(), anyString());
214 public static AuthenticationHandler getAuthHandler() throws IOException {
215 return new LoginPassword(USERNAME, PASSWORD);
219 protected LocalAddress getTcpServerAddress() {
220 return NetconfConfigUtil.getNetconfLocalAddress();