Configuration and Auto-Certificates
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / cert / CSRMeta.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.cert;
22
23 import java.io.IOException;
24 import java.math.BigInteger;
25 import java.security.KeyPair;
26 import java.security.SecureRandom;
27 import java.security.cert.CertificateException;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.GregorianCalendar;
32 import java.util.List;
33
34 import org.bouncycastle.asn1.ASN1Sequence;
35 import org.bouncycastle.asn1.DERPrintableString;
36 import org.bouncycastle.asn1.pkcs.Attribute;
37 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
38 import org.bouncycastle.asn1.x500.X500Name;
39 import org.bouncycastle.asn1.x500.X500NameBuilder;
40 import org.bouncycastle.asn1.x500.style.BCStyle;
41 import org.bouncycastle.asn1.x509.Extension;
42 import org.bouncycastle.asn1.x509.Extensions;
43 import org.bouncycastle.asn1.x509.GeneralName;
44 import org.bouncycastle.asn1.x509.GeneralNames;
45 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
46 import org.bouncycastle.cert.X509v3CertificateBuilder;
47 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
48 import org.bouncycastle.operator.OperatorCreationException;
49 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
50 import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
51 import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder;
52 import org.onap.aaf.cadi.configure.CertException;
53 import org.onap.aaf.cadi.configure.Factory;
54 import org.onap.aaf.misc.env.Trans;
55
56 public class CSRMeta {
57         private String cn;
58         private String mechID;
59         private String environment;
60         private String email;
61         private String challenge;
62         private List<RDN> rdns;
63         private ArrayList<String> sanList = new ArrayList<>();
64         private KeyPair keyPair;
65         private X500Name name = null;
66         private SecureRandom random = new SecureRandom();
67
68         public CSRMeta(List<RDN> rdns) {
69                 this.rdns = rdns;
70         }
71
72         public X500Name x500Name() {
73                 if(name==null) {
74                         X500NameBuilder xnb = new X500NameBuilder();
75                         xnb.addRDN(BCStyle.CN,cn);
76                         xnb.addRDN(BCStyle.E,email);
77                         if(mechID!=null) {
78                                 if(environment==null) {
79                                         xnb.addRDN(BCStyle.OU,mechID);
80                                 } else {
81                                         xnb.addRDN(BCStyle.OU,mechID+':'+environment);
82                                 }
83                         }
84                         for(RDN rdn : rdns) {
85                                 xnb.addRDN(rdn.aoi,rdn.value);
86                         }
87                         name = xnb.build();
88                 }
89                 return name;
90         }
91         
92         
93         public PKCS10CertificationRequest  generateCSR(Trans trans) throws IOException, CertException {
94                 PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name(),keypair(trans).getPublic());
95                 if(challenge!=null) {
96                         DERPrintableString password = new DERPrintableString(challenge);
97                         builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, password);
98                 }
99                 
100                 int plus = email==null?0:1;
101                 if(!sanList.isEmpty()) {
102                         GeneralName[] gna = new GeneralName[sanList.size()+plus];
103                         int i=-1;
104                         for(String s : sanList) {
105                                 gna[++i]=new GeneralName(GeneralName.dNSName,s);
106                         }
107                         gna[++i]=new GeneralName(GeneralName.rfc822Name,email);
108                         
109                         builder.addAttribute(
110                                         PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
111                                         new Extensions(new Extension[] {
112                                                         new Extension(Extension.subjectAlternativeName,false,new GeneralNames(gna).getEncoded())
113                                         })
114                         );
115                 }
116
117                 try {
118                         return builder.build(BCFactory.contentSigner(keypair(trans).getPrivate()));
119                 } catch (OperatorCreationException e) {
120                         throw new CertException(e);
121                 }
122         }
123         
124         @SuppressWarnings("deprecation")
125         public static void dump(PKCS10CertificationRequest csr) {
126                  Attribute[] certAttributes = csr.getAttributes();
127                  for (Attribute attribute : certAttributes) {
128                      if (!attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
129                                          continue;
130                                  }
131
132                                  Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
133                                  GeneralNames gns = GeneralNames.fromExtensions(extensions,Extension.subjectAlternativeName);
134                                  GeneralName[] names = gns.getNames();
135                                  for(int k=0; k < names.length; k++) {
136                                                  String title = "";
137                                                  if(names[k].getTagNo() == GeneralName.dNSName) {
138                                                                  title = "dNSName";
139                                                  } else if(names[k].getTagNo() == GeneralName.iPAddress) {
140                                                                  title = "iPAddress";
141                                                                  // Deprecated, but I don't see anything better to use.
142                                                                  names[k].toASN1Object();
143                                                  } else if(names[k].getTagNo() == GeneralName.otherName) {
144                                                                  title = "otherName";
145                                                  } else if(names[k].getTagNo() == GeneralName.rfc822Name) {
146                                                                  title = "email";
147                                                  }
148
149                                                  System.out.println(title + ": "+ names[k].getName());
150                                  }
151                  }
152         }
153         
154         public X509Certificate initialConversationCert(Trans trans) throws IOException, CertificateException, OperatorCreationException {
155                 GregorianCalendar gc = new GregorianCalendar();
156                 Date start = gc.getTime();
157                 gc.add(GregorianCalendar.DAY_OF_MONTH,2);
158                 Date end = gc.getTime();
159                 @SuppressWarnings("deprecation")
160                 X509v3CertificateBuilder xcb = new X509v3CertificateBuilder(
161                                 x500Name(),
162                                 new BigInteger(12,random), // replace with Serialnumber scheme
163                                 start,
164                                 end,
165                                 x500Name(),
166                                 new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keypair(trans).getPublic().getEncoded()))
167                                 );
168                 return new JcaX509CertificateConverter().getCertificate(
169                                 xcb.build(BCFactory.contentSigner(keypair(trans).getPrivate())));
170         }
171
172         public CSRMeta san(String v) {
173                 sanList.add(v);
174                 return this;
175         }
176
177         public List<String> sans() {
178                 return sanList;
179         }
180
181
182         public KeyPair keypair(Trans trans) {
183                 if(keyPair == null) {
184                         keyPair = Factory.generateKeyPair(trans);
185                 }
186                 return keyPair;
187         }
188
189         /**
190          * @return the cn
191          */
192         public String cn() {
193                 return cn;
194         }
195
196
197         /**
198          * @param cn the cn to set
199          */
200         public void cn(String cn) {
201                 this.cn = cn;
202         }
203
204         /**
205          * Environment of Service MechID is good for
206          */
207         public void environment(String env) {
208                 environment = env;
209         }
210         
211         /**
212          * 
213          * @return
214          */
215         public String environment() {
216                 return environment;
217         }
218         
219         /**
220          * @return the mechID
221          */
222         public String mechID() {
223                 return mechID;
224         }
225
226
227         /**
228          * @param mechID the mechID to set
229          */
230         public void mechID(String mechID) {
231                 this.mechID = mechID;
232         }
233
234
235         /**
236          * @return the email
237          */
238         public String email() {
239                 return email;
240         }
241
242
243         /**
244          * @param email the email to set
245          */
246         public void email(String email) {
247                 this.email = email;
248         }
249
250         /**
251          * @return the challenge
252          */
253         public String challenge() {
254                 return challenge;
255         }
256
257
258         /**
259          * @param challenge the challenge to set
260          */
261         public void challenge(String challenge) {
262                 this.challenge = challenge;
263         }
264         
265 }