summaryrefslogtreecommitdiffstats
path: root/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java
blob: 26b4e2aa9b8e4e5004c6734e080bcc196334016a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
 * ============LICENSE_START====================================================
 * org.onap.aaf
 * ===========================================================================
 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
 * ===========================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END====================================================
 *
 */
package org.onap.aaf.auth.cm.ca;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.bouncycastle.asn1.x500.style.BCStyle;
import org.onap.aaf.auth.cm.cert.CSRMeta;
import org.onap.aaf.auth.cm.cert.RDN;
import org.onap.aaf.cadi.Access;
import org.onap.aaf.cadi.Access.Level;
import org.onap.aaf.cadi.config.Config;
import org.onap.aaf.cadi.configure.CertException;
import org.onap.aaf.misc.env.Trans;
import org.onap.aaf.misc.env.util.Split;

public abstract class CA {
    private static final String MUST_EXIST_TO_CREATE_CSRS_FOR = " must exist to create CSRs for ";
    //TODO figuring out what is an Issuing CA is a matter of convention.  Consider SubClassing for Open Source
    public static final String ISSUING_CA = "Issuing CA";
    public static final String CM_CA_PREFIX = "cm_ca.";
    public static final String CM_CA_BASE_SUBJECT = ".baseSubject";
    public static final String CM_CA_ENV_TAG = ".env_tag";
    protected static final String CM_PUBLIC_DIR = "cm_public_dir";
    private static final String CM_TRUST_CAS = "cm_trust_cas";
    protected static final String CM_BACKUP_CAS = "cm_backup_cas";

    public static final Set<String> EMPTY = Collections.unmodifiableSet(new HashSet<>());

    
    private final String name;
    private final String env;
    private MessageDigest messageDigest;
    private final String permNS; 
    private final String permType;
    private final ArrayList<String> idDomains;
    private String[] trustedCAs;
    private String[] caIssuerDNs;
    private List<RDN> rdns;
    private final boolean env_tag;


    protected CA(Access access, String caName, String env) throws IOException, CertException {
        trustedCAs = new String[4]; // starting array
        this.name = caName;
        this.env = env;
        this.env_tag = env==null || env.isEmpty()?false: 
        		Boolean.parseBoolean(access.getProperty(CM_CA_ENV_TAG, Boolean.FALSE.toString()));
        permNS=null;
        String prefix = CM_CA_PREFIX + name;
        permType = access.getProperty(prefix + ".perm_type",null);
        if (permType==null) {
            throw new CertException(prefix + ".perm_type" + MUST_EXIST_TO_CREATE_CSRS_FOR + caName);
        }
        caIssuerDNs = Split.splitTrim(':', access.getProperty(Config.CADI_X509_ISSUERS, null));
        
        String tag = CA.CM_CA_PREFIX+caName+CA.CM_CA_BASE_SUBJECT;
        
        String fields = access.getProperty(tag, null);
        if (fields==null) {
            throw new CertException(tag + MUST_EXIST_TO_CREATE_CSRS_FOR + caName);
        }
        access.log(Level.INFO, tag, "=",fields);
        rdns = RDN.parse('/',fields);
        for (RDN rdn : rdns) {
            if (rdn.aoi==BCStyle.EmailAddress) { // Cert Specs say Emails belong in Subject
                throw new CertException("email address is not allowed in " + CM_CA_BASE_SUBJECT);
            }
        }
        
        idDomains = new ArrayList<>();
        StringBuilder sb = null;
        for (String s : Split.splitTrim(',', access.getProperty(CA.CM_CA_PREFIX+caName+".idDomains", ""))) {
            if (s.length()>0) {
                if (sb==null) {
                    sb = new StringBuilder();
                } else {
                    sb.append(", ");
                }
                idDomains.add(s);
                sb.append(s);
            }
        }
        if (sb!=null) {
            access.printf(Level.INIT, "CA '%s' supports Personal Certificates for %s", caName, sb);
        }
        
        String dataDir = access.getProperty(CM_PUBLIC_DIR,null);
        if (dataDir!=null) {
            File data = new File(dataDir);
            byte[] bytes;
            if (data.exists()) {
                String trustCas = access.getProperty(CM_TRUST_CAS,null);
                if (trustCas!=null) {
                    for (String fname : Split.splitTrim(',', trustCas)) {
                        File crt;
                        if (fname.contains("/")) {
                            crt = new File(fname);
                        } else {
                            crt = new File(data,fname);
                        }
                        if (crt.exists()) {
                            access.printf(Level.INIT, "Loading CA Cert from %s", crt.getAbsolutePath());
                            bytes = new byte[(int)crt.length()];
                            FileInputStream fis = new FileInputStream(crt);
                            try {
                                int read = fis.read(bytes);
                                if (read>0) {    
                                    addTrustedCA(new String(bytes));
                                }
                            } finally {
                                fis.close();
                            }
                        } else {
                            access.printf(Level.INIT, "FAILED to Load CA Cert from %s", crt.getAbsolutePath());
                        }
                    }
                } else {
                    access.printf(Level.INIT, "Cannot load external TRUST CAs: No property %s",CM_TRUST_CAS);
                }
            } else {
                access.printf(Level.INIT, "Cannot load external TRUST CAs: %s doesn't exist, or is not accessible",data.getAbsolutePath());
            }
        }
    }

    protected void addCaIssuerDN(String issuerDN) {
        boolean changed = true;
        for (String id : caIssuerDNs) {
            if (id.equals(issuerDN)) {
                changed = false;
                break;
            }
        }
        if (changed) {
            String[] newsa = new String[caIssuerDNs.length+1];
            newsa[0]=issuerDN;
            System.arraycopy(caIssuerDNs, 0, newsa, 1, caIssuerDNs.length);
            caIssuerDNs = newsa;
        }
    }
    
    protected synchronized void addTrustedCA(final String crtString) {
        String crt;
        if (crtString.endsWith("\n")) {
            crt = crtString;
        } else {
            crt = crtString + '\n';
        }
        for (int i=0;i<trustedCAs.length;++i) {
            if (trustedCAs[i]==null) {
                trustedCAs[i]=crt;
                return;
            }
        }
        String[] temp = new String[trustedCAs.length+5];
        System.arraycopy(trustedCAs,0,temp, 0, trustedCAs.length);
        temp[trustedCAs.length]=crt;
        trustedCAs = temp;
    }
    
    public String[] getCaIssuerDNs() {
        return caIssuerDNs;
    }
    
    public String[] getTrustedCAs() {
        return trustedCAs;
    }
    
    public boolean shouldAddEnvTag() {
    	return env_tag; 
    }
    
    public String getEnv() {
        return env;
    }

    protected void setMessageDigest(MessageDigest md) {
        messageDigest = md;
    }

    /*
     * End Required Constructor calls
     */

    public String getName() {
        return name;
    }
    
    
    public String getPermNS() {
        return permNS;
    }
    
    public String getPermType() {
        return permType;
    }
    
    public abstract X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException;

    /* (non-Javadoc)
     * @see org.onap.aaf.auth.cm.ca.CA#inPersonalDomains(java.security.Principal)
     */
    public boolean inPersonalDomains(Principal p) {
        int at = p.getName().indexOf('@');
        if (at>=0) {
            return idDomains.contains(p.getName().substring(at+1));
        } else {
            return false;
        }
    }

    public MessageDigest messageDigest() {
        return messageDigest;
    }

    public CSRMeta newCSRMeta() {
        return new CSRMeta(rdns);
    }

}