Merge "BUG-2511 Fix XXE vulnerability in Netconf"
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / AbstractNetconfConfigTest.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 package org.opendaylight.controller.netconf.it;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.mockito.Matchers.any;
13 import static org.mockito.Matchers.anySetOf;
14 import static org.mockito.Matchers.anyString;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.EventLoopGroup;
22 import io.netty.channel.local.LocalAddress;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.util.HashedWheelTimer;
25 import io.netty.util.concurrent.GlobalEventExecutor;
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.InetSocketAddress;
30 import java.net.SocketAddress;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.List;
37 import org.apache.commons.io.IOUtils;
38 import org.junit.After;
39 import org.junit.Before;
40 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
41 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
42 import org.opendaylight.controller.config.spi.ModuleFactory;
43 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
44 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
45 import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
46 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
47 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
48 import org.opendaylight.controller.netconf.api.NetconfMessage;
49 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
50 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
51 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
52 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
53 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
54 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
55 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
56 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl;
57 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
58 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
59 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
60 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
61 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
62 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
63 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
64 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
65 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
69 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
70 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
73 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
74 import org.w3c.dom.Element;
75
76 public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
77
78     public static final String LOOPBACK_ADDRESS = "127.0.0.1";
79     public static final int SERVER_CONNECTION_TIMEOUT_MILLIS = 5000;
80
81     static ModuleFactory[] FACTORIES = {new TestImplModuleFactory(),
82                                         new DepTestImplModuleFactory(),
83                                         new NetconfTestImplModuleFactory(),
84                                         new IdentityTestModuleFactory(),
85                                         new MultipleDependenciesModuleFactory() };
86
87     private EventLoopGroup nettyThreadgroup;
88     private HashedWheelTimer hashedWheelTimer;
89
90     private NetconfClientDispatcherImpl clientDispatcher;
91     private Channel serverTcpChannel;
92
93     private NetconfMessage getConfig;
94     private NetconfMessage get;
95
96     /**
97      * @Before in subclasses is called after this method.
98      */
99     @Before
100     public void setUpAbstractNetconfConfigTest() throws Exception {
101         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORIES));
102
103         nettyThreadgroup = new NioEventLoopGroup();
104         hashedWheelTimer = new HashedWheelTimer();
105
106         loadMessages();
107
108         setUpTestInitial();
109
110         final NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
111         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
112
113         for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories()) {
114             factoriesListener.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory);
115         }
116
117         serverTcpChannel = startNetconfTcpServer(factoriesListener);
118         clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
119     }
120
121     /**
122      * Called before setUp method is executed, so test classes can set up resources before setUpAbstractNetconfConfigTest method is called.
123      */
124     protected void setUpTestInitial() throws Exception {}
125
126     private void loadMessages() throws Exception {
127         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
128         this.get = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml");
129     }
130
131     public NetconfMessage getGetConfig() {
132         return getConfig;
133     }
134
135     public NetconfMessage getGet() {
136         return get;
137     }
138
139     private Channel startNetconfTcpServer(final NetconfOperationServiceFactoryListenerImpl factoriesListener) throws Exception {
140         final NetconfServerDispatcher dispatch = createDispatcher(factoriesListener, getNetconfMonitoringService(), getNotificationProducer());
141
142         final ChannelFuture s;
143         if(getTcpServerAddress() instanceof LocalAddress) {
144             s = dispatch.createLocalServer(((LocalAddress) getTcpServerAddress()));
145         } else {
146             s = dispatch.createServer(((InetSocketAddress) getTcpServerAddress()));
147         }
148         s.await();
149         return s.channel();
150     }
151
152     protected DefaultCommitNotificationProducer getNotificationProducer() {
153         final DefaultCommitNotificationProducer notificationProducer = mock(DefaultCommitNotificationProducer.class);
154         doNothing().when(notificationProducer).close();
155         doNothing().when(notificationProducer).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
156         return notificationProducer;
157     }
158
159     protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories() {
160         return Collections.emptySet();
161     }
162
163     protected SessionMonitoringService getNetconfMonitoringService() throws Exception {
164         final NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
165         final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
166         doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
167         doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
168         return new NetconfMonitoringServiceImpl(netconfOperationProvider);
169     }
170
171     protected abstract SocketAddress getTcpServerAddress();
172
173     public NetconfClientDispatcherImpl getClientDispatcher() {
174         return clientDispatcher;
175     }
176
177     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
178         final Collection<InputStream> yangDependencies = getBasicYangs();
179         return new HardcodedYangStoreService(yangDependencies);
180     }
181
182     static Collection<InputStream> getBasicYangs() throws IOException {
183
184         final List<String> paths = Arrays.asList(
185                 "/META-INF/yang/config.yang",
186                 "/META-INF/yang/rpc-context.yang",
187                 "/META-INF/yang/config-test.yang",
188                 "/META-INF/yang/config-test-impl.yang",
189                 "/META-INF/yang/test-types.yang",
190                 "/META-INF/yang/ietf-inet-types.yang");
191
192         final Collection<InputStream> yangDependencies = new ArrayList<>();
193         final List<String> failedToFind = new ArrayList<>();
194         for (final String path : paths) {
195             final InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
196             if (resourceAsStream == null) {
197                 failedToFind.add(path);
198             } else {
199                 yangDependencies.add(resourceAsStream);
200             }
201         }
202         assertEquals("Some yang files were not found", Collections.<String>emptyList(), failedToFind);
203         return yangDependencies;
204     }
205
206     protected NetconfServerDispatcher createDispatcher(
207             final NetconfOperationServiceFactoryListenerImpl factoriesListener, final SessionMonitoringService sessionMonitoringService,
208             final DefaultCommitNotificationProducer commitNotifier) {
209         final SessionIdProvider idProvider = new SessionIdProvider();
210
211         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
212                 hashedWheelTimer, factoriesListener, idProvider, SERVER_CONNECTION_TIMEOUT_MILLIS, commitNotifier, sessionMonitoringService);
213
214         final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
215                 serverNegotiatorFactory);
216         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
217     }
218
219     protected HashedWheelTimer getHashedWheelTimer() {
220         return hashedWheelTimer;
221     }
222
223     protected EventLoopGroup getNettyThreadgroup() {
224         return nettyThreadgroup;
225     }
226
227     /**
228      * @After in subclasses is be called before this.
229      */
230     @After
231     public void cleanUpNetconf() throws Exception {
232         serverTcpChannel.close().await();
233         hashedWheelTimer.stop();
234         nettyThreadgroup.shutdownGracefully().await();
235     }
236
237     public NetconfClientConfiguration getClientConfiguration(final InetSocketAddress tcpAddress, final int timeout) {
238         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
239         b.withAddress(tcpAddress);
240         b.withSessionListener(new SimpleNetconfClientSessionListener());
241         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, timeout));
242         b.withConnectionTimeoutMillis(timeout);
243         return b.build();
244     }
245
246     public static final class HardcodedYangStoreService implements YangStoreService {
247
248         private final List<InputStream> byteArrayInputStreams;
249
250         public HardcodedYangStoreService(final Collection<? extends InputStream> inputStreams) throws YangStoreException, IOException {
251             byteArrayInputStreams = new ArrayList<>();
252             for (final InputStream inputStream : inputStreams) {
253                 assertNotNull(inputStream);
254                 final byte[] content = IOUtils.toByteArray(inputStream);
255                 final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
256                 byteArrayInputStreams.add(byteArrayInputStream);
257             }
258         }
259
260         @Override
261         public YangStoreSnapshot getYangStoreSnapshot() throws YangStoreException {
262             for (final InputStream inputStream : byteArrayInputStreams) {
263                 try {
264                     inputStream.reset();
265                 } catch (final IOException e) {
266                     throw new RuntimeException(e);
267                 }
268             }
269
270             final YangParserImpl yangParser = new YangParserImpl();
271             final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(byteArrayInputStreams).values()));
272             final YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() {
273                 @Override
274                 public SchemaContext getSchemaContext() {
275                     return schemaContext ;
276                 }
277             });
278             return yangStoreService.getYangStoreSnapshot();
279         }
280     }
281 }