KickJava   Java API By Example, From Geeks To Geeks.

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


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.IOException JavaDoc;
17 import java.util.Date JavaDoc;
18 import java.util.Enumeration JavaDoc;
19
20 import javax.ejb.CreateException JavaDoc;
21 import javax.ejb.EJBException JavaDoc;
22 import javax.ejb.ObjectNotFoundException JavaDoc;
23 import javax.naming.InitialContext JavaDoc;
24 import javax.servlet.ServletConfig JavaDoc;
25 import javax.servlet.ServletException JavaDoc;
26 import javax.servlet.http.HttpServlet JavaDoc;
27 import javax.servlet.http.HttpServletRequest JavaDoc;
28 import javax.servlet.http.HttpServletResponse JavaDoc;
29
30 import org.apache.log4j.Logger;
31 import org.ejbca.core.ejb.ServiceLocator;
32 import org.ejbca.core.ejb.ca.sign.ISignSessionLocal;
33 import org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome;
34 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionHome;
35 import org.ejbca.core.ejb.ca.store.ICertificateStoreSessionRemote;
36 import org.ejbca.core.ejb.ra.IUserAdminSessionHome;
37 import org.ejbca.core.ejb.ra.IUserAdminSessionRemote;
38 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionHome;
39 import org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionRemote;
40 import org.ejbca.core.model.SecConst;
41 import org.ejbca.core.model.ca.AuthLoginException;
42 import org.ejbca.core.model.ca.AuthStatusException;
43 import org.ejbca.core.model.ca.SignRequestException;
44 import org.ejbca.core.model.ca.SignRequestSignatureException;
45 import org.ejbca.core.model.log.Admin;
46 import org.ejbca.core.model.ra.UserDataVO;
47 import org.ejbca.ui.web.RequestHelper;
48 import org.ejbca.util.CertTools;
49 import org.ejbca.util.StringTools;
50
51
52
53
54 /**
55  * This is a servlet that is used for creating a user into EJBCA and
56  * retrieving her certificate. Supports only POST.
57  * <p>
58  * The CGI parameters for requests are the following.
59  * </p>
60  * <dl>
61  * <dt>pkcs10req</dt>
62  * <dd>
63  * A PKCS#10 request, mandatory.
64  * </dd>
65  * <dt>username</dt>
66  * <dd>
67  * The username (for EJBCA use only). Optional, defaults to the CN in
68  * the PKCS#10 request.
69  * </dd>
70  * <dt>password</dt>
71  * <dd>
72  * Password for the user (for EJBCA internal use only). Optional,
73  * defaults to an empty string. Used for authorization of the certificate request.
74  * </dd>
75  * <dt>email</dt>
76  * <dd>
77  * Email of the user for inclusion in subject alternative names. Optional,
78  * defaults to none.
79  * </dd>
80  * <dt>entityprofile</dt>
81  * <dd>
82  * The name of the EJBCA end entity profile for the user. Optional,
83  * defaults to an empty end entity profile.
84  * </dd>
85  * <dt>certificateprofile</dt>
86  * <dd>
87  * The name of the EJBCA certificate profile to use. Optional,
88  * defaults to the fixed end user profile.
89  * </dd>
90  * </dl>
91  *
92  * @version $Id: DemoCertReqServlet.java,v 1.5 2007/01/03 14:34:11 anatom Exp $
93  */

