Mass removal of all Tabs (Style Warnings)
[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.configure.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 static final String MS_PROFILE="1";
63     private static final int MAX_RETRY=3;
64     public static final long INVALIDATE_TIME = 1000*60*10L; // 10 mins
65
66     // package on purpose
67     private Map<String,X509ChainWithIssuer> mxcwiS;
68     private Map<Client,X509ChainWithIssuer> mxcwiC;
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          mxcwiS = new ConcurrentHashMap<>();
76          mxcwiC = new ConcurrentHashMap<>();
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<>(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                 mxcwiS.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 = mxcwiC.get(client);
177                         return new X509ChainWithIssuer(mxcwi,x509);
178
179                     } else if (er.isPending()) {
180                         trans.checkpoint("Polling, waiting on CA to complete");
181                         Thread.sleep(3000);
182                     } else if (er.isFailure()) {
183                         throw new CertException(clients.info(item)+':'+er.getFailInfo().toString());
184                     }
185                 }
186             } catch(LocatorException e) {
187                 trans.error().log(e);
188                 i=MAX_RETRY;
189             } catch (ClientException e) {
190                 trans.error().log(e,"SCEP Client Error, Temporarily Invalidating Client: " + clients.info(item));
191                 try  { 
192                     clients.invalidate(client);
193                     if(!clients.hasItems()) {
194                         clients.refresh();
195                     }
196                 } catch (LocatorException e1) {
197                     trans.error().log(e,clients.info(item));
198                     i=MAX_RETRY;  // can't go any further
199                 }
200             } catch (InterruptedException|TransactionException|CertificateException|OperatorCreationException | CertStoreException e) {
201                 trans.error().log(e);
202                 i=MAX_RETRY;
203             } finally {
204                 tt.done();
205             }
206         }
207         
208         return null;
209     }
210     
211     /**
212      * Locator specifically for Jscep Clients.
213      * 
214      * Class based client for access to common Map
215      */
216     private class JscepClientLocator extends HotPeerLocator<Client> {
217
218         protected JscepClientLocator(Access access, String urlstr)throws LocatorException {
219             super(access, urlstr, JscepCA.INVALIDATE_TIME,
220                  access.getProperty("cadi_latitude","39.833333"), //Note: Defaulting to GEO center of US
221                  access.getProperty("cadi_longitude","-98.583333")
222                  );
223         }
224
225         @Override
226         protected Client _newClient(String urlinfo) throws LocatorException {
227             try {
228                 String[] info = Split.split('/', urlinfo);
229                 Client c = new Client(new URL(JscepCA.CA_PREFIX + info[0] + JscepCA.CA_POSTFIX), 
230                         new CertificateVerifier() {
231                         @Override
232                         public boolean verify(X509Certificate cert) {
233                             //TODO checkIssuer
234                             return true;
235                         }
236                     }
237                 );
238                 // Map URL to Client, because Client doesn't expose Connection
239                 mxcwiC.put(c, mxcwiS.get(urlinfo));
240                 return c;
241             } catch (MalformedURLException e) {
242                 throw new LocatorException(e);
243             }
244         }
245
246         @Override
247         protected Client _invalidate(Client client) {
248             return null;
249         }
250
251         @Override
252         protected void _destroy(Client client) {
253             mxcwiC.remove(client);
254         }
255         
256         
257     }
258 }