KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ejbca > ui > web > admin > cainterface > CACertServlet


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.admin.cainterface;
15
16 import java.io.IOException JavaDoc;
17 import java.io.PrintStream JavaDoc;
18 import java.security.cert.Certificate JavaDoc;
19 import java.security.cert.X509Certificate JavaDoc;
20
21 import javax.ejb.EJBException JavaDoc;
22 import javax.servlet.ServletConfig JavaDoc;
23 import javax.servlet.ServletException JavaDoc;
24 import javax.servlet.http.HttpServlet JavaDoc;
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.http.HttpServletResponse JavaDoc;
27
28 import org.apache.log4j.Logger;
29 import org.ejbca.core.ejb.ServiceLocator;
30 import org.ejbca.core.ejb.ca.sign.ISignSessionLocal;
31 import org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome;
32 import org.ejbca.core.model.log.Admin;
33 import org.ejbca.ui.web.RequestHelper;
34 import org.ejbca.ui.web.admin.configuration.EjbcaWebBean;
35 import org.ejbca.ui.web.pub.ServletUtils;
36 import org.ejbca.util.Base64;
37
38 /**
39  * Servlet used to distribute CA certificates <br>
40  *
41  * cacert - returns ca certificate in PEM-format
42  * nscacert - returns ca certificate for Netscape/Mozilla
43  * iecacert - returns ca certificate for Internet Explorer
44  *
45  * cacert, nscacert and iecacert also takes optional parameter level=<int 1,2,...>, where the level is
46  * which ca certificate in a hierachy should be returned. 0=root (default), 1=sub to root etc.
47  *
48  * @version $Id: CACertServlet.java,v 1.10 2006/12/04 15:04:59 anatom Exp $
49  *
50  * @web.servlet name = "CACert"
51  * display-name = "CACertServlet"
52  * description="Returns the specified CA certificate"
53  * load-on-startup = "99"
54  *
55  * @web.servlet-mapping url-pattern = "/ca/cacert"
56  *
57  * We put all ejb-env-entrys in this servlet, this is a collection of all envs for all servlets and jsps
58  *
59  * @web.env-entry description="Defines the admin directory"
60  * name="ADMINDIRECTORY"
61  * type="java.lang.String"
62  * value="adminweb"
63  *
64  * @web.env-entry description="Defines the available languages by languagecodes separated with a comma"
65  * name="AVAILABLELANGUAGES"
66  * type="java.lang.String"
67  * value="${web.availablelanguages}"
68  *
69  * @web.env-entry description="Defines the available themes by css-filenames separated with a comma"
70  * name="AVAILABLETHEMES"
71  * type="java.lang.String"
72  * value="default_theme.css"
73  *
74  * @web.env-entry description="Port used by EJBCA public webcomponents. i.e that doesn't require client authentication"
75  * name="PUBLICPORT"
76  * type="java.lang.String"
77  * value="${httpserver.pubhttp}"
78  *
79  * @web.env-entry description="Port used by EJBCA private webcomponents. i.e that requires client authentication"
80  * name="PRIVATEPORT"
81  * type="java.lang.String"
82  * value="${httpserver.privhttps}"
83  *
84  * @web.env-entry description="Protocol used by EJBCA public webcomponents. i.e that doesn't require client authentication"
85  * name="PUBLICPROTOCOL"
86  * type="java.lang.String"
87  * value="http"
88  *
89  * @web.env-entry description="Protocol used by EJBCA private webcomponents. i.e that requires client authentication"
90  * name="PRIVATEPROTOCOL"
91  * type="java.lang.String"
92  * value="https"
93  *
94  * @web.env-entry description="Default content encoding used to display JSP pages"
95  * name="contentEncoding"
96  * type="java.lang.String"
97  * value="${web.contentencoding}"
98  *
99  * We put all ejb-local-refs in this servlet, this is a collection of all refs for all servlets and jsps
100  *
101  * @web.ejb-local-ref
102  * name="ejb/RSASignSessionLocal"
103  * type="Session"
104  * link="RSASignSession"
105  * home="org.ejbca.core.ejb.ca.sign.ISignSessionLocalHome"
106  * local="org.ejbca.core.ejb.ca.sign.ISignSessionLocal"
107  *
108  * @web.ejb-local-ref
109  * name="ejb/CertificateStoreSessionLocal"
110  * type="Session"
111  * link="CertificateStoreSession"
112  * home="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocalHome"
113  * local="org.ejbca.core.ejb.ca.store.ICertificateStoreSessionLocal"
114  *
115  * @web.ejb-local-ref
116  * name="ejb/CAAdminSessionLocal"
117  * type="Session"
118  * link="CAAdminSession"
119  * home="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocalHome"
120  * local="org.ejbca.core.ejb.ca.caadmin.ICAAdminSessionLocal"
121  *
122  * @web.ejb-local-ref
123  * name="ejb/UserAdminSessionLocal"
124  * type="Session"
125  * link="UserAdminSession"
126  * home="org.ejbca.core.ejb.ra.IUserAdminSessionLocalHome"
127  * local="org.ejbca.core.ejb.ra.IUserAdminSessionLocal"
128  *
129  * @web.ejb-local-ref
130  * name="ejb/RaAdminSessionLocal"
131  * type="Session"
132  * link="RaAdminSession"
133  * home="org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocalHome"
134  * local="org.ejbca.core.ejb.ra.raadmin.IRaAdminSessionLocal"
135  *
136  * @web.ejb-local-ref
137  * name="ejb/LogSessionLocal"
138  * type="Session"
139  * link="LogSession"
140  * home="org.ejbca.core.ejb.log.ILogSessionLocalHome"
141  * local="org.ejbca.core.ejb.log.ILogSessionLocal"
142  *
143  * @web.ejb-local-ref
144  * name="ejb/AuthorizationSessionLocal"
145  * type="Session"
146  * link="AuthorizationSession"
147  * home="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocalHome"
148  * local="org.ejbca.core.ejb.authorization.IAuthorizationSessionLocal"
149  *
150  * @web.ejb-local-ref
151  * name="ejb/HardTokenSessionLocal"
152  * type="Session"
153  * link="HardTokenSession"
154  * home="org.ejbca.core.ejb.hardtoken.IHardTokenSessionLocalHome"
155  * local="org.ejbca.core.ejb.hardtoken.IHardTokenSessionLocal"
156  *
157  * @web.ejb-local-ref
158  * name="ejb/HardTokenBatchJobSessionLocal"
159  * type="Session"
160  * link="HardTokenBatchJobSession"
161  * home="org.ejbca.core.ejb.hardtoken.IHardTokenBatchJobSessionLocalHome"
162  * local="org.ejbca.core.ejb.hardtoken.IHardTokenBatchJobSessionLocal"
163  *
164  * @web.ejb-local-ref
165  * name="ejb/KeyRecoverySessionLocal"
166  * type="Session"
167  * link="KeyRecoverySession"
168  * home="org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocalHome"
169  * local="org.ejbca.core.ejb.keyrecovery.IKeyRecoverySessionLocal"
170  *
171  * @web.ejb-local-ref
172  * name="ejb/PublisherSessionLocal"
173  * type="Session"
174  * link="PublisherSession"
175  * home="org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocalHome"
176  * local="org.ejbca.core.ejb.ca.publisher.IPublisherSessionLocal"
177  *
178  * @web.ejb-local-ref
179  * name="ejb/UserDataSourceSessionLocal"
180  * type="Session"
181  * link="UserDataSourceSession"
182  * home="org.ejbca.core.ejb.ra.userdatasource.IUserDataSourceSessionLocalHome"
183  * local="org.ejbca.core.ejb.ra.userdatasource.IUserDataSourceSessionLocal"
184  *
185  * @web.ejb-local-ref
186  * name="ejb/ApprovalSessionLocal"
187  * type="Session"
188  * link="ApprovalSession"
189  * home="org.ejbca.core.ejb.approval.IApprovalSessionLocalHome"
190  * local="org.ejbca.core.ejb.approval.IApprovalSessionLocal"
191  *
192  * @web.ejb-local-ref
193  * name="ejb/ServiceSessionLocal"
194  * type="Session"
195  * link="ServiceSession"
196  * home="org.ejbca.core.ejb.services.IServiceSessionLocalHome"
197  * local="org.ejbca.core.ejb.services.IServiceSessionLocal"
198  *
199  * @web.ejb-local-ref
200  * name="ejb/ServiceTimerSessionLocal"
201  * type="Session"
202  * link="ServiceTimerSession"
203  * home="org.ejbca.core.ejb.services.IServiceTimerSessionLocalHome"
204  * local="org.ejbca.core.ejb.services.IServiceTimerSessionLocal"
205  *
206  * @web.resource-ref
207  * name="${datasource.jndi-name-prefix}${datasource.jndi-name}"
208  * type="javax.sql.DataSource"
209  * auth="Container"
210  */

