2 * Copyright (c) 2017 Cisco Systems, Inc. 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.sal.connect.netconf.sal;
10 import static java.util.Objects.requireNonNull;
12 import java.io.ByteArrayInputStream;
13 import java.io.IOException;
14 import java.security.GeneralSecurityException;
15 import java.security.KeyFactory;
16 import java.security.KeyStore;
17 import java.security.KeyStoreException;
18 import java.security.cert.Certificate;
19 import java.security.cert.CertificateException;
20 import java.security.cert.CertificateFactory;
21 import java.security.cert.X509Certificate;
22 import java.security.spec.InvalidKeySpecException;
23 import java.security.spec.PKCS8EncodedKeySpec;
24 import java.util.ArrayList;
25 import java.util.Base64;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.Optional;
33 import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
34 import org.opendaylight.mdsal.binding.api.DataBroker;
35 import org.opendaylight.mdsal.binding.api.DataObjectModification;
36 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
37 import org.opendaylight.mdsal.binding.api.DataTreeModification;
38 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.Keystore;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017._private.keys.PrivateKey;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.keystore.entry.KeyCredential;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.keystore.rev171017.trusted.certificates.TrustedCertificate;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public final class NetconfKeystoreAdapter implements ClusteredDataTreeChangeListener<Keystore> {
49 private static final Logger LOG = LoggerFactory.getLogger(NetconfKeystoreAdapter.class);
51 private final Map<String, KeyCredential> pairs = Collections.synchronizedMap(new HashMap<>());
52 private final Map<String, PrivateKey> privateKeys = Collections.synchronizedMap(new HashMap<>());
53 private final Map<String, TrustedCertificate> trustedCertificates = Collections.synchronizedMap(new HashMap<>());
55 public NetconfKeystoreAdapter(final DataBroker dataBroker) {
56 dataBroker.registerDataTreeChangeListener(
57 DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Keystore.class)),
61 public Optional<KeyCredential> getKeypairFromId(final String keyId) {
62 return Optional.ofNullable(pairs.get(keyId));
66 * Using private keys and trusted certificates to create a new JDK <code>KeyStore</code> which
67 * will be used by TLS clients to create <code>SSLEngine</code>. The private keys are essential
68 * to create JDK <code>KeyStore</code> while the trusted certificates are optional.
70 * @return A JDK KeyStore object
71 * @throws GeneralSecurityException If any security exception occurred
72 * @throws IOException If there is an I/O problem with the keystore data
74 public KeyStore getJavaKeyStore() throws GeneralSecurityException, IOException {
75 return getJavaKeyStore(Collections.emptySet());
79 * Using private keys and trusted certificates to create a new JDK <code>KeyStore</code> which
80 * will be used by TLS clients to create <code>SSLEngine</code>. The private keys are essential
81 * to create JDK <code>KeyStore</code> while the trusted certificates are optional.
83 * @param allowedKeys Set of keys to include during KeyStore generation, empty set will creatr
84 * a KeyStore with all possible keys.
85 * @return A JDK KeyStore object
86 * @throws GeneralSecurityException If any security exception occurred
87 * @throws IOException If there is an I/O problem with the keystore data
89 public KeyStore getJavaKeyStore(final Set<String> allowedKeys) throws GeneralSecurityException, IOException {
90 requireNonNull(allowedKeys);
92 final KeyStore keyStore = KeyStore.getInstance("JKS");
94 keyStore.load(null, null);
96 synchronized (privateKeys) {
97 if (privateKeys.isEmpty()) {
98 throw new KeyStoreException("No keystore private key found");
101 for (Map.Entry<String, PrivateKey> entry : privateKeys.entrySet()) {
102 if (!allowedKeys.isEmpty() && !allowedKeys.contains(entry.getKey())) {
105 final java.security.PrivateKey key = getJavaPrivateKey(entry.getValue().getData());
107 final List<X509Certificate> certificateChain =
108 getCertificateChain(entry.getValue().getCertificateChain().toArray(new String[0]));
109 if (certificateChain.isEmpty()) {
110 throw new CertificateException("No certificate chain associated with private key found");
113 keyStore.setKeyEntry(entry.getKey(), key, "".toCharArray(),
114 certificateChain.stream().toArray(Certificate[]::new));
118 synchronized (trustedCertificates) {
119 for (Map.Entry<String, TrustedCertificate> entry : trustedCertificates.entrySet()) {
120 final List<X509Certificate> x509Certificates =
121 getCertificateChain(new String[] {entry.getValue().getCertificate()});
123 keyStore.setCertificateEntry(entry.getKey(), x509Certificates.get(0));
130 private static java.security.PrivateKey getJavaPrivateKey(final String base64PrivateKey)
131 throws GeneralSecurityException {
132 final byte[] encodedKey = base64Decode(base64PrivateKey);
133 final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
134 java.security.PrivateKey key;
137 final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
138 key = keyFactory.generatePrivate(keySpec);
139 } catch (InvalidKeySpecException ignore) {
140 final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
141 key = keyFactory.generatePrivate(keySpec);
147 private static List<X509Certificate> getCertificateChain(final String[] base64Certificates)
148 throws GeneralSecurityException {
149 final CertificateFactory factory = CertificateFactory.getInstance("X.509");
150 final List<X509Certificate> certificates = new ArrayList<>();
152 for (String cert : base64Certificates) {
153 final byte[] buffer = base64Decode(cert);
154 certificates.add((X509Certificate)factory.generateCertificate(new ByteArrayInputStream(buffer)));
160 private static byte[] base64Decode(final String base64) {
161 return Base64.getMimeDecoder().decode(base64.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
165 public void onDataTreeChanged(final Collection<DataTreeModification<Keystore>> changes) {
166 LOG.debug("Keystore updated: {}", changes);
168 for (final DataTreeModification<Keystore> change : changes) {
169 final DataObjectModification<Keystore> rootNode = change.getRootNode();
171 for (final DataObjectModification<? extends DataObject> changedChild : rootNode.getModifiedChildren()) {
172 if (changedChild.getDataType().equals(KeyCredential.class)) {
173 final Keystore dataAfter = rootNode.getDataAfter();
176 if (dataAfter != null) {
177 dataAfter.nonnullKeyCredential().values()
178 .forEach(pair -> pairs.put(pair.key().getKeyId(), pair));
181 } else if (changedChild.getDataType().equals(PrivateKey.class)) {
182 onPrivateKeyChanged((DataObjectModification<PrivateKey>)changedChild);
183 } else if (changedChild.getDataType().equals(TrustedCertificate.class)) {
184 onTrustedCertificateChanged((DataObjectModification<TrustedCertificate>)changedChild);
191 private void onPrivateKeyChanged(final DataObjectModification<PrivateKey> objectModification) {
192 switch (objectModification.getModificationType()) {
193 case SUBTREE_MODIFIED:
195 final PrivateKey privateKey = objectModification.getDataAfter();
196 privateKeys.put(privateKey.getName(), privateKey);
199 privateKeys.remove(objectModification.getDataBefore().getName());
206 private void onTrustedCertificateChanged(final DataObjectModification<TrustedCertificate> objectModification) {
207 switch (objectModification.getModificationType()) {
208 case SUBTREE_MODIFIED:
210 final TrustedCertificate trustedCertificate = objectModification.getDataAfter();
211 trustedCertificates.put(trustedCertificate.getName(), trustedCertificate);
214 trustedCertificates.remove(objectModification.getDataBefore().getName());