Flatten callhome-provider
[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
45 @Component(service = CallHomeTlsAuthProvider.class, immediate = true)
46 @Singleton
47 public final class CallHomeMountTlsAuthProvider extends CallHomeTlsAuthProvider implements AutoCloseable {
48     private static final Logger LOG = LoggerFactory.getLogger(CallHomeMountTlsAuthProvider.class);
49
50     private final ConcurrentMap<String, String> deviceToPrivateKey = new ConcurrentHashMap<>();
51     private final ConcurrentMap<String, String> deviceToCertificate = new ConcurrentHashMap<>();
52     private final Registration allowedDevicesReg;
53     private final Registration certificatesReg;
54     private final SslContextFactory sslContextFactory;
55
56     private volatile ImmutableMultimap<PublicKey, String> publicKeyToName = ImmutableMultimap.of();
57
58     @Inject
59     @Activate
60     public CallHomeMountTlsAuthProvider(@Reference final SslContextFactoryProvider sslContextFactoryProvider,
61             @Reference final DataBroker dataBroker, @Reference final NetconfKeystoreService keystoreService) {
62         sslContextFactory = sslContextFactoryProvider.getSslContextFactory(null);
63         allowedDevicesReg = dataBroker.registerTreeChangeListener(
64             DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION,
65                 InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class).child(Device.class)),
66             new AllowedDevicesMonitor());
67         certificatesReg = keystoreService.registerKeystoreConsumer(this::updateCertificates);
68     }
69
70     @PreDestroy
71     @Deactivate
72     @Override
73     public void close() {
74         allowedDevicesReg.close();
75         certificatesReg.close();
76     }
77
78     private void updateCertificates(final NetconfKeystore keystore) {
79         final var builder = ImmutableMultimap.<PublicKey, String>builder();
80         keystore.trustedCertificates().forEach((name, cert) -> builder.put(cert.getPublicKey(), name));
81         publicKeyToName = builder.build();
82     }
83
84     @Override
85     public String idFor(final PublicKey key) {
86         // Find certificate names by the public key
87         final var certificateNames = publicKeyToName.get(key);
88
89         // Find devices names associated with a certificate name
90         final var deviceNames = deviceToCertificate.entrySet().stream()
91             .filter(v -> certificateNames.contains(v.getValue()))
92             .map(Map.Entry::getKey)
93             .toList();
94
95         // In real world scenario it is not possible to have multiple certificates with the same private/public key,
96         // but in theory/synthetic tests it is practically possible to generate multiple certificates from a single
97         // private key. In such case it's not possible to pin certificate to particular device.
98         return switch (deviceNames.size()) {
99             case 0 -> null;
100             case 1 -> deviceNames.get(0);
101             default -> {
102                 LOG.error("Unable to find device by provided certificate. Possible reason: one certificate configured "
103                     + "with multiple devices/names or multiple certificates contain same public key");
104                 yield null;
105             }
106         };
107     }
108
109     @Override
110     protected SslContext getSslContext(final SocketAddress remoteAddress) {
111         return sslContextFactory.createSslContext(Set.copyOf(deviceToPrivateKey.values()));
112     }
113
114     private final class AllowedDevicesMonitor implements DataTreeChangeListener<Device> {
115         @Override
116         public void onDataTreeChanged(final List<DataTreeModification<Device>> mods) {
117             for (var dataTreeModification : mods) {
118                 final var deviceMod = dataTreeModification.getRootNode();
119                 switch (deviceMod.modificationType()) {
120                     case DELETE -> deleteDevice(deviceMod.dataBefore());
121                     case SUBTREE_MODIFIED, WRITE -> {
122                         deleteDevice(deviceMod.dataBefore());
123                         writeDevice(deviceMod.dataAfter());
124                     }
125                     default -> {
126                         // Should never happen
127                     }
128                 }
129             }
130         }
131
132         private void deleteDevice(final Device dataBefore) {
133             if (dataBefore != null && dataBefore.getTransport() instanceof Tls) {
134                 LOG.debug("Removing device {}", dataBefore.getUniqueId());
135                 deviceToPrivateKey.remove(dataBefore.getUniqueId());
136                 deviceToCertificate.remove(dataBefore.getUniqueId());
137             }
138         }
139
140         private void writeDevice(final Device dataAfter) {
141             if (dataAfter != null && dataAfter.getTransport() instanceof Tls tls) {
142                 LOG.debug("Adding device {}", dataAfter.getUniqueId());
143                 final var tlsClientParams = tls.getTlsClientParams();
144                 deviceToPrivateKey.putIfAbsent(dataAfter.getUniqueId(), tlsClientParams.getKeyId());
145                 deviceToCertificate.putIfAbsent(dataAfter.getUniqueId(), tlsClientParams.getCertificateId());
146             }
147         }
148     }
149 }