summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java
blob: da721b29cc944a753146989104be49696c6b3a64 (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
// --- 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.csadmin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

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

import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509Key;

import org.apache.velocity.context.Context;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.base.ISubsystem;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.property.Descriptor;
import com.netscape.certsrv.property.IDescriptor;
import com.netscape.certsrv.property.PropertySet;
import com.netscape.certsrv.util.HttpInput;
import com.netscape.cms.servlet.wizard.WizardServlet;
import com.netscape.cmsutil.crypto.CryptoUtil;

public class NamePanel extends WizardPanelBase {
    private Vector<Cert> mCerts = null;
    private WizardServlet mServlet = null;

    public NamePanel() {
    }

    /**
     * Initializes this panel.
     */
    public void init(ServletConfig config, int panelno)
            throws ServletException {
        setPanelNo(panelno);
        setName("Subject Names");
    }

    public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
            throws ServletException {
        setPanelNo(panelno);
        setName("Subject Names");
        setId(id);
        mServlet = servlet;
    }

    /**
     * Returns the usage.XXX usage needs to be made dynamic
     */
    public PropertySet getUsage() {
        PropertySet set = new PropertySet();

        Descriptor caDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
                null, /* no default parameter */
                "CA Signing Certificate's DN");

        set.add("caDN", caDN);

        Descriptor sslDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
                null, /* no default parameter */
                "SSL Server Certificate's DN");

        set.add("sslDN", sslDN);

        Descriptor subsystemDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
                null, /* no default parameter */
                "CA Subsystem Certificate's DN");

        set.add("subsystemDN", subsystemDN);

        Descriptor ocspDN = new Descriptor(IDescriptor.STRING, null, /* no constraint */
                null, /* no default parameter */
                "OCSP Signing Certificate's DN");

        set.add("ocspDN", ocspDN);

        return set;
    }

    public void cleanUp() throws IOException {
        IConfigStore cs = CMS.getConfigStore();
        try {
            boolean done = cs.getBoolean("preop.NamePanel.done");
            cs.putBoolean("preop.NamePanel.done", false);
            cs.commit(false);
        } catch (Exception e) {
        }

        String list = "";
        try {
            list = cs.getString("preop.cert.list", "");
        } catch (Exception e) {
        }

        StringTokenizer st = new StringTokenizer(list, ",");
        while (st.hasMoreTokens()) {
            String t = st.nextToken();
            cs.remove("preop.cert." + t + ".done");
        }

        try {
            cs.commit(false);
        } catch (Exception e) {
        }
    }

    public boolean isPanelDone() {
        IConfigStore cs = CMS.getConfigStore();
        try {
            boolean s = cs.getBoolean("preop.NamePanel.done", false);
            if (s != true) {
                return false;
            } else {
                return true;
            }
        } catch (EBaseException e) {
        }

        return false;
    }

    public String capitalize(String s) {
        if (s.length() == 0) {
            return s;
        } else {
            return s.substring(0, 1).toUpperCase() + s.substring(1);
        }
    }

    /**
     * Display the panel.
     */
    public void display(HttpServletRequest request,
            HttpServletResponse response,
            Context context) {
        CMS.debug("NamePanel: display()");
        context.put("title", "Subject Names");

        // update session id 
        String session_id = request.getParameter("session_id");
        if (session_id != null) {
            CMS.debug("NamePanel setting session id.");
            CMS.setConfigSDSessionId(session_id);
        }

        mCerts = new Vector<Cert>();

        String domainname = "";
        IConfigStore config = CMS.getConfigStore();
        String select = "";
        String hselect = "";
        String cstype = "";
        try {
            //if CA, at the hierarchy panel, was it root or subord?
            hselect = config.getString("preop.hierarchy.select", "");
            select = config.getString("preop.subsystem.select", "");
            cstype = config.getString("cs.type", "");
            context.put("select", select);
            if (cstype.equals("CA") && hselect.equals("root")) {
                CMS.debug("NamePanel ca is root");
                context.put("isRoot", "true");
            } else {
                CMS.debug("NamePanel not ca or not root");
                context.put("isRoot", "false");
            }
        } catch (Exception e) {
        }

        try {
            domainname = config.getString("securitydomain.name", "");

            String certTags = config.getString("preop.cert.list");
            // same token for now
            String token = config.getString(PRE_CONF_CA_TOKEN);
            StringTokenizer st = new StringTokenizer(certTags, ",");
            String domaintype = config.getString("securitydomain.select");
            int count = 0;
            String host = "";
            int sd_admin_port = -1;
            if (domaintype.equals("existing")) {
                host = config.getString("securitydomain.host", "");
                sd_admin_port = config.getInteger("securitydomain.httpsadminport", -1);
                count = getSubsystemCount(host, sd_admin_port, true, cstype);
            }

            while (st.hasMoreTokens()) {
                String certTag = st.nextToken();

                CMS.debug("NamePanel: display() about to process certTag :" + certTag);
                String nn = config.getString(
                        PCERT_PREFIX + certTag + ".nickname");
                Cert c = new Cert(token, nn, certTag);
                String userfriendlyname = config.getString(
                        PCERT_PREFIX + certTag + ".userfriendlyname");
                String subsystem = config.getString(
                        PCERT_PREFIX + certTag + ".subsystem");

                c.setUserFriendlyName(userfriendlyname);

                String type = config.getString(PCERT_PREFIX + certTag + ".type");
                c.setType(type);
                boolean enable = config.getBoolean(PCERT_PREFIX + certTag + ".enable", true);
                c.setEnable(enable);

                String cert = config.getString(subsystem + "." + certTag + ".cert", "");
                String certreq =
                        config.getString(subsystem + "." + certTag + ".certreq", "");

                String dn = config.getString(PCERT_PREFIX + certTag + ".dn");
                boolean override = config.getBoolean(PCERT_PREFIX + certTag +
                        ".cncomponent.override", true);
                //o_sd is to add o=secritydomainname
                boolean o_sd = config.getBoolean(PCERT_PREFIX + certTag +
                         "o_securitydomain", true);
                domainname = config.getString("securitydomain.name", "");
                CMS.debug("NamePanel: display() override is " + override);
                CMS.debug("NamePanel: display() o_securitydomain is " + o_sd);
                CMS.debug("NamePanel: display() domainname is " + domainname);

                boolean dnUpdated = false;
                try {
                    dnUpdated = config.getBoolean(PCERT_PREFIX + certTag + ".updatedDN");
                } catch (Exception e) {
                }

                try {
                    boolean done = config.getBoolean("preop.NamePanel.done");
                    c.setDN(dn);
                } catch (Exception e) {
                    String instanceId = config.getString("service.instanceID", "");
                    if (select.equals("clone") || dnUpdated) {
                        c.setDN(dn);
                    } else if (count != 0 && override && (cert.equals("") || certreq.equals(""))) {
                        CMS.debug("NamePanel subsystemCount = " + count);
                        c.setDN(dn + " " + count +
                                ((!instanceId.equals("")) ? (",OU=" + instanceId) : "") +
                                ((o_sd) ? (",O=" + domainname) : ""));
                        config.putBoolean(PCERT_PREFIX + certTag + ".updatedDN", true);
                    } else {
                        c.setDN(dn +
                                ((!instanceId.equals("")) ? (",OU=" + instanceId) : "") +
                                ((o_sd) ? (",O=" + domainname) : ""));
                        config.putBoolean(PCERT_PREFIX + certTag + ".updatedDN", true);
                    }
                }

                mCerts.addElement(c);
                CMS.debug(
                        "NamePanel: display() added cert to mCerts: certTag "
                                + certTag);
                config.putString(PCERT_PREFIX + c.getCertTag() + ".dn", c.getDN());
            }// while
        } catch (EBaseException e) {
            CMS.debug("NamePanel: display() exception caught:" + e.toString());
        } catch (Exception e) {
            CMS.debug("NamePanel: " + e.toString());
        }

        CMS.debug("NamePanel: Ready to get SSL EE HTTPS urls");
        Vector v = getUrlListFromSecurityDomain(config, "CA", "SecurePort");
        v.addElement("External CA");
        StringBuffer list = new StringBuffer();
        int size = v.size();

        for (int i = 0; i < size; i++) {
            if (i == size - 1) {
                list.append(v.elementAt(i));
            } else {
                list.append(v.elementAt(i));
                list.append(",");
            }
        }

        try {
            config.putString("preop.ca.list", list.toString());
            config.commit(false);
        } catch (Exception e) {
        }

        context.put("urls", v);

        context.put("certs", mCerts);
        context.put("panel", "admin/console/config/namepanel.vm");
        context.put("errorString", "");

    }

    /**
     * Checks if the given parameters are valid.
     */
    public void validate(HttpServletRequest request,
            HttpServletResponse response,
            Context context) throws IOException {
        Enumeration<Cert> c = mCerts.elements();

        while (c.hasMoreElements()) {
            Cert cert = c.nextElement();
            // get the dn's and put in config
            if (cert.isEnable()) {
                String dn = HttpInput.getDN(request, cert.getCertTag());

                if (dn == null || dn.length() == 0) {
                    context.put("updateStatus", "validate-failure");
                    throw new IOException("Empty DN for " + cert.getUserFriendlyName());
                }
            }
        } // while
    }

    /* 
     * update some parameters for clones
     */
    public void updateCloneConfig(IConfigStore config)
            throws EBaseException, IOException {
        String cstype = config.getString("cs.type", null);
        cstype = toLowerCaseSubsystemType(cstype);
        if (cstype.equals("kra")) {
            String token = config.getString(PRE_CONF_CA_TOKEN);
            if (!token.equals("Internal Key Storage Token")) {
                CMS.debug("NamePanel: updating configuration for KRA clone with hardware token");
                String subsystem = config.getString(PCERT_PREFIX + "storage.subsystem");
                String storageNickname = getNickname(config, "storage");
                String transportNickname = getNickname(config, "transport");

                config.putString(subsystem + ".storageUnit.hardware", token);
                config.putString(subsystem + ".storageUnit.nickName", token + ":" + storageNickname);
                config.putString(subsystem + ".transportUnit.nickName", token + ":" + transportNickname);
                config.commit(false);
            } else { // software token
                // parameters already set
            }
        }

        // audit signing cert
        String audit_nn = config.getString(cstype + ".audit_signing" + ".nickname", "");
        String audit_tk = config.getString(cstype + ".audit_signing" + ".tokenname", "");
        if (!audit_tk.equals("Internal Key Storage Token") && !audit_tk.equals("")) {
            config.putString("log.instance.SignedAudit.signedAuditCertNickname",
                    audit_tk + ":" + audit_nn);
        } else {
            config.putString("log.instance.SignedAudit.signedAuditCertNickname",
                    audit_nn);
        }
    }

    /*
     * get some of the "preop" parameters to persisting parameters
     */
    public void updateConfig(IConfigStore config, String certTag)
            throws EBaseException, IOException {
        String token = config.getString(PRE_CONF_CA_TOKEN);
        String subsystem = config.getString(PCERT_PREFIX + certTag + ".subsystem");
        CMS.debug("NamePanel: subsystem " + subsystem);
        String nickname = getNickname(config, certTag);

        CMS.debug("NamePanel: updateConfig() for certTag " + certTag);
        // XXX these two are used throughout the CA so have to write them
        // should change the entire system to use the uniformed names later
        if (certTag.equals("signing") || certTag.equals("ocsp_signing")) {
            CMS.debug("NamePanel: setting signing nickname=" + nickname);
            config.putString(subsystem + "." + certTag + ".cacertnickname", nickname);
            config.putString(subsystem + "." + certTag + ".certnickname", nickname);
        }

        // if KRA, hardware token needs param "kra.storageUnit.hardware" in CS.cfg
        String cstype = config.getString("cs.type", null);
        cstype = toLowerCaseSubsystemType(cstype);
        if (cstype.equals("kra")) {
            if (!token.equals("Internal Key Storage Token")) {
                if (certTag.equals("storage")) {
                    config.putString(subsystem + ".storageUnit.hardware", token);
                    config.putString(subsystem + ".storageUnit.nickName", token + ":" + nickname);
                } else if (certTag.equals("transport")) {
                    config.putString(subsystem + ".transportUnit.nickName", token + ":" + nickname);
                }
            } else { // software token
                if (certTag.equals("storage")) {
                    config.putString(subsystem + ".storageUnit.nickName", nickname);
                } else if (certTag.equals("transport")) {
                    config.putString(subsystem + ".transportUnit.nickName", nickname);
                }
            }
        }

        String serverCertNickname = nickname;
        String path = CMS.getConfigStore().getString("instanceRoot", "");
        if (certTag.equals("sslserver")) {
            if (!token.equals("Internal Key Storage Token")) {
                serverCertNickname = token + ":" + nickname;
            }
            File file = new File(path + "/conf/serverCertNick.conf");
            PrintStream ps = new PrintStream(new FileOutputStream(path + "/conf/serverCertNick.conf"));
            ps.println(serverCertNickname);
            ps.close();
        }

        config.putString(subsystem + "." + certTag + ".nickname", nickname);
        config.putString(subsystem + "." + certTag + ".tokenname", token);
        if (certTag.equals("audit_signing")) {
            if (!token.equals("Internal Key Storage Token") && !token.equals("")) {
                config.putString("log.instance.SignedAudit.signedAuditCertNickname",
                        token + ":" + nickname);
            } else {
                config.putString("log.instance.SignedAudit.signedAuditCertNickname",
                        nickname);
            }
        }
        /*
        config.putString(CERT_PREFIX + certTag + ".defaultSigningAlgorithm",
                "SHA1withRSA");
         */

        // for system certs verification
        if (!token.equals("Internal Key Storage Token") && !token.equals("")) {
            config.putString(subsystem + ".cert." + certTag + ".nickname",
                    token + ":" + nickname);
        } else {
            config.putString(subsystem + ".cert." + certTag + ".nickname", nickname);
        }

        config.commit(false);
        CMS.debug("NamePanel: updateConfig() done");
    }

    /**
     * create and sign a cert locally (handles both "selfsign" and "local")
     */
    public void configCert(HttpServletRequest request,
            HttpServletResponse response,
            Context context, Cert certObj) throws IOException {
        CMS.debug("NamePanel: configCert called");

        IConfigStore config = CMS.getConfigStore();
        String caType = certObj.getType();
        CMS.debug("NamePanel: in configCert caType is " + caType);
        X509CertImpl cert = null;
        String certTag = certObj.getCertTag();

        try {
            updateConfig(config, certTag);
            if (caType.equals("remote")) {
                String v = config.getString("preop.ca.type", "");

                CMS.debug("NamePanel configCert: remote CA");
                String pkcs10 = CertUtil.getPKCS10(config, PCERT_PREFIX,
                        certObj, context);
                certObj.setRequest(pkcs10);
                String subsystem = config.getString(
                        PCERT_PREFIX + certTag + ".subsystem");
                config.putString(subsystem + "." + certTag + ".certreq", pkcs10);
                String profileId = config.getString(PCERT_PREFIX + certTag + ".profile");
                String session_id = CMS.getConfigSDSessionId();
                String sd_hostname = "";
                int sd_ee_port = -1;
                try {
                    sd_hostname = config.getString("securitydomain.host", "");
                    sd_ee_port = config.getInteger("securitydomain.httpseeport", -1);
                } catch (Exception ee) {
                    CMS.debug("NamePanel: configCert() exception caught:" + ee.toString());
                }
                String sysType = config.getString("cs.type", "");
                String machineName = config.getString("machineName", "");
                String securePort = config.getString("service.securePort", "");
                if (certTag.equals("subsystem")) {
                    String content =
                            "requestor_name="
                                    + sysType + "-" + machineName + "-" + securePort + "&profileId=" + profileId
                                    + "&cert_request_type=pkcs10&cert_request=" + URLEncoder.encode(pkcs10, "UTF-8")
                                    + "&xmlOutput=true&sessionID=" + session_id;
                    cert = CertUtil.createRemoteCert(sd_hostname, sd_ee_port,
                            content, response, this);
                    if (cert == null) {
                        throw new IOException("Error: remote certificate is null");
                    }
                } else if (v.equals("sdca")) {
                    String ca_hostname = "";
                    int ca_port = -1;
                    try {
                        ca_hostname = config.getString("preop.ca.hostname", "");
                        ca_port = config.getInteger("preop.ca.httpsport", -1);
                    } catch (Exception ee) {
                    }

                    String content =
                            "requestor_name="
                                    + sysType + "-" + machineName + "-" + securePort + "&profileId=" + profileId
                                    + "&cert_request_type=pkcs10&cert_request=" + URLEncoder.encode(pkcs10, "UTF-8")
                                    + "&xmlOutput=true&sessionID=" + session_id;
                    cert = CertUtil.createRemoteCert(ca_hostname, ca_port,
                            content, response, this);
                    if (cert == null) {
                        throw new IOException("Error: remote certificate is null");
                    }
                } else if (v.equals("otherca")) {
                    config.putString(subsystem + "." + certTag + ".cert",
                            "...paste certificate here...");
                } else {
                    CMS.debug("NamePanel: no preop.ca.type is provided");
                }
            } else { // not remote CA, ie, self-signed or local
                ISubsystem ca = CMS.getSubsystem(ICertificateAuthority.ID);

                if (ca == null) {
                    String s = PCERT_PREFIX + certTag + ".type";

                    CMS.debug(
                            "The value for " + s
                                    + " should be remote, nothing else.");
                    throw new IOException(
                            "The value for " + s + " should be remote");
                }

                String pubKeyType = config.getString(
                        PCERT_PREFIX + certTag + ".keytype");
                if (pubKeyType.equals("rsa")) {

                    String pubKeyModulus = config.getString(
                            PCERT_PREFIX + certTag + ".pubkey.modulus");
                    String pubKeyPublicExponent = config.getString(
                            PCERT_PREFIX + certTag + ".pubkey.exponent");
                    String subsystem = config.getString(
                            PCERT_PREFIX + certTag + ".subsystem");

                    if (certTag.equals("signing")) {
                        X509Key x509key = CryptoUtil.getPublicX509Key(
                                CryptoUtil.string2byte(pubKeyModulus),
                                CryptoUtil.string2byte(pubKeyPublicExponent));

                        cert = CertUtil.createLocalCert(config, x509key,
                                PCERT_PREFIX, certTag, caType, context);
                    } else {
                        String cacert = config.getString("ca.signing.cert", "");

                        if (cacert.equals("") || cacert.startsWith("...")) {
                            certObj.setCert(
                                    "...certificate be generated internally...");
                            config.putString(subsystem + "." + certTag + ".cert",
                                    "...certificate be generated internally...");
                        } else {
                            X509Key x509key = CryptoUtil.getPublicX509Key(
                                    CryptoUtil.string2byte(pubKeyModulus),
                                    CryptoUtil.string2byte(pubKeyPublicExponent));

                            cert = CertUtil.createLocalCert(config, x509key,
                                    PCERT_PREFIX, certTag, caType, context);
                        }
                    }
                } else if (pubKeyType.equals("ecc")) {
                    String pubKeyEncoded = config.getString(
                            PCERT_PREFIX + certTag + ".pubkey.encoded");
                    String subsystem = config.getString(
                            PCERT_PREFIX + certTag + ".subsystem");

                    if (certTag.equals("signing")) {

                        X509Key x509key = CryptoUtil.getPublicX509ECCKey(CryptoUtil.string2byte(pubKeyEncoded));
                        cert = CertUtil.createLocalCert(config, x509key,
                                PCERT_PREFIX, certTag, caType, context);
                    } else {
                        String cacert = config.getString("ca.signing.cert", "");

                        if (cacert.equals("") || cacert.startsWith("...")) {
                            certObj.setCert(
                                    "...certificate be generated internally...");
                            config.putString(subsystem + "." + certTag + ".cert",
                                    "...certificate be generated internally...");
                        } else {
                            X509Key x509key = CryptoUtil.getPublicX509ECCKey(
                                    CryptoUtil.string2byte(pubKeyEncoded));

                            cert = CertUtil.createLocalCert(config, x509key,
                                    PCERT_PREFIX, certTag, caType, context);
                        }
                    }
                } else {
                    // invalid key type
                    CMS.debug("Invalid key type " + pubKeyType);
                }
                if (cert != null) {
                    if (certTag.equals("subsystem"))
                        CertUtil.addUserCertificate(cert);
                }
            } // done self-signed or local

            if (cert != null) {
                byte[] certb = cert.getEncoded();
                String certs = CryptoUtil.base64Encode(certb);

                // certObj.setCert(certs);
                String subsystem = config.getString(
                        PCERT_PREFIX + certTag + ".subsystem");
                config.putString(subsystem + "." + certTag + ".cert", certs);
            }
            config.commit(false);
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            CMS.debug("NamePanel configCert() exception caught:" + e.toString());
        }
    }

    public void configCertWithTag(HttpServletRequest request,
            HttpServletResponse response,
            Context context, String tag) throws IOException {
        CMS.debug("NamePanel: configCertWithTag start");
        Enumeration<Cert> c = mCerts.elements();
        IConfigStore config = CMS.getConfigStore();

        while (c.hasMoreElements()) {
            Cert cert = c.nextElement();
            String ct = cert.getCertTag();
            CMS.debug("NamePanel: configCertWithTag ct=" + ct +
                        " tag=" + tag);
            if (ct.equals(tag)) {
                try {
                    String nickname = HttpInput.getNickname(request, ct + "_nick");
                    if (nickname != null) {
                        CMS.debug("configCertWithTag: Setting nickname for " + ct + " to " + nickname);
                        config.putString(PCERT_PREFIX + ct + ".nickname", nickname);
                        cert.setNickname(nickname);
                        config.commit(false);
                    }
                    String dn = HttpInput.getDN(request, ct);
                    if (dn != null) {
                        config.putString(PCERT_PREFIX + ct + ".dn", dn);
                        config.commit(false);
                    }
                } catch (Exception e) {
                    CMS.debug("NamePanel: configCertWithTag: Exception in setting nickname for "
                            + ct + ": " + e.toString());
                }

                configCert(request, response, context, cert);
                CMS.debug("NamePanel: configCertWithTag done with tag=" + tag);
                return;
            }
        }
        CMS.debug("NamePanel: configCertWithTag done");
    }

    private boolean inputChanged(HttpServletRequest request)
            throws IOException {
        IConfigStore config = CMS.getConfigStore();

        boolean hasChanged = false;
        try {
            Enumeration<Cert> c = mCerts.elements();

            while (c.hasMoreElements()) {
                Cert cert = c.nextElement();
                String ct = cert.getCertTag();
                boolean enable = config.getBoolean(PCERT_PREFIX + ct + ".enable", true);
                if (!enable)
                    continue;

                String olddn = config.getString(PCERT_PREFIX + cert.getCertTag() + ".dn", "");
                // get the dn's and put in config
                String dn = HttpInput.getDN(request, cert.getCertTag());

                if (!olddn.equals(dn))
                    hasChanged = true;

                String oldnick = config.getString(PCERT_PREFIX + ct + ".nickname");
                String nick = HttpInput.getNickname(request, ct + "_nick");
                if (!oldnick.equals(nick))
                    hasChanged = true;

            }
        } catch (Exception e) {
        }

        return hasChanged;
    }

    public String getURL(HttpServletRequest request, IConfigStore config) {
        String index = request.getParameter("urls");
        if (index == null) {
            return null;
        }
        String url = "";
        if (index.startsWith("http")) {
            // user may submit url directlry
            url = index;
        } else {
            try {
                int x = Integer.parseInt(index);
                String list = config.getString("preop.ca.list", "");
                StringTokenizer tokenizer = new StringTokenizer(list, ",");
                int counter = 0;

                while (tokenizer.hasMoreTokens()) {
                    url = tokenizer.nextToken();
                    if (counter == x) {
                        break;
                    }
                    counter++;
                }
            } catch (Exception e) {
            }
        }
        return url;
    }

    /**
     * Commit parameter changes
     */
    public void update(HttpServletRequest request,
            HttpServletResponse response,
            Context context) throws IOException {
        CMS.debug("NamePanel: in update()");
        boolean hasErr = false;

        if (inputChanged(request)) {
            mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
        } else if (isPanelDone()) {
            context.put("updateStatus", "success");
            return;
        }

        IConfigStore config = CMS.getConfigStore();

        String hselect = "";
        ISubsystem subsystem = CMS.getSubsystem(ICertificateAuthority.ID);
        try {
            //if CA, at the hierarchy panel, was it root or subord?
            hselect = config.getString("preop.hierarchy.select", "");
            String cstype = config.getString("preop.subsystem.select", "");
            if (cstype.equals("clone")) {
                CMS.debug("NamePanel: clone configuration detected");
                // still need to handle SSL certificate
                configCertWithTag(request, response, context, "sslserver");
                String url = getURL(request, config);
                if (url != null && !url.equals("External CA")) {
                    // preop.ca.url and admin port are required for setting KRA connector
                    url = url.substring(url.indexOf("https"));
                    config.putString("preop.ca.url", url);

                    URL urlx = new URL(url);
                    updateCloneSDCAInfo(request, context, urlx.getHost(),
                            Integer.toString(urlx.getPort()));

                }
                updateCloneConfig(config);
                CMS.debug("NamePanel: clone configuration done");
                context.put("updateStatus", "success");
                return;
            }
        } catch (Exception e) {
            CMS.debug("NamePanel: configCertWithTag failure - " + e);
            context.put("updateStatus", "failure");
            return;
        }

        //if no hselect, then not CA
        if (hselect.equals("") || hselect.equals("join")) {
            String select = null;
            String url = getURL(request, config);

            URL urlx = null;

            if (url.equals("External CA")) {
                CMS.debug("NamePanel: external CA selected");
                select = "otherca";
                config.putString("preop.ca.type", "otherca");
                if (subsystem != null) {
                    config.putString(PCERT_PREFIX + "signing.type", "remote");
                }

                config.putString("preop.ca.pkcs7", "");
                config.putInteger("preop.ca.certchain.size", 0);
                context.put("check_otherca", "checked");
                CMS.debug("NamePanel: update: this is the external CA.");
            } else {
                CMS.debug("NamePanel: local CA selected");
                select = "sdca";
                // parse URL (CA1 - https://...)
                url = url.substring(url.indexOf("https"));
                config.putString("preop.ca.url", url);

                urlx = new URL(url);
                config.putString("preop.ca.type", "sdca");
                CMS.debug("NamePanel: update: this is a CA in the security domain.");
                context.put("check_sdca", "checked");
                sdca(request, context, urlx.getHost(),
                        Integer.toString(urlx.getPort()));
                if (subsystem != null) {
                    config.putString(PCERT_PREFIX + "signing.type", "remote");
                    config.putString(PCERT_PREFIX + "signing.profile",
                            "caInstallCACert");
                }
            }

            try {
                config.commit(false);
            } catch (Exception e) {
            }

        }

        try {

            Enumeration<Cert> c = mCerts.elements();

            while (c.hasMoreElements()) {
                Cert cert = c.nextElement();
                String ct = cert.getCertTag();
                String tokenname = cert.getTokenname();
                boolean enable = config.getBoolean(PCERT_PREFIX + ct + ".enable", true);
                if (!enable)
                    continue;

                boolean certDone = config.getBoolean(PCERT_PREFIX + ct + ".done", false);
                if (certDone)
                    continue;

                // get the nicknames and put in config
                String nickname = HttpInput.getNickname(request, ct + "_nick");
                if (nickname != null) {
                    CMS.debug("NamePanel: update: Setting nickname for " + ct + " to " + nickname);
                    config.putString(PCERT_PREFIX + ct + ".nickname", nickname);
                    cert.setNickname(nickname);
                } else {
                    nickname = cert.getNickname();
                }

                // get the dn's and put in config
                String dn = HttpInput.getDN(request, ct);

                config.putString(PCERT_PREFIX + ct + ".dn", dn);
                // commit here in case it changes
                config.commit(false);

                try {
                    configCert(request, response, context, cert);
                    config.putBoolean("preop.cert." + cert.getCertTag() + ".done",
                            true);
                    config.commit(false);
                } catch (Exception e) {
                    CMS.debug(
                            "NamePanel: update() exception caught:"
                                    + e.toString());
                    hasErr = true;
                    System.err.println("Exception caught: " + e.toString());
                }

            } // while 
            if (hasErr == false) {
                config.putBoolean("preop.NamePanel.done", true);
                config.commit(false);
            }

        } catch (Exception e) {
            CMS.debug("NamePanel: Exception caught: " + e.toString());
            System.err.println("Exception caught: " + e.toString());
        }// try

        try {
            config.commit(false);
        } catch (Exception e) {
        }

        if (!hasErr) {
            context.put("updateStatus", "success");
        } else {
            context.put("updateStatus", "failure");
        }
        CMS.debug("NamePanel: update() done");
    }

    private void updateCloneSDCAInfo(HttpServletRequest request, Context context, String hostname, String httpsPortStr)
            throws IOException {
        CMS.debug("NamePanel updateCloneSDCAInfo: selected CA hostname=" + hostname + " port=" + httpsPortStr);
        String https_admin_port = "";
        IConfigStore config = CMS.getConfigStore();

        if (hostname == null || hostname.length() == 0) {
            context.put("errorString", "Hostname is null");
            throw new IOException("Hostname is null");
        }

        // Retrieve the associated HTTPS Admin port so that it
        // may be stored for use with ImportAdminCertPanel
        https_admin_port = getSecurityDomainAdminPort(config,
                                                       hostname,
                                                       httpsPortStr,
                                                       "CA");

        int httpsport = -1;

        try {
            httpsport = Integer.parseInt(httpsPortStr);
        } catch (Exception e) {
            CMS.debug(
                    "NamePanel update: Https port is not valid. Exception: "
                            + e.toString());
            throw new IOException("Https Port is not valid.");
        }

        config.putString("preop.ca.hostname", hostname);
        config.putString("preop.ca.httpsport", httpsPortStr);
        config.putString("preop.ca.httpsadminport", https_admin_port);
    }

    private void sdca(HttpServletRequest request, Context context, String hostname, String httpsPortStr)
            throws IOException {
        CMS.debug("NamePanel update: this is the CA in the security domain.");
        CMS.debug("NamePanel update: selected CA hostname=" + hostname + " port=" + httpsPortStr);
        String https_admin_port = "";
        IConfigStore config = CMS.getConfigStore();

        context.put("sdcaHostname", hostname);
        context.put("sdHttpPort", httpsPortStr);

        if (hostname == null || hostname.length() == 0) {
            context.put("errorString", "Hostname is null");
            throw new IOException("Hostname is null");
        }

        // Retrieve the associated HTTPS Admin port so that it
        // may be stored for use with ImportAdminCertPanel
        https_admin_port = getSecurityDomainAdminPort(config,
                                                       hostname,
                                                       httpsPortStr,
                                                       "CA");

        int httpsport = -1;

        try {
            httpsport = Integer.parseInt(httpsPortStr);
        } catch (Exception e) {
            CMS.debug(
                    "NamePanel update: Https port is not valid. Exception: "
                            + e.toString());
            throw new IOException("Https Port is not valid.");
        }

        config.putString("preop.ca.hostname", hostname);
        config.putString("preop.ca.httpsport", httpsPortStr);
        config.putString("preop.ca.httpsadminport", https_admin_port);
        ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
        updateCertChainUsingSecureEEPort(config, "ca", hostname,
                                          httpsport, true, context,
                                          certApprovalCallback);
        try {
            CMS.debug("Importing CA chain");
            importCertChain("ca");
        } catch (Exception e1) {
            CMS.debug("Failed in importing CA chain");
        }
    }

    public void initParams(HttpServletRequest request, Context context)
                   throws IOException {
        context.put("certs", mCerts);
    }

    /**
     * If validiate() returns false, this method will be called.
     */
    public void displayError(HttpServletRequest request,
            HttpServletResponse response,
            Context context) {
        try {
            initParams(request, context);
        } catch (IOException e) {
        }
        context.put("title", "Subject Names");
        context.put("panel", "admin/console/config/namepanel.vm");
    }
}