c2d6701afd8f1c040260b043fbca7580d92108c3
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / ca / LocalCA.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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====================================================
19  *
20  */
21 package org.onap.aaf.auth.cm.ca;
22
23 import java.io.File;
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;
46
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;
73
74 public class LocalCA extends CA {
75
76     private final static BigInteger ONE = new BigInteger("1");
77     // Extensions
78     private static final KeyPurposeId[] ASN_WebUsage = new KeyPurposeId[] {
79                 KeyPurposeId.id_kp_serverAuth, // WebServer
80                 KeyPurposeId.id_kp_clientAuth // WebClient
81                 };
82
83     private final PrivateKey caKey;
84     private final X500Name issuer;
85     private BigInteger serial;
86     private final X509ChainWithIssuer x509cwi; // "Cert" is CACert
87
88
89     public LocalCA(Access access, final String name, final String env, final String[][] params) throws IOException, CertException {
90         super(access, name, env);
91
92         serial = new BigInteger(64,new SecureRandom());
93
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>]+");
96         }
97
98         // Read in the Private Key
99         String configured;
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);
106                 try {
107                     String dir = access.getProperty(CM_PUBLIC_DIR, "");
108                     if (!"".equals(dir) && !dir.endsWith("/")) {
109                         dir = dir + '/';
110                     }
111
112                     String path;
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));
117                     }
118                     x509cwi = new X509ChainWithIssuer(frs);
119                 } finally {
120                     for (FileReader fr : frs) {
121                         if (fr!=null) {
122                             fr.close();
123                         }
124                     }
125                 }
126                 configured = "Configured with " + fileName;
127             } else {
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>>");
130                 }
131                 try {
132                     Provider p;
133                     KeyStore keyStore;
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);
145                     } else {
146                         throw new CertException("Unknown Keystore type from filename " + fileName);
147                     }
148
149                     KeyStore.ProtectionParameter keyPass;
150
151                     try {
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.");
155                         }
156                         char[] ksPass = pass.toCharArray();
157                         //Assuming Key Pass is same as Keystore Pass
158                         keyPass = new KeyStore.PasswordProtection(ksPass);
159
160                         keyStore.load(fis,ksPass);
161                     } finally {
162                         if (fis != null) {
163                             fis.close();
164                         }
165                     }
166                     Entry entry;
167                     if (fileName.endsWith(".pkcs11")) {
168                         entry = keyStore.getEntry(params[0][1]/*alias*/, null);
169                     } else {
170                         entry = keyStore.getEntry(params[0][1]/*alias*/, keyPass);
171                     }
172                     if (entry==null) {
173                         throw new CertException("There is no Keystore entry with name '" + params[0][1] +'\'');
174                     }
175                     PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry)entry;
176                     caKey = privateKeyEntry.getPrivateKey();
177
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);
182                 }
183             }
184         } else {
185             throw new CertException("Private Key, " + f.getPath() + ", does not exist");
186         }
187
188         X500NameBuilder xnb = new X500NameBuilder();
189         List<RDN> rp = RDN.parse(',', x509cwi.getIssuerDN());
190         Collections.reverse(rp);
191         for (RDN rnd : rp) {
192             xnb.addRDN(rnd.aoi,rnd.value);
193         }
194         issuer = xnb.build();
195         access.printf(Level.INIT, "LocalCA is configured with %s.  The Issuer DN is %s.",
196                 configured, issuer.toString());
197     }
198
199     /* (non-Javadoc)
200      * @see org.onap.aaf.auth.cm.service.CA#sign(org.bouncycastle.pkcs.PKCS10CertificationRequest)
201      */
202     @Override
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);
210         try {
211             BigInteger bi;
212
213             synchronized(ONE) {
214                 bi = serial;
215                 serial = serial.add(ONE);
216             }
217
218             RSAPublicKey rpk = (RSAPublicKey)csrmeta.keypair(trans).getPublic();
219             X509v3CertificateBuilder xcb = new X509v3CertificateBuilder(
220                     issuer,
221                     bi, // replace with Serialnumber scheme
222                     start,
223                     end,
224                     csrmeta.x500Name(),
225                     SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(new RSAKeyParameters(false,rpk.getModulus(),rpk.getPublicExponent()))
226 //                    new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded()))
227                     );
228             List<GeneralName> lsan = new ArrayList<>();
229             for (String s : csrmeta.sans()) {
230                 lsan.add(new GeneralName(GeneralName.dNSName,s));
231             }
232             GeneralName[] sans = new GeneralName[lsan.size()];
233             lsan.toArray(sans);
234
235             JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
236                 xcb.addExtension(Extension.basicConstraints,
237                         false, new BasicConstraints(false
238                                 ))
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))
253                     ;
254
255             x509 = new JcaX509CertificateConverter().getCertificate(
256                     xcb.build(BCFactory.contentSigner(caKey)));
257         } catch (GeneralSecurityException|OperatorCreationException e) {
258             throw new CertException(e);
259         } finally {
260             tt.done();
261         }
262
263         return new X509andChain(x509,x509cwi.trustChain);
264     }
265
266 }