2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
21 package org.onap.aaf.auth.cm.ca;
24 import java.io.FileInputStream;
25 import java.io.FileReader;
26 import java.io.IOException;
27 import java.math.BigInteger;
28 import java.security.GeneralSecurityException;
29 import java.security.KeyStore;
30 import java.security.KeyStore.Entry;
31 import java.security.KeyStore.PrivateKeyEntry;
32 import java.security.KeyStoreException;
33 import java.security.NoSuchAlgorithmException;
34 import java.security.PrivateKey;
35 import java.security.Provider;
36 import java.security.SecureRandom;
37 import java.security.UnrecoverableEntryException;
38 import java.security.cert.CertificateException;
39 import java.security.cert.X509Certificate;
40 import java.security.interfaces.RSAPublicKey;
41 import java.util.ArrayList;
42 import java.util.Collections;
43 import java.util.Date;
44 import java.util.GregorianCalendar;
45 import java.util.List;
47 import org.bouncycastle.asn1.x500.X500Name;
48 import org.bouncycastle.asn1.x500.X500NameBuilder;
49 import org.bouncycastle.asn1.x509.BasicConstraints;
50 import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
51 import org.bouncycastle.asn1.x509.Extension;
52 import org.bouncycastle.asn1.x509.GeneralName;
53 import org.bouncycastle.asn1.x509.GeneralNames;
54 import org.bouncycastle.asn1.x509.KeyPurposeId;
55 import org.bouncycastle.asn1.x509.KeyUsage;
56 import org.bouncycastle.cert.X509v3CertificateBuilder;
57 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
58 import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
59 import org.bouncycastle.crypto.params.RSAKeyParameters;
60 import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
61 import org.bouncycastle.operator.OperatorCreationException;
62 import org.onap.aaf.auth.cm.cert.BCFactory;
63 import org.onap.aaf.auth.cm.cert.CSRMeta;
64 import org.onap.aaf.auth.cm.cert.RDN;
65 import org.onap.aaf.auth.env.NullTrans;
66 import org.onap.aaf.cadi.Access;
67 import org.onap.aaf.cadi.Access.Level;
68 import org.onap.aaf.cadi.configure.CertException;
69 import org.onap.aaf.cadi.configure.Factory;
70 import org.onap.aaf.misc.env.Env;
71 import org.onap.aaf.misc.env.TimeTaken;
72 import org.onap.aaf.misc.env.Trans;
74 public class LocalCA extends CA {
76 private final static BigInteger ONE = new BigInteger("1");
78 private static final KeyPurposeId[] ASN_WebUsage = new KeyPurposeId[] {
79 KeyPurposeId.id_kp_serverAuth, // WebServer
80 KeyPurposeId.id_kp_clientAuth // WebClient
83 private final PrivateKey caKey;
84 private final X500Name issuer;
85 private BigInteger serial;
86 private final X509ChainWithIssuer x509cwi; // "Cert" is CACert
89 public LocalCA(Access access, final String name, final String env, final String[][] params) throws IOException, CertException {
90 super(access, name, env);
92 serial = new BigInteger(64,new SecureRandom());
94 if (params.length<1 || params[0].length<2) {
95 throw new IOException("LocalCA expects cm_ca.<ca name>=org.onap.aaf.auth.cm.ca.LocalCA,<full path to key file>[;<Full Path to Trust Chain, ending with actual CA>]+");
98 // Read in the Private Key
100 File f = new File(params[0][0]);
101 if (f.exists() && f.isFile()) {
102 String fileName = f.getName();
103 if (fileName.endsWith(".key")) {
104 caKey = Factory.toPrivateKey(NullTrans.singleton(),f);
105 List<FileReader> frs = new ArrayList<>(params.length-1);
107 String dir = access.getProperty(CM_PUBLIC_DIR, "");
108 if (!"".equals(dir) && !dir.endsWith("/")) {
113 for (int i=1; i<params[0].length; ++i) { // first param is Private Key, remainder are TrustChain
114 path = !params[0][i].contains("/")?dir+params[0][i]:params[0][i];
115 access.printf(Level.INIT, "Loading a TrustChain Member for %s from %s\n",name, path);
116 frs.add(new FileReader(path));
118 x509cwi = new X509ChainWithIssuer(frs);
120 for (FileReader fr : frs) {
126 configured = "Configured with " + fileName;
128 if (params.length<1 || params[0].length<3) {
129 throw new CertException("LocalCA parameters must be <keystore [.p12|.pkcs12|.jks|.pkcs11(sun only)]; <alias>; enc:<encrypted Keystore Password>>");
134 FileInputStream fis = null;
135 if (fileName.endsWith(".pkcs11")) {
136 String ksType="PKCS11";
137 p = Factory.getSecurityProvider(ksType,params);
138 keyStore = KeyStore.getInstance(ksType,p);
139 } else if (fileName.endsWith(".jks")) {
140 keyStore = KeyStore.getInstance("JKS");
141 fis = new FileInputStream(f);
142 } else if (fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) {
143 keyStore = KeyStore.getInstance("PKCS12");
144 fis = new FileInputStream(f);
146 throw new CertException("Unknown Keystore type from filename " + fileName);
149 KeyStore.ProtectionParameter keyPass;
152 String pass = access.decrypt(params[0][2]/*encrypted passcode*/, true);
153 if (pass==null || pass.isEmpty()) {
154 throw new CertException("Passcode for " + fileName + " cannot be decrypted.");
156 char[] ksPass = pass.toCharArray();
157 //Assuming Key Pass is same as Keystore Pass
158 keyPass = new KeyStore.PasswordProtection(ksPass);
160 keyStore.load(fis,ksPass);
167 if (fileName.endsWith(".pkcs11")) {
168 entry = keyStore.getEntry(params[0][1]/*alias*/, null);
170 entry = keyStore.getEntry(params[0][1]/*alias*/, keyPass);
173 throw new CertException("There is no Keystore entry with name '" + params[0][1] +'\'');
175 PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry)entry;
176 caKey = privateKeyEntry.getPrivateKey();
178 x509cwi = new X509ChainWithIssuer(privateKeyEntry.getCertificateChain());
179 configured = "keystore \"" + fileName + "\", alias " + params[0][1];
180 } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException e) {
181 throw new CertException("Exception opening Keystore " + fileName, e);
185 throw new CertException("Private Key, " + f.getPath() + ", does not exist");
188 X500NameBuilder xnb = new X500NameBuilder();
189 List<RDN> rp = RDN.parse(',', x509cwi.getIssuerDN());
190 Collections.reverse(rp);
192 xnb.addRDN(rnd.aoi,rnd.value);
194 issuer = xnb.build();
195 access.printf(Level.INIT, "LocalCA is configured with %s. The Issuer DN is %s.",
196 configured, issuer.toString());
200 * @see org.onap.aaf.auth.cm.service.CA#sign(org.bouncycastle.pkcs.PKCS10CertificationRequest)
203 public X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException {
204 GregorianCalendar gc = new GregorianCalendar();
205 Date start = gc.getTime();
206 gc.add(GregorianCalendar.MONTH, 12);
207 Date end = gc.getTime();
208 X509Certificate x509;
209 TimeTaken tt = trans.start("Create/Sign Cert",Env.SUB);
215 serial = serial.add(ONE);
218 RSAPublicKey rpk = (RSAPublicKey)csrmeta.keypair(trans).getPublic();
219 X509v3CertificateBuilder xcb = new X509v3CertificateBuilder(
221 bi, // replace with Serialnumber scheme
225 SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new RSAKeyParameters(false,rpk.getModulus(),rpk.getPublicExponent()))
226 // new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded()))
228 List<GeneralName> lsan = new ArrayList<>();
229 for (String s : csrmeta.sans()) {
230 lsan.add(new GeneralName(GeneralName.dNSName,s));
232 GeneralName[] sans = new GeneralName[lsan.size()];
235 JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
236 xcb.addExtension(Extension.basicConstraints,
237 false, new BasicConstraints(false
239 .addExtension(Extension.keyUsage,
240 true, new KeyUsage(KeyUsage.digitalSignature
241 | KeyUsage.keyEncipherment
242 | KeyUsage.nonRepudiation))
243 .addExtension(Extension.extendedKeyUsage,
244 true, new ExtendedKeyUsage(ASN_WebUsage))
245 .addExtension(Extension.authorityKeyIdentifier,
246 false, extUtils.createAuthorityKeyIdentifier(x509cwi.cert))
247 .addExtension(Extension.subjectKeyIdentifier,
248 false, extUtils.createSubjectKeyIdentifier(rpk))
249 .addExtension(Extension.subjectAlternativeName,
250 false, new GeneralNames(sans))
251 // .addExtension(MiscObjectIdentifiers.netscape, true, new NetscapeCertType(
252 // NetscapeCertType.sslClient|NetscapeCertType.sslClient))
255 x509 = new JcaX509CertificateConverter().getCertificate(
256 xcb.build(BCFactory.contentSigner(caKey)));
257 } catch (GeneralSecurityException|OperatorCreationException e) {
258 throw new CertException(e);
263 return new X509andChain(x509,x509cwi.trustChain);