KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > ui > web > pub > CertReqServlet


1 /*************************************************************************
2  * *
3  * EJBCA: The OpenSource Certificate Authority *
4  * *
5  * This software is free software; you can redistribute it and/or *
6  * modify it under the terms of the GNU Lesser General Public *
7  * License as published by the Free Software Foundation; either *
8  * version 2.1 of the License, or any later version. *
9  * *
10  * See terms of license at gnu.org. *
11  * *
12  *************************************************************************/

13  
14 package org.ejbca.ui.web.pub;
15
16 import java.io.ByteArrayOutputStream JavaDoc;
17 import java.io.File JavaDoc;
18 import java.io.FileInputStream JavaDoc;
19 import java.io.FileOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.OutputStream JavaDoc;
22 import java.io.PrintStream JavaDoc;
23 import java.security.GeneralSecurityException JavaDoc;
24 import java.security.KeyPair JavaDoc;
25 import java.security.KeyStore JavaDoc;
26 import java.security.PrivateKey JavaDoc;
27 import java.security.cert.Certificate JavaDoc;
28 import java.security.cert.X509Certificate JavaDoc;
29 import java.util.Enumeration JavaDoc;
30
31 import javax.ejb.EJBException JavaDoc;
32 import javax.ejb.ObjectNotFoundException JavaDoc;
33 import javax.naming.InitialContext JavaDoc;
34 import javax.rmi.PortableRemoteObject JavaDoc;
35 import javax.servlet.ServletConfig JavaDoc;
36 import javax.servlet.ServletException JavaDoc;
37 import javax.servlet.http.HttpServlet JavaDoc;
38 import javax.servlet.http.HttpServletRequest JavaDoc;
39 import javax.servlet.http.HttpServletResponse JavaDoc;
40
41 import org.apache.commons.lang.StringUtils;
42 import org.apache.log4j.Logger;
43 import org.ejbca.core.ejb.ServiceLocator;
44 import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionHome;
45 import org.ejbca.core.ejb.ca.auth.IAuthenticationSessionRemote;
46 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocal;
47 import org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocalHome;
48 import org.ejbca.core.ejb.ca.sign.ISignSessionLocal;
49 import org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome;
50 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionHome;
51 import org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionRemote;
52 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
53 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
54 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionHome;
55 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionRemote;
56 import org.ejbca.core.model.InternalResources;
57 import org.ejbca.core.model.SecConst;
58 import org.ejbca.core.model.ca.AuthLoginException;
59 import org.ejbca.core.model.ca.AuthStatusException;
60 import org.ejbca.core.model.ca.SignRequestException;
61 import org.ejbca.core.model.ca.SignRequestSignatureException;
62 import org.ejbca.core.model.ca.catoken.CATokenConstants;
63 import org.ejbca.core.model.keyrecovery.KeyRecoveryData;
64 import org.ejbca.core.model.log.Admin;
65 import org.ejbca.core.model.ra.UserDataConstants;
66 import org.ejbca.core.model.ra.UserDataVO;
67 import org.ejbca.core.model.ra.raadmin.EndEntityProfile;
68 import org.ejbca.ui.web.RequestHelper;
69 import org.ejbca.util.Base64;
70 import org.ejbca.util.CertTools;
71 import org.ejbca.util.KeyTools;
72
73
74
75
76 /**
77  * Servlet used to install a private key with a corresponding certificate in a browser. A new
78  * certificate is installed in the browser in following steps:<br>
79  * 1. The key pair is generated by the browser. <br>
80  * 2. The public part is sent to the servlet in a POST together with user info ("pkcs10|keygen",
81  * "inst", "user", "password"). For internet explorer the public key is sent as a PKCS10
82  * certificate request. <br>
83  * 3. The new certificate is created by calling the RSASignSession session bean. <br>
84  * 4. A page containing the new certificate and a script that installs it is returned to the
85  * browser. <br>
86  *
87  * <p></p>
88  *
89  * <p>
90  * The following initiation parameters are needed by this servlet: <br>
91  * "responseTemplate" file that defines the response to the user (IE). It should have one line
92  * with the text "cert =". This line is replaced with the new certificate. "keyStorePass".
93  * Password needed to load the key-store. If this parameter is none existing it is assumed that no
94  * password is needed. The path could be absolute or relative.<br>
95  * </p>
96  *
97  * @author Original code by Lars Silv?n
98  * @version $Id: CertReqServlet.java,v 1.15.2.2 2007/07/02 15:28:28 jeklund Exp $
99  */

