b728ec24ae90c27ec589c0def07f2cf3f81b5657
[netconf.git] / transport / transport-ssh / src / main / java / org / opendaylight / netconf / transport / ssh / SSHServer.java
1 /*
2  * Copyright (c) 2022 PANTHEON.tech, s.r.o. 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.netconf.transport.ssh;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import io.netty.bootstrap.Bootstrap;
17 import io.netty.bootstrap.ServerBootstrap;
18 import io.netty.channel.group.DefaultChannelGroup;
19 import io.netty.util.concurrent.GlobalEventExecutor;
20 import java.security.PublicKey;
21 import java.util.List;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.netconf.shaded.sshd.common.io.IoHandler;
25 import org.opendaylight.netconf.shaded.sshd.common.keyprovider.KeyPairProvider;
26 import org.opendaylight.netconf.shaded.sshd.common.util.threads.ThreadUtils;
27 import org.opendaylight.netconf.shaded.sshd.server.ServerFactoryManager;
28 import org.opendaylight.netconf.shaded.sshd.server.SshServer;
29 import org.opendaylight.netconf.shaded.sshd.server.auth.UserAuthFactory;
30 import org.opendaylight.netconf.shaded.sshd.server.auth.hostbased.UserAuthHostBasedFactory;
31 import org.opendaylight.netconf.shaded.sshd.server.auth.password.UserAuthPasswordFactory;
32 import org.opendaylight.netconf.shaded.sshd.server.auth.pubkey.UserAuthPublicKeyFactory;
33 import org.opendaylight.netconf.shaded.sshd.server.session.SessionFactory;
34 import org.opendaylight.netconf.transport.api.TransportChannelListener;
35 import org.opendaylight.netconf.transport.api.TransportStack;
36 import org.opendaylight.netconf.transport.api.UnsupportedConfigurationException;
37 import org.opendaylight.netconf.transport.tcp.TCPClient;
38 import org.opendaylight.netconf.transport.tcp.TCPServer;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ssh.server.rev230417.SshServerGrouping;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ssh.server.rev230417.ssh.server.grouping.ClientAuthentication;
41 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ssh.server.rev230417.ssh.server.grouping.ServerIdentity;
42 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.tcp.client.rev230417.TcpClientGrouping;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.tcp.server.rev230417.TcpServerGrouping;
44
45 /**
46  * A {@link TransportStack} acting as an SSH server.
47  */
48 public final class SSHServer extends SSHTransportStack {
49
50     private final ServerFactoryManager serverFactoryManager;
51     private final SessionFactory serverSessionFactory;
52
53     private SSHServer(final TransportChannelListener listener, final ServerFactoryManager serverFactoryManager) {
54         super(listener);
55         this.serverFactoryManager = requireNonNull(serverFactoryManager);
56         this.serverFactoryManager.addSessionListener(new UserAuthSessionListener(sessionAuthHandlers, sessions));
57         serverSessionFactory = new SessionFactory(serverFactoryManager);
58         ioService = new SshIoService(this.serverFactoryManager,
59                 new DefaultChannelGroup("sshd-server-channels", GlobalEventExecutor.INSTANCE),
60                 serverSessionFactory);
61     }
62
63     @Override
64     protected IoHandler getSessionFactory() {
65         return serverSessionFactory;
66     }
67
68     public static @NonNull ListenableFuture<SSHServer> connect(final TransportChannelListener listener,
69             final Bootstrap bootstrap, final TcpClientGrouping connectParams, final SshServerGrouping serverParams)
70             throws UnsupportedConfigurationException {
71         final var server = new SSHServer(listener, newFactoryManager(requireNonNull(serverParams), null));
72         return transformUnderlay(server, TCPClient.connect(server.asListener(), bootstrap, connectParams));
73     }
74
75     public static @NonNull ListenableFuture<SSHServer> listen(final TransportChannelListener listener,
76             final ServerBootstrap bootstrap, final TcpServerGrouping connectParams,
77             final SshServerGrouping serverParams) throws UnsupportedConfigurationException {
78         requireNonNull(serverParams);
79         return listen(listener, bootstrap, connectParams, serverParams, null);
80     }
81
82     /**
83      * Builds and starts SSH Server.
84      *
85      * @param listener server channel listener, required
86      * @param bootstrap server bootstrap instance, required
87      * @param connectParams tcp transport configuration, required
88      * @param serverParams ssh overlay configuration, optional if configurator is defined, required otherwise
89      * @param configurator server factory manager configurator, optional if serverParams is defined, required otherwise
90      * @return server instance as listenable future
91      * @throws UnsupportedConfigurationException if any of configurations is invalid or incomplete
92      * @throws NullPointerException if any of required parameters is null
93      * @throws IllegalArgumentException if both configurator and serverParams are null
94      */
95     public static @NonNull ListenableFuture<SSHServer> listen(final TransportChannelListener listener,
96             final ServerBootstrap bootstrap, final TcpServerGrouping connectParams,
97             final SshServerGrouping serverParams, final ServerFactoryManagerConfigurator configurator)
98             throws UnsupportedConfigurationException {
99         checkArgument(serverParams != null || configurator != null,
100             "Neither server parameters nor factory configurator is defined");
101         final var factoryMgr = newFactoryManager(serverParams, configurator);
102         final var server = new SSHServer(listener, factoryMgr);
103         return transformUnderlay(server, TCPServer.listen(server.asListener(), bootstrap, connectParams));
104     }
105
106     private static ServerFactoryManager newFactoryManager(final @Nullable SshServerGrouping serverParams,
107             final @Nullable ServerFactoryManagerConfigurator configurator) throws UnsupportedConfigurationException {
108         final var factoryMgr = SshServer.setUpDefaultServer();
109         if (serverParams != null) {
110             ConfigUtils.setTransportParams(factoryMgr, serverParams.getTransportParams());
111             ConfigUtils.setKeepAlives(factoryMgr, serverParams.getKeepalives());
112             setServerIdentity(factoryMgr, serverParams.getServerIdentity());
113             setClientAuthentication(factoryMgr, serverParams.getClientAuthentication());
114         }
115         if (configurator != null) {
116             configurator.configureServerFactoryManager(factoryMgr);
117         }
118         factoryMgr.setServiceFactories(SshServer.DEFAULT_SERVICE_FACTORIES);
119         factoryMgr.setScheduledExecutorService(ThreadUtils.newSingleThreadScheduledExecutor(""));
120         return factoryMgr;
121     }
122
123     private static void setServerIdentity(final @NonNull ServerFactoryManager factoryMgr,
124             final @Nullable ServerIdentity serverIdentity) throws UnsupportedConfigurationException {
125         if (serverIdentity == null) {
126             throw new UnsupportedConfigurationException("Server identity configuration is required");
127         }
128         final var hostKey = serverIdentity.getHostKey();
129         if (hostKey == null || hostKey.isEmpty()) {
130             throw new UnsupportedConfigurationException("Host keys is missing in server identity configuration");
131         }
132         final var serverHostKeyPairs = ConfigUtils.extractServerHostKeys(hostKey);
133         if (!serverHostKeyPairs.isEmpty()) {
134             factoryMgr.setKeyPairProvider(KeyPairProvider.wrap(serverHostKeyPairs));
135         }
136     }
137
138     private static void setClientAuthentication(final @NonNull ServerFactoryManager factoryMgr,
139             final @Nullable ClientAuthentication clientAuthentication) throws UnsupportedConfigurationException {
140         if (clientAuthentication == null) {
141             return;
142         }
143         final var users = clientAuthentication.getUsers();
144         if (users == null) {
145             return;
146         }
147         final var userMap = users.getUser();
148         if (userMap != null) {
149             final var passwordMapBuilder = ImmutableMap.<String, String>builder();
150             final var hostBasedMapBuilder = ImmutableMap.<String, List<PublicKey>>builder();
151             final var publicKeyMapBuilder = ImmutableMap.<String, List<PublicKey>>builder();
152             for (var entry : userMap.entrySet()) {
153                 final String username = entry.getKey().getName();
154                 final var value = entry.getValue();
155                 final var password = value.getPassword();
156                 if (password != null) {
157                     passwordMapBuilder.put(username, password.getValue());
158                 }
159                 final var hostBased = value.getHostbased();
160                 if (hostBased != null) {
161                     hostBasedMapBuilder.put(username, ConfigUtils.extractPublicKeys(hostBased.getInlineOrTruststore()));
162                 }
163                 final var publicKey = value.getPublicKeys();
164                 if (publicKey != null) {
165                     publicKeyMapBuilder.put(username, ConfigUtils.extractPublicKeys(publicKey.getInlineOrTruststore()));
166                 }
167             }
168             final var authFactoriesBuilder = ImmutableList.<UserAuthFactory>builder();
169             final var passwordMap = passwordMapBuilder.build();
170             if (!passwordMap.isEmpty()) {
171                 authFactoriesBuilder.add(new UserAuthPasswordFactory());
172                 factoryMgr.setPasswordAuthenticator(new CryptHashPasswordAuthenticator(passwordMap));
173             }
174             final var hostBasedMap = hostBasedMapBuilder.build();
175             if (!hostBasedMap.isEmpty()) {
176                 final var factory = new UserAuthHostBasedFactory();
177                 factory.setSignatureFactories(factoryMgr.getSignatureFactories());
178                 authFactoriesBuilder.add(factory);
179                 factoryMgr.setHostBasedAuthenticator(new UserPublicKeyAuthenticator(hostBasedMap));
180             }
181             final var publicKeyMap = publicKeyMapBuilder.build();
182             if (!publicKeyMap.isEmpty()) {
183                 final var factory = new UserAuthPublicKeyFactory();
184                 factory.setSignatureFactories(factoryMgr.getSignatureFactories());
185                 authFactoriesBuilder.add(factory);
186                 factoryMgr.setPublickeyAuthenticator(new UserPublicKeyAuthenticator(publicKeyMap));
187             }
188             factoryMgr.setUserAuthFactories(authFactoriesBuilder.build());
189         }
190     }
191 }