Merge "Sonar fixes related to exceptions"
[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 final SecureRandom random = new SecureRandom();
86         private BigInteger serial;
87         private final X509ChainWithIssuer x509cwi; // "Cert" is CACert
88         
89         
90         public LocalCA(Access access, final String name, final String env, final String[][] params) throws IOException, CertException {
91                 super(access, name, env);
92         
93                 serial = new BigInteger(64,random);
94
95                 if(params.length<1 || params[0].length<2) {
96                         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>]+");
97                 }
98                 
99                 // Read in the Private Key
100                 String configured;
101                 File f = new File(params[0][0]);
102                 if(f.exists() && f.isFile()) {
103                         String fileName = f.getName();
104                         if(fileName.endsWith(".key")) {
105                                 caKey = Factory.toPrivateKey(NullTrans.singleton(),f);
106                                 List<FileReader> frs = new ArrayList<>(params.length-1);
107                                 try {
108                                         String dir = access.getProperty(CM_PUBLIC_DIR, "");
109                                         if(!"".equals(dir) && !dir.endsWith("/")) {
110                                                 dir = dir + '/';
111                                         }
112
113                                         String path;
114                                         for(int i=1; i<params[0].length; ++i) { // first param is Private Key, remainder are TrustChain
115                                                 path = !params[0][i].contains("/")?dir+params[0][i]:params[0][i];
116                                                 access.printf(Level.INIT, "Loading a TrustChain Member for %s from %s\n",name, path);
117                                                 frs.add(new FileReader(path));
118                                         }
119                                         x509cwi = new X509ChainWithIssuer(frs);
120                                 } finally {
121                                         for(FileReader fr : frs) {
122                                                 if(fr!=null) {
123                                                         fr.close();
124                                                 }
125                                         }
126                                 }
127                                 configured = "Configured with " + fileName;
128                         } else {
129                                 if(params.length<1 || params[0].length<3) {
130                                         throw new CertException("LocalCA parameters must be <keystore [.p12|.pkcs12|.jks|.pkcs11(sun only)]; <alias>; enc:<encrypted Keystore Password>>");
131                                 }
132                                 try {
133                                         Provider p;
134                                         KeyStore keyStore;
135                                         FileInputStream fis = null;
136                                         if(fileName.endsWith(".pkcs11")) {
137                                                 String ksType="PKCS11";
138                                                 p = Factory.getSecurityProvider(ksType,params);
139                                                 keyStore = KeyStore.getInstance(ksType,p);
140                                         } else if(fileName.endsWith(".jks")) {
141                                                 keyStore = KeyStore.getInstance("JKS");
142                                                 fis = new FileInputStream(f);
143                                         } else if(fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) {
144                                                 keyStore = KeyStore.getInstance("PKCS12");
145                                                 fis = new FileInputStream(f);
146                                         } else {
147                                                 throw new CertException("Unknown Keystore type from filename " + fileName);
148                                         }
149                                         
150                                         KeyStore.ProtectionParameter keyPass;
151
152                                         try {
153                                                 String pass = access.decrypt(params[0][2]/*encrypted passcode*/, true);
154                                                 if(pass==null) {
155                                                         throw new CertException("Passcode for " + fileName + " cannot be decrypted.");
156                                                 }
157                                                 char[] ksPass = pass.toCharArray();
158                                                 //Assuming Key Pass is same as Keystore Pass
159                                                 keyPass = new KeyStore.PasswordProtection(ksPass);
160
161                                                 keyStore.load(fis,ksPass);
162                                         } finally {
163                                                 if (fis != null)
164                                                         fis.close();
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, 6);
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 }