94 public class DemoCertReqServlet extends HttpServlet JavaDoc {
95
96   private final static Logger log = Logger.getLogger(DemoCertReqServlet.class);
97
98   private IUserAdminSessionHome useradminsessionhome = null;
99   private IRaAdminSessionHome raadminsessionhome = null;
100   private ICertificateStoreSessionHome storesessionhome = null;
101
102   // Edit this constant to the id of your preferable ca used to sign certificate.
103
private final static int DEFAULT_DEMOCAID = 0;
104   
105   private ISignSessionLocal signsession = null;
106
107   private synchronized ISignSessionLocal getSignSession(){
108     if(signsession == null){
109         try {
110             ISignSessionLocalHome signhome = (ISignSessionLocalHome)ServiceLocator.getInstance().getLocalHome(ISignSessionLocalHome.COMP_NAME);
111             signsession = signhome.create();
112         }catch(Exception JavaDoc e){
113             throw new EJBException JavaDoc(e);
114         }
115     }
116     return signsession;
117   }
118   public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc
119   {
120     super.init(config);
121     try {
122       // Install BouncyCastle provider
123
CertTools.installBCProvider();
124
125       // Get EJB context and home interfaces
126
InitialContext JavaDoc ctx = new InitialContext JavaDoc();
127       useradminsessionhome = (IUserAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("UserAdminSession"), IUserAdminSessionHome.class);
128       raadminsessionhome = (IRaAdminSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("RaAdminSession"), IRaAdminSessionHome.class);
129       storesessionhome = (ICertificateStoreSessionHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("CertificateStoreSession"), ICertificateStoreSessionHome.class);
130     } catch (Exception JavaDoc e) {
131       throw new ServletException JavaDoc(e);
132     }
133   }
134
135
136   /**
137    * Handles PKCS10 certificate request, these are constructed as:
138    * <pre><code>
139    * CertificationRequest ::= SEQUENCE {
140    * certificationRequestInfo CertificationRequestInfo,
141    * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
142    * signature BIT STRING
143    * }
144    * CertificationRequestInfo ::= SEQUENCE {
145    * version INTEGER { v1(0) } (v1,...),
146    * subject Name,
147    * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
148    * attributes [0] Attributes{{ CRIAttributes }}
149    * }
150    * SubjectPublicKeyInfo { ALGORITHM : IOSet} ::= SEQUENCE {
151    * algorithm AlgorithmIdentifier {{IOSet}},
152    * subjectPublicKey BIT STRING
153    * }
154    * </pre>
155    *
156    * PublicKey's encoded-format has to be RSA X.509.
157    */

158   public void doPost(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
159     throws IOException JavaDoc, ServletException JavaDoc
160   {
161     ServletDebug debug = new ServletDebug(request, response);
162
163     ISignSessionLocal signsession = null;
164     ICertificateStoreSessionRemote storesession = null;
165     IUserAdminSessionRemote useradminsession = null;
166     IRaAdminSessionRemote raadminsession = null;
167     try {
168         useradminsession = useradminsessionhome.create();
169         raadminsession = raadminsessionhome.create();
170         signsession = getSignSession();
171         storesession = storesessionhome.create();
172     } catch (CreateException JavaDoc e) {
173       throw new ServletException JavaDoc(e);
174     }
175
176      Admin admin = new Admin(Admin.TYPE_RA_USER, request.getRemoteAddr());
177      RequestHelper.setDefaultCharacterEncoding(request);
178
179       String JavaDoc dn = null;
180       dn = request.getParameter("user");
181       byte[] reqBytes = null;
182       int type = 0;
183       if (request.getParameter("keygen") != null) {
184           reqBytes=request.getParameter("keygen").getBytes();
185           log.debug("Received NS request:"+new String JavaDoc(reqBytes));
186           if (reqBytes != null) {
187               type = 1;
188           }
189       } else if (request.getParameter("pkcs10req") != null) {
190           // if not netscape, check if it's IE
191
reqBytes=request.getParameter("pkcs10req").getBytes();
192           log.debug("Received IE request:"+new String JavaDoc(reqBytes));
193           if (reqBytes != null) {
194               type = 2;
195           }
196       }
197     if (reqBytes == null) {
198       // abort here, no request received
199
throw new ServletException JavaDoc("A certification request must be provided!");
200     }
201
202     String JavaDoc username = request.getParameter("username");
203     if (username == null || username.trim().length() == 0) {
204         username = CertTools.getPartFromDN(dn, "CN");
205     }
206     username = username + "("+(new Date JavaDoc()).toString()+")";
207     // Strip dangerous chars
208
username = StringTools.strip(username);
209     // need null check here?
210
// Before doing anything else, check if the user name is unique and ok.
211
boolean check = checkUsername(admin,username, useradminsession);
212     if (check == false) {
213         String JavaDoc msg = "User '"+username+"' already exist.";
214         log.error(msg);
215         debug.printMessage(msg);
216         debug.printDebugInfo();
217         return;
218     }
219
220     // Functionality to determine the class id of ie page.
221
String JavaDoc classid = "clsid:127698e4-e730-4e5c-a2b1-21490a70c8a1\" CODEBASE=\"/CertControl/xenroll.cab#Version=5,131,3659,0";
222     if(request.getParameter("classid")!=null && !request.getParameter("classid").equals(""))
223       classid= request.getParameter("classid");
224     
225     String JavaDoc includeEmail = request.getParameter("includeemail");
226     log.debug("includeEmail="+includeEmail);
227
228     UserDataVO newuser = new UserDataVO();
229     newuser.setType(SecConst.USER_ENDUSER);
230     newuser.setUsername(username);
231     newuser.setDN(dn);
232     newuser.setTokenType(SecConst.TOKEN_SOFT_BROWSERGEN);
233     newuser.setAdministrator(false);
234     newuser.setKeyRecoverable(false);
235     newuser.setSendNotification(false);
236     
237     String JavaDoc email = request.getParameter("email");
238     if (email == null) email = CertTools.getPartFromDN(dn, "EMAILADDRESS");
239     if ((email != null) && (email.length() > 0)) {
240       newuser.setEmail(email);
241       if (includeEmail != null) {
242           newuser.setSubjectAltName("RFC822NAME="+email);
243       }
244     }
245
246     String JavaDoc tmp = null;
247     int eProfileId = SecConst.EMPTY_ENDENTITYPROFILE;
248     if ((tmp=request.getParameter("entityprofile")) != null) {
249         eProfileId = raadminsession.getEndEntityProfileId(admin, request.getParameter("entityprofile"));
250         if (eProfileId == 0) {
251             throw new ServletException JavaDoc("No such end entity profile: " + tmp);
252         }
253     }
254     newuser.setEndEntityProfileId(eProfileId);
255
256     int cProfileId = SecConst.CERTPROFILE_FIXED_ENDUSER;
257     if ((tmp=request.getParameter("certificateprofile")) != null) {
258         cProfileId = storesession.getCertificateProfileId(admin, request.getParameter("certificateprofile"));
259         if (cProfileId == 0) {
260             throw new ServletException JavaDoc("No such certificate profile: " + tmp);
261         }
262     }
263     newuser.setCertificateProfileId(cProfileId);
264
265     int caid = DEFAULT_DEMOCAID;
266     if ((tmp=request.getParameter("ca")) != null) {
267         // Do NOT get requested CA to sign with from form.
268
// For security reasons, if there are more than one CA in the system
269
// we definataly want to hardwire the demo to the demo CA.
270
}
271     newuser.setCAId(caid);
272     
273
274     String JavaDoc password = request.getParameter("password");
275     if (password == null) password = "demo";
276     newuser.setPassword(password);
277    
278
279     try {
280         useradminsession.addUser(admin, newuser.getUsername(), newuser.getPassword(), newuser.getDN(), newuser.getSubjectAltName()
281                                ,newuser.getEmail(), false, newuser.getEndEntityProfileId(),
282                                 newuser.getCertificateProfileId(), newuser.getType(),
283                                 newuser.getTokenType(), newuser.getHardTokenIssuerId(), newuser.getCAId());
284     } catch (Exception JavaDoc e) {
285       throw new ServletException JavaDoc("Error adding user: ", e);
286     }
287
288     RequestHelper helper = new RequestHelper(admin, debug);
289     try {
290         if (type == 1) {
291               byte[] certs = helper.nsCertRequest(signsession, reqBytes, username, password);
292               RequestHelper.sendNewCertToNSClient(certs, response);
293         }
294         if (type == 2) {
295               byte[] b64cert=helper.pkcs10CertRequest(signsession, reqBytes, username, password, RequestHelper.ENCODED_PKCS7);
296               debug.ieCertFix(b64cert);
297               RequestHelper.sendNewCertToIEClient(b64cert, response.getOutputStream(), getServletContext(), getInitParameter("responseTemplate"), classid);
298         }
299     } catch (ObjectNotFoundException JavaDoc oe) {
300         log.debug("Non existens username!");
301         debug.printMessage("Non existent username!");
302         debug.printMessage("To generate a certificate a valid username and password must be entered.");
303         debug.printDebugInfo();
304         return;
305     } catch (AuthStatusException ase) {
306         log.debug("Wrong user status!");
307         debug.printMessage("Wrong user status!");
308         debug.printMessage("To generate a certificate for a user the user must have status new, failed or inprocess.");
309         debug.printDebugInfo();
310         return;
311     } catch (AuthLoginException ale) {
312         log.debug("Wrong password for user!");
313         debug.printMessage("Wrong username or password!");
314         debug.printMessage("To generate a certificate a valid username and password must be entered.");
315         debug.printDebugInfo();
316         return;
317     } catch (SignRequestException re) {
318         log.debug("Invalid request!");
319         debug.printMessage("Invalid request!");
320         debug.printMessage("Please supply a correct request.");
321         debug.printDebugInfo();
322         return;
323     } catch (SignRequestSignatureException se) {
324         log.debug("Invalid signature on certificate request!");
325         debug.printMessage("Invalid signature on certificate request!");
326         debug.printMessage("Please supply a correctly signed request.");
327         debug.printDebugInfo();
328         return;
329     } catch (java.lang.ArrayIndexOutOfBoundsException JavaDoc ae) {
330         log.debug("Empty or invalid request received.");
331         debug.printMessage("Empty or invalid request!");
332         debug.printMessage("Please supply a correct request.");
333         debug.printDebugInfo();
334         return;
335     } catch (Exception JavaDoc e) {
336         log.debug(e);
337         debug.print("<h3>parameter name and values: </h3>");
338         Enumeration JavaDoc paramNames=request.getParameterNames();
339         while (paramNames.hasMoreElements()) {
340             String JavaDoc name=paramNames.nextElement().toString();
341             String JavaDoc parameter=request.getParameter(name);
342             debug.print("<h4>"+name+":</h4>"+parameter+"<br>");
343         }
344         debug.takeCareOfException(e);
345         debug.printDebugInfo();
346         return;
347     }
348   }
349
350
351   public void doGet(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws IOException JavaDoc, ServletException JavaDoc
352   {
353     log.debug(">doGet()");
354     response.setHeader("Allow", "POST");
355     ServletDebug debug = new ServletDebug(request,response);
356     debug.print("The certificate request servlet only handles POST method.");
357     debug.printDebugInfo();
358     log.debug("<doGet()");
359   } // doGet
360

361
362
363   /**
364    * @return true if the username is ok (does not already exist), false otherwise
365    */

366   private final boolean checkUsername(Admin admin, String JavaDoc username, IUserAdminSessionRemote adminsession) throws ServletException JavaDoc
367   {
368     if (username != null) username = username.trim();
369     if (username == null || username.length() == 0) {
370       throw new ServletException JavaDoc("Username must not be empty.");
371     }
372
373     UserDataVO tmpuser = null;
374     try {
375         tmpuser = adminsession.findUser(admin, username);
376      } catch (Exception JavaDoc e) {
377         throw new ServletException JavaDoc("Error checking username '" + username +": ", e);
378      }
379     return (tmpuser==null) ? true:false;
380   }
381
382 }
383
Popular Tags