211 public class CACertServlet extends HttpServlet JavaDoc {
212
213     private static final Logger log = Logger.getLogger(CACertServlet.class);
214
215     private static final String JavaDoc COMMAND_PROPERTY_NAME = "cmd";
216     private static final String JavaDoc COMMAND_NSCACERT = "nscacert";
217     private static final String JavaDoc COMMAND_IECACERT = "iecacert";
218     private static final String JavaDoc COMMAND_CACERT = "cacert";
219
220     private static final String JavaDoc LEVEL_PROPERTY = "level";
221     private static final String JavaDoc ISSUER_PROPERTY = "issuer";
222
223     private ISignSessionLocal signsession = null;
224
225     private synchronized ISignSessionLocal getSignSession(){
226         if(signsession == null){
227             try {
228                 ISignSessionLocalHome signhome = (ISignSessionLocalHome)ServiceLocator.getInstance().getLocalHome(ISignSessionLocalHome.COMP_NAME);
229                 signsession = signhome.create();
230             }catch(Exception JavaDoc e){
231                 throw new EJBException JavaDoc(e);
232             }
233         }
234         return signsession;
235     }
236
237     public void init(ServletConfig JavaDoc config) throws ServletException JavaDoc {
238         super.init(config);
239     }
240     
241     public void doPost(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res)
242         throws IOException JavaDoc, ServletException JavaDoc {
243         log.debug(">doPost()");
244         doGet(req, res);
245         log.debug("<doPost()");
246     } //doPost
247

248     public void doGet(HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) throws java.io.IOException JavaDoc, ServletException JavaDoc {
249         log.debug(">doGet()");
250         // Check if authorized
251
EjbcaWebBean ejbcawebbean= (org.ejbca.ui.web.admin.configuration.EjbcaWebBean)
252                                    req.getSession().getAttribute("ejbcawebbean");
253         if ( ejbcawebbean == null ){
254           try {
255             ejbcawebbean = (org.ejbca.ui.web.admin.configuration.EjbcaWebBean) java.beans.Beans.instantiate(this.getClass().getClassLoader(), "org.ejbca.ui.web.admin.configuration.EjbcaWebBean");
256            } catch (ClassNotFoundException JavaDoc exc) {
257                throw new ServletException JavaDoc(exc.getMessage());
258            }catch (Exception JavaDoc exc) {
259                throw new ServletException JavaDoc (" Cannot create bean of class "+"org.ejbca.ui.web.admin.configuration.EjbcaWebBean", exc);
260            }
261            req.getSession().setAttribute("ejbcawebbean", ejbcawebbean);
262         }
263
264         try{
265           ejbcawebbean.initialize(req,"/ca_functionality/basic_functions");
266         } catch(Exception JavaDoc e){
267            throw new java.io.IOException JavaDoc("Authorization Denied");
268         }
269         
270         RequestHelper.setDefaultCharacterEncoding(req);
271
272         String JavaDoc issuerdn = req.getParameter(ISSUER_PROPERTY);
273         
274         String JavaDoc command;
275         // Keep this for logging.
276
log.debug("Got request from "+req.getRemoteAddr());
277         command = req.getParameter(COMMAND_PROPERTY_NAME);
278         if (command == null)
279             command = "";
280         if ((command.equalsIgnoreCase(COMMAND_NSCACERT) || command.equalsIgnoreCase(COMMAND_IECACERT) || command.equalsIgnoreCase(COMMAND_CACERT)) && issuerdn != null ) {
281             String JavaDoc lev = req.getParameter(LEVEL_PROPERTY);
282             int level = 0;
283             if (lev != null)
284                 level = Integer.parseInt(lev);
285             // Root CA is level 0, next below root level 1 etc etc
286
try {
287                 ISignSessionLocal ss = getSignSession();
288                 Admin admin = new Admin(((X509Certificate JavaDoc[]) req.getAttribute( "javax.servlet.request.X509Certificate" ))[0]);
289                 Certificate JavaDoc[] chain = (Certificate JavaDoc[]) ss.getCertificateChain(admin, issuerdn.hashCode()).toArray(new Certificate JavaDoc[0]);
290                                                             
291                 // chain.length-1 is last cert in chain (root CA)
292
if ( (chain.length-1-level) < 0 ) {
293                     PrintStream JavaDoc ps = new PrintStream JavaDoc(res.getOutputStream());
294                     ps.println("No CA certificate of level "+level+"exist.");
295                     log.error("No CA certificate of level "+level+"exist.");
296                     return;
297                 }
298                 X509Certificate JavaDoc cacert = (X509Certificate JavaDoc)chain[level];
299                 byte[] enccert = cacert.getEncoded();
300                 // We must remove cache headers for IE
301
ServletUtils.removeCacheHeaders(res);
302                 if (command.equalsIgnoreCase(COMMAND_NSCACERT)) {
303                     res.setContentType("application/x-x509-ca-cert");
304                     res.setContentLength(enccert.length);
305                     res.getOutputStream().write(enccert);
306                     log.debug("Sent CA cert to NS client, len="+enccert.length+".");
307                 } else if (command.equalsIgnoreCase(COMMAND_IECACERT)) {
308                     res.setHeader("Content-disposition", "attachment; filename=ca.crt");
309                     res.setContentType("application/octet-stream");
310                     res.setContentLength(enccert.length);
311                     res.getOutputStream().write(enccert);
312                     log.debug("Sent CA cert to IE client, len="+enccert.length+".");
313                 } else if (command.equalsIgnoreCase(COMMAND_CACERT)) {
314                     byte[] b64cert = Base64.encode(enccert);
315                     String JavaDoc out = RequestHelper.BEGIN_CERTIFICATE_WITH_NL;
316                     out += new String JavaDoc(b64cert);
317                     out += RequestHelper.END_CERTIFICATE_WITH_NL;
318                     res.setHeader("Content-disposition", "attachment; filename=ca.pem");
319                     res.setContentType("application/octet-stream");
320                     res.setContentLength(out.length());
321                     res.getOutputStream().write(out.getBytes());
322                     log.debug("Sent CA cert to client, len="+out.length()+".");
323                 } else {
324                     res.setContentType("text/plain");
325                     res.getOutputStream().println("Commands="+COMMAND_NSCACERT+" || "+COMMAND_IECACERT+" || "+COMMAND_CACERT);
326                     return;
327                 }
328             } catch (Exception JavaDoc e) {
329                 log.error("Error getting CA certificates: ", e);
330                 res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificates.");
331                 return;
332             }
333         }
334         else {
335             res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad Request format");
336             return;
337         }
338
339     } // doGet
340

341 }
342
Popular Tags