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