summaryrefslogtreecommitdiffstats
path: root/base/server/cms/src/org/dogtagpki/server/rest/SystemConfigService.java
blob: 7cedbf24b7ac9ffd4112561fbe96340270aa84cd (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
// --- 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) 2012 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package org.dogtagpki.server.rest;

import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.mutable.MutableBoolean;
import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.CryptoManager.NotInitializedException;
import org.mozilla.jss.NoSuchTokenException;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.ObjectNotFoundException;
import org.mozilla.jss.crypto.PrivateKey;
import org.mozilla.jss.crypto.TokenException;
import org.mozilla.jss.crypto.X509Certificate;
import org.mozilla.jss.util.IncorrectPasswordException;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.BadRequestException;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.PKIException;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.certsrv.system.ConfigurationRequest;
import com.netscape.certsrv.system.ConfigurationResponse;
import com.netscape.certsrv.system.SystemCertData;
import com.netscape.certsrv.system.SystemConfigResource;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
import com.netscape.cms.servlet.base.PKIService;
import com.netscape.cms.servlet.csadmin.Cert;
import com.netscape.cms.servlet.csadmin.ConfigurationUtils;
import com.netscape.cms.servlet.csadmin.SystemCertDataFactory;
import com.netscape.cmsutil.crypto.CryptoUtil;
import com.netscape.cmsutil.util.Utils;

import netscape.security.x509.X509CertImpl;

/**
 * @author alee
 *
 */
public class SystemConfigService extends PKIService implements SystemConfigResource {
    @Context
    public UriInfo uriInfo;

    @Context
    public HttpHeaders headers;

    @Context
    public Request request;

    @Context
    public HttpServletRequest servletRequest;

    public IConfigStore cs;
    public String csType;
    public String csSubsystem;
    public String csState;
    public boolean isMasterCA = false;
    public String instanceRoot;

    public static String SUCCESS = "0";
    public static final String RESTART_SERVER_AFTER_CONFIGURATION =
            "restart_server_after_configuration";

    public SystemConfigService() throws EBaseException {
        cs = CMS.getConfigStore();
        csType = cs.getString("cs.type");
        csSubsystem = csType.toLowerCase();
        csState = cs.getString("cs.state");
        String domainType = cs.getString("securitydomain.select", "existingdomain");
        if (csType.equals("CA") && domainType.equals("new")) {
            isMasterCA = true;
        }
        instanceRoot = cs.getString("instanceRoot");
    }

    /* (non-Javadoc)
     * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(com.netscape.cms.servlet.csadmin.data.ConfigurationData)
     */
    @Override
    public ConfigurationResponse configure(ConfigurationRequest request) throws Exception {

        CMS.debug("SystemConfigService: configure()");

        try {
            ConfigurationResponse response = new ConfigurationResponse();

            HttpSession session = servletRequest.getSession(true);
            session.setAttribute("configuration_request", request);
            session.setAttribute("configuration_response", response);

            configure(request, response);
            return response;

        } catch (PKIException e) { // normal responses
            CMS.debug(e.getMessage()); // log the response
            throw e;

        } catch (Exception e) { // unexpected exceptions
            CMS.debug(e); // show stack trace for troubleshooting
            throw e;

        } catch (Error e) { // system errors
            CMS.debug(e); // show stack trace for troubleshooting
            throw e;
        }
    }

    public void configure(ConfigurationRequest data, ConfigurationResponse response) throws Exception {


        if (csState.equals("1")) {
            throw new BadRequestException("System is already configured");
        }

        CMS.debug("SystemConfigService: request: " + data);
        validateRequest(data);

        Collection<String> certList = getCertList(data);

        // specify module and log into token
        CMS.debug("=== Token Authentication ===");
        String token = data.getToken();
        if (token == null) {
            token = ConfigurationRequest.TOKEN_DEFAULT;
        }
        loginToken(data, token);

        // configure security domain
        CMS.debug("=== Security Domain Configuration ===");
        String domainXML = configureSecurityDomain(data);

        // configure subsystem
        CMS.debug("=== Subsystem Configuration ===");
        configureSubsystem(data, certList, token, domainXML);

        // configure hierarchy
        CMS.debug("=== Hierarchy Configuration ===");
        configureHierarchy(data);

        // configure database
        CMS.debug("=== Database Configuration ===");
        try {
            configureDatabase(data);
            cs.commit(false);
        } catch (EBaseException e) {
            CMS.debug(e);
            throw new PKIException("Unable to commit config parameters to file", e);
        }
        initializeDatabase(data);

        configureCACertChain(data, domainXML);

        Collection<Cert> certs = new ArrayList<Cert>();
        HttpSession session = servletRequest.getSession();
        session.setAttribute("system_certificates", certs);

        if (!data.getExistingDatabase()) {
            MutableBoolean hasSigningCert = new MutableBoolean();
            processCerts(data, token, certList, certs, hasSigningCert);
        }
    }

    @Override
    public void createCertificates() {

        HttpSession session = servletRequest.getSession();
        ConfigurationRequest request = (ConfigurationRequest)session.getAttribute("configuration_request");
        ConfigurationResponse response = (ConfigurationResponse)session.getAttribute("configuration_response");
        Collection<Cert> certs = (Collection<Cert>)session.getAttribute("system_certificates");

        for (Cert cert : certs) {
            int ret;

            try {
                CMS.debug("Processing '" + cert.getCertTag() + "' certificate:");
                ret = ConfigurationUtils.handleCerts(cert);
                ConfigurationUtils.setCertPermissions(cert.getCertTag());
                CMS.debug("Processed '" + cert.getCertTag() + "' certificate.");

            } catch (Exception e) {
                CMS.debug(e);
                throw new PKIException("Error in configuring system certificates: " + e, e);
            }

            if (ret != 0) {
                throw new PKIException("Error in configuring system certificates");
            }
        }
    }

    @Override
    public void backupKeys() {

        HttpSession session = servletRequest.getSession();
        ConfigurationRequest request = (ConfigurationRequest)session.getAttribute("configuration_request");
        ConfigurationResponse response = (ConfigurationResponse)session.getAttribute("configuration_response");

        if (request.getBackupKeys().equals("true")) {
            backupKeys(request);
        }
    }

    @Override
    public void createUsers() {

        HttpSession session = servletRequest.getSession();
        ConfigurationRequest request = (ConfigurationRequest)session.getAttribute("configuration_request");
        ConfigurationResponse response = (ConfigurationResponse)session.getAttribute("configuration_response");

        configureAdministrator(request, response);
        setupDBUser(request);
    }

    @Override
    public void configureSecurityDomain() {

        HttpSession session = servletRequest.getSession();
        ConfigurationRequest request = (ConfigurationRequest)session.getAttribute("configuration_request");

        setupSecurityDomain(request);
    }

    @Override
    public void finalizeConfiguration() {

        HttpSession session = servletRequest.getSession();
        ConfigurationRequest request = (ConfigurationRequest)session.getAttribute("configuration_request");
        ConfigurationResponse response = (ConfigurationResponse)session.getAttribute("configuration_response");

        finalizeConfiguration(request, response);
    }

    @Override
    public void cleanUp() {

        cs.putInteger("cs.state", 1);

        // update serial numbers for clones

        // save some variables, remove remaining preops
        try {
            ConfigurationUtils.removePreopConfigEntries();
        } catch (EBaseException e) {
            CMS.debug(e);
            throw new PKIException("Errors when removing preop config entries: " + e, e);
        }

        // Create an empty file that designates the fact that although
        // this server instance has been configured, it has NOT yet
        // been restarted!
        String restart_server = instanceRoot + "/conf/" + RESTART_SERVER_AFTER_CONFIGURATION;
        Utils.exec("touch " + restart_server);
        Utils.exec("chmod 00660 " + restart_server);
    }

    @Override
    public ConfigurationResponse getConfigurationResponse() {

        HttpSession session = servletRequest.getSession();
        ConfigurationResponse response = (ConfigurationResponse)session.getAttribute("configuration_response");
        Collection<Cert> certs = (Collection<Cert>)session.getAttribute("system_certificates");
        response.setSystemCerts(SystemCertDataFactory.create(certs));

        return response;
    }

    private void setupDBUser(ConfigurationRequest data) {
        try {
            if (!data.getSharedDB()) ConfigurationUtils.setupDBUser(data);
        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Errors in creating or updating dbuser: " + e);
        }
    }

    private void setupSecurityDomain(ConfigurationRequest data) {
        try {
            String securityDomainType = data.getSecurityDomainType();
            if (securityDomainType.equals(ConfigurationRequest.NEW_DOMAIN)) {
                CMS.debug("Creating new security domain");
                ConfigurationUtils.createSecurityDomain(data);
            } else if (securityDomainType.equals(ConfigurationRequest.NEW_SUBDOMAIN)) {
                CMS.debug("Creating subordinate CA security domain");

                // switch out security domain parameters from issuing CA security domain
                // to subordinate CA hosted security domain
                cs.putString("securitydomain.name", data.getSubordinateSecurityDomainName());
                cs.putString("securitydomain.host", CMS.getEENonSSLHost());
                cs.putString("securitydomain.httpport", CMS.getEENonSSLPort());
                cs.putString("securitydomain.httpsagentport", CMS.getAgentPort());
                cs.putString("securitydomain.httpseeport", CMS.getEESSLPort());
                cs.putString("securitydomain.httpsadminport", CMS.getAdminPort());
                ConfigurationUtils.createSecurityDomain(data);
            } else {
                CMS.debug("Updating existing security domain");
                ConfigurationUtils.updateSecurityDomain();
            }
            cs.putString("service.securityDomainPort", CMS.getAgentPort());
            cs.putString("securitydomain.store", "ldap");
            cs.commit(false);
        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Error while updating security domain: " + e);
        }
    }

    public Collection<String> getCertList(ConfigurationRequest request) {

        Collection<String> certList = new ArrayList<String>();

        if (request.getStandAlone() && request.getStepTwo()) {
            // Stand-alone PKI (Step 2)
            // Special case to import the external CA and its Chain
            certList.add("external_signing");
        }

        try {
            String value = cs.getString("preop.cert.list");
            certList.addAll(Arrays.asList(value.split(",")));

        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Unable to get certList from config file");
        }

        return certList;
    }

    public void processCerts(ConfigurationRequest request, String token, Collection<String> certList,
            Collection<Cert> certs, MutableBoolean hasSigningCert) {

        try {
            boolean generateServerCert = !request.getGenerateServerCert().equalsIgnoreCase("false");
            boolean generateSubsystemCert = request.getGenerateSubsystemCert();

            hasSigningCert.setValue(false);

            for (String tag : certList) {
                boolean enable = cs.getBoolean("preop.cert." + tag + ".enable", true);
                if (!enable) continue;

                SystemCertData certData = null;

                for (SystemCertData systemCert : request.getSystemCerts()) {
                    if (systemCert.getTag().equals(tag)) {
                        certData = systemCert;
                        CMS.debug("Found data for '" + tag + "'");
                        if (tag.equals("signing") &&
                                certData.getReqExtOID() != null &&
                                certData.getReqExtData() != null) {
                            CMS.debug("SystemConfigService:processCerts: adding request extension to config");
                            cs.putString("preop.cert.signing.ext.oid", certData.getReqExtOID());
                            cs.putString("preop.cert.signing.ext.data", certData.getReqExtData());
                            cs.putBoolean("preop.cert.signing.ext.critical", certData.getReqExtCritical());
                        }
                        break;
                    }
                }

                if (certData == null) {
                    CMS.debug("No data for '" + tag + "' was found!");
                    throw new BadRequestException("No data for '" + tag + "' was found!");
                }

                String tokenName = certData.getToken() != null ? certData.getToken() : token;
                if (request.getStandAlone() && request.getStepTwo()) {
                    // Stand-alone PKI (Step 2)
                    if (tag.equals("external_signing")) {

                        String b64 = certData.getCert();
                        if (b64 != null && b64.length() > 0 && !b64.startsWith("...")) {
                            hasSigningCert.setValue(true);

                            if (request.getIssuingCA().equals("External CA")) {
                                String nickname = certData.getNickname() != null ? certData.getNickname() : "caSigningCert External CA";
                                Cert cert = new Cert(tokenName, nickname, tag);
                                ConfigurationUtils.setExternalCACert(b64, csSubsystem, cs, cert);

                                CMS.debug("Step 2:  certStr for '" + tag + "' is " + b64);
                                String certChainStr = certData.getCertChain();

                                if (certChainStr != null) {
                                    ConfigurationUtils.setExternalCACertChain(certChainStr, csSubsystem, cs, cert);
                                    CMS.debug("Step 2:  certChainStr for '" + tag + "' is " + certChainStr);
                                    certs.add(cert);

                                } else {
                                    throw new BadRequestException("CertChain not provided");
                                }
                            }

                            continue;
                        }
                    }
                }

                if (!generateServerCert && tag.equals("sslserver")) {
                    updateConfiguration(request, certData, "sslserver");
                    continue;
                }

                if (!generateSubsystemCert && tag.equals("subsystem")) {
                    // update the details for the shared subsystem cert here.
                    updateConfiguration(request, certData, "subsystem");

                    // get parameters needed for cloning
                    updateCloneConfiguration(certData, "subsystem", tokenName);
                    continue;
                }

                String keytype = certData.getKeyType() != null ? certData.getKeyType() : "rsa";

                String keyalgorithm = certData.getKeyAlgorithm();
                if (keyalgorithm == null) {
                    keyalgorithm = keytype.equals("ecc") ? "SHA256withEC" : "SHA256withRSA";
                }

                String signingalgorithm = certData.getSigningAlgorithm() != null ? certData.getSigningAlgorithm() : keyalgorithm;
                String nickname = certData.getNickname() != null ? certData.getNickname() :
                    cs.getString("preop.cert." + tag + ".nickname");
                String dn = certData.getSubjectDN() != null ? certData.getSubjectDN() :
                    cs.getString("preop.cert." + tag + ".dn");

                cs.putString("preop.cert." + tag + ".keytype", keytype);
                cs.putString("preop.cert." + tag + ".keyalgorithm", keyalgorithm);
                cs.putString("preop.cert." + tag + ".signingalgorithm", signingalgorithm);
                cs.putString("preop.cert." + tag + ".nickname", nickname);
                cs.putString("preop.cert." + tag + ".dn", dn);

                // support injecting SAN into server cert
                if ( tag.equals("sslserver") && certData.getServerCertSAN() != null) {
                    CMS.debug("updateConfiguration(): san_server_cert found");
                    cs.putString("service.injectSAN", "true");
                    cs.putString("service.sslserver.san", certData.getServerCertSAN());
                } else {
                    if ( tag.equals("sslserver"))
                        CMS.debug("SystemConfigService:processCerts(): san_server_cert not found for tag sslserver");
                }
                cs.commit(false);

                if (request.isExternal() && tag.equals("signing")) { // external/existing CA
                    // load key pair for existing and externally-signed signing cert
                    CMS.debug("SystemConfigService: loading signing cert key pair");
                    KeyPair pair = ConfigurationUtils.loadKeyPair(certData.getNickname());
                    ConfigurationUtils.storeKeyPair(cs, tag, pair);

                } else if (!request.getStepTwo()) {
                    if (keytype.equals("ecc")) {
                        String curvename = certData.getKeyCurveName() != null ?
                                certData.getKeyCurveName() : cs.getString("keys.ecc.curve.default");
                        cs.putString("preop.cert." + tag + ".curvename.name", curvename);
                        ConfigurationUtils.createECCKeyPair(token, curvename, cs, tag);

                    } else {
                        String keysize = certData.getKeySize() != null ? certData.getKeySize() : cs
                                .getString("keys.rsa.keysize.default");
                        cs.putString("preop.cert." + tag + ".keysize.size", keysize);
                        ConfigurationUtils.createRSAKeyPair(token, Integer.parseInt(keysize), cs, tag);
                    }

                } else {
                    CMS.debug("configure(): step two selected.  keys will not be generated for '" + tag + "'");
                }

                Cert cert = new Cert(tokenName, nickname, tag);
                cert.setDN(dn);
                cert.setSubsystem(cs.getString("preop.cert." + tag + ".subsystem"));
                cert.setType(cs.getString("preop.cert." + tag + ".type"));

                if (request.isExternal() && tag.equals("signing")) { // external/existing CA

                    // update configuration for existing or externally-signed signing certificate
                    String certStr = cs.getString("ca." + tag + ".cert" );
                    cert.setCert(certStr);
                    CMS.debug("SystemConfigService: certificate " + tag + ": " + certStr);
                    ConfigurationUtils.updateConfig(cs, tag);

                } else if (!request.getStepTwo()) {
                    ConfigurationUtils.configCert(null, null, null, cert);

                } else {
                    String subsystem = cs.getString("preop.cert." + tag + ".subsystem");
                    String certStr;

                    if (request.getStandAlone()) {
                        // Stand-alone PKI (Step 2)
                        certStr = certData.getCert();
                        certStr = CryptoUtil.stripCertBrackets(certStr.trim());
                        certStr = CryptoUtil.normalizeCertStr(certStr);
                        cs.putString(subsystem + "." + tag + ".cert", certStr);

                    } else {
                        certStr = cs.getString(subsystem + "." + tag + ".cert" );
                    }

                    cert.setCert(certStr);
                    CMS.debug("Step 2:  certStr for '" + tag + "' is " + certStr);
                }

                if (request.isExternal() && tag.equals("signing")) { // external/existing CA

                    CMS.debug("SystemConfigService: Loading cert request for " + tag + " cert");
                    ConfigurationUtils.loadCertRequest(cs, tag, cert);

                    CMS.debug("SystemConfigService: Loading cert " + tag);
                    ConfigurationUtils.loadCert(cs, cert);

                } else if (request.getStandAlone()) {
                    // Handle Cert Requests for everything EXCEPT Stand-alone PKI (Step 2)
                    if (!request.getStepTwo()) {
                        // Stand-alone PKI (Step 1)
                        ConfigurationUtils.handleCertRequest(cs, tag, cert);

                        CMS.debug("Stand-alone " + csType + " Admin CSR");
                        String adminSubjectDN = request.getAdminSubjectDN();
                        String certreqStr = request.getAdminCertRequest();
                        certreqStr = CryptoUtil.normalizeCertAndReq(certreqStr);

                        cs.putString("preop.cert.admin.dn", adminSubjectDN);
                        cs.putString(csSubsystem + ".admin.certreq", certreqStr);
                        cs.putString(csSubsystem + ".admin.cert", "...paste certificate here...");
                    }

                } else {
                    ConfigurationUtils.handleCertRequest(cs, tag, cert);
                }

                if (request.isClone()) {
                    ConfigurationUtils.updateCloneConfig();
                }

                if (request.isExternal() && tag.equals("signing")) { // external/existing CA
                    CMS.debug("SystemConfigService: External CA has signing cert");
                    hasSigningCert.setValue(true);
                    certs.add(cert);
                    continue;
                }

                // to determine if we have the signing cert when using an external ca
                // this will only execute on a ca or stand-alone pki
                String b64 = certData.getCert();
                if ((tag.equals("signing") || tag.equals("external_signing")) && b64 != null && b64.length() > 0 && !b64.startsWith("...")) {
                    hasSigningCert.setValue(true);

                    if (request.getIssuingCA().equals("External CA")) {
                        b64 = CryptoUtil.stripCertBrackets(b64.trim());
                        cert.setCert(CryptoUtil.normalizeCertStr(b64));

                        if (certData.getCertChain() != null) {
                            cert.setCertChain(certData.getCertChain());

                        } else {
                            throw new BadRequestException("CertChain not provided");
                        }
                    }
                }

                certs.add(cert);
            }

            // make sure to commit changes here for step 1
            cs.commit(false);

        } catch (NumberFormatException e) {
            // move these validations to validate()?
            throw new BadRequestException("Non-integer value for key size");

        } catch (NoSuchAlgorithmException e) {
            throw new BadRequestException("Invalid algorithm " + e);

        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Error in setting certificate names and key sizes: " + e);
        }
    }

    private void updateCloneConfiguration(SystemCertData cdata, String tag, String tokenName) throws NotInitializedException,
            ObjectNotFoundException, TokenException {
        // TODO - some of these parameters may only be valid for RSA
        CryptoManager cryptoManager = CryptoManager.getInstance();
        if (!tokenName.isEmpty())
            CMS.debug("SystemConfigService:updateCloneConfiguration: tokenName=" + tokenName);
        else
            CMS.debug("SystemConfigService:updateCloneConfiguration: tokenName empty; using internal");

        X509Certificate cert = cryptoManager.findCertByNickname(!tokenName.isEmpty()? tokenName + ":" + cdata.getNickname() :  cdata.getNickname());
        PublicKey pubk = cert.getPublicKey();
        byte[] exponent = CryptoUtil.getPublicExponent(pubk);
        byte[] modulus = CryptoUtil.getModulus(pubk);
        PrivateKey privk = cryptoManager.findPrivKeyByCert(cert);

        cs.putString("preop.cert." + tag + ".pubkey.modulus", CryptoUtil.byte2string(modulus));
        cs.putString("preop.cert." + tag + ".pubkey.exponent", CryptoUtil.byte2string(exponent));
        cs.putString("preop.cert." + tag + ".privkey.id", CryptoUtil.byte2string(privk.getUniqueID()));
        cs.putString("preop.cert." + tag + ".dn", cdata.getSubjectDN());
        cs.putString("preop.cert." + tag + ".keyalgorithm", cdata.getKeyAlgorithm());
        cs.putString("preop.cert." + tag + ".keytype", cdata.getKeyType());
        cs.putString("preop.cert." + tag + ".nickname", cdata.getNickname());
    }

    private void updateConfiguration(ConfigurationRequest data, SystemCertData cdata, String tag) {
        if (cdata.getToken().equals("Internal Key Storage Token")) {
            cs.putString(csSubsystem + ".cert." + tag + ".nickname", cdata.getNickname());
        } else {
            cs.putString(csSubsystem + ".cert." + tag + ".nickname", data.getToken() +
                    ":" + cdata.getNickname());
        }

        cs.putString(csSubsystem + "." + tag + ".nickname", cdata.getNickname());
        cs.putString(csSubsystem + "." + tag + ".tokenname", cdata.getToken());
        cs.putString(csSubsystem + "." + tag + ".certreq", cdata.getRequest());
        cs.putString(csSubsystem + "." + tag + ".cert", cdata.getCert());
        cs.putString(csSubsystem + "." + tag + ".dn", cdata.getSubjectDN());
    }

    public void backupKeys(ConfigurationRequest request) {
        try {
            ConfigurationUtils.backupKeys(request.getBackupPassword(), request.getBackupFile());
        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Error in creating pkcs12 to backup keys and certs: " + e);
        }
    }

    public void finalizeConfiguration(ConfigurationRequest request, ConfigurationResponse response) {
    }

    public void configureAdministrator(ConfigurationRequest data, ConfigurationResponse response) {

        if (!data.isClone()) {
            try {
                X509CertImpl admincerts[] = new X509CertImpl[1];
                ConfigurationUtils.createAdmin(data.getAdminUID(), data.getAdminEmail(),
                        data.getAdminName(), data.getAdminPassword());

                if (data.getImportAdminCert().equalsIgnoreCase("true")) {
                    String b64 = CryptoUtil.stripCertBrackets(data.getAdminCert().trim());
                    b64 = CryptoUtil.normalizeCertStr(b64);
                    if (data.getStandAlone() && data.getStepTwo()) {
                        // Stand-alone PKI (Step 2)
                        CMS.debug("SystemConfigService:  Stand-alone " + csType + " Admin Cert");
                        cs.putString(csSubsystem + ".admin.cert", b64);
                        cs.commit(false);
                    }
                    // Convert Admin Cert to X509CertImpl
                    byte[] b = CryptoUtil.base64Decode(b64);
                    admincerts[0] = new X509CertImpl(b);

                } else {
                    if (csType.equals("CA")) {
                        ConfigurationUtils.createAdminCertificate(data.getAdminCertRequest(),
                                data.getAdminCertRequestType(), data.getAdminSubjectDN());

                        String serialno = cs.getString("preop.admincert.serialno.0");
                        ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(ICertificateAuthority.ID);
                        ICertificateRepository repo = ca.getCertificateRepository();
                        admincerts[0] = repo.getX509Certificate(new BigInteger(serialno, 16));

                    } else {
                        String type = cs.getString("preop.ca.type", "");
                        String ca_hostname = "";
                        int ca_port = -1;
                        if (type.equals("sdca")) {
                            ca_hostname = cs.getString("preop.ca.hostname");
                            ca_port = cs.getInteger("preop.ca.httpsport");
                        } else {
                            ca_hostname = cs.getString("securitydomain.host", "");
                            ca_port = cs.getInteger("securitydomain.httpseeport");
                        }
                        String b64 = ConfigurationUtils.submitAdminCertRequest(ca_hostname, ca_port,
                                data.getAdminProfileID(), data.getAdminCertRequestType(),
                                data.getAdminCertRequest(), data.getAdminSubjectDN());
                        b64 = CryptoUtil.stripCertBrackets(b64.trim());
                        byte[] b = CryptoUtil.base64Decode(b64);
                        admincerts[0] = new X509CertImpl(b);
                    }
                }
                CMS.reinit(IUGSubsystem.ID);

                IUGSubsystem ug = (IUGSubsystem) CMS.getSubsystem(IUGSubsystem.ID);
                IUser user = ug.getUser(data.getAdminUID());
                user.setX509Certificates(admincerts);
                ug.addUserCert(user);
                response.setAdminCert(admincerts[0]);

            } catch (Exception e) {
                CMS.debug(e);
                throw new PKIException("Error in creating admin user: " + e);
            }
        }
    }

    public void configureDatabase(ConfigurationRequest data) {
        cs.putString("internaldb.ldapconn.host", data.getDsHost());
        cs.putString("internaldb.ldapconn.port", data.getDsPort());
        cs.putString("internaldb.database", data.getDatabase());
        cs.putString("internaldb.basedn", data.getBaseDN());
        cs.putString("internaldb.ldapauth.bindDN", data.getBindDN());
        cs.putBoolean("internaldb.ldapconn.secureConn", data.getSecureConn().equals("true"));
        cs.putBoolean("preop.database.setupReplication", data.getSetupReplication());
        cs.putBoolean("preop.database.reindexData", data.getReindexData());
    }

    public void initializeDatabase(ConfigurationRequest data) {

        if (data.isClone() && data.getSetupReplication()) {
            String masterhost = "";
            String masterport = "";
            String masterbasedn = "";
            String realhostname = "";
            try {
                masterhost = cs.getString("preop.internaldb.master.ldapconn.host", "");
                masterport = cs.getString("preop.internaldb.master.ldapconn.port", "");
                masterbasedn = cs.getString("preop.internaldb.master.basedn", "");
                realhostname = cs.getString("machineName", "");
            } catch (Exception e) {
            }

            if (masterhost.equals(realhostname) && masterport.equals(data.getDsPort())) {
                throw new BadRequestException("Master and clone must not share the same internal database");
            }

            if (!masterbasedn.equals(data.getBaseDN())) {
                throw new BadRequestException("Master and clone should have the same base DN");
            }

            String masterReplicationPort = data.getMasterReplicationPort();
            if ((masterReplicationPort != null) && (!masterReplicationPort.equals(""))) {
                cs.putString("internaldb.ldapconn.masterReplicationPort", masterReplicationPort);
            } else {
                cs.putString("internaldb.ldapconn.masterReplicationPort", masterport);
            }

            String cloneReplicationPort = data.getCloneReplicationPort();
            if ((cloneReplicationPort == null) || (cloneReplicationPort.length() == 0)) {
                cloneReplicationPort = data.getDsPort();
            }
            cs.putString("internaldb.ldapconn.cloneReplicationPort", cloneReplicationPort);

            String replicationSecurity = data.getReplicationSecurity();
            if ((cloneReplicationPort == data.getDsPort()) && (data.getSecureConn().equals("true"))) {
                replicationSecurity = "SSL";
            } else if (replicationSecurity == null) {
                replicationSecurity = "None";
            }
            cs.putString("internaldb.ldapconn.replicationSecurity", replicationSecurity);

            cs.putString("preop.internaldb.replicateSchema", data.getReplicateSchema());
        }

        try {
            /* BZ 430745 create password for replication manager */
            // use user-provided password if specified
            String replicationPassword = data.getReplicationPassword();

            if (StringUtils.isEmpty(replicationPassword)) {
                // generate random password
                replicationPassword = Integer.toString(new Random().nextInt());
            }

            IConfigStore psStore = null;
            String passwordFile = null;
            passwordFile = cs.getString("passwordFile");
            psStore = CMS.createFileConfigStore(passwordFile);
            psStore.putString("internaldb", data.getBindpwd());
            if (StringUtils.isEmpty(psStore.getString("replicationdb", null))) {
                psStore.putString("replicationdb", replicationPassword);
            }
            psStore.commit(false);

            if (!data.getStepTwo()) {
                ConfigurationUtils.enableUSNPlugin(data);
                ConfigurationUtils.populateDB(data);

                cs.putString("preop.internaldb.replicationpwd", replicationPassword);
                cs.putString("preop.database.removeData", "false");
                if (data.getSharedDB()) {
                    cs.putString("preop.internaldb.dbuser", data.getSharedDBUserDN());
                }
                cs.commit(false);

                if (data.isClone() && data.getSetupReplication()) {
                    CMS.debug("Start setting up replication.");
                    ConfigurationUtils.setupReplication(data);
                }

                ConfigurationUtils.reInitSubsystem(csType);
                ConfigurationUtils.populateDBManager(data);
                ConfigurationUtils.populateVLVIndexes(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new PKIException("Error in populating database: " + e, e);
        }
    }

    public void configureHierarchy(ConfigurationRequest data) {
        if (csType.equals("CA") && !data.isClone()) {
            if (data.getHierarchy().equals("root")) {
                cs.putString("preop.hierarchy.select", "root");
                cs.putString("hierarchy.select", "Root");
                cs.putString("preop.ca.type", "sdca");
            } else if (data.getHierarchy().equals("join")) {
                cs.putString("preop.cert.signing.type", "remote");
                cs.putString("preop.hierarchy.select", "join");
                cs.putString("hierarchy.select", "Subordinate");
            } else {
                throw new BadRequestException("Invalid hierarchy provided");
            }
        }
    }

    public void configureCACertChain(ConfigurationRequest data, String domainXML) {
        if (data.getHierarchy() == null || data.getHierarchy().equals("join")) {
            try {
                String url = data.getIssuingCA();
                if (url.equals("External CA")) {
                    CMS.debug("external CA selected");
                    cs.putString("preop.ca.type", "otherca");
                    cs.putString("preop.ca.pkcs7", "");
                    cs.putInteger("preop.ca.certchain.size", 0);
                    if (csType.equals("CA")) {
                        cs.putString("preop.cert.signing.type", "remote");
                    }

                } else {
                    CMS.debug("local CA selected");
                    url = url.substring(url.indexOf("https"));
                    cs.putString("preop.ca.url", url);
                    URL urlx = new URL(url);
                    String host = urlx.getHost();
                    int port = urlx.getPort();

                    int admin_port = ConfigurationUtils.getPortFromSecurityDomain(domainXML,
                            host, port, "CA", "SecurePort", "SecureAdminPort");

                    cs.putString("preop.ca.type", "sdca");
                    cs.putString("preop.ca.hostname", host);
                    cs.putInteger("preop.ca.httpsport", port);
                    cs.putInteger("preop.ca.httpsadminport", admin_port);

                    if (!data.isClone() && !data.getSystemCertsImported()) {
                        ConfigurationUtils.importCertChain(host, admin_port, "/ca/admin/ca/getCertChain", "ca");
                    }

                    if (csType.equals("CA")) {
                        cs.putString("preop.cert.signing.type", "remote");
                        cs.putString("preop.cert.signing.profile","caInstallCACert");
                    }
                }
            } catch (Exception e) {
                throw new PKIException("Error in obtaining certificate chain from issuing CA: " + e);
            }
        }
    }

    private void configureClone(ConfigurationRequest data, Collection<String> certList, String token, String domainXML) throws Exception {
        for (String tag : certList) {
            if (tag.equals("sslserver")) {
                cs.putBoolean("preop.cert." + tag + ".enable", true);
            } else {
                cs.putBoolean("preop.cert." + tag + ".enable", false);
            }
        }

        String cloneUri = data.getCloneUri();
        URL url = new URL(cloneUri);
        String masterHost = url.getHost();
        int masterPort = url.getPort();

        CMS.debug("SystemConfigService: validate clone URI: " + url);
        boolean validCloneUri = ConfigurationUtils.isValidCloneURI(domainXML, masterHost, masterPort);

        if (!validCloneUri) {
            throw new BadRequestException(
                    "Clone URI does not match available subsystems: " + url);
        }

        if (csType.equals("CA") && !data.getSystemCertsImported()) {
            CMS.debug("SystemConfigService: import certificate chain from master");
            int masterAdminPort = ConfigurationUtils.getPortFromSecurityDomain(domainXML,
                    masterHost, masterPort, "CA", "SecurePort", "SecureAdminPort");
            ConfigurationUtils.importCertChain(masterHost, masterAdminPort,
                    "/ca/admin/ca/getCertChain", "clone");
        }

        CMS.debug("SystemConfigService: get configuration entries from master");
        ConfigurationUtils.getConfigEntriesFromMaster();

        if (token.equals(ConfigurationRequest.TOKEN_DEFAULT)) {
            if (!data.getSystemCertsImported()) {
                CMS.debug("SystemConfigService: restore certificates from P12 file");
                String p12File = data.getP12File();
                String p12Pass = data.getP12Password();
                ConfigurationUtils.restoreCertsFromP12(p12File, p12Pass);
            }

        } else {
            CMS.debug("SystemConfigService: import certificates from HSM and set permission");
            ConfigurationUtils.importAndSetCertPermissionsFromHSM();
        }

        CMS.debug("SystemConfigService: verify certificates");
        ConfigurationUtils.verifySystemCertificates();
    }

    public String configureSecurityDomain(ConfigurationRequest data) throws Exception {

        String domainXML = null;

        String securityDomainType = data.getSecurityDomainType();
        String securityDomainName = data.getSecurityDomainName();

        if (securityDomainType.equals(ConfigurationRequest.NEW_DOMAIN)) {
            configureNewSecurityDomain(data, securityDomainName);
        } else if (securityDomainType.equals(ConfigurationRequest.NEW_SUBDOMAIN)){
            CMS.debug("Configuring new subordinate root CA");
            configureNewSecurityDomain(data, data.getSubordinateSecurityDomainName());
            String securityDomainURL = data.getSecurityDomainUri();
            domainXML = logIntoSecurityDomain(data, securityDomainURL);
        } else {
            CMS.debug("Joining existing security domain");
            cs.putString("preop.securitydomain.select", "existing");
            cs.putString("securitydomain.select", "existing");
            cs.putString("preop.cert.subsystem.type", "remote");
            cs.putString("preop.cert.subsystem.profile", "caInternalAuthSubsystemCert");
            String securityDomainURL = data.getSecurityDomainUri();
            domainXML = logIntoSecurityDomain(data, securityDomainURL);
        }
        return domainXML;
    }

    private void configureNewSecurityDomain(ConfigurationRequest data, String securityDomainName) {
        CMS.debug("Creating new security domain");
        cs.putString("preop.securitydomain.select", "new");
        cs.putString("securitydomain.select", "new");
        cs.putString("preop.securitydomain.name", securityDomainName);
        cs.putString("securitydomain.name", securityDomainName);
        cs.putString("securitydomain.host", CMS.getEENonSSLHost());
        cs.putString("securitydomain.httpport", CMS.getEENonSSLPort());
        cs.putString("securitydomain.httpsagentport", CMS.getAgentPort());
        cs.putString("securitydomain.httpseeport", CMS.getEESSLPort());
        cs.putString("securitydomain.httpsadminport", CMS.getAdminPort());
        // Stand-alone PKI (Step 1)
        if (data.getStandAlone()) {
            cs.putString("preop.cert.subsystem.type", "remote");
        } else {
            cs.putString("preop.cert.subsystem.type", "local");
        }
        cs.putString("preop.cert.subsystem.profile", "subsystemCert.profile");
    }

    private String logIntoSecurityDomain(ConfigurationRequest data, String securityDomainURL) throws Exception {
        URL secdomainURL;
        String host;
        int port;
        try {
            CMS.debug("Resolving security domain URL " + securityDomainURL);
            secdomainURL = new URL(securityDomainURL);
            host = secdomainURL.getHost();
            port = secdomainURL.getPort();
            cs.putString("securitydomain.host", host);
            cs.putInteger("securitydomain.httpsadminport",port);
        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Failed to resolve security domain URL", e);
        }

        if (!data.getSystemCertsImported()) {
            CMS.debug("Getting security domain cert chain");
            ConfigurationUtils.importCertChain(host, port, "/ca/admin/ca/getCertChain", "securitydomain");
        }

        getInstallToken(data, host, port);

        return getDomainXML(host, port);
    }

    private String getDomainXML(String host, int port) {
        CMS.debug("Getting domain XML");
        String domainXML = null;
        try {
            domainXML = ConfigurationUtils.getDomainXML(host, port, true);
            ConfigurationUtils.getSecurityDomainPorts(domainXML, host, port);
        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Failed to obtain security domain decriptor from security domain master: " + e, e);
        }
        return domainXML;
    }

    private void getInstallToken(ConfigurationRequest data, String host, int port) {
        CMS.debug("Getting install token");
        // log onto security domain and get token
        String user = data.getSecurityDomainUser();
        String pass = data.getSecurityDomainPassword();
        String installToken;
        try {
            installToken = ConfigurationUtils.getInstallToken(host, port, user, pass);
        } catch (Exception e) {
            CMS.debug(e);
            throw new PKIException("Failed to obtain installation token from security domain: " + e, e);
        }

        if (installToken == null) {
            CMS.debug("Install token is null");
            throw new PKIException("Failed to obtain installation token from security domain");
        }
        CMS.setConfigSDSessionId(installToken);
    }

    public void configureSubsystem(ConfigurationRequest request,
            Collection<String> certList, String token, String domainXML) throws Exception {

        cs.putString("preop.subsystem.name", request.getSubsystemName());

        // is this a clone of another subsystem?
        if (!request.isClone()) {
            cs.putString("preop.subsystem.select", "new");
            cs.putString("subsystem.select", "New");

        } else {
            cs.putString("preop.subsystem.select", "clone");
            cs.putString("subsystem.select", "Clone");
            configureClone(request, certList, token, domainXML);
        }
    }

    public void loginToken(ConfigurationRequest data, String token) {
        cs.putString("preop.module.token", token);

        if (! token.equals(ConfigurationRequest.TOKEN_DEFAULT)) {
            try {
                CryptoManager cryptoManager = CryptoManager.getInstance();
                CryptoToken ctoken = cryptoManager.getTokenByName(token);
                String tokenpwd = data.getTokenPassword();
                ConfigurationUtils.loginToken(ctoken, tokenpwd);
            } catch (NotInitializedException e) {
                throw new PKIException("Token is not initialized");
            } catch (NoSuchTokenException e) {
                throw new BadRequestException("Invalid Token provided. No such token.");
            } catch (TokenException e) {
                e.printStackTrace();
                throw new PKIException("Token Exception" + e);
            } catch (IncorrectPasswordException e) {
                throw new BadRequestException("Incorrect Password provided for token.");
            }
        }
    }

    private void validateRequest(ConfigurationRequest data) throws Exception {

        // validate installation pin
        String pin = data.getPin();
        if (pin == null) {
            throw new BadRequestException("No preop pin provided");
        }

        String preopPin = cs.getString("preop.pin");
        if (!preopPin.equals(pin)) {
            throw new BadRequestException("Incorrect pin provided");
        }

        // validate legal stand-alone PKI subsystems
        if (data.getStandAlone()) {
            // ADD checks for valid types of Stand-alone PKI subsystems here
            // AND to the 'checkStandalonePKI()' Python method of
            // the 'ConfigurationFile' Python class in the Python file called
            // 'pkihelper.py'
            if (!csType.equals("KRA")) {
                throw new BadRequestException("Stand-alone PKI " + csType + " subsystems are currently NOT supported!");
            }
            if (data.isClone()) {
                throw new BadRequestException("A stand-alone PKI subsystem cannot be a clone");
            }
        }

        // validate security domain settings
        String domainType = data.getSecurityDomainType();
        if (domainType == null) {
            throw new BadRequestException("Security Domain Type not provided");
        }

        if (domainType.equals(ConfigurationRequest.NEW_DOMAIN)) {
            if (!(data.getStandAlone() || csType.equals("CA"))) {
                throw new BadRequestException("New Domain is only valid for stand-alone PKI or CA subsytems");
            }
            if (data.getSecurityDomainName() == null) {
                throw new BadRequestException("Security Domain Name is not provided");
            }

        } else if (domainType.equals(ConfigurationRequest.EXISTING_DOMAIN) ||
                   domainType.equals(ConfigurationRequest.NEW_SUBDOMAIN)) {
            if (data.getStandAlone()) {
                throw new BadRequestException("Existing security domains are not valid for stand-alone PKI subsytems");
            }

            String domainURI = data.getSecurityDomainUri();
            if (domainURI == null) {
                throw new BadRequestException("Existing security domain requested, but no security domain URI provided");
            }

            try {
                new URL(domainURI);
            } catch (MalformedURLException e) {
                throw new BadRequestException("Invalid security domain URI: " + domainURI, e);
            }

            if ((data.getSecurityDomainUser() == null) || (data.getSecurityDomainPassword() == null)) {
                throw new BadRequestException("Security domain user or password not provided");
            }

        } else {
            throw new BadRequestException("Invalid security domain URI provided");
        }

        // validate subordinate CA security domain settings
        if (domainType.equals(ConfigurationRequest.NEW_SUBDOMAIN)) {
            if (StringUtils.isEmpty(data.getSubordinateSecurityDomainName())) {
                throw new BadRequestException("Subordinate CA security domain name not provided");
            }
        }

        if ((data.getSubsystemName() == null) || (data.getSubsystemName().length() ==0)) {
            throw new BadRequestException("Invalid or no subsystem name provided");
        }

        if (data.isClone()) {
            String cloneUri = data.getCloneUri();
            if (cloneUri == null) {
                throw new BadRequestException("Clone selected, but no clone URI provided");
            }
            try {
                URL url = new URL(cloneUri);
                // confirm protocol is https
                if (!"https".equals(url.getProtocol())) {
                    throw new BadRequestException("Clone URI must use HTTPS protocol: " + cloneUri);
                }
            } catch (MalformedURLException e) {
                throw new BadRequestException("Invalid clone URI: " + cloneUri, e);
            }

            if (data.getToken().equals(ConfigurationRequest.TOKEN_DEFAULT)) {
                if (!data.getSystemCertsImported()) {
                    if (data.getP12File() == null) {
                        throw new BadRequestException("P12 filename not provided");
                    }

                    if (data.getP12Password() == null) {
                        throw new BadRequestException("P12 password not provided");
                    }
                }
            } else {
                if (data.getP12File() != null) {
                    throw new BadRequestException("P12 filename should not be provided since HSM clones must share their HSM master's private keys");
                }

                if (data.getP12Password() != null) {
                    throw new BadRequestException("P12 password should not be provided since HSM clones must share their HSM master's private keys");
                }
            }

        } else {
            data.setClone("false");
        }

        String dsHost = data.getDsHost();
        if (dsHost == null || dsHost.length() == 0) {
            throw new BadRequestException("Internal database host not provided");
        }

        try {
            Integer.parseInt(data.getDsPort());  // check for errors
        } catch (NumberFormatException e) {
            throw new BadRequestException("Internal database port is invalid: " + data.getDsPort(), e);
        }

        String basedn = data.getBaseDN();
        if (basedn == null || basedn.length() == 0) {
            throw new BadRequestException("Internal database basedn not provided");
        }

        String binddn = data.getBindDN();
        if (binddn == null || binddn.length() == 0) {
            throw new BadRequestException("Internal database basedn not provided");
        }

        String database = data.getDatabase();
        if (database == null || database.length() == 0) {
            throw new BadRequestException("Internal database database name not provided");
        }

        String bindpwd = data.getBindpwd();
        if (bindpwd == null || bindpwd.length() == 0) {
            throw new BadRequestException("Internal database database name not provided");
        }

        String masterReplicationPort = data.getMasterReplicationPort();
        if (masterReplicationPort != null && masterReplicationPort.length() > 0) {
            try {
                Integer.parseInt(masterReplicationPort); // check for errors
            } catch (NumberFormatException e) {
                throw new BadRequestException("Master replication port is invalid: " + masterReplicationPort, e);
            }
        }

        String cloneReplicationPort = data.getCloneReplicationPort();
        if (cloneReplicationPort != null && cloneReplicationPort.length() > 0) {
            try {
                Integer.parseInt(cloneReplicationPort); // check for errors
            } catch (NumberFormatException e) {
                throw new BadRequestException("Clone replication port is invalid: " + cloneReplicationPort, e);
            }
        }

        if ((data.getReplicateSchema() != null) && (data.getReplicateSchema().equalsIgnoreCase("false"))) {
            data.setReplicateSchema("false");
        } else {
            data.setReplicateSchema("true");
        }

        if ((data.getBackupKeys() != null) && data.getBackupKeys().equals("true")) {
            if (! data.getToken().equals(ConfigurationRequest.TOKEN_DEFAULT)) {
                throw new BadRequestException("HSMs cannot publish private keys to PKCS #12 files");
            }

            if ((data.getBackupFile() == null) || (data.getBackupFile().length()<=0)) {
                //TODO: also check for valid path, perhaps by touching file there
                throw new BadRequestException("Invalid key backup file name");
            }

            if ((data.getBackupPassword() == null) || (data.getBackupPassword().length()<8)) {
                throw new BadRequestException("key backup password must be at least 8 characters");
            }
        } else {
            data.setBackupKeys("false");
        }

        if (csType.equals("CA") && (data.getHierarchy() == null)) {
            throw new BadRequestException("Hierarchy is required for CA, not provided");
        }

        if (!data.isClone()) {
            if ((data.getAdminUID() == null) || (data.getAdminUID().length() == 0)) {
                throw new BadRequestException("Admin UID not provided");
            }
            if ((data.getAdminPassword() == null) || (data.getAdminPassword().length() == 0)) {
                throw new BadRequestException("Admin Password not provided");
            }
            if ((data.getAdminEmail() == null) || (data.getAdminEmail().length() == 0)) {
                throw new BadRequestException("Admin UID not provided");
            }
            if ((data.getAdminName() == null) || (data.getAdminName().length() == 0)) {
                throw new BadRequestException("Admin name not provided");
            }

            if (data.getImportAdminCert() == null) {
                data.setImportAdminCert("false");
            }

            if (data.getImportAdminCert().equalsIgnoreCase("true")) {
                if (data.getAdminCert() == null) {
                    throw new BadRequestException("Admin Cert not provided");
                }
            } else {
                if ((data.getAdminCertRequest() == null) || (data.getAdminCertRequest().length() == 0)) {
                    throw new BadRequestException("Admin cert request not provided");
                }
                if ((data.getAdminCertRequestType() == null) || (data.getAdminCertRequestType().length() == 0)) {
                    throw new BadRequestException("Admin cert request type not provided");
                }
                if ((data.getAdminSubjectDN() == null) || (data.getAdminSubjectDN().length() == 0)) {
                    throw new BadRequestException("Admin subjectDN not provided");
                }
            }
        }

        if (data.getGenerateServerCert() == null) {
            data.setGenerateServerCert("true");
        }

        if (! data.getGenerateSubsystemCert()) {
            // No subsystem cert to be generated.  All interactions use a shared subsystem cert.
            if (data.getSharedDB() && StringUtils.isEmpty(data.getSharedDBUserDN())) {
                throw new BadRequestException("Shared db user DN not provided");
            }
        } else {
            // if the subsystem cert is not shared, we do not need to worry about sharing the db
            data.setSharedDB("false");
        }

        if (csType.equals("TPS")) {
            if (data.getCaUri() == null) {
                throw new BadRequestException("CA URI not provided");
            }

            if (data.getTksUri() == null) {
                throw new BadRequestException("TKS URI not provided");
            }

            if (data.getEnableServerSideKeyGen().equalsIgnoreCase("true")) {
                if (data.getKraUri() == null) {
                    throw new BadRequestException("KRA URI required if server-side key generation requested");
                }
            }

            if ((data.getAuthdbBaseDN()==null) || data.getAuthdbBaseDN().isEmpty()) {
                throw new BadRequestException("Authentication Database baseDN not provided");
            }
            if ((data.getAuthdbHost()==null) || data.getAuthdbHost().isEmpty()) {
                throw new BadRequestException("Authentication Database hostname not provided");
            }
            if ((data.getAuthdbPort()==null) || data.getAuthdbPort().isEmpty()) {
                throw new BadRequestException("Authentication Database port not provided");
            }
            if ((data.getAuthdbSecureConn()==null) || data.getAuthdbSecureConn().isEmpty()) {
                throw new BadRequestException("Authentication Database secure conn not provided");
            }

            try {
                Integer.parseInt(data.getAuthdbPort()); // check for errors
            } catch (NumberFormatException e) {
                throw new BadRequestException("Authentication Database port is invalid: " + data.getAuthdbPort(), e);
            }

            // TODO check connection with authdb

            if (data.getImportSharedSecret().equalsIgnoreCase("true")) {
                data.setImportSharedSecret("true");
            } else {
                data.setImportSharedSecret("false");
            }
        }
    }
}