13876b141b90713f8bd72ce593cd628a0c8aaf66
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / ca / CA.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.IOException;
26 import java.security.MessageDigest;
27 import java.security.Principal;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Set;
33
34 import org.bouncycastle.asn1.x500.style.BCStyle;
35 import org.onap.aaf.auth.cm.cert.CSRMeta;
36 import org.onap.aaf.auth.cm.cert.RDN;
37 import org.onap.aaf.cadi.Access;
38 import org.onap.aaf.cadi.Access.Level;
39 import org.onap.aaf.cadi.config.Config;
40 import org.onap.aaf.cadi.configure.CertException;
41 import org.onap.aaf.misc.env.Trans;
42 import org.onap.aaf.misc.env.util.Split;
43
44 public abstract class CA {
45     private static final String MUST_EXIST_TO_CREATE_CSRS_FOR = " must exist to create CSRs for ";
46     //TODO figuring out what is an Issuing CA is a matter of convention.  Consider SubClassing for Open Source
47     public static final String ISSUING_CA = "Issuing CA";
48     public static final String CM_CA_PREFIX = "cm_ca.";
49     public static final String CM_CA_BASE_SUBJECT = ".baseSubject";
50     public static final String CM_CA_ENV_TAG = ".env_tag";
51     protected static final String CM_PUBLIC_DIR = "cm_public_dir";
52     private static final String CM_TRUST_CAS = "cm_trust_cas";
53     protected static final String CM_BACKUP_CAS = "cm_backup_cas";
54
55     public static final Set<String> EMPTY = Collections.unmodifiableSet(new HashSet<>());
56
57
58     private final String name;
59     private final String env;
60     private MessageDigest messageDigest;
61     private final String permNS;
62     private final String permType;
63     private final ArrayList<String> idDomains;
64     private String[] trustedCAs;
65     private String[] caIssuerDNs;
66     private List<RDN> rdns;
67     private final boolean env_tag;
68
69
70     protected CA(Access access, String caName, String env) throws IOException, CertException {
71         trustedCAs = new String[4]; // starting array
72         this.name = caName;
73         this.env = env;
74         this.env_tag = env==null || env.isEmpty()?false:
75                 Boolean.parseBoolean(access.getProperty(CM_CA_ENV_TAG, Boolean.FALSE.toString()));
76         permNS=null;
77         String prefix = CM_CA_PREFIX + name;
78         permType = access.getProperty(prefix + ".perm_type",null);
79         if (permType==null) {
80             throw new CertException(prefix + ".perm_type" + MUST_EXIST_TO_CREATE_CSRS_FOR + caName);
81         }
82         caIssuerDNs = Split.splitTrim(':', access.getProperty(Config.CADI_X509_ISSUERS, null));
83
84         String tag = CA.CM_CA_PREFIX+caName+CA.CM_CA_BASE_SUBJECT;
85
86         String fields = access.getProperty(tag, null);
87         if (fields==null) {
88             throw new CertException(tag + MUST_EXIST_TO_CREATE_CSRS_FOR + caName);
89         }
90         access.log(Level.INFO, tag, "=",fields);
91         rdns = RDN.parse('/',fields);
92         for (RDN rdn : rdns) {
93             if (rdn.aoi==BCStyle.EmailAddress) { // Cert Specs say Emails belong in Subject
94                 throw new CertException("email address is not allowed in " + CM_CA_BASE_SUBJECT);
95             }
96         }
97
98         idDomains = new ArrayList<>();
99         StringBuilder sb = null;
100         for (String s : Split.splitTrim(',', access.getProperty(CA.CM_CA_PREFIX+caName+".idDomains", ""))) {
101             if (s.length()>0) {
102                 if (sb==null) {
103                     sb = new StringBuilder();
104                 } else {
105                     sb.append(", ");
106                 }
107                 idDomains.add(s);
108                 sb.append(s);
109             }
110         }
111         if (sb!=null) {
112             access.printf(Level.INIT, "CA '%s' supports Personal Certificates for %s", caName, sb);
113         }
114
115         String dataDir = access.getProperty(CM_PUBLIC_DIR,null);
116         if (dataDir!=null) {
117             File data = new File(dataDir);
118             byte[] bytes;
119             if (data.exists()) {
120                 String trustCas = access.getProperty(CM_TRUST_CAS,null);
121                 if (trustCas!=null) {
122                     for (String fname : Split.splitTrim(',', trustCas)) {
123                         File crt;
124                         if (fname.contains("/")) {
125                             crt = new File(fname);
126                         } else {
127                             crt = new File(data,fname);
128                         }
129                         if (crt.exists()) {
130                             access.printf(Level.INIT, "Loading CA Cert from %s", crt.getAbsolutePath());
131                             bytes = new byte[(int)crt.length()];
132                             FileInputStream fis = new FileInputStream(crt);
133                             try {
134                                 int read = fis.read(bytes);
135                                 if (read>0) {
136                                     addTrustedCA(new String(bytes));
137                                 }
138                             } finally {
139                                 fis.close();
140                             }
141                         } else {
142                             access.printf(Level.INIT, "FAILED to Load CA Cert from %s", crt.getAbsolutePath());
143                         }
144                     }
145                 } else {
146                     access.printf(Level.INIT, "Cannot load external TRUST CAs: No property %s",CM_TRUST_CAS);
147                 }
148             } else {
149                 access.printf(Level.INIT, "Cannot load external TRUST CAs: %s doesn't exist, or is not accessible",data.getAbsolutePath());
150             }
151         }
152     }
153
154     protected void addCaIssuerDN(String issuerDN) {
155         boolean changed = true;
156         for (String id : caIssuerDNs) {
157             if (id.equals(issuerDN)) {
158                 changed = false;
159                 break;
160             }
161         }
162         if (changed) {
163             String[] newsa = new String[caIssuerDNs.length+1];
164             newsa[0]=issuerDN;
165             System.arraycopy(caIssuerDNs, 0, newsa, 1, caIssuerDNs.length);
166             caIssuerDNs = newsa;
167         }
168     }
169
170     protected synchronized void addTrustedCA(final String crtString) {
171         String crt;
172         if (crtString.endsWith("\n")) {
173             crt = crtString;
174         } else {
175             crt = crtString + '\n';
176         }
177         for (int i=0;i<trustedCAs.length;++i) {
178             if (trustedCAs[i]==null) {
179                 trustedCAs[i]=crt;
180                 return;
181             }
182         }
183         String[] temp = new String[trustedCAs.length+5];
184         System.arraycopy(trustedCAs,0,temp, 0, trustedCAs.length);
185         temp[trustedCAs.length]=crt;
186         trustedCAs = temp;
187     }
188
189     public String[] getCaIssuerDNs() {
190         return caIssuerDNs;
191     }
192
193     public String[] getTrustedCAs() {
194         return trustedCAs;
195     }
196
197     public boolean shouldAddEnvTag() {
198         return env_tag;
199     }
200
201     public String getEnv() {
202         return env;
203     }
204
205     protected void setMessageDigest(MessageDigest md) {
206         messageDigest = md;
207     }
208
209     /*
210      * End Required Constructor calls
211      */
212
213     public String getName() {
214         return name;
215     }
216
217
218     public String getPermNS() {
219         return permNS;
220     }
221
222     public String getPermType() {
223         return permType;
224     }
225
226     public abstract X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException;
227
228     /* (non-Javadoc)
229      * @see org.onap.aaf.auth.cm.ca.CA#inPersonalDomains(java.security.Principal)
230      */
231     public boolean inPersonalDomains(Principal p) {
232         int at = p.getName().indexOf('@');
233         if (at>=0) {
234             return idDomains.contains(p.getName().substring(at+1));
235         } else {
236             return false;
237         }
238     }
239
240     public MessageDigest messageDigest() {
241         return messageDigest;
242     }
243
244     public CSRMeta newCSRMeta() {
245         return new CSRMeta(rdns);
246     }
247
248 }