BUG-693 Config module for netconf client dispatcher.
[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.mockito.Matchers.any;
12 import static org.mockito.Matchers.anyString;
13 import static org.mockito.Mockito.doAnswer;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16
17 import java.io.File;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.lang.management.ManagementFactory;
21 import java.net.InetSocketAddress;
22 import java.nio.file.Files;
23 import java.util.Collection;
24 import java.util.List;
25
26 import junit.framework.Assert;
27
28 import org.junit.After;
29 import org.junit.Before;
30 import org.junit.Test;
31 import org.mockito.invocation.InvocationOnMock;
32 import org.mockito.stubbing.Answer;
33 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
34 import org.opendaylight.controller.config.spi.ModuleFactory;
35 import org.opendaylight.controller.netconf.api.NetconfMessage;
36 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
37 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
38 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
39 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
40 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
41 import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
42 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
43 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
44 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
45 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
46 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
47 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
48 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
49 import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator;
50 import org.opendaylight.controller.netconf.util.handler.ssh.authentication.AuthenticationHandler;
51 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
52 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
53 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
54 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
55 import org.opendaylight.controller.usermanager.IUserManager;
56 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
57
58 import ch.ethz.ssh2.Connection;
59 import io.netty.channel.ChannelFuture;
60 import io.netty.util.concurrent.GlobalEventExecutor;
61
62 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
63
64     private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024);
65     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
66
67     private DefaultCommitNotificationProducer commitNot;
68     private NetconfSSHServer sshServer;
69     private NetconfMessage getConfig;
70
71     @Before
72     public void setUp() throws Exception {
73         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
74
75         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, getModuleFactories().toArray(
76                 new ModuleFactory[0])));
77
78         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
79         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
80
81         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
82
83
84         final NetconfServerDispatcher dispatchS = createDispatcher(factoriesListener);
85         ChannelFuture s = dispatchS.createServer(tcpAddress);
86         s.await();
87
88         sshServer = NetconfSSHServer.start(tlsAddress.getPort(), tcpAddress, getAuthProvider());
89         Thread thread = new Thread(sshServer);
90         thread.setDaemon(true);
91         thread.start();
92     }
93
94     private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
95         return super.createDispatcher(factoriesListener, NetconfITTest.getNetconfMonitoringListenerService(), commitNot);
96     }
97
98     @After
99     public void tearDown() throws Exception {
100         sshServer.stop();
101         commitNot.close();
102     }
103
104     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
105         final Collection<InputStream> yangDependencies = NetconfITTest.getBasicYangs();
106         return new HardcodedYangStoreService(yangDependencies);
107     }
108
109     protected List<ModuleFactory> getModuleFactories() {
110         return NetconfITTest.getModuleFactoriesS();
111     }
112
113     @Test
114     public void testSecure() throws Exception {
115         NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
116         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration())) {
117             NetconfMessage response = netconfClient.sendMessage(getConfig);
118             Assert.assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
119                     NetconfMessageUtil.isErrorMessage(response));
120
121             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" +
125                     "    </get-schema>\n" +
126                     "</rpc>\n"));
127
128             response = netconfClient.sendMessage(gs);
129             Assert.assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
130                     NetconfMessageUtil.isErrorMessage(response));
131         }
132     }
133
134     public NetconfClientConfiguration getClientConfiguration() throws IOException {
135         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
136         b.withAddress(tlsAddress);
137         b.withSessionListener(new SimpleNetconfClientSessionListener());
138         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
139         b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
140         b.withConnectionTimeoutMillis(5000);
141         b.withAuthHandler(getAuthHandler());
142         return b.build();
143     }
144
145     public AuthProvider getAuthProvider() throws Exception {
146         final IUserManager userManager = mock(IUserManager.class);
147         doReturn(AuthResultEnum.AUTH_ACCEPT).when(userManager).authenticate(anyString(), anyString());
148
149         final File privateKeyFile = Files.createTempFile("tmp-netconf-test", "pk").toFile();
150         privateKeyFile.deleteOnExit();
151         String privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
152         return new AuthProvider(userManager, privateKeyPEMString);
153     }
154
155     public AuthenticationHandler getAuthHandler() throws IOException {
156         final AuthenticationHandler authHandler = mock(AuthenticationHandler.class);
157         doAnswer(new Answer() {
158             @Override
159             public Object answer(final InvocationOnMock invocation) throws Throwable {
160                 Connection conn = (Connection) invocation.getArguments()[0];
161                 conn.authenticateWithPassword("user", "pwd");
162                 return null;
163             }
164         }).when(authHandler).authenticate(any(Connection.class));
165         doReturn("auth handler").when(authHandler).toString();
166         return authHandler;
167     }
168 }