100 public class CertReqServlet extends HttpServlet JavaDoc {
101     private static final Logger log = Logger.getLogger(CertReqServlet.class);
102     /** Internal localization of logs and errors */
103     private static final InternalResources intres = InternalResources.getInstance();
104
105     private byte[] bagattributes = "Bag Attributes\n".getBytes();
106     private byte[] friendlyname = " friendlyName: ".getBytes();
107     private byte[] subject = "subject=/".getBytes();
108     private byte[] issuer = "issuer=/".getBytes();
109     private byte[] beginCertificate = "-----BEGIN CERTIFICATE-----".getBytes();
110     private byte[] endCertificate = "-----END CERTIFICATE-----".getBytes();
111     private byte[] beginPrivateKey = "-----BEGIN PRIVATE KEY-----".getBytes();
112     private byte[] endPrivateKey = "-----END PRIVATE KEY-----".getBytes();
113     private byte[] NL = "\n".getBytes();
114
115     private IUserAdminSessionHome useradminhome = null;
116     private IRaAdminSessionHome raadminhome = null;
117     private IKeyRecoverySessionHome keyrecoveryhome = null;
118     private IAuthenticationSessionHome authhome = null;
119
120     private ISignSessionLocal signsession = null;
121     private ICAAdminSessionLocal casession = null;
122
123     private synchronized ISignSessionLocal getSignSession(){
124         if(signsession == null){
125             try {
126                 ISignSessionLocalHome signhome = (ISignSessionLocalHome)ServiceLocator.getInstance().getLocalHome(ISignSessionLocalHome.COMP_NAME);
127                 signsession = signhome.create();
128             }catch(Exception JavaDoc e){
129                 throw new EJBException JavaDoc(e);
130             }
131         }
132         return signsession;
133     }
134     private synchronized ICAAdminSessionLocal getCASession(){
135         if(casession == null){
136             try {
137                 ICAAdminSessionLocalHome cahome = (ICAAdminSessionLocalHome)ServiceLocator.getInstance().getLocalHome(ICAAdminSessionLocalHome.COMP_NAME);
138                 casession = cahome.create();
139             }catch(Exception JavaDoc e){
140                 throw new EJBException JavaDoc(e);
141             }
142         }
143         return casession;
144     }
145     /**
146      * Servlet init
147      *
148      * @param config servlet configuration
149      *
150      * @throws ServletException on error
151      */

152     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
153         super.init(config);
154
155         try {
156             // Install BouncyCastle provider
157
CertTools.installBCProvider();
158
159             // Get EJB context and home interfaces
160
InitialContext JavaDoc ctx = new InitialContext JavaDoc();
161             useradminhome = (IUserAdminSessionHome) PortableRemoteObject.narrow(
162                              ctx.lookup("UserAdminSession"), IUserAdminSessionHome.class );
163             raadminhome = (IRaAdminSessionHome) PortableRemoteObject.narrow(
164                              ctx.lookup("RaAdminSession"), IRaAdminSessionHome.class );
165             keyrecoveryhome = (IKeyRecoverySessionHome) PortableRemoteObject.narrow(
166                              ctx.lookup("KeyRecoverySession"), IKeyRecoverySessionHome.class );
167             
168             authhome = (IAuthenticationSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("AuthenticationSession"), IAuthenticationSessionHome.class);
169         } catch( Exception JavaDoc e ) {
170             throw new ServletException JavaDoc(e);
171         }
172     }
173
174     /**
175      * Handles HTTP POST
176      *
177      * @param request servlet request
178      * @param response servlet response
179      *
180      * @throws IOException input/output error
181      * @throws ServletException on error
182      */

