Enforce base64 encoding for netconf-keystore
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / topology / callhome / CallHomeMountTlsAuthProvider.java
1 /*
2  * Copyright (c) 2020 Pantheon Technologies, 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.callhome;
9
10 import com.google.common.collect.ImmutableMultimap;
11 import io.netty.handler.ssl.SslContext;
12 import java.net.SocketAddress;
13 import java.security.PublicKey;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Set;
17 import java.util.concurrent.ConcurrentHashMap;
18 import java.util.concurrent.ConcurrentMap;
19 import javax.annotation.PreDestroy;
20 import javax.inject.Inject;
21 import javax.inject.Singleton;
22 import org.opendaylight.mdsal.binding.api.DataBroker;
23 import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
24 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
25 import org.opendaylight.mdsal.binding.api.DataTreeModification;
26 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
27 import org.opendaylight.netconf.client.SslContextFactory;
28 import org.opendaylight.netconf.client.mdsal.api.SslContextFactoryProvider;
29 import org.opendaylight.netconf.keystore.legacy.NetconfKeystore;
30 import org.opendaylight.netconf.keystore.legacy.NetconfKeystoreService;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.NetconfCallhomeServer;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.AllowedDevices;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.Device;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev240129.netconf.callhome.server.allowed.devices.device.transport.Tls;
35 import org.opendaylight.yangtools.concepts.Registration;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
37 import org.osgi.service.component.annotations.Activate;
38 import org.osgi.service.component.annotations.Component;
39 import org.osgi.service.component.annotations.Deactivate;
40 import org.osgi.service.component.annotations.Reference;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 @Component(service = CallHomeTlsAuthProvider.class, immediate = true)
45 @Singleton
46 public final class CallHomeMountTlsAuthProvider extends CallHomeTlsAuthProvider implements AutoCloseable {
47     private static final Logger LOG = LoggerFactory.getLogger(CallHomeMountTlsAuthProvider.class);
48
49     private final ConcurrentMap<String, String> deviceToPrivateKey = new ConcurrentHashMap<>();
50     private final ConcurrentMap<String, String> deviceToCertificate = new ConcurrentHashMap<>();
51     private final Registration allowedDevicesReg;
52     private final Registration certificatesReg;
53     private final SslContextFactory sslContextFactory;
54
55     private volatile ImmutableMultimap<PublicKey, String> publicKeyToName = ImmutableMultimap.of();
56
57     @Inject
58     @Activate
59     public CallHomeMountTlsAuthProvider(@Reference final SslContextFactoryProvider sslContextFactoryProvider,
60             @Reference final DataBroker dataBroker, @Reference final NetconfKeystoreService keystoreService) {
61         sslContextFactory = sslContextFactoryProvider.getSslContextFactory(null);
62         allowedDevicesReg = dataBroker.registerTreeChangeListener(
63             DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION,
64                 InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class).child(Device.class)),
65             new AllowedDevicesMonitor());
66         certificatesReg = keystoreService.registerKeystoreConsumer(this::updateCertificates);
67     }
68
69     @PreDestroy
70     @Deactivate
71     @Override
72     public void close() {
73         allowedDevicesReg.close();
74         certificatesReg.close();
75     }
76
77     private void updateCertificates(final NetconfKeystore keystore) {
78         final var builder = ImmutableMultimap.<PublicKey, String>builder();
79         keystore.trustedCertificates().forEach((name, cert) -> builder.put(cert.getPublicKey(), name));
80         publicKeyToName = builder.build();
81     }
82
83     @Override
84     public String idFor(final PublicKey key) {
85         // Find certificate names by the public key
86         final var certificateNames = publicKeyToName.get(key);
87
88         // Find devices names associated with a certificate name
89         final var deviceNames = deviceToCertificate.entrySet().stream()
90             .filter(v -> certificateNames.contains(v.getValue()))
91             .map(Map.Entry::getKey)
92             .toList();
93
94         // In real world scenario it is not possible to have multiple certificates with the same private/public key,
95         // but in theory/synthetic tests it is practically possible to generate multiple certificates from a single
96         // private key. In such case it's not possible to pin certificate to particular device.
97         return switch (deviceNames.size()) {
98             case 0 -> null;
99             case 1 -> deviceNames.get(0);
100             default -> {
101                 LOG.error("Unable to find device by provided certificate. Possible reason: one certificate configured "
102                     + "with multiple devices/names or multiple certificates contain same public key");
103                 yield null;
104             }
105         };
106     }
107
108     @Override
109     protected SslContext getSslContext(final SocketAddress remoteAddress) {
110         return sslContextFactory.createSslContext(Set.copyOf(deviceToPrivateKey.values()));
111     }
112
113     private final class AllowedDevicesMonitor implements DataTreeChangeListener<Device> {
114         @Override
115         public void onDataTreeChanged(final List<DataTreeModification<Device>> mods) {
116             for (var dataTreeModification : mods) {
117                 final var deviceMod = dataTreeModification.getRootNode();
118                 switch (deviceMod.modificationType()) {
119                     case DELETE -> deleteDevice(deviceMod.dataBefore());
120                     case SUBTREE_MODIFIED, WRITE -> {
121                         deleteDevice(deviceMod.dataBefore());
122                         writeDevice(deviceMod.dataAfter());
123                     }
124                     default -> {
125                         // Should never happen
126                     }
127                 }
128             }
129         }
130
131         private void deleteDevice(final Device dataBefore) {
132             if (dataBefore != null && dataBefore.getTransport() instanceof Tls) {
133                 LOG.debug("Removing device {}", dataBefore.getUniqueId());
134                 deviceToPrivateKey.remove(dataBefore.getUniqueId());
135                 deviceToCertificate.remove(dataBefore.getUniqueId());
136             }
137         }
138
139         private void writeDevice(final Device dataAfter) {
140             if (dataAfter != null && dataAfter.getTransport() instanceof Tls tls) {
141                 LOG.debug("Adding device {}", dataAfter.getUniqueId());
142                 final var tlsClientParams = tls.getTlsClientParams();
143                 deviceToPrivateKey.putIfAbsent(dataAfter.getUniqueId(), tlsClientParams.getKeyId());
144                 deviceToCertificate.putIfAbsent(dataAfter.getUniqueId(), tlsClientParams.getCertificateId());
145             }
146         }
147     }
148 }