2 * Copyright (c) 2020 Pantheon Technologies, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.netconf.callhome.mount.tls;
10 import static java.nio.charset.StandardCharsets.US_ASCII;
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;
22 import java.util.Optional;
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;
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<>();
53 private final Registration allowedDevicesReg;
54 private final Registration certificatesReg;
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());
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());
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());
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();
88 return deviceNames.stream().findFirst();
93 public Set<String> findAllowedKeys() {
94 return new HashSet<>(DEVICE_TO_PRIVATE_KEY.values());
99 allowedDevicesReg.close();
100 certificatesReg.close();
103 private static class CertificatesMonitor implements ClusteredDataTreeChangeListener<Keystore> {
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);
114 private void updateCertificate(final DataObjectModification<TrustedCertificate> change) {
115 final DataObjectModification.ModificationType modType = change.getModificationType();
118 deleteCertificate(change.getDataBefore());
120 case SUBTREE_MODIFIED:
122 deleteCertificate(change.getDataBefore());
123 writeCertificate(change.getDataAfter());
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());
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()));
144 private PublicKey buildPublicKey(final String encoded) {
145 final byte[] decoded = Base64.getMimeDecoder().decode(encoded.getBytes(US_ASCII));
147 final CertificateFactory factory = CertificateFactory.getInstance("X.509");
148 try (InputStream in = new ByteArrayInputStream(decoded)) {
149 return factory.generateCertificate(in).getPublicKey();
151 } catch (final CertificateException | IOException e) {
152 LOG.error("Unable to build X.509 certificate from encoded value: {}", e.getLocalizedMessage());
159 private static class AllowedDevicesMonitor implements ClusteredDataTreeChangeListener<Device> {
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();
168 deleteDevice(deviceMod.getDataBefore());
170 case SUBTREE_MODIFIED:
172 deleteDevice(deviceMod.getDataBefore());
173 writeDevice(deviceMod.getDataAfter());
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());
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());