Clean up TlsAllowedDevicesMonitorImpl constants
[netconf.git] / apps / callhome-provider / src / main / java / org / opendaylight / netconf / callhome / mount / tls / TlsAllowedDevicesMonitorImpl.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.callhome.mount.tls;
9
10 import static java.nio.charset.StandardCharsets.US_ASCII;
11
12 import java.io.ByteArrayInputStream;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.security.PublicKey;
16 import java.security.cert.CertificateException;
17 import java.security.cert.CertificateFactory;
18 import java.util.Base64;
19 import java.util.Collection;
20 import java.util.HashSet;
21 import java.util.Map;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.stream.Collectors;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
29 import org.opendaylight.mdsal.binding.api.DataBroker;
30 import org.opendaylight.mdsal.binding.api.DataObjectModification;
31 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
32 import org.opendaylight.mdsal.binding.api.DataTreeModification;
33 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
34 import org.opendaylight.netconf.callhome.protocol.tls.TlsAllowedDevicesMonitor;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.trusted.certificates.TrustedCertificate;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.NetconfCallhomeServer;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.AllowedDevices;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.Device;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.Tls;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.netconf.callhome.server.rev201015.netconf.callhome.server.allowed.devices.device.transport.tls.TlsClientParams;
42 import org.opendaylight.yangtools.concepts.Registration;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public class TlsAllowedDevicesMonitorImpl implements TlsAllowedDevicesMonitor, AutoCloseable {
48     private static final Logger LOG = LoggerFactory.getLogger(TlsAllowedDevicesMonitorImpl.class);
49     private static final ConcurrentMap<String, String> DEVICE_TO_PRIVATE_KEY = new ConcurrentHashMap<>();
50     private static final ConcurrentMap<String, String> DEVICE_TO_CERTIFICATE = new ConcurrentHashMap<>();
51     private static final ConcurrentMap<String, PublicKey> CERTIFICATE_TO_PUBLIC_KEY = new ConcurrentHashMap<>();
52
53     private final Registration allowedDevicesReg;
54     private final Registration certificatesReg;
55
56     public TlsAllowedDevicesMonitorImpl(final DataBroker dataBroker) {
57         allowedDevicesReg = dataBroker.registerDataTreeChangeListener(
58             DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION,
59                 InstanceIdentifier.create(NetconfCallhomeServer.class).child(AllowedDevices.class).child(Device.class)),
60             new AllowedDevicesMonitor());
61         certificatesReg = dataBroker.registerDataTreeChangeListener(
62             DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Keystore.class)),
63             new CertificatesMonitor());
64     }
65
66     @Override
67     public Optional<String> findDeviceIdByPublicKey(final PublicKey key) {
68         // Find certificate names by the public key
69         final Set<String> certificates = CERTIFICATE_TO_PUBLIC_KEY.entrySet().stream()
70             .filter(v -> key.equals(v.getValue()))
71             .map(Map.Entry::getKey)
72             .collect(Collectors.toSet());
73
74         // Find devices names associated with a certificate name
75         final Set<String> deviceNames = DEVICE_TO_CERTIFICATE.entrySet().stream()
76             .filter(v -> certificates.contains(v.getValue()))
77             .map(Map.Entry::getKey)
78             .collect(Collectors.toSet());
79
80         // In real world scenario it is not possible to have multiple certificates with the same private/public key,
81         // but in theor/synthetic tests it is practically possible to generate mulitple certificates from a single
82         // private key. In such case it's not possible to pin certificate to particular device.
83         if (deviceNames.size() > 1) {
84             LOG.error("Unable to find device by provided certificate. Possible reason: one certificate configured "
85                 + "with multiple devices/names or multiple certificates contain same public key");
86             return Optional.empty();
87         } else {
88             return deviceNames.stream().findFirst();
89         }
90     }
91
92     @Override
93     public Set<String> findAllowedKeys() {
94         return new HashSet<>(DEVICE_TO_PRIVATE_KEY.values());
95     }
96
97     @Override
98     public void close() {
99         allowedDevicesReg.close();
100         certificatesReg.close();
101     }
102
103     private static class CertificatesMonitor implements ClusteredDataTreeChangeListener<Keystore> {
104
105         @Override
106         public void onDataTreeChanged(@NonNull final Collection<DataTreeModification<Keystore>> changes) {
107             changes.stream().map(DataTreeModification::getRootNode)
108                 .flatMap(v -> v.getModifiedChildren().stream())
109                 .filter(v -> v.getDataType().equals(TrustedCertificate.class))
110                 .map(v -> (DataObjectModification<TrustedCertificate>) v)
111                 .forEach(this::updateCertificate);
112         }
113
114         private void updateCertificate(final DataObjectModification<TrustedCertificate> change) {
115             final DataObjectModification.ModificationType modType = change.getModificationType();
116             switch (modType) {
117                 case DELETE:
118                     deleteCertificate(change.getDataBefore());
119                     break;
120                 case SUBTREE_MODIFIED:
121                 case WRITE:
122                     deleteCertificate(change.getDataBefore());
123                     writeCertificate(change.getDataAfter());
124                     break;
125                 default:
126                     break;
127             }
128         }
129
130         private void deleteCertificate(final TrustedCertificate dataBefore) {
131             if (dataBefore != null) {
132                 LOG.debug("Removing public key mapping for certificate {}", dataBefore.getName());
133                 CERTIFICATE_TO_PUBLIC_KEY.remove(dataBefore.getName());
134             }
135         }
136
137         private void writeCertificate(final TrustedCertificate dataAfter) {
138             if (dataAfter != null) {
139                 LOG.debug("Adding public key mapping for certificate {}", dataAfter.getName());
140                 CERTIFICATE_TO_PUBLIC_KEY.putIfAbsent(dataAfter.getName(), buildPublicKey(dataAfter.getCertificate()));
141             }
142         }
143
144         private PublicKey buildPublicKey(final String encoded) {
145             final byte[] decoded = Base64.getMimeDecoder().decode(encoded.getBytes(US_ASCII));
146             try {
147                 final CertificateFactory factory = CertificateFactory.getInstance("X.509");
148                 try (InputStream in = new ByteArrayInputStream(decoded)) {
149                     return factory.generateCertificate(in).getPublicKey();
150                 }
151             } catch (final CertificateException | IOException e) {
152                 LOG.error("Unable to build X.509 certificate from encoded value: {}", e.getLocalizedMessage());
153             }
154             return null;
155         }
156
157     }
158
159     private static class AllowedDevicesMonitor implements ClusteredDataTreeChangeListener<Device> {
160
161         @Override
162         public final void onDataTreeChanged(final Collection<DataTreeModification<Device>> mods) {
163             for (final DataTreeModification<Device> dataTreeModification : mods) {
164                 final DataObjectModification<Device> deviceMod = dataTreeModification.getRootNode();
165                 final DataObjectModification.ModificationType modType = deviceMod.getModificationType();
166                 switch (modType) {
167                     case DELETE:
168                         deleteDevice(deviceMod.getDataBefore());
169                         break;
170                     case SUBTREE_MODIFIED:
171                     case WRITE:
172                         deleteDevice(deviceMod.getDataBefore());
173                         writeDevice(deviceMod.getDataAfter());
174                         break;
175                     default:
176                         break;
177                 }
178             }
179         }
180
181         private void deleteDevice(final Device dataBefore) {
182             if (dataBefore != null && dataBefore.getTransport() instanceof Tls) {
183                 LOG.debug("Removing device {}", dataBefore.getUniqueId());
184                 DEVICE_TO_PRIVATE_KEY.remove(dataBefore.getUniqueId());
185                 DEVICE_TO_CERTIFICATE.remove(dataBefore.getUniqueId());
186             }
187         }
188
189         private void writeDevice(final Device dataAfter) {
190             if (dataAfter != null && dataAfter.getTransport() instanceof Tls) {
191                 LOG.debug("Adding device {}", dataAfter.getUniqueId());
192                 final TlsClientParams clientParams = ((Tls) dataAfter.getTransport()).getTlsClientParams();
193                 DEVICE_TO_PRIVATE_KEY.putIfAbsent(dataAfter.getUniqueId(), clientParams.getKeyId());
194                 DEVICE_TO_CERTIFICATE.putIfAbsent(dataAfter.getUniqueId(), clientParams.getCertificateId());
195             }
196         }
197     }
198 }