183     public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
184         throws IOException JavaDoc, ServletException JavaDoc {
185         ServletDebug debug = new ServletDebug(request, response);
186         boolean usekeyrecovery = false;
187
188         RequestHelper.setDefaultCharacterEncoding(request);
189         try {
190             String JavaDoc username = request.getParameter("user");
191             String JavaDoc password = request.getParameter("password");
192             String JavaDoc keylengthstring = request.getParameter("keylength");
193             String JavaDoc keyalgstring = request.getParameter("keyalg");
194             String JavaDoc openvpn = request.getParameter("openvpn");
195             String JavaDoc keylength = "1024";
196             String JavaDoc keyalg = CATokenConstants.KEYALGORITHM_RSA;
197             
198             int resulttype = 0;
199             if(request.getParameter("resulttype") != null)
200               resulttype = Integer.parseInt(request.getParameter("resulttype")); // Indicates if certificate or PKCS7 should be returned on manual PKCS10 request.
201

202
203             String JavaDoc classid = "clsid:127698e4-e730-4e5c-a2b1-21490a70c8a1\" CODEBASE=\"/CertControl/xenroll.cab#Version=5,131,3659,0";
204
205             if ((request.getParameter("classid") != null) &&
206                     !request.getParameter("classid").equals("")) {
207                 classid = request.getParameter("classid");
208             }
209
210             if (keylengthstring != null) {
211                 keylength = keylengthstring;
212             }
213             if (keyalgstring != null) {
214                 keyalg = keyalgstring;
215             }
216
217             Admin administrator = new Admin(Admin.TYPE_PUBLIC_WEB_USER, request.getRemoteAddr());
218
219             IUserAdminSessionRemote adminsession = useradminhome.create();
220             IRaAdminSessionRemote raadminsession = raadminhome.create();
221             ISignSessionLocal signsession = getSignSession();
222             RequestHelper helper = new RequestHelper(administrator, debug);
223
224             String JavaDoc iMsg = intres.getLocalizedMessage("certreq.receivedcertreq", username, request.getRemoteAddr());
225             log.info(iMsg);
226             debug.print("<h3>username: " + username + "</h3>");
227
228             // Check user
229
int tokentype = SecConst.TOKEN_SOFT_BROWSERGEN;
230
231             usekeyrecovery = (raadminsession.loadGlobalConfiguration(administrator)).getEnableKeyRecovery();
232
233             UserDataVO data = adminsession.findUser(administrator, username);
234
235             if (data == null) {
236                 throw new ObjectNotFoundException JavaDoc();
237             }
238
239             boolean savekeys = data.getKeyRecoverable() && usekeyrecovery && (data.getStatus() != UserDataConstants.STATUS_KEYRECOVERY);
240             boolean loadkeys = (data.getStatus() == UserDataConstants.STATUS_KEYRECOVERY) &&
241                 usekeyrecovery;
242
243             // get users Token Type.
244
tokentype = data.getTokenType();
245             if(tokentype == SecConst.TOKEN_SOFT_P12){
246               KeyStore JavaDoc ks = generateToken(administrator, username, password, data.getCAId(), keylength, keyalg, false, loadkeys, savekeys, data.getEndEntityProfileId());
247               if (StringUtils.equals(openvpn, "on")) {
248                   sendOpenVPNToken(ks, username, password, response);
249               } else {
250                   sendP12Token(ks, username, password, response);
251               }
252             }
253             if(tokentype == SecConst.TOKEN_SOFT_JKS){
254               KeyStore JavaDoc ks = generateToken(administrator, username, password, data.getCAId(), keylength, keyalg, true, loadkeys, savekeys, data.getEndEntityProfileId());
255               sendJKSToken(ks, username, password, response);
256             }
257             if(tokentype == SecConst.TOKEN_SOFT_PEM){
258               KeyStore JavaDoc ks = generateToken(administrator, username, password, data.getCAId(), keylength, keyalg, false, loadkeys, savekeys, data.getEndEntityProfileId());
259               sendPEMTokens(ks, username, password, response);
260             }
261             if(tokentype == SecConst.TOKEN_SOFT_BROWSERGEN){
262
263               // first check if it is a netcsape request,
264
if (request.getParameter("keygen") != null) {
265                   byte[] reqBytes=request.getParameter("keygen").getBytes();
266                   log.debug("Received NS request:"+new String JavaDoc(reqBytes));
267                   if (reqBytes != null) {
268                       byte[] certs = helper.nsCertRequest(signsession, reqBytes, username, password);
269                       RequestHelper.sendNewCertToNSClient(certs, response);
270                   }
271               } else if ( request.getParameter("iidPkcs10") != null && !request.getParameter("iidPkcs10").equals("") ) {
272                   // NetID iid?
273
byte[] reqBytes=request.getParameter("iidPkcs10").getBytes();
274                   if (reqBytes != null) {
275                       byte[] b64cert=helper.pkcs10CertRequest(signsession, reqBytes, username, password, RequestHelper.ENCODED_CERTIFICATE, false);
276                       RequestHelper.sendNewCertToIidClient(b64cert, response.getOutputStream(), getServletContext(), getInitParameter("responseIidTemplate"),classid);
277                   }
278               } else if ( (request.getParameter("pkcs10") != null) || (request.getParameter("PKCS10") != null) ) {
279                   // if not netscape, check if it's IE
280
byte[] reqBytes=request.getParameter("pkcs10").getBytes();
281                   if (reqBytes == null)
282                       reqBytes=request.getParameter("PKCS10").getBytes();
283                   log.debug("Received IE request:"+new String JavaDoc(reqBytes));
284                   if (reqBytes != null) {
285                       byte[] b64cert=helper.pkcs10CertRequest(signsession, reqBytes, username, password, RequestHelper.ENCODED_PKCS7);
286                       debug.ieCertFix(b64cert);
287                       RequestHelper.sendNewCertToIEClient(b64cert, response.getOutputStream(), getServletContext(), getInitParameter("responseTemplate"),classid);
288                   }
289               } else if (request.getParameter("pkcs10req") != null && resulttype != 0) {
290                   // if not IE, check if it's manual request
291
byte[] reqBytes=request.getParameter("pkcs10req").getBytes();
292                   if (reqBytes != null) {
293                       byte[] b64cert=helper.pkcs10CertRequest(signsession, reqBytes, username, password, resulttype);
294                       if(resulttype == RequestHelper.ENCODED_PKCS7)
295                         RequestHelper.sendNewB64Cert(b64cert, response, RequestHelper.BEGIN_PKCS7_WITH_NL, RequestHelper.END_PKCS7_WITH_NL);
296                       if(resulttype == RequestHelper.ENCODED_CERTIFICATE)
297                         RequestHelper.sendNewB64Cert(b64cert, response, RequestHelper.BEGIN_CERTIFICATE_WITH_NL, RequestHelper.END_CERTIFICATE_WITH_NL);
298                   }
299               }
300             }
301         } catch (ObjectNotFoundException JavaDoc oe) {
302             log.debug("Non existent username!");
303             debug.printMessage("Non existent username!");
304             debug.printMessage(
305                 "To generate a certificate a valid username and password must be entered.");
306             debug.printDebugInfo();
307             return;
308         } catch (AuthStatusException ase) {
309             log.debug("Wrong user status!");
310             debug.printMessage("Wrong user status!");
311             if (usekeyrecovery) {
312                 debug.printMessage(
313                     "To generate a certificate for a user the user must have status new, failed or inprocess.");
314             } else {
315                 debug.printMessage(
316                     "To generate a certificate for a user the user must have status new, failed or inprocess.");
317             }
318             debug.printDebugInfo();
319             return;
320         } catch (AuthLoginException ale) {
321             log.debug("Wrong password for user!");
322             debug.printMessage("Wrong username or password!");
323             debug.printMessage(
324                 "To generate a certificate a valid username and password must be entered.");
325             debug.printDebugInfo();
326             return;
327         } catch (SignRequestException re) {
328             log.debug("Invalid request!");
329             debug.printMessage("Invalid request!");
330             debug.printMessage("Please supply a correct request.");
331             debug.printDebugInfo();
332             return;
333         } catch (SignRequestSignatureException se) {
334             log.error("Invalid signature on certificate request:", se);
335             debug.printMessage("Invalid signature on certificate request!");
336             debug.printMessage("Please supply a correctly signed request.");
337             debug.printDebugInfo();
338             return;
339         } catch (java.lang.ArrayIndexOutOfBoundsException JavaDoc ae) {
340             log.debug("Empty or invalid request received.");
341             debug.printMessage("Empty or invalid request!");
342             debug.printMessage("Please supply a correct request.");
343             debug.printDebugInfo();
344             return;
345         } catch (org.ejbca.core.model.ca.IllegalKeyException e) {
346             log.debug("Illegal Key received: "+e.getMessage());
347             debug.printMessage("Invalid Key in request: "+e.getMessage());
348             debug.printMessage("Please supply a correct request.");
349             debug.printDebugInfo();
350             return;
351         } catch (Exception JavaDoc e) {
352             log.debug(e);
353             debug.print("<h3>parameter name and values: </h3>");
354             Enumeration JavaDoc paramNames = request.getParameterNames();
355             while (paramNames.hasMoreElements()) {
356                 String JavaDoc name = paramNames.nextElement().toString();
357                 String JavaDoc parameter = request.getParameter(name);
358                 debug.print("<h4>" + name + ":</h4>" + parameter + "<br>");
359             }
360             debug.takeCareOfException(e);
361             debug.printDebugInfo();
362         }
363     }
364
365     //doPost
366

