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.mockito.Mock;
45 import org.mockito.MockitoAnnotations;
46 import org.opendaylight.controller.netconf.api.NetconfMessage;
47 import org.opendaylight.controller.netconf.auth.AuthProvider;
48 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
49 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
50 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
51 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
52 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
53 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
54 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
55 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
56 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
57 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
58 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
59 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
60 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
61 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
62 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
63 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
64 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
65 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
66 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
67 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
68 import org.opendaylight.yangtools.yang.common.QName;
69 import org.opendaylight.yangtools.yang.common.RpcResult;
70 import org.xml.sax.SAXException;
72 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
74 public static final int PORT = 12024;
75 private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
77 public static final String USERNAME = "user";
78 public static final String PASSWORD = "pwd";
80 private SshProxyServer sshProxyServer;
82 private ExecutorService nioExec;
83 private EventLoopGroup clientGroup;
84 private ScheduledExecutorService minaTimerEx;
87 public void setUp() throws Exception {
88 nioExec = Executors.newFixedThreadPool(1);
89 clientGroup = new NioEventLoopGroup();
90 minaTimerEx = Executors.newScheduledThreadPool(1);
91 sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
93 new SshProxyServerConfigurationBuilder()
94 .setBindingAddress(TLS_ADDRESS)
95 .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
96 .setAuthenticator(new PasswordAuthenticator() {
98 public boolean authenticate(final String username, final String password, final ServerSession session) {
102 .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
103 .setIdleTimeout(Integer.MAX_VALUE)
104 .createSshProxyServerConfiguration());
108 public void tearDown() throws Exception {
109 sshProxyServer.close();
110 clientGroup.shutdownGracefully().await();
111 minaTimerEx.shutdownNow();
112 nioExec.shutdownNow();
116 public void testSecure() throws Exception {
117 final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
118 try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(new SimpleNetconfClientSessionListener()))) {
119 NetconfMessage response = netconfClient.sendMessage(getGetConfig());
120 assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
121 NetconfMessageUtil.isErrorMessage(response));
123 final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
124 " xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
125 " <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
126 " <identifier>config</identifier>\n" +
130 response = netconfClient.sendMessage(gs);
131 assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
132 NetconfMessageUtil.isErrorMessage(response));
137 * Test all requests are handled properly and no mismatch occurs in listener
139 @Test(timeout = 6*60*1000)
140 public void testSecureStress() throws Exception {
141 final int requests = 4000;
143 final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
144 final NetconfDeviceCommunicator sessionListener = getSessionListener();
145 try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(sessionListener))) {
147 final AtomicInteger responseCounter = new AtomicInteger(0);
148 final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
150 for (int i = 0; i < requests; i++) {
151 NetconfMessage getConfig = getGetConfig();
152 getConfig = changeMessageId(getConfig, i);
153 final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
154 futures.add(netconfMessageFuture);
155 Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
157 public void onSuccess(final RpcResult<NetconfMessage> result) {
158 responseCounter.incrementAndGet();
162 public void onFailure(final Throwable t) {
163 throw new RuntimeException(t);
168 // Wait for every future
169 for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
171 future.get(3, TimeUnit.MINUTES);
172 } catch (final TimeoutException e) {
173 fail("Request " + futures.indexOf(future) + " is not responding");
177 // Give future listeners some time to finish counter incrementation
180 assertEquals(requests, responseCounter.get());
184 private NetconfMessage changeMessageId(final NetconfMessage getConfig, final int i) throws IOException, SAXException {
185 String s = XmlUtil.toString(getConfig.getDocument(), false);
186 s = s.replace("101", Integer.toString(i));
187 return new NetconfMessage(XmlUtil.readXmlToDocument(s));
190 public NetconfClientConfiguration getClientConfiguration(final NetconfClientSessionListener sessionListener) throws IOException {
191 final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
192 b.withAddress(TLS_ADDRESS);
193 // Using session listener from sal-netconf-connector since stress test cannot be performed with simple listener
194 b.withSessionListener(sessionListener);
195 b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
196 b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
197 b.withConnectionTimeoutMillis(5000);
198 b.withAuthHandler(getAuthHandler());
203 private RemoteDevice<NetconfSessionCapabilities, NetconfMessage> mockedRemoteDevice;
205 private NetconfDeviceCommunicator getSessionListener() {
206 MockitoAnnotations.initMocks(this);
207 doNothing().when(mockedRemoteDevice).onRemoteSessionUp(any(NetconfSessionCapabilities.class), any(RemoteDeviceCommunicator.class));
208 doNothing().when(mockedRemoteDevice).onRemoteSessionDown();
209 return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test"), mockedRemoteDevice);
212 public AuthProvider getAuthProvider() throws Exception {
213 final AuthProvider mockAuth = mock(AuthProvider.class);
214 doReturn("mockedAuth").when(mockAuth).toString();
215 doReturn(true).when(mockAuth).authenticated(anyString(), anyString());
219 public AuthenticationHandler getAuthHandler() throws IOException {
220 return new LoginPassword(USERNAME, PASSWORD);
224 protected LocalAddress getTcpServerAddress() {
225 return NetconfConfigUtil.getNetconfLocalAddress();