summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/cert/EnrollServlet.java
blob: c48cd86353b94fe904920fc917ab5e2d9cff77b0 (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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
// --- 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.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateParsingException;
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.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import netscape.security.pkcs.PKCS10;
import netscape.security.x509.AlgorithmId;
import netscape.security.x509.CertificateAlgorithmId;
import netscape.security.x509.CertificateX509Key;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509CertInfo;
import netscape.security.x509.X509Key;

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.IConfigStore;
import com.netscape.certsrv.base.KeyGenInfo;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.ICertRecordList;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.certsrv.logging.AuditFormat;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.policy.IPolicyProcessor;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.certsrv.usrgrp.IGroup;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSGateway;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.ECMSGWException;
import com.netscape.cms.servlet.common.ICMSTemplateFiller;
import com.netscape.cms.servlet.processors.CMCProcessor;
import com.netscape.cms.servlet.processors.CRMFProcessor;
import com.netscape.cms.servlet.processors.KeyGenProcessor;
import com.netscape.cms.servlet.processors.PKCS10Processor;
import com.netscape.cms.servlet.processors.PKIProcessor;

/**
 * Submit a Certificate Enrollment request
 * 
 * @version $Revision$, $Date$
 */
public class EnrollServlet extends CMSServlet {
    /**
     *
     */
    private static final long serialVersionUID = -6983729702665630013L;

    public final static String ADMIN_ENROLL_SERVLET_ID = "caadminEnroll";

    // enrollment templates.
    public static final String ENROLL_SUCCESS_TEMPLATE = "EnrollSuccess.template";

    // http params 
    public static final String OLD_CERT_TYPE = "csrCertType";
    public static final String CERT_TYPE = "certType";
    // same as in ConfigConstant.java
    public static final String REQUEST_FORMAT = "reqFormat";
    public static final String REQUEST_FORMAT_PKCS10 = "PKCS10";
    public static final String REQUEST_FORMAT_CMC = "CMC";
    public static final String REQUEST_CONTENT = "requestContent";
    public static final String SUBJECT_KEYGEN_INFO = "subjectKeyGenInfo";
    public static final String PKCS10_REQUEST = "pkcs10Request";
    public static final String CMC_REQUEST = "cmcRequest";
    public static final String CRMF_REQUEST = "CRMFRequest";
    public static final String SUBJECT_NAME = "subject";
    public static final String CRMF_REQID = "crmfReqId";
    public static final String CHALLENGE_PASSWORD = "challengePhrase";

    private static final String CERT_AUTH_DUAL = "dual";
    private static final String CERT_AUTH_ENCRYPTION = "encryption";
    private static final String CERT_AUTH_SINGLE = "single";
    private static final String CLIENT_ISSUER = "clientIssuer";

    private boolean mAuthTokenOverride = true;
    private String mEnrollSuccessTemplate = null;
    private ICMSTemplateFiller mEnrollSuccessFiller = new ImportCertsTemplateFiller();

    ICertificateAuthority mCa = null;
    ICertificateRepository mRepository = null;

    private boolean enforcePop = false;

    private String auditServiceID = ILogger.UNIDENTIFIED;
    private final static String ADMIN_CA_ENROLLMENT_SERVLET =
            "caadminEnroll";
    private final static String AGENT_CA_BULK_ENROLLMENT_SERVLET =
            "cabulkissuance";
    private final static String AGENT_RA_BULK_ENROLLMENT_SERVLET =
            "rabulkissuance";
    private final static String EE_CA_CERT_BASED_ENROLLMENT_SERVLET =
            "cacertbasedenrollment";
    private final static String EE_CA_ENROLLMENT_SERVLET =
            "caenrollment";
    private final static String EE_RA_CERT_BASED_ENROLLMENT_SERVLET =
            "racertbasedenrollment";
    private final static String EE_RA_ENROLLMENT_SERVLET =
            "raenrollment";
    private final static byte EOL[] = { Character.LINE_SEPARATOR };
    private final static String[] SIGNED_AUDIT_AUTOMATED_REJECTION_REASON = new String[] {

    /* 0 */"automated non-profile cert request rejection:  "
            + "unable to render OLD_CERT_TYPE response",

    /* 1 */"automated non-profile cert request rejection:  "
            + "unable to complete handleEnrollAuditLog() method",

    /* 2 */"automated non-profile cert request rejection:  "
            + "unable to render success template",

    /* 3 */"automated non-profile cert request rejection:  "
            + "indeterminate reason for inability to process "
            + "cert request due to an EBaseException"
        };
    private final static String LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST =
            "LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5";
    private final static String LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED =
            "LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED_5";

    private static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----";
    private static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----";

    public EnrollServlet() {
        super();
    }

    /**
     * initialize the servlet.
     * <p>
     * the following parameters are read from the servlet config:
     * <ul>
     * <li>CMSServlet.PROP_ID - ID for signed audit log messages
     * <li>CMSServlet.PROP_SUCCESS_TEMPLATE - success template file
     * 
     * @param sc servlet configuration, read from the web.xml file
     */
    public void init(ServletConfig sc) throws ServletException {
        try {
            super.init(sc);

            CMS.debug("EnrollServlet: In Enroll Servlet init!");

            try {
                IConfigStore configStore = CMS.getConfigStore();
                String PKI_Subsystem = configStore.getString("subsystem.0.id",
                                                              null);

                // CMS 6.1 began utilizing the "Certificate Profiles" framework
                // instead of the legacy "Certificate Policies" framework.
                //
                // Beginning with CS 8.1, to meet the Common Criteria
                // evaluation performed on this version of the product, it
                // was determined that this legacy "Certificate Policies"
                // framework would be deprecated and disabled by default
                // (see Bugzilla Bug #472597).
                //
                // NOTE:  The "Certificate Policies" framework ONLY applied to
                //        to CA, KRA, and legacy RA (pre-CMS 7.0) subsystems.
                //
                //        Further, the "EnrollServlet.java" servlet is ONLY
                //        used by the CA for the following:
                //
                //        SERVLET-NAME           URL-PATTERN
                //        ====================================================
                //        caadminEnroll          ca/admin/ca/adminEnroll.html
                //        cabulkissuance         ca/agent/ca/bulkissuance.html
                //        cacertbasedenrollment  ca/certbasedenrollment.html
                //        caenrollment           ca/enrollment.html
                //
                //        The "EnrollServlet.java" servlet is NOT used by
                //        the KRA.
                //
                if (PKI_Subsystem.trim().equalsIgnoreCase("ca")) {
                    String policyStatus = PKI_Subsystem.trim().toLowerCase()
                                        + "." + "Policy"
                                        + "." + IPolicyProcessor.PROP_ENABLE;

                    if (configStore.getBoolean(policyStatus, true) == true) {
                        // NOTE:  If "<subsystem>.Policy.enable=<boolean>"
                        //        is missing, then the referenced instance
                        //        existed prior to this name=value pair
                        //        existing in its 'CS.cfg' file, and thus
                        //        we err on the side that the user may
                        //        still need to use the policy framework.
                        CMS.debug("EnrollServlet::init Certificate "
                                 + "Policy Framework (deprecated) "
                                 + "is ENABLED");
                    } else {
                        // CS 8.1 Default:  <subsystem>.Policy.enable=false
                        CMS.debug("EnrollServlet::init Certificate "
                                 + "Policy Framework (deprecated) "
                                 + "is DISABLED");
                        return;
                    }
                }
            } catch (EBaseException e) {
                throw new ServletException("EnrollServlet::init - "
                                          + "EBaseException:  "
                                          + "Unable to initialize "
                                          + "Certificate Policy Framework "
                                          + "(deprecated)");
            }

            // override success template to allow direct import of keygen certs.
            mTemplates.remove(CMSRequest.SUCCESS);

            try {
                // determine the service ID for signed audit log messages
                String id = sc.getInitParameter(CMSServlet.PROP_ID);

                if (id != null) {
                    if (!(auditServiceID.equals(
                                ADMIN_CA_ENROLLMENT_SERVLET))
                            && !(auditServiceID.equals(
                                    AGENT_CA_BULK_ENROLLMENT_SERVLET))
                            && !(auditServiceID.equals(
                                    AGENT_RA_BULK_ENROLLMENT_SERVLET))
                            && !(auditServiceID.equals(
                                    EE_CA_CERT_BASED_ENROLLMENT_SERVLET))
                            && !(auditServiceID.equals(
                                    EE_CA_ENROLLMENT_SERVLET))
                            && !(auditServiceID.equals(
                                    EE_RA_CERT_BASED_ENROLLMENT_SERVLET))
                            && !(auditServiceID.equals(
                                    EE_RA_ENROLLMENT_SERVLET))) {
                        auditServiceID = ILogger.UNIDENTIFIED;
                    } else {
                        auditServiceID = id.trim();
                    }
                }

                mEnrollSuccessTemplate = sc.getInitParameter(
                            CMSServlet.PROP_SUCCESS_TEMPLATE);
                if (mEnrollSuccessTemplate == null)
                    mEnrollSuccessTemplate = ENROLL_SUCCESS_TEMPLATE;
                String fillername = sc.getInitParameter(
                        PROP_SUCCESS_TEMPLATE_FILLER);

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

                    if (filler != null)
                        mEnrollSuccessFiller = filler;
                }

                // cfu
                mCa = (ICertificateAuthority) CMS.getSubsystem("ca");

                init_testbed_hack(mConfig);
            } catch (Exception e) {
                // this should never happen. 
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSGW_IMP_INIT_SERV_ERR",
                                e.toString(), mId));
            }
        } catch (ServletException eAudit1) {
            // rethrow caught exception
            throw eAudit1;
        }
    }

    /**
     * XXX (SHOULD CHANGE TO READ FROM Servletconfig)
     * Getter method to see if Proof of Posession checking is enabled.
     * this value is set in the CMS.cfg filem with the parameter
     * "enrollment.enforcePop". It defaults to false
     * 
     * @return true if user is required to Prove that they possess the
     *         private key corresponding to the public key in the certificate
     *         request they are submitting
     */
    public boolean getEnforcePop() {
        return enforcePop;
    }

    /**
     * Process the HTTP request.
     * <UL>
     * <LI>If the request is coming through the admin port, it is only allowed to continue if 'admin enrollment' is
     * enabled in the CMS.cfg file
     * <LI>If the CMS.cfg parameter useThreadNaming is true, the current thread is renamed with more information about
     * the current request ID
     * <LI>The request is preprocessed, then processed further in one of the cert request processor classes:
     * KeyGenProcessor, PKCS10Processor, CMCProcessor, CRMFProcessor
     * </UL>
     * 
     * @param cmsReq the object holding the request and response information
     */
    protected void process(CMSRequest cmsReq)
            throws EBaseException {
        // SPECIAL CASE:
        // if it is adminEnroll servlet,check if it's enabled
        if (mId.equals(ADMIN_ENROLL_SERVLET_ID) &&
                !CMSGateway.getEnableAdminEnroll()) {
            log(ILogger.LL_SECURITY,
                    CMS.getLogMessage("ADMIN_SRVLT_ENROLL_ACCESS_AFTER_SETUP"));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_REDIRECTING_ADMINENROLL_ERROR",
                            "Attempt to access adminEnroll after already setup."));
        }

        processX509(cmsReq);
    }

    private boolean getCertAuthEnrollStatus(IArgBlock httpParams) {

        /*
         * === certAuth based enroll ===
         * "certAuthEnroll" is on.
         * "certauthEnrollType can be one of the three:
         *               single - it's for single cert enrollment
         *               dual - it's for dual certs enrollment
         *               encryption - getting the encryption cert only via
         *                    authentication of the signing cert
         *                    (crmf or keyGenInfo)
         */
        boolean certAuthEnroll = false;

        String certAuthEnrollOn =
                httpParams.getValueAsString("certauthEnroll", null);

        if ((certAuthEnrollOn != null) && (certAuthEnrollOn.equals("on"))) {
            certAuthEnroll = true;
            CMS.debug("EnrollServlet: certAuthEnroll is on");
        }

        return certAuthEnroll;

    }

    private String getCertAuthEnrollType(IArgBlock httpParams, boolean certAuthEnroll)
            throws EBaseException {

        String certauthEnrollType = null;

        if (certAuthEnroll == true) {
            certauthEnrollType =
                    httpParams.getValueAsString("certauthEnrollType", null);
            if (certauthEnrollType != null) {
                if (certauthEnrollType.equals("dual")) {
                    CMS.debug("EnrollServlet: certauthEnrollType is dual");
                } else if (certauthEnrollType.equals("encryption")) {
                    CMS.debug("EnrollServlet: certauthEnrollType is encryption");
                } else if (certauthEnrollType.equals("single")) {
                    CMS.debug("EnrollServlet: certauthEnrollType is single");
                } else {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_INVALID_CERTAUTH_ENROLL_TYPE_1", certauthEnrollType));
                    throw new ECMSGWException(
                            CMS.getUserMessage("CMS_GW_INVALID_CERTAUTH_ENROLL_TYPE"));
                }
            } else {
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("MSGW_MISSING_CERTAUTH_ENROLL_TYPE"));
                throw new ECMSGWException(
                        CMS.getUserMessage("CMS_GW_MISSING_CERTAUTH_ENROLL_TYPE"));
            }
        }

        return certauthEnrollType;

    }

    private boolean checkClientCertSigningOnly(X509Certificate sslClientCert)
            throws EBaseException {
        if ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
                false) ||
                ((CMS.isSigningCert((X509CertImpl) sslClientCert) ==
                    true) &&
                (CMS.isEncryptionCert((X509CertImpl) sslClientCert) ==
                    true))) {

            // either it's not a signing cert, or it's a dual cert
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_INVALID_CERT_TYPE"));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_INVALID_CERT_TYPE"));
        }

        return true;
    }

    private X509CertInfo[] handleCertAuthDual(X509CertInfo certInfo, IAuthToken authToken,
            X509Certificate sslClientCert,
            ICertificateAuthority mCa, String certBasedOldSubjectDN,
            BigInteger certBasedOldSerialNum)
            throws EBaseException {

        CMS.debug("EnrollServlet: In handleCertAuthDual!");

        if (mCa == null) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_NOT_A_CA"));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_NOT_A_CA"));
        }

        // first, make sure the client cert is indeed a
        // signing only cert

        try {

            checkClientCertSigningOnly(sslClientCert);
        } catch (ECMSGWException e) {

            throw new ECMSGWException(e.toString());

        }

        X509Key key = null;

        // for signing cert
        key = (X509Key) sslClientCert.getPublicKey();
        try {
            certInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
        } catch (CertificateException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
        } catch (IOException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_IO", e.toString()));
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
        }

        String filter =
                "(&(x509cert.subject="
                        + certBasedOldSubjectDN + ")(!(x509cert.serialNumber=" + certBasedOldSerialNum
                        + "))(certStatus=VALID))";
        ICertRecordList list =
                (ICertRecordList) mCa.getCertificateRepository().findCertRecordsInList(filter, null, 10);
        int size = list.getSize();
        Enumeration<ICertRecord> en = list.getCertRecords(0, size - 1);
        boolean gotEncCert = false;

        CMS.debug("EnrollServlet: signing cert filter " + filter);

        if (!en.hasMoreElements()) {
            CMS.debug("EnrollServlet: pairing encryption cert not found!");
            return null;
            // pairing encryption cert not found
        } else {
            X509CertInfo encCertInfo = CMS.getDefaultX509CertInfo();
            X509CertInfo[] cInfoArray = new X509CertInfo[] { certInfo,
                    encCertInfo };
            int i = 1;

            boolean encCertFound = false;

            while (en.hasMoreElements()) {
                ICertRecord record = en.nextElement();
                X509CertImpl cert = record.getCertificate();

                // if not encryption cert only, try next one
                if ((CMS.isEncryptionCert(cert) == false) ||
                        ((CMS.isEncryptionCert(cert) == true) &&
                        (CMS.isSigningCert(cert) == true))) {

                    CMS.debug("EnrollServlet: Not encryption only cert, will try next one.");
                    continue;
                }

                key = (X509Key) cert.getPublicKey();
                CMS.debug("EnrollServlet: Found key for encryption cert.");
                encCertFound = true;

                try {
                    encCertInfo = (X509CertInfo)
                            cert.get(
                                    X509CertImpl.NAME + "." + X509CertImpl.INFO);

                } catch (CertificateParsingException ex) {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_MISSING_CERTINFO_ENCRYPT_CERT"));
                    throw new ECMSGWException(
                            CMS.getUserMessage("CMS_GW_MISSING_CERTINFO"));
                }

                try {
                    encCertInfo.set(X509CertInfo.KEY, new CertificateX509Key(key));
                } catch (CertificateException e) {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
                    throw new ECMSGWException(
                            CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
                } catch (IOException e) {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_FAILED_SET_KEY_FROM_CERT_AUTH_ENROLL_1", e.toString()));
                    throw new ECMSGWException(
                            CMS.getUserMessage("CMS_GW_SET_KEY_FROM_CERT_AUTH_ENROLL_FAILED", e.toString()));
                }

                CMS.debug("EnrollServlet: About to fillCertInfoFromAuthToken!");
                PKIProcessor.fillCertInfoFromAuthToken(encCertInfo, authToken);

                cInfoArray[i++] = encCertInfo;
                break;

            }
            if (encCertFound == false) {
                CMS.debug("EnrollServlet: Leaving because Enc Cert not found.");
                return null;
            }

            CMS.debug("EnrollServlet: returning cInfoArray of length " + cInfoArray.length);
            return cInfoArray;
        }

    }

    private boolean handleEnrollAuditLog(IRequest req, CMSRequest cmsReq, String authMgr, IAuthToken authToken,
            X509CertInfo certInfo, long startTime)
            throws EBaseException {
        //for audit log

        String initiative = null;
        String agentID = null;

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

        // if service not complete return standard templates.
        RequestStatus status = req.getRequestStatus();

        if (status != RequestStatus.COMPLETE) {
            cmsReq.setIRequestStatus(); // set status acc. to IRequest status.
            // audit log the status
            try {
                if (status == RequestStatus.REJECTED) {
                    Vector<String> messages = req.getExtDataInStringVector(IRequest.ERRORS);

                    if (messages != null) {
                        Enumeration<String> 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.ENROLLMENTFORMAT,
                                new Object[] {
                                        req.getRequestId(),
                                        initiative,
                                        authMgr,
                                        status.toString(),
                                        certInfo.get(X509CertInfo.SUBJECT),
                                        " violation: " +
                                                wholeMsg.toString() }
                                );
                    } else { // no policy violation, from agent
                        mLogger.log(ILogger.EV_AUDIT,
                                ILogger.S_OTHER,
                                AuditFormat.LEVEL,
                                AuditFormat.ENROLLMENTFORMAT,
                                new Object[] {
                                        req.getRequestId(),
                                        initiative,
                                        authMgr,
                                        status.toString(),
                                        certInfo.get(X509CertInfo.SUBJECT), "" }
                                );
                    }
                } else { // other imcomplete status
                    long endTime = CMS.getCurrentDate().getTime();

                    mLogger.log(ILogger.EV_AUDIT,
                            ILogger.S_OTHER,
                            AuditFormat.LEVEL,
                            AuditFormat.ENROLLMENTFORMAT,
                            new Object[] {
                                    req.getRequestId(),
                                    initiative,
                                    authMgr,
                                    status.toString(),
                                    certInfo.get(X509CertInfo.SUBJECT) + " time: " + (endTime - startTime), "" }
                            );
                }
            } catch (IOException e) {
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
                                e.toString()));
            } catch (CertificateException e) {
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
                                e.toString()));
            }
            return false;
        }
        // if service error use standard error templates.
        Integer result = req.getExtDataInInteger(IRequest.RESULT);

        if (result.equals(IRequest.RES_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);
                        // audit log the error
                        try {
                            mLogger.log(ILogger.EV_AUDIT,
                                    ILogger.S_OTHER,
                                    AuditFormat.LEVEL,
                                    AuditFormat.ENROLLMENTFORMAT,
                                    new Object[] {
                                            req.getRequestId(),
                                            initiative,
                                            authMgr,
                                            "completed with error: " +
                                                    err,
                                            certInfo.get(X509CertInfo.SUBJECT), ""
                                }
                                    );
                        } catch (IOException e) {
                            log(ILogger.LL_FAILURE,
                                    CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
                                            e.toString()));
                        } catch (CertificateException e) {
                            log(ILogger.LL_FAILURE,
                                    CMS.getLogMessage("CMSGW_CANT_GET_CERT_SUBJ_AUDITING",
                                            e.toString()));
                        }

                    }
                }
            }
            return false;

        }

        return true;

    }

    /**
     * Process X509 certificate enrollment request
     * <P>
     * 
     * (Certificate Request - either an "admin" cert request for an admin certificate, an "agent" cert request for
     * "bulk enrollment", or an "EE" standard cert request)
     * <P>
     * 
     * (Certificate Request Processed - either an automated "admin" non-profile based CA admin cert acceptance, an
     * automated "admin" non-profile based CA admin cert rejection, an automated "EE" non-profile based cert acceptance,
     * or an automated "EE" non-profile based cert rejection)
     * <P>
     * 
     * <ul>
     * <li>signed.audit LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST used when a non-profile cert request is made
     * (before approval process)
     * <li>signed.audit LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED used when a certificate request has just been
     * through the approval process
     * </ul>
     * 
     * @param cmsReq a certificate enrollment request
     * @exception EBaseException an error has occurred
     */
    protected void processX509(CMSRequest cmsReq)
            throws EBaseException {
        String auditMessage = null;
        String auditSubjectID = auditSubjectID();
        String auditRequesterID = ILogger.UNIDENTIFIED;
        String auditCertificateSubjectName = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
        String id = null;

        // define variables common to try-catch-blocks
        long startTime = 0;
        IArgBlock httpParams = null;
        HttpServletRequest httpReq = null;
        IAuthToken authToken = null;
        AuthzToken authzToken = null;
        IRequest req = null;
        X509CertInfo certInfo = null;

        IConfigStore configStore = CMS.getConfigStore();

        /* XXX shouldn't we read this from ServletConfig at init time? */
        enforcePop = configStore.getBoolean("enrollment.enforcePop", false);
        CMS.debug("EnrollServlet: enforcePop " + enforcePop);

        // ensure that any low-level exceptions are reported
        // to the signed audit log and stored as failures
        try {
            startTime = CMS.getCurrentDate().getTime();
            httpParams = cmsReq.getHttpParams();
            httpReq = cmsReq.getHttpReq();
            if (mAuthMgr != null) {
                authToken = authenticate(cmsReq);
            }

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

                // store a message in the signed audit log file
                // (either an "admin" cert request for an admin certificate,
                //  an "agent" cert request for "bulk enrollment", or
                //  an "EE" standard cert request)
                auditMessage = CMS.getLogMessage(
                            LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                            auditSubjectID,
                            ILogger.FAILURE,
                            auditRequesterID,
                            auditServiceID,
                            auditCertificateSubjectName);

                audit(auditMessage);

                return;
            }

            // create enrollment request in request queue.
            req = mRequestQueue.newRequest(IRequest.ENROLLMENT_REQUEST);

            // retrieve the actual "auditRequesterID"
            if (req != null) {
                // overwrite "auditRequesterID" if and only if "id" != null
                id = req.getRequestId().toString();
                if (id != null) {
                    auditRequesterID = id.trim();
                }
            }

            try {
                if (CMS.getConfigStore().getBoolean("useThreadNaming", false)) {
                    String currentName = Thread.currentThread().getName();

                    Thread.currentThread().setName(currentName
                            + "-request-"
                            + req.getRequestId().toString()
                            + "-"
                            + (new Date()).getTime());
                }
            } catch (Exception e) {
            }

            /*
             * === certAuth based enroll ===
             * "certAuthEnroll" is on.
             * "certauthEnrollType can be one of the three:
             *       single - it's for single cert enrollment 
             *       dual - it's for dual certs enrollment
             *       encryption - getting the encryption cert only via
             *                    authentication of the signing cert
             *                    (crmf or keyGenInfo)
             */
            boolean certAuthEnroll = false;
            String certauthEnrollType = null;

            certAuthEnroll = getCertAuthEnrollStatus(httpParams);

            try {
                if (certAuthEnroll == true) {
                    certauthEnrollType = getCertAuthEnrollType(httpParams,
                                certAuthEnroll);
                }
            } catch (ECMSGWException e) {
                // store a message in the signed audit log file
                // (either an "admin" cert request for an admin certificate,
                //  an "agent" cert request for "bulk enrollment", or
                //  an "EE" standard cert request)
                auditMessage = CMS.getLogMessage(
                            LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                            auditSubjectID,
                            ILogger.FAILURE,
                            auditRequesterID,
                            auditServiceID,
                            auditCertificateSubjectName);

                audit(auditMessage);

                throw new ECMSGWException(e.toString());
            }

            CMS.debug("EnrollServlet: In EnrollServlet.processX509!");
            CMS.debug("EnrollServlet: certAuthEnroll " + certAuthEnroll);
            CMS.debug("EnrollServlet: certauthEnrollType " + certauthEnrollType);

            String challengePassword = httpParams.getValueAsString(
                    "challengePassword", "");

            cmsReq.setIRequest(req);
            saveHttpHeaders(httpReq, req);
            saveHttpParams(httpParams, req);

            X509Certificate sslClientCert = null;

            // cert auth enroll
            String certBasedOldSubjectDN = null;
            BigInteger certBasedOldSerialNum = null;

            // check if request was authenticated, if so set authtoken &
            // certInfo.  also if authenticated, take certInfo from authToken.
            certInfo = null;
            if (certAuthEnroll == true) {
                sslClientCert = getSSLClientCertificate(httpReq);
                if (sslClientCert == null) {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_MISSING_SSL_CLIENT_CERT"));

                    // store a message in the signed audit log file
                    // (either an "admin" cert request for an admin certificate,
                    //  an "agent" cert request for "bulk enrollment", or
                    //  an "EE" standard cert request)
                    auditMessage = CMS.getLogMessage(
                                LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                auditSubjectID,
                                ILogger.FAILURE,
                                auditRequesterID,
                                auditServiceID,
                                auditCertificateSubjectName);

                    audit(auditMessage);

                    throw new ECMSGWException(
                            CMS.getUserMessage("CMS_GW_MISSING_SSL_CLIENT_CERT"));
                }

                certBasedOldSubjectDN = (String)
                        sslClientCert.getSubjectDN().toString();
                certBasedOldSerialNum = (BigInteger)
                        sslClientCert.getSerialNumber();

                CMS.debug("EnrollServlet: certBasedOldSubjectDN " + certBasedOldSubjectDN);
                CMS.debug("EnrollServlet: certBasedOldSerialNum " + certBasedOldSerialNum);

                // if the cert subject name is NOT MISSING, retrieve the
                // actual "auditCertificateSubjectName" and "normalize" it
                if (certBasedOldSubjectDN != null) {
                    // NOTE:  This is ok even if the cert subject name
                    //        is "" (empty)!
                    auditCertificateSubjectName = certBasedOldSubjectDN.trim();
                }

                try {
                    certInfo = (X509CertInfo)
                            ((X509CertImpl) sslClientCert).get(
                                    X509CertImpl.NAME + "." + X509CertImpl.INFO);
                } catch (CertificateParsingException ex) {
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_MISSING_CERTINFO"));

                    // store a message in the signed audit log file
                    // (either an "admin" cert request for an admin certificate,
                    //  an "agent" cert request for "bulk enrollment", or
                    //  an "EE" standard cert request)
                    auditMessage = CMS.getLogMessage(
                                LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                auditSubjectID,
                                ILogger.FAILURE,
                                auditRequesterID,
                                auditServiceID,
                                auditCertificateSubjectName);

                    audit(auditMessage);

                    throw new ECMSGWException(
                            CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_CERTINFO"));
                }
            } else {
                CMS.debug("EnrollServlet: No CertAuthEnroll.");
                certInfo = CMS.getDefaultX509CertInfo();
            }

            X509CertInfo[] certInfoArray = new X509CertInfo[] { certInfo };

            X509CertInfo authCertInfo = null;
            String authMgr = AuditFormat.NOAUTH;

            // if authentication
            if (authToken != null) {
                authMgr =
                        authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME);
                // don't store agent token in request. 
                // agent currently used for bulk issuance. 
                // if (!authMgr.equals(AuthSubsystem.CERTUSERDB_AUTHMGR_ID)) {
                log(ILogger.LL_INFO,
                        "Enrollment request was authenticated by " +
                                authToken.getInString(AuthToken.TOKEN_AUTHMGR_INST_NAME));

                PKIProcessor.fillCertInfoFromAuthToken(certInfo,
                        authToken);
                // save authtoken attrs to request directly
                // (for policy use)
                saveAuthToken(authToken, req);
                // req.set(IRequest.AUTH_TOKEN, authToken);
                // }
            }

            CMS.debug("EnrollServlet: Enroll authMgr " + authMgr);

            if (certAuthEnroll == true) {
                // log(ILogger.LL_DEBUG,
                //     "just gotten subjectDN and serialNumber " +
                //     "from ssl client cert");
                if (authToken == null) {
                    // authToken is null, can't match to anyone; bail!
                    log(ILogger.LL_FAILURE,
                            CMS.getLogMessage("CMSGW_ERR_PROCESS_ENROLL_NO_AUTH"));

                    // store a message in the signed audit log file
                    // (either an "admin" cert request for an admin certificate,
                    //  an "agent" cert request for "bulk enrollment", or
                    //  an "EE" standard cert request)
                    auditMessage = CMS.getLogMessage(
                                LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                auditSubjectID,
                                ILogger.FAILURE,
                                auditRequesterID,
                                auditServiceID,
                                auditCertificateSubjectName);

                    audit(auditMessage);

                    return;
                }
            }

            // fill certInfo from input types: keygen, cmc, pkcs10 or crmf
            KeyGenInfo keyGenInfo = httpParams.getValueAsKeyGenInfo(
                    SUBJECT_KEYGEN_INFO, null);
            PKCS10 pkcs10 = null;

            String certType = null;

            //
            String test = httpParams.getValueAsString("certNickname", null);

            // support Enterprise 3.5.1 server where CERT_TYPE=csrCertType
            // instead of certType
            certType = httpParams.getValueAsString(OLD_CERT_TYPE, null);
            CMS.debug("EnrollServlet: certType " + certType);

            if (certType == null) {
                certType = httpParams.getValueAsString(CERT_TYPE, "client");
                CMS.debug("EnrollServlet: certType " + certType);
            } else {
                // some policies may rely on the fact that
                // CERT_TYPE is set. So for 3.5.1 or eariler
                // we need to set CERT_TYPE here.
                req.setExtData(IRequest.HTTP_PARAMS, CERT_TYPE, certType);
            }
            if (certType.equals("client")) {
                // coming from MSIE
                String p10b64 = httpParams.getValueAsString(PKCS10_REQUEST,
                        null);

                if (p10b64 != null) {
                    try {
                        byte[] bytes = CMS.AtoB(p10b64);

                        pkcs10 = new PKCS10(bytes);
                    } catch (Exception e) {
                        // ok, if the above fails, it could
                        // be a PKCS10 with header
                        pkcs10 = httpParams.getValueAsPKCS10(PKCS10_REQUEST,
                                    false, null);
                        // e.printStackTrace();
                    }
                }

                //pkcs10 = httpParams.getValuePKCS10(PKCS10_REQUEST, null);

            } else {
                try {
                    // coming from server cut & paste blob.
                    pkcs10 = httpParams.getValueAsPKCS10(PKCS10_REQUEST,
                                false, null);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            String cmc = null;
            String asciiBASE64Blob = httpParams.getValueAsString(CMC_REQUEST, null);

            if (asciiBASE64Blob != null) {
                int startIndex = asciiBASE64Blob.indexOf(HEADER);
                int endIndex = asciiBASE64Blob.indexOf(TRAILER);
                if (startIndex != -1 && endIndex != -1) {
                    startIndex = startIndex + HEADER.length();
                    cmc = asciiBASE64Blob.substring(startIndex, endIndex);
                } else
                    cmc = asciiBASE64Blob;
                CMS.debug("EnrollServlet: cmc " + cmc);
            }

            String crmf = httpParams.getValueAsString(CRMF_REQUEST, null);

            CMS.debug("EnrollServlet: crmf " + crmf);

            if (certAuthEnroll == true) {

                PKIProcessor.fillCertInfoFromAuthToken(certInfo, authToken);

                // for dual certs
                if (certauthEnrollType.equals(CERT_AUTH_DUAL)) {

                    CMS.debug("EnrollServlet: Attempting CERT_AUTH_DUAL");
                    boolean gotEncCert = false;
                    X509CertInfo[] cInfoArray = null;

                    try {
                        cInfoArray = handleCertAuthDual(certInfo, authToken,
                                    sslClientCert, mCa,
                                    certBasedOldSubjectDN,
                                    certBasedOldSerialNum);
                    } catch (ECMSGWException e) {
                        // store a message in the signed audit log file
                        // (either an "admin" cert request for an admin
                        //  certificate, an "agent" cert request for
                        //  "bulk enrollment", or an "EE" standard cert request)
                        auditMessage = CMS.getLogMessage(
                                    LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditServiceID,
                                    auditCertificateSubjectName);

                        audit(auditMessage);

                        throw new ECMSGWException(e.toString());
                    }

                    if (cInfoArray != null && cInfoArray.length != 0) {
                        CMS.debug("EnrollServlet: cInfoArray Length " + cInfoArray.length);

                        certInfoArray = cInfoArray;
                        gotEncCert = true;
                    }

                    if (gotEncCert == false) {
                        // encryption cert not found, bail
                        log(ILogger.LL_FAILURE,
                                CMS.getLogMessage(
                                        "CMSGW_ENCRYPTION_CERT_NOT_FOUND"));

                        // store a message in the signed audit log file
                        // (either an "admin" cert request for an admin
                        //  certificate, an "agent" cert request for
                        //  "bulk enrollment", or an "EE" standard cert request)
                        auditMessage = CMS.getLogMessage(
                                    LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditServiceID,
                                    auditCertificateSubjectName);

                        audit(auditMessage);

                        throw new ECMSGWException(
                                CMS.getUserMessage("CMS_GW_ENCRYPTION_CERT_NOT_FOUND"));
                    }

                } else if (certauthEnrollType.equals(CERT_AUTH_ENCRYPTION)) {

                    // first, make sure the client cert is indeed a
                    // signing only cert

                    try {

                        checkClientCertSigningOnly(sslClientCert);
                    } catch (ECMSGWException e) {
                        // store a message in the signed audit log file
                        // (either an "admin" cert request for an admin
                        //  certificate, an "agent" cert request for
                        //  "bulk enrollment", or an "EE" standard cert request)
                        auditMessage = CMS.getLogMessage(
                                    LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditServiceID,
                                    auditCertificateSubjectName);

                        audit(auditMessage);

                        throw new ECMSGWException(e.toString());
                    }

                    /*
                     * either crmf or keyGenInfo
                     */
                    if (keyGenInfo != null) {
                        KeyGenProcessor keyGenProc = new KeyGenProcessor(cmsReq,
                                this);

                        keyGenProc.fillCertInfo(null, certInfo,
                                authToken, httpParams);

                        req.setExtData(CLIENT_ISSUER,
                                sslClientCert.getIssuerDN().toString());
                        CMS.debug("EnrollServlet: sslClientCert issuerDN = " +
                                sslClientCert.getIssuerDN().toString());
                    } else if (crmf != null && crmf != "") {
                        CRMFProcessor crmfProc = new CRMFProcessor(cmsReq, this, enforcePop);

                        certInfoArray = crmfProc.fillCertInfoArray(crmf,
                                    authToken,
                                    httpParams,
                                    req);

                        req.setExtData(CLIENT_ISSUER,
                                sslClientCert.getIssuerDN().toString());
                        CMS.debug("EnrollServlet: sslClientCert issuerDN = " +
                                sslClientCert.getIssuerDN().toString());
                    } else {
                        log(ILogger.LL_FAILURE,
                                CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
                                        CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));

                        // store a message in the signed audit log file
                        // (either an "admin" cert request for an admin
                        //  certificate, an "agent" cert request for
                        //  "bulk enrollment", or an "EE" standard cert request)
                        auditMessage = CMS.getLogMessage(
                                    LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditServiceID,
                                    auditCertificateSubjectName);

                        audit(auditMessage);

                        throw new ECMSGWException(
                                CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
                    }

                } else if (certauthEnrollType.equals(CERT_AUTH_SINGLE)) {

                    // have to be buried here to handle the issuer

                    if (keyGenInfo != null) {
                        KeyGenProcessor keyGenProc = new KeyGenProcessor(cmsReq,
                                this);

                        keyGenProc.fillCertInfo(null, certInfo,
                                authToken, httpParams);
                    } else if (pkcs10 != null) {
                        PKCS10Processor pkcs10Proc = new PKCS10Processor(cmsReq,
                                this);

                        pkcs10Proc.fillCertInfo(pkcs10, certInfo,
                                authToken, httpParams);
                    } else if (cmc != null && cmc != "") {
                        CMCProcessor cmcProc = new CMCProcessor(cmsReq, this, enforcePop);

                        certInfoArray = cmcProc.fillCertInfoArray(cmc,
                                    authToken,
                                    httpParams,
                                    req);
                    } else if (crmf != null && crmf != "") {
                        CRMFProcessor crmfProc = new CRMFProcessor(cmsReq, this, enforcePop);

                        certInfoArray = crmfProc.fillCertInfoArray(crmf,
                                    authToken,
                                    httpParams,
                                    req);
                    } else {
                        log(ILogger.LL_FAILURE,
                                CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
                                        CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));

                        // store a message in the signed audit log file
                        // (either an "admin" cert request for an admin
                        //  certificate, an "agent" cert request for
                        //  "bulk enrollment", or an "EE" standard cert request)
                        auditMessage = CMS.getLogMessage(
                                    LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditServiceID,
                                    auditCertificateSubjectName);

                        audit(auditMessage);

                        throw new ECMSGWException(
                                CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
                    }
                    req.setExtData(CLIENT_ISSUER,
                            sslClientCert.getIssuerDN().toString());
                }

            } else if (keyGenInfo != null) {

                CMS.debug("EnrollServlet: Trying KeyGen with no cert auth.");
                KeyGenProcessor keyGenProc = new KeyGenProcessor(cmsReq, this);

                keyGenProc.fillCertInfo(null, certInfo, authToken, httpParams);
            } else if (pkcs10 != null) {
                CMS.debug("EnrollServlet: Trying PKCS10 with no cert auth.");
                PKCS10Processor pkcs10Proc = new PKCS10Processor(cmsReq, this);

                pkcs10Proc.fillCertInfo(pkcs10, certInfo, authToken, httpParams);
            } else if (cmc != null) {
                CMS.debug("EnrollServlet: Trying CMC with no cert auth.");
                CMCProcessor cmcProc = new CMCProcessor(cmsReq, this, enforcePop);

                certInfoArray = cmcProc.fillCertInfoArray(cmc, authToken,
                            httpParams, req);
            } else if (crmf != null && crmf != "") {
                CMS.debug("EnrollServlet: Trying CRMF with no cert auth.");
                CRMFProcessor crmfProc = new CRMFProcessor(cmsReq, this, enforcePop);

                certInfoArray = crmfProc.fillCertInfoArray(crmf, authToken,
                            httpParams, req);
            } else {
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSGW_CANT_PROCESS_ENROLL_REQ") +
                                CMS.getLogMessage("CMSGW_MISSING_KEYGEN_INFO"));

                // store a message in the signed audit log file
                // (either an "admin" cert request for an admin certificate,
                //  an "agent" cert request for "bulk enrollment", or
                //  an "EE" standard cert request)
                auditMessage = CMS.getLogMessage(
                            LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                            auditSubjectID,
                            ILogger.FAILURE,
                            auditRequesterID,
                            auditServiceID,
                            auditCertificateSubjectName);

                audit(auditMessage);

                throw new ECMSGWException(CMS.getUserMessage(getLocale(httpReq), "CMS_GW_MISSING_KEYGEN_INFO"));
            }

            // if ca, fill in default signing alg here

            try {
                ICertificateAuthority caSub =
                        (ICertificateAuthority) CMS.getSubsystem("ca");
                if (certInfoArray != null && caSub != null) {
                    for (int ix = 0; ix < certInfoArray.length; ix++) {
                        X509CertInfo ci = (X509CertInfo) certInfoArray[ix];
                        String defaultSig = caSub.getDefaultAlgorithm();
                        AlgorithmId algid = AlgorithmId.get(defaultSig);
                        ci.set(X509CertInfo.ALGORITHM_ID,
                                new CertificateAlgorithmId(algid));
                    }
                }
            } catch (Exception e) {
                CMS.debug("Failed to set signing alg to certinfo " + e.toString());
            }

            req.setExtData(IRequest.CERT_INFO, certInfoArray);

            if (challengePassword != null && !challengePassword.equals("")) {
                String pwd = hashPassword(challengePassword);

                req.setExtData(CHALLENGE_PASSWORD, pwd);
            }

            // store a message in the signed audit log file
            // (either an "admin" cert request for an admin certificate,
            //  an "agent" cert request for "bulk enrollment", or
            //  an "EE" standard cert request)
            auditMessage = CMS.getLogMessage(
                        LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                        auditSubjectID,
                        ILogger.SUCCESS,
                        auditRequesterID,
                        auditServiceID,
                        auditCertificateSubjectName);

            audit(auditMessage);

        } catch (EBaseException eAudit1) {
            // store a message in the signed audit log file
            // (either an "admin" cert request for an admin certificate,
            //  an "agent" cert request for "bulk enrollment", or
            //  an "EE" standard cert request)
            auditMessage = CMS.getLogMessage(
                        LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST,
                        auditSubjectID,
                        ILogger.FAILURE,
                        auditRequesterID,
                        auditServiceID,
                        auditCertificateSubjectName);

            audit(auditMessage);

            throw eAudit1;
        }

        X509CertImpl[] issuedCerts = null;

        // ensure that any low-level exceptions are reported
        // to the signed audit log and stored as failures
        try {
            // send request to request queue. 
            mRequestQueue.processRequest(req);
            // process result. 

            // render OLD_CERT_TYPE's response differently, we
            // do not want any javascript in HTML, and need to
            // override the default render.
            if (httpParams.getValueAsString(OLD_CERT_TYPE, null) != null) {
                try {
                    renderServerEnrollResult(cmsReq);
                    cmsReq.setStatus(CMSRequest.SUCCESS); // no default render

                    issuedCerts =
                            cmsReq.getIRequest().getExtDataInCertArray(
                                    IRequest.ISSUED_CERTS);

                    for (int i = 0; i < issuedCerts.length; i++) {
                        // (automated "agent" cert request processed
                        //  - "accepted")
                        auditMessage = CMS.getLogMessage(
                                    LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                                    auditSubjectID,
                                    ILogger.SUCCESS,
                                    auditRequesterID,
                                    ILogger.SIGNED_AUDIT_ACCEPTANCE,
                                    auditInfoCertValue(issuedCerts[i]));

                        audit(auditMessage);
                    }
                } catch (IOException ex) {
                    cmsReq.setStatus(CMSRequest.ERROR);

                    // (automated "agent" cert request processed - "rejected")
                    auditMessage = CMS.getLogMessage(
                                LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                                auditSubjectID,
                                ILogger.FAILURE,
                                auditRequesterID,
                                ILogger.SIGNED_AUDIT_REJECTION,
                                SIGNED_AUDIT_AUTOMATED_REJECTION_REASON[0]);

                    audit(auditMessage);
                }

                return;
            }

            boolean completed = handleEnrollAuditLog(req, cmsReq,
                    mAuthMgr, authToken,
                    certInfo, startTime);

            if (completed == false) {
                // (automated "agent" cert request processed - "rejected")
                auditMessage = CMS.getLogMessage(
                            LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                            auditSubjectID,
                            ILogger.FAILURE,
                            auditRequesterID,
                            ILogger.SIGNED_AUDIT_REJECTION,
                            SIGNED_AUDIT_AUTOMATED_REJECTION_REASON[1]);

                audit(auditMessage);

                return;
            }

            // service success
            cmsReq.setStatus(CMSRequest.SUCCESS);
            issuedCerts = req.getExtDataInCertArray(IRequest.ISSUED_CERTS);

            String initiative = null;
            String agentID;

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

            // audit log the success.
            long endTime = CMS.getCurrentDate().getTime();

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

            // handle initial admin enrollment if in adminEnroll mode.
            checkAdminEnroll(cmsReq, issuedCerts);

            // return cert as mime type binary if requested.
            if (checkImportCertToNav(cmsReq.getHttpResp(),
                    httpParams, issuedCerts[0])) {
                cmsReq.setStatus(CMSRequest.SUCCESS);

                for (int i = 0; i < issuedCerts.length; i++) {
                    // (automated "agent" cert request processed - "accepted")
                    auditMessage = CMS.getLogMessage(
                                LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                                auditSubjectID,
                                ILogger.SUCCESS,
                                auditRequesterID,
                                ILogger.SIGNED_AUDIT_ACCEPTANCE,
                                auditInfoCertValue(issuedCerts[i]));

                    audit(auditMessage);
                }

                return;
            }

            // use success template.
            try {
                cmsReq.setResult(issuedCerts);
                renderTemplate(cmsReq, mEnrollSuccessTemplate,
                        mEnrollSuccessFiller);
                cmsReq.setStatus(CMSRequest.SUCCESS);

                for (int i = 0; i < issuedCerts.length; i++) {
                    // (automated "agent" cert request processed - "accepted")
                    auditMessage = CMS.getLogMessage(
                                LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                                auditSubjectID,
                                ILogger.SUCCESS,
                                auditRequesterID,
                                ILogger.SIGNED_AUDIT_ACCEPTANCE,
                                auditInfoCertValue(issuedCerts[i]));

                    audit(auditMessage);
                }
            } catch (IOException e) {
                log(ILogger.LL_FAILURE,
                        CMS.getLogMessage("CMSGW_TEMP_REND_ERR",
                                mEnrollSuccessFiller.toString(),
                                e.toString()));

                // (automated "agent" cert request processed - "rejected")
                auditMessage = CMS.getLogMessage(
                            LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                            auditSubjectID,
                            ILogger.FAILURE,
                            auditRequesterID,
                            ILogger.SIGNED_AUDIT_REJECTION,
                            SIGNED_AUDIT_AUTOMATED_REJECTION_REASON[2]);

                audit(auditMessage);

                throw new ECMSGWException(
                        CMS.getUserMessage("CMS_GW_RETURNING_RESULT_ERROR"));
            }
        } catch (EBaseException eAudit1) {
            // store a message in the signed audit log file
            // (automated "agent" cert request processed - "rejected")
            auditMessage = CMS.getLogMessage(
                        LOGGING_SIGNED_AUDIT_CERT_REQUEST_PROCESSED,
                        auditSubjectID,
                        ILogger.FAILURE,
                        auditRequesterID,
                        ILogger.SIGNED_AUDIT_REJECTION,
                        SIGNED_AUDIT_AUTOMATED_REJECTION_REASON[3]);

            audit(auditMessage);

            throw eAudit1;
        }

        return;
    }

    /**
     * check if this is first enroll from admin enroll.
     * If so disable admin enroll from here on.
     */
    protected void checkAdminEnroll(CMSRequest cmsReq, X509CertImpl[] issuedCerts)
            throws EBaseException {
        // this is special case, get the admin certificate
        if (mAuthMgr != null && mAuthMgr.equals(IAuthSubsystem.PASSWDUSERDB_AUTHMGR_ID)) {
            addAdminAgent(cmsReq, issuedCerts);
            CMSGateway.disableAdminEnroll();
        }
    }

    protected void addAdminAgent(CMSRequest cmsReq, X509CertImpl[] issuedCerts)
            throws EBaseException {
        String userid = cmsReq.getHttpParams().getValueAsString("uid");
        IUGSubsystem ug = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);

        IUser adminuser = ug.createUser(userid);

        adminuser.setX509Certificates(issuedCerts);
        try {
            ug.addUserCert(adminuser);
        } catch (netscape.ldap.LDAPException e) {
            CMS.debug(
                    "EnrollServlet: Cannot add admin's certificate to its entry in the " +
                            "user group database. Error " + e);
            throw new ECMSGWException(
                    CMS.getUserMessage("CMS_GW_ADDING_ADMIN_CERT_ERROR", e.toString()));
        }
        IGroup agentGroup =
                ug.getGroupFromName(CA_AGENT_GROUP);

        if (agentGroup != null) {
            // add user to the group if necessary
            if (!agentGroup.isMember(userid)) {
                agentGroup.addMemberName(userid);
                ug.modifyGroup(agentGroup);
                mLogger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP,
                        AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT,
                        new Object[] { userid, userid, CA_AGENT_GROUP }
                        );

            }
        } else {
            String msg = "Cannot add admin to the " +
                    CA_AGENT_GROUP +
                    " group: Group does not exist.";

            CMS.debug("EnrollServlet: " + msg);
            throw new ECMSGWException(CMS.getUserMessage("CMS_GW_ADDING_ADMIN_ERROR"));
        }
    }

    protected void renderServerEnrollResult(CMSRequest cmsReq) throws
            IOException {
        HttpServletResponse httpResp = cmsReq.getHttpResp();

        httpResp.setContentType("text/html");
        ServletOutputStream out = null;

        out = httpResp.getOutputStream();

        // get template based on request status
        out.println("<HTML>");
        out.println("<TITLE>");
        out.println("Server Enrollment");
        out.println("</TITLE>");
        // out.println("<BODY BGCOLOR=white>");

        if (cmsReq.getIRequest().getRequestStatus().equals(RequestStatus.COMPLETE)) {
            out.println("<H1>");
            out.println("SUCCESS");
            out.println("</H1>");
            out.println("Your request is submitted and approved. Please cut and paste the certificate into your server."); // XXX - localize the message
            out.println("<P>");
            out.println("Request Creation Time: ");
            out.println(cmsReq.getIRequest().getCreationTime().toString());
            out.println("<P>");
            out.println("Request Status: ");
            out.println(cmsReq.getStatus().toString());
            out.println("<P>");
            out.println("Request ID: ");
            out.println(cmsReq.getIRequest().getRequestId().toString());
            out.println("<P>");
            out.println("Certificate: ");
            out.println("<P>");
            out.println("<PRE>");
            X509CertImpl certs[] =
                    cmsReq.getIRequest().getExtDataInCertArray(IRequest.ISSUED_CERTS);

            out.println(CMS.getEncodedCert(certs[0]));
            out.println("</PRE>");
            out.println("<P>");
            out.println("<!HTTP_OUTPUT REQUEST_CREATION_TIME=" +
                    cmsReq.getIRequest().getCreationTime().toString() + ">");
            out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
                    cmsReq.getStatus().toString() + ">");
            out.println("<!HTTP_OUTPUT REQUEST_ID=" +
                    cmsReq.getIRequest().getRequestId().toString() + ">");
            out.println("<!HTTP_OUTPUT X509_CERTIFICATE=" +
                    CMS.getEncodedCert(certs[0]) + ">");
        } else if (cmsReq.getIRequest().getRequestStatus().equals(RequestStatus.PENDING)) {
            out.println("<H1>");
            out.println("PENDING");
            out.println("</H1>");
            out.println("Your request is submitted. You can check on the status of your request with an authorized agent or local administrator by referring to the request ID."); // XXX - localize the message
            out.println("<P>");
            out.println("Request Creation Time: ");
            out.println(cmsReq.getIRequest().getCreationTime().toString());
            out.println("<P>");
            out.println("Request Status: ");
            out.println(cmsReq.getStatus().toString());
            out.println("<P>");
            out.println("Request ID: ");
            out.println(cmsReq.getIRequest().getRequestId().toString());
            out.println("<P>");
            out.println("<!HTTP_OUTPUT REQUEST_CREATION_TIME=" +
                    cmsReq.getIRequest().getCreationTime().toString() + ">");
            out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
                    cmsReq.getStatus().toString() + ">");
            out.println("<!HTTP_OUTPUT REQUEST_ID=" +
                    cmsReq.getIRequest().getRequestId().toString() + ">");
        } else {
            out.println("<H1>");
            out.println("ERROR");
            out.println("</H1>");
            out.println("<!INFO>");
            out.println("Please consult your local administrator for assistance."); // XXX - localize the message
            out.println("<!/INFO>");
            out.println("<P>");
            out.println("Request Status: ");
            out.println(cmsReq.getStatus().toString());
            out.println("<P>");
            out.println("Error: ");
            out.println(cmsReq.getError()); // XXX - need to parse in Locale
            out.println("<P>");
            out.println("<!HTTP_OUTPUT REQUEST_STATUS=" +
                    cmsReq.getStatus().toString() + ">");
            out.println("<!HTTP_OUTPUT ERROR=" +
                    cmsReq.getError() + ">");
        }

        /**
         * // include all the input data
         * ArgBlock args = cmsReq.getHttpParams();
         * Enumeration ele = args.getElements();
         * while (ele.hasMoreElements()) {
         * String eleT = (String)ele.nextElement();
         * out.println("<!HTTP_INPUT " + eleT + "=" +
         * args.get(eleT) + ">");
         * }
         **/

        out.println("</HTML>");
    }

    // XXX ALERT !! 
    // Remove the following and calls to them when we bundle a cartman 
    // later than alpha1. 
    // These are here to cover up problem in cartman where the 
    // key usage extension always ends up being digital signature only 
    // and for rsa-ex ends up having no bits set.

    private boolean mIsTestBed = false;

    private void init_testbed_hack(IConfigStore config)
            throws EBaseException {
        mIsTestBed = config.getBoolean("isTestBed", true);
    }

    /**
     * Signed Audit Log Info Certificate Value
     * 
     * This method is called to obtain the certificate from the passed in
     * "X509CertImpl" for a signed audit log message.
     * <P>
     * 
     * @param x509cert an X509CertImpl
     * @return cert string containing the certificate
     */
    private String auditInfoCertValue(X509CertImpl x509cert) {
        // if no signed audit object exists, bail
        if (mSignedAuditLogger == null) {
            return null;
        }

        if (x509cert == null) {
            return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
        }

        byte rawData[] = null;

        try {
            rawData = x509cert.getEncoded();
        } catch (CertificateEncodingException e) {
            return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
        }

        String cert = null;

        // convert "rawData" into "base64Data"
        if (rawData != null) {
            String base64Data = null;

            base64Data = com.netscape.osutil.OSUtil.BtoA(rawData).trim();

            StringBuffer sb = new StringBuffer();
            // extract all line separators from the "base64Data"
            for (int i = 0; i < base64Data.length(); i++) {
                if (base64Data.substring(i, i).getBytes() != EOL) {
                    sb.append(base64Data.substring(i, i));
                }
            }
            cert = sb.toString();
        }

        if (cert != null) {
            cert = cert.trim();

            if (cert.equals("")) {
                return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
            } else {
                return cert;
            }
        } else {
            return ILogger.SIGNED_AUDIT_EMPTY_VALUE;
        }
    }
}