367     /**
368      * Handles HTTP GET
369      *
370      * @param request servlet request
371      * @param response servlet response
372      *
373      * @throws IOException input/output error
374      * @throws ServletException on error
375      */

376     public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
377         throws IOException JavaDoc, ServletException JavaDoc {
378         log.debug(">doGet()");
379         response.setHeader("Allow", "POST");
380
381         ServletDebug debug = new ServletDebug(request, response);
382         debug.print("The certificate request servlet only handles POST method.");
383         debug.printDebugInfo();
384         log.debug("<doGet()");
385     }
386
387     // doGet
388
/**
389      * method to create an install package for OpenVPN including keys and send to user.
390      * Contributed by: Jon Bendtsen, jon.bendtsen(at)laerdal.dk
391      */

392     private void sendOpenVPNToken(KeyStore JavaDoc ks, String JavaDoc username, String JavaDoc kspassword, HttpServletResponse JavaDoc out) throws Exception JavaDoc {
393         ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
394         ks.store(buffer, kspassword.toCharArray());
395         
396         File JavaDoc fout = new File JavaDoc("/usr/local/tmp/" + username + ".p12");
397         FileOutputStream JavaDoc certfile = new FileOutputStream JavaDoc(fout);
398         
399         Enumeration JavaDoc en = ks.aliases();
400         String JavaDoc alias = (String JavaDoc)en.nextElement();
401         // Then get the certificates
402
Certificate JavaDoc[] certs = KeyTools.getCertChain(ks, alias);
403         // The first one (certs[0]) is the users cert and the last
404
// one (certs [certs.lenght-1]) is the CA-cert
405
X509Certificate JavaDoc x509cert = (X509Certificate JavaDoc) certs[0];
406         String JavaDoc IssuerDN = x509cert.getIssuerDN().toString();
407         String JavaDoc SubjectDN = x509cert.getSubjectDN().toString();
408         
409         // export the users certificate to file
410
buffer.writeTo(certfile);
411         buffer.flush();
412         buffer.close();
413         certfile.close();
414         
415         // run shell script, which will also remove the created files
416
// parameters are the username, IssuerDN and SubjectDN
417
// IssuerDN and SubjectDN will be used to select the right
418
// openvpn configuration file
419
// they have to be written to stdin of the script to support
420
// spaces in the username, IssuerDN or SubjectDN
421
Runtime JavaDoc rt = Runtime.getRuntime();
422         if (rt==null) {
423             log.error("getRuntime failed. null pointer");
424         } else {
425             Process JavaDoc p = rt.exec("/usr/local/ejbca/bin/mk_openvpn_" + "windows_installer.sh");
426             if (p==null) {
427                 log.error("execution of openvpn windows" + " installer script failed. Null pointer");
428             } else {
429                 OutputStream JavaDoc pstdin = p.getOutputStream();
430                 PrintStream JavaDoc stdoutp = new PrintStream JavaDoc(pstdin);
431                 stdoutp.println(username);
432                 stdoutp.println(IssuerDN);
433                 stdoutp.println(SubjectDN);
434                 stdoutp.flush();
435                 stdoutp.close();
436                 pstdin.close();
437                 int exitVal = p.waitFor();
438                 if (exitVal != 0) {
439                     log.error("Openvpn windows installer script exitValue: " + exitVal);
440                 } else {
441                     log.debug("Openvpn windows installer script exitValue: " + exitVal);
442                 }
443             }
444         }
445         
446         // we ought to check if the script was okay or not, but in a little
447
// while we will look for the openvpn-gui-install-$username.exe
448
// and fail there if the script failed. Also, one could question
449
// what to do if it did fail, serve the user the certificate?
450

451         // sending the OpenVPN windows installer
452
String JavaDoc filename = "openvpn-gui-install-" + username + ".exe";
453         File JavaDoc fin = new File JavaDoc("/usr/local/tmp/" + filename);
454         FileInputStream JavaDoc vpnfile = new FileInputStream JavaDoc(fin);
455         
456         out.setContentType("application/x-msdos-program");
457         out.setHeader("Content-disposition", "filename=" + filename);
458         out.setContentLength( new Long JavaDoc(fin.length()).intValue() );
459         OutputStream JavaDoc os = out.getOutputStream();
460         byte[] buf = new byte[4096];
461         int offset = 0;
462         int bytes = 0;
463         while ( (bytes=vpnfile.read(buf)) != -1 ) {
464             os.write(buf,0,bytes);
465             offset += bytes;
466         }
467         vpnfile.close();
468         // delete OpenVPN windows installer, the script will delete cert.
469
fin.delete();
470         out.flushBuffer();
471     } // sendOpenVPNToken
472

