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