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