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