7d568b64628f82ec6499d1d9288ef6eb54b0c572
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfITSecureTest.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.it;
10
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;
19
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.api.RemoteDeviceCommunicator;
62 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
63 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
64 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
65 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
66 import org.opendaylight.yangtools.yang.common.QName;
67 import org.opendaylight.yangtools.yang.common.RpcResult;
68 import org.xml.sax.SAXException;
69
70 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
71
72     public static final int PORT = 12024;
73     private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
74
75     public static final String USERNAME = "user";
76     public static final String PASSWORD = "pwd";
77
78     private SshProxyServer sshProxyServer;
79
80     private ExecutorService nioExec;
81     private EventLoopGroup clientGroup;
82     private ScheduledExecutorService minaTimerEx;
83
84     @Before
85     public void setUp() throws Exception {
86         nioExec = Executors.newFixedThreadPool(1);
87         clientGroup = new NioEventLoopGroup();
88         minaTimerEx = Executors.newScheduledThreadPool(1);
89         sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
90         sshProxyServer.bind(
91                 new SshProxyServerConfigurationBuilder()
92                         .setBindingAddress(TLS_ADDRESS)
93                         .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
94                         .setAuthenticator(new PasswordAuthenticator() {
95                             @Override
96                             public boolean authenticate(final String username, final String password, final ServerSession session) {
97                                 return true;
98                             }
99                         }
100                     )
101                         .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
102                         .setIdleTimeout(Integer.MAX_VALUE)
103                         .createSshProxyServerConfiguration());
104     }
105
106     @After
107     public void tearDown() throws Exception {
108         sshProxyServer.close();
109         clientGroup.shutdownGracefully();
110         minaTimerEx.shutdownNow();
111         nioExec.shutdownNow();
112     }
113
114     @Test(timeout = 2*60*1000)
115     public void testSecure() throws Exception {
116         final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
117         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(new SimpleNetconfClientSessionListener(), TLS_ADDRESS))) {
118             NetconfMessage response = netconfClient.sendMessage(getGetConfig());
119             assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
120                     NetconfMessageUtil.isErrorMessage(response));
121
122             final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
123                     "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
124                     "    <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
125                     "        <identifier>config</identifier>\n" +
126                     "    </get-schema>\n" +
127                     "</rpc>\n"));
128
129             response = netconfClient.sendMessage(gs);
130             assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
131                     NetconfMessageUtil.isErrorMessage(response));
132         }
133     }
134
135     /**
136      * Test all requests are handled properly and no mismatch occurs in listener
137      */
138     @Test(timeout = 6*60*1000)
139     public void testSecureStress() throws Exception {
140         final int requests = 4000;
141
142         final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
143         final NetconfDeviceCommunicator sessionListener = getSessionListener();
144         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(sessionListener, TLS_ADDRESS))) {
145
146             final AtomicInteger responseCounter = new AtomicInteger(0);
147             final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
148
149             for (int i = 0; i < requests; i++) {
150                 NetconfMessage getConfig = getGetConfig();
151                 getConfig = changeMessageId(getConfig, i);
152                 final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
153                 futures.add(netconfMessageFuture);
154                 Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
155                     @Override
156                     public void onSuccess(final RpcResult<NetconfMessage> result) {
157                         responseCounter.incrementAndGet();
158                     }
159
160                     @Override
161                     public void onFailure(final Throwable t) {
162                         throw new RuntimeException(t);
163                     }
164                 });
165             }
166
167             // Wait for every future
168             for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
169                 try {
170                     future.get(3, TimeUnit.MINUTES);
171                 } catch (final TimeoutException e) {
172                     fail("Request " + futures.indexOf(future) + " is not responding");
173                 }
174             }
175
176             // Give future listeners some time to finish counter incrementation
177             Thread.sleep(5000);
178
179             assertEquals(requests, responseCounter.get());
180         }
181     }
182
183     public static NetconfMessage changeMessageId(final NetconfMessage getConfig, final int i) throws IOException, SAXException {
184         String s = XmlUtil.toString(getConfig.getDocument(), false);
185         s = s.replace("101", Integer.toString(i));
186         return new NetconfMessage(XmlUtil.readXmlToDocument(s));
187     }
188
189     static NetconfClientConfiguration getClientConfiguration(final NetconfClientSessionListener sessionListener,final InetSocketAddress tlsAddress) throws IOException {
190         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
191         b.withAddress(tlsAddress);
192         // Using session listener from sal-netconf-connector since stress test cannot be performed with simple listener
193         b.withSessionListener(sessionListener);
194         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
195         b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
196         b.withConnectionTimeoutMillis(5000);
197         b.withAuthHandler(getAuthHandler());
198         return b.build();
199     }
200
201     static NetconfDeviceCommunicator getSessionListener() {
202         RemoteDevice<NetconfSessionCapabilities, NetconfMessage> mockedRemoteDevice = mock(RemoteDevice.class);
203         doNothing().when(mockedRemoteDevice).onRemoteSessionUp(any(NetconfSessionCapabilities.class), any(RemoteDeviceCommunicator.class));
204         doNothing().when(mockedRemoteDevice).onRemoteSessionDown();
205         return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test"), mockedRemoteDevice);
206     }
207
208     public AuthProvider getAuthProvider() throws Exception {
209         final AuthProvider mockAuth = mock(AuthProvider.class);
210         doReturn("mockedAuth").when(mockAuth).toString();
211         doReturn(true).when(mockAuth).authenticated(anyString(), anyString());
212         return mockAuth;
213     }
214
215     public static AuthenticationHandler getAuthHandler() throws IOException {
216         return new LoginPassword(USERNAME, PASSWORD);
217     }
218
219     @Override
220     protected LocalAddress getTcpServerAddress() {
221         return NetconfConfigUtil.getNetconfLocalAddress();
222     }
223 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.