473     private void sendP12Token(KeyStore JavaDoc ks, String JavaDoc username, String JavaDoc kspassword,
474         HttpServletResponse JavaDoc out) throws Exception JavaDoc {
475         ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
476         ks.store(buffer, kspassword.toCharArray());
477
478         out.setContentType("application/x-pkcs12");
479         out.setHeader("Content-disposition", "filename=" + username + ".p12");
480         out.setContentLength(buffer.size());
481         buffer.writeTo(out.getOutputStream());
482         out.flushBuffer();
483         buffer.close();
484     }
485
486     private void sendJKSToken(KeyStore JavaDoc ks, String JavaDoc username, String JavaDoc kspassword,
487         HttpServletResponse JavaDoc out) throws Exception JavaDoc {
488         ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
489         ks.store(buffer, kspassword.toCharArray());
490
491         out.setContentType("application/octet-stream");
492         out.setHeader("Content-disposition", "filename=" + username + ".jks");
493         out.setContentLength(buffer.size());
494         buffer.writeTo(out.getOutputStream());
495         out.flushBuffer();
496         buffer.close();
497     }
498
499     private void sendPEMTokens(KeyStore JavaDoc ks, String JavaDoc username, String JavaDoc kspassword,
500         HttpServletResponse JavaDoc out) throws Exception JavaDoc {
501         ByteArrayOutputStream JavaDoc buffer = new ByteArrayOutputStream JavaDoc();
502         String JavaDoc alias = "";
503
504         // Find the key private key entry in the keystore
505
Enumeration JavaDoc e = ks.aliases();
506         Object JavaDoc o = null;
507         PrivateKey JavaDoc serverPrivKey = null;
508
509         while (e.hasMoreElements()) {
510             o = e.nextElement();
511
512             if (o instanceof String JavaDoc) {
513                 if ((ks.isKeyEntry((String JavaDoc) o)) &&
514                         ((serverPrivKey = (PrivateKey JavaDoc) ks.getKey((String JavaDoc) o,
515                                 kspassword.toCharArray())) != null)) {
516                     alias = (String JavaDoc) o;
517
518                     break;
519                 }
520             }
521         }
522
523         byte[] privKeyEncoded = "".getBytes();
524
525         if (serverPrivKey != null) {
526             privKeyEncoded = serverPrivKey.getEncoded();
527         }
528
529         //Certificate chain[] = ks.getCertificateChain((String) o);
530
Certificate JavaDoc[] chain = KeyTools.getCertChain(ks, (String JavaDoc) o);
531         X509Certificate JavaDoc userX509Certificate = (X509Certificate JavaDoc) chain[0];
532
533         byte[] output = userX509Certificate.getEncoded();
534         String JavaDoc sn = CertTools.getSubjectDN(userX509Certificate);
535
536         String JavaDoc subjectdnpem = sn.replace(',', '/');
537         String JavaDoc issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/');
538
539         buffer.write(bagattributes);
540         buffer.write(friendlyname);
541         buffer.write(alias.getBytes());
542         buffer.write(NL);
543         buffer.write(beginPrivateKey);
544         buffer.write(NL);
545
546         byte[] privKey = Base64.encode(privKeyEncoded);
547         buffer.write(privKey);
548         buffer.write(NL);
549         buffer.write(endPrivateKey);
550         buffer.write(NL);
551         buffer.write(bagattributes);
552         buffer.write(friendlyname);
553         buffer.write(alias.getBytes());
554         buffer.write(NL);
555         buffer.write(subject);
556         buffer.write(subjectdnpem.getBytes());
557         buffer.write(NL);
558         buffer.write(issuer);
559         buffer.write(issuerdnpem.getBytes());
560         buffer.write(NL);
561         buffer.write(beginCertificate);
562         buffer.write(NL);
563
564         byte[] userCertB64 = Base64.encode(output);
565         buffer.write(userCertB64);
566         buffer.write(NL);
567         buffer.write(endCertificate);
568         buffer.write(NL);
569
570         if (CertTools.isSelfSigned(userX509Certificate)) {
571         } else {
572             for (int num = 1; num < chain.length; num++) {
573                 X509Certificate JavaDoc tmpX509Cert = (X509Certificate JavaDoc) chain[num];
574                 sn = CertTools.getSubjectDN(tmpX509Cert);
575
576                 String JavaDoc cn = CertTools.getPartFromDN(sn, "CN");
577                 if (StringUtils.isEmpty(cn)) {
578                     cn="Unknown";
579                 }
580
581                 subjectdnpem = sn.replace(',', '/');
582                 issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/');
583
584                 buffer.write(bagattributes);
585                 buffer.write(friendlyname);
586                 buffer.write(cn.getBytes());
587                 buffer.write(NL);
588                 buffer.write(subject);
589                 buffer.write(subjectdnpem.getBytes());
590                 buffer.write(NL);
591                 buffer.write(issuer);
592                 buffer.write(issuerdnpem.getBytes());
593                 buffer.write(NL);
594
595                 byte[] tmpOutput = tmpX509Cert.getEncoded();
596                 buffer.write(beginCertificate);
597                 buffer.write(NL);
598
599                 byte[] tmpCACertB64 = Base64.encode(tmpOutput);
600                 buffer.write(tmpCACertB64);
601                 buffer.write(NL);
602                 buffer.write(endCertificate);
603                 buffer.write(NL);
604             }
605         }
606
607         out.setContentType("application/octet-stream");
608         out.setHeader("Content-disposition", " attachment; filename=" + username + ".pem");
609         buffer.writeTo(out.getOutputStream());
610         out.flushBuffer();
611         buffer.close();
612     }
613
614
615     private KeyStore JavaDoc generateToken(Admin administrator, String JavaDoc username, String JavaDoc password, int caid, String JavaDoc keylength, String JavaDoc keyalg, boolean createJKS,
616                                    boolean loadkeys, boolean savekeys, int endEntityProfileId)
617        throws Exception JavaDoc{
618         
619         
620          KeyRecoveryData keyData = null;
621          KeyPair JavaDoc rsaKeys = null;
622          boolean reusecertificate = false;
623          if(loadkeys){
624              
625            IRaAdminSessionRemote raadminsession = raadminhome.create();
626            EndEntityProfile endEntityProfile = raadminsession.getEndEntityProfile(administrator, endEntityProfileId);
627            reusecertificate = endEntityProfile.getReUseKeyRevoceredCertificate();
628              
629            // used saved keys.
630
IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome.create();
631            keyData = keyrecoverysession.keyRecovery(administrator, username, endEntityProfileId);
632            rsaKeys = keyData.getKeyPair();
633            
634            if(reusecertificate){
635                keyrecoverysession.unmarkUser(administrator,username);
636            }
637          }
638          else{
639            // generate new keys.
640
rsaKeys = KeyTools.genKeys(keylength, keyalg);
641          }
642          
643          ISignSessionLocal signsession = getSignSession();
644          X509Certificate JavaDoc cert = null;
645          if(reusecertificate){
646              cert = (X509Certificate JavaDoc) keyData.getCertificate();
647              ICAAdminSessionLocal caadminsession = getCASession();
648              boolean finishUser = caadminsession.getCAInfo(administrator,caid).getFinishUser();
649              if(finishUser){
650               IAuthenticationSessionRemote authsession = authhome.create();
651               authsession.finishUser(administrator, username, password);
652              }
653              
654          }else{
655              cert = (X509Certificate JavaDoc)signsession.createCertificate(administrator, username, password, rsaKeys.getPublic());
656          }
657
658         // Make a certificate chain from the certificate and the CA-certificate
659
Certificate JavaDoc[] cachain = (Certificate JavaDoc[]) signsession.getCertificateChain(administrator, caid).toArray(new Certificate JavaDoc[0]);
660
661         // Verify CA-certificate
662
if (CertTools.isSelfSigned((X509Certificate JavaDoc) cachain[cachain.length - 1])) {
663             try {
664                 cachain[cachain.length - 1].verify(cachain[cachain.length - 1].getPublicKey());
665             } catch (GeneralSecurityException JavaDoc se) {
666                 throw new Exception JavaDoc("RootCA certificate does not verify");
667             }
668         } else {
669             throw new Exception JavaDoc("RootCA certificate not self-signed");
670         }
671
672         // Verify that the user-certificate is signed by our CA
673
try {
674             cert.verify(cachain[0].getPublicKey());
675         } catch (GeneralSecurityException JavaDoc se) {
676             throw new Exception JavaDoc("Generated certificate does not verify using CA-certificate.");
677         }
678
679         if (savekeys) {
680             // Save generated keys to database.
681
IKeyRecoverySessionRemote keyrecoverysession = keyrecoveryhome.create();
682             keyrecoverysession.addKeyRecoveryData(administrator, cert, username, rsaKeys);
683         }
684
685         // Use CN if as alias in the keystore, if CN is not present use username
686
String JavaDoc alias = CertTools.getPartFromDN(CertTools.getSubjectDN(cert), "CN");
687         if (alias == null) alias = username;
688
689         // Store keys and certificates in keystore.
690
KeyStore JavaDoc ks = null;
691
692         if (createJKS) {
693             ks = KeyTools.createJKS(alias, rsaKeys.getPrivate(), password, cert, cachain);
694         } else {
695             ks = KeyTools.createP12(alias, rsaKeys.getPrivate(), cert, cachain);
696         }
697
698         return ks;
699     }
700 }
701
702
703 // CertReqServlet
704
Popular Tags