summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/cert/GetCAChain.java
blob: 4093b989fe5be5ce0da0b3a274b64092de61518b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
	package com.netscape.cms.servlet.cert;


	import com.netscape.cms.servlet.common.*;
	import com.netscape.cms.servlet.base.*;
	import java.io.*;
	import java.util.*;
	import java.math.*;
	import javax.servlet.*;
	import java.security.cert.*;
	import javax.servlet.http.*;
	import netscape.ldap.*;
	import netscape.security.x509.*;
	import com.netscape.certsrv.base.*;
	import com.netscape.certsrv.authority.*;
	import com.netscape.certsrv.policy.*;
	import com.netscape.certsrv.request.IRequest;
	import com.netscape.certsrv.dbs.*;
	import com.netscape.certsrv.dbs.certdb.*;
	import com.netscape.certsrv.ldap.*;
	import com.netscape.certsrv.logging.*;
	import com.netscape.certsrv.apps.CMS;
	import com.netscape.certsrv.authentication.*;
	import com.netscape.certsrv.authorization.*;
	import com.netscape.cms.servlet.*;


	/**
	 * Retrieve the Certificates comprising the CA Chain for this CA.
	 *
	 * @version $Revision$, $Date$
	 */
	public class GetCAChain extends CMSServlet {
	    private final static String TPL_FILE = "displayCaCert.template";
	    private String mFormPath = null;

	    public GetCAChain() {
		super();
	    }

	    /**
	     * initialize the servlet.
	     * @param sc servlet configuration, read from the web.xml file
	     */
	    public void init(ServletConfig sc) throws ServletException {
		super.init(sc);

		// override success to display own output.
		mTemplates.remove(CMSRequest.SUCCESS);
		// coming from ee
		mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
	    }

	    /**
	     * Process the HTTP request. 
	     * <ul>
	     * <li>http.param op 'downloadBIN' - return the binary certificate chain
	     * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
	     * </ul>
	     * @param cmsReq the object holding the request and response information
	     */
	    protected void process(CMSRequest cmsReq)
		throws EBaseException {
		HttpServletRequest httpReq = cmsReq.getHttpReq();
		HttpServletResponse httpResp = cmsReq.getHttpResp();

		IAuthToken authToken = authenticate(cmsReq);

		// Construct an ArgBlock
		IArgBlock args = cmsReq.getHttpParams();

		// Get the operation code
		String op = null;

		op = args.getValueAsString("op", null);
		if (op == null) {
		    log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_NO_OPTIONS_SELECTED"));
		    throw new ECMSGWException(
		      CMS.getUserMessage("CMS_GW_NO_OPTIONS_SELECTED"));
		}

		cmsReq.setStatus(CMSRequest.SUCCESS);

		AuthzToken authzToken = null;

		if (op.startsWith("download")) {
		    try {
			authzToken = authorize(mAclMethod, authToken,
				    mAuthzResourceName, "download");
		    } catch (EAuthzAccessDenied e) {
			log(ILogger.LL_FAILURE,
			    CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
		    } catch (Exception e) {
			log(ILogger.LL_FAILURE,
			    CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
		    }

		    if (authzToken == null) {
			cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
			return;
		    }

		    downloadChain(op, args, httpReq, httpResp, cmsReq);
		} else if (op.startsWith("display")) {
		    try {
			authzToken = mAuthz.authorize(mAclMethod, authToken,
				    mAuthzResourceName, "read");
		    } catch (EAuthzAccessDenied e) {
			log(ILogger.LL_FAILURE,
			    CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
		    } catch (Exception e) {
			log(ILogger.LL_FAILURE,
			    CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
		    }

		    if (authzToken == null) {
			cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
			return;
		    }

		    displayChain(op, args, httpReq, httpResp, cmsReq);
		} else {
		    log(ILogger.LL_FAILURE, 
			CMS.getLogMessage("CMSGW_INVALID_OPTIONS_CA_CHAIN"));
		    throw new ECMSGWException(
		      CMS.getUserMessage("CMS_GW_INVALID_OPTIONS_SELECTED"));
		}
		//		cmsReq.setResult(null);
		return;
	    }

	    private void downloadChain(String op, 
		IArgBlock args, 
		HttpServletRequest httpReq, 
		HttpServletResponse httpResp,
		CMSRequest cmsReq)
		throws EBaseException {

		/* check browser info ? */
		
		/* check if pkcs7 will work for both nav and ie */

		byte[] bytes = null;

		/*
		 * Some IE actions - IE doesn't want PKCS7 for "download" CA Cert.
		 * This means that we can only hand out the root CA, and not
		 * the whole chain.
		 */

		if (clientIsMSIE(httpReq) && (op.equals("download") || op.equals("downloadBIN"))) {
		    X509Certificate[] caCerts = 
			((ICertAuthority) mAuthority).getCACertChain().getChain();

		    try {
			bytes = caCerts[0].getEncoded();
		    } catch (CertificateEncodingException e) {
			cmsReq.setStatus(CMSRequest.ERROR);
			log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_GETTING_CACERT_ENCODED", e.toString()));
			throw new ECMSGWException(
			  CMS.getUserMessage("CMS_GW_GETTING_CA_CERT_ERROR"));
		    }
		} else {
		    CertificateChain certChain = 
			((ICertAuthority) mAuthority).getCACertChain();

		    if (certChain == null) {
			log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_CHAIN_EMPTY"));
			throw new ECMSGWException(
			  CMS.getUserMessage("CMS_GW_CA_CHAIN_EMPTY"));
		    }
				
		    try {
			ByteArrayOutputStream encoded = new ByteArrayOutputStream();

			certChain.encode(encoded, false);
			bytes = encoded.toByteArray();
		    } catch (IOException e) {
			cmsReq.setStatus(CMSRequest.ERROR);
			log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1", e.toString()));
			throw new ECMSGWException(
			  CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
		    }
		}

		String mimeType = null;

		if (op.equals("downloadBIN")) {
		    mimeType = "application/octet-stream";
		} else {
		    try {
			mimeType = args.getValueAsString("mimeType");
		    } catch (EBaseException e) {
			mimeType = "application/octet-stream";
		    }
		}

		try {
		    if (op.equals("downloadBIN")) {
		        // file suffixes changed to comply with RFC 5280
		        // requirements for AIA extensions
		        if (clientIsMSIE(httpReq)) {
		            httpResp.setHeader("Content-disposition",
		                "attachment; filename=ca.cer");
		        } else {
		            httpResp.setHeader("Content-disposition",
		                "attachment; filename=ca.p7c");
		        }
		    }
		    httpResp.setContentType(mimeType);
		    httpResp.getOutputStream().write(bytes);
		    httpResp.setContentLength(bytes.length);
		    httpResp.getOutputStream().flush();
		} catch (IOException e) {
		    cmsReq.setStatus(CMSRequest.ERROR);
		    log(ILogger.LL_FAILURE, 
			CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CACHAIN_1", e.toString()));
		    throw new ECMSGWException(
		      CMS.getUserMessage("CMS_GW_DISPLAYING_CACHAIN_ERROR"));
		}
	    }

	    private void displayChain(String op, 
		IArgBlock args, 
		HttpServletRequest httpReq, 
		HttpServletResponse httpResp,
		CMSRequest cmsReq)
		throws EBaseException {
		String outputString = null;

		CertificateChain certChain = 
		    ((ICertAuthority) mAuthority).getCACertChain();

		if (certChain == null) {
		    cmsReq.setStatus(CMSRequest.ERROR);
		    log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CA_CHAIN_NOT_AVAILABLE"));
		    throw new ECMSGWException(
		      CMS.getUserMessage("CMS_GW_CA_CHAIN_NOT_AVAILABLE"));
		}

		CMSTemplate form = null;
		Locale[] locale = new Locale[1];

		if (mOutputTemplatePath != null)
		    mFormPath = mOutputTemplatePath;
        try {
            form = getTemplate(mFormPath, httpReq, locale);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
            cmsReq.setError(new ECMSGWException(
              CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
            cmsReq.setStatus(CMSRequest.ERROR);
            return;
        }

        IArgBlock header = CMS.createArgBlock();
        IArgBlock fixed = CMS.createArgBlock();
        CMSTemplateParams argSet = new CMSTemplateParams(header, fixed);

        String displayFormat = null;

        if (op.equals("displayIND")) {
            displayFormat = "individual";
        } else {
            try {
                displayFormat = args.getValueAsString("displayFormat");
            } catch (EBaseException e) {
                displayFormat = "chain";
            }
        }

        header.addStringValue("displayFormat", displayFormat);

        if (displayFormat.equals("chain")) {
            String subjectdn = null;
            byte[] bytes = null;

            try {
                subjectdn = 
                        certChain.getFirstCertificate().getSubjectDN().toString();
                ByteArrayOutputStream encoded = new ByteArrayOutputStream();

                certChain.encode(encoded);
                bytes = encoded.toByteArray();
            } catch (IOException e) {
                log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1", e.toString()));
                throw new ECMSGWException(
                  CMS.getUserMessage("CMS_GW_ENCODING_CA_CHAIN_ERROR"));
            }

            String chainBase64 = getBase64(bytes);

            header.addStringValue("subjectdn", subjectdn);
            header.addStringValue("chainBase64", chainBase64);
        } else { 
            try {
                X509Certificate[] certs = certChain.getChain();

                header.addIntegerValue("length", certs.length);
                locale[0] = getLocale(httpReq);
                for (int i = 0; i < certs.length; i++) {
                    byte[] bytes = null;

                    try {
                        bytes = certs[i].getEncoded();
                    } catch (CertificateEncodingException e) {
                        throw new IOException("Internal Error");
                    }
                    String subjectdn = certs[i].getSubjectDN().toString();
                    String finger = null;
                    try {
			finger = CMS.getFingerPrints(certs[i]);
                    } catch (Exception e) {
                        throw new IOException("Internal Error");
                    }

                    ICertPrettyPrint certDetails = 
                        CMS.getCertPrettyPrint((X509CertImpl) certs[i]);

                    IArgBlock rarg = CMS.createArgBlock();

                    rarg.addStringValue("fingerprints", finger);
                    rarg.addStringValue("subjectdn", subjectdn);
                    rarg.addStringValue("base64", getBase64(bytes));
                    rarg.addStringValue("certDetails",
                        certDetails.toString(locale[0]));
                    argSet.addRepeatRecord(rarg);
                }
            } catch (IOException e) {
                log(ILogger.LL_FAILURE, 
                    CMS.getLogMessage("CMSGW_ERROR_DISPLAYING_CACHAIN_1", e.toString()));
                throw new ECMSGWException(
                  CMS.getUserMessage("CMS_GW_DISPLAYING_CACHAIN_ERROR"));
            }
        }

        try {
            ServletOutputStream out = httpResp.getOutputStream();

            httpResp.setContentType("text/html");
            form.renderOutput(out, argSet);
            cmsReq.setStatus(CMSRequest.SUCCESS);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "", e.toString()));
            cmsReq.setError(new ECMSGWException(
              CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR")));
            cmsReq.setStatus(CMSRequest.ERROR);
        }

    }

    /**
     * gets base 64 encoded cert
     */
    private String getBase64(byte[] certBytes) {
        String certBase64 = CMS.BtoA(certBytes);

        return certBase64;
    }

    /**
     * gets base 64 encoded cert chain
     */
    private String getChainBase64(byte[] certBytes) {
        String certBase64 = CMS.BtoA(certBytes);

        return certBase64;
    }

    /**
     * Retrieves locale based on the request.
     */
    protected Locale getLocale(HttpServletRequest req) {
        Locale locale = null;
        String lang = req.getHeader("accept-language");

        if (lang == null) {
            // use server locale
            locale = Locale.getDefault();
        } else {
            locale = new Locale(UserInfo.getUserLanguage(lang),
                        UserInfo.getUserCountry(lang));
        }
        return locale;
    }
}