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;
29 import java.io.IOException;
30 import java.net.InetSocketAddress;
31 import java.nio.file.Files;
32 import java.util.List;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.ScheduledExecutorService;
36 import java.util.concurrent.TimeUnit;
37 import java.util.concurrent.TimeoutException;
38 import java.util.concurrent.atomic.AtomicInteger;
39 import org.apache.sshd.server.PasswordAuthenticator;
40 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
41 import org.apache.sshd.server.session.ServerSession;
42 import org.junit.After;
43 import org.junit.Before;
44 import org.junit.Test;
45 import org.mockito.Mock;
46 import org.mockito.MockitoAnnotations;
47 import org.opendaylight.controller.netconf.api.NetconfMessage;
48 import org.opendaylight.controller.netconf.auth.AuthProvider;
49 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
50 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
51 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
52 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
53 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
54 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
55 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
56 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
57 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
58 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
59 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
60 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
61 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
62 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
63 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
64 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
65 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
66 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
67 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
68 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
69 import org.opendaylight.yangtools.yang.common.QName;
70 import org.opendaylight.yangtools.yang.common.RpcResult;
71 import org.xml.sax.SAXException;
73 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
75 public static final int PORT = 12024;
76 private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
78 public static final String USERNAME = "user";
79 public static final String PASSWORD = "pwd";
81 private File sshKeyPair;
82 private SshProxyServer sshProxyServer;
84 private ExecutorService nioExec;
85 private EventLoopGroup clientGroup;
86 private ScheduledExecutorService minaTimerEx;
89 public void setUp() throws Exception {
90 sshKeyPair = Files.createTempFile("sshKeyPair", ".pem").toFile();
91 sshKeyPair.deleteOnExit();
92 nioExec = Executors.newFixedThreadPool(1);
93 clientGroup = new NioEventLoopGroup();
94 minaTimerEx = Executors.newScheduledThreadPool(1);
95 sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
97 new SshProxyServerConfigurationBuilder()
98 .setBindingAddress(TLS_ADDRESS)
99 .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
100 .setAuthenticator(new PasswordAuthenticator() {
102 public boolean authenticate(final String username, final String password, final ServerSession session) {
106 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString()))
107 .setIdleTimeout(Integer.MAX_VALUE)
108 .createSshProxyServerConfiguration());
112 public void tearDown() throws Exception {
113 sshProxyServer.close();
114 clientGroup.shutdownGracefully().await();
115 minaTimerEx.shutdownNow();
116 nioExec.shutdownNow();
120 public void testSecure() throws Exception {
121 final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
122 try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(new SimpleNetconfClientSessionListener()))) {
123 NetconfMessage response = netconfClient.sendMessage(getGetConfig());
124 assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
125 NetconfMessageUtil.isErrorMessage(response));
127 final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
128 " xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
129 " <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
130 " <identifier>config</identifier>\n" +
134 response = netconfClient.sendMessage(gs);
135 assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
136 NetconfMessageUtil.isErrorMessage(response));
141 * Test all requests are handled properly and no mismatch occurs in listener
143 @Test(timeout = 6*60*1000)
144 public void testSecureStress() throws Exception {
145 final int requests = 4000;
147 final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
148 final NetconfDeviceCommunicator sessionListener = getSessionListener();
149 try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(sessionListener))) {
151 final AtomicInteger responseCounter = new AtomicInteger(0);
152 final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
154 for (int i = 0; i < requests; i++) {
155 NetconfMessage getConfig = getGetConfig();
156 getConfig = changeMessageId(getConfig, i);
157 final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
158 futures.add(netconfMessageFuture);
159 Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
161 public void onSuccess(final RpcResult<NetconfMessage> result) {
162 responseCounter.incrementAndGet();
166 public void onFailure(final Throwable t) {
167 throw new RuntimeException(t);
172 // Wait for every future
173 for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
175 future.get(3, TimeUnit.MINUTES);
176 } catch (final TimeoutException e) {
177 fail("Request " + futures.indexOf(future) + " is not responding");
181 // Give future listeners some time to finish counter incrementation
184 assertEquals(requests, responseCounter.get());
188 private NetconfMessage changeMessageId(final NetconfMessage getConfig, final int i) throws IOException, SAXException {
189 String s = XmlUtil.toString(getConfig.getDocument(), false);
190 s = s.replace("101", Integer.toString(i));
191 return new NetconfMessage(XmlUtil.readXmlToDocument(s));
194 public NetconfClientConfiguration getClientConfiguration(final NetconfClientSessionListener sessionListener) throws IOException {
195 final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
196 b.withAddress(TLS_ADDRESS);
197 // Using session listener from sal-netconf-connector since stress test cannot be performed with simple listener
198 b.withSessionListener(sessionListener);
199 b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
200 b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
201 b.withConnectionTimeoutMillis(5000);
202 b.withAuthHandler(getAuthHandler());
207 private RemoteDevice<NetconfSessionCapabilities, NetconfMessage> mockedRemoteDevice;
209 private NetconfDeviceCommunicator getSessionListener() {
210 MockitoAnnotations.initMocks(this);
211 doNothing().when(mockedRemoteDevice).onRemoteSessionUp(any(NetconfSessionCapabilities.class), any(RemoteDeviceCommunicator.class));
212 doNothing().when(mockedRemoteDevice).onRemoteSessionDown();
213 return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test"), mockedRemoteDevice);
216 public AuthProvider getAuthProvider() throws Exception {
217 final AuthProvider mockAuth = mock(AuthProvider.class);
218 doReturn("mockedAuth").when(mockAuth).toString();
219 doReturn(true).when(mockAuth).authenticated(anyString(), anyString());
223 public AuthenticationHandler getAuthHandler() throws IOException {
224 return new LoginPassword(USERNAME, PASSWORD);
228 protected LocalAddress getTcpServerAddress() {
229 return NetconfConfigUtil.getNetconfLocalAddress();