2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.netconf.ssh.osgi;
10 import com.google.common.base.Optional;
12 import java.io.FileInputStream;
13 import java.io.IOException;
14 import java.net.InetSocketAddress;
15 import java.util.ArrayList;
16 import java.util.List;
17 import org.apache.commons.io.FilenameUtils;
18 import org.apache.commons.io.IOUtils;
19 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
20 import org.opendaylight.controller.netconf.ssh.authentication.AuthProvider;
21 import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator;
22 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
23 import org.opendaylight.controller.sal.authorization.UserLevel;
24 import org.opendaylight.controller.usermanager.IUserManager;
25 import org.opendaylight.controller.usermanager.UserConfig;
26 import org.osgi.framework.BundleActivator;
27 import org.osgi.framework.BundleContext;
28 import org.osgi.framework.ServiceReference;
29 import org.osgi.util.tracker.ServiceTracker;
30 import org.osgi.util.tracker.ServiceTrackerCustomizer;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import static com.google.common.base.Preconditions.checkNotNull;
36 * Activator for netconf SSH bundle which creates SSH bridge between netconf client and netconf server. Activator
37 * starts SSH Server in its own thread. This thread is closed when activator calls stop() method. Server opens socket
38 * and listens for client connections. Each client connection creation is handled in separate
39 * {@link org.opendaylight.controller.netconf.ssh.threads.SocketThread} thread.
40 * This thread creates two additional threads {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}
41 * forwarding data from/to client.IOThread closes servers session and server connection when it gets -1 on input stream.
42 * {@link org.opendaylight.controller.netconf.ssh.threads.IOThread}'s run method waits for -1 on input stream to finish.
43 * All threads are daemons.
45 public class NetconfSSHActivator implements BundleActivator{
47 private NetconfSSHServer server;
48 private static final Logger logger = LoggerFactory.getLogger(NetconfSSHActivator.class);
49 private static final String EXCEPTION_MESSAGE = "Netconf ssh bridge is not available.";
50 private IUserManager iUserManager;
51 private BundleContext context = null;
52 private Optional<String> defaultPassword;
53 private Optional<String> defaultUser;
55 private ServiceTrackerCustomizer<IUserManager, IUserManager> customizer = new ServiceTrackerCustomizer<IUserManager, IUserManager>(){
57 public IUserManager addingService(ServiceReference<IUserManager> reference) {
58 logger.trace("Service {} added, let there be SSH bridge.", reference);
59 iUserManager = context.getService(reference);
61 onUserManagerFound(iUserManager);
62 } catch (Exception e) {
63 logger.trace("Can't start SSH server due to {}",e);
68 public void modifiedService(ServiceReference<IUserManager> reference, IUserManager service) {
69 logger.trace("Replacing modified service {} in netconf SSH.", reference);
70 server.addUserManagerService(service);
73 public void removedService(ServiceReference<IUserManager> reference, IUserManager service) {
74 logger.trace("Removing service {} from netconf SSH. " +
75 "SSH won't authenticate users until IUserManager service will be started.", reference);
76 removeUserManagerService();
82 public void start(BundleContext context) {
83 this.context = context;
84 listenForManagerService();
88 public void stop(BundleContext context) throws IOException {
89 if (this.defaultUser.isPresent()){
90 this.iUserManager.removeLocalUser(this.defaultUser.get());
94 logger.trace("Netconf SSH bridge is down ...");
97 private void startSSHServer() throws IllegalStateException, IOException {
98 checkNotNull(this.iUserManager, "No user manager service available.");
99 logger.trace("Starting netconf SSH bridge.");
100 Optional<InetSocketAddress> sshSocketAddressOptional = NetconfConfigUtil.extractSSHNetconfAddress(context, EXCEPTION_MESSAGE);
101 InetSocketAddress tcpSocketAddress = NetconfConfigUtil.extractTCPNetconfAddress(context,
102 EXCEPTION_MESSAGE, true);
104 if (sshSocketAddressOptional.isPresent()){
105 String path = FilenameUtils.separatorsToSystem(NetconfConfigUtil.getPrivateKeyPath(context));
106 if (path.equals("")){
107 throw new IllegalStateException("Missing netconf.ssh.pk.path key in configuration file.");
110 File privateKeyFile = new File(path);
111 String privateKeyPEMString = null;
112 if (privateKeyFile.exists() == false) {
114 privateKeyPEMString = PEMGenerator.generateTo(privateKeyFile);
115 } catch (Exception e) {
116 logger.error("Exception occurred while generating PEM string {}",e);
120 try (FileInputStream fis = new FileInputStream(path)) {
121 privateKeyPEMString = IOUtils.toString(fis);
122 } catch (IOException e) {
123 logger.error("Error reading RSA key from file '{}'", path);
124 throw new IllegalStateException("Error reading RSA key from file " + path);
127 AuthProvider authProvider = null;
129 this.defaultPassword = NetconfConfigUtil.getSSHDefaultPassword(context);
130 this.defaultUser = NetconfConfigUtil.getSSHDefaultUser(context);
131 // Since there is no user data store yet (ldap, ...) this adds default user/password to UserManager
132 // if these parameters are set in netconf configuration file.
133 if (defaultUser.isPresent() &&
134 defaultPassword.isPresent()){
135 logger.trace(String.format("Default username and password for netconf ssh bridge found. Adding user %s to user manager.",defaultUser.get()));
136 List<String> roles = new ArrayList<String>(1);
137 roles.add(UserLevel.SYSTEMADMIN.toString());
138 iUserManager.addLocalUser(new UserConfig(defaultUser.get(), defaultPassword.get(), roles));
140 authProvider = new AuthProvider(iUserManager, privateKeyPEMString);
141 } catch (Exception e) {
142 logger.error("Error instantiating AuthProvider {}",e);
144 this.server = NetconfSSHServer.start(sshSocketAddressOptional.get().getPort(),tcpSocketAddress,authProvider);
146 Thread serverThread = new Thread(server,"netconf SSH server thread");
147 serverThread.setDaemon(true);
148 serverThread.start();
149 logger.trace("Netconf SSH bridge up and running.");
151 logger.trace("No valid connection configuration for SSH bridge found.");
152 throw new IllegalStateException("No valid connection configuration for SSH bridge found.");
155 private void onUserManagerFound(IUserManager userManager) throws IOException {
156 if (server!=null && server.isUp()){
157 server.addUserManagerService(userManager);
162 private void removeUserManagerService(){
163 this.server.removeUserManagerService();
165 private void listenForManagerService(){
166 ServiceTracker<IUserManager, IUserManager> listenerTracker = new ServiceTracker<>(context, IUserManager.class,customizer);
167 listenerTracker.open();