summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/key/RecoverBySerial.java
blob: 28ff30803ca454d65c99eb81b2ed37628a7422c1 (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
521
522
523
524
525
526
527
528
529
// --- 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.key;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Vector;

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

import netscape.security.x509.X509CertImpl;

import com.netscape.certsrv.apps.CMS;
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.SessionContext;
import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.security.Credential;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cmsutil.util.Cert;

/**
 * A class representing a recoverBySerial servlet.
 * 
 * @version $Revision$, $Date$
 */
public class RecoverBySerial extends CMSServlet {

    /**
     *
     */
    private static final long serialVersionUID = -4544485601409309840L;
    private final static String INFO = "recoverBySerial";
    private final static String TPL_FILE = "recoverBySerial.template";

    private final static String IN_SERIALNO = "serialNumber";
    private final static String IN_UID = "uid";
    private final static String IN_PWD = "pwd";
    private final static String IN_PASSWORD = "p12Password";
    private final static String IN_PASSWORD_AGAIN = "p12PasswordAgain";
    private final static String IN_DELIVERY = "p12Delivery";
    private final static String IN_CERT = "cert";
    private final static String IN_NICKNAME = "nickname";

    private final static String OUT_OP = "op";
    private final static String OUT_SERIALNO = IN_SERIALNO;
    private final static String OUT_RECOVERY_SUCCESS = "recoverySuccess";
    private final static String OUT_SERVICE_URL = "serviceURL";
    private final static String OUT_ERROR = "errorDetails";

    private final static String SCHEME = "scheme";
    private final static String HOST = "host";
    private final static String PORT = "port";

    private com.netscape.certsrv.kra.IKeyService mService = null;
    private String mFormPath = null;

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

    /**
     * Initializes the servlet.
     */
    public void init(ServletConfig sc) throws ServletException {
        super.init(sc);
        mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;
        mService = (com.netscape.certsrv.kra.IKeyService) mAuthority;

        mTemplates.remove(CMSRequest.SUCCESS);
        if (mOutputTemplatePath != null)
            mFormPath = mOutputTemplatePath;
    }

    /**
     * Returns serlvet information.
     */
    public String getServletInfo() {
        return INFO;
    }

    /**
     * Serves HTTP request. The format of this request is as follows:
     * recoverBySerial?
     * [serialNumber=<number>]
     * [uid#=<uid>]
     * [pwd#=<password>]
     * [localAgents=yes|null]
     * [recoveryID=recoveryID]
     * [pkcs12Password=<password of pkcs12>]
     * [pkcs12PasswordAgain=<password of pkcs12>]
     * [pkcs12Delivery=<delivery mechanism for pkcs12>]
     * [cert=<encryption certificate>]
     */
    public void process(CMSRequest cmsReq) throws EBaseException {

        HttpServletRequest req = cmsReq.getHttpReq();
        HttpServletResponse resp = cmsReq.getHttpResp();

        IAuthToken authToken = authenticate(cmsReq);
        AuthzToken authzToken = null;

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

        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()));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
        }

        cmsReq.setStatus(CMSRequest.SUCCESS);
        IArgBlock header = CMS.createArgBlock();
        IArgBlock fixed = CMS.createArgBlock();
        CMSTemplateParams argSet = new CMSTemplateParams(header, fixed);

        // set host name and port.
        HttpServletRequest httpReq = cmsReq.getHttpReq();
        String host = httpReq.getServerName();
        int port = httpReq.getServerPort();
        String scheme = httpReq.getScheme();

        fixed.set(HOST, host);
        fixed.set(PORT, Integer.valueOf(port));
        fixed.set(SCHEME, scheme);

        SessionContext ctx = null;

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

            // this information is needed within the server for
            // various signed audit log messages to report
            ctx = SessionContext.getContext();

            /*
               When Recovery is first initiated, if it is in asynch mode,
               no pkcs#12 password is needed.
               The initiating agent uid will be recorded in the recovery
               request.
               Later, as approving agents submit their approvals, they will
               also be listed in the request.
             */
            if ((initAsyncRecovery != null) &&
                    initAsyncRecovery.equalsIgnoreCase("ON")) {
                process(form, argSet, header,
                        req.getParameter(IN_SERIALNO),
                        req.getParameter(IN_CERT),
                        req, resp, locale[0]);

                int requiredNumber = mService.getNoOfRequiredAgents();
                header.addIntegerValue("noOfRequiredAgents", requiredNumber);
            } else {
                String recoveryID = req.getParameter("recoveryID");

                if (recoveryID != null && !recoveryID.equals("")) {
                    ctx.put(SessionContext.RECOVERY_ID,
                            req.getParameter("recoveryID"));
                }
                byte pkcs12[] = process(form, argSet, header,
                        req.getParameter(IN_SERIALNO),
                        req.getParameter("localAgents"),
                        req.getParameter(IN_PASSWORD),
                        req.getParameter(IN_PASSWORD_AGAIN),
                        req.getParameter(IN_CERT),
                        req.getParameter(IN_DELIVERY),
                        req.getParameter(IN_NICKNAME),
                        req, resp, locale[0]);

                if (pkcs12 != null) {
                    //resp.setStatus(HttpServletResponse.SC_OK);
                    resp.setContentType("application/x-pkcs12");
                    //resp.setContentLength(pkcs12.length);
                    resp.getOutputStream().write(pkcs12);
                    mRenderResult = false;
                    return;
                }
            }
        } catch (NumberFormatException e) {
            header.addStringValue(OUT_ERROR,
                    CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
        } catch (IOException e) {
            header.addStringValue(OUT_ERROR,
                    CMS.getUserMessage(locale[0], "CMS_BASE_INTERNAL_ERROR", e.toString()));
        } finally {
            SessionContext.releaseContext();
        }

        // return status page
        try {
            ServletOutputStream out = resp.getOutputStream();

            resp.setContentType("text/html");
            form.renderOutput(out, argSet);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE", e.toString()));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
        }

        cmsReq.setStatus(CMSRequest.SUCCESS);
    }

    /**
     * Async Key Recovery - request initiation
     */
    private void process(CMSTemplate form, CMSTemplateParams argSet,
            IArgBlock header, String seq, String cert,
            HttpServletRequest req, HttpServletResponse resp,
            Locale locale) {

        // seq is the key id
        if (seq == null) {
            header.addStringValue(OUT_ERROR, "sequence number not found");
            return;
        }
        X509CertImpl x509cert = null;

        if (cert == null || cert.trim().length() == 0) {
            header.addStringValue(OUT_ERROR, "certificate not found");
            return;
        } else {
            try {
                x509cert = Cert.mapCert(cert);
            } catch (IOException e) {
                header.addStringValue(OUT_ERROR, e.toString());
            }
        }
        if (x509cert == null) {
            header.addStringValue(OUT_ERROR, "invalid X.509 certificate");
            return;
        }

        SessionContext sContext = SessionContext.getContext();

        try {
            String reqID = mService.initAsyncKeyRecovery(
                    new BigInteger(seq), x509cert,
                      (String) sContext.get(SessionContext.USER_ID));
            header.addStringValue(OUT_SERIALNO, req.getParameter(IN_SERIALNO));
            header.addStringValue("requestID", reqID);
        } catch (EBaseException e) {
            String error =
                    "Failed to recover key for key id " +
                            seq + ".\nException: " + e.toString();

            CMS.getLogger().log(ILogger.EV_SYSTEM,
                    ILogger.S_KRA, ILogger.LL_FAILURE, error);
            try {
                ((IKeyRecoveryAuthority) mService).createError(seq, error);
            } catch (EBaseException eb) {
                CMS.getLogger().log(ILogger.EV_SYSTEM,
                        ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
            }
        }
        return;
    }

    /**
     * Recovers a key. The p12 will be protected by the password
     * provided by the administrator.
     */
    private byte[] process(CMSTemplate form, CMSTemplateParams argSet,
            IArgBlock header, String seq, String localAgents,
            String password, String passwordAgain,
            String cert, String delivery, String nickname,
            HttpServletRequest req, HttpServletResponse resp,
            Locale locale) {
        if (seq == null) {
            header.addStringValue(OUT_ERROR, "sequence number not found");
            return null;
        }
        if (password == null || password.equals("")) {
            header.addStringValue(OUT_ERROR, "PKCS12 password not found");
            return null;
        }
        if (passwordAgain == null || !passwordAgain.equals(password)) {
            header.addStringValue(OUT_ERROR, "PKCS12 password not matched");
            return null;
        }
        X509CertImpl x509cert = null;

        if (cert == null || cert.trim().length() == 0) {
            // perform recovery
            header.addStringValue(OUT_ERROR, "certificate not found");
            return null;
        } else {
            try {
                x509cert = Cert.mapCert(cert);
            } catch (IOException e) {
                header.addStringValue(OUT_ERROR, e.toString());
            }
        }
        if (x509cert == null) {
            header.addStringValue(OUT_ERROR, "invalid X.509 certificate");
            return null;
        }
        try {
            Credential creds[] = null;

            SessionContext sContext = SessionContext.getContext();
            String agent = null;

            if (sContext != null) {
                agent = (String) sContext.get(SessionContext.USER_ID);
            }
            if (CMS.getConfigStore().getBoolean("kra.keySplitting")) {
                if (localAgents == null) {
                    String recoveryID = req.getParameter("recoveryID");

                    if (recoveryID == null || recoveryID.equals("")) {
                        header.addStringValue(OUT_ERROR, "No recovery ID specified");
                        return null;
                    }
                    Hashtable<String, Object> params = mService.createRecoveryParams(recoveryID);

                    params.put("keyID", req.getParameter(IN_SERIALNO));

                    header.addStringValue("recoveryID", recoveryID);

                    params.put("agent", agent);

                    // new thread to wait for pk12
                    Thread waitThread = new WaitApprovalThread(recoveryID,
                            seq, password, x509cert, delivery, nickname,
                            SessionContext.getContext());

                    waitThread.start();
                    return null;
                } else {
                    Vector<Credential> v = new Vector<Credential>();

                    for (int i = 0; i < mService.getNoOfRequiredAgents(); i++) {
                        String uid = req.getParameter(IN_UID + i);
                        String pwd = req.getParameter(IN_PWD + i);

                        if (uid != null && pwd != null && !uid.equals("") &&
                                !pwd.equals("")) {
                            v.addElement(new Credential(uid, pwd));
                        } else {
                            header.addStringValue(OUT_ERROR, "Uid(s) or password(s) are not provided");
                            return null;
                        }
                    }
                    if (v.size() != mService.getNoOfRequiredAgents()) {
                        header.addStringValue(OUT_ERROR, "Uid(s) or password(s) are not provided");
                        return null;
                    }
                    creds = new Credential[v.size()];
                    v.copyInto(creds);
                }

                header.addStringValue(OUT_OP,
                        req.getParameter(OUT_OP));
                header.addBigIntegerValue(OUT_SERIALNO,
                        new BigInteger(seq), 10);
                header.addStringValue(OUT_SERVICE_URL,
                        req.getRequestURI());
                byte pkcs12[] = mService.doKeyRecovery(
                        new BigInteger(seq),
                        creds, password, x509cert,
                        delivery, nickname, agent);

                return pkcs12;
            } else {
                String recoveryID = req.getParameter("recoveryID");

                if (recoveryID == null || recoveryID.equals("")) {
                    header.addStringValue(OUT_ERROR, "No recovery ID specified");
                    return null;
                }
                Hashtable<String, Object> params = mService.createRecoveryParams(recoveryID);

                params.put("keyID", req.getParameter(IN_SERIALNO));

                header.addStringValue("recoveryID", recoveryID);

                params.put("agent", agent);

                // new thread to wait for pk12
                Thread waitThread = new WaitApprovalThread(recoveryID,
                        seq, password, x509cert, delivery, nickname,
                        SessionContext.getContext());

                waitThread.start();
                return null;
            }
        } catch (EBaseException e) {
            header.addStringValue(OUT_ERROR, e.toString(locale));
        } catch (Exception e) {
            header.addStringValue(OUT_ERROR, e.toString());
        }
        return null;
    }

    /**
     * Wait approval thread. Wait for recovery agents' approval
     * exit when required number of approval received
     */
    final class WaitApprovalThread extends Thread {
        String theRecoveryID = null;
        String theSeq = null;
        String thePassword = null;
        X509CertImpl theCert = null;
        String theDelivery = null;
        String theNickname = null;
        SessionContext theSc = null;

        /**
         * Wait approval thread constructor including thread name
         */
        public WaitApprovalThread(String recoveryID, String seq,
                String password, X509CertImpl cert,
                String delivery, String nickname, SessionContext sc) {
            super();
            super.setName("waitApproval." + recoveryID + "-" +
                    (Thread.activeCount() + 1));
            theRecoveryID = recoveryID;
            theSeq = seq;
            thePassword = password;
            theCert = cert;
            theDelivery = delivery;
            theNickname = nickname;
            theSc = sc;
        }

        public void run() {
            SessionContext.setContext(theSc);
            Credential creds[] = null;

            try {
                creds = mService.getDistributedCredentials(theRecoveryID);
            } catch (EBaseException e) {
                String error =
                        "Failed to get required approvals for recovery id " +
                                theRecoveryID + ".\nException: " + e.toString();

                CMS.getLogger().log(ILogger.EV_SYSTEM,
                        ILogger.S_KRA, ILogger.LL_FAILURE, error);
                try {
                    ((IKeyRecoveryAuthority) mService).createError(theRecoveryID, error);
                } catch (EBaseException eb) {
                    CMS.getLogger().log(ILogger.EV_SYSTEM,
                            ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
                }
                return;
            }

            SessionContext sContext = SessionContext.getContext();

            try {
                byte pkcs12[] = mService.doKeyRecovery(
                        new BigInteger(theSeq),
                        creds, thePassword, theCert,
                        theDelivery, theNickname,
                        (String) sContext.get(SessionContext.USER_ID));

                ((IKeyRecoveryAuthority) mService).createPk12(theRecoveryID, pkcs12);
            } catch (EBaseException e) {
                String error =
                        "Failed to recover key for recovery id " +
                                theRecoveryID + ".\nException: " + e.toString();

                CMS.getLogger().log(ILogger.EV_SYSTEM,
                        ILogger.S_KRA, ILogger.LL_FAILURE, error);
                try {
                    ((IKeyRecoveryAuthority) mService).createError(theRecoveryID, error);
                } catch (EBaseException eb) {
                    CMS.getLogger().log(ILogger.EV_SYSTEM,
                            ILogger.S_KRA, ILogger.LL_FAILURE, eb.toString());
                }
            }
            return;
        }
    }

}