52a1941e0fb2962803bea1ec3e0f798f35b5ecff
[netconf.git] / apps / netconf-topology / src / main / java / org / opendaylight / netconf / topology / spi / NetconfClientConfigurationBuilderFactoryImpl.java
1 /*
2  * Copyright (c) 2023 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.topology.spi;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Strings;
13 import java.io.IOException;
14 import java.io.StringReader;
15 import java.security.KeyPair;
16 import java.util.Base64;
17 import java.util.List;
18 import javax.inject.Inject;
19 import javax.inject.Singleton;
20 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
21 import org.opendaylight.aaa.encrypt.PKIUtil;
22 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration.NetconfClientProtocol;
23 import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
24 import org.opendaylight.netconf.client.mdsal.api.CredentialProvider;
25 import org.opendaylight.netconf.client.mdsal.api.SslHandlerFactoryProvider;
26 import org.opendaylight.netconf.shaded.sshd.client.auth.pubkey.UserAuthPublicKeyFactory;
27 import org.opendaylight.netconf.shaded.sshd.common.keyprovider.KeyIdentityProvider;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.crypto.types.rev230417.password.grouping.password.type.CleartextPasswordBuilder;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.client.rev230417.netconf.client.initiate.stack.grouping.transport.ssh.ssh.SshClientParametersBuilder;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.client.rev230417.netconf.client.initiate.stack.grouping.transport.ssh.ssh.TcpClientParametersBuilder;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ssh.client.rev230417.ssh.client.grouping.ClientIdentity;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ssh.client.rev230417.ssh.client.grouping.ClientIdentityBuilder;
33 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ssh.client.rev230417.ssh.client.grouping.client.identity.PasswordBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240110.connection.parameters.Protocol.Name;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240110.credentials.Credentials;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240110.credentials.credentials.KeyAuth;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240110.credentials.credentials.LoginPw;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.device.rev240110.credentials.credentials.LoginPwUnencrypted;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev231121.NetconfNode;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
41 import org.osgi.service.component.annotations.Activate;
42 import org.osgi.service.component.annotations.Component;
43 import org.osgi.service.component.annotations.Reference;
44
45 /**
46  * Default implementation of NetconfClientConfigurationBuildFactory.
47  */
48 @Component
49 @Singleton
50 public final class NetconfClientConfigurationBuilderFactoryImpl implements NetconfClientConfigurationBuilderFactory {
51     private final SslHandlerFactoryProvider sslHandlerFactoryProvider;
52     private final AAAEncryptionService encryptionService;
53     private final CredentialProvider credentialProvider;
54
55     @Inject
56     @Activate
57     public NetconfClientConfigurationBuilderFactoryImpl(
58             @Reference final AAAEncryptionService encryptionService,
59             @Reference final CredentialProvider credentialProvider,
60             @Reference final SslHandlerFactoryProvider sslHandlerFactoryProvider) {
61         this.encryptionService = requireNonNull(encryptionService);
62         this.credentialProvider = requireNonNull(credentialProvider);
63         this.sslHandlerFactoryProvider = requireNonNull(sslHandlerFactoryProvider);
64     }
65
66     @Override
67     public NetconfClientConfigurationBuilder createClientConfigurationBuilder(final NodeId nodeId,
68         final NetconfNode node) {
69         final var builder = NetconfClientConfigurationBuilder.create();
70         final var protocol = node.getProtocol();
71         if (node.requireTcpOnly()) {
72             builder.withProtocol(NetconfClientProtocol.TCP);
73         } else if (protocol == null || protocol.getName() == Name.SSH) {
74             builder.withProtocol(NetconfClientProtocol.SSH);
75             setSshParametersFromCredentials(builder, node.getCredentials());
76         } else if (protocol.getName() == Name.TLS) {
77             builder.withProtocol(NetconfClientProtocol.TLS).withSslHandlerFactory(
78                 channel -> sslHandlerFactoryProvider.getSslHandlerFactory(protocol.getSpecification())
79                     .createSslHandler());
80         } else {
81             throw new IllegalArgumentException("Unsupported protocol type: " + protocol.getName());
82         }
83
84         final var helloCapabilities = node.getOdlHelloMessageCapabilities();
85         if (helloCapabilities != null) {
86             builder.withOdlHelloCapabilities(List.copyOf(helloCapabilities.requireCapability()));
87         }
88
89         return builder
90             .withName(nodeId.getValue())
91             .withTcpParameters(new TcpClientParametersBuilder()
92                 .setRemoteAddress(node.requireHost())
93                 .setRemotePort(node.requirePort()).build())
94             .withConnectionTimeoutMillis(node.requireConnectionTimeoutMillis().toJava());
95     }
96
97     private void setSshParametersFromCredentials(final NetconfClientConfigurationBuilder confBuilder,
98             final Credentials credentials) {
99         final var sshParamsBuilder = new SshClientParametersBuilder();
100         if (credentials instanceof LoginPwUnencrypted unencrypted) {
101             final var loginPassword = unencrypted.getLoginPasswordUnencrypted();
102             sshParamsBuilder.setClientIdentity(loginPasswordIdentity(
103                 loginPassword.getUsername(), loginPassword.getPassword()));
104         } else if (credentials instanceof LoginPw loginPw) {
105             final var loginPassword = loginPw.getLoginPassword();
106             final var username = loginPassword.getUsername();
107             final var password = Base64.getEncoder().encodeToString(loginPassword.getPassword());
108             sshParamsBuilder.setClientIdentity(loginPasswordIdentity(username, encryptionService.decrypt(password)));
109         } else if (credentials instanceof KeyAuth keyAuth) {
110             final var keyBased = keyAuth.getKeyBased();
111             sshParamsBuilder.setClientIdentity(new ClientIdentityBuilder().setUsername(keyBased.getUsername()).build());
112             confBuilder.withSshConfigurator(factoryMgr -> {
113                 final var keyPair = getKeyPair(keyBased.getKeyId());
114                 factoryMgr.setKeyIdentityProvider(KeyIdentityProvider.wrapKeyPairs(keyPair));
115                 final var factory = new UserAuthPublicKeyFactory();
116                 factory.setSignatureFactories(factoryMgr.getSignatureFactories());
117                 factoryMgr.setUserAuthFactories(List.of(factory));
118             });
119         } else {
120             throw new IllegalArgumentException("Unsupported credential type: " + credentials.getClass());
121         }
122         confBuilder.withSshParameters(sshParamsBuilder.build());
123     }
124
125     private static ClientIdentity loginPasswordIdentity(final String username, final String password) {
126         return new ClientIdentityBuilder()
127             .setUsername(requireNonNull(username, "username is undefined"))
128             .setPassword(new PasswordBuilder()
129                 .setPasswordType(new CleartextPasswordBuilder()
130                     .setCleartextPassword(requireNonNull(password, "password is undefined"))
131                     .build())
132                 .build())
133             .build();
134     }
135
136     private KeyPair getKeyPair(final String keyId) {
137         // public key retrieval logic taken from DatastoreBackedPublicKeyAuth
138         final var dsKeypair = credentialProvider.credentialForId(keyId);
139         if (dsKeypair == null) {
140             throw new IllegalArgumentException("No keypair found with keyId=" + keyId);
141         }
142         final var passPhrase = Strings.isNullOrEmpty(dsKeypair.getPassphrase()) ? "" : dsKeypair.getPassphrase();
143         try {
144             return new PKIUtil().decodePrivateKey(
145                 new StringReader(encryptionService.decrypt(dsKeypair.getPrivateKey()).replace("\\n", "\n")),
146                 encryptionService.decrypt(passPhrase));
147         } catch (IOException e) {
148             throw new IllegalStateException("Could not decode private key with keyId=" + keyId, e);
149         }
150     }
151 }