AT&T 2.0.19 Code drop, stage 3
[aaf/authz.git] / auth / auth-certman / src / main / java / org / onap / aaf / auth / cm / ca / JscepCA.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.FileReader;
24 import java.io.IOException;
25 import java.net.Authenticator;
26 import java.net.MalformedURLException;
27 import java.net.PasswordAuthentication;
28 import java.net.URL;
29 import java.security.cert.CertStoreException;
30 import java.security.cert.Certificate;
31 import java.security.cert.CertificateException;
32 import java.security.cert.X509Certificate;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.concurrent.ConcurrentHashMap;
37
38 import org.bouncycastle.operator.OperatorCreationException;
39 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
40 import org.jscep.client.Client;
41 import org.jscep.client.ClientException;
42 import org.jscep.client.EnrollmentResponse;
43 import org.jscep.client.verification.CertificateVerifier;
44 import org.jscep.transaction.TransactionException;
45 import org.onap.aaf.auth.cm.cert.BCFactory;
46 import org.onap.aaf.auth.cm.cert.CSRMeta;
47 import org.onap.aaf.cadi.Access;
48 import org.onap.aaf.cadi.LocatorException;
49 import org.onap.aaf.cadi.Access.Level;
50 import org.onap.aaf.cadi.Locator.Item;
51 import org.onap.aaf.cadi.cm.CertException;
52 import org.onap.aaf.cadi.locator.HotPeerLocator;
53 import org.onap.aaf.misc.env.Env;
54 import org.onap.aaf.misc.env.TimeTaken;
55 import org.onap.aaf.misc.env.Trans;
56 import org.onap.aaf.misc.env.util.Split;
57
58 public class JscepCA extends CA {
59         static final String CA_PREFIX = "http://";
60         static final String CA_POSTFIX="/certsrv/mscep_admin/mscep.dll";
61
62         private final static String MS_PROFILE="1";
63         private final static int MAX_RETRY=3;
64         public static final long INVALIDATE_TIME = 1000*60*10; // 10 mins
65
66         // package on purpose
67         private Map<String,X509ChainWithIssuer> mxcwi_s;
68         private Map<Client,X509ChainWithIssuer> mxcwi_c;
69
70
71         private JscepClientLocator clients;
72
73         public JscepCA(final Access access, final String name, final String env, String [][] params) throws IOException, CertException, LocatorException {
74                 super(access, name, env);
75                 mxcwi_s = new ConcurrentHashMap<String,X509ChainWithIssuer>();
76                 mxcwi_c = new ConcurrentHashMap<Client,X509ChainWithIssuer>();
77                 
78                 if(params.length<2) {
79                         throw new CertException("No Trust Chain parameters are included");
80                 } 
81                 if(params[0].length<2) {
82                         throw new CertException("User/Password required for JSCEP");
83                 }
84                 final String id = params[0][0];
85                 final String pw = params[0][1]; 
86                 
87                 // Set this for NTLM password Microsoft
88                 Authenticator.setDefault(new Authenticator() {
89                           public PasswordAuthentication getPasswordAuthentication () {
90                             try {
91                                                 return new PasswordAuthentication (id,access.decrypt(pw,true).toCharArray());
92                                         } catch (IOException e) {
93                                                 access.log(e);
94                                         }
95                                         return null;
96                       }
97                 });
98                 
99                 StringBuilder urlstr = new StringBuilder();
100
101                 for(int i=1;i<params.length;++i) { // skip first section, which is user/pass
102                         // Work 
103                         if(i>1) {
104                                 urlstr.append(','); // delimiter
105                         }
106                         urlstr.append(params[i][0]);
107                         
108                         String dir = access.getProperty(CM_PUBLIC_DIR, "");
109                         if(!"".equals(dir) && !dir.endsWith("/")) {
110                                 dir = dir + '/';
111                         }
112                         String path;
113                         List<FileReader> frs = new ArrayList<FileReader>(params.length-1);
114                         try {
115                                 for(int j=1; j<params[i].length; ++j) { // first 3 taken up, see above
116                                         path = !params[i][j].contains("/")?dir+params[i][j]:params[i][j];
117                                         access.printf(Level.INIT, "Loading a TrustChain Member for %s from %s",name, path);
118                                         frs.add(new FileReader(path));
119                                 }
120                                 X509ChainWithIssuer xcwi = new X509ChainWithIssuer(frs);
121                                 addCaIssuerDN(xcwi.getIssuerDN());
122                                 mxcwi_s.put(params[i][0],xcwi);
123                         } finally {
124                                 for(FileReader fr : frs) {
125                                         if(fr!=null) {
126                                                 fr.close();
127                                         }
128                                 }
129                         }
130                 }               
131                 clients = new JscepClientLocator(access,urlstr.toString());
132         }
133
134         // package on purpose
135         
136         @Override
137         public X509ChainWithIssuer sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException {
138                 TimeTaken tt = trans.start("Generating CSR and Keys for New Certificate", Env.SUB);
139                 PKCS10CertificationRequest csr;
140                 try {
141                         csr = csrmeta.generateCSR(trans);
142                         if(trans.info().isLoggable()) {
143                                 trans.info().log(BCFactory.toString(csr));
144                         } 
145                         if(trans.info().isLoggable()) {
146                                 trans.info().log(csr);
147                         }
148                 } finally {
149                         tt.done();
150                 }
151                 
152                 tt = trans.start("Enroll CSR", Env.SUB);
153                 Client client = null;
154                 Item item = null;
155                 for(int i=0; i<MAX_RETRY;++i) {
156                         try {
157                                 item = clients.best();
158                                 client = clients.get(item);
159                                 
160                                 EnrollmentResponse er = client.enrol(
161                                                 csrmeta.initialConversationCert(trans),
162                                                 csrmeta.keypair(trans).getPrivate(),
163                                                 csr,
164                                                 MS_PROFILE /* profile... MS can't deal with blanks*/);
165                                 
166                                 while(true) {
167                                         if(er.isSuccess()) {
168                                                 trans.checkpoint("Cert from " + clients.info(item));
169                                                 X509Certificate x509 = null;
170                                                 for( Certificate cert : er.getCertStore().getCertificates(null)) {
171                                                         if(x509==null) {
172                                                                 x509 = (X509Certificate)cert;
173                                                                 break;
174                                                         }
175                                                 }
176                                                 X509ChainWithIssuer mxcwi = mxcwi_c.get(client);
177                                                 return new X509ChainWithIssuer(mxcwi,x509);
178 //                                              break;
179                                         } else if (er.isPending()) {
180                                                 trans.checkpoint("Polling, waiting on CA to complete");
181                                                 Thread.sleep(3000);
182                                         } else if (er.isFailure()) {
183 //                                              switch(er.getFailInfo()) {
184 //                                                      case badMessageCheck:
185 //                                                              throw new ClientException("Received BadMessageCheck from Jscep");
186 //                                                      case badAlg:
187 //                                                      case badCertId:
188 //                                                      case badRequest:
189 //                                                      case badTime:
190 //                                                      default:
191 //                                              }
192                                                 throw new CertException(clients.info(item)+':'+er.getFailInfo().toString());
193                                         }
194                                 }
195                                 //i=MAX_RETRY;
196                         } catch(LocatorException e) {
197                                 trans.error().log(e);
198                                 i=MAX_RETRY;
199                         } catch (ClientException e) {
200                                 trans.error().log(e,"SCEP Client Error, Temporarily Invalidating Client: " + clients.info(item));
201                                 try  { 
202                                         clients.invalidate(client);
203                                         if(!clients.hasItems()) {
204                                                 clients.refresh();
205                                         }
206                                 } catch (LocatorException e1) {
207                                         trans.error().log(e,clients.info(item));
208                                         i=MAX_RETRY;  // can't go any further
209                                 }
210                         } catch (InterruptedException|TransactionException|CertificateException|OperatorCreationException | CertStoreException e) {
211                                 trans.error().log(e);
212                                 i=MAX_RETRY;
213                         } finally {
214                                 tt.done();
215                         }
216                 }
217                 
218                 return null;
219         }
220         
221         /**
222          * Locator specifically for Jscep Clients.
223          * 
224          * Class based client for access to common Map
225          */
226         private class JscepClientLocator extends HotPeerLocator<Client> {
227
228                 protected JscepClientLocator(Access access, String urlstr)throws LocatorException {
229                         super(access, urlstr, JscepCA.INVALIDATE_TIME,
230                                 access.getProperty("cadi_latitude","39.833333"), //Note: Defaulting to GEO center of US
231                                 access.getProperty("cadi_longitude","-98.583333")
232                                 );
233                 }
234
235                 @Override
236                 protected Client _newClient(String urlinfo) throws LocatorException {
237                         try {
238                                 String[] info = Split.split('/', urlinfo);
239                                 Client c = new Client(new URL(JscepCA.CA_PREFIX + info[0] + JscepCA.CA_POSTFIX), 
240                                                 new CertificateVerifier() {
241                                                 @Override
242                                                 public boolean verify(X509Certificate cert) {
243                                                         //TODO checkIssuer
244                                                         return true;
245                                                 }
246                                         }
247                                 );
248                                 // Map URL to Client, because Client doesn't expose Connection
249                                 mxcwi_c.put(c,mxcwi_s.get(urlinfo));
250                                 return c;
251                         } catch (MalformedURLException e) {
252                                 throw new LocatorException(e);
253                         }
254                 }
255
256                 @Override
257                 protected Client _invalidate(Client client) {
258                         return null;
259                 }
260
261                 @Override
262                 protected void _destroy(Client client) {
263                         mxcwi_c.remove(client);
264                 }
265                 
266                 
267         }
268 }