Merge "Fixed sonar issue in JscepCA"
[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  * Modifications Copyright (C) 2018 IBM.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END====================================================
21  *
22  */
23 package org.onap.aaf.auth.cm.ca;
24
25 import java.io.FileReader;
26 import java.io.IOException;
27 import java.net.Authenticator;
28 import java.net.MalformedURLException;
29 import java.net.PasswordAuthentication;
30 import java.net.URL;
31 import java.security.cert.Certificate;
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
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.onap.aaf.auth.cm.cert.BCFactory;
45 import org.onap.aaf.auth.cm.cert.CSRMeta;
46 import org.onap.aaf.cadi.Access;
47 import org.onap.aaf.cadi.LocatorException;
48 import org.onap.aaf.cadi.Access.Level;
49 import org.onap.aaf.cadi.Locator.Item;
50 import org.onap.aaf.cadi.configure.CertException;
51 import org.onap.aaf.cadi.locator.HotPeerLocator;
52 import org.onap.aaf.misc.env.Env;
53 import org.onap.aaf.misc.env.TimeTaken;
54 import org.onap.aaf.misc.env.Trans;
55 import org.onap.aaf.misc.env.util.Split;
56
57 public class JscepCA extends CA {
58     static final String CA_PREFIX = "http://";
59     static final String CA_POSTFIX="/certsrv/mscep_admin/mscep.dll";
60
61     private static final String MS_PROFILE="1";
62     private static final int MAX_RETRY=3;
63     public static final long INVALIDATE_TIME = 1000*60*10L; // 10 mins
64
65     // package on purpose
66     private Map<String,X509ChainWithIssuer> mxcwiS;
67     private Map<Client,X509ChainWithIssuer> mxcwiC;
68
69
70     private JscepClientLocator clients;
71
72     public JscepCA(final Access access, final String name, final String env, String [][] params) throws IOException, CertException, LocatorException {
73          super(access, name, env);
74          mxcwiS = new ConcurrentHashMap<>();
75          mxcwiC = new ConcurrentHashMap<>();
76          
77          if (params.length<2) {
78              throw new CertException("No Trust Chain parameters are included");
79          } 
80          if (params[0].length<2) {
81              throw new CertException("User/Password required for JSCEP");
82          }
83          final String id = params[0][0];
84          final String pw = params[0][1]; 
85         
86         // Set this for NTLM password Microsoft
87         Authenticator.setDefault(new Authenticator() {
88               public PasswordAuthentication getPasswordAuthentication () {
89                     try {
90                         return new PasswordAuthentication (id,access.decrypt(pw,true).toCharArray());
91                     } catch (IOException e) {
92                         access.log(e);
93                     }
94                     return null;
95               }
96         });
97         
98         StringBuilder urlstr = new StringBuilder();
99
100         for (int i=1;i<params.length;++i) { // skip first section, which is user/pass
101             // Work 
102             if (i>1) {
103                 urlstr.append(','); // delimiter
104             }
105             urlstr.append(params[i][0]);
106             
107             String dir = access.getProperty(CM_PUBLIC_DIR, "");
108             if (!"".equals(dir) && !dir.endsWith("/")) {
109                 dir = dir + '/';
110             }
111             String path;
112             List<FileReader> frs = new ArrayList<>(params.length-1);
113             try {
114                 for (int j=1; j<params[i].length; ++j) { // first 3 taken up, see above
115                     path = !params[i][j].contains("/")?dir+params[i][j]:params[i][j];
116                     access.printf(Level.INIT, "Loading a TrustChain Member for %s from %s",name, path);
117                     frs.add(new FileReader(path));
118                 }
119                 X509ChainWithIssuer xcwi = new X509ChainWithIssuer(frs);
120                 addCaIssuerDN(xcwi.getIssuerDN());
121                 mxcwiS.put(params[i][0],xcwi);
122             } finally {
123                 for (FileReader fr : frs) {
124                     if (fr!=null) {
125                         fr.close();
126                     }
127                 }
128             }
129         }        
130         clients = new JscepClientLocator(access,urlstr.toString());
131     }
132
133     // package on purpose
134     
135     @Override
136     public X509ChainWithIssuer sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException {
137         TimeTaken tt = trans.start("Generating CSR and Keys for New Certificate", Env.SUB);
138         PKCS10CertificationRequest csr;
139         try {
140             csr = csrmeta.generateCSR(trans);
141             if (trans.info().isLoggable()) {
142                 trans.info().log(BCFactory.toString(csr));
143             } 
144             if (trans.info().isLoggable()) {
145                 trans.info().log(csr);
146             }
147         } finally {
148             tt.done();
149         }
150         
151         tt = trans.start("Enroll CSR", Env.SUB);
152         Client client = null;
153         Item item = null;
154         for (int i=0; i<MAX_RETRY;++i) {
155             try {
156                 item = clients.best();
157                 client = clients.get(item);
158                 
159                 EnrollmentResponse er = client.enrol(
160                         csrmeta.initialConversationCert(trans),
161                         csrmeta.keypair(trans).getPrivate(),
162                         csr,
163                         MS_PROFILE /* profile... MS can't deal with blanks*/);
164                 
165                 while (true) {
166                     if (er.isSuccess()) {
167                         trans.checkpoint("Cert from " + clients.info(item));
168                         X509Certificate x509 = null;
169                         for ( Certificate cert : er.getCertStore().getCertificates(null)) {
170                             if (x509==null) {
171                                 x509 = (X509Certificate)cert;
172                                 break;
173                             }
174                         }
175                         X509ChainWithIssuer mxcwi = mxcwiC.get(client);
176                         return new X509ChainWithIssuer(mxcwi,x509);
177
178                     } else if (er.isPending()) {
179                         trans.checkpoint("Polling, waiting on CA to complete");
180                         Thread.sleep(3000);
181                     } else if (er.isFailure()) {
182                         throw new CertException(clients.info(item)+':'+er.getFailInfo().toString());
183                     }
184                 }
185             } catch (LocatorException e) {
186                 trans.error().log(e);
187                 i=MAX_RETRY;
188             } catch (ClientException e) {
189                 trans.error().log(e,"SCEP Client Error, Temporarily Invalidating Client: " + clients.info(item));
190                 try  { 
191                     clients.invalidate(client);
192                     if (!clients.hasItems()) {
193                         clients.refresh();
194                     }
195                 } catch (LocatorException e1) {
196                     trans.error().log(e,clients.info(item));
197                     i=MAX_RETRY;  // can't go any further
198                 }
199             } catch (Exception e) {
200                 trans.error().log(e);
201                 i=MAX_RETRY;
202             } finally {
203                 tt.done();
204             }
205         }
206         
207         return null;
208     }
209     
210     /**
211      * Locator specifically for Jscep Clients.
212      * 
213      * Class based client for access to common Map
214      */
215     private class JscepClientLocator extends HotPeerLocator<Client> {
216
217         protected JscepClientLocator(Access access, String urlstr)throws LocatorException {
218             super(access, urlstr, JscepCA.INVALIDATE_TIME,
219                  access.getProperty("cadi_latitude","39.833333"), //Note: Defaulting to GEO center of US
220                  access.getProperty("cadi_longitude","-98.583333")
221                  );
222         }
223
224         @Override
225         protected Client _newClient(String urlinfo) throws LocatorException {
226             try {
227                 String[] info = Split.split('/', urlinfo);
228                 Client c = new Client(new URL(JscepCA.CA_PREFIX + info[0] + JscepCA.CA_POSTFIX), 
229                         new CertificateVerifier() {
230                         @Override
231                         public boolean verify(X509Certificate cert) {
232                             //TODO checkIssuer
233                             return true;
234                         }
235                     }
236                 );
237                 // Map URL to Client, because Client doesn't expose Connection
238                 mxcwiC.put(c, mxcwiS.get(urlinfo));
239                 return c;
240             } catch (MalformedURLException e) {
241                 throw new LocatorException(e);
242             }
243         }
244
245         @Override
246         protected Client _invalidate(Client client) {
247             return null;
248         }
249
250         @Override
251         protected void _destroy(Client client) {
252             mxcwiC.remove(client);
253         }
254         
255         
256     }
257 }