summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/cert/RenewalServlet.java
blob: a83c390d9464d6dfd84c6b4ab69228f9afb075c3 (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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// --- 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 java.io.IOException;
import java.math.BigInteger;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import netscape.security.extensions.CertInfo;
import netscape.security.x509.CertificateSerialNumber;
import netscape.security.x509.CertificateValidity;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509CertInfo;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.AuthToken;
import com.netscape.certsrv.authentication.IAuthSubsystem;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.authorization.AuthzToken;
import com.netscape.certsrv.authorization.EAuthzAccessDenied;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.base.MetaInfo;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.logging.AuditFormat;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;

/**
 * Certificate Renewal
 *
 * @version $Revision$, $Date$
 */
public class RenewalServlet extends CMSServlet {
    // renewal templates.
    public static final String 
        RENEWAL_SUCCESS_TEMPLATE = "RenewalSuccess.template";

    // http params 
    public static final String CERT_TYPE = "certType";
    public static final String SERIAL_NO = "serialNo";
    // XXX can't do pkcs10 cause it's got no serial no. 
    // (unless put serial no in pki attributes)
    // public static final String PKCS10 = "pkcs10";	
    public static final String IMPORT_CERT = "importCert";

    private String mRenewalSuccessTemplate = RENEWAL_SUCCESS_TEMPLATE;
    private ICMSTemplateFiller 
        mRenewalSuccessFiller = new ImportCertsTemplateFiller();

    public RenewalServlet() {
        super();
    }

    /**
     * initialize the servlet. This servlet makes use of the
     * template file "RenewalSuccess.template" to render the
     * response
     * @param sc servlet configuration, read from the web.xml file
     */
    public void init(ServletConfig sc) throws ServletException {
        super.init(sc);
        // override success template. has same info as enrollment.
        mTemplates.remove(CMSRequest.SUCCESS);
        try {
            mRenewalSuccessTemplate = sc.getInitParameter(
                        PROP_SUCCESS_TEMPLATE);
            if (mRenewalSuccessTemplate == null)
                mRenewalSuccessTemplate = RENEWAL_SUCCESS_TEMPLATE;
            String fillername = 
                sc.getInitParameter(PROP_SUCCESS_TEMPLATE_FILLER);

            if (fillername != null) {
                ICMSTemplateFiller filler = newFillerObject(fillername);

                if (filler != null) 
                    mRenewalSuccessFiller = filler;
            }
        } catch (Exception e) {
            // this should never happen. 
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR", e.toString(),
                    mId));
        }

    }


    /**
     * Process the HTTP request. 
     *
     * @param cmsReq the object holding the request and response information
     */
    protected void process(CMSRequest cmsReq) 
        throws EBaseException {
        long startTime = CMS.getCurrentDate().getTime();
        IArgBlock httpParams = cmsReq.getHttpParams();
        HttpServletRequest httpReq = cmsReq.getHttpReq();

        // renewal requires either: 
        //  - coming from ee: 
        //		- old cert from ssl client auth 
        //		- old certs from auth manager
        // 	- coming from agent or trusted RA: 
        //  	- serial no of cert to be renewed. 
		
        BigInteger old_serial_no = null;
        X509CertImpl old_cert = null;
        X509CertImpl renewed_cert = null;
        Date notBefore = null;
        Date notAfter = null;
        boolean doSaveAuthToken = false;

        IAuthToken authToken = authenticate(cmsReq);

        AuthzToken authzToken = null;

        try {
            authzToken = authorize(mAclMethod, authToken,
                        mAuthzResourceName, "renew");
        } 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;
        }

        String authMgr = AuditFormat.NOAUTH;

        if (authToken != null && !mAuthMgr.equals("sslClientCertAuthMgr")) {
            authMgr =
                    authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
        }

        // coming from agent 
        if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
            X509Certificate[] cert = new X509Certificate[1];

            old_serial_no = getCertFromAgent(httpParams, cert);
            old_cert = (X509CertImpl) cert[0];

            // optional validity params from input.
            int beginYear = httpParams.getValueAsInt("beginYear", -1);
            int beginMonth = httpParams.getValueAsInt("beginMonth", -1);
            int beginDate = httpParams.getValueAsInt("beginDate", -1);
            int endYear = httpParams.getValueAsInt("endYear", -1);
            int endMonth = httpParams.getValueAsInt("endMonth", -1);
            int endDate = httpParams.getValueAsInt("endDate", -1);

            if (beginYear != -1 && beginMonth != -1 && beginDate != -1 &&
                endYear != -1 && endMonth != -1 && endDate != -1) {
                notBefore = new Date(beginYear, beginMonth, beginDate);
                notAfter = new Date(endYear, endMonth, endDate);
            }
        } // coming from client
        else {
            // from auth manager 
            X509CertImpl[] cert = new X509CertImpl[1];

            old_serial_no = getCertFromAuthMgr(authToken, cert);
            old_cert = cert[0];
        }

        IRequest req = null;

        try {
            // get ready to send request to request queue.
            X509CertInfo new_certInfo = null;

            req = mRequestQueue.newRequest(IRequest.RENEWAL_REQUEST);
            req.setExtData(IRequest.OLD_SERIALS, new BigInteger[] {old_serial_no});
            if (old_cert != null) {
                req.setExtData(IRequest.OLD_CERTS,
                    new X509CertImpl[] { old_cert }
                );
                // create new certinfo from old_cert contents. 
                X509CertInfo old_certInfo = (X509CertInfo)
                    ((X509CertImpl) old_cert).get(
                        X509CertImpl.NAME + "." + X509CertImpl.INFO);

                new_certInfo = new X509CertInfo(old_certInfo.getEncodedInfo());
            } else {
                // if no old cert (came from RA agent) create new cert info 
                // (serializable) to pass through policies. And set the old 
                // serial number to pick up.
                new_certInfo = new CertInfo();
                new_certInfo.set(X509CertInfo.SERIAL_NUMBER, 
                    new CertificateSerialNumber(old_serial_no));
            }
			
            if (notBefore == null || notAfter == null) {
                notBefore = new Date(0);
                notAfter = new Date(0);
            }
            new_certInfo.set(X509CertInfo.VALIDITY, 
                new CertificateValidity(notBefore, notAfter));
            req.setExtData(IRequest.CERT_INFO, new X509CertInfo[] { new_certInfo }
            );
        } catch (CertificateException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_ERROR_SETTING_RENEWAL_VALIDITY_1", e.toString()));
            throw new ECMSGWException(
              CMS.getUserMessage("CMS_GW_SETTING_RENEWAL_VALIDITY_ERROR"));
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_ERROR_SETTING_RENEWAL_VALIDITY_1", e.toString()));
            throw new ECMSGWException(
              CMS.getUserMessage("CMS_GW_SETTING_RENEWAL_VALIDITY_ERROR"));
        }

        saveHttpHeaders(httpReq, req);
        saveHttpParams(httpParams, req);
        if (doSaveAuthToken)
            saveAuthToken(authToken, req);
        cmsReq.setIRequest(req);

        // send request to request queue. 
        mRequestQueue.processRequest(req);

        // for audit log
        String initiative = null;
        String agentID = null;

        if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
            agentID = authToken.getInString("userid");
            initiative = AuditFormat.FROMAGENT + " agentID: " + agentID;
        }else {
            // request is from eegateway, so fromUser.
            initiative = AuditFormat.FROMUSER;
        }

        // check resulting status 
        RequestStatus status = req.getRequestStatus();

        if (status != RequestStatus.COMPLETE) {
            cmsReq.setIRequestStatus();
            // audit log the status
            if (status == RequestStatus.REJECTED) {
                Vector messages = req.getExtDataInStringVector(IRequest.ERRORS);

                if (messages != null) {
                    Enumeration msgs = messages.elements();
                    StringBuffer wholeMsg = new StringBuffer();

                    while (msgs.hasMoreElements()) {
                        wholeMsg.append("\n");
                        wholeMsg.append(msgs.nextElement());
                    }

                    mLogger.log(ILogger.EV_AUDIT, 
                        ILogger.S_OTHER,
                        AuditFormat.LEVEL,
                        AuditFormat.RENEWALFORMAT,
                        new Object[] {
                            req.getRequestId(), 
                            initiative,
                            authMgr,
                            status.toString(),
                            old_cert.getSubjectDN(),
                            old_cert.getSerialNumber().toString(16),
                            "violation: " +
                            wholeMsg.toString()}
                        // wholeMsg},
                        // ILogger.L_MULTILINE
                    );
                } else { // no policy violation, from agent
                    mLogger.log(ILogger.EV_AUDIT,
                        ILogger.S_OTHER,
                        AuditFormat.LEVEL,
                        AuditFormat.RENEWALFORMAT,
                        new Object[] {
                            req.getRequestId(), 
                            initiative,
                            authMgr,
                            status.toString(),
                            old_cert.getSubjectDN(),
                            old_cert.getSerialNumber().toString(16),
                            "" }
                    );
                }
            } else { // other imcomplete status 
                mLogger.log(ILogger.EV_AUDIT,
                    ILogger.S_OTHER,
                    AuditFormat.LEVEL,
                    AuditFormat.RENEWALFORMAT,
                    new Object[] {
                        req.getRequestId(), 
                        initiative,
                        authMgr,
                        status.toString(),
                        old_cert.getSubjectDN(),
                        old_cert.getSerialNumber().toString(16),
                        "" }
                );
            }
            return;
        }

        // service error 
        Integer result = req.getExtDataInInteger(IRequest.RESULT);

        CMS.debug(
            "RenewalServlet: Result for request " + req.getRequestId() + " is " + result);
        if (result.equals(IRequest.RES_ERROR)) {
            CMS.debug(
                "RenewalServlet: Result for request " + req.getRequestId() + " is error.");

            cmsReq.setStatus(CMSRequest.ERROR);
            cmsReq.setError(req.getExtDataInString(IRequest.ERROR));
            String[] svcErrors =
                req.getExtDataInStringArray(IRequest.SVCERRORS);

            if (svcErrors != null && svcErrors.length > 0) {
                for (int i = 0; i < svcErrors.length; i++) {
                    String err = svcErrors[i];

                    if (err != null) {
                        //System.out.println(
                        //"revocation servlet: setting error description "+
                        //err.toString());
                        cmsReq.setErrorDescription(err);
                        mLogger.log(ILogger.EV_AUDIT,
                            ILogger.S_OTHER,
                            AuditFormat.LEVEL,
                            AuditFormat.RENEWALFORMAT,
                            new Object[] {
                                req.getRequestId(), 
                                initiative,
                                authMgr,
                                "completed with error: " +
                                err,
                                old_cert.getSubjectDN(),
                                old_cert.getSerialNumber().toString(16),
                                "" }
                        );

                    }
                }
            }
            return;
        }

        // success.
        X509CertImpl[] certs = req.getExtDataInCertArray(IRequest.ISSUED_CERTS);

        renewed_cert = certs[0];
        respondSuccess(cmsReq, renewed_cert);
        long endTime = CMS.getCurrentDate().getTime();

        mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
            AuditFormat.LEVEL,
            AuditFormat.RENEWALFORMAT,
            new Object[] {
                req.getRequestId(), 
                initiative,
                authMgr,
                "completed",
                old_cert.getSubjectDN(),
                old_cert.getSerialNumber().toString(16),
                "new serial number: 0x" +
                renewed_cert.getSerialNumber().toString(16) + " time: " + (endTime - startTime)}
        );

        return;
    }

    private void respondSuccess(
        CMSRequest cmsReq, X509CertImpl renewed_cert)
        throws EBaseException {
        cmsReq.setResult(new X509CertImpl[] {renewed_cert}
        );
        cmsReq.setStatus(CMSRequest.SUCCESS);

        // check if cert should be imported. 
        // browser must have input type set to nav or cartman since 
        // there's no other way to tell

        IArgBlock httpParams = cmsReq.getHttpParams();
        HttpServletRequest httpReq = cmsReq.getHttpReq();
        String certType = httpParams.getValueAsString(CERT_TYPE, "client");
        String agent = httpReq.getHeader("user-agent");

        if (checkImportCertToNav(cmsReq.getHttpResp(), 
                httpParams, renewed_cert)) {
            return;
        } else {
            try {
                renderTemplate(cmsReq, 
                    mRenewalSuccessTemplate, mRenewalSuccessFiller);
            } catch (IOException e) {
                log(ILogger.LL_FAILURE, 
                    CMS.getLogMessage("CMSGE_ERROR_DISPLAY_TEMPLATE_1",
                        mRenewalSuccessTemplate, e.toString()));
                throw new ECMSGWException(
                  CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
            }
        }
        return;
    }

    protected BigInteger getRenewedCert(ICertRecord certRec) 
        throws EBaseException {
        BigInteger renewedCert = null;
        String serial = null;
        MetaInfo meta = certRec.getMetaInfo(); 

        if (meta == null) {
            log(ILogger.LL_INFO, 
                "no meta info in cert serial 0x" + certRec.getSerialNumber().toString(16));
            return null;
        }
        serial = (String) meta.get(ICertRecord.META_RENEWED_CERT);
        if (serial == null) {
            log(ILogger.LL_INFO, 
                "no renewed cert in cert 0x" + certRec.getSerialNumber().toString(16));
            return null;
        }
        renewedCert = new BigInteger(serial);
        log(ILogger.LL_INFO, 
            "renewed cert serial 0x" + renewedCert.toString(16) + "found for 0x" +
            certRec.getSerialNumber().toString(16));
        return renewedCert;
    }

    /**
     * get certs to renew from agent.
     */
    private BigInteger getCertFromAgent(
        IArgBlock httpParams, X509Certificate[] certContainer)
        throws EBaseException {
        BigInteger serialno = null;
        X509Certificate cert = null;

        // get serial no
        serialno = httpParams.getValueAsBigInteger(SERIAL_NO, null);
        if (serialno == null) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_RENEW"));
            throw new ECMSGWException(
              CMS.getUserMessage("CMS_GW_MISSING_SERIALNO_FOR_RENEW"));
        }
        // get cert from db if we're cert authority.
        if (mAuthority instanceof ICertificateAuthority) {
            cert = getX509Certificate(serialno);
            if (cert == null) {
                log(ILogger.LL_FAILURE, 
                    CMS.getLogMessage("CMSGW_MISSING_SERIALNO_FOR_RENEW_1", serialno.toString(16)));
                throw new ECMSGWException(
                  CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_RENEWAL"));
            }
        }
        certContainer[0] = cert;
        return serialno;
    }

    /**
     * get cert to renew from auth manager
     */
    private BigInteger getCertFromAuthMgr(
        IAuthToken authToken, X509Certificate[] certContainer) 
        throws EBaseException {
        X509CertImpl cert =
            authToken.getInCert(AuthToken.TOKEN_CERT);

        if (cert == null) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_MISSING_CERTS_RENEW_FROM_AUTHMGR"));
            throw new ECMSGWException(
              CMS.getUserMessage("CMS_GW_MISSING_CERTS_RENEW_FROM_AUTHMGR"));
        }
        if (mAuthority instanceof ICertificateAuthority && 
            !isCertFromCA(cert)) {
            log(ILogger.LL_FAILURE, "certficate from auth manager for " +
                " renewal is not from this ca.");
            throw new ECMSGWException(
                  CMS.getUserMessage("CMS_GW_INVALID_CERT_FOR_RENEWAL"));
        }
        certContainer[0] = cert;
        BigInteger serialno = ((X509Certificate) cert).getSerialNumber();

        return serialno;
    }

}