Make netconf utilize encrypted passwords only
[netconf.git] / netconf / netconf-topology-singleton / src / main / java / org / opendaylight / netconf / topology / singleton / impl / RemoteDeviceConnectorImpl.java
1 /*
2  * Copyright (c) 2016 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.netconf.topology.singleton.impl;
10
11 import akka.actor.ActorRef;
12 import akka.util.Timeout;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Lists;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import io.netty.util.concurrent.EventExecutor;
20 import java.math.BigDecimal;
21 import java.net.InetSocketAddress;
22 import java.net.URL;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Objects;
27 import java.util.Optional;
28 import javax.annotation.Nullable;
29 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
30 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
31 import org.opendaylight.netconf.api.NetconfMessage;
32 import org.opendaylight.netconf.client.NetconfClientSessionListener;
33 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
34 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
35 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
36 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
37 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
38 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
39 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
40 import org.opendaylight.netconf.sal.connect.netconf.LibraryModulesSchemas;
41 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
42 import org.opendaylight.netconf.sal.connect.netconf.NetconfDeviceBuilder;
43 import org.opendaylight.netconf.sal.connect.netconf.SchemalessNetconfDevice;
44 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
45 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
46 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
47 import org.opendaylight.netconf.sal.connect.netconf.listener.UserPreferences;
48 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade;
49 import org.opendaylight.netconf.sal.connect.netconf.schema.YangLibrarySchemaYangSourceProvider;
50 import org.opendaylight.netconf.sal.connect.util.AuthEncryptor;
51 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
52 import org.opendaylight.netconf.topology.singleton.api.RemoteDeviceConnector;
53 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfConnectorDTO;
54 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
55 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
56 import org.opendaylight.protocol.framework.ReconnectStrategy;
57 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
58 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
59 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Host;
60 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability.CapabilityOrigin;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.credentials.Credentials;
64 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
67 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
73
74     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
75
76     // Initializes default constant instances for the case when the default schema repository
77     // directory cache/schema is used.
78
79     private final NetconfTopologySetup netconfTopologyDeviceSetup;
80     private final RemoteDeviceId remoteDeviceId;
81     private final DOMMountPointService mountService;
82     private final Timeout actorResponseWaitTime;
83     private final AAAEncryptionService encryptionService;
84
85     private NetconfConnectorDTO deviceCommunicatorDTO;
86
87     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
88                                      final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
89                                      final DOMMountPointService mountService) {
90
91         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
92         this.remoteDeviceId = remoteDeviceId;
93         this.actorResponseWaitTime = actorResponseWaitTime;
94         this.mountService = mountService;
95         this.encryptionService = netconfTopologyDeviceSetup.getEncryptionService();
96
97     }
98
99     @Override
100     public void startRemoteDeviceConnection(final ActorRef deviceContextActorRef) {
101
102         final NetconfNode netconfNode = netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class);
103         final NodeId nodeId = netconfTopologyDeviceSetup.getNode().getNodeId();
104
105         AuthEncryptor.encryptIfNeeded(nodeId, netconfNode, encryptionService,
106                 netconfTopologyDeviceSetup.getTopologyId(),
107                 netconfTopologyDeviceSetup.getDataBroker());
108
109         Preconditions.checkNotNull(netconfNode.getHost());
110         Preconditions.checkNotNull(netconfNode.getPort());
111         Preconditions.checkNotNull(netconfNode.isTcpOnly());
112
113         this.deviceCommunicatorDTO = createDeviceCommunicator(nodeId, netconfNode, deviceContextActorRef);
114         final NetconfDeviceCommunicator deviceCommunicator = deviceCommunicatorDTO.getCommunicator();
115         final NetconfClientSessionListener netconfClientSessionListener = deviceCommunicatorDTO.getSessionListener();
116         final NetconfReconnectingClientConfiguration clientConfig =
117                 getClientConfig(netconfClientSessionListener, netconfNode);
118         final ListenableFuture<NetconfDeviceCapabilities> future = deviceCommunicator
119                 .initializeRemoteConnection(netconfTopologyDeviceSetup.getNetconfClientDispatcher(), clientConfig);
120
121         Futures.addCallback(future, new FutureCallback<NetconfDeviceCapabilities>() {
122             @Override
123             public void onSuccess(final NetconfDeviceCapabilities result) {
124                 LOG.debug("{}: Connector started successfully", remoteDeviceId);
125             }
126
127             @Override
128             public void onFailure(@Nullable final Throwable throwable) {
129                 LOG.error("{}: Connector failed, {}", remoteDeviceId, throwable);
130             }
131         });
132     }
133
134     @SuppressWarnings("checkstyle:IllegalCatch")
135     @Override
136     public void stopRemoteDeviceConnection() {
137         Preconditions.checkNotNull(deviceCommunicatorDTO, remoteDeviceId + ": Device communicator was not created.");
138         try {
139             deviceCommunicatorDTO.close();
140         } catch (final Exception e) {
141             LOG.error("{}: Error at closing device communicator.", remoteDeviceId, e);
142         }
143     }
144
145     @VisibleForTesting
146     NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node,
147                                                  final ActorRef deviceContextActorRef) {
148         //setup default values since default value is not supported in mdsal
149         final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null
150                 ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis();
151         final Long keepaliveDelay = node.getKeepaliveDelay() == null
152                 ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay();
153         final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null
154                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
155
156         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
157                 netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
158                 mountService, netconfTopologyDeviceSetup.getDataBroker());
159         if (keepaliveDelay > 0) {
160             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
161             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
162                     netconfTopologyDeviceSetup.getKeepaliveExecutor().getExecutor(), keepaliveDelay,
163                     defaultRequestTimeoutMillis);
164         }
165
166         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = netconfTopologyDeviceSetup.getSchemaResourcesDTO();
167
168
169         // pre register yang library sources as fallback schemas to schema registry
170         final List<SchemaSourceRegistration<YangTextSchemaSource>> registeredYangLibSources = Lists.newArrayList();
171         if (node.getYangLibrary() != null) {
172             final String yangLibURL = node.getYangLibrary().getYangLibraryUrl().getValue();
173             final String yangLibUsername = node.getYangLibrary().getUsername();
174             final String yangLigPassword = node.getYangLibrary().getPassword();
175
176             final LibraryModulesSchemas libraryModulesSchemas;
177             if (yangLibURL != null) {
178                 if (yangLibUsername != null && yangLigPassword != null) {
179                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL, yangLibUsername, yangLigPassword);
180                 } else {
181                     libraryModulesSchemas = LibraryModulesSchemas.create(yangLibURL);
182                 }
183
184                 for (final Map.Entry<SourceIdentifier, URL> sourceIdentifierURLEntry :
185                         libraryModulesSchemas.getAvailableModels().entrySet()) {
186                     registeredYangLibSources
187                             .add(schemaResourcesDTO.getSchemaRegistry().registerSchemaSource(
188                                     new YangLibrarySchemaYangSourceProvider(remoteDeviceId,
189                                             libraryModulesSchemas.getAvailableModels()),
190                                     PotentialSchemaSource
191                                             .create(sourceIdentifierURLEntry.getKey(), YangTextSchemaSource.class,
192                                                     PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
193                 }
194             }
195         }
196
197         final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device;
198         if (node.isSchemaless()) {
199             device = new SchemalessNetconfDevice(remoteDeviceId, salFacade);
200         } else {
201             device = new NetconfDeviceBuilder()
202                     .setReconnectOnSchemasChange(reconnectOnChangedSchema)
203                     .setSchemaResourcesDTO(schemaResourcesDTO)
204                     .setGlobalProcessingExecutor(netconfTopologyDeviceSetup.getProcessingExecutor().getExecutor())
205                     .setId(remoteDeviceId)
206                     .setSalFacade(salFacade)
207                     .build();
208         }
209
210         final Optional<NetconfSessionPreferences> userCapabilities = getUserCapabilities(node);
211         final int rpcMessageLimit =
212                 node.getConcurrentRpcLimit() == null
213                         ? NetconfTopologyUtils.DEFAULT_CONCURRENT_RPC_LIMIT : node.getConcurrentRpcLimit();
214
215         if (rpcMessageLimit < 1) {
216             LOG.info("{}: Concurrent rpc limit is smaller than 1, no limit will be enforced.", remoteDeviceId);
217         }
218
219         return new NetconfConnectorDTO(
220                 userCapabilities.isPresent() ? new NetconfDeviceCommunicator(remoteDeviceId, device,
221                         new UserPreferences(userCapabilities.get(),
222                                 Objects.isNull(node.getYangModuleCapabilities())
223                                         ? false : node.getYangModuleCapabilities().isOverride(),
224                                 Objects.isNull(node.getNonModuleCapabilities())
225                                         ? false : node.getNonModuleCapabilities().isOverride()), rpcMessageLimit)
226                         : new NetconfDeviceCommunicator(remoteDeviceId, device, rpcMessageLimit), salFacade);
227     }
228
229     private Optional<NetconfSessionPreferences> getUserCapabilities(final NetconfNode node) {
230         if (node.getYangModuleCapabilities() == null && node.getNonModuleCapabilities() == null) {
231             return Optional.empty();
232         }
233         final List<String> capabilities = new ArrayList<>();
234
235         if (node.getYangModuleCapabilities() != null) {
236             capabilities.addAll(node.getYangModuleCapabilities().getCapability());
237         }
238
239         //non-module capabilities should not exist in yang module capabilities
240         final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(capabilities);
241         Preconditions.checkState(netconfSessionPreferences.getNonModuleCaps().isEmpty(),
242                 "List yang-module-capabilities/capability should contain only module based capabilities. "
243                         + "Non-module capabilities used: " + netconfSessionPreferences.getNonModuleCaps());
244
245         if (node.getNonModuleCapabilities() != null) {
246             capabilities.addAll(node.getNonModuleCapabilities().getCapability());
247         }
248
249         return Optional.of(NetconfSessionPreferences.fromStrings(capabilities, CapabilityOrigin.UserDefined));
250     }
251
252     //TODO: duplicate code
253     private InetSocketAddress getSocketAddress(final Host host, final int port) {
254         if (host.getDomainName() != null) {
255             return new InetSocketAddress(host.getDomainName().getValue(), port);
256         } else {
257             final IpAddress ipAddress = host.getIpAddress();
258             final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() :
259                     ipAddress.getIpv6Address().getValue();
260             return new InetSocketAddress(ip, port);
261         }
262     }
263
264     @VisibleForTesting
265     NetconfReconnectingClientConfiguration getClientConfig(final NetconfClientSessionListener listener,
266                                                            final NetconfNode node) {
267
268         //setup default values since default value is not supported in mdsal
269         final long clientConnectionTimeoutMillis = node.getConnectionTimeoutMillis() == null
270                 ? NetconfTopologyUtils.DEFAULT_CONNECTION_TIMEOUT_MILLIS : node.getConnectionTimeoutMillis();
271         final long maxConnectionAttempts = node.getMaxConnectionAttempts() == null
272                 ? NetconfTopologyUtils.DEFAULT_MAX_CONNECTION_ATTEMPTS : node.getMaxConnectionAttempts();
273         final int betweenAttemptsTimeoutMillis = node.getBetweenAttemptsTimeoutMillis() == null
274                 ? NetconfTopologyUtils.DEFAULT_BETWEEN_ATTEMPTS_TIMEOUT_MILLIS : node.getBetweenAttemptsTimeoutMillis();
275         final BigDecimal sleepFactor = node.getSleepFactor() == null
276                 ? NetconfTopologyUtils.DEFAULT_SLEEP_FACTOR : node.getSleepFactor();
277
278         final InetSocketAddress socketAddress = getSocketAddress(node.getHost(), node.getPort().getValue());
279
280         final ReconnectStrategyFactory sf =
281                 new TimedReconnectStrategyFactory(netconfTopologyDeviceSetup.getEventExecutor(), maxConnectionAttempts,
282                         betweenAttemptsTimeoutMillis, sleepFactor);
283         final ReconnectStrategy strategy = sf.createReconnectStrategy();
284
285         final AuthenticationHandler authHandler;
286         final Credentials credentials = node.getCredentials();
287         if (credentials instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
288                 .node.credentials.credentials.LoginPassword) {
289             authHandler = new LoginPassword(
290                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
291                             .node.credentials.credentials.LoginPassword) credentials).getUsername(),
292                     ((org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf
293                             .node.credentials.credentials.LoginPassword) credentials).getPassword(),
294                             encryptionService);
295         } else {
296             throw new IllegalStateException(remoteDeviceId + ": Only login/password authentication is supported");
297         }
298
299         return NetconfReconnectingClientConfigurationBuilder.create()
300                 .withAddress(socketAddress)
301                 .withConnectionTimeoutMillis(clientConnectionTimeoutMillis)
302                 .withReconnectStrategy(strategy)
303                 .withAuthHandler(authHandler)
304                 .withProtocol(node.isTcpOnly()
305                         ? NetconfClientConfiguration.NetconfClientProtocol.TCP
306                         : NetconfClientConfiguration.NetconfClientProtocol.SSH)
307                 .withConnectStrategyFactory(sf)
308                 .withSessionListener(listener)
309                 .build();
310     }
311
312     private static final class TimedReconnectStrategyFactory implements ReconnectStrategyFactory {
313         private final Long connectionAttempts;
314         private final EventExecutor executor;
315         private final double sleepFactor;
316         private final int minSleep;
317
318         TimedReconnectStrategyFactory(final EventExecutor executor, final Long maxConnectionAttempts,
319                                       final int minSleep, final BigDecimal sleepFactor) {
320             if (maxConnectionAttempts != null && maxConnectionAttempts > 0) {
321                 connectionAttempts = maxConnectionAttempts;
322             } else {
323                 connectionAttempts = null;
324             }
325
326             this.sleepFactor = sleepFactor.doubleValue();
327             this.executor = executor;
328             this.minSleep = minSleep;
329         }
330
331         @Override
332         public ReconnectStrategy createReconnectStrategy() {
333             final Long maxSleep = null;
334             final Long deadline = null;
335
336             return new TimedReconnectStrategy(executor, minSleep,
337                     minSleep, sleepFactor, maxSleep, connectionAttempts, deadline);
338         }
339     }
340 }