Refactor Client Config
[aaf/authz.git] / cadi / aaf / src / main / java / org / onap / aaf / cadi / configure / PlaceArtifactInKeystore.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
22 package org.onap.aaf.cadi.configure;
23
24 import java.io.File;
25 import java.security.KeyStore;
26 import java.security.PrivateKey;
27 import java.security.cert.Certificate;
28 import java.security.cert.X509Certificate;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Set;
34
35 import org.onap.aaf.cadi.CadiException;
36 import org.onap.aaf.cadi.Symm;
37 import org.onap.aaf.cadi.config.Config;
38 import org.onap.aaf.cadi.util.Chmod;
39 import org.onap.aaf.misc.env.Trans;
40
41 import certman.v1_0.Artifacts.Artifact;
42 import certman.v1_0.CertInfo;
43
44 public class PlaceArtifactInKeystore extends ArtifactDir {
45     private String kst;
46
47     public PlaceArtifactInKeystore(String kst) {
48         this.kst = kst;
49     }
50
51     @Override
52     public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException {
53         File fks = new File(dir,arti.getNs()+'.'+(kst==Agent.PKCS12?"p12":kst));
54         try {
55             KeyStore jks = KeyStore.getInstance(kst);
56             if (fks.exists()) {
57                 File backup = File.createTempFile(fks.getName()+'.', ".backup",dir);
58                 fks.renameTo(backup);
59             }    
60
61             // Get the Cert(s)... Might include Trust store
62             Collection<? extends Certificate> certColl = Factory.toX509Certificate(certInfo.getCerts());
63             // find where the trusts end in 1.0 API
64         
65             X509Certificate x509;
66             List<X509Certificate> chainList = new ArrayList<>();
67             Set<X509Certificate> caSet = new HashSet<>();
68             for (Certificate c : certColl) {
69                 x509 = (X509Certificate)c;
70                 // Is a Root (self-signed, anyway)
71                 if (x509.getSubjectDN().equals(x509.getIssuerDN())) {
72                     caSet.add(x509);
73                 } else {
74                     chainList.add(x509);
75                 }
76             }
77 //            chainList.addAll(caSet);
78             //Collections.reverse(chainList);
79
80             // Properties, etc
81             // Add CADI Keyfile Entry to Properties
82             File keyfile = new File(arti.getDir()+'/'+arti.getNs() + ".keyfile");
83             PropHolder props = PropHolder.get(arti, "cred.props");
84             props.add(Config.CADI_KEYFILE,keyfile.getAbsolutePath());
85
86             // Set Keystore Password
87             props.add(Config.CADI_KEYSTORE,fks.getAbsolutePath());
88             String keystorePass = Symm.randomGen(Agent.PASS_SIZE);
89             props.addEnc(Config.CADI_KEYSTORE_PASSWORD,keystorePass);
90             char[] keystorePassArray = keystorePass.toCharArray();
91             jks.load(null,keystorePassArray); // load in
92             
93             // Add Private Key/Cert Entry for App
94             // Note: Java SSL security classes, while having a separate key from keystore,
95             // is documented to not actually work. 
96             // java.security.UnrecoverableKeyException: Cannot recover key
97             // You can create a custom Key Manager to make it work, but Practicality  
98             // dictates that you live with the default, meaning, they are the same
99             String keyPass = keystorePass; //Symm.randomGen(CmAgent.PASS_SIZE);
100             PrivateKey pk = Factory.toPrivateKey(trans, certInfo.getPrivatekey());
101             props.addEnc(Config.CADI_KEY_PASSWORD, keyPass);
102             props.add(Config.CADI_ALIAS, arti.getMechid());
103 //            Set<Attribute> attribs = new HashSet<>();
104 //            if (kst.equals("pkcs12")) {
105 //                // Friendly Name
106 //                attribs.add(new PKCS12Attribute("1.2.840.113549.1.9.20", arti.getNs()));
107 //            } 
108 //            
109             KeyStore.ProtectionParameter protParam = 
110                     new KeyStore.PasswordProtection(keyPass.toCharArray());
111             
112             Certificate[] trustChain = new Certificate[chainList.size()];
113             chainList.toArray(trustChain);
114             KeyStore.PrivateKeyEntry pkEntry = 
115                 new KeyStore.PrivateKeyEntry(pk, trustChain);
116             jks.setEntry(arti.getMechid(), 
117                     pkEntry, protParam);
118
119             // Write out
120             write(fks,Chmod.to644,jks,keystorePassArray);
121             
122             // Change out to TrustStore
123             // NOTE: PKCS12 does NOT support Trusted Entries.  Put in JKS Always
124             fks = new File(dir,arti.getNs()+".trust.jks");
125             if (fks.exists()) {
126                 File backup = File.createTempFile(fks.getName()+'.', ".backup",dir);
127                 fks.renameTo(backup);
128             }    
129
130             jks = KeyStore.getInstance(Agent.JKS);
131             
132             // Set Truststore Password
133             props.add(Config.CADI_TRUSTSTORE,fks.getAbsolutePath());
134             String trustStorePass = Symm.randomGen(Agent.PASS_SIZE);
135             props.addEnc(Config.CADI_TRUSTSTORE_PASSWORD,trustStorePass);
136             char[] truststorePassArray = trustStorePass.toCharArray();
137             jks.load(null,truststorePassArray); // load in
138             
139             // Add Trusted Certificates, but PKCS12 doesn't support
140             Certificate[] trustCAs = new Certificate[caSet.size()];
141             caSet.toArray(trustCAs);
142             for (int i=0; i<trustCAs.length;++i) {
143                 jks.setCertificateEntry("ca_" + arti.getCa() + '_' + i, trustCAs[i]);
144             }
145             // Write out
146             write(fks,Chmod.to644,jks,truststorePassArray);
147             return true;
148         } catch (Exception e) {
149             throw new CadiException(e);
150         }
151     }
152
153 }