a984294945a52ea941e5a16a592dd25efed7eb0f
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / NetconfKeystoreAdapter.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. 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.sal.connect.netconf.sal;
9
10 import static java.util.Objects.requireNonNull;
11
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;
30 import java.util.Map;
31 import java.util.Optional;
32 import java.util.Set;
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;
47
48 public final class NetconfKeystoreAdapter implements ClusteredDataTreeChangeListener<Keystore> {
49     private static final Logger LOG = LoggerFactory.getLogger(NetconfKeystoreAdapter.class);
50
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<>());
54
55     public NetconfKeystoreAdapter(final DataBroker dataBroker) {
56         dataBroker.registerDataTreeChangeListener(
57             DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Keystore.class)),
58             this);
59     }
60
61     public Optional<KeyCredential> getKeypairFromId(final String keyId) {
62         return Optional.ofNullable(pairs.get(keyId));
63     }
64
65     /**
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.
69      *
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
73      */
74     public KeyStore getJavaKeyStore() throws GeneralSecurityException, IOException {
75         return getJavaKeyStore(Collections.emptySet());
76     }
77
78     /**
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.
82      *
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
88      */
89     public KeyStore getJavaKeyStore(final Set<String> allowedKeys) throws GeneralSecurityException, IOException {
90         requireNonNull(allowedKeys);
91
92         final KeyStore keyStore = KeyStore.getInstance("JKS");
93
94         keyStore.load(null, null);
95
96         synchronized (privateKeys) {
97             if (privateKeys.isEmpty()) {
98                 throw new KeyStoreException("No keystore private key found");
99             }
100
101             for (Map.Entry<String, PrivateKey> entry : privateKeys.entrySet()) {
102                 if (!allowedKeys.isEmpty() && !allowedKeys.contains(entry.getKey())) {
103                     continue;
104                 }
105                 final java.security.PrivateKey key = getJavaPrivateKey(entry.getValue().getData());
106
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");
111                 }
112
113                 keyStore.setKeyEntry(entry.getKey(), key, "".toCharArray(),
114                         certificateChain.stream().toArray(Certificate[]::new));
115             }
116         }
117
118         synchronized (trustedCertificates) {
119             for (Map.Entry<String, TrustedCertificate> entry : trustedCertificates.entrySet()) {
120                 final List<X509Certificate> x509Certificates =
121                         getCertificateChain(new String[] {entry.getValue().getCertificate()});
122
123                 keyStore.setCertificateEntry(entry.getKey(), x509Certificates.get(0));
124             }
125         }
126
127         return keyStore;
128     }
129
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;
135
136         try {
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);
142         }
143
144         return key;
145     }
146
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<>();
151
152         for (String cert : base64Certificates) {
153             final byte[] buffer = base64Decode(cert);
154             certificates.add((X509Certificate)factory.generateCertificate(new ByteArrayInputStream(buffer)));
155         }
156
157         return certificates;
158     }
159
160     private static byte[] base64Decode(final String base64) {
161         return Base64.getMimeDecoder().decode(base64.getBytes(java.nio.charset.StandardCharsets.US_ASCII));
162     }
163
164     @Override
165     public void onDataTreeChanged(final Collection<DataTreeModification<Keystore>> changes) {
166         LOG.debug("Keystore updated: {}", changes);
167
168         for (final DataTreeModification<Keystore> change : changes) {
169             final DataObjectModification<Keystore> rootNode = change.getRootNode();
170
171             for (final DataObjectModification<? extends DataObject> changedChild : rootNode.getModifiedChildren()) {
172                 if (changedChild.getDataType().equals(KeyCredential.class)) {
173                     final Keystore dataAfter = rootNode.getDataAfter();
174
175                     pairs.clear();
176                     if (dataAfter != null) {
177                         dataAfter.nonnullKeyCredential().values()
178                             .forEach(pair -> pairs.put(pair.key().getKeyId(), pair));
179                     }
180
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);
185                 }
186
187             }
188         }
189     }
190
191     private void onPrivateKeyChanged(final DataObjectModification<PrivateKey> objectModification) {
192         switch (objectModification.getModificationType()) {
193             case SUBTREE_MODIFIED:
194             case WRITE:
195                 final PrivateKey privateKey = objectModification.getDataAfter();
196                 privateKeys.put(privateKey.getName(), privateKey);
197                 break;
198             case DELETE:
199                 privateKeys.remove(objectModification.getDataBefore().getName());
200                 break;
201             default:
202                 break;
203         }
204     }
205
206     private void onTrustedCertificateChanged(final DataObjectModification<TrustedCertificate> objectModification) {
207         switch (objectModification.getModificationType()) {
208             case SUBTREE_MODIFIED:
209             case WRITE:
210                 final TrustedCertificate trustedCertificate = objectModification.getDataAfter();
211                 trustedCertificates.put(trustedCertificate.getName(), trustedCertificate);
212                 break;
213             case DELETE:
214                 trustedCertificates.remove(objectModification.getDataBefore().getName());
215                 break;
216             default:
217                 break;
218         }
219     }
220 }