summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/cert/UpdateCRL.java
blob: 52b66874f24c132006848f20b7f1f98f6bc81a36 (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
// --- 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.net.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.security.*;
import javax.servlet.*;
import javax.servlet.http.*;
import netscape.security.x509.*;
import netscape.security.util.*;
import com.netscape.certsrv.common.*;
import com.netscape.certsrv.authority.*;
import com.netscape.certsrv.base.*;

import com.netscape.cms.servlet.*;
import com.netscape.certsrv.util.*;
import com.netscape.certsrv.ca.*;
import com.netscape.certsrv.logging.*;
import com.netscape.certsrv.ldap.*;
import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.publish.*;
import com.netscape.certsrv.authentication.*;
import com.netscape.certsrv.authorization.*;


/**
 * Force the CRL to be updated now.
 *
 * @version $Revision$, $Date$
 */
public class UpdateCRL extends CMSServlet {

    private final static String INFO = "UpdateCRL";
    private final static String TPL_FILE = "updateCRL.template";

    private static Vector mTesting = new Vector();

    private String mFormPath = null;
    private ICertificateAuthority mCA = null;

    /**
     * Constructs UpdateCRL servlet.
     */
    public UpdateCRL() {
        super();
    }

    /**
     * Initializes the servlet. This servlet uses updateCRL.template
     * to render the result
     */
    public void init(ServletConfig sc) throws ServletException {
        super.init(sc);
        mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
        if (mAuthority instanceof ICertificateAuthority)
            mCA = (ICertificateAuthority) mAuthority;
		
            // override success to do output orw own template.
        mTemplates.remove(CMSRequest.SUCCESS);
        if (mOutputTemplatePath != null)
            mFormPath = mOutputTemplatePath;
    }

    /**
     * Process the HTTP request. 
     * <ul>
     * <li>http.param signatureAlgorithm the algorithm to use to sign the CRL
	 * <li>http.param waitForUpdate true/false - should the servlet wait until
	 *     the CRL update is complete?
     * <li>http.param clearCRLCache true/false - should the CRL cache cleared
     *     before the CRL is generated?
     * <li>http.param crlIssuingPoint the CRL Issuing Point to Update
     * </ul>
     * @param cmsReq the object holding the request and response information
     */
    public void process(CMSRequest cmsReq) throws EBaseException {
        HttpServletRequest req = cmsReq.getHttpReq();
        HttpServletResponse resp = cmsReq.getHttpResp();

        IStatsSubsystem statsSub = (IStatsSubsystem)CMS.getSubsystem("stats");
        if (statsSub != null) {
          statsSub.startTiming("crl", true /* main action */);
        }

        long startTime = CMS.getCurrentDate().getTime();
        IAuthToken authToken = authenticate(cmsReq);
        AuthzToken authzToken = null;

        try {
            authzToken = authorize(mAclMethod, authToken,
                        mAuthzResourceName, "update");
        } 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);
            if (statsSub != null) {
              statsSub.endTiming("crl");
            }
            return;
        }

        EBaseException error = null;

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

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

        try {
            form = getTemplate(mFormPath, req, locale);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
            if (statsSub != null) {
              statsSub.endTiming("crl");
            }
            throw new ECMSGWException(
              CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
        }

        try {
            String signatureAlgorithm = 
                req.getParameter("signatureAlgorithm");

            process(argSet, header, req, resp, 
                signatureAlgorithm, locale[0]);
        } catch (EBaseException e) {
            error = e;
        }

        try {
            ServletOutputStream out = resp.getOutputStream();

            if (error == null) {
                String xmlOutput = req.getParameter("xml");
                if (xmlOutput != null && xmlOutput.equals("true")) {
                  outputXML(resp, argSet);
                } else {
                  resp.setContentType("text/html");
                  form.renderOutput(out, argSet);
                  cmsReq.setStatus(CMSRequest.SUCCESS);
                }
            } else {
                cmsReq.setStatus(CMSRequest.ERROR);
                cmsReq.setError(error);
            }
        } catch (IOException e) {
            log(ILogger.LL_FAILURE, 
                CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
                    e.toString()));
            if (statsSub != null) {
              statsSub.endTiming("crl");
            }
            throw new ECMSGWException(
              CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
        }
        if (statsSub != null) {
          statsSub.endTiming("crl");
        }
    }

    private CRLExtensions crlEntryExtensions (String reason, String invalidity) {
        CRLExtensions entryExts = new CRLExtensions();

        CRLReasonExtension crlReasonExtn = null;
        if (reason != null && reason.length() > 0) {
            try {
                RevocationReason revReason = RevocationReason.fromInt(Integer.parseInt(reason));
                if (revReason == null) revReason = RevocationReason.UNSPECIFIED;
                crlReasonExtn = new CRLReasonExtension(revReason);
            } catch (Exception e) {
                CMS.debug("Invalid revocation reason: "+reason);
            }
        }

        InvalidityDateExtension invalidityDateExtn = null;
        if (invalidity != null && invalidity.length() > 0) {
            long now = System.currentTimeMillis();
            Date invalidityDate = null;
            try {
                long backInTime = Long.parseLong(invalidity);
                invalidityDate = new Date(now-(backInTime*60000));
            } catch (Exception e) {
                CMS.debug("Invalid invalidity time offset: "+invalidity);
            }
            if (invalidityDate != null) {
                try {
                    invalidityDateExtn = new InvalidityDateExtension(invalidityDate);
                } catch (Exception e) {
                    CMS.debug("Error creating invalidity extension: "+e);
                }
            }
        }

        if (crlReasonExtn != null) {
            try {
                entryExts.set(crlReasonExtn.getName(), crlReasonExtn);
            } catch (Exception e) {
                CMS.debug("Error adding revocation reason extension to entry extensions: "+e);
            }
        }

        if (invalidityDateExtn != null) {
            try {
                entryExts.set(invalidityDateExtn.getName(), invalidityDateExtn);
            } catch (Exception e) {
                CMS.debug("Error adding invalidity date extension to entry extensions: "+e);
            }
        }

        return entryExts;
    }

    private void addInfo(CMSTemplateParams argSet, ICRLIssuingPoint crlIssuingPoint, long cacheUpdate) {
        IArgBlock rarg = CMS.createArgBlock();

        rarg.addLongValue("cacheUpdate", cacheUpdate);

        String crlNumbers = crlIssuingPoint.getCRLNumber().toString();
        BigInteger deltaNumber = crlIssuingPoint.getDeltaCRLNumber();
        String crlSizes = "" + crlIssuingPoint.getCRLSize();
        if (deltaNumber != null && deltaNumber.compareTo(BigInteger.ZERO) > 0) {
            if (crlNumbers != null)
                crlNumbers += ",";
            if (crlNumbers != null)
                crlNumbers += deltaNumber.toString();
            if (crlSizes != null)
                crlSizes += "," + crlIssuingPoint.getDeltaCRLSize();
        }
        rarg.addStringValue("crlNumbers", crlNumbers);
        rarg.addStringValue("crlSizes", crlSizes);

        StringBuffer crlSplits = new StringBuffer();
        Vector splits = crlIssuingPoint.getSplitTimes();
        for (int i = 0; i < splits.size(); i++) {
            crlSplits.append(splits.elementAt(i));
            if (i + 1 < splits.size())
                crlSplits.append(",");
        }
        rarg.addStringValue("crlSplits", crlSplits.toString());

        argSet.addRepeatRecord(rarg);
    }

    private void process(CMSTemplateParams argSet, IArgBlock header,
        HttpServletRequest req,
        HttpServletResponse resp,
        String signatureAlgorithm,
        Locale locale)
        throws EBaseException {
        long startTime = CMS.getCurrentDate().getTime();
        String waitForUpdate = 
            req.getParameter("waitForUpdate");
        String clearCache = 
            req.getParameter("clearCRLCache");
        String crlIssuingPointId = 
            req.getParameter("crlIssuingPoint");
        String test = req.getParameter("test");
        String add = req.getParameter("add");
        String from = req.getParameter("from");
        String by = req.getParameter("by");
        String reason = req.getParameter("reason");
        String invalidity = req.getParameter("invalidity");
        String results = req.getParameter("results");

        if (crlIssuingPointId != null) {
            Enumeration ips = mCA.getCRLIssuingPoints();

            while (ips.hasMoreElements()) {
                ICRLIssuingPoint ip = (ICRLIssuingPoint) ips.nextElement();

                if (crlIssuingPointId.equals(ip.getId())) {
                    break;
                }
                if (!ips.hasMoreElements()) crlIssuingPointId = null;
            }
        }
        if (crlIssuingPointId == null) {
            crlIssuingPointId = mCA.PROP_MASTER_CRL;
        }

        ICRLIssuingPoint crlIssuingPoint = 
            mCA.getCRLIssuingPoint(crlIssuingPointId);
        header.addStringValue("crlIssuingPoint", crlIssuingPointId);
        IPublisherProcessor lpm = mCA.getPublisherProcessor();

        if (crlIssuingPoint != null) {
            if (clearCache != null && clearCache.equals("true") &&
                crlIssuingPoint.isCRLGenerationEnabled() &&
                crlIssuingPoint.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_DONE &&
                crlIssuingPoint.isCRLIssuingPointInitialized()
                                == ICRLIssuingPoint.CRL_IP_INITIALIZED) {
                crlIssuingPoint.clearCRLCache();
            }
            if (waitForUpdate != null && waitForUpdate.equals("true") &&
                crlIssuingPoint.isCRLGenerationEnabled() &&
                crlIssuingPoint.isCRLUpdateInProgress() == ICRLIssuingPoint.CRL_UPDATE_DONE &&
                crlIssuingPoint.isCRLIssuingPointInitialized()
                                == ICRLIssuingPoint.CRL_IP_INITIALIZED) {
                if (test != null && test.equals("true") &&
                    crlIssuingPoint.isCRLCacheTestingEnabled() &&
                    (!mTesting.contains(crlIssuingPointId))) {
                    CMS.debug("CRL test started.");
                    mTesting.add(crlIssuingPointId);
                    BigInteger addLen = null;
                    BigInteger startFrom = null;
                    if (add != null && add.length() > 0 &&
                        from != null && from.length() > 0) {
                        try {
                            addLen = new BigInteger(add);
                            startFrom = new BigInteger(from);
                        } catch (Exception e) {
                        }
                    }
                    if (addLen != null && startFrom != null) {
                        Date revocationDate = CMS.getCurrentDate();
                        String err = null;

                        CRLExtensions entryExts = crlEntryExtensions (reason, invalidity);

                        BigInteger serialNumber = startFrom;
                        BigInteger counter = addLen;
                        BigInteger stepBy = null;
                        if (by != null && by.length() > 0) {
                            try {
                                stepBy = new BigInteger(by);
                            } catch (Exception e) {
                            }
                        }

                        long t1 = System.currentTimeMillis();
                        long t2 = 0;
                       
                        while (counter.compareTo(BigInteger.ZERO) > 0) {
                            RevokedCertImpl revokedCert =
                                new RevokedCertImpl(serialNumber, revocationDate, entryExts);
                            crlIssuingPoint.addRevokedCert(serialNumber, revokedCert);
                            serialNumber = serialNumber.add(BigInteger.ONE);
                            counter = counter.subtract(BigInteger.ONE);

                            if ((counter.compareTo(BigInteger.ZERO) == 0) ||
                                (stepBy != null && ((counter.mod(stepBy)).compareTo(BigInteger.ZERO) == 0))) {
                                t2 = System.currentTimeMillis();
                                long t0 = t2 - t1;
                                t1 = t2;
                                try {
                                    if (signatureAlgorithm != null) {
                                        crlIssuingPoint.updateCRLNow(signatureAlgorithm);
                                    } else {
                                        crlIssuingPoint.updateCRLNow();
                                    }
                                } catch (Throwable e) {
                                    counter = BigInteger.ZERO;
                                    err = e.toString();
                                }
                                if (results != null && results.equals("1")) {
                                    addInfo(argSet, crlIssuingPoint, t0);
                                }
                            }
                        }
                        if (err != null) {
                            header.addStringValue("crlUpdate", "Failure");
                            header.addStringValue("error", err);
                        } else {
                            header.addStringValue("crlUpdate", "Success");
                        }
                    } else {
                        CMS.debug("CRL test error: missing parameters.");
                        header.addStringValue("crlUpdate", "missingParameters");
                    }

                    mTesting.remove(crlIssuingPointId);
                    CMS.debug("CRL test finished.");
                } else if (test != null && test.equals("true") &&
                           crlIssuingPoint.isCRLCacheTestingEnabled() &&
                           mTesting.contains(crlIssuingPointId)) {
                    header.addStringValue("crlUpdate", "testingInProgress");
                } else if (test != null && test.equals("true") &&
                           (!crlIssuingPoint.isCRLCacheTestingEnabled())) {
                    header.addStringValue("crlUpdate", "testingNotEnabled");
                } else {
                    try {
                        EBaseException publishError = null;

                        try {
                            long now1 = System.currentTimeMillis();

                            if (signatureAlgorithm != null) {
                                crlIssuingPoint.updateCRLNow(signatureAlgorithm);
                            } else {
                                crlIssuingPoint.updateCRLNow();
                            }

                            long now2 = System.currentTimeMillis();

                            header.addStringValue("time", "" + (now2 - now1));
                        } catch (EErrorPublishCRL e) {
                            publishError = e;
                        }

                        if (lpm != null && lpm.enabled()) {
                            Enumeration rules = lpm.getRules(IPublisherProcessor.PROP_LOCAL_CRL);
                            if (rules != null && rules.hasMoreElements()) {
                                if (publishError != null) {
                                    header.addStringValue("crlPublished", "Failure");
                                    header.addStringValue("error", publishError.toString(locale));
                                } else {
                                    header.addStringValue("crlPublished", "Success");
                                }
                            }
                        }

                        // for audit log
                        SessionContext sContext = SessionContext.getContext();
                        String agentId = (String) sContext.get(SessionContext.USER_ID);
                        IAuthToken authToken = (IAuthToken) sContext.get(SessionContext.AUTH_TOKEN);
                        String authMgr = AuditFormat.NOAUTH;
        
                        if (authToken != null) {
                            authMgr = authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
                        }
                        long endTime = CMS.getCurrentDate().getTime();

                        if (crlIssuingPoint.getNextUpdate() != null) {
                            mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, 
                                AuditFormat.LEVEL,
                                AuditFormat.CRLUPDATEFORMAT,
                                new Object[] { 
                                    AuditFormat.FROMAGENT + " agentID: " + agentId,
                                    authMgr,
                                    "completed",
                                    crlIssuingPoint.getId(),
                                    crlIssuingPoint.getCRLNumber(),
                                    crlIssuingPoint.getLastUpdate(),
                                    crlIssuingPoint.getNextUpdate(),
                                    Long.toString(crlIssuingPoint.getCRLSize()) + " time: " + (endTime - startTime)}
                            );
                        }else {
                            mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, 
                                AuditFormat.LEVEL,
                                AuditFormat.CRLUPDATEFORMAT,
                                new Object[] { 
                                    AuditFormat.FROMAGENT + " agentID: " + agentId,
                                    authMgr,
                                    "completed",
                                    crlIssuingPoint.getId(),
                                    crlIssuingPoint.getCRLNumber(),
                                    crlIssuingPoint.getLastUpdate(),
                                    "not set",
                                    Long.toString(crlIssuingPoint.getCRLSize()) + " time: " + (endTime - startTime)}
                            );
                        }
                    } catch (EBaseException e) {
                        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERR_UPDATE_CRL", e.toString()));
                        if ((lpm != null) && lpm.enabled() && (e instanceof ELdapException)) {
                            header.addStringValue("crlPublished", "Failure");
                            header.addStringValue("error", e.toString(locale));
                        } else {
                            throw e;
                        }
                    }
                }
            } else {
                if (crlIssuingPoint.isCRLIssuingPointInitialized()
                           != ICRLIssuingPoint.CRL_IP_INITIALIZED) {
                    header.addStringValue("crlUpdate", "notInitialized");
                } else if (crlIssuingPoint.isCRLUpdateInProgress()
                           != ICRLIssuingPoint.CRL_UPDATE_DONE ||
                           crlIssuingPoint.isManualUpdateSet()) {
                    header.addStringValue("crlUpdate", "inProgress");
                } else if (!crlIssuingPoint.isCRLGenerationEnabled()) {
                    header.addStringValue("crlUpdate", "Disabled");
                } else {
                    crlIssuingPoint.setManualUpdate(signatureAlgorithm);
                    header.addStringValue("crlUpdate", "Scheduled");
                }
            }
        }
        return;
    }
}