summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/csadmin
diff options
context:
space:
mode:
Diffstat (limited to 'pki/base/common/src/com/netscape/cms/servlet/csadmin')
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java326
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java687
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java229
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java193
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java430
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java114
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java328
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java184
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java216
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java757
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java652
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java115
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java117
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java37
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java46
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java46
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java190
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java318
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java287
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java46
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java185
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java135
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java302
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java1507
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java45
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java235
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java45
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java800
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java146
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java160
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java211
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java276
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java241
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java115
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java155
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java147
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java189
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java203
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java342
-rwxr-xr-xpki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java161
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java195
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java333
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java70
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java155
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java330
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java86
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java986
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java255
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java693
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java159
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java81
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java500
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java100
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java47
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java652
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java137
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java203
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java486
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java284
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java180
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java123
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java45
-rw-r--r--pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java1603
63 files changed, 18621 insertions, 0 deletions
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java
new file mode 100644
index 000000000..876cd2a04
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminAuthenticatePanel.java
@@ -0,0 +1,326 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.certsrv.base.*;
+import java.util.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class AdminAuthenticatePanel extends WizardPanelBase {
+
+ public AdminAuthenticatePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Admin Authentication");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Admin Authentication");
+ setId(id);
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ /**
+ * Should we skip this panel for the configuration.
+ */
+ public boolean shouldSkip() {
+ CMS.debug("AdminAuthenticatePanel: should skip");
+
+ IConfigStore cs = CMS.getConfigStore();
+ // if we are root, no need to get the certificate chain.
+
+ try {
+ String select = cs.getString("preop.subsystem.select","");
+ if (select.equals("new")) {
+ return true;
+ }
+ } catch (EBaseException e) {
+ }
+
+ return false;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ /* clean up if necessary */
+ try {
+ boolean done = cs.getBoolean("preop.AdminAuthenticate.done");
+ cs.putBoolean("preop.AdminAuthenticate.done", false);
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.AdminAuthenticate.done", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Admin Authentication");
+ IConfigStore config = CMS.getConfigStore();
+
+ if (isPanelDone()) {
+
+ try {
+ String s = config.getString("preop.master.admin.uid", "");
+ String type = config.getString("preop.subsystem.select", "");
+ if (type.equals("clone"))
+ context.put("uid", s);
+ else
+ context.put("uid", "");
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("uid", "");
+ }
+
+ context.put("password", "");
+ context.put("panel", "admin/console/config/adminauthenticatepanel.vm");
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ String subsystemtype = "";
+ String cstype = "";
+ try {
+ subsystemtype = config.getString("preop.subsystem.select", "");
+ cstype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ }
+ cstype = toLowerCaseSubsystemType(cstype);
+
+ if (subsystemtype.equals("clone")) {
+ CMS.debug("AdminAuthenticatePanel: this is the clone subsystem");
+ String uid = HttpInput.getUID(request, "uid");
+ if (uid == null) {
+ context.put("errorString", "Uid is empty");
+ throw new IOException("Uid is empty");
+ }
+ context.put("uid", uid);
+ String pwd = HttpInput.getPassword(request, "__password");
+ config.putString("preop.master.admin.uid", uid);
+ config.putString("preop.master.admin.pwd", pwd);
+ String host = "";
+ int httpsport = -1;
+ try {
+ host = config.getString("preop.master.hostname");
+ } catch (Exception e) {
+ CMS.debug("AdminAuthenticatePanel update: "+e.toString());
+ context.put("errorString", "Missing hostname for master");
+ throw new IOException("Missing hostname");
+ }
+
+ try {
+ httpsport = config.getInteger("preop.master.httpsadminport");
+ } catch (Exception e) {
+ CMS.debug("AdminAuthenticatePanel update: "+e.toString());
+ context.put("errorString", "Missing port for master");
+ throw new IOException("Missing port");
+ }
+
+ String list = "";
+ try {
+ list = config.getString("preop.cert.list", "");
+ } catch (Exception e) {
+ }
+
+ StringBuffer c1 = new StringBuffer();
+ StringBuffer s1 = new StringBuffer();
+
+ StringTokenizer tok = new StringTokenizer(list, ",");
+ while (tok.hasMoreTokens()) {
+ String t1 = tok.nextToken();
+ c1.append(",");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".nickname,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".dn,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".keytype,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".keyalgorithm,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".privkey.id,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".pubkey.exponent,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".pubkey.modulus,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".pubkey.encoded");
+
+ if (s1.length()!=0)
+ s1.append(",");
+
+ s1.append(cstype);
+ s1.append(".");
+ s1.append(t1);
+ }
+
+ if (!cstype.equals("ca")) {
+ c1.append(",preop.ca.hostname,preop.ca.httpport,preop.ca.httpsport,preop.ca.list,preop.ca.pkcs7,preop.ca.type");
+ }
+
+ String content = "uid="+uid+"&pwd="+pwd+"&op=get&names=cloning.module.token,instanceId,internaldb.basedn,internaldb.ldapauth.password,internaldb.replication.password,internaldb.ldapconn.host,internaldb.ldapconn.port,internaldb.ldapauth.bindDN"+c1.toString()+"&substores="+s1.toString();
+
+ boolean success = updateConfigEntries(host, httpsport, true,
+ "/"+cstype+"/admin/"+cstype+"/getConfigEntries", content, config,
+ response);
+
+ try {
+ config.commit(false);
+ } catch (Exception ee) {
+ }
+
+ if (!success) {
+ context.put("errorString", "Failed to get configuration entries from the master");
+ throw new IOException("Failed to get configuration entries from the master");
+ } else {
+ boolean cloneReady = isCertdbCloned(request, context);
+ if (!cloneReady) {
+ CMS.debug("AdminAuthenticatePanel update: clone does not have all the certificates.");
+ context.put("errorString", "Make sure you have copied the certificate database over to the clone");
+ throw new IOException("Clone is not ready");
+ }
+ }
+ } else {
+ CMS.debug("AdminAuthentication update: no authentication is required.");
+ }
+
+ config.putBoolean("preop.AdminAuthenticate.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context)
+ {
+ context.put("title", "Admin Authentication");
+ context.put("password", "");
+ context.put("panel", "admin/console/config/adminauthenticatepanel.vm");
+ }
+
+ private boolean isCertdbCloned(HttpServletRequest request,
+ Context context) {
+ IConfigStore config = CMS.getConfigStore();
+ String certList = "";
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ certList = config.getString("preop.cert.list");
+ StringTokenizer st = new StringTokenizer(certList, ",");
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken();
+ String tokenname = config.getString("preop.module.token", "");
+ CryptoToken tok = cm.getTokenByName(tokenname);
+ CryptoStore store = tok.getCryptoStore();
+ String name1 = "preop.master."+token+".nickname";
+ String nickname = config.getString(name1, "");
+ if (!tokenname.equals("Internal Key Storage Token") &&
+ !tokenname.equals("internal"))
+ nickname = tokenname+":"+nickname;
+
+ CMS.debug("AdminAuthenticatePanel isCertdbCloned: "+nickname);
+ X509Certificate cert = cm.findCertByNickname(nickname);
+ if (cert == null)
+ return false;
+ }
+ } catch (Exception e) {
+ context.put("errorString", "Check your CS.cfg for cloning");
+ return false;
+ }
+
+ return true;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java
new file mode 100644
index 000000000..c205dad95
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AdminPanel.java
@@ -0,0 +1,687 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.cmsutil.http.*;
+import com.netscape.certsrv.template.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.request.*;
+import com.netscape.certsrv.ca.*;
+import java.io.*;
+import java.util.*;
+import java.security.*;
+import java.security.cert.*;
+import java.net.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+import com.netscape.cmsutil.xml.*;
+import org.xml.sax.*;
+import org.mozilla.jss.asn1.*;
+import org.mozilla.jss.pkix.*;
+import org.mozilla.jss.pkix.primitive.*;
+import org.mozilla.jss.pkix.crmf.*;
+
+import com.netscape.cms.servlet.wizard.*;
+import com.netscape.certsrv.request.*;
+import com.netscape.certsrv.dbs.certdb.*;
+
+public class AdminPanel extends WizardPanelBase {
+
+ private static final String ADMIN_UID = "admin";
+ private final static String CERT_TAG = "admin";
+
+ public AdminPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Administrator");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id) {
+ setPanelNo(panelno);
+ setName("Administrator");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.admin.email", "");
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.admin.email", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (Exception e) {}
+
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ Descriptor emailDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ null, /* no default parameter */
+ "Email address for an administrator");
+
+ set.add("admin_email", emailDesc);
+
+ Descriptor pwdDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ null, /* no default parameter */
+ "Administrator's password");
+
+ set.add("pwd", pwdDesc);
+
+ Descriptor pwdAgainDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ null, /* no default parameter */
+ "Administrator's password again");
+
+ set.add("admin_password_again", pwdAgainDesc);
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("AdminPanel: display");
+
+ IConfigStore cs = CMS.getConfigStore();
+ String session_id = request.getParameter("session_id");
+ if (session_id != null) {
+ CMS.debug("NamePanel setting session id.");
+ CMS.setConfigSDSessionId(session_id);
+ }
+
+ String type = "";
+ String info = "";
+ context.put("import", "true");
+
+ String subsystemtype = "";
+ try {
+ type = cs.getString("preop.ca.type", "");
+ subsystemtype = cs.getString("cs.type", "");
+ } catch (Exception e) {}
+
+ if (isPanelDone()) {
+ try {
+ context.put("admin_email", cs.getString("preop.admin.email"));
+ context.put("admin_name", cs.getString("preop.admin.name"));
+ context.put("admin_pwd", "");
+ context.put("admin_pwd_again", "");
+ context.put("admin_uid", cs.getString("preop.admin.uid"));
+ } catch (Exception e) {}
+ } else {
+ String def_admin_name = "";
+ try {
+ def_admin_name = cs.getString("cs.type") + " Administrator of Instance " + cs.getString("instanceId");
+ } catch (EBaseException e) {
+ }
+ context.put("admin_name", def_admin_name);
+ context.put("admin_email", "");
+ context.put("admin_pwd", "");
+ context.put("admin_pwd_again", "");
+ context.put("admin_uid", ADMIN_UID);
+ }
+ ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
+
+ if (ca == null) {
+ context.put("ca", "false");
+ } else {
+ context.put("ca", "true");
+ }
+ context.put("caType", type);
+
+ String domainname = "";
+ try {
+ domainname = cs.getString("securitydomain.name", "");
+ } catch (EBaseException e1) {}
+ context.put("securityDomain", domainname);
+ context.put("title", "Administrator");
+ context.put("panel", "admin/console/config/adminpanel.vm");
+ context.put("errorString", "");
+ context.put("info", info);
+
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException
+ {
+ String pwd = HttpInput.getPassword(request, "__pwd");
+ String pwd_again = HttpInput.getPassword(request, "__admin_password_again");
+ String email = HttpInput.getEmail(request, "email");
+ String name = HttpInput.getName(request, "name");
+ String uid = HttpInput.getUID(request, "uid");
+ context.put("admin_email", email);
+ context.put("admin_name", name);
+ context.put("admin_pwd", pwd);
+ context.put("admin_pwd_again", pwd_again);
+ context.put("import", "true");
+
+ if (name == null || name.equals("")) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Name is empty");
+ }
+
+ if (email == null || email.equals("")) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Email is empty");
+ }
+
+ if (uid == null || uid.equals("")) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Uid is empty");
+ }
+
+ if (!pwd.equals(pwd_again)) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Password and password again are not the same.");
+ }
+
+ if (email == null || email.length() == 0) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Email address is empty string.");
+ }
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ context.put("info", "");
+ context.put("import", "true");
+
+ String type = "";
+ String subsystemtype = "";
+ String security_domain_type = "";
+ String selected_hierarchy = "";
+ try {
+ type = config.getString(PRE_CA_TYPE, "");
+ subsystemtype = config.getString("cs.type", "");
+ security_domain_type = config.getString("securitydomain.select","");
+ selected_hierarchy = config.getString("preop.hierarchy.select", "");
+ } catch (Exception e) {}
+
+ ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
+
+ if (ca == null) {
+ context.put("ca", "false");
+ } else {
+ context.put("ca", "true");
+ }
+ context.put("caType", type);
+ String uid = HttpInput.getUID(request, "uid");
+ String email = HttpInput.getEmail(request, "email");
+ String name = HttpInput.getName(request, "name");
+
+ CMS.debug("AdminPanel update: email address = " + email);
+ String pwd = HttpInput.getPassword(request, "__pwd");
+
+ config.putString("preop.admin.uid", uid);
+ config.putString("preop.admin.email", email);
+ config.putString("preop.admin.name", name);
+ try {
+ createAdmin(request);
+ } catch (IOException e) {
+ context.put("errorString", "Failed to create administrator.");
+ context.put("updateStatus", "failure");
+ throw e;
+ }
+
+ // REMINDER: This panel is NOT used by "clones"
+ if( ca != null ) {
+ if( selected_hierarchy.equals( "root" ) ) {
+ CMS.debug( "AdminPanel update: "
+ + "Root CA subsystem");
+ } else {
+ CMS.debug( "AdminPanel update: "
+ + "Subordinate CA subsystem");
+ }
+
+ try {
+ createAdminCertificate(request, response, context);
+ } catch (IOException e) {
+ CMS.debug("AdminPanel update: Exception: " + e.toString());
+ context.put("errorString",
+ "Failed to create administrator certificate.");
+ context.put("updateStatus", "failure");
+ throw e;
+ }
+ } else {
+ String ca_hostname = null;
+ int ca_port = -1;
+
+ // REMINDER: This panel is NOT used by "clones"
+ CMS.debug( "AdminPanel update: "
+ + subsystemtype
+ + " subsystem" );
+
+ if (type.equals("sdca")) {
+ try {
+ ca_hostname = config.getString("preop.ca.hostname");
+ ca_port = config.getInteger("preop.ca.httpsport");
+ } catch (Exception e) {
+ }
+ } else {
+ try {
+ ca_hostname = config.getString("securitydomain.host", "");
+ ca_port = config.getInteger("securitydomain.httpseeport");
+ } catch (Exception e) {
+ }
+ }
+
+ submitRequest(ca_hostname, ca_port, request, response, context);
+ }
+
+ try {
+ CMS.reinit(IUGSubsystem.ID);
+ } catch (Exception e) {
+ CMS.debug("AdminPanel update: " + e.toString());
+ }
+
+ try {
+ config.commit(false);
+ } catch (Exception e) {}
+
+ context.put("updateStatus", "success");
+
+ }
+
+ private void createAdmin(HttpServletRequest request) throws IOException {
+ IUGSubsystem system = (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
+ IConfigStore config = CMS.getConfigStore();
+ String adminName = null;
+ String groupName = null;
+
+ try {
+ adminName = config.getString(PRE_CONF_ADMIN_NAME,
+ "Certificate System Administrator");
+ groupName = config.getString(PRE_CONF_AGENT_GROUP,
+ "Certificate Manager Agents");
+ } catch (Exception e) {
+ CMS.debug("AdminPanel createAdmin: " + e.toString());
+ }
+
+ IUser user = null;
+ String uid = HttpInput.getUID(request, "uid");
+
+ try {
+ user = system.createUser(uid);
+ String email = HttpInput.getEmail(request, "email");
+ String name = HttpInput.getName(request, "name");
+ String pwd = HttpInput.getPassword(request, "__pwd");
+
+ user.setEmail(email);
+ user.setPassword(pwd);
+ user.setFullName(name);
+ user.setUserType("adminType");
+ user.setState("1");
+ user.setPhone("");
+ system.addUser(user);
+ } catch (LDAPException e) {
+ CMS.debug("AdminPanel createAdmin: addUser " + e.toString());
+ if (e.getLDAPResultCode() != LDAPException.ENTRY_ALREADY_EXISTS) {
+ throw new IOException(e.toString());
+ }
+ } catch (Exception e) {
+ CMS.debug("AdminPanel createAdmin: addUser " + e.toString());
+ throw new IOException(e.toString());
+ }
+
+ IGroup group = null;
+
+ try {
+ group = system.getGroupFromName(groupName);
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+ group = system.getGroupFromName("Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ String select = config.getString("securitydomain.select", "");
+ if (select.equals("new")) {
+ group = system.getGroupFromName("Security Domain Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ group = system.getGroupFromName("Enterprise CA Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ group = system.getGroupFromName("Enterprise KRA Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ group = system.getGroupFromName("Enterprise RA Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ group = system.getGroupFromName("Enterprise TKS Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ group = system.getGroupFromName("Enterprise OCSP Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+
+ group = system.getGroupFromName("Enterprise TPS Administrators");
+ if (!group.isMember(uid)) {
+ group.addMemberName(uid);
+ system.modifyGroup(group);
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug("AdminPanel createAdmin: modifyGroup " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ private void submitRequest(String ca_hostname, int ca_port, HttpServletRequest request,
+ HttpServletResponse response, Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ String sd_hostname = null;
+ int sd_port = -1;
+
+ try {
+ sd_hostname = config.getString("securitydomain.host", "");
+ sd_port = config.getInteger("securitydomain.httpseeport");
+ } catch (Exception e) {}
+
+ String profileId = HttpInput.getID(request, "profileId");
+ if (profileId == null) {
+ try {
+ profileId = config.getString("preop.admincert.profile", "caAdminCert");
+ } catch (Exception e) {}
+ }
+
+ String cert_request_type = HttpInput.getID(request, "cert_request_type");
+ String cert_request = HttpInput.getCertRequest(request, "cert_request");
+ cert_request = URLEncoder.encode(cert_request, "UTF-8");
+ String session_id = CMS.getConfigSDSessionId();
+ String subjectDN = HttpInput.getString(request, "subject");
+
+ String content = "profileId="+profileId+"&cert_request_type="+cert_request_type+"&cert_request="+cert_request+"&xmlOutput=true&sessionID="+session_id+"&subject="+subjectDN;
+
+ HttpClient httpclient = new HttpClient();
+ String c = null;
+
+ try {
+ JssSSLSocketFactory factory = new JssSSLSocketFactory();
+
+ httpclient = new HttpClient(factory);
+ httpclient.connect(ca_hostname, ca_port);
+ HttpRequest httprequest = new HttpRequest();
+ httprequest.setMethod(HttpRequest.POST);
+ httprequest.setURI("/ca/ee/ca/profileSubmit");
+ httprequest.setHeader("user-agent", "HTTPTool/1.0");
+
+ httprequest.setHeader("content-length", "" + content.length());
+ httprequest.setHeader("content-type",
+ "application/x-www-form-urlencoded");
+ httprequest.setContent(content);
+ HttpResponse httpresponse = httpclient.send(httprequest);
+
+ c = httpresponse.getContent();
+ CMS.debug("AdminPanel submitRequest: content=" + c);
+
+ // retrieve the request Id ad admin certificate
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(
+ c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "AdminPanel::submitRequest() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+ String status = parser.getValue("Status");
+
+ CMS.debug("AdminPanel update: status=" + status);
+ if (status.equals("2")) {
+ //relogin to the security domain
+ reloginSecurityDomain(response);
+ return;
+ } else if (!status.equals("0")) {
+ String error = parser.getValue("Error");
+
+ context.put("errorString", error);
+ throw new IOException(error);
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+ String id = parser.getValue("Id");
+
+ cs.putString("preop.admincert.requestId.0", id);
+ String serial = parser.getValue("serialno");
+
+ cs.putString("preop.admincert.serialno.0", serial);
+ String b64 = parser.getValue("b64");
+ String instanceRoot = cs.getString("instanceRoot", "");
+ String dir = instanceRoot + File.separator + "conf"
+ + File.separator + "admin.b64";
+
+ cs.putString("preop.admincert.b64", dir);
+ PrintStream ps = new PrintStream(new FileOutputStream(dir));
+
+ ps.println(b64);
+ ps.flush();
+ ps.close();
+ } catch (IOException ee) {
+ context.put("errorString", ee.toString());
+ throw ee;
+ } catch (Exception ee) {
+ context.put("errorString", ee.toString());
+ throw new IOException(ee.toString());
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug("AdminPanel submitRequest: " + e.toString());
+ }
+ }
+
+ private void createAdminCertificate(HttpServletRequest request,
+ HttpServletResponse response, Context context) throws IOException {
+ String cert_request = HttpInput.getCertRequest(request, "cert_request");
+
+ String cert_request_type = HttpInput.getID(request, "cert_request_type");
+ IConfigStore cs = CMS.getConfigStore();
+
+ if( cs == null ) {
+ CMS.debug( "AdminPanel::createAdminCertificate() - cs is null!" );
+ throw new IOException( "cs is null" );
+ }
+
+ String subject = "";
+ X509Key x509key = null;
+ if (cert_request_type.equals("crmf")) {
+ try {
+ byte[] b = CMS.AtoB(cert_request);
+ SEQUENCE crmfMsgs = CryptoUtil.parseCRMFMsgs(b);
+ subject = CryptoUtil.getSubjectName(crmfMsgs);
+ x509key = CryptoUtil.getX509KeyFromCRMFMsgs(crmfMsgs);
+ } catch (Exception e) {
+ CMS.debug(
+ "AdminPanel createAdminCertificate: Exception="
+ + e.toString());
+ }
+ // this request is from IE. The VBScript has problem of generating
+ // certificate request if the subject name has E and UID components.
+ // For now, we always hardcoded the subject DN to be cn=NAME in
+ // the IE browser.
+ } else if (cert_request_type.equals("pkcs10")) {
+ try {
+ byte[] b = CMS.AtoB(cert_request);
+ PKCS10 pkcs10 = new PKCS10(b);
+ subject = request.getParameter("subject");
+ x509key = pkcs10.getSubjectPublicKeyInfo();
+ } catch (Exception e) {
+ CMS.debug("AdminPanel createAdminCertificate: Exception="
+ + e.toString());
+ }
+ }
+
+ if( x509key == null ) {
+ CMS.debug( "AdminPanel::createAdminCertificate() - x509key is null!" );
+ throw new IOException( "x509key is null" );
+ }
+
+ try {
+ cs.putString(PCERT_PREFIX + CERT_TAG + ".dn", subject);
+ String caType = cs.getString(PCERT_PREFIX + CERT_TAG + ".type", "local");
+ X509CertImpl impl = CertUtil.createLocalCert(cs, x509key,
+ PCERT_PREFIX, CERT_TAG, caType, context);
+
+ // update the locally created request for renewal
+ CertUtil.updateLocalRequest(cs, CERT_TAG, cert_request,cert_request_type, subject);
+
+ ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
+ if (ca != null) {
+ createPKCS7(impl);
+ }
+ cs.putString("preop.admincert.serialno.0",
+ impl.getSerialNumber().toString(16));
+ } catch (Exception e) {
+ CMS.debug("AdminPanel createAdminCertificate: Exception="
+ + e.toString());
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ context.put("title", "Administrator");
+ context.put("panel", "admin/console/config/adminpanel.vm");
+ ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
+ IConfigStore cs = CMS.getConfigStore();
+ String type = "";
+ String info = "";
+
+ try {
+ type = cs.getString("preop.ca.type", "");
+ } catch (Exception e) {}
+ if (ca == null && type.equals("otherca")) {
+ info = "Since you do not join the Redhat CA network, the administrator's certificate will not be generated automatically.";
+ }
+ context.put("info", info);
+ context.put("admin_email", request.getParameter("email"));
+ context.put("admin_name", request.getParameter("name"));
+ context.put("admin_pwd", "");
+ context.put("admin_pwd_again", "");
+ context.put("admin_uid", request.getParameter("uid"));
+ }
+
+ public boolean shouldSkip() {
+ try {
+ IConfigStore c = CMS.getConfigStore();
+ String s = c.getString("preop.subsystem.select",null);
+ if (s != null && s.equals("clone")) {
+ return true;
+ }
+ } catch (EBaseException e) {
+ }
+
+ return false;
+ }
+
+
+ private void createPKCS7(X509CertImpl cert) {
+ try {
+ IConfigStore cs = CMS.getConfigStore();
+ ICertificateAuthority ca = (ICertificateAuthority)CMS.getSubsystem("ca");
+ CertificateChain cachain = ca.getCACertChain();
+ X509Certificate[] cacerts = cachain.getChain();
+ X509CertImpl[] userChain = new X509CertImpl[cacerts.length + 1];
+ int m = 1, n = 0;
+
+ for (; n < cacerts.length; m++, n++) {
+ userChain[m] = (X509CertImpl) cacerts[n];
+ }
+
+ userChain[0] = cert;
+ PKCS7 p7 = new PKCS7(new AlgorithmId[0],
+ new ContentInfo(new byte[0]), userChain, new SignerInfo[0]);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ p7.encodeSignedData(bos);
+ byte[] p7Bytes = bos.toByteArray();
+ String p7Str = CMS.BtoA(p7Bytes);
+ cs.putString("preop.admincert.pkcs7", CryptoUtil.normalizeCertStr(p7Str));
+ } catch (Exception e) {
+ CMS.debug("AdminPanel createPKCS7: Failed to create pkcs7 file. Exception: "+e.toString());
+ }
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java
new file mode 100644
index 000000000..18741bfb0
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AgentAuthenticatePanel.java
@@ -0,0 +1,229 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.certsrv.base.*;
+import java.util.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class AgentAuthenticatePanel extends WizardPanelBase {
+
+ public AgentAuthenticatePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Agent Authentication");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Agent Authentication");
+ setId(id);
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ /**
+ * Should we skip this panel for the configuration.
+ */
+ public boolean shouldSkip() {
+ CMS.debug("DisplayCertChainPanel: should skip");
+
+ IConfigStore cs = CMS.getConfigStore();
+ // if we are root, no need to get the certificate chain.
+
+ try {
+ String select = cs.getString("securitydomain.select","");
+ if (select.equals("new")) {
+ return true;
+ }
+
+ String catype = cs.getString("preop.ca.type", "");
+ if (catype.equals("otherca"))
+ return true;
+ } catch (EBaseException e) {
+ }
+
+ return false;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.ca.agent.uid", "");
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.ca.agent.uid", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Agent Authentication");
+ IConfigStore config = CMS.getConfigStore();
+
+ if (isPanelDone()) {
+
+ try {
+ String s = config.getString("preop.ca.agent.uid", "");
+ String type = config.getString("preop.hierarchy.select", "");
+ if (type.equals("root"))
+ context.put("uid", "");
+ else
+ context.put("uid", s);
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("uid", "");
+ }
+
+ context.put("password", "");
+ context.put("panel", "admin/console/config/agentauthenticatepanel.vm");
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException
+ {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ context.put("panel", "admin/console/config/agentauthenticatepanel.vm");
+ context.put("title", "Agent Authentication");
+ String type = "";
+ String catype = "";
+ try {
+ type = config.getString("preop.hierarchy.select", "");
+ catype = config.getString("preop.ca.type", "");
+ } catch (Exception e) {
+ }
+
+ if (type.equals("root")) {
+ CMS.debug("AgentAuthenticatePanel: This is root, no need for authentication");
+ } else if (catype.equals("sdca")) {
+ CMS.debug("AgentAuthenticatePanel: This is not external CA");
+ String uid = HttpInput.getUID(request, "uid");
+ if (uid == null) {
+ context.put("errorString", "Uid is empty");
+ throw new IOException("Uid is empty");
+ }
+ context.put("uid", uid);
+ String pwd = HttpInput.getPassword(request, "__password");
+ config.putString("preop.ca.agent.uid", uid);
+ config.putString("preop.ca.agent.pwd", pwd);
+ String host = "";
+ int httpsport = -1;
+ try {
+ host = config.getString("preop.ca.hostname");
+ } catch (Exception e) {
+ CMS.debug("AgentAuthenticatePanel update: "+e.toString());
+ context.put("errorString", "Missing hostname");
+ throw new IOException("Missing hostname");
+ }
+
+ try {
+ httpsport = config.getInteger("preop.ca.httpsport");
+ } catch (Exception e) {
+ CMS.debug("AgentAuthenticatePanel update: "+e.toString());
+ context.put("errorString", "Missing port");
+ throw new IOException("Missing port");
+ }
+
+/*
+ // Bugzilla Bug #583825 - CC: Obsolete servlets to be removed from
+ // web.xml as part of CC interface review
+ boolean authenticated = authenticate(host, httpsport, true,
+ "/ca/ee/ca/checkIdentity", "uid="+uid+"&pwd="+pwd);
+
+ if (!authenticated) {
+ context.put("errorString", "Wrong user id or password");
+ throw new IOException("Wrong user id or password");
+ }
+*/
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {}
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context)
+ {
+ context.put("password", "");
+ context.put("title", "Agent Authentication");
+ context.put("panel", "admin/console/config/agentauthenticatepanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java
new file mode 100644
index 000000000..77aa5bda3
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/AuthenticatePanel.java
@@ -0,0 +1,193 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.certsrv.base.*;
+import java.util.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class AuthenticatePanel extends WizardPanelBase {
+
+ public AuthenticatePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Authentication");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Authentication");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.ca.agent.uid", "");
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.ca.agent.uid","");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Authentication");
+ IConfigStore config = CMS.getConfigStore();
+
+ if (isPanelDone()) {
+
+ try {
+ String s = config.getString("preop.ca.agent.uid", "");
+ String type = config.getString("preop.hierarchy.select", "");
+ if (type.equals("root"))
+ context.put("uid", "");
+ else
+ context.put("uid", s);
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("uid", "");
+ }
+
+ context.put("password", "");
+ context.put("panel", "admin/console/config/authenticatepanel.vm");
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ String type = "";
+ String catype = "";
+ try {
+ type = config.getString("preop.hierarchy.select", "");
+ catype = config.getString("preop.ca.type", "");
+ } catch (Exception e) {
+ }
+
+ if (type.equals("root")) {
+ CMS.debug("AuthenticatePanel: This is root, no need for authentication");
+ } else if (catype.equals("sdca")) {
+ CMS.debug("AuthenticatePanel: This is not external CA");
+ String uid = HttpInput.getUID(request, "uid");
+ if (uid == null) {
+ context.put("errorString", "Uid is empty");
+ throw new IOException("Uid is empty");
+ }
+ context.put("uid", uid);
+ String pwd = HttpInput.getPassword(request, "__password");
+ config.putString("preop.ca.agent.uid", uid);
+ config.putString("preop.ca.agent.pwd", pwd);
+ String host = "";
+ int httpsport = -1;
+ try {
+ host = config.getString("preop.ca.hostname");
+ } catch (Exception e) {
+ CMS.debug("AuthenticatePanel update: "+e.toString());
+ context.put("errorString", "Missing hostname");
+ throw new IOException("Missing hostname");
+ }
+
+ try {
+ httpsport = config.getInteger("preop.ca.httpsport");
+ } catch (Exception e) {
+ CMS.debug("AuthenticatePanel update: "+e.toString());
+ context.put("errorString", "Missing port");
+ throw new IOException("Missing port");
+ }
+
+ boolean authenticated = authenticate(host, httpsport, true,
+ "/ca/ee/ca/configSubsystem", "uid="+uid+"&pwd="+pwd);
+
+ if (!authenticated) {
+ context.put("errorString", "Wrong user id or password");
+ throw new IOException("Wrong user id or password");
+ }
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {}
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context)
+ {
+ context.put("password", "");
+ context.put("panel", "admin/console/config/authenticatepanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java
new file mode 100644
index 000000000..7e2aedad2
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BackupKeyCertPanel.java
@@ -0,0 +1,430 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import org.mozilla.jss.util.Password;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.certsrv.base.*;
+import java.util.*;
+import java.security.*;
+import java.security.cert.*;
+import java.security.KeyPair;
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.asn1.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.pkcs12.*;
+import org.mozilla.jss.pkix.primitive.*;
+import org.mozilla.jss.crypto.X509Certificate;
+import org.mozilla.jss.crypto.PrivateKey;
+import com.netscape.cmsutil.crypto.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class BackupKeyCertPanel extends WizardPanelBase {
+
+ public BackupKeyCertPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Export Keys and Certificates");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Export Keys and Certificates");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ /* clean up if necessary */
+ try {
+ boolean done = cs.getBoolean("preop.backupkeycert.done");
+ cs.putBoolean("preop.backupkeycert.done", false);
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+ }
+
+ public boolean shouldSkip() {
+ IConfigStore cs = CMS.getConfigStore();
+
+ try {
+ String s = cs.getString("preop.module.token", "");
+ if (s.equals("Internal Key Storage Token"))
+ return false;
+ } catch (Exception e) {
+ }
+
+ return true;
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.backupkeycert.done", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Export Keys and Certificates");
+ IConfigStore config = CMS.getConfigStore();
+
+ if (isPanelDone()) {
+ try {
+ boolean enable = config.getBoolean("preop.backupkeys.enable");
+ if (enable) {
+ context.put("dobackup", "checked");
+ context.put("nobackup", "");
+ } else {
+ context.put("dobackup", "");
+ context.put("nobackup", "checked");
+ }
+ } catch (Exception e) {
+ }
+ } else {
+ context.put("dobackup", "");
+ context.put("nobackup", "checked");
+ }
+
+ context.put("panel", "admin/console/config/backupkeycertpanel.vm");
+ context.put("pwd", "");
+ context.put("pwdagain", "");
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response, Context context) throws IOException {
+ String select = HttpInput.getID(request, "choice");
+ if (select.equals("backupkey")) {
+ String pwd = request.getParameter("__pwd");
+ String pwdAgain = request.getParameter("__pwdagain");
+ if (pwd == null || pwdAgain == null || pwd.equals("") || pwdAgain.equals("")) {
+ CMS.debug("BackupKeyCertPanel validate: Password is null");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("PK12 password is empty.");
+ }
+
+ if (!pwd.equals(pwdAgain)) {
+ CMS.debug("BackupKeyCertPanel validate: Password and password again are not the same.");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("PK12 password is different from the PK12 password again.");
+ }
+ }
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+
+ String select = HttpInput.getID(request, "choice");
+ if (select.equals("backupkey")) {
+ CMS.debug("BackupKeyCertPanel update: backup");
+ config.putBoolean("preop.backupkeys.enable", true);
+ backupKeysCerts(request);
+ } else {
+ CMS.debug("BackupKeyCertPanel update: no backup");
+ config.putBoolean("preop.backupkeys.enable", false);
+ }
+
+ config.putBoolean("preop.backupkeycert.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context)
+ {
+ String select = "";
+ try {
+ select = HttpInput.getID(request, "choice");
+ } catch (Exception e) {
+ }
+
+ if (select.equals("backupkey")) {
+ context.put("dobackup", "checked");
+ context.put("nobackup", "");
+ } else {
+ context.put("dobackup", "");
+ context.put("nobackup", "checked");
+ }
+
+ context.put("pwd", "");
+ context.put("pwdagain", "");
+ context.put("title", "Export Keys and Certificates");
+ context.put("panel", "admin/console/config/backupkeycertpanel.vm");
+ }
+
+ public void backupKeysCerts(HttpServletRequest request)
+ throws IOException {
+ CMS.debug("BackupKeyCertPanel backupKeysCerts: start");
+ IConfigStore cs = CMS.getConfigStore();
+ String certlist = "";
+ try {
+ certlist = cs.getString("preop.cert.list");
+ } catch (Exception e) {
+ }
+
+ StringTokenizer st = new StringTokenizer(certlist, ",");
+ CryptoManager cm = null;
+ try {
+ cm = CryptoManager.getInstance();
+ } catch (Exception e) {
+ CMS.debug( "BackupKeyCertPanel::backupKeysCerts() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String pwd = request.getParameter("__pwd");
+ Password pass = new org.mozilla.jss.util.Password(pwd.toCharArray());
+ SEQUENCE encSafeContents = new SEQUENCE();
+ SEQUENCE safeContents = new SEQUENCE();
+ while (st.hasMoreTokens()) {
+ String t = st.nextToken();
+ if (t.equals("sslserver"))
+ continue;
+ String nickname = "";
+ String modname = "";
+ try {
+ nickname = cs.getString("preop.cert."+t+".nickname");
+ modname = cs.getString("preop.module.token");
+ } catch (Exception e) {
+ }
+ if (!modname.equals("Internal Key Storage Token"))
+ nickname = modname+":"+nickname;
+
+ X509Certificate x509cert = null;
+ byte localKeyId[] = null;
+ try {
+ x509cert = cm.findCertByNickname(nickname);
+ localKeyId = addCertBag(x509cert, nickname, safeContents);
+ } catch (IOException e) {
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel: Exception="+e.toString());
+ throw new IOException("Failed to create pkcs12 file.");
+ }
+
+ try {
+ PrivateKey pkey = cm.findPrivKeyByCert(x509cert);
+ addKeyBag(pkey, x509cert, pass, localKeyId, encSafeContents);
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel: Exception="+e.toString());
+ throw new IOException("Failed to create pkcs12 file.");
+ }
+ } //while loop
+
+ X509Certificate[] cacerts = cm.getCACerts();
+
+ for (int i=0; i<cacerts.length; i++) {
+ //String nickname = cacerts[i].getSubjectDN().toString();
+ String nickname = null;
+ try {
+ byte[] localKeyId = addCertBag(cacerts[i], nickname, safeContents);
+ } catch (IOException e) {
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel backKeysCerts: Exception="+e.toString());
+ throw new IOException("Failed to create pkcs12 file.");
+ }
+ }
+
+ try {
+ AuthenticatedSafes authSafes = new AuthenticatedSafes();
+ authSafes.addSafeContents(safeContents);
+ authSafes.addSafeContents(encSafeContents);
+ PFX pfx = new PFX(authSafes);
+ pfx.computeMacData(pass, null, 5);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ pfx.encode(bos);
+ byte[] output = bos.toByteArray();
+ cs.putString("preop.pkcs12", CryptoUtil.byte2string(output));
+ pass.clear();
+ cs.commit(false);
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel backupKeysCerts: Exception="+e.toString());
+ }
+ }
+
+ private void addKeyBag(PrivateKey pkey, X509Certificate x509cert,
+ Password pass, byte[] localKeyId, SEQUENCE safeContents)
+ throws IOException {
+ try {
+ PasswordConverter passConverter = new PasswordConverter();
+
+ SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
+ byte salt[] = random.generateSeed(4); // 4 bytes salt
+ byte[] priData = getEncodedKey(pkey);
+
+ PrivateKeyInfo pki = (PrivateKeyInfo)
+ ASN1Util.decode(PrivateKeyInfo.getTemplate(), priData);
+ ASN1Value key = EncryptedPrivateKeyInfo.createPBE(
+ PBEAlgorithm.PBE_SHA1_DES3_CBC,
+ pass, salt, 1, passConverter, pki);
+ SET keyAttrs = createBagAttrs(
+ x509cert.getSubjectDN().toString(), localKeyId);
+ SafeBag keyBag = new SafeBag(SafeBag.PKCS8_SHROUDED_KEY_BAG,
+ key, keyAttrs);
+ safeContents.addElement(keyBag);
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel getKeyBag: Exception="+e.toString());
+ throw new IOException("Failed to create pk12 file.");
+ }
+ }
+
+ private byte[] addCertBag(X509Certificate x509cert, String nickname,
+ SEQUENCE safeContents) throws IOException {
+ byte[] localKeyId = null;
+ try {
+ ASN1Value cert = new OCTET_STRING(x509cert.getEncoded());
+ localKeyId = createLocalKeyId(x509cert);
+ SET certAttrs = null;
+ if (nickname != null)
+ certAttrs = createBagAttrs(nickname, localKeyId);
+ SafeBag certBag = new SafeBag(SafeBag.CERT_BAG,
+ new CertBag(CertBag.X509_CERT_TYPE, cert), certAttrs);
+ safeContents.addElement(certBag);
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel addCertBag: "+e.toString());
+ throw new IOException("Failed to create pk12 file.");
+ }
+
+ return localKeyId;
+ }
+
+ private byte[] getEncodedKey(PrivateKey pkey) {
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ CryptoToken token = cm.getInternalKeyStorageToken();
+ KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3);
+ SymmetricKey sk = kg.generate();
+ KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
+ byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ IVParameterSpec param = new IVParameterSpec(iv);
+ wrapper.initWrap(sk, param);
+ byte[] enckey = wrapper.wrap(pkey);
+ Cipher c = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
+ c.initDecrypt(sk, param);
+ byte[] recovered = c.doFinal(enckey);
+ return recovered;
+ } catch (Exception e) {
+ CMS.debug("BackupKeyCertPanel getEncodedKey: Exception="+e.toString());
+ }
+
+ return null;
+ }
+
+ private byte[] createLocalKeyId(X509Certificate cert)
+ throws IOException {
+ try {
+ // SHA1 hash of the X509Cert der encoding
+ byte certDer[] = cert.getEncoded();
+
+ MessageDigest md = MessageDigest.getInstance("SHA");
+
+ md.update(certDer);
+ return md.digest();
+ } catch (CertificateEncodingException e) {
+ CMS.debug("BackupKeyCertPanel createLocalKeyId: Exception: "+e.toString());
+ throw new IOException("Failed to encode certificate.");
+ } catch (NoSuchAlgorithmException e) {
+ CMS.debug("BackupKeyCertPanel createLocalKeyId: Exception: "+e.toString());
+ throw new IOException("No such algorithm supported.");
+ }
+ }
+
+ private SET createBagAttrs(String nickName, byte localKeyId[])
+ throws IOException {
+ try {
+ SET attrs = new SET();
+ SEQUENCE nickNameAttr = new SEQUENCE();
+
+ nickNameAttr.addElement(SafeBag.FRIENDLY_NAME);
+ SET nickNameSet = new SET();
+
+ nickNameSet.addElement(new BMPString(nickName));
+ nickNameAttr.addElement(nickNameSet);
+ attrs.addElement(nickNameAttr);
+ SEQUENCE localKeyAttr = new SEQUENCE();
+
+ localKeyAttr.addElement(SafeBag.LOCAL_KEY_ID);
+ SET localKeySet = new SET();
+
+ localKeySet.addElement(new OCTET_STRING(localKeyId));
+ localKeyAttr.addElement(localKeySet);
+ attrs.addElement(localKeyAttr);
+ return attrs;
+ } catch (CharConversionException e) {
+ CMS.debug("BackupKeyCertPanel createBagAttrs: Exception="+e.toString());
+ throw new IOException("Failed to create PKCS12 file.");
+ }
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java
new file mode 100644
index 000000000..9bbb09005
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/BaseServlet.java
@@ -0,0 +1,114 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import java.io.*;
+import java.util.*;
+import com.netscape.certsrv.apps.*;
+
+
+public class BaseServlet extends VelocityServlet {
+
+ /**
+ * Returns usage of this servlet.
+ */
+ public String getUsage() {
+ return null;
+ }
+
+ public boolean authenticate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String pin = (String) request.getSession().getAttribute("pin");
+
+ if (pin == null) {
+ try {
+ response.sendRedirect("login");
+ } catch (IOException e) {}
+ return false;
+ }
+ return true;
+ }
+
+ public void outputHttpParameters(HttpServletRequest httpReq) {
+ CMS.debug("BaseServlet:service() uri = " + httpReq.getRequestURI());
+ Enumeration paramNames = httpReq.getParameterNames();
+
+ while (paramNames.hasMoreElements()) {
+ String pn = (String) paramNames.nextElement();
+ // added this facility so that password can be hidden,
+ // all sensitive parameters should be prefixed with
+ // __ (double underscores); however, in the event that
+ // a security parameter slips through, we perform multiple
+ // additional checks to insure that it is NOT displayed
+ if( pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.equalsIgnoreCase("uPasswd") ) {
+ CMS.debug("BaseServlet::service() param name='" + pn +
+ "' value='(sensitive)'" );
+ } else {
+ CMS.debug("BaseServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'" );
+ }
+ }
+ }
+
+ /**
+ * Processes request.
+ */
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ return null;
+ }
+
+ public Template handleRequest(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ if (CMS.debugOn()) {
+ outputHttpParameters(request);
+ }
+
+ /* XXX - authentication */
+ if (!authenticate(request, response, context)) {
+ return null;
+ }
+
+ /* XXX - authorization */
+
+ return process(request, response, context);
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java
new file mode 100644
index 000000000..316c5706d
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CAInfoPanel.java
@@ -0,0 +1,328 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import org.xml.sax.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.template.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.cmsutil.crypto.*;
+import java.io.*;
+import java.util.*;
+import java.net.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import com.netscape.cmsutil.http.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.asn1.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class CAInfoPanel extends WizardPanelBase {
+
+ public CAInfoPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("CA Information");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("CA Information");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.ca.type", "");
+ }
+
+ public boolean shouldSkip() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.subsystem.select", "");
+ if (s.equals("clone"))
+ return true;
+ } catch (Exception e) {
+ }
+ return false;
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.ca.type", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (Exception e) {}
+
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("CAInfoPanel: display");
+
+ IConfigStore cs = CMS.getConfigStore();
+ String hostname = "";
+ String httpport = "";
+ String httpsport = "";
+
+ if (isPanelDone()) {
+ String type = "sdca";
+
+ try {
+ type = cs.getString("preop.ca.type");
+ } catch (Exception e) {
+ CMS.debug("CAInfoPanel exception: " + e.toString());
+ return;
+ }
+
+ try {
+ hostname = cs.getString("preop.ca.hostname");
+ } catch (Exception e) {}
+
+ try {
+ httpport = cs.getString("preop.ca.httpport");
+ } catch (Exception e) {}
+
+ try {
+ httpsport = cs.getString("preop.ca.httpsport");
+ } catch (Exception e) {}
+
+ if (type.equals("sdca")) {
+ context.put("check_sdca", "checked");
+ context.put("check_otherca", "");
+ } else if (type.equals("otherca")) {
+ context.put("check_sdca", "");
+ context.put("check_otherca", "checked");
+ }
+ } else {
+ context.put("check_sdca", "checked");
+ context.put("check_otherca", "");
+ }
+
+ String cstype = "CA";
+ String portType = "SecurePort";
+
+/*
+ try {
+ cstype = cs.getString("cs.type", "");
+ } catch (EBaseException e) {}
+*/
+
+ CMS.debug("CAInfoPanel: Ready to get url");
+ Vector v = getUrlListFromSecurityDomain(cs, cstype, portType);
+ 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 {
+ cs.putString("preop.ca.list", list.toString());
+ cs.commit(false);
+ } catch (Exception e) {}
+
+ context.put("urls", v);
+
+ context.put("sdcaHostname", hostname);
+ context.put("sdcaHttpPort", httpport);
+ context.put("sdcaHttpsPort", httpsport);
+ context.put("title", "CA Information");
+ context.put("panel", "admin/console/config/cainfopanel.vm");
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+
+ /*
+ String select = request.getParameter("choice");
+ if (select == null) {
+ CMS.debug("CAInfoPanel: choice not found");
+ throw new IOException("choice not found");
+ }
+ */
+ IConfigStore config = CMS.getConfigStore();
+
+ try {
+ String subsystemselect = config.getString("preop.subsystem.select", "");
+ if (subsystemselect.equals("clone"))
+ return;
+ } catch (Exception e) {
+ }
+
+ String select = null;
+ String index = request.getParameter("urls");
+ 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) {}
+ }
+
+ URL urlx = null;
+
+ if (url.equals("External CA")) {
+ select = "otherca";
+ config.putString("preop.ca.pkcs7", "");
+ config.putInteger("preop.ca.certchain.size", 0);
+ } else {
+ select = "sdca";
+
+ // parse URL (CA1 - https://...)
+ url = url.substring(url.indexOf("https"));
+ urlx = new URL(url);
+ }
+
+ ISubsystem subsystem = CMS.getSubsystem(ICertificateAuthority.ID);
+
+ if (select.equals("sdca")) {
+ config.putString("preop.ca.type", "sdca");
+ CMS.debug("CAInfoPanel update: this is the 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");
+ }
+ } else if (select.equals("otherca")) {
+ config.putString("preop.ca.type", "otherca");
+ context.put("check_otherca", "checked");
+ if (subsystem != null) {
+ config.putString(PCERT_PREFIX + "signing.type", "remote");
+ }
+ CMS.debug("CAInfoPanel update: this is the other CA.");
+ }
+
+ try {
+ config.commit(false);
+ } catch (Exception e) {}
+ }
+
+ private void sdca(HttpServletRequest request, Context context, String hostname, String httpsPortStr) throws IOException {
+ CMS.debug("CAInfoPanel update: this is the CA in the security domain.");
+ IConfigStore config = CMS.getConfigStore();
+
+ context.put("sdcaHostname", hostname);
+ context.put("sdcaHttpsPort", httpsPortStr);
+
+ if (hostname == null || hostname.length() == 0) {
+ context.put("errorString", "Hostname is null");
+ throw new IOException("Hostname is null");
+ }
+
+ int httpsport = -1;
+
+ try {
+ httpsport = Integer.parseInt(httpsPortStr);
+ } catch (Exception e) {
+ CMS.debug(
+ "CAInfoPanel update: Https port is not valid. Exception: "
+ + e.toString());
+ throw new IOException("Http Port is not valid.");
+ }
+
+ config.putString("preop.ca.hostname", hostname);
+ config.putString("preop.ca.httpsport", httpsPortStr);
+ ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
+ updateCertChainUsingSecureEEPort( config, "ca", hostname,
+ httpsport, true, context,
+ certApprovalCallback );
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ /* This should never be called */
+ context.put("title", "CA Information");
+ context.put("panel", "admin/console/config/cainfopanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java
new file mode 100644
index 000000000..4aca6cec7
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/Cert.java
@@ -0,0 +1,184 @@
+// --- 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.util.StringTokenizer;
+import java.util.Vector;
+
+
+public class Cert {
+ private String mNickname = "";
+ private String mTokenname = "";
+ private String mRequest = "";
+ private String mCert = "";
+ private String mType = ""; // "selfsign," "local," or "remote"
+ private String mDN = "";
+ private String mCertTag = "";
+ private String mCertpp = "";
+ private String mUserFriendlyName = "";
+ private String mKeyOption = "";
+ private String mCustomKeysize = "";
+ private String mCustomCurvename = "";
+ private boolean mEnable = true;
+ private boolean mSigningRequired = false;
+ private String mSubsystem = "";
+
+ public Cert(String tokenName, String nickName, String certTag) {
+ mTokenname = tokenName;
+ mNickname = nickName;
+ mCertTag = certTag;
+ }
+
+ public void setEnable(boolean enable) {
+ mEnable = enable;
+ }
+
+ public boolean isEnable() {
+ return mEnable;
+ }
+
+ public void setSigningRequired(boolean required) {
+ mSigningRequired = required;
+ }
+
+ public boolean isSigningRequired() {
+ return mSigningRequired;
+ }
+
+ public void setNickname(String s) {
+ mNickname = s;
+ }
+
+ public String getNickname() {
+ return mNickname;
+ }
+
+ public void setSubsystem(String s) {
+ mSubsystem = s;
+ }
+
+ public String getSubsystem() {
+ return mSubsystem;
+ }
+
+ public String getUserFriendlyName() {
+ return mUserFriendlyName;
+ }
+
+ public void setUserFriendlyName(String name) {
+ mUserFriendlyName = name;
+ }
+
+ public String getTokenname() {
+ return mTokenname;
+ }
+
+ public String getRequest() {
+ return mRequest;
+ }
+
+ public void setRequest(String req) {
+ mRequest = req;
+ }
+
+ public String getEscapedCert() {
+ return escapeForHTML(mCert);
+ }
+
+ public String getCert() {
+ return mCert;
+ }
+
+ public void setCert(String cert) {
+ mCert = cert;
+ }
+
+ public String getType() {
+ return mType;
+ }
+
+ public void setType(String type) {
+ mType = type;
+ }
+
+ public String escapeForHTML(String s) {
+ s = s.replaceAll("\"", "&quot;");
+ return s;
+ }
+
+ public String getEscapedDN() {
+ // Need to escape "
+ return escapeForHTML(mDN);
+ }
+
+ public String getDN() {
+ return mDN;
+ }
+
+ public void setDN(String dn) {
+ mDN = dn;
+ }
+
+ public String getCertTag() {
+ return mCertTag;
+ }
+
+ public String getEscapedCertpp() {
+ return escapeForHTML(mCertpp);
+ }
+
+ public String getCertpp() {
+ return mCertpp;
+ }
+
+ public void setCertpp(String pp) {
+ mCertpp = pp;
+ }
+
+ public String getKeyOption() {
+ return mKeyOption;
+ }
+
+ /*
+ * "default" or "custom"
+ */
+ public void setKeyOption(String option) {
+ mKeyOption = option;
+ }
+
+ public boolean useDefaultKey() {
+ return (mKeyOption.equals("default"));
+ }
+
+ public String getCustomKeysize() {
+ return mCustomKeysize;
+ }
+
+ public void setCustomKeysize(String size) {
+ mCustomKeysize = size;
+ }
+
+ public String getCustomCurvename() {
+ return mCustomCurvename;
+ }
+
+ public void setCustomCurvename(String curve) {
+ mCustomCurvename = curve;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java
new file mode 100644
index 000000000..bd4893915
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertPrettyPrintPanel.java
@@ -0,0 +1,216 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.util.*;
+import java.io.*;
+import java.security.*;
+
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.security.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.cmsutil.crypto.*;
+
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.PrivateKey;
+import org.mozilla.jss.pkcs11.*;
+
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class CertPrettyPrintPanel extends WizardPanelBase {
+ private Vector mCerts = null;
+
+ public CertPrettyPrintPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Certificates");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Certificates");
+ setId(id);
+ }
+
+ public PropertySet getUsage() {
+ // expects no input from client
+ PropertySet set = new PropertySet();
+
+ return set;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putBoolean("preop.CertPrettyPrintPanel.done", false);
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ boolean s = cs.getBoolean("preop.CertPrettyPrintPanel.done",
+ false);
+
+ if (s != true) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+
+ return false;
+ }
+
+ public void getCert(HttpServletRequest req, IConfigStore config,
+ Context context, String certTag, Cert cert) {
+ CMS.debug("CertPrettyPrintPanel: in getCert()");
+ try {
+ // String cert = config.getString(CONF_CA_CERT);
+ String subsystem = config.getString(PCERT_PREFIX + certTag + ".subsystem");
+ String certs = config.getString(subsystem + "." + certTag + ".cert");
+ byte[] certb = CryptoUtil.base64Decode(certs);
+
+ if (cert != null) {
+ CertPrettyPrint pp = new CertPrettyPrint(certb);
+ cert.setCertpp(pp.toString(Locale.getDefault()));
+ String certf = CryptoUtil.certFormat(certs);
+
+ // String canickname = config.getString(CONF_CA_CERTNICKNAME);
+ // context.put("cert", certf);
+ // context.put("nickname", nickname);
+ cert.setCert(certf);
+ }
+ } catch (Exception e) {
+ CMS.debug("CertPrettyPrintPanel:getCert" + e.toString());
+ } // try
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ CMS.debug("CertPrettyPrintPanel: display()");
+ context.put("title", "Certificates Pretty Print");
+
+ try {
+ mCerts = new Vector();
+
+ IConfigStore config = CMS.getConfigStore();
+
+ String certTags = config.getString("preop.cert.list");
+ StringTokenizer st = new StringTokenizer(certTags, ",");
+
+ while (st.hasMoreTokens()) {
+ String certTag = st.nextToken();
+
+ try {
+ String subsystem = config.getString(
+ PCERT_PREFIX + certTag + ".subsystem");
+
+ String nickname = config.getString(
+ subsystem + "." + certTag + ".nickname");
+ String tokenname = config.getString(
+ subsystem + "." + certTag + ".tokenname");
+ Cert c = new Cert(tokenname, nickname, certTag);
+
+ String type = config.getString(
+ PCERT_PREFIX + certTag + ".type");
+
+ c.setType(type);
+ getCert(request, config, context, certTag, c);
+
+ mCerts.addElement(c);
+ } catch (Exception e) {
+ CMS.debug(
+ "CertPrettyPrintPanel: display() certTag " + certTag
+ + " Exception caught: " + e.toString());
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug(
+ "CertPrettyPrintPanel:display() Exception caught: "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+
+ } // try
+
+ context.put("ppcerts", mCerts);
+ context.put("status", "display");
+ // context.put("status_token", "None");
+ context.put("panel", "admin/console/config/certprettyprintpanel.vm");
+
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ CMS.debug("CertPrettyPrintPanel: in update()");
+ IConfigStore config = CMS.getConfigStore();
+ config.putBoolean("preop.CertPrettyPrintPanel.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ CMS.debug(
+ "CertPrettyPrintPanel: update() Exception caught at config commit: "
+ + e.toString());
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Certificates Pretty Print");
+ context.put("panel", "admin/console/config/certprettyprintpanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java
new file mode 100644
index 000000000..842f87b5f
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertRequestPanel.java
@@ -0,0 +1,757 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.util.*;
+import java.io.*;
+import java.security.*;
+import java.math.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.security.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.request.*;
+
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.PrivateKey;
+import org.mozilla.jss.pkcs11.*;
+
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class CertRequestPanel extends WizardPanelBase {
+ private Vector mCerts = null;
+ private WizardServlet mServlet = null;
+
+ public CertRequestPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Requests & Certificates");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Requests and Certificates");
+ mServlet = servlet;
+ setId(id);
+ }
+
+ // XXX how do you do this? There could be multiple certs.
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ Descriptor certDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ null, /* no default parameters */
+ null);
+
+ set.add("cert", certDesc);
+
+ return set;
+ }
+
+ /**
+ * Show "Apply" button on frame?
+ */
+ public boolean showApplyButton() {
+ if (isPanelDone())
+ return false;
+ else
+ return true;
+ }
+
+ private boolean findCertificate(String tokenname, String nickname)
+ throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ CryptoManager cm = null;
+ try {
+ cm = CryptoManager.getInstance();
+ } catch (Exception e) {
+ }
+
+ String fullnickname = nickname;
+
+ boolean hardware = false;
+ if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token")) {
+ hardware = true;
+ fullnickname = tokenname+":"+nickname;
+ }
+
+ try {
+ X509Certificate cert = cm.findCertByNickname(fullnickname);
+ if (cert == null)
+ return false;
+ try {
+ boolean done = cs.getBoolean("preop.CertRequestPanel.done");
+ return true;
+ } catch (Exception ee) {
+ if (hardware) {
+ CMS.debug("CertRequestPanel findCertificate: The certificate with the same nickname: "+ fullnickname +" has been found on HSM. Please remove it before proceeding.");
+ throw new IOException("The certificate with the same nickname: "+ fullnickname +" has been found on HSM. Please remove it before proceeding.");
+ }
+ return true;
+ }
+ } catch (IOException e) {
+ CMS.debug("CertRequestPanel findCertificate: throw exception:"+e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel findCertificate: Exception="+e.toString());
+ return false;
+ }
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ String select = "";
+ String list = "";
+ String tokenname = "";
+ try {
+ select = cs.getString("preop.subsystem.select", "");
+ list = cs.getString("preop.cert.list", "");
+ tokenname = cs.getString("preop.module.token", "");
+ } catch (Exception e) {
+ }
+
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
+ ICertificateAuthority.ID);
+
+ if (ca != null) {
+ CMS.debug("CertRequestPanel cleanup: get certificate repository");
+ BigInteger beginS = null;
+ BigInteger endS = null;
+ String beginNum = "";
+ String endNum = "";
+ try {
+ beginNum = cs.getString("dbs.beginSerialNumber", "");
+ endNum = cs.getString("dbs.endSerialNumber", "");
+ if (!beginNum.equals(""))
+ beginS = new BigInteger(beginNum, 16);
+ if (!endNum.equals(""))
+ endS = new BigInteger(endNum, 16);
+ } catch (Exception e) {
+ }
+
+ ICertificateRepository cr = ca.getCertificateRepository();
+ if (cr != null) {
+ try {
+ cr.removeCertRecords(beginS, endS);
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel cleanUp exception in removing all objects: "+e.toString());
+ }
+
+ try {
+ cr.resetSerialNumber(new BigInteger(beginNum,16));
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel cleanUp exception in resetting serial number: "+e.toString());
+ }
+ }
+ }
+
+
+ StringTokenizer st = new StringTokenizer(list, ",");
+ String nickname = "";
+ boolean enable = false;
+ while (st.hasMoreTokens()) {
+ String t = st.nextToken();
+
+ try {
+ enable = cs.getBoolean(PCERT_PREFIX+t+".enable", true);
+ nickname = cs.getString(PCERT_PREFIX +t+".nickname", "");
+ } catch (Exception e) {
+ }
+
+ if (!enable)
+ continue;
+
+ if (t.equals("sslserver"))
+ continue;
+
+ if (findCertificate(tokenname, nickname)) {
+ try {
+ CMS.debug("CertRequestPanel cleanup: deleting certificate ("+nickname+").");
+ deleteCert(tokenname, nickname);
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel cleanup: failed to delete certificate (" +nickname+"). Exception: " +e.toString());
+ }
+ }
+ }
+
+ try {
+ boolean done = cs.getBoolean("preop.CertRequestPanel.done");
+ cs.putBoolean("preop.CertRequestPanel.done", false);
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ boolean s = cs.getBoolean("preop.CertRequestPanel.done",
+ false);
+
+ if (s != true) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+
+ return false;
+ }
+
+ public void getCert(IConfigStore config,
+ Context context, String certTag, Cert cert) {
+ try {
+
+ String subsystem = config.getString(
+ PCERT_PREFIX + certTag + ".subsystem");
+
+ String certs = config.getString(subsystem + "." + certTag + ".cert", "");
+
+ if (cert != null) {
+ String certf = certs;
+
+ CMS.debug(
+ "CertRequestPanel getCert: certTag=" + certTag
+ + " cert=" + certs);
+ //get and set formated cert
+ if (!certs.startsWith("...")) {
+ certf = CryptoUtil.certFormat(certs);
+ }
+ cert.setCert(certf);
+
+ //get and set cert pretty print
+ byte[] certb = CryptoUtil.base64Decode(certs);
+ CertPrettyPrint pp = new CertPrettyPrint(certb);
+ cert.setCertpp(pp.toString(Locale.getDefault()));
+ } else {
+ CMS.debug( "CertRequestPanel::getCert() - cert is null!" );
+ return;
+ }
+ String userfriendlyname = config.getString(
+ PCERT_PREFIX + certTag + ".userfriendlyname");
+
+ cert.setUserFriendlyName(userfriendlyname);
+ String type = config.getString(PCERT_PREFIX + certTag + ".type");
+
+ cert.setType(type);
+ String dn = config.getString(PCERT_PREFIX + certTag + ".dn");
+
+ cert.setDN(dn);
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel:getCert" + e.toString());
+ } // try
+ }
+
+ public X509Key getECCX509Key(IConfigStore config, String certTag)
+ throws Exception
+ {
+ X509Key pubk = null;
+ String pubKeyEncoded = config.getString(
+ PCERT_PREFIX + certTag + ".pubkey.encoded");
+ pubk = CryptoUtil.getPublicX509ECCKey(CryptoUtil.string2byte(pubKeyEncoded));
+ return pubk;
+ }
+
+ public X509Key getRSAX509Key(IConfigStore config, String certTag)
+ throws Exception
+ {
+ X509Key pubk = null;
+
+ String pubKeyModulus = config.getString(
+ PCERT_PREFIX + certTag + ".pubkey.modulus");
+ String pubKeyPublicExponent = config.getString(
+ PCERT_PREFIX + certTag + ".pubkey.exponent");
+ pubk = CryptoUtil.getPublicX509Key(
+ CryptoUtil.string2byte(pubKeyModulus),
+ CryptoUtil.string2byte(pubKeyPublicExponent));
+ return pubk;
+ }
+
+ public void handleCertRequest(IConfigStore config,
+ Context context, String certTag, Cert cert) {
+ try {
+ // get public key
+ String pubKeyType = config.getString(
+ PCERT_PREFIX + certTag + ".keytype");
+ String algorithm = config.getString(
+ PCERT_PREFIX + certTag + ".keyalgorithm");
+ X509Key pubk = null;
+ if (pubKeyType.equals("rsa")) {
+ pubk = getRSAX509Key(config, certTag);
+ } else if (pubKeyType.equals("ecc")) {
+ pubk = getECCX509Key(config, certTag);
+ } else {
+ CMS.debug( "CertRequestPanel::handleCertRequest() - "
+ + "pubKeyType " + pubKeyType + " is unsupported!" );
+ return;
+ }
+
+ CMS.debug("CertRequestPanel: tag=" + certTag);
+ if (pubk != null) {
+ CMS.debug("CertRequestPanel: got public key");
+ } else {
+ CMS.debug("CertRequestPanel: error getting public key null");
+ return;
+ }
+
+ // get private key
+ String privKeyID = config.getString(
+ PCERT_PREFIX + certTag + ".privkey.id");
+ CMS.debug("CertRequestPanel: privKeyID=" + privKeyID);
+ byte[] keyIDb = CryptoUtil.string2byte(privKeyID);
+
+ PrivateKey privk = CryptoUtil.findPrivateKeyFromID(keyIDb);
+
+ if (privk != null) {
+ CMS.debug("CertRequestPanel: got private key");
+ } else {
+ CMS.debug("CertRequestPanel: error getting private key null");
+ }
+
+ // construct cert request
+ String caDN = config.getString(PCERT_PREFIX + certTag + ".dn");
+
+ cert.setDN(caDN);
+ PKCS10 certReq = CryptoUtil.createCertificationRequest(caDN, pubk,
+ privk, algorithm);
+
+ CMS.debug("CertRequestPanel: created cert request");
+ byte[] certReqb = certReq.toByteArray();
+ String certReqs = CryptoUtil.base64Encode(certReqb);
+ String certReqf = CryptoUtil.reqFormat(certReqs);
+
+ String subsystem = config.getString(
+ PCERT_PREFIX + certTag + ".subsystem");
+ config.putString(subsystem + "." + certTag + ".certreq", certReqs);
+ config.commit(false);
+ cert.setRequest(certReqf);
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel::handleCertRequest" + e.toString());
+ CMS.debug(e);
+ } // try
+
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ CMS.debug("CertRequestPanel: display()");
+ context.put("title", "Requests and Certificates");
+
+ try {
+ mCerts = new Vector();
+
+ IConfigStore config = CMS.getConfigStore();
+
+ String certTags = config.getString("preop.cert.list");
+ StringTokenizer st = new StringTokenizer(certTags, ",");
+
+ while (st.hasMoreTokens()) {
+ String certTag = st.nextToken();
+
+ try {
+ String subsystem = config.getString(
+ PCERT_PREFIX + certTag + ".subsystem");
+ String nickname = config.getString(
+ subsystem + "." + certTag + ".nickname");
+ String tokenname = config.getString(
+ subsystem + "." + certTag + ".tokenname");
+ Cert c = new Cert(tokenname, nickname, certTag);
+
+ handleCertRequest(config, context, certTag, c);
+
+ String type = config.getString(
+ PCERT_PREFIX + certTag + ".type");
+
+ c.setType(type);
+ boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ c.setEnable(enable);
+ getCert(config, context, certTag, c);
+
+ c.setSubsystem(subsystem);
+ mCerts.addElement(c);
+ } catch (Exception e) {
+ CMS.debug(
+ "CertRequestPanel:display() Exception caught: "
+ + e.toString() + " for certTag " + certTag);
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug(
+ "CertRequestPanel:display() Exception caught: "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+
+ } // try
+
+ context.put("reqscerts", mCerts);
+ context.put("status", "display");
+ // context.put("status_token", "None");
+ context.put("panel", "admin/console/config/certrequestpanel.vm");
+
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ private boolean findBootstrapServerCert() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String instanceID = cs.getString("instanceId", "");
+ String nickname = "Server-Cert cert-" + instanceID;
+
+ CryptoManager cm = CryptoManager.getInstance();
+ X509Certificate cert = cm.findCertByNickname(nickname);
+ Principal issuerDN = cert.getIssuerDN();
+ Principal subjectDN = cert.getSubjectDN();
+ if (issuerDN.equals(subjectDN))
+ return true;
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel findBootstrapServerCert Exception="+e.toString());
+ }
+
+ return false;
+ }
+
+ private void deleteBootstrapServerCert() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String instanceID = cs.getString("instanceId", "");
+ String nickname = "Server-Cert cert-" + instanceID;
+
+ deleteCert("Internal Key Storage Token", nickname);
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel deleteBootstrapServerCert Exception="+e.toString());
+ }
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ CMS.debug("CertRequestPanel: in update()");
+ boolean hasErr = false;
+ IConfigStore config = CMS.getConfigStore();
+
+ String catype = "";
+ try {
+ catype = config.getString("preop.ca.type", "");
+ } catch (Exception e) {
+ }
+
+ if (isPanelDone()) {
+ context.put("updateStatus", "success");
+ return;
+ }
+
+ try {
+ Enumeration c = mCerts.elements();
+
+ String tokenname = "";
+ try {
+ tokenname = config.getString("preop.module.token", "");
+ } catch (Exception e) {
+ }
+
+ while (c.hasMoreElements()) {
+ Cert cert = (Cert) c.nextElement();
+ String certTag = cert.getCertTag();
+ String subsystem = cert.getSubsystem();
+ boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ if (!enable)
+ continue;
+
+ if (hasErr)
+ continue;
+
+ String nickname = cert.getNickname();
+
+ CMS.debug(
+ "CertRequestPanel: update() for cert tag "
+ + cert.getCertTag());
+ // String b64 = config.getString(CERT_PREFIX+ certTag +".cert", "");
+ String b64 = HttpInput.getCert(request, certTag);
+
+ if (cert.getType().equals("local")
+ && b64.equals(
+ "...certificate be generated internally...")) {
+
+ String pubKeyType = config.getString(
+ PCERT_PREFIX + certTag + ".keytype");
+ X509Key x509key = null;
+ if (pubKeyType.equals("rsa")) {
+ x509key = getRSAX509Key(config, certTag);
+ } else if (pubKeyType.equals("ecc")) {
+ x509key = getECCX509Key(config, certTag);
+ }
+
+ if (findCertificate(tokenname, nickname)) {
+ if (!certTag.equals("sslserver"))
+ continue;
+ }
+ X509CertImpl impl = CertUtil.createLocalCert(config, x509key,
+ PCERT_PREFIX, certTag, cert.getType(), context);
+
+ if (impl != null) {
+ byte[] certb = impl.getEncoded();
+ String certs = CryptoUtil.base64Encode(certb);
+
+ cert.setCert(certs);
+ config.putString(subsystem + "." + certTag + ".cert", certs);
+ /* import certificate */
+ CMS.debug(
+ "CertRequestPanel configCert: nickname="
+ + nickname);
+
+ try {
+ if (certTag.equals("sslserver") && findBootstrapServerCert())
+ deleteBootstrapServerCert();
+ if (findCertificate(tokenname, nickname))
+ deleteCert(tokenname, nickname);
+ if (certTag.equals("signing") && subsystem.equals("ca"))
+ CryptoUtil.importUserCertificate(impl, nickname);
+ else
+ CryptoUtil.importUserCertificate(impl, nickname, false);
+ CMS.debug(
+ "CertRequestPanel configCert: cert imported for certTag "
+ + certTag);
+ } catch (Exception ee) {
+ CMS.debug(
+ "CertRequestPanel configCert: import certificate for certTag="
+ + certTag + " Exception: "
+ + ee.toString());
+ CMS.debug("ok");
+// hasErr = true;
+ }
+ }
+ } else if (cert.getType().equals("remote")) {
+ if (b64 != null && b64.length() > 0
+ && !b64.startsWith("...")) {
+ String b64chain = HttpInput.getCertChain(request, certTag+"_cc");
+ CMS.debug(
+ "CertRequestPanel: in update() process remote...import cert");
+
+ String input = HttpInput.getCert(request, cert.getCertTag());
+
+ if (input != null) {
+ try {
+ if (certTag.equals("sslserver") && findBootstrapServerCert())
+ deleteBootstrapServerCert();
+ if (findCertificate(tokenname, nickname)) {
+ deleteCert(tokenname, nickname);
+ }
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel update (remote): deleteCert Exception="+e.toString());
+ }
+ input = CryptoUtil.stripCertBrackets(input.trim());
+ String certs = CryptoUtil.normalizeCertStr(input);
+ byte[] certb = CryptoUtil.base64Decode(certs);
+
+ config.putString(subsystem + "." + certTag + ".cert",
+ certs);
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ X509Certificate x509cert = cm.importCertPackage(
+ certb, nickname);
+
+ CryptoUtil.trustCertByNickname(nickname);
+ X509Certificate[] certchains = cm.buildCertificateChain(
+ x509cert);
+ X509Certificate leaf = null;
+
+ if (certchains != null) {
+ CMS.debug(
+ "CertRequestPanel certchains length="
+ + certchains.length);
+ leaf = certchains[certchains.length - 1];
+ }
+
+ if( leaf == null ) {
+ CMS.debug( "CertRequestPanel::update() - "
+ + "leaf is null!" );
+ throw new IOException( "leaf is null" );
+ }
+
+ if (/*(certchains.length <= 1) &&*/
+ (b64chain != null)) {
+ CMS.debug("CertRequestPanel: cert might not have contained chain...calling importCertificateChain");
+ try {
+ CryptoUtil.importCertificateChain(
+ CryptoUtil.normalizeCertAndReq(b64chain));
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel: importCertChain: Exception: "+e.toString());
+ }
+ }
+
+ InternalCertificate icert = (InternalCertificate) leaf;
+
+ icert.setSSLTrust(
+ InternalCertificate.TRUSTED_CA
+ | InternalCertificate.TRUSTED_CLIENT_CA
+ | InternalCertificate.VALID_CA);
+ CMS.debug(
+ "CertRequestPanel configCert: import certificate successfully, certTag="
+ + certTag);
+ } catch (Exception ee) {
+ CMS.debug(
+ "CertRequestPanel configCert: import certificate for certTag="
+ + certTag + " Exception: "
+ + ee.toString());
+ CMS.debug("ok");
+// hasErr=true;
+ }
+ } else {
+ CMS.debug("CertRequestPanel: in update() input null");
+ hasErr = true;
+ }
+ } else {
+ CMS.debug("CertRequestPanel: in update() b64 not set");
+ hasErr=true;
+ }
+
+ } else {
+ b64 = CryptoUtil.stripCertBrackets(b64.trim());
+ String certs = CryptoUtil.normalizeCertStr(b64);
+ byte[] certb = CryptoUtil.base64Decode(certs);
+ X509CertImpl impl = new X509CertImpl(certb);
+ try {
+ if (certTag.equals("sslserver") && findBootstrapServerCert())
+ deleteBootstrapServerCert();
+ if (findCertificate(tokenname, nickname)) {
+ deleteCert(tokenname, nickname);
+ }
+ } catch (Exception ee) {
+ CMS.debug("CertRequestPanel update: deleteCert Exception="+ee.toString());
+ }
+
+ try {
+ if (certTag.equals("signing") && subsystem.equals("ca"))
+ CryptoUtil.importUserCertificate(impl, nickname);
+ else
+ CryptoUtil.importUserCertificate(impl, nickname, false);
+ } catch (Exception ee) {
+ CMS.debug("CertRequestPanel: Failed to import user certificate."+ee.toString());
+ hasErr=true;
+ }
+ }
+
+ //update requests in request queue for local certs to allow renewal
+ if ((cert.getType().equals("local")) || (cert.getType().equals("selfsign"))) {
+ CertUtil.updateLocalRequest(config, certTag, cert.getRequest(), "pkcs10", null);
+ }
+
+ if (certTag.equals("signing") && subsystem.equals("ca")) {
+ String NickName = nickname;
+ if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
+ NickName = tokenname+ ":"+ nickname;
+
+ CMS.debug("CertRequestPanel update: set trust on CA signing cert "+NickName);
+ CryptoUtil.trustCertByNickname(NickName);
+ CMS.reinit(ICertificateAuthority.ID);
+ }
+ } //while loop
+
+ if (hasErr == false) {
+ config.putBoolean("preop.CertRequestPanel.done", true);
+ }
+ config.commit(false);
+ } catch (Exception e) {
+ CMS.debug("CertRequestPanel: Exception caught: " + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+
+ //reset the attribute of the user certificate to u,u,u
+ String certlist = "";
+ try {
+ certlist = config.getString("preop.cert.list", "");
+ StringTokenizer tokenizer = new StringTokenizer(certlist, ",");
+ CryptoManager cm = CryptoManager.getInstance();
+ while (tokenizer.hasMoreTokens()) {
+ String tag = tokenizer.nextToken();
+ if (tag.equals("signing"))
+ continue;
+ String nickname = config.getString("preop.cert."+tag+".nickname", "");
+ String tokenname = config.getString("preop.module.token", "");
+ if (!tokenname.equals("Internal Key Storage Token"))
+ nickname = tokenname+":"+nickname;
+ X509Certificate c = cm.findCertByNickname(nickname);
+ if (c instanceof InternalCertificate) {
+ InternalCertificate ic = (InternalCertificate)c;
+ ic.setSSLTrust(InternalCertificate.USER);
+ ic.setEmailTrust(InternalCertificate.USER);
+ if (tag.equals("audit_signing")) {
+ ic.setObjectSigningTrust(InternalCertificate.USER | InternalCertificate.VALID_PEER | InternalCertificate.TRUSTED_PEER);
+ } else {
+ ic.setObjectSigningTrust(InternalCertificate.USER);
+ }
+ }
+ }
+ } catch (Exception e) {
+ }
+ if (!hasErr) {
+ context.put("updateStatus", "success");
+ } else {
+ context.put("updateStatus", "failure");
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Certificate Request");
+ context.put("panel", "admin/console/config/certrequestpanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java
new file mode 100644
index 000000000..dc8adaf97
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CertUtil.java
@@ -0,0 +1,652 @@
+// --- 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.security.*;
+import java.security.cert.*;
+import java.net.*;
+import java.util.*;
+import java.math.*;
+import java.io.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.request.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.cmsutil.http.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.usrgrp.*;
+import netscape.security.x509.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.X509Certificate;
+import org.mozilla.jss.crypto.PrivateKey;
+import com.netscape.cmsutil.xml.*;
+import org.mozilla.jss.crypto.KeyPairGenerator;
+import netscape.security.pkcs.*;
+import netscape.ldap.*;
+import org.apache.velocity.context.Context;
+import org.xml.sax.*;
+
+
+public class CertUtil {
+ static final int LINE_COUNT = 76;
+
+ public static X509CertImpl createRemoteCert(String hostname,
+ int port, String content, HttpServletResponse response, WizardPanelBase panel)
+ throws IOException {
+ HttpClient httpclient = new HttpClient();
+ String c = null;
+ CMS.debug("CertUtil createRemoteCert: content " + content);
+ try {
+ JssSSLSocketFactory factory = new JssSSLSocketFactory();
+
+ httpclient = new HttpClient(factory);
+ httpclient.connect(hostname, port);
+ HttpRequest httprequest = new HttpRequest();
+
+ httprequest.setMethod(HttpRequest.POST);
+ httprequest.setURI("/ca/ee/ca/profileSubmit");
+ httprequest.setHeader("user-agent", "HTTPTool/1.0");
+ httprequest.setHeader("content-length", "" + content.length());
+ httprequest.setHeader("content-type",
+ "application/x-www-form-urlencoded");
+ httprequest.setContent(content);
+ HttpResponse httpresponse = httpclient.send(httprequest);
+
+ c = httpresponse.getContent();
+ } catch (Exception e) {
+ CMS.debug("CertUtil createRemoteCert: " + e.toString());
+ throw new IOException(e.toString());
+ }
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "CertUtil::createRemoteCert() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+ String status = parser.getValue("Status");
+
+ CMS.debug("CertUtil createRemoteCert: status=" + status);
+ if (status.equals("2")) {
+ //relogin to the security domain
+ panel.reloginSecurityDomain(response);
+ return null;
+ } else if (!status.equals("0")) {
+ String error = parser.getValue("Error");
+ throw new IOException(error);
+ }
+
+ String b64 = parser.getValue("b64");
+
+ CMS.debug("CertUtil createRemoteCert: " + b64);
+ b64 = CryptoUtil.normalizeCertAndReq(b64);
+ byte[] b = CryptoUtil.base64Decode(b64);
+
+ return new X509CertImpl(b);
+ } catch (Exception e) {
+ CMS.debug("CertUtil createRemoteCert: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return null;
+ }
+
+ public static String getPKCS10(IConfigStore config, String prefix,
+ Cert certObj, Context context) throws IOException {
+ String certTag = certObj.getCertTag();
+
+ X509Key pubk = null;
+ try {
+ String pubKeyType = config.getString(
+ prefix + certTag + ".keytype");
+ String algorithm = config.getString(
+ prefix + certTag + ".keyalgorithm");
+ if (pubKeyType.equals("rsa")) {
+ String pubKeyModulus = config.getString(
+ prefix + certTag + ".pubkey.modulus");
+ String pubKeyPublicExponent = config.getString(
+ prefix + certTag + ".pubkey.exponent");
+ pubk = CryptoUtil.getPublicX509Key(
+ CryptoUtil.string2byte(pubKeyModulus),
+ CryptoUtil.string2byte(pubKeyPublicExponent));
+ } else if (pubKeyType.equals("ecc")) {
+ String pubKeyEncoded = config.getString(
+ prefix + certTag + ".pubkey.encoded");
+ pubk = CryptoUtil.getPublicX509ECCKey(
+ CryptoUtil.string2byte(pubKeyEncoded));
+ } else {
+ CMS.debug( "CertRequestPanel::getPKCS10() - "
+ + "public key type is unsupported!" );
+ throw new IOException( "public key type is unsupported" );
+ }
+
+ if (pubk != null) {
+ CMS.debug("CertRequestPanel: got public key");
+ } else {
+ CMS.debug("CertRequestPanel: error getting public key null");
+ throw new IOException( "public key is null" );
+ }
+ // get private key
+ String privKeyID = config.getString(prefix + certTag + ".privkey.id");
+ byte[] keyIDb = CryptoUtil.string2byte(privKeyID);
+
+ PrivateKey privk = CryptoUtil.findPrivateKeyFromID(keyIDb);
+
+ if (privk != null) {
+ CMS.debug("CertRequestPanel: got private key");
+ } else {
+ CMS.debug("CertRequestPanel: error getting private key null");
+ }
+
+ // construct cert request
+ String dn = config.getString(prefix + certTag + ".dn");
+
+ PKCS10 certReq = null;
+ certReq = CryptoUtil.createCertificationRequest(dn, pubk,
+ privk, algorithm);
+ byte[] certReqb = certReq.toByteArray();
+ String certReqs = CryptoUtil.base64Encode(certReqb);
+
+ return certReqs;
+ } catch (Throwable e) {
+ CMS.debug(e);
+ context.put("errorString", e.toString());
+ CMS.debug("CertUtil getPKCS10: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+
+/*
+ * create requests so renewal can work on these initial certs
+ */
+ public static IRequest createLocalRequest(IRequestQueue queue, String serialNum, X509CertInfo info) throws EBaseException {
+// RequestId rid = new RequestId(serialNum);
+ // just need a request, no need to get into a queue
+// IRequest r = new EnrollmentRequest(rid);
+ CMS.debug("CertUtil: createLocalRequest for serial: "+ serialNum);
+ IRequest req = queue.newRequest("enrollment");
+ CMS.debug("certUtil: newRequest called");
+ req.setExtData("profile", "true");
+ req.setExtData("requestversion", "1.0.0");
+ req.setExtData("req_seq_num", "0");
+ req.setExtData(IEnrollProfile.REQUEST_CERTINFO, info);
+ req.setExtData(IEnrollProfile.REQUEST_EXTENSIONS,
+ new CertificateExtensions());
+ req.setExtData("requesttype", "enrollment");
+ req.setExtData("requestor_name", "");
+ req.setExtData("requestor_email", "");
+ req.setExtData("requestor_phone", "");
+ req.setExtData("profileRemoteHost", "");
+ req.setExtData("profileRemoteAddr", "");
+ req.setExtData("requestnotes","");
+ req.setExtData("isencryptioncert", "false");
+ req.setExtData("profileapprovedby", "system");
+
+ // mark request as complete
+ CMS.debug("certUtil: calling setRequestStatus");
+ req.setRequestStatus(RequestStatus.COMPLETE);
+
+ return req;
+ }
+
+/**
+ * update local cert request with the actual request
+ * called from CertRequestPanel.java
+ */
+ public static void updateLocalRequest(IConfigStore config, String certTag, String certReq, String reqType, String subjectName)
+ {
+ try {
+ CMS.debug("Updating local request... certTag=" + certTag);
+ RequestId rid = new RequestId(config.getString("preop.cert." + certTag + ".reqId"));
+
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
+ ICertificateAuthority.ID);
+
+ IRequestQueue queue = ca.getRequestQueue();
+ if (queue != null) {
+ IRequest req = queue.findRequest(rid);
+ if (req != null) {
+ if (!certReq.equals(""))
+ req.setExtData("cert_request", certReq);
+ req.setExtData("cert_request_type", reqType);
+ if (subjectName != null) {
+ req.setExtData("subject", subjectName);
+ X500Name x5Name = new X500Name(subjectName);
+ }
+ }
+ queue.updateRequest(req);
+ } else {
+ CMS.debug("CertUtil:updateLocalRequest - request queue = null");
+ }
+ } catch (Exception e) {
+ CMS.debug("CertUtil:updateLocalRequest - Exception:" + e.toString());
+ }
+ }
+
+/**
+ * reads from the admin cert profile caAdminCert.profile and takes the first
+ * entry in the list of allowed algorithms. Users that wish a different algorithm
+ * can specify it in the profile using default.params.signingAlg
+ */
+
+ public static String getAdminProfileAlgorithm(IConfigStore config) {
+ String algorithm = "SHA256withRSA";
+ try {
+ String caSigningKeyType = config.getString("preop.cert.signing.keytype","rsa");
+ String pfile = config.getString("profile.caAdminCert.config");
+ FileInputStream fis = new FileInputStream(pfile);
+ DataInputStream in = new DataInputStream(fis);
+ BufferedReader br = new BufferedReader(new InputStreamReader(in));
+
+ String strLine;
+ while ((strLine = br.readLine()) != null) {
+ String marker2 = "default.params.signingAlg=";
+ int indx = strLine.indexOf(marker2);
+ if (indx != -1) {
+ String alg = strLine.substring(indx + marker2.length());
+ if ((alg.length() > 0) && (!alg.equals("-"))) {
+ algorithm = alg;
+ break;
+ };
+ };
+
+ String marker = "signingAlgsAllowed=";
+ indx = strLine.indexOf(marker);
+ if (indx != -1) {
+ String[] algs = strLine.substring(indx + marker.length()).split(",");
+ for (int i=0; i<algs.length; i++) {
+ if ((caSigningKeyType.equals("rsa") && (algs[i].indexOf("RSA") != -1)) ||
+ (caSigningKeyType.equals("ecc") && (algs[i].indexOf("EC" ) != -1)) ) {
+ algorithm = algs[i];
+ break;
+ }
+ }
+ }
+ }
+ in.close();
+ } catch (Exception e) {
+ CMS.debug("getAdminProfleAlgorithm: exception: " + e);
+ }
+ return algorithm;
+ }
+
+ public static X509CertImpl createLocalCert(IConfigStore config, X509Key x509key,
+ String prefix, String certTag, String type, Context context) throws IOException {
+
+ CMS.debug("Creating local certificate... certTag=" + certTag);
+ String profile = null;
+
+ try {
+ profile = config.getString(prefix + certTag + ".profile");
+ } catch (Exception e) {}
+
+ X509CertImpl cert = null;
+ ICertificateAuthority ca = null;
+ ICertificateRepository cr = null;
+ RequestId reqId = null;
+ String profileId = null;
+ IRequestQueue queue = null;
+ IRequest req = null;
+
+ try {
+ String dn = config.getString(prefix + certTag + ".dn");
+ String keyAlgorithm = null;
+ Date date = new Date();
+
+ X509CertInfo info = null;
+
+ if (certTag.equals("admin")) {
+ keyAlgorithm = getAdminProfileAlgorithm(config);
+ } else {
+ keyAlgorithm = config.getString(prefix + certTag + ".keyalgorithm");
+ }
+ ca = (ICertificateAuthority) CMS.getSubsystem(
+ ICertificateAuthority.ID);
+ cr = (ICertificateRepository) ca.getCertificateRepository();
+ BigInteger serialNo = cr.getNextSerialNumber();
+ if (type.equals("selfsign")) {
+ CMS.debug("Creating local certificate... issuerdn=" + dn);
+ CMS.debug("Creating local certificate... dn=" + dn);
+ info = CryptoUtil.createX509CertInfo(x509key, serialNo.intValue(), dn, dn, date,
+ date, keyAlgorithm);
+ } else {
+ String issuerdn = config.getString("preop.cert.signing.dn", "");
+ CMS.debug("Creating local certificate... issuerdn=" + issuerdn);
+ CMS.debug("Creating local certificate... dn=" + dn);
+
+ info = CryptoUtil.createX509CertInfo(x509key,
+ serialNo.intValue(), issuerdn, dn, date, date, keyAlgorithm);
+ }
+ CMS.debug("Cert Template: " + info.toString());
+
+ String instanceRoot = config.getString("instanceRoot");
+
+ CertInfoProfile processor = new CertInfoProfile(
+ instanceRoot + "/conf/" + profile);
+
+ // cfu - create request to enable renewal
+ try {
+ queue = ca.getRequestQueue();
+ if (queue != null) {
+ req = createLocalRequest(queue, serialNo.toString(), info);
+ CMS.debug("CertUtil profile name= "+profile);
+ req.setExtData("req_key", x509key.toString());
+
+ // store original profile id in cert request
+ int idx = profile.lastIndexOf('.');
+ if (idx == -1) {
+ CMS.debug("CertUtil profileName contains no .");
+ req.setExtData("origprofileid", profile);
+ } else {
+ String name = profile.substring(0, idx);
+ req.setExtData("origprofileid", name);
+ }
+
+ // store mapped profile ID for use in renewal
+ profileId = processor.getProfileIDMapping();
+ req.setExtData("profileid", profileId);
+ req.setExtData("profilesetid", processor.getProfileSetIDMapping());
+
+ reqId = req.getRequestId();
+ config.putString("preop.cert." + certTag + ".reqId", reqId.toString());
+ } else {
+ CMS.debug("certUtil: requestQueue null");
+ }
+ } catch (Exception e) {
+ CMS.debug("Creating local request exception:"+e.toString());
+ }
+
+ processor.populate(info);
+
+ String caPriKeyID = config.getString(
+ prefix + "signing" + ".privkey.id");
+ byte[] keyIDb = CryptoUtil.string2byte(caPriKeyID);
+ PrivateKey caPrik = CryptoUtil.findPrivateKeyFromID(
+ keyIDb);
+
+ if( caPrik == null ) {
+ CMS.debug( "CertUtil::createSelfSignedCert() - "
+ + "CA private key is null!" );
+ throw new IOException( "CA private key is null" );
+ } else {
+ CMS.debug("CertUtil createSelfSignedCert: got CA private key");
+ }
+
+ String keyAlgo = x509key.getAlgorithm();
+ CMS.debug("key algorithm is " + keyAlgo);
+ String caSigningKeyType =
+ config.getString("preop.cert.signing.keytype","rsa");
+ String caSigningKeyAlgo = "";
+ if (type.equals("selfsign")) {
+ caSigningKeyAlgo = config.getString("preop.cert.signing.keyalgorithm","SHA256withRSA");
+ } else {
+ caSigningKeyAlgo = config.getString("preop.cert.signing.signingalgorithm","SHA256withRSA");
+ }
+
+ CMS.debug("CA Signing Key type " + caSigningKeyType);
+ CMS.debug("CA Signing Key algorithm " + caSigningKeyAlgo);
+
+ if (caSigningKeyType.equals("ecc")) {
+ CMS.debug("CA signing cert is ECC");
+ cert = CryptoUtil.signECCCert(caPrik, info,
+ caSigningKeyAlgo);
+ } else {
+ CMS.debug("CA signing cert is not ecc");
+ cert = CryptoUtil.signCert(caPrik, info,
+ caSigningKeyAlgo);
+ }
+
+ if (cert != null) {
+ CMS.debug("CertUtil createSelfSignedCert: got cert signed");
+ }
+ } catch (Exception e) {
+ CMS.debug(e);
+ CMS.debug("NamePanel configCert() exception caught:" + e.toString());
+ }
+
+ if (cr == null) {
+ context.put("errorString",
+ "Ceritifcate Authority is not ready to serve.");
+ throw new IOException("Ceritifcate Authority is not ready to serve.");
+ }
+
+ ICertRecord record = null;
+ try {
+ MetaInfo meta = new MetaInfo();
+ if (reqId != null) {
+ meta.set(ICertRecord.META_REQUEST_ID, reqId.toString());
+ }
+
+ meta.set(ICertRecord.META_PROFILE_ID, profileId);
+ record = (ICertRecord) cr.createCertRecord(
+ cert.getSerialNumber(), cert, meta);
+ } catch (Exception e) {
+ CMS.debug(
+ "NamePanel configCert: failed to add metainfo. Exception: " + e.toString());
+ }
+
+ try {
+ cr.addCertificateRecord(record);
+ CMS.debug(
+ "NamePanel configCert: finished adding certificate record.");
+ } catch (Exception e) {
+ CMS.debug(
+ "NamePanel configCert: failed to add certificate record. Exception: "
+ + e.toString());
+ try {
+ cr.deleteCertificateRecord(record.getSerialNumber());
+ cr.addCertificateRecord(record);
+ } catch (Exception ee) {
+ CMS.debug("NamePanel update: Exception: " + ee.toString());
+ }
+ }
+
+ if (req != null) {
+ // update request with cert
+ req.setExtData(IEnrollProfile.REQUEST_ISSUED_CERT, cert);
+
+ // store request in db
+ try {
+ CMS.debug("certUtil: before updateRequest");
+ if (queue != null) {
+ queue.updateRequest(req);
+ }
+ } catch (Exception e) {
+ CMS.debug("Exception in updateRequest" + e);
+ }
+ }
+
+ return cert;
+ }
+
+ public static void addUserCertificate(X509CertImpl cert) {
+ IConfigStore cs = CMS.getConfigStore();
+ int num=0;
+ try {
+ num = cs.getInteger("preop.subsystem.count", 0);
+ } catch (Exception e) {
+ }
+ IUGSubsystem system = (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
+ String id = "user"+num;
+
+ try {
+ String sysType = cs.getString("cs.type", "");
+ String machineName = cs.getString("machineName", "");
+ String securePort = cs.getString("service.securePort", "");
+ id = sysType + "-" + machineName + "-" + securePort;
+ } catch (Exception e1) {
+ // ignore
+ }
+
+ num++;
+ cs.putInteger("preop.subsystem.count", num);
+ cs.putInteger("subsystem.count", num);
+
+ try {
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+
+ IUser user = null;
+ X509CertImpl[] certs = new X509CertImpl[1];
+ CMS.debug("CertUtil addUserCertificate starts");
+ try {
+ user = system.createUser(id);
+ user.setFullName(id);
+ user.setEmail("");
+ user.setPassword("");
+ user.setUserType("agentType");
+ user.setState("1");
+ user.setPhone("");
+ certs[0] = cert;
+ user.setX509Certificates(certs);
+ system.addUser(user);
+ CMS.debug("CertUtil addUserCertificate: successfully add the user");
+ } catch (LDAPException e) {
+ CMS.debug("CertUtil addUserCertificate" + e.toString());
+ if (e.getLDAPResultCode() != LDAPException.ENTRY_ALREADY_EXISTS) {
+ try {
+ user = system.getUser(id);
+ user.setX509Certificates(certs);
+ } catch (Exception ee) {
+ CMS.debug("CertUtil addUserCertificate: successfully find the user");
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug("CertUtil addUserCertificate addUser " + e.toString());
+ }
+
+ try {
+ system.addUserCert(user);
+ CMS.debug("CertUtil addUserCertificate: successfully add the user certificate");
+ } catch (Exception e) {
+ CMS.debug("CertUtil addUserCertificate exception="+e.toString());
+ }
+
+ IGroup group = null;
+ String groupName = "Subsystem Group";
+
+ try {
+ group = system.getGroupFromName(groupName);
+ if (!group.isMember(id)) {
+ group.addMemberName(id);
+ system.modifyGroup(group);
+ CMS.debug("CertUtil addUserCertificate: update: successfully added the user to the group.");
+ }
+ } catch (Exception e) {
+ CMS.debug("CertUtil addUserCertificate update: modifyGroup " + e.toString());
+ }
+ }
+
+ /*
+ * formats a cert fingerprints
+ */
+ public static String fingerPrintFormat(String content) {
+ if (content == null || content.length() == 0) {
+ return "";
+ }
+
+ StringBuffer result = new StringBuffer();
+ result.append("Fingerprints:\n");
+ int index = 0;
+
+ while (content.length() >= LINE_COUNT) {
+ result.append(content.substring(0, LINE_COUNT));
+ result.append("\n");
+ content = content.substring(LINE_COUNT);
+ }
+ if (content.length() > 0)
+ result.append(content);
+ result.append("\n");
+
+ return result.toString();
+ }
+
+ public static boolean privateKeyExistsOnToken(String certTag,
+ String tokenname, String nickname) {
+ IConfigStore cs = CMS.getConfigStore();
+ String givenid = "";
+ try {
+ givenid = cs.getString("preop.cert."+certTag+".privkey.id");
+ } catch (Exception e) {
+ CMS.debug("CertUtil privateKeyExistsOnToken: we did not generate private key yet.");
+ return false;
+ }
+
+ String fullnickname = nickname;
+
+ boolean hardware = false;
+ if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token")) {
+ hardware = true;
+ fullnickname = tokenname+":"+nickname;
+ }
+
+ X509Certificate cert = null;
+ CryptoManager cm = null;
+ try {
+ cm = CryptoManager.getInstance();
+ cert = cm.findCertByNickname(fullnickname);
+ } catch (Exception e) {
+ CMS.debug("CertUtil privateKeyExistsOnToken: nickname="+fullnickname+" Exception:"+e.toString());
+ return false;
+ }
+
+ PrivateKey privKey = null;
+ try {
+ privKey = cm.findPrivKeyByCert(cert);
+ } catch (Exception e) {
+ CMS.debug("CertUtil privateKeyExistsOnToken: cant find private key ("+fullnickname+") exception: "+e.toString());
+ return false;
+ }
+
+ if (privKey == null) {
+ CMS.debug("CertUtil privateKeyExistsOnToken: cant find private key ("+fullnickname+")");
+ return false;
+ } else {
+ String str = "";
+ try {
+ str = CryptoUtil.byte2string(privKey.getUniqueID());
+ } catch (Exception e) {
+ CMS.debug("CertUtil privateKeyExistsOnToken: encode string Exception: "+e.toString());
+ }
+
+ if (str.equals(givenid)) {
+ CMS.debug("CertUtil privateKeyExistsOnToken: find the private key on the token.");
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java
new file mode 100644
index 000000000..829e46a44
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CheckIdentity.java
@@ -0,0 +1,115 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+
+
+public class CheckIdentity extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public CheckIdentity() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+
+ CMS.debug("CheckIdentity init");
+ }
+
+ /**
+ * Process the HTTP request.
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = null;
+
+ try {
+ authToken = authenticate(cmsReq);
+ } catch (Exception e) {
+ CMS.debug("CheckIdentity authentication failed");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ outputError(httpResp, "Error: Not authenticated");
+ return;
+ }
+
+ try {
+ XMLObject xmlObj = null;
+
+ xmlObj = new XMLObject();
+
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {
+ // do nothing, ie, it will not return the default javascript.
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java
new file mode 100644
index 000000000..8017a893f
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigBaseServlet.java
@@ -0,0 +1,117 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import java.io.*;
+import java.util.*;
+import com.netscape.certsrv.apps.*;
+
+
+public abstract class ConfigBaseServlet extends BaseServlet {
+ public boolean isDisplayMode(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String display = request.getParameter("display");
+
+ if (display == null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public abstract void display(HttpServletRequest request,
+ HttpServletResponse response, Context context);
+
+ public abstract void update(HttpServletRequest request,
+ HttpServletResponse response, Context context);
+
+ public abstract Template getTemplate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context);
+
+ public void outputHttpParameters(HttpServletRequest httpReq) {
+ CMS.debug("ConfigBaseServlet:service() uri = " + httpReq.getRequestURI());
+ Enumeration paramNames = httpReq.getParameterNames();
+
+ while (paramNames.hasMoreElements()) {
+ String pn = (String) paramNames.nextElement();
+ // added this facility so that password can be hidden,
+ // all sensitive parameters should be prefixed with
+ // __ (double underscores); however, in the event that
+ // a security parameter slips through, we perform multiple
+ // additional checks to insure that it is NOT displayed
+ if( pn.startsWith("__") ||
+ pn.endsWith("password") ||
+ pn.endsWith("passwd") ||
+ pn.endsWith("pwd") ||
+ pn.equalsIgnoreCase("admin_password_again") ||
+ pn.equalsIgnoreCase("directoryManagerPwd") ||
+ pn.equalsIgnoreCase("bindpassword") ||
+ pn.equalsIgnoreCase("bindpwd") ||
+ pn.equalsIgnoreCase("passwd") ||
+ pn.equalsIgnoreCase("password") ||
+ pn.equalsIgnoreCase("pin") ||
+ pn.equalsIgnoreCase("pwd") ||
+ pn.equalsIgnoreCase("pwdagain") ||
+ pn.equalsIgnoreCase("uPasswd") ) {
+ CMS.debug("ConfigBaseServlet::service() param name='" + pn +
+ "' value='(sensitive)'" );
+ } else {
+ CMS.debug("ConfigBaseServlet::service() param name='" + pn +
+ "' value='" + httpReq.getParameter(pn) + "'" );
+ }
+ }
+ }
+
+ /**
+ * Processes request.
+ */
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ if (CMS.debugOn()) {
+ outputHttpParameters(request);
+ }
+
+ if (isDisplayMode(request, response, context)) {
+ display(request, response, context);
+ } else {
+ update(request, response, context);
+ }
+
+ Template template = null;
+
+ try {
+ context.put("name", "Velocity Test");
+ template = getTemplate(request, response, context);
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java
new file mode 100644
index 000000000..6acb71273
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertApprovalCallback.java
@@ -0,0 +1,37 @@
+// --- 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.util.*;
+import com.netscape.certsrv.apps.CMS;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.ssl.*;
+
+
+public class ConfigCertApprovalCallback
+ implements SSLCertificateApprovalCallback {
+
+ public ConfigCertApprovalCallback() {
+ }
+
+ public boolean approve(X509Certificate cert,
+ SSLCertificateApprovalCallback.ValidityStatus status) {
+ return true;
+ }
+}
+
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java
new file mode 100644
index 000000000..0a9d9a9cd
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCertReqServlet.java
@@ -0,0 +1,46 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+
+public class ConfigCertReqServlet extends BaseServlet {
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ Template template = null;
+
+ try {
+ context.put("name", "Velocity Test");
+ template = Velocity.getTemplate(
+ "admin/console/config/config_certreq.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java
new file mode 100644
index 000000000..73150946b
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigCloneServlet.java
@@ -0,0 +1,46 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+
+public class ConfigCloneServlet extends BaseServlet {
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ Template template = null;
+
+ try {
+ context.put("name", "Velocity Test");
+ template = Velocity.getTemplate(
+ "admin/console/config/config_clone.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java
new file mode 100644
index 000000000..56da3a232
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigDatabaseServlet.java
@@ -0,0 +1,190 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.base.*;
+import java.io.*;
+
+
+public class ConfigDatabaseServlet extends ConfigBaseServlet {
+
+ private static final String HOST = "localhost";
+ private static final String PORT = "389";
+ private static final String BASEDN = "o=netscapeCertificateServer";
+ private static final String BINDDN = "cn=Directory Manager";
+ private static final String DATABASE = "userRoot";
+
+ public boolean isPanelModified() {
+ IConfigStore cs = CMS.getConfigStore();
+ String modified = "";
+
+ try {
+ modified = cs.getString("preop.configDatabase.modified", "");
+ } catch (Exception e) {}
+
+ if (modified.equals("true")) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String hostname = null;
+ String portStr = null;
+ String basedn = null;
+ String binddn = null;
+ String bindpwd = "";
+ String database = null;
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ if (isPanelModified()) {
+ try {
+ hostname = cs.getString("internaldb.ldapconn.host", "");
+ portStr = cs.getString("internaldb.ldapconn.port", "");
+ basedn = cs.getString("internaldb.basedn", "");
+ binddn = cs.getString("internaldb.ldapauth.bindDN", "");
+ database = cs.getString("internaldb.database", "");
+ } catch (Exception e) {}
+ } else {
+ hostname = HOST;
+ portStr = PORT;
+ basedn = BASEDN;
+ binddn = BINDDN;
+ database = DATABASE;
+ }
+
+ context.put("hostname", hostname);
+ context.put("portStr", portStr);
+ context.put("basedn", basedn);
+ context.put("binddn", binddn);
+ context.put("bindpwd", bindpwd);
+ context.put("database", database);
+ context.put("displayStr", "initial");
+ context.put("errorString", "");
+ }
+
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ IConfigStore cs = CMS.getConfigStore();
+ String errorString = "";
+ String hostname = request.getParameter("host");
+
+ if (hostname != null && hostname.length() > 0) {
+ cs.putString("internaldb.ldapconn.host", hostname);
+ } else {
+ errorString = "Host is empty string";
+ }
+
+ String portStr = request.getParameter("port");
+
+ if (portStr != null && portStr.length() > 0) {
+ int port = -1;
+
+ try {
+ port = Integer.parseInt(portStr);
+ cs.putInteger("internaldb.ldapconn.port", port);
+ } catch (Exception e) {
+ errorString = "Port is invalid";
+ }
+ } else {
+ errorString = "Port is empty string";
+ }
+
+ String basedn = request.getParameter("basedn");
+
+ if (basedn != null && basedn.length() > 0) {
+ cs.putString("internaldb.basedn", basedn);
+ } else {
+ errorString = "Base DN is empty string";
+ }
+
+ String binddn = request.getParameter("binddn");
+
+ if (binddn != null && binddn.length() > 0) {
+ cs.putString("internaldb.ldapauth.bindDN", binddn);
+ } else {
+ errorString = "Bind DN is empty string";
+ }
+
+ String database = request.getParameter("database");
+
+ if (database != null && database.length() > 0) {
+ cs.putString("internaldb.database", database);
+ } else {
+ errorString = "Database is empty string";
+ }
+
+ String bindpwd = request.getParameter("__bindpwd");
+ IConfigStore psStore = null;
+
+ if (bindpwd != null && bindpwd.length() > 0) {
+ String passwordFile = null;
+
+ try {
+ passwordFile = cs.getString("passwordFile");
+ psStore = CMS.createFileConfigStore(passwordFile);
+ } catch (Exception e) {
+ CMS.debug("ConfigDatabaseServlet update: " + e.toString());
+ return;
+ }
+ psStore.putString("internaldb", bindpwd);
+ } else {
+ errorString = "Bind password is empty string";
+ }
+
+ cs.putString("preop.configDatabase.modified", "true");
+ if (errorString.equals("")) {
+ try {
+ psStore.commit(false);
+ cs.commit(false);
+ } catch (Exception e) {
+ CMS.debug("ConfigDatabaseServlet update: " + e.toString());
+ }
+ }
+
+ context.put("hostname", hostname);
+ context.put("portStr", portStr);
+ context.put("basedn", basedn);
+ context.put("binddn", binddn);
+ context.put("bindpwd", bindpwd);
+ context.put("database", database);
+ context.put("displayStr", "loaded");
+ context.put("errorString", errorString);
+ }
+
+ public Template getTemplate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ try {
+ return Velocity.getTemplate("admin/console/config/config_db.vm");
+ } catch (Exception e) {}
+ return null;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java
new file mode 100644
index 000000000..caee8c1d4
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMLoginPanel.java
@@ -0,0 +1,318 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+import javax.servlet.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.property.*;
+import com.netscape.cmsutil.crypto.*;
+import java.util.*;
+import java.io.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.pkcs11.*;
+import org.mozilla.jss.util.Password;
+import org.mozilla.jss.util.PasswordCallback;
+import org.mozilla.jss.util.IncorrectPasswordException;
+import com.netscape.cmsutil.password.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class ConfigHSMLoginPanel extends WizardPanelBase {
+ private CryptoManager mCryptoManager = null;
+ private String mPwdFilePath = "";
+
+ public ConfigHSMLoginPanel() {}
+
+ public void init(ServletConfig config, int panelno) throws ServletException {
+ try {
+ mCryptoManager = CryptoManager.getInstance();
+ mPwdFilePath = CMS.getConfigStore().getString(
+ "passwordFile");
+ } catch (Exception e) {
+ CMS.debug("ConfigHSMLoginPanel: " + e.toString());
+ }
+ setPanelNo(panelno);
+ setName("ConfigHSMLogin");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id) throws ServletException {
+ try {
+ mCryptoManager = CryptoManager.getInstance();
+ mPwdFilePath = CMS.getConfigStore().getString(
+ "passwordFile");
+ } catch (Exception e) {
+ CMS.debug("ConfigHSMLoginPanel: " + e.toString());
+ }
+ setPanelNo(panelno);
+ setName("ConfigHSMLogin");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ }
+
+ public boolean isPanelDone() {
+ return true;
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ public boolean isLoopbackPanel() {
+ return true;
+ }
+
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ CMS.debug("ConfigHSMLoginPanel: in display()");
+ context.put("title", "Security Module Login");
+
+ // get token selected to be logged in
+ String tokName = null;
+ try {
+ tokName = HttpInput.getTokenName(request, "SecToken");
+ } catch (IOException e) {
+ }
+
+ if (tokName != null) {
+ CMS.debug("ConfigHSMLoginPanel: selected token name= " + tokName);
+ } else {
+ CMS.debug("ConfigHSMLoginPanel: missing SecToken name");
+ context.put("error", "noTokenName");
+ context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
+ return;
+ }
+ CryptoToken token = null;
+
+ try {
+ token = mCryptoManager.getTokenByName(tokName);
+ } catch (Exception e) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: getTokenByName() failed: "
+ + e.toString());
+ context.put("error", "tokenNotFound:" + tokName);
+ context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
+ return;
+ }
+ // first see if password in password file, try to login
+ PlainPasswordReader pr = new PlainPasswordReader();
+
+ try {
+ pr.init(mPwdFilePath);
+ } catch (Exception e) {
+ // is ok to not have it
+ CMS.debug("ConfigHSMLoginPanel: passwrd file path: " + e.toString());
+ }
+ CMS.debug("ConfigHSMLoginPanel: checking if passwd in cache");
+ String tokPwd = pr.getPassword("hardware-"+tokName);
+
+ boolean loggedIn = false;
+
+ if (tokPwd == null) {
+ CMS.debug("ConfigHSMLoginPanel: passwd not in cache");
+ } else {
+ loggedIn = loginToken(token, tokPwd, context);
+ }
+
+ if (!loggedIn) {
+ context.put("status", "display");
+ }
+ context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
+ context.put("SecToken", tokName);
+ }
+
+ // if logged in successfully, returns true
+ private boolean loginToken(CryptoToken token, String tokPwd, Context context) {
+ boolean rv = true;
+ Password password = null;
+
+ password = new Password(tokPwd.toCharArray());
+
+ if (password != null) {
+ try {
+ if (token.passwordIsInitialized()) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():token password is initialized");
+ if (!token.isLoggedIn()) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():Token is not logged in, try it");
+ token.login(password);
+ context.put("status", "justLoggedIn");
+ } else {
+ CMS.debug(
+ "ConfigHSMLoginPanel:Token has already logged on");
+ context.put("status", "alreadyLoggedIn");
+ }
+ } else {
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():Token password not initialized");
+ context.put("status", "tokenPasswordNotInitialized");
+ rv = false;
+ }
+
+ } catch (IncorrectPasswordException e) {
+ context.put("status", "incorrectPassword");
+ context.put("errorString", e.toString());
+ CMS.debug("ConfigHSMLoginPanel: loginToken():" + e.toString());
+ rv = false;
+ } catch (Exception e) {
+ CMS.debug("ConfigHSMLoginPanel: loginToken():" + e.toString());
+ context.put("errorString", e.toString());
+ rv = false;
+ }
+ } else { // no password in password file, get from user
+ CMS.debug(
+ "ConfigHSMLoginPanel: loginToken():no password in cache, getting from user");
+ rv = false;
+ }
+ return rv;
+ }
+
+ // XXX how do you do this?
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ Descriptor choiceDesc = new Descriptor(IDescriptor.CHOICE, "", "", null); /* no default parameters */
+
+ set.add(
+ "choice", choiceDesc);
+
+ return set;
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ IConfigStore cs = CMS.getConfigStore();
+ String select = "";
+ try {
+ select = cs.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+
+// if (select.equals("clone"))
+ // return;
+
+ CMS.debug("ConfigHSMLoginPanel: in update()");
+
+ String uTokName = null;
+ String uPasswd = null;
+ try {
+ uTokName = HttpInput.getTokenName(request, "uTokName");
+ uPasswd = HttpInput.getPassword(request, "__uPasswd");
+ } catch (Exception e) {
+ }
+
+ if (uPasswd == null) {
+ CMS.debug("ConfigHSMLoginPanel: password not found");
+ context.put("error", "no password");
+ context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
+ context.put("updateStatus", "no password");
+ return;
+ } else {
+ CMS.debug("ConfigHSMLoginPanel: got password");
+
+ CryptoToken token = null;
+
+ try {
+ token = mCryptoManager.getTokenByName(uTokName);
+ } catch (Exception e) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: getTokenByName() failed: "
+ + e.toString());
+ context.put("error", "tokenNotFound:" + uTokName);
+ }
+
+ try {
+ if (loginToken(token, uPasswd, context) == false) {
+ CMS.debug(
+ "ConfigHSMLoginPanel:loginToken failed for "
+ + uTokName);
+ context.put("error", "tokenLoginFailed");
+ context.put("updateStatus", "login failed");
+ context.put("panel",
+ "admin/console/config/config_hsmloginpanel.vm");
+ return;
+ }
+ CMS.debug(
+ "ConfigHSMLoginPanel: update(): just logged in successfully");
+ PlainPasswordWriter pw = new PlainPasswordWriter();
+
+ pw.init(mPwdFilePath);
+ pw.putPassword("hardware-"+uTokName, uPasswd);
+ pw.commit();
+
+ } catch (FileNotFoundException e) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: update(): Exception caught: "
+ + e.toString() + " writing to "+ mPwdFilePath);
+ CMS.debug(
+ "ConfigHSMLoginPanel: update(): password not written to cache");
+ System.err.println("Exception caught: " + e.toString());
+ context.put("error", "Exception:" + e.toString());
+ } catch (Exception e) {
+ CMS.debug(
+ "ConfigHSMLoginPanel: update(): Exception caught: "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ context.put("error", "Exception:" + e.toString());
+ }
+
+ } // found password
+
+ context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
+ context.put("status", "update");
+ context.put("error", "");
+ context.put("updateStatus", "success");
+
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Security Module Login");
+ context.put("panel", "admin/console/config/config_hsmloginpanel.vm");
+ }
+}
+
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java
new file mode 100644
index 000000000..536dfe770
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigHSMServlet.java
@@ -0,0 +1,287 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+import javax.servlet.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.cmsutil.crypto.*;
+import java.util.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.pkcs11.*;
+
+
+public class ConfigHSMServlet extends ConfigBaseServlet {
+ private CryptoManager mCryptoManager = null;
+ private Vector mSupportedModules = null;
+ private Vector mOtherModules = null;
+ private String mDefaultTok = null;
+ private Hashtable mCurrModTable = new Hashtable();
+
+ public void init(ServletConfig config) throws ServletException {
+ super.init(config);
+ }
+
+ public void loadCurrModTable() {
+ try {
+ // getting existing modules
+ mCryptoManager = CryptoManager.getInstance();
+ Enumeration modules = mCryptoManager.getModules();
+
+ while (modules.hasMoreElements()) {
+ PK11Module mod = (PK11Module) modules.nextElement();
+
+ CMS.debug("ConfigHSMServlet: got module " + mod.getName());
+ mCurrModTable.put(mod.getName(), mod);
+ } // while
+ } catch (Exception e) {
+ CMS.debug(
+ "ConfigHSMServlet: Exception caught in loadCurrModTable: "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+ }
+
+ /*
+ * Modules not listed as supported modules
+ */
+ public void loadOtherModules() {
+ Enumeration m = mCurrModTable.elements();
+
+ mOtherModules = new Vector();
+ while (m.hasMoreElements()) {
+ PK11Module mod = (PK11Module) m.nextElement();
+ Enumeration s = mSupportedModules.elements();
+ boolean found = false;
+
+ while (s.hasMoreElements()) {
+ Module sm = (Module) s.nextElement();
+
+ if (mod.getName().equals(sm.getCommonName())) {
+ found = true;
+ break;
+ } else {
+ found = false;
+ }
+ }// while
+ if (!found) {
+ // unsupported, use common name as user friendly name
+ Module module = new Module(mod.getName(), mod.getName());
+
+ loadModTokens(module, mod);
+ module.setFound(true);
+ mOtherModules.addElement((Object) module);
+ break;
+ }
+ }// while
+ }
+
+ /*
+ * find all tokens belonging to a module and load the Module
+ */
+ public void loadModTokens(Module module, PK11Module mod) {
+ Enumeration tokens = mod.getTokens();
+
+ while (tokens.hasMoreElements()) {
+ try {
+ CryptoToken token = (CryptoToken) tokens.nextElement();
+
+ CMS.debug("ConfigHSMServlet: token nick name=" + token.getName());
+ CMS.debug(
+ "ConfigHSMServlet: token logged in?"
+ + token.isLoggedIn());
+ CMS.debug(
+ "ConfigHSMServlet: token is present?"
+ + token.isPresent());
+ if (!token.getName().equals("Internal Crypto Services Token")) {
+ module.addToken(token);
+ } else {
+ CMS.debug(
+ "ConfigHSMServlet: token " + token.getName()
+ + " not to be added");
+ }
+
+ } catch (TokenException ex) {
+ CMS.debug("ConfigHSMServlet:" + ex.toString());
+ }
+ }
+ }
+
+ /*
+ * Modules unsupported by the system will not be included
+ */
+ public void loadSupportedModules() {
+
+ // getting supported security modules
+ // a Vectgor of Modules
+ mSupportedModules = new Vector();
+ // read from conf store all supported modules
+ try {
+ int count = CMS.getConfigStore().getInteger(
+ "preop.configModules.count");
+
+ CMS.debug("ConfigHSMServlet: supported modules count= " + count);
+ for (int i = 0; i < count; i++) {
+ String cn = CMS.getConfigStore().getString(
+ "preop.configModules.module" + i + ".commonName");
+ String pn = CMS.getConfigStore().getString(
+ "preop.configModules.module" + i + ".userFriendlyName");
+ String img = CMS.getConfigStore().getString(
+ "preop.configModules.module" + i + ".imagePath");
+
+ if ((cn == null) || (cn.equals(""))) {
+ break;
+ }
+
+ CMS.debug("ConfigHSMServlet: got from config module: " + cn);
+ // create a Module object
+ Module module = new Module(cn, pn, img);
+
+ if (mCurrModTable.containsKey(cn)) {
+ CMS.debug("ConfigHSMServlet: module found: " + cn);
+ module.setFound(true);
+ // add token info to module vector
+ PK11Module m = (PK11Module) mCurrModTable.get(cn);
+
+ loadModTokens(module, m);
+ }
+
+ CMS.debug("ConfigHSMServlet: adding module " + cn);
+ // add module to set
+ if (!mSupportedModules.contains(module)) {
+ mSupportedModules.addElement((Object) module);
+ }
+ }// for
+
+ } catch (Exception e) {
+ CMS.debug(
+ "ConfigHSMServlet: Exception caught in loadSupportedModules(): "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+ }
+
+ public boolean isDisplayMode(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String choice = request.getParameter("choice");
+
+ if (choice == null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isPanelModified(IConfigStore cs) {
+ String modified = "";
+
+ try {
+ modified = cs.getString("preop.configModules.modified", "");
+ } catch (Exception e) {
+ return false;
+ }
+
+ if (modified.equals("true")) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("ConfigHSMServlet: in display()");
+
+ loadCurrModTable();
+ loadSupportedModules();
+ loadOtherModules();
+ // getting default token selection
+ try {
+ mDefaultTok = CMS.getConfigStore().getString(
+ "preop.configModules.defaultTok",
+ "Internal Key Storage Token");
+ } catch (Exception e) {
+ CMS.debug("ConfigHSMServlet: Exception caught: " + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+ if (mSupportedModules == null) {
+ CMS.debug("ConfigHSMServlet: mSupportedModules not loaded");
+ } else {
+ CMS.debug("ConfigHSMServlet: mSupportedModules loaded");
+ }
+
+ context.put("status", "display");
+ context.put("oms", mOtherModules);
+ context.put("sms", mSupportedModules);
+ context.put("defTok", mDefaultTok);
+ }
+
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ CMS.debug("ConfigHSMServlet: in update()");
+
+ if (mSupportedModules == null) {
+ CMS.debug("ConfigHSMServlet: mSupportedModules not loaded");
+ } else {
+ CMS.debug("ConfigHSMServlet: mSupportedModules loaded");
+ }
+
+ String select = request.getParameter("choice");
+
+ if (select == null) {
+ CMS.debug("ConfigHSMServlet: choice not found");
+ // throw new IOException("choice not found");
+ }
+
+ try {
+ CMS.debug("ConfigHSMServlet: choice =" + select);
+ cs.putString("preop.configModules.defaultTok", select);
+ cs.commit(false);
+ } catch (Exception e) {
+ CMS.debug("ConfigHSMServlet: Exception caught: " + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+ context.put("status", "update");
+ context.put("error", "");
+
+ }
+
+ public Template getTemplate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ try {
+ return Velocity.getTemplate("admin/console/config/config_hsm.vm");
+ } catch (Exception e) {}
+ return null;
+ }
+}
+
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java
new file mode 100644
index 000000000..892d24584
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigImportCertServlet.java
@@ -0,0 +1,46 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+
+public class ConfigImportCertServlet extends BaseServlet {
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ Template template = null;
+
+ try {
+ context.put("name", "Velocity Test");
+ template = Velocity.getTemplate(
+ "admin/console/config/config_importcert.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java
new file mode 100644
index 000000000..b22178b48
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigJoinServlet.java
@@ -0,0 +1,185 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.cmsutil.crypto.*;
+
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+
+import java.util.*;
+import java.io.*;
+
+import java.security.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.KeyPairGenerator;
+
+
+public class ConfigJoinServlet extends ConfigBaseServlet {
+
+ public boolean isDisplayMode(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String cert = request.getParameter("cert");
+
+ if (cert == null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isPanelModified() {
+ IConfigStore config = CMS.getConfigStore();
+
+ String cert = null;
+
+ try {
+ cert = config.getString("preop.join.cert", null);
+ } catch (EBaseException e) {}
+ if (cert == null || cert.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ /**
+ * Displays panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ IConfigStore config = CMS.getConfigStore();
+
+ try {
+ String pubKeyModulus = config.getString(
+ "preop.keysize.pubKeyModulus");
+ String pubKeyPublicExponent = config.getString(
+ "preop.keysize.pubKeyPublicExponent");
+ String dn = config.getString("preop.name.dn");
+ String priKeyID = config.getString("preop.keysize.priKeyID");
+ String pkcs10 = CryptoUtil.getPKCS10FromKey(dn,
+ CryptoUtil.string2byte(pubKeyModulus),
+ CryptoUtil.string2byte(pubKeyPublicExponent),
+ CryptoUtil.string2byte(priKeyID));
+ context.put("certreq", pkcs10);
+ } catch (Exception e) {}
+
+ String select = "auto";
+ boolean select_manual = true;
+
+ if (isPanelModified()) {
+ try {
+ select = config.getString("preop.join.select", null);
+ } catch (EBaseException e) {
+ CMS.debug( "ConfigJoinServlet::display() - "
+ + "Exception="+e.toString() );
+ return;
+ }
+ if (select.equals("auto")) {
+
+ /* automated enrollment */
+ select_manual = false;
+ } else {
+ try {
+
+ /* manual enrollment */
+ String cert = config.getString("preop.join.cert", "");
+
+ context.put("cert", cert);
+ } catch (EBaseException e) {}
+ }
+ } else {
+ context.put("cert", "");
+ }
+ if (select_manual) {
+ context.put("check_manual", "checked");
+ context.put("check_auto", "");
+ } else {
+ context.put("check_manual", "");
+ context.put("check_auto", "checked");
+ }
+ context.put("status", "display");
+ }
+
+ /**
+ * Updates panel.
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("JoinServlet: update");
+ IConfigStore config = CMS.getConfigStore();
+ String select = request.getParameter("choice");
+
+ try {
+ if (select.equals("manual")) {
+
+ /* manual enrollment */
+ CMS.debug("JoinServlet: manual");
+ String certchain = request.getParameter("cert");
+
+ config.putString("preop.join.cert", certchain);
+ } else if (select.equals("auto")) {
+ CMS.debug("JoinServlet: auto");
+
+ /* automated enrollment */
+ String url = request.getParameter("url");
+ String uid = request.getParameter("uid");
+ String pwd = request.getParameter("__pwd");
+
+ config.putString("preop.join.url", url);
+ config.putString("preop.join.uid", uid);
+ config.putString("preop.join.pwd", pwd);
+
+ /* XXX - submit request to the CA, and import it automatically */
+ config.putString(
+ "preop.join.cert", ""); /* store the chain */
+ }
+ config.putString("preop.join.select", select);
+ config.commit(false);
+ } catch (Exception e) {}
+ }
+
+ public Template getTemplate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ Template template = null;
+
+ try {
+ template = Velocity.getTemplate(
+ "admin/console/config/config_join.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java
new file mode 100644
index 000000000..e07ea3c3b
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ConfigRootCAServlet.java
@@ -0,0 +1,135 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.profile.*;
+
+import java.util.*;
+
+
+public class ConfigRootCAServlet extends ConfigBaseServlet {
+
+ public boolean isDisplayMode(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String profile = request.getParameter("profile");
+
+ if (profile == null) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isPanelModified() {
+ IConfigStore config = CMS.getConfigStore();
+
+ String profile = null;
+
+ try {
+ profile = config.getString("preop.hierarchy.profile", null);
+ } catch (EBaseException e) {}
+ if (profile == null || profile.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ public Vector getProfiles() {
+ IConfigStore config = CMS.getConfigStore();
+ String instancePath = "";
+
+ try {
+ instancePath = config.getString("instanceRoot");
+ } catch (EBaseException e) {}
+ String p[] = { "caCert.profile" };
+ Vector profiles = new Vector();
+
+ for (int i = 0; i < p.length; i++) {
+ try {
+ profiles.addElement(
+ new CertInfoProfile(instancePath + "/conf/" + p[i]));
+ } catch (Exception e) {}
+ }
+ return profiles;
+ }
+
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ IConfigStore config = CMS.getConfigStore();
+ String profile = null;
+
+ if (isPanelModified()) {
+ try {
+ profile = config.getString("preop.hierarchy.profile", null);
+ } catch (EBaseException e) {}
+ }
+ if (profile == null) {
+ profile = "caCert.profile";
+ }
+ Vector profiles = getProfiles();
+
+ context.put("status", "display");
+ context.put("profiles", profiles);
+ context.put("selected_profile_id", profile);
+ }
+
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ String profile = request.getParameter("profile");
+ IConfigStore config = CMS.getConfigStore();
+
+ config.putString("preop.hierarchy.profile", profile);
+ try {
+ config.commit(false);
+ } catch (Exception e) {}
+ context.put("status", "update");
+ context.put("error", "");
+ Vector profiles = getProfiles();
+
+ context.put("profiles", profiles);
+ context.put("selected_profile_id", profile);
+ }
+
+ public Template getTemplate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ Template template = null;
+
+ try {
+ template = Velocity.getTemplate(
+ "admin/console/config/config_rootca.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java
new file mode 100644
index 000000000..a99969880
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/CreateSubsystemPanel.java
@@ -0,0 +1,302 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import org.mozilla.jss.crypto.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.cmsutil.crypto.*;
+import java.net.*;
+import java.io.*;
+import java.util.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.xml.sax.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class CreateSubsystemPanel extends WizardPanelBase {
+
+ public CreateSubsystemPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Subsystem Selection");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Subsystem Type");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.subsystem.select", "");
+ cs.putString("subsystem.select", "");
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.subsystem.select", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Subsystem Type");
+ IConfigStore config = CMS.getConfigStore();
+ String session_id = request.getParameter("session_id");
+ if (session_id != null) {
+ CMS.debug("CreateSubsystemPanel setting session id.");
+ CMS.setConfigSDSessionId(session_id);
+ }
+
+ String errorString = "";
+ String url = "";
+
+ if (isPanelDone()) {
+ try {
+ String s = config.getString("preop.subsystem.select");
+
+ if (s.equals("new")) {
+ context.put("check_newsubsystem", "checked");
+ context.put("check_clonesubsystem", "");
+ } else if (s.equals("clone")) {
+ context.put("check_newsubsystem", "");
+ context.put("check_clonesubsystem", "checked");
+ }
+ context.put("subsystemName",
+ config.getString("preop.subsystem.name"));
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("check_newsubsystem", "checked");
+ context.put("check_clonesubsystem", "");
+ try {
+ context.put("subsystemName",
+ config.getString("preop.system.fullname"));
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ }
+
+ String cstype = "";
+
+ try {
+ cstype = config.getString("cs.type", "");
+ context.put("cstype", cstype);
+ context.put("wizardname", config.getString("preop.wizard.name"));
+ context.put("systemname", config.getString("preop.system.name"));
+ context.put("fullsystemname", config.getString("preop.system.fullname"));
+ context.put("machineName", config.getString("machineName"));
+ context.put("http_port", CMS.getEENonSSLPort());
+ context.put("https_agent_port", CMS.getAgentPort());
+ context.put("https_ee_port", CMS.getEESSLPort());
+ context.put("https_admin_port", CMS.getAdminPort());
+ } catch (EBaseException e) {
+ }
+
+ Vector v = getUrlListFromSecurityDomain(config, cstype, "SecurePort" );
+
+ 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.master.list", list.toString());
+ config.commit(false);
+ } catch (Exception e) {
+ errorString = "Internal error, cs.type is missing from CS.cfg";
+ }
+
+ if (list.length()==0)
+ context.put("disableClone", "true");
+
+ context.put("panel", "admin/console/config/createsubsystempanel.vm");
+ context.put("errorString", errorString);
+ context.put("urls", v);
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ String errorString = "";
+ IConfigStore config = CMS.getConfigStore();
+ String select = HttpInput.getID(request, "choice");
+
+ if (select == null) {
+ CMS.debug("CreateSubsystemPanel: choice not found");
+ context.put("updateStatus", "failure");
+ throw new IOException("choice not found");
+ }
+
+ config.putString("preop.subsystem.name",
+ HttpInput.getName(request, "subsystemName"));
+ if (select.equals("newsubsystem")) {
+ config.putString("preop.subsystem.select", "new");
+ config.putString("subsystem.select", "New");
+ } else if (select.equals("clonesubsystem")) {
+ String cstype = "";
+ try {
+ cstype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ }
+
+ cstype = toLowerCaseSubsystemType(cstype);
+
+ config.putString("preop.subsystem.select", "clone");
+ config.putString("subsystem.select", "Clone");
+
+ String lists = "";
+ try {
+ lists = config.getString("preop.cert.list", "");
+ } catch (Exception ee) {
+ }
+
+ StringTokenizer t = new StringTokenizer(lists, ",");
+ while (t.hasMoreTokens()) {
+ String tag = t.nextToken();
+ if (tag.equals("sslserver"))
+ config.putBoolean(PCERT_PREFIX+tag+".enable", true);
+ else
+ config.putBoolean(PCERT_PREFIX+tag+".enable", false);
+ }
+
+ // get the master CA
+ String index = request.getParameter("urls");
+ String url = "";
+
+ try {
+ int x = Integer.parseInt(index);
+ String list = config.getString("preop.master.list", "");
+ StringTokenizer tokenizer = new StringTokenizer(list, ",");
+ int counter = 0;
+
+ while (tokenizer.hasMoreTokens()) {
+ url = tokenizer.nextToken();
+ if (counter == x) {
+ break;
+ }
+ counter++;
+ }
+ } catch (Exception e) {
+ }
+
+ url = url.substring(url.indexOf("http"));
+
+ URL u = new URL(url);
+ String host = u.getHost();
+ int https_ee_port = u.getPort();
+
+ String https_admin_port = getSecurityDomainAdminPort( config,
+ host,
+ String.valueOf(https_ee_port),
+ cstype );
+
+ config.putString("preop.master.hostname", host);
+ config.putInteger("preop.master.httpsport", https_ee_port);
+ config.putString("preop.master.httpsadminport", https_admin_port);
+
+ ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
+ if (cstype.equals("ca")) {
+ updateCertChainUsingSecureEEPort( config, "clone", host, https_ee_port,
+ true, context, certApprovalCallback );
+ }
+
+ getTokenInfo(config, cstype, host, https_ee_port, true, context,
+ certApprovalCallback);
+ } else {
+ CMS.debug("CreateSubsystemPanel: invalid choice " + select);
+ errorString = "Invalid choice";
+ context.put("updateStatus", "failure");
+ throw new IOException("invalid choice " + select);
+ }
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+
+ context.put("errorString", errorString);
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Subsystem Type");
+ context.put("panel", "admin/console/config/createsubsystempanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java
new file mode 100644
index 000000000..bdd0b0d08
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabasePanel.java
@@ -0,0 +1,1507 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.ca.*;
+import java.io.*;
+import java.util.*;
+import com.netscape.cmsutil.ldap.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class DatabasePanel extends WizardPanelBase {
+
+ private static final String HOST = "localhost";
+ private static final String CLONE_HOST="Enter FQDN here";
+ private static final String PORT = "389";
+ private static final String BASEDN = "o=netscapeCertificateServer";
+ private static final String BINDDN = "cn=Directory Manager";
+ private static final String DATABASE = "csRoot";
+ private static final String MASTER_AGREEMENT = "masteragreement-";
+ private static final String CLONE_AGREEMENT = "cloneagreement-";
+
+ private WizardServlet mServlet = null;
+
+ public DatabasePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Internal Database");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Internal Database");
+ setId(id);
+ mServlet = servlet;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putBoolean("preop.Database.done", false);
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ boolean s = cs.getBoolean("preop.Database.done",
+ false);
+
+ if (s != true) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+ Descriptor hostDesc = new Descriptor(IDescriptor.STRING, null, null,
+ "Host name");
+
+ set.add("hostname", hostDesc);
+
+ Descriptor portDesc = new Descriptor(IDescriptor.INTEGER, null, null,
+ "Port");
+
+ set.add("portStr", portDesc);
+
+ Descriptor basednDesc = new Descriptor(IDescriptor.STRING, null, null,
+ "Base DN");
+
+ set.add("basedn", basednDesc);
+
+ Descriptor binddnDesc = new Descriptor(IDescriptor.STRING, null, null,
+ "Bind DN");
+
+ set.add("binddn", binddnDesc);
+
+ Descriptor bindpwdDesc = new Descriptor(IDescriptor.PASSWORD, null, null,
+ "Bind Password");
+
+ set.add("bindpwd", bindpwdDesc);
+
+ Descriptor databaseDesc = new Descriptor(IDescriptor.STRING, null, null,
+ "Database");
+
+ set.add("database", databaseDesc);
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("DatabasePanel: display()");
+ context.put("title", "Internal Database");
+ context.put("firsttime", "false");
+ IConfigStore cs = CMS.getConfigStore();
+ String hostname = null;
+ String portStr = null;
+ String basedn = null;
+ String binddn = null;
+ String bindpwd = "";
+ String database = null;
+ String errorString = "";
+ String secure = "false";
+ String cloneStartTLS = "false";
+ try {
+ String s = cs.getString("preop.database.removeData");
+ } catch (Exception e) {
+ context.put("firsttime", "true");
+ }
+
+ String select = "";
+ try {
+ select = cs.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+
+ if (isPanelDone()) {
+ try {
+ hostname = cs.getString("internaldb.ldapconn.host", "");
+ portStr = cs.getString("internaldb.ldapconn.port", "");
+ basedn = cs.getString("internaldb.basedn", "");
+ binddn = cs.getString("internaldb.ldapauth.bindDN", "");
+ database = cs.getString("internaldb.database", "");
+ secure = cs.getString("internaldb.ldapconn.secureConn", "");
+ cloneStartTLS = cs.getString("internaldb.ldapconn.cloneStartTLS", "");
+ errorString = cs.getString("preop.database.errorString", "");
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel display: " + e.toString());
+ }
+ } else if (select.equals("clone")) {
+ hostname = CLONE_HOST;
+ portStr = PORT;
+ try {
+ basedn = cs.getString("internaldb.basedn", "");
+ } catch (Exception e) {
+ CMS.debug( "DatabasePanel::display() - "
+ + "Exception="+e.toString() );
+ return;
+ }
+ binddn = BINDDN;
+ database = basedn.substring(basedn.lastIndexOf('=')+1);
+ CMS.debug("Clone: database=" + database);
+ } else {
+ hostname = HOST;
+ portStr = PORT;
+ String instanceId = "";
+ String machineName = "";
+
+ try {
+ instanceId = cs.getString("instanceId", "");
+ machineName = cs.getString("machineName", "");
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel display: " + e.toString());
+ }
+ String suffix = "dc=" + machineName + "-" + instanceId;
+
+ boolean multipleEnable = false;
+ try {
+ multipleEnable = cs.getBoolean(
+ "internaldb.multipleSuffix.enable", false);
+ } catch (Exception e) {
+ }
+
+
+ if (multipleEnable)
+ basedn = "ou=" + instanceId + "," + suffix;
+ else
+ basedn = suffix;
+ binddn = BINDDN;
+ database = machineName + "-" + instanceId;
+ }
+
+ context.put("clone", select);
+ context.put("hostname", hostname);
+ context.put("portStr", portStr);
+ context.put("basedn", basedn);
+ context.put("binddn", binddn);
+ context.put("bindpwd", bindpwd);
+ context.put("database", database);
+ context.put("secureConn", (secure.equals("true")? "on":"off"));
+ context.put("cloneStartTLS", (cloneStartTLS.equals("true")? "on":"off"));
+ context.put("panel", "admin/console/config/databasepanel.vm");
+ context.put("errorString", errorString);
+ }
+
+ public void initParams(HttpServletRequest request, Context context)
+ throws IOException
+ {
+ IConfigStore config = CMS.getConfigStore();
+ String select = "";
+ try {
+ select = config.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+ context.put("clone", select);
+ context.put("hostname", request.getParameter("host"));
+ context.put("portStr", request.getParameter("port"));
+ context.put("basedn", request.getParameter("basedn"));
+ context.put("binddn", request.getParameter("binddn"));
+ context.put("bindpwd", request.getParameter("__bindpwd"));
+ context.put("database", request.getParameter("database"));
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+
+ IConfigStore cs = CMS.getConfigStore();
+ context.put("firsttime", "false");
+ try {
+ String s = cs.getString("preop.database.removeData");
+ } catch (Exception e) {
+ context.put("firsttime", "true");
+ }
+
+ String hostname = HttpInput.getHostname(request, "host");
+ context.put("hostname", hostname);
+
+ String portStr = HttpInput.getPortNumber(request, "port");
+ context.put("portStr", portStr);
+
+ String basedn = HttpInput.getDN(request, "basedn");
+ context.put("basedn", basedn);
+
+ String binddn = HttpInput.getDN(request, "binddn");
+ context.put("binddn", binddn);
+
+ String database = HttpInput.getLdapDatabase(request, "database");
+ context.put("database", database);
+
+ String bindpwd = HttpInput.getPassword(request, "__bindpwd");
+ context.put("bindpwd", bindpwd);
+
+ String secure = HttpInput.getCheckbox(request, "secureConn");
+ context.put("secureConn", secure);
+
+ String cloneStartTLS = HttpInput.getCheckbox(request, "cloneStartTLS");
+ context.put("cloneStartTLS", cloneStartTLS);
+
+ String select = "";
+ try {
+ select = cs.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+
+ if (select.equals("clone")) {
+ String masterhost = "";
+ String masterport = "";
+ String masterbasedn = "";
+ try {
+ masterhost = cs.getString("preop.internaldb.master.hostname", "");
+ masterport = cs.getString("preop.internaldb.master.port", "");
+ masterbasedn = cs.getString("preop.internaldb.master.basedn", "");
+ } catch (Exception e) {
+ }
+
+ //get the real host name
+ String realhostname = "";
+ if (hostname.equals("localhost")) {
+ try {
+ realhostname = cs.getString("machineName", "");
+ } catch (Exception ee) {
+ }
+ }
+ if (masterhost.equals(realhostname) && masterport.equals(portStr)) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Master and clone must not share the same internal database");
+ }
+
+ if (!masterbasedn.equals(basedn)) {
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Master and clone should have the same base DN");
+ }
+ }
+
+ if (hostname == null || hostname.length() == 0) {
+ cs.putString("preop.database.errorString", "Host is empty string");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Host is empty string");
+ }
+
+ if (portStr != null && portStr.length() > 0) {
+ int port = -1;
+
+ try {
+ port = Integer.parseInt(portStr);
+ } catch (Exception e) {
+ cs.putString("preop.database.errorString", "Port is invalid");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Port is invalid");
+ }
+ } else {
+ cs.putString("preop.database.errorString", "Port is empty string");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Port is empty string");
+ }
+
+ if (basedn == null || basedn.length() == 0) {
+ cs.putString("preop.database.errorString", "Base DN is empty string");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Base DN is empty string");
+ }
+
+ if (binddn == null || binddn.length() == 0) {
+ cs.putString("preop.database.errorString", "Bind DN is empty string");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Bind DN is empty string");
+ }
+
+ if (database == null || database.length() == 0) {
+ cs.putString("preop.database.errorString",
+ "Database is empty string");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Database is empty string");
+ }
+
+ if (bindpwd == null || bindpwd.length() == 0) {
+ cs.putString("preop.database.errorString",
+ "Bind password is empty string");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Bind password is empty string");
+ }
+
+ context.put("errorString", "");
+ cs.putString("preop.database.errorString", "");
+ }
+
+ private LDAPConnection getLocalLDAPConn(Context context, String secure)
+ throws IOException
+ {
+ IConfigStore cs = CMS.getConfigStore();
+
+ String host = "";
+ String port = "";
+ String pwd = "";
+ String binddn = "";
+ String security = "";
+
+ try {
+ host = cs.getString("internaldb.ldapconn.host");
+ port = cs.getString("internaldb.ldapconn.port");
+ binddn = cs.getString("internaldb.ldapauth.bindDN");
+ pwd = (String) context.get("bindpwd");
+ security = cs.getString("internaldb.ldapconn.secureConn");
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel populateDB: " + e.toString());
+ throw new IOException(
+ "Failed to retrieve LDAP information from CS.cfg.");
+ }
+
+ int p = -1;
+
+ try {
+ p = Integer.parseInt(port);
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel populateDB: " + e.toString());
+ throw new IOException("Port is not valid");
+ }
+
+ LDAPConnection conn = null;
+ if (security.equals("true")) {
+ CMS.debug("DatabasePanel populateDB: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ } else {
+ CMS.debug("DatabasePanel populateDB: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
+ }
+
+ CMS.debug("DatabasePanel connecting to " + host + ":" + p);
+ try {
+ conn.connect(host, p, binddn, pwd);
+ } catch (LDAPException e) {
+ CMS.debug("DatabasePanel populateDB: " + e.toString());
+ throw new IOException("Failed to connect to the internal database.");
+ }
+
+ return conn;
+ }
+
+ private boolean deleteDir(File dir)
+ {
+ if (dir.isDirectory()) {
+ String[] children = dir.list();
+ for (int i=0; i<children.length; i++) {
+ boolean success = deleteDir(new File(dir, children[i]));
+ if (!success) {
+ return false;
+ }
+ }
+ }
+
+ // The directory is now empty so delete it
+ return dir.delete();
+ }
+
+ private void cleanupDB(LDAPConnection conn, String baseDN, String database)
+ {
+ String[] entries = {};
+ String filter = "objectclass=*";
+ LDAPSearchConstraints cons = null;
+ String[] attrs = null;
+ String dn="";
+ try {
+ CMS.debug("Deleting baseDN: " + baseDN);
+ LDAPSearchResults res = conn.search(baseDN, LDAPConnection.SCOPE_BASE, filter,
+ attrs, true, cons);
+ if (res != null)
+ deleteEntries(res, conn, baseDN, entries);
+ }
+ catch (LDAPException e) {}
+
+ try {
+ dn="cn=mapping tree, cn=config";
+ filter = "nsslapd-backend=" + database;
+ LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
+ attrs, true, cons);
+ if (res != null) {
+ while (res.hasMoreElements()) {
+ dn = res.next().getDN();
+ filter = "objectclass=*";
+ LDAPSearchResults res2 = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
+ attrs, true, cons);
+ if (res2 != null)
+ deleteEntries(res2, conn, dn, entries);
+ }
+ }
+ }
+ catch (LDAPException e) {}
+
+ try {
+ dn = "cn=" + database + ",cn=ldbm database, cn=plugins, cn=config";
+ LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
+ attrs, true, cons);
+ if (res != null) {
+ deleteEntries(res, conn, dn, entries);
+ String dbdir = getInstanceDir(conn) + "/db/" + database;
+ if (dbdir != null) {
+ CMS.debug(" Deleting dbdir " + dbdir);
+ boolean success = deleteDir(new File(dbdir));
+ if (!success) {
+ CMS.debug("Unable to delete database directory " + dbdir);
+ }
+ }
+ }
+ }
+ catch (LDAPException e) {}
+ }
+
+
+ private void populateDB(HttpServletRequest request, Context context, String secure)
+ throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+
+ String baseDN = "";
+ String database = "";
+ String dn = "";
+
+ try {
+ baseDN = cs.getString("internaldb.basedn");
+ database = cs.getString("internaldb.database", "");
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel populateDB: " + e.toString());
+ throw new IOException(
+ "Failed to retrieve LDAP information from CS.cfg.");
+ }
+
+ String remove = HttpInput.getID(request, "removeData");
+ LDAPConnection conn = getLocalLDAPConn(context, secure);
+
+ // check that the database and baseDN do not exist
+
+ boolean foundBaseDN = false;
+ boolean foundDatabase = false;
+ try {
+ LDAPEntry entry = conn.read(baseDN);
+ if (entry != null) foundBaseDN = true;
+ } catch (LDAPException e) {
+ switch( e.getLDAPResultCode() ) {
+ case LDAPException.NO_SUCH_OBJECT:
+ break;
+ default:
+ CMS.debug("DatabasePanel update: LDAPException " + e.toString());
+ throw new IOException("Failed to create the database");
+ }
+ }
+
+ try {
+ dn = "cn=" + database + ",cn=ldbm database, cn=plugins, cn=config";
+ LDAPEntry entry = conn.read(dn);
+ if (entry != null) foundDatabase = true;
+ } catch (LDAPException e) {
+ switch( e.getLDAPResultCode() ) {
+ case LDAPException.NO_SUCH_OBJECT:
+ break;
+ default:
+ CMS.debug("DatabasePanel update: LDAPException " + e.toString());
+ throw new IOException("Failed to create the database");
+ }
+ }
+ try {
+ dn = "cn=\"" + baseDN + "\",cn=mapping tree, cn=config";
+ LDAPEntry entry = conn.read(dn);
+ if (entry != null) foundDatabase = true;
+ } catch (LDAPException e) {
+ switch( e.getLDAPResultCode() ) {
+ case LDAPException.NO_SUCH_OBJECT:
+ break;
+ default:
+ CMS.debug("DatabasePanel update: LDAPException " + e.toString());
+ throw new IOException("Failed to create the database");
+ }
+ }
+
+ if (foundDatabase) {
+ CMS.debug("DatabasePanel update: This database has already been used.");
+ if (remove == null) {
+ throw new IOException("This database has already been used. Select the checkbox below to remove all data and reuse this database");
+ }
+ else {
+ CMS.debug("DatabasePanel update: Deleting existing DB and reusing base DN");
+ cleanupDB(conn, baseDN, database);
+ foundBaseDN = false;
+ foundDatabase = false;
+ }
+ }
+
+ if (foundBaseDN) {
+ CMS.debug("DatabasePanel update: This base DN has already been used.");
+ if (remove == null) {
+ throw new IOException("This base DN ("+baseDN+") has already been used. Select the checkbox below to remove all data and reuse this base DN");
+ }
+ else {
+ CMS.debug("DatabasePanel update: Deleting existing DB and reusing base DN");
+ cleanupDB(conn, baseDN, database);
+ foundBaseDN = false;
+ foundDatabase = false;
+ }
+ }
+
+ // create database
+ try {
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ String oc[] = { "top", "extensibleObject", "nsBackendInstance"};
+ attrs.add(new LDAPAttribute("objectClass", oc));
+ attrs.add(new LDAPAttribute("cn", database));
+ attrs.add(new LDAPAttribute("nsslapd-suffix", baseDN));
+ dn = "cn=" + database + ",cn=ldbm database, cn=plugins, cn=config";
+ LDAPEntry entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ } catch (Exception e) {
+ CMS.debug("Warning: database creation error - " + e.toString());
+ throw new IOException("Failed to create the database.");
+ }
+
+ try {
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ String oc2[] = { "top", "extensibleObject", "nsMappingTree"};
+ attrs.add(new LDAPAttribute("objectClass", oc2));
+ attrs.add(new LDAPAttribute("cn", baseDN));
+ attrs.add(new LDAPAttribute("nsslapd-backend", database));
+ attrs.add(new LDAPAttribute("nsslapd-state", "Backend"));
+ dn = "cn=\"" + baseDN + "\",cn=mapping tree, cn=config";
+ LDAPEntry entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ } catch (Exception e) {
+ CMS.debug("Warning: database mapping tree creation error - " + e.toString());
+ throw new IOException("Failed to create the database.");
+ }
+
+ try {
+ // create base dn
+ CMS.debug("Creating base DN: " + baseDN);
+ String dns3[] = LDAPDN.explodeDN(baseDN, false);
+ StringTokenizer st = new StringTokenizer(dns3[0], "=");
+ String n = st.nextToken();
+ String v = st.nextToken();
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ String oc3[] = { "top", "domain"};
+ if (n.equals("o")) {
+ oc3[1] = "organization";
+ } else if (n.equals("ou")) {
+ oc3[1] = "organizationalUnit";
+ }
+ attrs.add(new LDAPAttribute("objectClass", oc3));
+ attrs.add(new LDAPAttribute(n, v));
+ LDAPEntry entry = new LDAPEntry(baseDN, attrs);
+ conn.add(entry);
+ } catch (Exception e) {
+ CMS.debug("Warning: suffix creation error - " + e.toString());
+ throw new IOException("Failed to create the base DN: "+baseDN);
+ }
+
+ // check to see if the base dn exists
+ CMS.debug("DatabasePanel checking existing " + baseDN);
+
+ try {
+ LDAPEntry entry = conn.read(baseDN);
+
+ if (entry != null) {
+ foundBaseDN = true;
+ }
+ } catch (LDAPException e) {}
+ boolean createBaseDN = true;
+
+ boolean testing = false;
+ try {
+ testing = cs.getBoolean("internaldb.multipleSuffix.enable", false);
+ } catch (Exception e) {}
+
+ if (!foundBaseDN) {
+ if (!testing) {
+ context.put("errorString", "Base DN was not found. Please make sure to create the suffix in the internal database.");
+ throw new IOException("Base DN not found");
+ }
+
+ if (createBaseDN) {
+ // only auto create if it is an ou entry
+ String dns1[] = LDAPDN.explodeDN(baseDN, false);
+
+ if (dns1 == null) {
+ throw new IOException("Invalid base DN");
+ }
+ if (!dns1[0].startsWith("ou")) {
+ throw new IOException(
+ "Failed to find base DN, and failed to create non ou entry.");
+ }
+ String dns2[] = LDAPDN.explodeDN(baseDN, true);
+ // support only one level creation - create new entry
+ // right under the suffix
+ LDAPAttributeSet attrs = new LDAPAttributeSet();
+ String oc[] = { "top", "organizationalUnit"};
+
+ attrs.add(new LDAPAttribute("objectClass", oc));
+ attrs.add(new LDAPAttribute("ou", dns2[0]));
+ LDAPEntry entry = new LDAPEntry(baseDN, attrs);
+
+ try {
+ conn.add(entry);
+ foundBaseDN = true;
+ CMS.debug("DatabasePanel added " + baseDN);
+ } catch (LDAPException e) {
+ throw new IOException("Failed to create " + baseDN);
+ }
+ }
+ }
+ if (!foundBaseDN) {
+ throw new IOException("Failed to find base DN");
+ }
+
+ String select = "";
+ try {
+ select = cs.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+
+ if (select.equals("clone")) {
+ // if this is clone, add index before replication
+ // don't put in the schema or bad things will happen
+
+ importLDIFS("preop.internaldb.ldif", conn);
+ importLDIFS("preop.internaldb.index_ldif", conn);
+ } else {
+ // data will be replicated from the master to the clone
+ // so clone does not need the data
+ //
+
+ importLDIFS("preop.internaldb.schema.ldif", conn);
+ importLDIFS("preop.internaldb.ldif", conn);
+ importLDIFS("preop.internaldb.data_ldif", conn);
+ importLDIFS("preop.internaldb.index_ldif", conn);
+ }
+
+ try {
+ conn.disconnect();
+ } catch (LDAPException e) {}
+ }
+
+ private void importLDIFS(String param, LDAPConnection conn) throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ String v = null;
+
+ CMS.debug("DatabasePanel populateDB param=" + param);
+ try {
+ v = cs.getString(param);
+ } catch (EBaseException e) {
+ CMS.debug("DatabasePanel populateDB: " + e.toString());
+ throw new IOException("Cant find ldif files.");
+ }
+
+ StringTokenizer tokenizer = new StringTokenizer(v, ",");
+ String baseDN = null;
+ String database = null;
+
+ try {
+ baseDN = cs.getString("internaldb.basedn");
+ } catch (EBaseException e) {
+ throw new IOException("internaldb.basedn is missing.");
+ }
+
+ try {
+ database = cs.getString("internaldb.database");
+ CMS.debug("DatabasePanel update: database=" + database);
+ } catch (EBaseException e) {
+ CMS.debug(
+ "DatabasePanel update: Failed to get database name. Exception: "
+ + e.toString());
+ database = "userRoot";
+ }
+
+ String instancePath = null;
+
+ try {
+ instancePath = cs.getString("instanceRoot");
+ } catch (EBaseException e) {
+ throw new IOException("instanceRoot is missing");
+ }
+
+ String instanceId = null;
+
+ try {
+ instanceId = cs.getString("instanceId");
+ } catch (EBaseException e) {
+ throw new IOException("instanceId is missing");
+ }
+
+
+ String configDir = instancePath + File.separator + "conf";
+
+ while (tokenizer.hasMoreTokens()) {
+ String token = tokenizer.nextToken().trim();
+ int index = token.lastIndexOf("/");
+ String name = token;
+
+ if (index != -1) {
+ name = token.substring(index + 1);
+ }
+
+ CMS.debug("DatabasePanel importLDIFS: ldif file = " + token);
+ String filename = configDir + File.separator + name;
+
+ CMS.debug("DatabasePanel importLDIFS: ldif file copy to " + filename);
+ PrintStream ps = null;
+ BufferedReader in = null;
+
+ try {
+ in = new BufferedReader(new FileReader(token));
+ ps = new PrintStream(new FileOutputStream(filename, false));
+ while (in.ready()) {
+ String s = in.readLine();
+ int n = s.indexOf("{");
+
+ if (n == -1) {
+ ps.println(s);
+ } else {
+ boolean endOfline = false;
+
+ while (n != -1) {
+ ps.print(s.substring(0, n));
+ int n1 = s.indexOf("}");
+ String tok = s.substring(n + 1, n1);
+
+ if (tok.equals("instanceId")) {
+ ps.print(instanceId);
+ } else if (tok.equals("rootSuffix")) {
+ ps.print(baseDN);
+ } else if (tok.equals("database")) {
+ ps.print(database);
+ }
+ if ((s.length() + 1) == n1) {
+ endOfline = true;
+ break;
+ }
+ s = s.substring(n1 + 1);
+ n = s.indexOf("{");
+ }
+
+ if (!endOfline) {
+ ps.println(s);
+ }
+ }
+ }
+ in.close();
+ ps.close();
+ } catch (Exception e) {
+ CMS.debug("DBSubsystem popuateDB: " + e.toString());
+ throw new IOException(
+ "Problem of copying ldif file: " + filename);
+ }
+
+ LDAPUtil.importLDIF(conn, filename);
+ }
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ boolean hasErr = false;
+
+ boolean firsttime = false;
+ context.put("firsttime", "false");
+ try {
+ String v = cs.getString("preop.database.removeData");
+ } catch (Exception e) {
+ context.put("firsttime", "true");
+ firsttime = true;
+ }
+
+ String hostname1 = "";
+ String portStr1 = "";
+ String database1 = "";
+ String basedn1 = "";
+
+ try {
+ hostname1 = cs.getString("internaldb.ldapconn.host", "");
+ portStr1 = cs.getString("internaldb.ldapconn.port", "");
+ database1 = cs.getString("internaldb.database", "");
+ basedn1 = cs.getString("internaldb.basedn", "");
+ } catch (Exception e) {
+ }
+
+ String hostname2 = HttpInput.getHostname(request, "host");
+ String portStr2 = HttpInput.getPortNumber(request, "port");
+ String database2 = HttpInput.getLdapDatabase(request, "database");
+ String basedn2 = HttpInput.getDN(request, "basedn");
+
+ cs.putString("internaldb.ldapconn.host", hostname2);
+ cs.putString("internaldb.ldapconn.port", portStr2);
+ cs.putString("internaldb.basedn", basedn2);
+ String binddn = HttpInput.getDN(request, "binddn");
+ cs.putString("internaldb.ldapauth.bindDN", binddn);
+ cs.putString("internaldb.database", database2);
+ String secure = HttpInput.getCheckbox(request, "secureConn");
+ cs.putString("internaldb.ldapconn.secureConn", (secure.equals("on")?"true":"false"));
+ String cloneStartTLS = HttpInput.getCheckbox(request, "cloneStartTLS");
+ cs.putString("internaldb.ldapconn.cloneStartTLS", (cloneStartTLS.equals("on")?"true":"false"));
+
+ String remove = HttpInput.getID(request, "removeData");
+ if (isPanelDone() && (remove == null || remove.equals(""))) {
+ /* if user submits the same data, they just want to skip
+ to the next panel, no database population is required. */
+ if (hostname1.equals(hostname2) &&
+ portStr1.equals(portStr2) &&
+ database1.equals(database2)) {
+ context.put("updateStatus", "success");
+ return;
+ }
+ }
+
+ mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
+
+
+ try {
+ populateDB(request, context, (secure.equals("on")?"true":"false"));
+ } catch (IOException e) {
+ CMS.debug("DatabasePanel update: populateDB Exception: "+e.toString());
+ context.put("updateStatus", "failure");
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel update: populateDB Exception: "+e.toString());
+ context.put("errorString", e.toString());
+ cs.putString("preop.database.errorString", e.toString());
+ context.put("updateStatus", "failure");
+ throw new IOException(e.toString());
+ }
+
+ String bindpwd = HttpInput.getPassword(request, "__bindpwd");
+
+ /* BZ 430745 create password for replication manager */
+ String replicationpwd = Integer.toString(new Random().nextInt());
+
+ IConfigStore psStore = null;
+ String passwordFile = null;
+
+ try {
+ passwordFile = cs.getString("passwordFile");
+ psStore = CMS.createFileConfigStore(passwordFile);
+ } catch (Exception e) {
+ CMS.debug("ConfigDatabaseServlet update: " + e.toString());
+ context.put("updateStatus", "failure");
+ throw new IOException( e.toString() );
+ }
+ psStore.putString("internaldb", bindpwd);
+ psStore.putString("replicationdb", replicationpwd);
+ cs.putString("preop.internaldb.replicationpwd" , replicationpwd);
+ cs.putString("preop.database.removeData", "false");
+
+ try {
+ cs.commit(false);
+ psStore.commit(false);
+ CMS.reinit(IDBSubsystem.SUB_ID);
+ String type = cs.getString("cs.type", "");
+ if (type.equals("CA"))
+ CMS.reinit(ICertificateAuthority.ID);
+ CMS.reinit(IAuthSubsystem.ID);
+ CMS.reinit(IAuthzSubsystem.ID);
+ CMS.reinit(IUGSubsystem.ID);
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel update: " + e.toString());
+ context.put("errorString", e.toString());
+ cs.putString("preop.database.errorString", e.toString());
+ context.put("updateStatus", "failure");
+ throw new IOException(e.toString());
+ }
+
+ String select = "";
+ try {
+ select = cs.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+
+ // always populate the index the last
+ try {
+ CMS.debug("Populating local indexes");
+ LDAPConnection conn = getLocalLDAPConn(context,
+ (secure.equals("on")?"true":"false"));
+ importLDIFS("preop.internaldb.post_ldif", conn);
+
+ /* For vlvtask, we need to check if the task has
+ been completed or not. Presence of nsTaskExitCode means task is complete
+ */
+ String wait_dn = cs.getString("preop.internaldb.wait_dn", "");
+ if (!wait_dn.equals("")) {
+ int i = 0;
+ LDAPEntry task = null;
+ boolean taskComplete = false;
+ CMS.debug("Checking wait_dn " + wait_dn);
+ do {
+ Thread.sleep(1000);
+ try {
+ task = conn.read(wait_dn, (String[])null);
+ if (task != null) {
+ LDAPAttribute attr = task.getAttribute("nsTaskExitCode");
+ if (attr != null) {
+ taskComplete = true;
+ String val = (String) attr.getStringValues().nextElement();
+ if (val.compareTo("0") != 0) {
+ CMS.debug("Error in populating local indexes: nsTaskExitCode=" + val);
+ }
+ }
+ }
+ } catch (LDAPException le) {
+ CMS.debug("Still checking wait_dn '" + wait_dn + "' (" + le.toString() + ")");
+ } catch (Exception e) {
+ CMS.debug("Still checking wait_dn '" + wait_dn + "' (" + e.toString() + ").");
+ }
+ } while ((!taskComplete) && (i < 20));
+ if (i < 20) {
+ CMS.debug("Done checking wait_dn " + wait_dn);
+ } else {
+ CMS.debug("Done checking wait_dn " + wait_dn + " due to timeout.");
+ }
+ }
+
+ conn.disconnect();
+ CMS.debug("Done populating local indexes");
+ } catch (Exception e) {
+ CMS.debug("Populating index failure - " + e);
+ }
+
+ // setup replication after indexes have been created
+ if (select.equals("clone")) {
+ CMS.debug("Start setting up replication.");
+ setupReplication(request, context, (secure.equals("on")?"true":"false"), (cloneStartTLS.equals("on")?"true":"false"));
+ CMS.debug("Finish setting up replication.");
+
+ try {
+ CMS.reinit(IDBSubsystem.SUB_ID);
+ String type = cs.getString("cs.type", "");
+ if (type.equals("CA"))
+ CMS.reinit(ICertificateAuthority.ID);
+ CMS.reinit(IAuthSubsystem.ID);
+ CMS.reinit(IAuthzSubsystem.ID);
+ CMS.reinit(IUGSubsystem.ID);
+ } catch (Exception e) {
+ }
+ }
+
+
+ if (hasErr == false) {
+ cs.putBoolean("preop.Database.done", true);
+ try {
+ cs.commit(false);
+ } catch (EBaseException e) {
+ CMS.debug(
+ "DatabasePanel: update() Exception caught at config commit: "
+ + e.toString());
+ }
+ }
+ context.put("updateStatus", "success");
+ }
+
+ private void setupReplication(HttpServletRequest request,
+ Context context, String secure, String cloneStartTLS) throws IOException {
+ String bindpwd = HttpInput.getPassword(request, "__bindpwd");
+ IConfigStore cs = CMS.getConfigStore();
+
+ String cstype = "";
+ String machinename = "";
+ String instanceId = "";
+ try {
+ cstype = cs.getString("cs.type");
+ cstype = toLowerCaseSubsystemType(cstype);
+ machinename = cs.getString("machineName", "");
+ instanceId = cs.getString("instanceId", "");
+ } catch (Exception e) {
+ }
+
+
+ //setup replication agreement
+ String masterAgreementName = "masterAgreement1-"+machinename+"-"+instanceId;
+ cs.putString("internaldb.replication.master", masterAgreementName);
+ String cloneAgreementName = "cloneAgreement1-"+machinename+"-"+instanceId;
+ cs.putString("internaldb.replication.consumer", cloneAgreementName);
+
+ try {
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+
+ String master1_hostname = "";
+ int master1_port = -1;
+ String master1_binddn = "";
+ String master1_bindpwd = "";
+ String master1_replicationpwd = "";
+
+ try {
+ master1_hostname = cs.getString("preop.internaldb.master.hostname", "");
+ master1_port = cs.getInteger("preop.internaldb.master.port", -1);
+ master1_binddn = cs.getString("preop.internaldb.master.binddn", "");
+ master1_bindpwd = cs.getString("preop.internaldb.master.bindpwd", "");
+ master1_replicationpwd = cs.getString("preop.internaldb.master.replicationpwd", "");
+ } catch (Exception e) {
+ }
+
+ String master2_hostname = "";
+ int master2_port = -1;
+ String master2_binddn = "";
+ String master2_bindpwd = "";
+ String master2_replicationpwd = "";
+
+ try {
+ master2_hostname = cs.getString("internaldb.ldapconn.host", "");
+ master2_port = cs.getInteger("internaldb.ldapconn.port", -1);
+ master2_binddn = cs.getString("internaldb.ldapauth.bindDN", "");
+ master2_bindpwd = bindpwd;
+ master2_replicationpwd = cs.getString("preop.internaldb.replicationpwd", "");
+ } catch (Exception e) {
+ }
+
+ LDAPConnection conn1 = null;
+ LDAPConnection conn2 = null;
+ if (secure.equals("true")) {
+ CMS.debug("DatabasePanel setupReplication: creating secure (SSL) connections for internal ldap");
+ conn1 = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ conn2 = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ } else {
+ CMS.debug("DatabasePanel setupreplication: creating non-secure (non-SSL) connections for internal ldap");
+ conn1 = new LDAPConnection();
+ conn2 = new LDAPConnection();
+ }
+
+ String basedn = "";
+ try {
+ basedn = cs.getString("internaldb.basedn");
+ } catch (Exception e) {
+ }
+
+ try {
+ conn1.connect(master1_hostname, master1_port, master1_binddn,
+ master1_bindpwd);
+ conn2.connect(master2_hostname, master2_port, master2_binddn,
+ master2_bindpwd);
+ String suffix = cs.getString("internaldb.basedn", "");
+
+ String replicadn = "cn=replica,cn=\""+suffix+"\",cn=mapping tree,cn=config";
+ CMS.debug("DatabasePanel setupReplication: replicadn="+replicadn);
+
+ String masterBindUser = "Replication Manager " + masterAgreementName;
+ String cloneBindUser = "Replication Manager " + cloneAgreementName;
+
+ createReplicationManager(conn1, masterBindUser, master1_replicationpwd);
+ createReplicationManager(conn2, cloneBindUser, master2_replicationpwd);
+
+ String dir1 = getInstanceDir(conn1);
+ createChangeLog(conn1, dir1 + "/changelogs");
+
+ String dir2 = getInstanceDir(conn2);
+ createChangeLog(conn2, dir2 + "/changelogs");
+
+ int replicaId = cs.getInteger("dbs.beginReplicaNumber", 1);
+
+ replicaId = enableReplication(replicadn, conn1, masterBindUser, basedn, replicaId);
+ replicaId = enableReplication(replicadn, conn2, cloneBindUser, basedn, replicaId);
+ cs.putString("dbs.beginReplicaNumber", Integer.toString(replicaId));
+
+ CMS.debug("DatabasePanel setupReplication: Finished enabling replication");
+
+ createReplicationAgreement(replicadn, conn1, masterAgreementName,
+ master2_hostname, master2_port, master2_replicationpwd, basedn, cloneBindUser, secure, cloneStartTLS);
+
+ createReplicationAgreement(replicadn, conn2, cloneAgreementName,
+ master1_hostname, master1_port, master1_replicationpwd, basedn, masterBindUser, secure, cloneStartTLS);
+
+ // initialize consumer
+ initializeConsumer(replicadn, conn1, masterAgreementName);
+
+ while (! replicationDone(replicadn, conn1, masterAgreementName)) {
+ CMS.debug("DatabasePanel setupReplication: Waiting for replication to complete");
+ Thread.sleep(1000);
+ }
+
+ String status = replicationStatus(replicadn, conn1, masterAgreementName);
+ if (!status.startsWith("0 ")) {
+ CMS.debug("DatabasePanel setupReplication: consumer initialization failed. " +
+ status);
+ throw new IOException("consumer initialization failed. " + status);
+ }
+
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel setupReplication: "+e.toString());
+ throw new IOException("Failed to setup the replication for cloning.");
+ }
+ }
+
+ /**
+ * 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", "Database");
+ context.put("panel", "admin/console/config/databasepanel.vm");
+ }
+
+ private boolean isAgreementExist(String replicadn, LDAPConnection conn,
+ String name) {
+ String dn = "cn="+name+","+replicadn;
+ String filter = "(cn="+name+")";
+ String[] attrs = {"cn"};
+ try {
+ LDAPSearchResults results = conn.search(dn, LDAPv3.SCOPE_SUB,
+ filter, attrs, false);
+ while (results.hasMoreElements())
+ return true;
+ } catch (LDAPException e) {
+ return false;
+ }
+
+ return false;
+ }
+
+ private void createReplicationManager(LDAPConnection conn, String bindUser, String pwd)
+ throws LDAPException {
+ LDAPAttributeSet attrs = null;
+ LDAPEntry entry = null;
+ String dn = "cn=" + bindUser + ",cn=config";
+ try {
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "person"));
+ attrs.add(new LDAPAttribute("userpassword", pwd));
+ attrs.add(new LDAPAttribute("cn", bindUser));
+ attrs.add(new LDAPAttribute("sn", "manager"));
+ entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
+ CMS.debug("DatabasePanel createReplicationManager: Replication Manager has already used");
+ try {
+ conn.delete(dn);
+ conn.add(entry);
+ } catch (LDAPException ee) {
+ CMS.debug("DatabasePanel createReplicationManager: "+ee.toString());
+ }
+ return;
+ } else {
+ CMS.debug("DatabasePanel createReplicationManager: Failed to create replication manager. Exception: "+e.toString());
+ throw e;
+ }
+ }
+
+ CMS.debug("DatabasePanel createReplicationManager: Successfully created Replication Manager");
+ }
+
+ private void createChangeLog(LDAPConnection conn, String dir)
+ throws LDAPException {
+ LDAPAttributeSet attrs = null;
+ LDAPEntry entry = null;
+ String dn = "cn=changelog5,cn=config";
+ try {
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "extensibleObject"));
+ attrs.add(new LDAPAttribute("cn", "changelog5"));
+ attrs.add(new LDAPAttribute("nsslapd-changelogdir", dir));
+ entry = new LDAPEntry("cn=changelog5,cn=config", attrs);
+ conn.add(entry);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
+ CMS.debug("DatabasePanel createChangeLog: Changelog entry has already used");
+/* leave it, dont delete it because it will have operation error
+ try {
+ conn.delete(dn);
+ conn.add(entry);
+ } catch (LDAPException ee) {
+ CMS.debug("DatabasePanel createChangeLog: "+ee.toString());
+ }
+*/
+ return;
+ } else {
+ CMS.debug("DatabasePanel createChangeLog: Failed to create changelog entry. Exception: "+e.toString());
+ throw e;
+ }
+ }
+
+ CMS.debug("DatabasePanel createChangeLog: Successfully create change log entry");
+ }
+
+ private int enableReplication(String replicadn, LDAPConnection conn, String bindUser, String basedn, int id)
+ throws LDAPException {
+ CMS.debug("DatabasePanel enableReplication: replicadn: "+replicadn);
+ LDAPAttributeSet attrs = null;
+ LDAPEntry entry = null;
+ try {
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "nsDS5Replica"));
+ attrs.add(new LDAPAttribute("objectclass", "extensibleobject"));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaRoot", basedn));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaType", "3"));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaBindDN",
+ "cn=" + bindUser + ",cn=config"));
+ attrs.add(new LDAPAttribute("cn", "replica"));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaId", Integer.toString(id)));
+ attrs.add(new LDAPAttribute("nsds5flags", "1"));
+ entry = new LDAPEntry(replicadn, attrs);
+ conn.add(entry);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
+ /* BZ 470918 -we cant just add the new dn. We need to do a replace instead
+ * until the DS code is fixed */
+ CMS.debug("DatabasePanel enableReplication: "+replicadn+" has already been used");
+
+ try {
+ entry = conn.read(replicadn);
+ LDAPAttribute attr = entry.getAttribute("nsDS5ReplicaBindDN");
+ attr.addValue( "cn=" + bindUser + ",cn=config");
+ LDAPModification mod = new LDAPModification(LDAPModification.REPLACE, attr);
+ conn.modify(replicadn, mod);
+ } catch (LDAPException ee) {
+ CMS.debug("DatabasePanel enableReplication: Failed to modify "
+ +replicadn+" entry. Exception: "+e.toString());
+ }
+ return id;
+ } else {
+ CMS.debug("DatabasePanel enableReplication: Failed to create "+replicadn+" entry. Exception: "+e.toString());
+ return id;
+ }
+ }
+
+ CMS.debug("DatabasePanel enableReplication: Successfully create "+replicadn+" entry.");
+ return id + 1;
+ }
+
+ private void createReplicationAgreement(String replicadn,
+ LDAPConnection conn, String name, String replicahost, int replicaport,
+ String replicapwd, String basedn, String bindUser, String secure, String cloneStartTLS) throws LDAPException {
+ String dn = "cn="+name+","+replicadn;
+ CMS.debug("DatabasePanel createReplicationAgreement: dn: "+dn);
+ LDAPEntry entry = null;
+ LDAPAttributeSet attrs = null;
+ try {
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass",
+ "nsds5replicationagreement"));
+ attrs.add(new LDAPAttribute("cn", name));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaRoot", basedn));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaHost", replicahost));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaPort", ""+replicaport));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaBindDN",
+ "cn=" + bindUser + ",cn=config"));
+ attrs.add(new LDAPAttribute("nsDS5ReplicaBindMethod", "Simple"));
+ attrs.add(new LDAPAttribute("nsds5replicacredentials", replicapwd));
+
+ if (secure.equals("true")) {
+ attrs.add(new LDAPAttribute("nsDS5ReplicaTransportInfo", "SSL"));
+ } else if (cloneStartTLS.equals("true")) {
+ attrs.add(new LDAPAttribute("nsDS5ReplicaTransportInfo", "TLS"));
+ }
+
+ CMS.debug("About to set description attr to " + name);
+ attrs.add(new LDAPAttribute("description",name));
+
+ entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
+ CMS.debug("DatabasePanel createReplicationAgreement: "+dn+" has already used");
+ try {
+ conn.delete(dn);
+ } catch (LDAPException ee) {
+ CMS.debug("DatabasePanel createReplicationAgreement: "+ee.toString());
+ throw ee;
+ }
+
+ try {
+ conn.add(entry);
+ } catch (LDAPException ee) {
+ CMS.debug("DatabasePanel createReplicationAgreement: "+ee.toString());
+ throw ee;
+ }
+ } else {
+ CMS.debug("DatabasePanel createReplicationAgreement: Failed to create "+dn+" entry. Exception: "+e.toString());
+ throw e;
+ }
+ }
+
+ CMS.debug("DatabasePanel createReplicationAgreement: Successfully create replication agreement "+name);
+ }
+
+ private void initializeConsumer(String replicadn, LDAPConnection conn,
+ String name) {
+ String dn = "cn="+name+","+replicadn;
+ CMS.debug("DatabasePanel initializeConsumer: initializeConsumer dn: "+dn);
+ CMS.debug("DatabasePanel initializeConsumer: initializeConsumer host: "+conn.getHost() + " port: " + conn.getPort());
+ try {
+ LDAPAttribute attr = new LDAPAttribute("nsds5beginreplicarefresh",
+ "start");
+ LDAPModification mod = new LDAPModification(
+ LDAPModification.REPLACE, attr);
+ CMS.debug("DatabasePanel initializeConsumer: start modifying");
+ conn.modify(dn, mod);
+ CMS.debug("DatabasePanel initializeConsumer: Finish modification.");
+ } catch (LDAPException e) {
+ CMS.debug("DatabasePanel initializeConsumer: Failed to modify "+dn+" entry. Exception: "+e.toString());
+ return;
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel initializeConsumer: exception " + e);
+ }
+
+ try {
+ CMS.debug("DatabasePanel initializeConsumer: thread sleeping for 5 seconds.");
+ Thread.sleep(5000);
+ CMS.debug("DatabasePanel initializeConsumer: finish sleeping.");
+ } catch (InterruptedException ee) {
+ CMS.debug("DatabasePanel initializeConsumer: exception: "+ee.toString());
+ }
+
+ CMS.debug("DatabasePanel initializeConsumer: Successfully initialize consumer");
+ }
+
+ private boolean replicationDone(String replicadn, LDAPConnection conn, String name)
+ throws IOException {
+ String dn = "cn="+name+","+replicadn;
+ String filter = "(objectclass=*)";
+ String[] attrs = {"nsds5beginreplicarefresh"};
+
+ CMS.debug("DatabasePanel replicationDone: dn: "+dn);
+ try {
+ LDAPSearchResults results = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
+ attrs, true);
+
+ int count = results.getCount();
+ if (count < 1) {
+ throw new IOException("Replication entry not found");
+ }
+
+ LDAPEntry entry = results.next();
+ LDAPAttribute refresh = entry.getAttribute("nsds5beginreplicarefresh");
+ if (refresh == null) {
+ return true;
+ }
+ return false;
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel replicationDone: exception " + e);
+ throw new IOException("Exception in replicationDone: " + e);
+ }
+ }
+
+ private String replicationStatus(String replicadn, LDAPConnection conn, String name)
+ throws IOException {
+ String dn = "cn="+name+","+replicadn;
+ String filter = "(objectclass=*)";
+ String[] attrs = {"nsds5replicalastinitstatus"};
+ String status = null;
+
+ CMS.debug("DatabasePanel replicationStatus: dn: "+dn);
+ try {
+ LDAPSearchResults results = conn.search(dn, LDAPConnection.SCOPE_BASE, filter,
+ attrs, false);
+
+ int count = results.getCount();
+ if (count < 1) {
+ throw new IOException("Replication entry not found");
+ }
+
+ LDAPEntry entry = results.next();
+ LDAPAttribute attr = entry.getAttribute("nsds5replicalastinitstatus");
+ if (attr != null) {
+ Enumeration valsInAttr = attr.getStringValues();
+ if (valsInAttr.hasMoreElements()) {
+ return (String)valsInAttr.nextElement();
+ } else {
+ throw new IOException("No value returned for nsds5replicalastinitstatus");
+ }
+ } else {
+ throw new IOException("nsDS5ReplicaLastInitStatus is null.");
+ }
+ } catch (Exception e) {
+ CMS.debug("DatabasePanel replicationStatus: exception " + e);
+ throw new IOException("Exception in replicationStatus: " + e);
+ }
+ }
+
+ private String getInstanceDir(LDAPConnection conn) {
+ String instancedir="";
+ try {
+ String filter = "(objectclass=*)";
+ String[] attrs = {"nsslapd-directory"};
+ LDAPSearchResults results = conn.search("cn=config,cn=ldbm database,cn=plugins,cn=config", LDAPv3.SCOPE_SUB,
+ filter, attrs, false);
+
+ while (results.hasMoreElements()) {
+ LDAPEntry entry = results.next();
+ String dn = entry.getDN();
+ CMS.debug("DatabasePanel getInstanceDir: DN for storing nsslapd-directory: "+dn);
+ LDAPAttributeSet entryAttrs = entry.getAttributeSet();
+ Enumeration attrsInSet = entryAttrs.getAttributes();
+ while (attrsInSet.hasMoreElements()) {
+ LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.nextElement();
+ String attrName = nextAttr.getName();
+ CMS.debug("DatabasePanel getInstanceDir: attribute name: "+attrName);
+ Enumeration valsInAttr = nextAttr.getStringValues();
+ while ( valsInAttr.hasMoreElements() ) {
+ String nextValue = (String)valsInAttr.nextElement();
+ if (attrName.equalsIgnoreCase("nsslapd-directory")) {
+ CMS.debug("DatabasePanel getInstanceDir: instanceDir="+nextValue);
+ return nextValue.substring(0,nextValue.lastIndexOf("/db"));
+ }
+ }
+ }
+ }
+ } catch (LDAPException e) {
+ CMS.debug("DatabasePanel getInstanceDir: Error in retrieving the instance directory. Exception: "+e.toString());
+ }
+
+ return instancedir;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java
new file mode 100644
index 000000000..03f8f2f86
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DatabaseServlet.java
@@ -0,0 +1,45 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+
+public class DatabaseServlet extends BaseServlet {
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ Template template = null;
+
+ try {
+ context.put("name", "Velocity Test");
+ template = Velocity.getTemplate("admin/console/config/database.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java
new file mode 100644
index 000000000..cf25ab0e9
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayCertChainPanel.java
@@ -0,0 +1,235 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import org.xml.sax.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.template.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.cmsutil.xml.*;
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import com.netscape.cmsutil.http.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.asn1.*;
+import netscape.security.util.*;
+import netscape.security.x509.X509CertImpl;
+
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.cms.servlet.wizard.*;
+
+public class DisplayCertChainPanel extends WizardPanelBase {
+
+ public DisplayCertChainPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Display Certificate Chain");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Display Certificate Chain");
+ setId(id);
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ public boolean isPanelDone() {
+ return true;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ return set;
+ }
+
+ public void cleanUp() throws IOException {
+ }
+
+ /**
+ * Should we skip this panel for the configuration.
+ */
+ public boolean shouldSkip() {
+ CMS.debug("DisplayCertChainPanel: should skip");
+
+ IConfigStore cs = CMS.getConfigStore();
+ // if we are root, no need to get the certificate chain.
+
+ try {
+ String select = cs.getString("securitydomain.select","");
+ String type = cs.getString("preop.subsystem.select", "");
+ String hierarchy = cs.getString("preop.hierarchy.select", "");
+
+ if (getId().equals("hierarchy") && hierarchy.equals("root"))
+ return true;
+
+ if (select.equals("new")) {
+ return true;
+ }
+
+ if (type.equals("new") && getId().equals("clone"))
+ return true;
+
+ if (type.equals("clone") && getId().equals("ca"))
+ return true;
+ } catch (EBaseException e) {
+ }
+
+ return false;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("DisplayCertChainPanel: display");
+
+ // update session id
+ String session_id = request.getParameter("session_id");
+ if (session_id != null) {
+ CMS.debug("DisplayCertChainPanel setting session id.");
+ CMS.setConfigSDSessionId(session_id);
+ }
+
+ String type = getId();
+
+ IConfigStore cs = CMS.getConfigStore();
+ String certChainConfigName = "preop." + type + ".certchain.size";
+ String certchain_size = "";
+
+ try {
+ certchain_size = cs.getString(certChainConfigName, "");
+ } catch (Exception e) {}
+
+ int size = 0;
+ Vector v = new Vector();
+
+ if (!certchain_size.equals("")) {
+ try {
+ size = Integer.parseInt(certchain_size);
+ } catch (Exception e) {}
+ for (int i = 0; i < size; i++) {
+ certChainConfigName = "preop." + type + ".certchain." + i;
+ try {
+ String c = cs.getString(certChainConfigName, "");
+ byte[] b_c = CryptoUtil.base64Decode(c);
+ CertPrettyPrint pp = new CertPrettyPrint(
+ new X509CertImpl(b_c));
+
+ v.addElement(pp.toString(Locale.getDefault()));
+ } catch (Exception e) {}
+ }
+ }
+
+ if (getId().equals("securitydomain")) {
+ context.put("panelid", "securitydomain");
+ context.put("panelname", "Security Domain Trust Verification");
+ } else {
+ context.put("panelid", "other");
+ context.put("panelname", "Subsystem Trust Verification");
+ }
+ context.put("title", "Display Certificate Chain");
+ context.put("panel", "admin/console/config/displaycertchainpanel.vm");
+ context.put("errorString", "");
+ context.put("certchain", v);
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ importCertChain(getId());
+
+ if (getId().equals("securitydomain")) {
+ int panel = getPanelNo()+1;
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String sd_hostname = cs.getString("securitydomain.host", "");
+ int sd_port = cs.getInteger("securitydomain.httpsadminport", -1);
+ String cs_hostname = cs.getString("machineName", "");
+ int cs_port = cs.getInteger("pkicreate.admin_secure_port", -1);
+ String subsystem = cs.getString("cs.type", "");
+ String urlVal = "https://"+cs_hostname+":"+cs_port+"/"+toLowerCaseSubsystemType(subsystem)+"/admin/console/config/wizard?p="+panel+"&subsystem="+subsystem;
+ String encodedValue = URLEncoder.encode(urlVal, "UTF-8");
+ String sdurl = "https://"+sd_hostname+":"+sd_port+"/ca/admin/ca/securityDomainLogin?url="+encodedValue;
+ response.sendRedirect(sdurl);
+
+ // The user previously specified the CA Security Domain's
+ // SSL Admin port in the "Security Domain Panel";
+ // now retrieve this specified CA Security Domain's
+ // non-SSL EE, SSL Agent, and SSL EE ports:
+ cs.putString( "securitydomain.httpport",
+ getSecurityDomainPort( cs, "UnSecurePort" ) );
+ cs.putString("securitydomain.httpsagentport",
+ getSecurityDomainPort( cs, "SecureAgentPort" ) );
+ cs.putString("securitydomain.httpseeport",
+ getSecurityDomainPort( cs, "SecurePort" ) );
+ } catch (Exception ee) {
+ CMS.debug("DisplayCertChainPanel Exception="+ee.toString());
+ }
+ }
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ /* This should never be called */
+ context.put("title", "Display Certificate Chain");
+ context.put("panel", "admin/console/config/displaycertchainpanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java
new file mode 100644
index 000000000..2c0184f26
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DisplayServlet.java
@@ -0,0 +1,45 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+
+public class DisplayServlet extends BaseServlet {
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ Template template = null;
+
+ try {
+ String tmpl = request.getParameter("t");
+
+ template = Velocity.getTemplate(tmpl);
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java
new file mode 100644
index 000000000..f21a56de9
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DonePanel.java
@@ -0,0 +1,800 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.dbs.crldb.*;
+import com.netscape.certsrv.ocsp.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.cmsutil.util.Cert;
+import com.netscape.cmsutil.util.*;
+import com.netscape.cmsutil.password.*;
+import netscape.security.x509.*;
+import netscape.ldap.*;
+import java.net.*;
+import java.io.*;
+import java.math.*;
+import java.security.cert.*;
+import org.w3c.dom.*;
+import java.util.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class DonePanel extends WizardPanelBase {
+
+ public static final BigInteger BIG_ZERO = new BigInteger("0");
+ public static final Long MINUS_ONE = Long.valueOf(-1);
+ public static final String RESTART_SERVER_AFTER_CONFIGURATION =
+ "restart_server_after_configuration";
+ public static final String PKI_SECURITY_DOMAIN = "pki_security_domain";
+
+ public DonePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Done");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Done");
+ setId(id);
+ }
+
+ public boolean hasSubPanel() {
+ return false;
+ }
+
+ public void cleanUp() throws IOException {
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ private LDAPConnection getLDAPConn(Context context)
+ throws IOException
+ {
+ IConfigStore cs = CMS.getConfigStore();
+
+ String host = "";
+ String port = "";
+ String pwd = null;
+ String binddn = "";
+ String security = "";
+
+ IPasswordStore pwdStore = CMS.getPasswordStore();
+
+ if (pwdStore != null) {
+ CMS.debug("DonePanel: getLDAPConn: password store available");
+ pwd = pwdStore.getPassword("internaldb");
+ }
+
+ if ( pwd == null) {
+ throw new IOException("DonePanel: Failed to obtain password from password store");
+ }
+
+ try {
+ host = cs.getString("internaldb.ldapconn.host");
+ port = cs.getString("internaldb.ldapconn.port");
+ binddn = cs.getString("internaldb.ldapauth.bindDN");
+ security = cs.getString("internaldb.ldapconn.secureConn");
+ } catch (Exception e) {
+ CMS.debug("DonePanel: getLDAPConn" + e.toString());
+ throw new IOException(
+ "Failed to retrieve LDAP information from CS.cfg.");
+ }
+
+ int p = -1;
+
+ try {
+ p = Integer.parseInt(port);
+ } catch (Exception e) {
+ CMS.debug("DonePanel getLDAPConn: " + e.toString());
+ throw new IOException("Port is not valid");
+ }
+
+ LDAPConnection conn = null;
+ if (security.equals("true")) {
+ CMS.debug("DonePanel getLDAPConn: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ } else {
+ CMS.debug("DonePanel getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
+ }
+
+ CMS.debug("DonePanel connecting to " + host + ":" + p);
+ try {
+ conn.connect(host, p, binddn, pwd);
+ } catch (LDAPException e) {
+ CMS.debug("DonePanel getLDAPConn: " + e.toString());
+ throw new IOException("Failed to connect to the internal database.");
+ }
+
+ return conn;
+ }
+
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("DonePanel: display()");
+
+ // update session id
+ String session_id = request.getParameter("session_id");
+ if (session_id != null) {
+ CMS.debug("NamePanel setting session id.");
+ CMS.setConfigSDSessionId(session_id);
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+ String ownport = CMS.getEENonSSLPort();
+ String ownsport = CMS.getEESSLPort();
+ String owneeclientauthsport = CMS.getEEClientAuthSSLPort();
+ String ownhost = CMS.getEESSLHost();
+ String ownagentsport = CMS.getAgentPort();
+ String ownagenthost = CMS.getAgentHost();
+ String ownadminsport = CMS.getAdminPort();
+ String ownadminhost = CMS.getAdminHost();
+ String select = "";
+
+ String type = "";
+ String instanceId = "";
+ String instanceRoot = "";
+ try {
+ type = cs.getString("cs.type", "");
+ instanceId = cs.getString("instanceId");
+ instanceRoot = cs.getString("instanceRoot");
+ select = cs.getString("preop.subsystem.select", "");
+ } catch (Exception e) {}
+
+ String initDaemon = "";
+ if (type.equals("CA")) {
+ initDaemon = "pki-cad";
+ } else if (type.equals("KRA")) {
+ initDaemon = "pki-krad";
+ } else if (type.equals("OCSP")) {
+ initDaemon = "pki-ocspd";
+ } else if (type.equals("TKS")) {
+ initDaemon = "pki-tksd";
+ }
+ String os = System.getProperty( "os.name" );
+ if( os.equalsIgnoreCase( "Linux" ) ) {
+ context.put( "initCommand", "/sbin/service " + initDaemon );
+ context.put( "instanceId", instanceId );
+ } else {
+ /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
+ context.put( "initCommand", "/etc/init.d/" + initDaemon );
+ context.put( "instanceId", instanceId );
+ }
+ context.put("title", "Done");
+ context.put("panel", "admin/console/config/donepanel.vm");
+ context.put("host", ownadminhost);
+ context.put("port", ownadminsport);
+ String subsystemType = toLowerCaseSubsystemType(type);
+ context.put("systemType", subsystemType);
+
+ try {
+ int state = cs.getInteger("cs.state");
+ if (state == 1) {
+ context.put("csstate", "1");
+ return;
+ } else
+ context.put("csstate", "0");
+
+ } catch (Exception e) {
+ }
+
+ String sd_agent_port = "";
+ String sd_admin_port = "";
+ String sd_host = "";
+ String ca_host = "";
+ try {
+ sd_host = cs.getString("securitydomain.host", "");
+ sd_agent_port = cs.getString("securitydomain.httpsagentport", "");
+ sd_admin_port = cs.getString("securitydomain.httpsadminport", "");
+ ca_host = cs.getString("preop.ca.hostname", "");
+ } catch (Exception e) {
+ }
+
+ if (ca_host.equals(""))
+ context.put("externalCA", "true");
+ else
+ context.put("externalCA", "false");
+
+ // update security domain
+ String sdtype = "";
+ String instanceName = "";
+ String subsystemName = "";
+ try {
+ sdtype = cs.getString("securitydomain.select", "");
+ instanceName = cs.getString("instanceId", "");
+ subsystemName = cs.getString("preop.subsystem.name", "");
+ } catch (Exception e) {
+ }
+
+ boolean cloneMaster = false;
+
+ if (select.equals("clone") && type.equalsIgnoreCase("CA") && isSDHostDomainMaster(cs)) {
+ cloneMaster = true;
+ CMS.debug("Cloning a domain master");
+ }
+
+ String s = getSubsystemNodeName(type);
+ if (sdtype.equals("new")) {
+ try {
+ LDAPConnection conn = getLDAPConn(context);
+
+ String basedn = cs.getString("internaldb.basedn");
+ String secdomain = cs.getString("securitydomain.name");
+
+ try {
+ // Create security domain ldap entry
+ String dn = "ou=Security Domain," + basedn;
+ CMS.debug("DonePanel: creating ldap entry : " + dn);
+
+ LDAPEntry entry = null;
+ LDAPAttributeSet attrs = null;
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "pkiSecurityDomain"));
+ if (secdomain.equals("")) {
+ // this should not happen - just in case
+ CMS.debug("DonePanel display(): Security domain is an empty string!");
+ throw new IOException("Security domain is an empty string!");
+ } else {
+ attrs.add(new LDAPAttribute("name", secdomain));
+ }
+ attrs.add(new LDAPAttribute("ou", "Security Domain"));
+ entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ } catch (Exception e) {
+ CMS.debug("Unable to create security domain");
+ throw e;
+ }
+
+ try {
+ // create list containers
+ String clist[] = {"CAList", "OCSPList", "KRAList", "RAList", "TKSList", "TPSList"};
+ for (int i=0; i< clist.length; i++) {
+ LDAPEntry entry = null;
+ LDAPAttributeSet attrs = null;
+ String dn = "cn=" + clist[i] + ",ou=Security Domain," + basedn;
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "pkiSecurityGroup"));
+ attrs.add(new LDAPAttribute("cn", clist[i]));
+ entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ }
+ } catch (Exception e) {
+ CMS.debug("Unable to create security domain list groups" );
+ throw e;
+ }
+
+ try {
+ // Add this host (only CA can create new domain)
+ String cn = ownhost + ":" + ownadminsport;
+ String dn = "cn=" + cn + ",cn=CAList,ou=Security Domain," + basedn;
+ LDAPEntry entry = null;
+ LDAPAttributeSet attrs = null;
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "pkiSubsystem"));
+ attrs.add(new LDAPAttribute("Host", ownhost));
+ attrs.add(new LDAPAttribute("SecurePort", ownsport));
+ attrs.add(new LDAPAttribute("SecureAgentPort",
+ ownagentsport));
+ attrs.add(new LDAPAttribute("SecureAdminPort",
+ ownadminsport));
+ if (owneeclientauthsport != null) {
+ attrs.add(new LDAPAttribute("SecureEEClientAuthPort",
+ owneeclientauthsport));
+ }
+ attrs.add(new LDAPAttribute("UnSecurePort", ownport));
+ attrs.add(new LDAPAttribute("Clone", "FALSE"));
+ attrs.add(new LDAPAttribute("SubsystemName", subsystemName));
+ attrs.add(new LDAPAttribute("cn", cn));
+ attrs.add(new LDAPAttribute("DomainManager", "TRUE"));
+ entry = new LDAPEntry(dn, attrs);
+ conn.add(entry);
+ } catch (Exception e) {
+ CMS.debug("Unable to create host entry in security domain");
+ throw e;
+ }
+ CMS.debug("DonePanel display: finish updating domain info");
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("DonePanel display: "+e.toString());
+ }
+
+ int sd_admin_port_int = -1;
+ try {
+ sd_admin_port_int = Integer.parseInt( sd_admin_port );
+ } catch (Exception e) {
+ }
+
+ try {
+ // Fetch the "new" security domain and display it
+ CMS.debug( "Dump contents of new Security Domain . . ." );
+ String c = getDomainXML( sd_host, sd_admin_port_int, true );
+ } catch( Exception e ) {}
+
+ // Since this instance is a new Security Domain,
+ // create an empty file to designate this fact.
+ String security_domain = instanceRoot + "/conf/"
+ + PKI_SECURITY_DOMAIN;
+ if( !Utils.isNT() ) {
+ Utils.exec( "touch " + security_domain );
+ Utils.exec( "chmod 00660 " + security_domain );
+ }
+
+ } else { //existing domain
+ int sd_agent_port_int = -1;
+ int sd_admin_port_int = -1;
+ try {
+ sd_agent_port_int = Integer.parseInt(sd_agent_port);
+ sd_admin_port_int = Integer.parseInt(sd_admin_port);
+ } catch (Exception e) {
+ }
+
+ try {
+ String cloneStr = "";
+ if (select.equals("clone"))
+ cloneStr = "&clone=true";
+ else
+ cloneStr = "&clone=false";
+
+ String domainMasterStr = "";
+ if (cloneMaster)
+ domainMasterStr = "&dm=true";
+ else
+ domainMasterStr = "&dm=false";
+ String eecaStr = "";
+ if (owneeclientauthsport != null)
+ eecaStr="&eeclientauthsport=" + owneeclientauthsport;
+
+ updateDomainXML( sd_host, sd_agent_port_int, true,
+ "/ca/agent/ca/updateDomainXML",
+ "list=" + s
+ + "&type=" + type
+ + "&host=" + ownhost
+ + "&name=" + subsystemName
+ + "&sport=" + ownsport
+ + domainMasterStr
+ + cloneStr
+ + "&agentsport=" + ownagentsport
+ + "&adminsport=" + ownadminsport
+ + eecaStr
+ + "&httpport=" + ownport );
+
+ // Fetch the "updated" security domain and display it
+ CMS.debug( "Dump contents of updated Security Domain . . ." );
+ String c = getDomainXML( sd_host, sd_admin_port_int, true );
+ } catch (Exception e) {
+ context.put("errorString", "Failed to update the security domain on the domain master.");
+ //return;
+ }
+ }
+
+ // add service.securityDomainPort to CS.cfg in case pkiremove
+ // needs to remove system reference from the security domain
+ try {
+ cs.putString("service.securityDomainPort", ownagentsport);
+ cs.putString("securitydomain.store", "ldap");
+ cs.commit(false);
+ } catch (Exception e) {
+ CMS.debug("DonePanel: exception in adding service.securityDomainPort to CS.cfg" + e);
+ }
+
+
+ // need to push connector information to the CA
+ if (type.equals("KRA") && !ca_host.equals("")) {
+ try {
+ updateConnectorInfo(ownagenthost, ownagentsport);
+ } catch (IOException e) {
+ context.put("errorString", "Failed to update connector information.");
+ return;
+ }
+ setupClientAuthUser();
+ } // if KRA
+
+ // import the CA certificate into the OCSP
+ // configure the CRL Publishing to OCSP in CA
+ if (type.equals("OCSP") && !ca_host.equals("")) {
+ try {
+ CMS.reinit(IOCSPAuthority.ID);
+ importCACertToOCSP();
+ } catch (Exception e) {
+ CMS.debug("DonePanel display: Failed to import the CA certificate into OCSP.");
+ }
+
+ try {
+ updateOCSPConfig(response);
+ } catch (Exception e) {
+ CMS.debug("DonePanel display: Failed to update OCSP information in CA.");
+ }
+
+ setupClientAuthUser();
+ }
+
+ if (!select.equals("clone")) {
+ if (type.equals("CA") || type.equals("KRA")) {
+ String beginRequestNumStr = "";
+ String endRequestNumStr = "";
+ String beginSerialNumStr = "";
+ String endSerialNumStr = "";
+ String requestIncStr = "";
+ String serialIncStr = "";
+
+ try {
+ endRequestNumStr = cs.getString("dbs.endRequestNumber", "");
+ endSerialNumStr = cs.getString("dbs.endSerialNumber", "");
+ BigInteger endRequestNum = new BigInteger(endRequestNumStr);
+ BigInteger endSerialNum = new BigInteger(endSerialNumStr);
+ BigInteger oneNum = new BigInteger("1");
+
+ // update global next range entries
+ LDAPConnection conn = getLDAPConn(context);
+ String basedn = cs.getString("internaldb.basedn");
+
+ String serialdn = "";
+ if (type.equals("CA")) {
+ serialdn = "ou=certificateRepository,ou=" + type.toLowerCase() + "," + basedn;
+ } else {
+ serialdn = "ou=keyRepository,ou=" + type.toLowerCase() + "," + basedn;
+ }
+ LDAPAttribute attrSerialNextRange = new LDAPAttribute( "nextRange", endSerialNum.add(oneNum).toString());
+ LDAPModification serialmod = new LDAPModification( LDAPModification.REPLACE, attrSerialNextRange );
+ conn.modify( serialdn, serialmod );
+
+ String requestdn = "ou=" + type.toLowerCase() + ",ou=requests," + basedn;
+ LDAPAttribute attrRequestNextRange = new LDAPAttribute( "nextRange", endRequestNum.add(oneNum).toString());
+ LDAPModification requestmod = new LDAPModification( LDAPModification.REPLACE, attrRequestNextRange );
+ conn.modify( requestdn, requestmod );
+
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("Unable to update global next range numbers: " + e);
+ }
+ }
+ }
+
+ if (cloneMaster) {
+ // cloning a domain master CA, the clone is also master of its domain
+ try {
+ cs.putString("securitydomain.host", ownhost);
+ cs.putString("securitydomain.httpport", ownport);
+ cs.putString("securitydomain.httpsadminport", ownadminsport);
+ cs.putString("securitydomain.httpsagentport", ownagentsport);
+ cs.putString("securitydomain.httpseeport", ownsport);
+ cs.putString("securitydomain.select", "new");
+ } catch (Exception e) {
+ CMS.debug("Caught exception trying to save security domain parameters for clone of a domain master");
+ }
+ }
+
+ cs.putInteger("cs.state", 1);
+ try {
+ // save variables needed for cloning and remove preop
+ String list = cs.getString("preop.cert.list", "");
+ StringTokenizer st = new StringTokenizer(list, ",");
+
+ while (st.hasMoreTokens()) {
+ String ss = st.nextToken();
+ if (ss.equals("sslserver"))
+ continue;
+ cs.putString("cloning." + ss + ".nickname", cs.getString("preop.cert." + ss + ".nickname", ""));
+ cs.putString("cloning." + ss + ".dn", cs.getString("preop.cert." + ss + ".dn", ""));
+ cs.putString("cloning." + ss + ".keytype", cs.getString("preop.cert." + ss + ".keytype", ""));
+ cs.putString("cloning." + ss + ".keyalgorithm", cs.getString("preop.cert." + ss + ".keyalgorithm", ""));
+ cs.putString("cloning." + ss + ".privkey.id", cs.getString("preop.cert." + ss + ".privkey.id", ""));
+ cs.putString("cloning." + ss + ".pubkey.exponent", cs.getString("preop.cert." + ss + ".pubkey.exponent", ""));
+ cs.putString("cloning." + ss + ".pubkey.modulus", cs.getString("preop.cert." + ss + ".pubkey.modulus", ""));
+ cs.putString("cloning." + ss + ".pubkey.encoded", cs.getString("preop.cert." + ss + ".pubkey.encoded", ""));
+ }
+ cs.putString("cloning.module.token", cs.getString("preop.module.token", ""));
+ cs.putString("cloning.list", list);
+
+ // more cloning variables needed for non-ca clones
+
+ if (! type.equals("CA")) {
+ String val = cs.getString("preop.ca.hostname", "");
+ if (val.compareTo("") != 0) cs.putString("cloning.ca.hostname", val);
+
+ val = cs.getString("preop.ca.httpport", "");
+ if (val.compareTo("") != 0) cs.putString("cloning.ca.httpport", val);
+
+ val = cs.getString("preop.ca.httpsport", "");
+ if (val.compareTo("") != 0) cs.putString("cloning.ca.httpsport", val);
+
+ val = cs.getString("preop.ca.list", "");
+ if (val.compareTo("") != 0) cs.putString("cloning.ca.list", val);
+
+ val = cs.getString("preop.ca.pkcs7", "");
+ if (val.compareTo("") != 0) cs.putString("cloning.ca.pkcs7", val);
+
+ val = cs.getString("preop.ca.type", "");
+ if (val.compareTo("") != 0) cs.putString("cloning.ca.type", val);
+ }
+
+ // save EC type for sslserver cert (if present)
+ cs.putString("jss.ssl.sslserver.ectype", cs.getString("preop.cert.sslserver.ec.type", "ECDHE"));
+
+ cs.removeSubStore("preop");
+ cs.commit(false);
+
+ // 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;
+ if( !Utils.isNT() ) {
+ Utils.exec( "touch " + restart_server );
+ Utils.exec( "chmod 00660 " + restart_server );
+ }
+
+ } catch (Exception e) {
+ CMS.debug("Caught exception saving preop variables: " + e);
+ }
+
+ context.put("csstate", "1");
+ }
+
+ private void setupClientAuthUser()
+ {
+ IConfigStore cs = CMS.getConfigStore();
+
+ // retrieve CA subsystem certificate from the CA
+ IUGSubsystem system =
+ (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID));
+ String id = "";
+ try {
+ String b64 = getCASubsystemCert();
+ if (b64 != null) {
+ int num = cs.getInteger("preop.subsystem.count", 0);
+ id = getCAUserId();
+ num++;
+ cs.putInteger("preop.subsystem.count", num);
+ cs.putInteger("subsystem.count", num);
+ IUser user = system.createUser(id);
+ user.setFullName(id);
+ user.setEmail("");
+ user.setPassword("");
+ user.setUserType("agentType");
+ user.setState("1");
+ user.setPhone("");
+ X509CertImpl[] certs = new X509CertImpl[1];
+ certs[0] = new X509CertImpl(CMS.AtoB(b64));
+ user.setX509Certificates(certs);
+ system.addUser(user);
+ CMS.debug("DonePanel display: successfully add the user");
+ system.addUserCert(user);
+ CMS.debug("DonePanel display: successfully add the user certificate");
+ cs.commit(false);
+ }
+ } catch (Exception e) {
+ }
+
+ try {
+ String groupName = "Trusted Managers";
+ IGroup group = system.getGroupFromName(groupName);
+ if (!group.isMember(id)) {
+ group.addMemberName(id);
+ system.modifyGroup(group);
+ CMS.debug("DonePanel display: successfully added the user to the group.");
+ }
+ } catch (Exception e) {
+ }
+ }
+
+
+ private void updateOCSPConfig(HttpServletResponse response)
+ throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ String cahost = "";
+ int caport = -1;
+ String sdhost = "";
+ int sdport = -1;
+
+ try {
+ cahost = config.getString("preop.ca.hostname", "");
+ caport = config.getInteger("preop.ca.httpsport", -1);
+ sdhost = config.getString("securitydomain.host", "");
+ sdport = config.getInteger("securitydomain.httpseeport", -1);
+ } catch (Exception e) {
+ }
+
+ String ocsphost = CMS.getAgentHost();
+ int ocspport = Integer.parseInt(CMS.getAgentPort());
+ int ocspagentport = Integer.parseInt(CMS.getAgentPort());
+ String session_id = CMS.getConfigSDSessionId();
+ String content = "xmlOutput=true&sessionID="+session_id+"&ocsp_host="+ocsphost+"&ocsp_port="+ocspport;
+
+ updateOCSPConfig(cahost, caport, true, content, response);
+ }
+
+ private void importCACertToOCSP() throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+
+ // get certificate chain from CA
+ try {
+ String b64 = config.getString("preop.ca.pkcs7", "");
+
+ if (b64.equals(""))
+ throw new IOException("Failed to get certificate chain.");
+
+ try {
+ // this could be a chain
+ X509Certificate[] certs = Cert.mapCertFromPKCS7(b64);
+ X509Certificate leafCert = null;
+ if (certs != null && certs.length > 0) {
+ if (certs[0].getSubjectDN().getName().equals(certs[0].getIssuerDN().getName())) {
+ leafCert = certs[certs.length - 1];
+ } else {
+ leafCert = certs[0];
+ }
+
+ IOCSPAuthority ocsp =
+ (IOCSPAuthority)CMS.getSubsystem(IOCSPAuthority.ID);
+ IDefStore defStore = ocsp.getDefaultStore();
+
+ // (1) need to normalize (sort) the chain
+
+ // (2) store certificate (and certificate chain) into
+ // database
+ ICRLIssuingPointRecord rec = defStore.createCRLIssuingPointRecord(
+ leafCert.getSubjectDN().getName(),
+ BIG_ZERO,
+ MINUS_ONE, null, null);
+
+ try {
+ rec.set(ICRLIssuingPointRecord.ATTR_CA_CERT, leafCert.getEncoded());
+ } catch (Exception e) {
+ // error
+ }
+ defStore.addCRLIssuingPoint(leafCert.getSubjectDN().getName(), rec);
+ //log(ILogger.EV_AUDIT, AuditFormat.LEVEL, "Added CA certificate " + leafCert.getSubjectDN().getName());
+
+ CMS.debug("DonePanel importCACertToOCSP: Added CA certificate.");
+ }
+ } catch (Exception e) {
+ throw new IOException("Failed to encode the certificate chain");
+ }
+ } catch (IOException e) {
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("DonePanel importCACertToOCSP: Failed to import the certificate chain into the OCSP");
+ throw new IOException("Failed to import the certificate chain into the OCSP");
+ }
+ }
+
+ private String getCASubsystemCert() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ String host = "";
+ int port = -1;
+ try {
+ host = cs.getString("preop.ca.hostname", "");
+ port = cs.getInteger("preop.ca.httpsadminport", -1);
+ } catch (Exception e) {
+ }
+
+ return getSubsystemCert(host, port, true);
+ }
+
+ private String getCAUserId() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ String host = "";
+ int port = -1;
+ try {
+ host = cs.getString("preop.ca.hostname", "");
+ port = cs.getInteger("preop.ca.httpsport", -1);
+ } catch (Exception e) {
+ }
+
+ return "CA-" + host + "-" + port;
+ }
+
+ private void updateConnectorInfo(String ownagenthost, String ownagentsport)
+ throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ int port = -1;
+ String url = "";
+ String host = null;
+ String transportCert = "";
+ try {
+ url = cs.getString("preop.ca.url", "");
+ if (!url.equals("")) {
+ host = cs.getString("preop.ca.hostname", "");
+ port = cs.getInteger("preop.ca.httpsadminport", -1);
+ transportCert = cs.getString("kra.transport.cert", "");
+ }
+ } catch (Exception e) {
+ }
+
+ if (host == null) {
+ CMS.debug("DonePanel: preop.ca.url is not defined. External CA selected. No transport certificate setup is required");
+ } else {
+ CMS.debug("DonePanel: Transport certificate is being setup in " + url);
+ String session_id = CMS.getConfigSDSessionId();
+ String content = "ca.connector.KRA.enable=true&ca.connector.KRA.local=false&ca.connector.KRA.timeout=30&ca.connector.KRA.uri=/kra/agent/kra/connector&ca.connector.KRA.host="+ownagenthost+"&ca.connector.KRA.port="+ownagentsport+"&ca.connector.KRA.transportCert="+URLEncoder.encode(transportCert)+"&sessionID="+session_id;
+
+ updateConnectorInfo(host, port, true, content);
+ }
+ }
+
+ private String getSubsystemNodeName(String type) {
+ if (type.equals("CA")) {
+ return "CAList";
+ } else if (type.equals("KRA")) {
+ return "KRAList";
+ } else if (type.equals("TKS")) {
+ return "TKSList";
+ } else if (type.equals("OCSP")) {
+ return "OCSPList";
+ }
+
+ return "";
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {}
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {/* This should never be called */}
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java
new file mode 100644
index 000000000..ecc1e7e40
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/DownloadPKCS12.java
@@ -0,0 +1,146 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import com.netscape.certsrv.connector.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.cmsutil.crypto.*;
+
+public class DownloadPKCS12 extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public DownloadPKCS12() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("DownloadPKCS12: initializing...");
+ super.init(sc);
+ CMS.debug("DownloadPKCS12: done initializing...");
+ }
+
+ /**
+ * Process the HTTP request.
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("DownloadPKCS12: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+ IConfigStore cs = CMS.getConfigStore();
+ mRenderResult = false;
+
+ // check the pin from the session
+ String pin = (String)httpReq.getSession().getAttribute("pin");
+ if (pin == null) {
+ CMS.debug("DownloadPKCS12 process: Failed to get the pin from the cookie.");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ String cspin = "";
+ try {
+ cspin = cs.getString("preop.pin");
+ } catch (Exception e) {
+ }
+
+ if (!pin.equals(cspin)) {
+ CMS.debug("DownloadPKCS12 process: Wrong pin");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ byte[] pkcs12 = null;
+ try {
+ String str = cs.getString("preop.pkcs12");
+ pkcs12 = CryptoUtil.string2byte(str);
+ } catch (Exception e) {
+ }
+
+ try {
+ httpResp.setContentType("application/x-pkcs12");
+ httpResp.getOutputStream().write(pkcs12);
+ return;
+ } catch (Exception e) {
+ CMS.debug("DownloadPKCS12 process: Exception="+e.toString());
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java
new file mode 100644
index 000000000..3a9a36e91
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCertChain.java
@@ -0,0 +1,160 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+
+
+public class GetCertChain extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public GetCertChain() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ }
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * </ul>
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ String outputString = null;
+
+ CertificateChain certChain = ((ICertAuthority) mAuthority).getCACertChain();
+
+ if (certChain == null) {
+ CMS.debug(
+ "GetCertChain displayChain: cannot get the certificate chain.");
+ outputError(httpResp, "Error: Failed to get certificate chain.");
+ return;
+ }
+
+ byte[] bytes = null;
+
+ try {
+ ByteArrayOutputStream encoded = new ByteArrayOutputStream();
+
+ certChain.encode(encoded);
+ bytes = encoded.toByteArray();
+ } catch (IOException e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERROR_ENCODING_CA_CHAIN_1",
+ e.toString()));
+ outputError(httpResp,
+ "Error: Failed to encode the certificate chain");
+ }
+
+ String chainBase64 = CMS.BtoA(bytes);
+
+ chainBase64 = normalizeCertStr(chainBase64);
+
+ try {
+ XMLObject xmlObj = null;
+
+ xmlObj = new XMLObject();
+
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ xmlObj.addItemToContainer(root, "ChainBase64", chainBase64);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+ private String normalizeCertStr(String s) {
+ StringBuffer val = new StringBuffer();
+
+ for (int i = 0; i < s.length(); i++) {
+ if (s.charAt(i) == '\n') {
+ continue;
+ } else if (s.charAt(i) == '\r') {
+ continue;
+ } else if (s.charAt(i) == '"') {
+ continue;
+ } else if (s.charAt(i) == ' ') {
+ continue;
+ }
+ val.append(s.charAt(i));
+ }
+ return val.toString();
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java
new file mode 100644
index 000000000..c47bfdc1c
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetConfigEntries.java
@@ -0,0 +1,211 @@
+// --- 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.*;
+import java.util.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.cmsutil.password.*;
+import org.w3c.dom.*;
+
+public class GetConfigEntries extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public GetConfigEntries() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ CMS.debug("GetConfigEntries init");
+ }
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * </ul>
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = null;
+
+ try {
+ authToken = authenticate(cmsReq);
+ } catch (Exception e) {
+ CMS.debug("GetConfigEntries authentication failed");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ // Construct an ArgBlock
+ IArgBlock args = cmsReq.getHttpParams();
+
+ // Get the operation code
+ String op = null;
+
+ op = args.getValueAsString("op", null);
+ CMS.debug("GetConfigEntries process: op=" + op);
+
+ XMLObject xmlObj = null;
+ try {
+ xmlObj = new XMLObject();
+ } catch (Exception e) {
+ CMS.debug("GetConfigEntries process: Exception: "+e.toString());
+ throw new EBaseException( e.toString() );
+ }
+
+ Node root = xmlObj.createRoot("XMLResponse");
+ AuthzToken authzToken = null;
+
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "read");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ if (op != null) {
+ IConfigStore config = CMS.getConfigStore();
+ String substores = args.getValueAsString("substores", "");
+ StringTokenizer t = new StringTokenizer(substores, ",");
+ while (t.hasMoreTokens()) {
+ String name1 = t.nextToken();
+ IConfigStore cs = config.getSubStore(name1);
+ Enumeration enum1 = cs.getPropertyNames();
+
+ while (enum1.hasMoreElements()) {
+ String name = name1+"."+enum1.nextElement();
+ try {
+ String value = config.getString(name);
+ Node container = xmlObj.createContainer(root, "Config");
+ xmlObj.addItemToContainer(container, "name", name);
+ xmlObj.addItemToContainer(container, "value", value);
+ } catch (Exception ee) {
+ continue;
+ }
+ }
+ }
+
+ String names = args.getValueAsString("names", "");
+ StringTokenizer t1 = new StringTokenizer(names, ",");
+ while (t1.hasMoreTokens()) {
+ String name = t1.nextToken();
+ String value = "";
+
+ try {
+ CMS.debug("Retrieving config name=" + name);
+ value = config.getString(name);
+ CMS.debug("Retrieving config value=" + value);
+ if (value.equals("localhost"))
+ value = config.getString("machineName", "");
+ } catch (Exception ee) {
+ if (name.equals("internaldb.ldapauth.password")) {
+ value = getLDAPPassword();
+ } else if (name.equals("internaldb.replication.password")) {
+ value = getReplicationPassword();
+ } else
+ continue;
+ }
+
+ Node container = xmlObj.createContainer(root, "Config");
+ xmlObj.addItemToContainer(container, "name", name);
+ xmlObj.addItemToContainer(container, "value", value);
+ }
+ }
+
+ try {
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ private String getLDAPPassword() {
+ IPasswordStore pwdStore = CMS.getPasswordStore();
+ return pwdStore.getPassword("internaldb");
+ }
+
+ private String getReplicationPassword() {
+ IPasswordStore pwdStore = CMS.getPasswordStore();
+ return pwdStore.getPassword("replicationdb");
+ }
+
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
new file mode 100644
index 000000000..b78b98b82
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetCookie.java
@@ -0,0 +1,276 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import java.net.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+
+
+public class GetCookie extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private static Random mRandom = null;
+ private final static int SESSION_MAX_AGE = 3600;
+ private String mErrorFormPath = null;
+ private String mFormPath = null;
+
+ public GetCookie() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+
+ CMS.debug("GetCookie init");
+ mTemplates.remove(CMSRequest.SUCCESS);
+ mRandom = new Random();
+ mErrorFormPath = sc.getInitParameter("errorTemplatePath");
+ if (mOutputTemplatePath != null) {
+ mFormPath = mOutputTemplatePath;
+ }
+ }
+
+ /**
+ * Process the HTTP request.
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ CMS.debug("GetCookie start");
+ IAuthToken authToken = null;
+ int sessionMaxAge = SESSION_MAX_AGE;
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ sessionMaxAge = cs.getInteger("sessionMaxAge", SESSION_MAX_AGE);
+ } catch (Exception e) {
+ }
+
+ IArgBlock header = CMS.createArgBlock();
+ IArgBlock ctx = CMS.createArgBlock();
+ CMSTemplateParams argSet = new CMSTemplateParams(header, ctx);
+
+ CMSTemplate form = null;
+ Locale[] locale = new Locale[1];
+
+ String url = httpReq.getParameter("url");
+ CMS.debug("GetCookie before auth, url ="+url);
+ String url_e = "";
+ URL u = null;
+ try {
+ url_e = URLDecoder.decode(url, "UTF-8");
+ u = new URL(url_e);
+ } catch (Exception eee) {
+ throw new ECMSGWException(
+ "GetCookie missing parameter: url");
+ }
+
+ int index2 = url_e.indexOf("subsystem=");
+ String subsystem = "";
+ if (index2 > 0) {
+ subsystem = url.substring(index2+10);
+ int index1 = subsystem.indexOf("&");
+ if (index1 > 0)
+ subsystem = subsystem.substring(0, index1);
+ }
+
+ try {
+ authToken = authenticate(cmsReq);
+ } catch (Exception e) {
+ CMS.debug("GetCookie authentication failed");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ header.addStringValue("sd_uid", "");
+ header.addStringValue("sd_pwd", "");
+ header.addStringValue("host", u.getHost());
+ header.addStringValue("sdhost", CMS.getEESSLHost());
+ header.addStringValue("subsystem", subsystem);
+ header.addStringValue("url", url_e);
+ header.addStringValue("errorString", "Failed Authentication");
+ String sdname = cs.getString("securitydomain.name", "");
+ header.addStringValue("sdname", sdname);
+
+ CMS.debug("mErrorFormPath=" + mErrorFormPath);
+ try {
+ form = getTemplate(mErrorFormPath, httpReq, locale);
+ } catch (IOException eee) {
+ CMS.debug("GetCookie process: cant locate the form");
+/*
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+*/
+ }
+
+ if( form == null ) {
+ CMS.debug("GetCookie::process() - form is null!");
+ throw new EBaseException( "form is null" );
+ }
+
+ try {
+ ServletOutputStream out = httpResp.getOutputStream();
+
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ httpResp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ } catch (IOException ee) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", ee.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ }
+ return;
+ }
+
+ String cookie = "";
+ if (authToken != null) {
+ String uid = authToken.getInString("uid");
+ String groupname = getGroupName(uid, subsystem);
+
+ if (groupname != null) {
+ // assign cookie
+ long num = mRandom.nextLong();
+ cookie = num+"";
+ ISecurityDomainSessionTable ctable = CMS.getSecurityDomainSessionTable();
+ String addr = "";
+ try {
+ addr = u.getHost();
+ } catch (Exception e) {
+ }
+ String ip = "";
+ try {
+ ip = InetAddress.getByName(addr).toString();
+ int index = ip.indexOf("/");
+ if (index > 0)
+ ip = ip.substring(index+1);
+ } catch (Exception e) {
+ }
+
+ ctable.addEntry(cookie, ip, uid, groupname);
+ try {
+ String sd_url = "https://"+CMS.getEESSLHost()+":"+CMS.getEESSLPort();
+ if (!url.startsWith("$")) {
+ try {
+ form = getTemplate(mFormPath, httpReq, locale);
+ } catch (IOException e) {
+ CMS.debug("GetCookie process: cant locate the form");
+/*
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+*/
+ }
+
+ header.addStringValue("url", url);
+ header.addStringValue("session_id", cookie);
+
+ EBaseException error = null;
+ try {
+ ServletOutputStream out = httpResp.getOutputStream();
+
+ if (error == null) {
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ httpResp.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ } else {
+ cmsReq.setStatus(CMSRequest.ERROR);
+ cmsReq.setError(error);
+ }
+ } catch (IOException e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ }
+ }
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ private String getGroupName(String uid, String subsystemname) {
+ String groupname = "";
+ IUGSubsystem subsystem =
+ (IUGSubsystem)(CMS.getSubsystem(IUGSubsystem.ID));
+ if (subsystem.isMemberOf(uid, "Enterprise CA Administrators") &&
+ subsystemname.equals("CA")) {
+ return "Enterprise CA Administrators";
+ } else if (subsystem.isMemberOf(uid, "Enterprise KRA Administrators") &&
+ subsystemname.equals("KRA")) {
+ return "Enterprise KRA Administrators";
+ } else if (subsystem.isMemberOf(uid, "Enterprise OCSP Administrators") &&
+ subsystemname.equals("OCSP")) {
+ return "Enterprise OCSP Administrators";
+ } else if (subsystem.isMemberOf(uid, "Enterprise TKS Administrators") &&
+ subsystemname.equals("TKS")) {
+ return "Enterprise TKS Administrators";
+ } else if (subsystem.isMemberOf(uid, "Enterprise RA Administrators") &&
+ subsystemname.equals("RA")) {
+ return "Enterprise RA Administrators";
+ } else if (subsystem.isMemberOf(uid, "Enterprise TPS Administrators") &&
+ subsystemname.equals("TPS")) {
+ return "Enterprise TPS Administrators";
+ }
+
+ return null;
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java
new file mode 100644
index 000000000..f2b4589e3
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetDomainXML.java
@@ -0,0 +1,241 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class GetDomainXML extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public GetDomainXML() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("GetDomainXML: initializing...");
+ super.init(sc);
+ CMS.debug("GetDomainXML: done initializing...");
+ }
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * </ul>
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("GetDomainXML: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+ ServletContext context = cmsReq.getServletContext();
+
+ String status = SUCCESS;
+ String basedn = null;
+ String secstore = null;
+
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ secstore = cs.getString("securitydomain.store");
+ basedn = cs.getString("internaldb.basedn");
+ }
+ catch (Exception e) {
+ CMS.debug("Unable to determine the security domain name or internal basedn. Please run the domaininfo migration script");
+ }
+
+ try {
+ XMLObject response = new XMLObject();
+ Node root = response.createRoot("XMLResponse");
+
+ if ((secstore != null) && (basedn != null) && (secstore.equals("ldap"))) {
+ ILdapConnFactory connFactory = null;
+ LDAPConnection conn = null;
+ try {
+ // get data from ldap
+ String[] entries = {};
+ String filter = "objectclass=pkiSecurityGroup";
+ LDAPSearchConstraints cons = null;
+ String[] attrs = null;
+ String dn = "ou=Security Domain," + basedn;
+
+ IConfigStore ldapConfig = cs.getSubStore("internaldb");
+ connFactory = CMS.getLdapBoundConnFactory();
+ connFactory.init(ldapConfig);
+ conn = connFactory.getConn();
+
+ // get the security domain name
+ String secdomain = (String) conn.read(dn).getAttribute("name").getStringValues().nextElement();
+
+ XMLObject xmlObj = new XMLObject();
+ Node domainInfo = xmlObj.createRoot("DomainInfo");
+ xmlObj.addItemToContainer(domainInfo, "Name", secdomain);
+
+ // this should return CAList, KRAList etc.
+ LDAPSearchResults res = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
+ attrs, true, cons);
+
+ while (res.hasMoreElements()) {
+ int count = 0;
+ dn = res.next().getDN();
+ String listName = dn.substring(3, dn.indexOf(","));
+ String subType = listName.substring(0, listName.indexOf("List"));
+ Node listNode = xmlObj.createContainer(domainInfo, listName);
+
+ filter = "objectclass=pkiSubsystem";
+ LDAPSearchResults res2 = conn.search(dn, LDAPConnection.SCOPE_ONE, filter,
+ attrs, false, cons);
+ while (res2.hasMoreElements()) {
+ Node node = xmlObj.createContainer(listNode, subType);
+ LDAPEntry entry = res2.next();
+ LDAPAttributeSet entryAttrs = entry.getAttributeSet();
+ Enumeration attrsInSet = entryAttrs.getAttributes();
+ while (attrsInSet.hasMoreElements()) {
+ LDAPAttribute nextAttr = (LDAPAttribute) attrsInSet.nextElement();
+ String attrName = nextAttr.getName();
+ if ((! attrName.equals("cn")) && (! attrName.equals("objectClass"))) {
+ String attrValue = (String) nextAttr.getStringValues().nextElement();
+ xmlObj.addItemToContainer(node, securityDomainLDAPtoXML(attrName), attrValue);
+ }
+ }
+ count ++;
+ }
+ xmlObj.addItemToContainer(listNode, "SubsystemCount", Integer.toString(count));
+ }
+
+ // Add new xml object as string to response.
+ response.addItemToContainer(root, "DomainInfo", xmlObj.toXMLString());
+ }
+ catch (Exception e) {
+ CMS.debug("GetDomainXML: Failed to read domain.xml from ldap " + e.toString());
+ status = FAILED;
+ }
+ finally {
+ if ((conn != null) && (connFactory!= null)) {
+ CMS.debug("Releasing ldap connection");
+ connFactory.returnConn(conn);
+ }
+ }
+ }
+ else {
+ // get data from file store
+
+ String path = CMS.getConfigStore().getString("instanceRoot", "")
+ + "/conf/domain.xml";
+
+ CMS.debug("GetDomainXML: got path=" + path);
+
+ try {
+ CMS.debug("GetDomainXML: Reading domain.xml from file ...");
+ FileInputStream fis = new FileInputStream(path);
+ int s = fis.available();
+
+ CMS.debug("GetDomainXML: size " + s);
+ byte buf[] = new byte[s];
+
+ fis.read(buf, 0, s);
+ fis.close();
+ CMS.debug("GetDomainXML: Done Reading domain.xml...");
+
+ response.addItemToContainer(root, "DomainInfo", new String(buf));
+ }
+ catch (Exception e) {
+ CMS.debug("Failed to read domain.xml from file" + e.toString());
+ status = FAILED;
+ }
+ }
+
+ response.addItemToContainer(root, "Status", status);
+ byte[] cb = response.toByteArray();
+ outputResult(httpResp, "application/xml", cb);
+
+ } catch (Exception e) {
+ CMS.debug("GetDomainXML: Failed to send the XML output" + e.toString());
+ }
+ }
+
+ protected String securityDomainLDAPtoXML(String attribute) {
+ if (attribute.equals("host")) return "Host";
+ else return attribute;
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java
new file mode 100644
index 000000000..5f533fbe4
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetStatus.java
@@ -0,0 +1,115 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+
+
+public class GetStatus extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public GetStatus() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ }
+
+ /**
+ * Process the HTTP request.
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+ IConfigStore config = CMS.getConfigStore();
+
+ String outputString = null;
+
+ String state = config.getString("cs.state", "");
+ String type = config.getString("cs.type", "");
+
+ try {
+ XMLObject xmlObj = null;
+
+ xmlObj = new XMLObject();
+
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "State", state);
+ xmlObj.addItemToContainer(root, "Type", type);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java
new file mode 100644
index 000000000..ab6a1aa01
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetSubsystemCert.java
@@ -0,0 +1,155 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.cmsutil.crypto.*;
+import org.w3c.dom.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.X509Certificate;
+
+
+public class GetSubsystemCert extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public GetSubsystemCert() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ }
+
+ /**
+ * Process the HTTP request.
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ String outputString = null;
+
+ IConfigStore cs = CMS.getConfigStore();
+ String nickname = "";
+ try {
+ nickname = cs.getString("ca.subsystem.nickname", "");
+ String tokenname = cs.getString("ca.subsystem.tokenname", "");
+ if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
+ nickname = tokenname+":"+nickname;
+ } catch (Exception e) {
+ }
+
+ CMS.debug("GetSubsystemCert process: nickname="+nickname);
+ String s = "";
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ X509Certificate cert = cm.findCertByNickname(nickname);
+
+ if (cert == null) {
+ CMS.debug("GetSubsystemCert process: subsystem cert is null");
+ outputError(httpResp, "Error: Failed to get subsystem certificate.");
+ return;
+ }
+
+ byte[] bytes = cert.getEncoded();
+ s = CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bytes));
+ } catch (Exception e) {
+ CMS.debug("GetSubsystemCert process: exception: "+e.toString());
+ }
+
+ try {
+ XMLObject xmlObj = null;
+ xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ xmlObj.addItemToContainer(root, "Cert", s);
+ byte[] cb = xmlObj.toByteArray();
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+ private String normalizeCertStr(String s) {
+ StringBuffer val = new StringBuffer();
+
+ for (int i = 0; i < s.length(); i++) {
+ if (s.charAt(i) == '\n') {
+ continue;
+ } else if (s.charAt(i) == '\r') {
+ continue;
+ } else if (s.charAt(i) == '"') {
+ continue;
+ } else if (s.charAt(i) == ' ') {
+ continue;
+ }
+ val.append(s.charAt(i));
+ }
+ return val.toString();
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java
new file mode 100644
index 000000000..442826c42
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTokenInfo.java
@@ -0,0 +1,147 @@
+// --- 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.*;
+import java.util.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.cmsutil.password.*;
+import org.w3c.dom.*;
+
+public class GetTokenInfo extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public GetTokenInfo() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ CMS.debug("GetTokenInfo init");
+ }
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * </ul>
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ // Construct an ArgBlock
+ IArgBlock args = cmsReq.getHttpParams();
+
+ XMLObject xmlObj = null;
+ try {
+ xmlObj = new XMLObject();
+ } catch (Exception e) {
+ CMS.debug("GetTokenInfo process: Exception: "+e.toString());
+ throw new EBaseException( e.toString() );
+ }
+
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ IConfigStore config = CMS.getConfigStore();
+
+ String certlist = "";
+ try {
+ certlist = config.getString("cloning.list");
+ } catch (Exception e) {
+ }
+
+ StringTokenizer t1 = new StringTokenizer(certlist, ",");
+ while (t1.hasMoreTokens()) {
+ String name = t1.nextToken();
+ if (name.equals("sslserver"))
+ continue;
+ name = "cloning."+name+".nickname";
+ String value = "";
+
+ try {
+ value = config.getString(name);
+ } catch (Exception ee) {
+ continue;
+ }
+
+ Node container = xmlObj.createContainer(root, "Config");
+ xmlObj.addItemToContainer(container, "name", name);
+ xmlObj.addItemToContainer(container, "value", value);
+ }
+
+ String value = "";
+ String name = "cloning.module.token";
+ try {
+ value = config.getString(name);
+ } catch (Exception e) {
+ }
+
+ Node container = xmlObj.createContainer(root, "Config");
+ xmlObj.addItemToContainer(container, "name", name);
+ xmlObj.addItemToContainer(container, "value", value);
+
+ try {
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java
new file mode 100644
index 000000000..21e64086e
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/GetTransportCert.java
@@ -0,0 +1,189 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.kra.*;
+import com.netscape.certsrv.security.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.cmsutil.util.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import com.netscape.certsrv.connector.*;
+import com.netscape.certsrv.ca.*;
+
+/**
+ * This servlet retrieves the transport certificate from DRM.
+ */
+public class GetTransportCert extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public GetTransportCert() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("GetTransportCert: initializing...");
+ super.init(sc);
+ CMS.debug("GetTransportCert: done initializing...");
+ }
+
+ /**
+ * Process the HTTP request.
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateUpdater: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = null;
+ try {
+ authToken = authenticate(cmsReq);
+ CMS.debug("GetTransportCert authentication successful.");
+ } catch (Exception e) {
+ CMS.debug("GetTransportCert: authentication failed.");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ if (authToken == null) {
+ CMS.debug("GetTransportCert: authentication failed.");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ AuthzToken authzToken = null;
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "read");
+ CMS.debug("GetTransportCert authorization successful.");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ IKeyRecoveryAuthority kra =
+ (IKeyRecoveryAuthority) mAuthority;
+ ITransportKeyUnit tu = kra.getTransportKeyUnit();
+ org.mozilla.jss.crypto.X509Certificate transportCert =
+ tu.getCertificate();
+
+ String mime64 = "";
+ try {
+ mime64 = CMS.BtoA(transportCert.getEncoded());
+ mime64 = com.netscape.cmsutil.util.Cert.normalizeCertStrAndReq(mime64);
+ } catch (CertificateEncodingException eee) {
+ CMS.debug("GetTransportCert: Failed to encode certificate");
+ }
+
+ // send success status back to the requestor
+ try {
+ CMS.debug("GetTransportCert: Sending response " + mime64);
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ xmlObj.addItemToContainer(root, "TransportCert", mime64);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("GetTransportCert: Failed to send the XML output " + e);
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java
new file mode 100644
index 000000000..653387bf4
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/HierarchyPanel.java
@@ -0,0 +1,203 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.base.*;
+
+import java.util.*;
+import java.security.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.KeyPairGenerator;
+
+import netscape.security.x509.*;
+import com.netscape.cms.servlet.wizard.*;
+
+public class HierarchyPanel extends WizardPanelBase {
+
+ public HierarchyPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("PKI Hierarchy");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("PKI Hierarchy");
+ setId(id);
+ }
+
+ public boolean shouldSkip() {
+
+ // we dont need to ask the hierachy if we are
+ // setting up a clone
+ try {
+ IConfigStore c = CMS.getConfigStore();
+ String s = c.getString("preop.subsystem.select",
+ null);
+ if (s != null && s.equals("clone")) {
+ // mark this panel as done
+ c.putString("preop.hierarchy.select","root");
+ c.putString("hierarchy.select","Clone");
+ return true;
+ }
+ } catch (EBaseException e) {
+ }
+
+ return false;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.hierarchy.select", "");
+ cs.putString("hierarchy.select", "");
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.hierarchy.select", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "PKI Hierarchy");
+ IConfigStore config = CMS.getConfigStore();
+
+ if (isPanelDone()) {
+ try {
+ String s = config.getString("preop.hierarchy.select");
+
+ if (s.equals("root")) {
+ context.put("check_root", "checked");
+ } else if (s.equals("join")) {
+ context.put("check_join", "checked");
+ }
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("check_root", "checked");
+ context.put("check_join", "");
+ }
+
+ context.put("panel", "admin/console/config/hierarchypanel.vm");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ try {
+ String cstype = config.getString("preop.subsystem.select", "");
+ if (cstype.equals("clone")) {
+ context.put("updateStatus", "success");
+ return;
+ }
+ } catch (Exception e) {
+ }
+
+ String select = HttpInput.getID(request, "choice");
+
+ if (select == null) {
+ CMS.debug("HierarchyPanel: choice not found");
+ context.put("updateStatus", "failure");
+ throw new IOException("choice not found");
+ }
+
+ if (select.equals("root")) {
+ config.putString("preop.hierarchy.select", "root");
+ config.putString("hierarchy.select", "Root");
+ config.putString("preop.ca.type", "sdca");
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {}
+ } else if (select.equals("join")) {
+ config.putString(PCERT_PREFIX + "signing.type", "remote");
+ config.putString("preop.hierarchy.select", "join");
+ config.putString("hierarchy.select", "Subordinate");
+ } else {
+ config.putString(PCERT_PREFIX + "signing.type", "remote");
+ CMS.debug("HierarchyPanel: invalid choice " + select);
+ context.put("updateStatus", "failure");
+ throw new IOException("invalid choice " + select);
+ }
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {}
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java
new file mode 100644
index 000000000..9b4a3ae3f
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportAdminCertPanel.java
@@ -0,0 +1,342 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.certsrv.template.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.request.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import java.io.*;
+import java.math.*;
+import java.util.*;
+import java.security.*;
+import java.security.cert.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+
+import org.mozilla.jss.asn1.*;
+import com.netscape.cms.servlet.wizard.*;
+
+public class ImportAdminCertPanel extends WizardPanelBase {
+
+ public ImportAdminCertPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Import Administrator's Certificate");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Import Administrator's Certificate");
+ setId(id);
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ public void cleanUp() throws IOException {
+ }
+
+ public boolean isPanelDone() {
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("ImportAdminCertPanel: display");
+ context.put("errorString", "");
+ context.put("title", "Import Administrator's Certificate");
+ context.put("panel", "admin/console/config/importadmincertpanel.vm");
+ context.put("import", "true");
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ String type = "";
+ String subsystemtype = "";
+
+ try {
+ type = cs.getString("preop.ca.type", "");
+ subsystemtype = cs.getString("cs.type", "");
+ } catch (Exception e) {}
+
+ try {
+ String serialno = cs.getString("preop.admincert.serialno.0");
+
+ context.put("serialNumber", serialno);
+ } catch (Exception e) {
+ context.put("errorString", "Failed to get serial number.");
+ }
+
+ context.put("caType", type);
+
+ ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
+
+ if (ca == null) {
+ context.put("ca", "false");
+ } else {
+ context.put("ca", "true");
+ }
+
+ String caHost = "";
+ String caPort = "";
+ String info = "";
+
+ if (ca == null) {
+ if (type.equals("otherca")) {
+ try {
+ // this is a non-CA system that has elected to have its certificates
+ // signed by a CA outside of the security domain.
+ // in this case, we submitted the cert request for the admin cert to
+ // to security domain host.
+ caHost = cs.getString("securitydomain.host", "");
+ caPort = cs.getString("securitydomain.httpsadminport", "");
+ } catch (Exception e) {}
+ } else if (type.equals("sdca")) {
+ try {
+ // this is a non-CA system that submitted its certs to a CA
+ // within the security domain. In this case, we submitted the cert
+ // request for the admin cert to this CA
+ caHost = cs.getString("preop.ca.hostname", "");
+ caPort = cs.getString("preop.ca.httpsadminport", "");
+ } catch (Exception e) {}
+ }
+ } else {
+ // for CAs, we always generate our own admin certs
+ // send our own connection details
+ try {
+ caHost = cs.getString("service.machineName", "");
+ caPort = cs.getString("pkicreate.admin_secure_port", "");
+ } catch (Exception e) {}
+ }
+
+ String pkcs7 = "";
+ try {
+ pkcs7 = cs.getString("preop.admincert.pkcs7", "");
+ } catch (Exception e) {
+ }
+
+ context.put("pkcs7", pkcs7);
+ context.put("caHost", caHost);
+ context.put("caPort", caPort);
+ context.put("info", info);
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+
+ String type = "";
+ String subsystemtype = "";
+ String security_domain_type = "";
+ String selected_hierarchy = "";
+
+ try {
+ type = cs.getString("preop.ca.type", "");
+ subsystemtype = cs.getString("cs.type", "");
+ security_domain_type = cs.getString("securitydomain.select", "");
+ selected_hierarchy = cs.getString("preop.hierarchy.select", "");
+ } catch (Exception e) {}
+
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
+ ICertificateAuthority.ID);
+
+ if (ca == null) {
+ context.put("ca", "false");
+ } else {
+ context.put("ca", "true");
+ }
+ context.put("caType", type);
+
+ X509CertImpl certs[] = new X509CertImpl[1];
+
+ // REMINDER: This panel is NOT used by "clones"
+ if( ca != null ) {
+ String serialno = null;
+
+ if( selected_hierarchy.equals( "root" ) ) {
+ CMS.debug( "ImportAdminCertPanel update: "
+ + "Root CA subsystem - "
+ + "(new Security Domain)" );
+ } else {
+ CMS.debug( "ImportAdminCertPanel update: "
+ + "Subordinate CA subsystem - "
+ + "(new Security Domain)" );
+ }
+
+ try {
+ serialno = cs.getString("preop.admincert.serialno.0");
+ } catch (Exception e) {
+ CMS.debug(
+ "ImportAdminCertPanel update: Failed to get request id.");
+ context.put("updateStatus", "failure");
+ throw new IOException("Failed to get request id.");
+ }
+
+ ICertificateRepository repost = ca.getCertificateRepository();
+
+ try {
+ certs[0] = repost.getX509Certificate(
+ new BigInteger(serialno, 16));
+ } catch (Exception ee) {}
+ } else {
+ String dir = null;
+
+ // REMINDER: This panel is NOT used by "clones"
+ if( subsystemtype.equals( "CA" ) ) {
+ if( selected_hierarchy.equals( "root" ) ) {
+ CMS.debug( "ImportAdminCertPanel update: "
+ + "Root CA subsystem - "
+ + "(existing Security Domain)" );
+ } else {
+ CMS.debug( "ImportAdminCertPanel update: "
+ + "Subordinate CA subsystem - "
+ + "(existing Security Domain)" );
+ }
+ } else {
+ CMS.debug( "ImportAdminCertPanel update: "
+ + subsystemtype
+ + " subsystem" );
+ }
+
+ try {
+ dir = cs.getString("preop.admincert.b64", "");
+ CMS.debug("ImportAdminCertPanel update: dir=" + dir);
+ } catch (Exception ee) {}
+
+ try {
+ BufferedReader reader = new BufferedReader(
+ new FileReader(dir));
+ String b64 = "";
+
+ StringBuffer sb = new StringBuffer();
+ while (reader.ready()) {
+ sb.append(reader.readLine());
+ }
+ b64 = sb.toString();
+ reader.close();
+
+ b64 = b64.trim();
+ b64 = CryptoUtil.stripCertBrackets(b64);
+ CMS.debug("ImportAdminCertPanel update: b64=" + b64);
+ byte[] b = CryptoUtil.base64Decode(b64);
+ certs[0] = new X509CertImpl(b);
+ } catch (Exception e) {
+ CMS.debug("ImportAdminCertPanel update: " + e.toString());
+ }
+ }
+
+ try {
+ IUGSubsystem ug = (IUGSubsystem) CMS.getSubsystem(IUGSubsystem.ID);
+ String uid = cs.getString("preop.admin.uid");
+ IUser user = ug.getUser(uid);
+ user.setX509Certificates(certs);
+ ug.addUserCert(user);
+ } catch (LDAPException e) {
+ CMS.debug("ImportAdminCertPanel update: failed to add certificate to the internal database. Exception: "+e.toString());
+ if (e.getLDAPResultCode() != LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) {
+ context.put("updateStatus", "failure");
+ throw new IOException(e.toString());
+ }
+ } catch (Exception e) {
+ CMS.debug(
+ "ImportAdminCertPanel update: failed to add certificate. Exception: "
+ + e.toString());
+ context.put("updateStatus", "failure");
+ throw new IOException(e.toString());
+ }
+
+ context.put("errorString", "");
+ context.put("info", "");
+ context.put("title", "Import Administrator Certificate");
+ context.put("panel", "admin/console/config/importadmincertpanel.vm");
+ context.put("updateStatus", "success");
+ }
+
+ public boolean shouldSkip() {
+ try {
+ IConfigStore c = CMS.getConfigStore();
+ String s = c.getString("preop.subsystem.select",null);
+ if (s != null && s.equals("clone")) {
+ return true;
+ }
+ } catch (EBaseException e) {
+ }
+
+ return false;
+ }
+
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ /* This should never be called */
+ context.put("title", "Import Administrator Certificate");
+ context.put("panel", "admin/console/config/importadmincertpanel.vm");
+ context.put("info", "");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java
new file mode 100755
index 000000000..8a730d519
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportCAChainPanel.java
@@ -0,0 +1,161 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.certsrv.template.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.request.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import java.io.*;
+import java.math.*;
+import java.util.*;
+import java.security.*;
+import java.security.cert.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+
+import org.mozilla.jss.asn1.*;
+import com.netscape.cms.servlet.wizard.*;
+
+public class ImportCAChainPanel extends WizardPanelBase {
+
+ public ImportCAChainPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Import CA's Certificate Chain");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Import CA's Certificate Chain");
+ setId(id);
+ }
+
+ public boolean isSubPanel() {
+ return false;
+ }
+
+ public void cleanUp() throws IOException {
+ }
+
+ public boolean isPanelDone() {
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("ImportCACertChain: display");
+ context.put("errorString", "");
+ context.put("title", "Import CA's Certificate Chain");
+ context.put("panel", "admin/console/config/importcachainpanel.vm");
+ context.put("import", "true");
+
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ context.put("machineName", cs.getString("machineName"));
+ context.put("https_port", cs.getString("pkicreate.ee_secure_port"));
+ context.put("http_port", cs.getString("pkicreate.unsecure_port"));
+ } catch (EBaseException e) {
+ CMS.debug("ImportCACertChain:display: Exception: " + e.toString());
+ context.put("errorString", "Error loading values for Import CA Certificate Panel");
+ }
+
+ ISubsystem ca = (ISubsystem) CMS.getSubsystem("ca");
+
+ if (ca == null) {
+ context.put("ca", "false");
+ } else {
+ context.put("ca", "true");
+ }
+
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+
+
+ context.put("errorString", "");
+ context.put("title", "Import CA's Certificate Chain");
+ context.put("panel", "admin/console/config/importcachainpanel.vm");
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ /* This should never be called */
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ context.put("machineName", cs.getString("machineName"));
+ context.put("https_port", cs.getString("pkicreate.ee_secure_port"));
+ context.put("http_port", cs.getString("pkicreate.unsecure_port"));
+ context.put("title", "Import CA's Certificate Chain");
+ context.put("panel", "admin/console/config/importcachainpanel.vm");
+ } catch (EBaseException e) {}
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java
new file mode 100644
index 000000000..1d884856f
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ImportTransportCert.java
@@ -0,0 +1,195 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.kra.*;
+import com.netscape.certsrv.security.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import com.netscape.certsrv.connector.*;
+import com.netscape.certsrv.ca.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.PrivateKey.Type;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.util.*;
+import org.mozilla.jss.pkcs12.*;
+import org.mozilla.jss.pkcs11.*;
+import org.mozilla.jss.asn1.*;
+import org.mozilla.jss.pkix.primitive.*;
+import org.mozilla.jss.pkix.primitive.Attribute;
+import java.security.interfaces.*;
+
+/**
+ * This servlet imports DRM's transport certificate into TKS.
+ */
+public class ImportTransportCert extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public ImportTransportCert() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("ImportTransportCert: initializing...");
+ super.init(sc);
+ CMS.debug("ImportTransportCert: done initializing...");
+ }
+
+ /**
+ * Process the HTTP request.
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateUpdater: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = null;
+ try {
+ authToken = authenticate(cmsReq);
+ CMS.debug("ImportTransportCert authentication successful.");
+ } catch (Exception e) {
+ CMS.debug("ImportTransportCert: authentication failed.");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ if (authToken == null) {
+ CMS.debug("ImportTransportCert: authentication failed.");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ AuthzToken authzToken = null;
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
+ CMS.debug("ImportTransportCert authorization successful.");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ String name = httpReq.getParameter("name");
+ String certsString = httpReq.getParameter("certificate");
+
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ CMS.debug("ImportTransportCert: Importing certificate");
+ org.mozilla.jss.crypto.X509Certificate cert =
+ cm.importCACertPackage(CMS.AtoB(certsString));
+ String nickName = cert.getNickname();
+ CMS.debug("ImportTransportCert: nickname " + nickName);
+ cs.putString("tks.drm_transport_cert_nickname", nickName);
+ CMS.debug("ImportTransportCert: Commiting configuration");
+ cs.commit(false);
+
+ // send success status back to the requestor
+ CMS.debug("ImportTransportCert: Sending response");
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("ImportTransportCert: Failed to send the XML output " + e);
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java
new file mode 100644
index 000000000..65b98a4ae
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LDAPSecurityDomainSessionTable.java
@@ -0,0 +1,333 @@
+// --- 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) 2010 Red Hat, Inc.
+// All rights reserved.
+// --- END COPYRIGHT BLOCK ---
+package com.netscape.cms.servlet.csadmin;
+
+import java.util.*;
+import java.io.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import netscape.ldap.*;
+import com.netscape.cmsutil.password.*;
+
+/**
+ * This object stores the values for IP, uid and group based on the cookie id in LDAP.
+ * Entries are stored under ou=Security Domain, ou=sessions, $basedn
+ */
+public class LDAPSecurityDomainSessionTable
+ implements ISecurityDomainSessionTable {
+
+ private long m_timeToLive;
+
+ public LDAPSecurityDomainSessionTable(long timeToLive) {
+ m_timeToLive = timeToLive;
+ }
+
+ public void addEntry(String sessionId, String ip,
+ String uid, String group) {
+ IConfigStore cs = CMS.getConfigStore();
+ LDAPConnection conn = null;
+ boolean sessions_exists = true;
+
+ String basedn = null;
+ String sessionsdn = null;
+ try {
+ basedn = cs.getString("internaldb.basedn");
+ sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: addEntry: failed to read basedn" + e);
+ return;
+ }
+
+ try {
+ // create session entry (if it does not exist)
+ conn = getLDAPConn();
+
+ LDAPEntry entry = null;
+ LDAPAttributeSet attrs = null;
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "organizationalUnit"));
+ attrs.add(new LDAPAttribute("ou", "sessions"));
+ entry = new LDAPEntry(sessionsdn, attrs);
+ conn.add(entry);
+ } catch (Exception e) {
+ if ((e instanceof LDAPException) && (((LDAPException) e).getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS)) {
+ // continue
+ } else {
+ CMS.debug("SecurityDomainSessionTable: unable to create ou=sessions:" + e);
+ sessions_exists = false;
+ }
+ }
+
+ // add new entry
+ try {
+ LDAPEntry entry = null;
+ LDAPAttributeSet attrs = null;
+ String entrydn = "cn=" + sessionId + "," + sessionsdn;
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "securityDomainSessionEntry"));
+ attrs.add(new LDAPAttribute("cn", sessionId));
+ attrs.add(new LDAPAttribute("host", ip));
+ attrs.add(new LDAPAttribute("uid", uid));
+ attrs.add(new LDAPAttribute("cmsUserGroup", group));
+ attrs.add(new LDAPAttribute("dateOfCreate", Long.toString((new Date()).getTime())));
+
+ entry = new LDAPEntry(entrydn, attrs);
+ if (sessions_exists) {
+ conn.add(entry);
+ }
+ CMS.debug("SecurityDomainSessionTable: added session entry" + sessionId);
+ } catch(Exception e) {
+ CMS.debug("SecurityDomainSessionTable: unable to create session entry" + sessionId + ": " + e);
+ }
+
+ try {
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable:addEntry: Error in disconnecting from database: " + e);
+ }
+ }
+
+ public void removeEntry(String sessionId) {
+ IConfigStore cs = CMS.getConfigStore();
+ LDAPConnection conn = null;
+ try {
+ String basedn = cs.getString("internaldb.basedn");
+ String dn = "cn=" + sessionId + ",ou=sessions,ou=Security Domain," + basedn;
+ conn = getLDAPConn();
+ conn.delete(dn);
+ } catch (Exception e) {
+ if ((e instanceof LDAPException) && (((LDAPException) e).getLDAPResultCode() == LDAPException.NO_SUCH_OBJECT)) {
+ // continue
+ } else {
+ CMS.debug("SecurityDomainSessionTable: unable to delete session " + sessionId + ": " + e);
+ }
+ }
+ try {
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: removeEntry: Error in disconnecting from database: " + e);
+ }
+ }
+
+ public boolean isSessionIdExist(String sessionId) {
+ IConfigStore cs = CMS.getConfigStore();
+ LDAPConnection conn = null;
+ boolean ret = false;
+ try {
+ String basedn = cs.getString("internaldb.basedn");
+ String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
+ String filter = "(cn=" + sessionId + ")";
+ String[] attrs = { "cn" };
+
+ conn = getLDAPConn();
+ LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
+ if (res.getCount() > 0) ret = true;
+ } catch(Exception e) {
+ CMS.debug("SecurityDomainSessionTable: unable to query session " + sessionId + ": " + e);
+ }
+
+ try {
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: isSessionIdExist: Error in disconnecting from database: " + e);
+ }
+ return ret;
+ }
+
+
+ public Enumeration getSessionIds() {
+ IConfigStore cs = CMS.getConfigStore();
+ LDAPConnection conn = null;
+ Vector ret = new Vector();
+
+ try {
+ String basedn = cs.getString("internaldb.basedn");
+ String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
+ String filter = "(objectclass=securityDomainSessionEntry)";
+ String[] attrs = { "cn" };
+
+ conn = getLDAPConn();
+ LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
+ while (res.hasMoreElements()) {
+ LDAPEntry entry = res.next();
+ ret.add(entry.getAttribute("cn").getStringValueArray()[0]);
+ }
+ } catch (LDAPException e) {
+ switch (e.getLDAPResultCode()) {
+ case LDAPException.NO_SUCH_OBJECT:
+ CMS.debug("SecurityDomainSessionTable: getSessionIds(): no sessions have been created");
+ break;
+ default:
+ CMS.debug("SecurityDomainSessionTable: unable to query sessionIds due to ldap exception: " + e);
+ }
+ } catch(Exception e) {
+ CMS.debug("SecurityDomainSessionTable: unable to query sessionIds: " + e);
+ }
+
+ try {
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: getSessionIds: Error in disconnecting from database: " + e);
+ }
+
+ return ret.elements();
+ }
+
+ private String getStringValue(String sessionId, String attr) {
+ IConfigStore cs = CMS.getConfigStore();
+ LDAPConnection conn = null;
+ String ret = null;
+ try {
+ String basedn = cs.getString("internaldb.basedn");
+ String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
+ String filter = "(cn=" + sessionId + ")";
+ String[] attrs = { attr };
+ conn = getLDAPConn();
+ LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
+ if (res.getCount() > 0) {
+ LDAPEntry entry = res.next();
+ ret = entry.getAttribute(attr).getStringValueArray()[0];
+ }
+ } catch(Exception e) {
+ CMS.debug("SecurityDomainSessionTable: unable to query session " + sessionId + ": " + e);
+ }
+
+ try {
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: isSessionIdExist: Error in disconnecting from database: " + e);
+ }
+ return ret;
+ }
+
+ public String getIP(String sessionId) {
+ return getStringValue(sessionId, "host");
+ }
+
+ public String getUID(String sessionId) {
+ return getStringValue(sessionId, "uid");
+ }
+
+ public String getGroup(String sessionId) {
+ return getStringValue(sessionId, "cmsUserGroup");
+ }
+
+ public long getBeginTime(String sessionId) {
+ String beginStr = getStringValue(sessionId, "dateOfCreate");
+ if (beginStr != null) {
+ return Long.parseLong(beginStr);
+ }
+ return -1;
+ }
+
+ public long getTimeToLive() {
+ return m_timeToLive;
+ }
+
+ public int getSize() {
+ IConfigStore cs = CMS.getConfigStore();
+ LDAPConnection conn = null;
+ int ret =0;
+
+ try {
+ String basedn = cs.getString("internaldb.basedn");
+ String sessionsdn = "ou=sessions,ou=Security Domain," + basedn;
+ String filter = "(objectclass=securityDomainSessionEntry)";
+ String[] attrs = { "cn" };
+
+ conn = getLDAPConn();
+ LDAPSearchResults res = conn.search(sessionsdn, LDAPv2.SCOPE_SUB, filter, attrs, false);
+ ret = res.getCount();
+ } catch(Exception e) {
+ CMS.debug("SecurityDomainSessionTable: unable to query sessionIds: " + e);
+ }
+
+ try {
+ conn.disconnect();
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: getSessionIds: Error in disconnecting from database: " + e);
+ }
+
+ return ret;
+ }
+
+ private LDAPConnection getLDAPConn()
+ throws IOException
+ {
+ IConfigStore cs = CMS.getConfigStore();
+
+ String host = "";
+ String port = "";
+ String pwd = null;
+ String binddn = "";
+ String security = "";
+
+ IPasswordStore pwdStore = CMS.getPasswordStore();
+
+ if (pwdStore != null) {
+ //CMS.debug("SecurityDomainSessionTable: getLDAPConn: password store available");
+ pwd = pwdStore.getPassword("internaldb");
+ }
+
+ if ( pwd == null) {
+ throw new IOException("SecurityDomainSessionTable: Failed to obtain password from password store");
+ }
+
+ try {
+ host = cs.getString("internaldb.ldapconn.host");
+ port = cs.getString("internaldb.ldapconn.port");
+ binddn = cs.getString("internaldb.ldapauth.bindDN");
+ security = cs.getString("internaldb.ldapconn.secureConn");
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable: getLDAPConn" + e.toString());
+ throw new IOException(
+ "Failed to retrieve LDAP information from CS.cfg.");
+ }
+
+ int p = -1;
+
+ try {
+ p = Integer.parseInt(port);
+ } catch (Exception e) {
+ CMS.debug("SecurityDomainSessionTable getLDAPConn: " + e.toString());
+ throw new IOException("Port is not valid");
+ }
+
+ LDAPConnection conn = null;
+ if (security.equals("true")) {
+ //CMS.debug("SecurityDomainSessionTable getLDAPConn: creating secure (SSL) connection for internal ldap");
+ conn = new LDAPConnection(CMS.getLdapJssSSLSocketFactory());
+ } else {
+ //CMS.debug("SecurityDomainSessionTable getLDAPConn: creating non-secure (non-SSL) connection for internal ldap");
+ conn = new LDAPConnection();
+ }
+
+ //CMS.debug("SecurityDomainSessionTable connecting to " + host + ":" + p);
+ try {
+ conn.connect(host, p, binddn, pwd);
+ } catch (LDAPException e) {
+ CMS.debug("SecurityDomainSessionTable getLDAPConn: " + e.toString());
+ throw new IOException("Failed to connect to the internal database.");
+ }
+
+ return conn;
+ }
+
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java
new file mode 100644
index 000000000..ca3879adb
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/LoginServlet.java
@@ -0,0 +1,70 @@
+// --- 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.util.*;
+
+import org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.apps.CMS;
+
+
+public class LoginServlet extends BaseServlet {
+
+ public boolean authenticate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ return true;
+ }
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ Template template = null;
+
+ try {
+ String pin = request.getParameter("pin");
+
+ if (pin == null) {
+ context.put("error", "");
+ } else {
+ String cspin = CMS.getConfigStore().getString("preop.pin");
+
+ if (cspin != null && cspin.equals(pin)) {
+ // create session
+ request.getSession(true).setAttribute("pin", cspin);
+ // pin match, redirect to the welcome page
+ response.sendRedirect("wizard");
+ return null;
+ } else {
+ context.put("error", "Login Failed");
+ }
+ }
+ template = Velocity.getTemplate("admin/console/config/login.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java
new file mode 100644
index 000000000..ff8d08b85
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/MainPageServlet.java
@@ -0,0 +1,155 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.template.ArgList;
+import com.netscape.certsrv.template.ArgSet;
+import com.netscape.cms.servlet.*;
+import com.netscape.certsrv.logging.ILogger;
+
+public class MainPageServlet extends CMSServlet {
+ private static final String PROP_AUTHORITY_ID="authorityId";
+ private String mAuthorityId = null;
+ private String mFormPath = null;
+
+ public MainPageServlet() {
+ }
+
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ mTemplates.remove(CMSRequest.SUCCESS);
+ mTemplates.remove(CMSRequest.ERROR);
+ }
+
+ public void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest request = cmsReq.getHttpReq();
+ HttpServletResponse response = cmsReq.getHttpResp();
+
+ CMS.debug("MainPageServlet process");
+ IArgBlock header = CMS.createArgBlock();
+ IArgBlock ctx = CMS.createArgBlock();
+ CMSTemplateParams argSet = new CMSTemplateParams(header, ctx);
+
+ CMSTemplate form = null;
+ Locale[] locale = new Locale[1];
+
+ if (mOutputTemplatePath != null)
+ mFormPath = mOutputTemplatePath;
+
+ try {
+ form = getTemplate(mFormPath, request, locale);
+ } catch (IOException e) {
+ CMS.debug("MainPageServlet process: cant locate the form");
+/*
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+*/
+ }
+
+ process(argSet, header, ctx, request, response);
+
+ EBaseException error = null;
+ try {
+ ServletOutputStream out = response.getOutputStream();
+
+ if (error == null) {
+ cmsReq.setStatus(CMSRequest.SUCCESS);
+ response.setContentType("text/html");
+ form.renderOutput(out, argSet);
+ } else {
+ cmsReq.setStatus(CMSRequest.ERROR);
+ cmsReq.setError(error);
+ }
+ } catch (IOException e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_OUT_STREAM_TEMPLATE", e.toString()));
+ throw new ECMSGWException(
+ CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
+ }
+ }
+
+ private void process(CMSTemplateParams argSet, IArgBlock header,
+ IArgBlock ctx, HttpServletRequest req, HttpServletResponse resp)
+ throws EBaseException {
+
+ int num = 0;
+ IArgBlock rarg = null;
+ IConfigStore cs = CMS.getConfigStore();
+ int state = 0;
+ String host = "";
+ String adminInterface = "";
+ String eeInterface = "";
+ String agentInterface = "";
+ try {
+ state = cs.getInteger("cs.state", 0);
+ host = cs.getString("machineName", "");
+ adminInterface = cs.getString("admin.interface.uri", "");
+ eeInterface = cs.getString("ee.interface.uri", "");
+ agentInterface = cs.getString("agent.interface.uri", "");
+ } catch (Exception e) {
+ }
+
+ if (state == 0) {
+ rarg = CMS.createArgBlock();
+ rarg.addStringValue("type", "admin");
+ rarg.addStringValue("prefix", "http");
+ rarg.addIntegerValue("port",
+ Integer.valueOf(CMS.getEENonSSLPort()).intValue());
+ rarg.addStringValue("host", host);
+ rarg.addStringValue("uri", adminInterface);
+ argSet.addRepeatRecord(rarg);
+ num++;
+ } else if (state == 1) {
+ if (!eeInterface.equals("")) {
+ rarg = CMS.createArgBlock();
+ rarg.addStringValue("type", "ee");
+ rarg.addStringValue("prefix", "https");
+ rarg.addIntegerValue("port",
+ Integer.valueOf(CMS.getEESSLPort()).intValue());
+ rarg.addStringValue("host", host);
+ rarg.addStringValue("uri", eeInterface);
+ argSet.addRepeatRecord(rarg);
+ num++;
+ }
+ if (!agentInterface.equals("")) {
+ rarg = CMS.createArgBlock();
+ rarg.addStringValue("type", "agent");
+ rarg.addStringValue("prefix", "https");
+ rarg.addIntegerValue("port",
+ Integer.valueOf(CMS.getAgentPort()).intValue());
+ rarg.addStringValue("host", host);
+ rarg.addStringValue("uri", agentInterface);
+ argSet.addRepeatRecord(rarg);
+ num++;
+ }
+ }
+ header.addIntegerValue("totalRecordCount", num);
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java
new file mode 100644
index 000000000..e5852cf59
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModulePanel.java
@@ -0,0 +1,330 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import com.netscape.certsrv.apps.CMS;
+
+import com.netscape.cmsutil.crypto.*;
+import java.util.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.pkcs11.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class ModulePanel extends WizardPanelBase {
+ private CryptoManager mCryptoManager = null;
+ private Vector mSupportedModules = null;
+ private Vector mOtherModules = null;
+ private Hashtable mCurrModTable = new Hashtable();
+ private WizardServlet mServlet = null;
+ public ModulePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Key Store");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Key Store");
+ setId(id);
+ mServlet = servlet;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putBoolean("preop.ModulePanel.done",false);
+ }
+
+ public void loadCurrModTable() {
+ try {
+ // getting existing modules
+ mCryptoManager = CryptoManager.getInstance();
+ Enumeration modules = mCryptoManager.getModules();
+
+ while (modules.hasMoreElements()) {
+ PK11Module mod = (PK11Module) modules.nextElement();
+
+ CMS.debug("ModulePanel: got module " + mod.getName());
+ mCurrModTable.put(mod.getName(), mod);
+ } // while
+ } catch (Exception e) {
+ CMS.debug(
+ "ModulePanel: Exception caught in loadCurrModTable: "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+ }
+
+ /*
+ * Modules not listed as supported modules
+ */
+ public void loadOtherModules() {
+ Enumeration m = mCurrModTable.elements();
+
+ mOtherModules = new Vector();
+ while (m.hasMoreElements()) {
+ PK11Module mod = (PK11Module) m.nextElement();
+ Enumeration s = mSupportedModules.elements();
+ boolean found = false;
+
+ while (s.hasMoreElements()) {
+ Module sm = (Module) s.nextElement();
+
+ if (mod.getName().equals(sm.getCommonName())) {
+ found = true;
+ break;
+ } else {
+ found = false;
+ }
+ }// while
+ if (!found) {
+ // unsupported, use common name as user friendly name
+ Module module = new Module(mod.getName(), mod.getName());
+
+ loadModTokens(module, mod);
+ module.setFound(true);
+ mOtherModules.addElement((Object) module);
+ break;
+ }
+ }// while
+ }
+
+ /*
+ * find all tokens belonging to a module and load the Module
+ */
+ public void loadModTokens(Module module, PK11Module mod) {
+ Enumeration tokens = mod.getTokens();
+
+ while (tokens.hasMoreElements()) {
+ try {
+ CryptoToken token = (CryptoToken) tokens.nextElement();
+
+ CMS.debug("ModulePanel: token nick name=" + token.getName());
+ CMS.debug("ModulePanel: token logged in?" + token.isLoggedIn());
+ CMS.debug("ModulePanel: token is present?" + token.isPresent());
+ if (!token.getName().equals("Internal Crypto Services Token") &&
+ !token.getName().equals("NSS Generic Crypto Services")) {
+ module.addToken(token);
+ } else {
+ CMS.debug(
+ "ModulePanel: token " + token.getName()
+ + " not to be added");
+ }
+
+ } catch (TokenException ex) {
+ CMS.debug("ModulePanel:" + ex.toString());
+ }
+ }
+ }
+
+ /*
+ * Modules unsupported by the system will not be included
+ */
+ public void loadSupportedModules() {
+
+ // getting supported security modules
+ // a Vectgor of Modules
+ mSupportedModules = new Vector();
+ // read from conf store all supported modules
+ try {
+ int count = CMS.getConfigStore().getInteger(
+ "preop.configModules.count");
+
+ CMS.debug("ModulePanel: supported modules count= " + count);
+ for (int i = 0; i < count; i++) {
+ String cn = CMS.getConfigStore().getString(
+ "preop.configModules.module" + i + ".commonName");
+ String pn = CMS.getConfigStore().getString(
+ "preop.configModules.module" + i + ".userFriendlyName");
+ String img = CMS.getConfigStore().getString(
+ "preop.configModules.module" + i + ".imagePath");
+
+ if ((cn == null) || (cn.equals(""))) {
+ break;
+ }
+
+ CMS.debug("ModulePanel: got from config module: " + cn);
+ // create a Module object
+ Module module = new Module(cn, pn, img);
+
+ if (mCurrModTable.containsKey(cn)) {
+ CMS.debug("ModulePanel: module found: " + cn);
+ module.setFound(true);
+ // add token info to module vector
+ PK11Module m = (PK11Module) mCurrModTable.get(cn);
+
+ loadModTokens(module, m);
+ }
+
+ CMS.debug("ModulePanel: adding module " + cn);
+ // add module to set
+ if (!mSupportedModules.contains(module)) {
+ mSupportedModules.addElement((Object) module);
+ }
+ }// for
+
+ } catch (Exception e) {
+ CMS.debug(
+ "ModulePanel: Exception caught in loadSupportedModules(): "
+ + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+ }
+
+ public PropertySet getUsage() {
+ // it a token choice. Available tokens are discovered dynamically so
+ // can't be a real CHOICE
+ PropertySet set = new PropertySet();
+
+ Descriptor tokenDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ null, /* default parameter */
+ "module token selection");
+
+ set.add("choice", tokenDesc);
+
+ return set;
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ boolean s = cs.getBoolean("preop.ModulePanel.done",
+ false);
+
+ if (s != true) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+
+ return false;
+ }
+
+ public boolean hasSubPanel() {
+ return true;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("ModulePanel: display()");
+ context.put("title", "Key Store");
+
+ loadCurrModTable();
+ loadSupportedModules();
+ loadOtherModules();
+
+ IConfigStore config = CMS.getConfigStore();
+
+ try {
+ String s = config.getString("preop.module.token",
+ "Internal Key Storage Token");
+
+ context.put("defTok", s);
+ } catch (Exception e) {
+ CMS.debug("ModulePanel:" + e.toString());
+ }
+
+ context.put("status", "display");
+ context.put("oms", mOtherModules);
+ context.put("sms", mSupportedModules);
+ // context.put("status_token", "None");
+ String subpanelno = String.valueOf(getPanelNo()+1);
+ CMS.debug("ModulePanel subpanelno =" +subpanelno);
+ context.put("subpanelno", subpanelno);
+ context.put("panel", "admin/console/config/modulepanel.vm");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ boolean hasErr = false;
+
+ try {
+ // get the value of the choice
+ String select = HttpInput.getID(request, "choice");
+
+ if (select == null) {
+ CMS.debug("ModulePanel: no choice selected");
+ hasErr = true;
+ throw new IOException("choice not found");
+ }
+
+ IConfigStore config = CMS.getConfigStore();
+ String oldtokenname = config.getString("preop.module.token", "");
+ if (!oldtokenname.equals(select))
+ mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
+
+ if (hasErr == false) {
+ config.putString("preop.module.token", select);
+ config.putBoolean("preop.ModulePanel.done", true);
+ }
+ config.commit(false);
+ context.put("updateStatus", "success");
+ } catch (Exception e) {
+ CMS.debug("ModulePanel: Exception caught: " + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ context.put("updateStatus", "failure");
+ }
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Security Module");
+ context.put("panel", "admin/console/config/modulepanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java
new file mode 100644
index 000000000..9230ef5b7
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/ModuleServlet.java
@@ -0,0 +1,86 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.apps.CMS;
+
+
+public class ModuleServlet extends BaseServlet {
+
+ /**
+ * Collect information on where keys are to be generated.
+ * Once collected, write to CS.cfg:
+ * "preop.module=soft"
+ * or
+ * "preop.module=hard"
+ *
+ * <ul>
+ * <li>http.param selection "soft" or "hard" for software token or hardware token
+ * </ul>
+ */
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ Template template = null;
+
+ CMS.debug("ModuleServlet: in ModuleServlet");
+ try {
+
+ // get the value of the selection
+ String selection = request.getParameter("selection");
+
+ if (selection != null) {
+
+ if (selection.equals("soft")) {
+ CMS.debug("ModuleServlet: user selected software");
+ // XXX
+ CMS.getConfigStore().putString("preop.module", "soft");
+ CMS.getConfigStore().commit(false);
+ response.sendRedirect("size");
+ } else if (selection.equals("hard")) {
+ CMS.debug("ModuleServlet: user selected hardware");
+ // YYY
+ CMS.getConfigStore().putString("preop.module", "hard");
+ CMS.getConfigStore().commit(false);
+ response.sendRedirect("size");
+ } else {
+ CMS.debug("ModuleServlet: illegal selection: " + selection);
+ context.put("error", "failed selection");
+ }
+
+ } else {
+ CMS.debug("ModuleServlet: no selection");
+ }
+
+ template = Velocity.getTemplate("admin/console/config/module.vm");
+ } catch (Exception e) {
+ CMS.debug("ModuleServlet: Exception caught: " + e.toString());
+ System.err.println("Exception caught: " + e.toString());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java
new file mode 100644
index 000000000..9e0b3c863
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/NamePanel.java
@@ -0,0 +1,986 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import java.util.*;
+import java.io.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.dbs.certdb.*;
+
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.certsrv.profile.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.base.*;
+import java.net.*;
+import java.security.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.KeyPairGenerator;
+
+import netscape.security.x509.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class NamePanel extends WizardPanelBase {
+ private Vector 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();
+
+ 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 c = mCerts.elements();
+
+ while (c.hasMoreElements()) {
+ Cert 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 c = mCerts.elements();
+ IConfigStore config = CMS.getConfigStore();
+
+ while (c.hasMoreElements()) {
+ Cert 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 c = mCerts.elements();
+
+ while (c.hasMoreElements()) {
+ Cert 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 c = mCerts.elements();
+
+ while (c.hasMoreElements()) {
+ Cert 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");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java
new file mode 100644
index 000000000..2bc5f94fc
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RegisterUser.java
@@ -0,0 +1,255 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.usrgrp.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import com.netscape.certsrv.connector.*;
+import com.netscape.certsrv.ca.*;
+
+/**
+ * This servlet creates a TPS user in the CA,
+ * and it associates TPS's server certificate to
+ * the user. Finally, it addes the user to the
+ * administrator group. This procedure will
+ * allows TPS to connect to the CA for certificate
+ * issuance.
+ */
+public class RegisterUser extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+ private String mGroupName = null;
+
+ public RegisterUser() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("RegisterUser: initializing...");
+ super.init(sc);
+ CMS.debug("RegisterUser: done initializing...");
+ mGroupName = sc.getInitParameter("GroupName");
+ CMS.debug("RegisterUser: group name " + mGroupName);
+ }
+
+ /**
+ * Process the HTTP request.
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateUpdater: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = null;
+ try {
+ authToken = authenticate(cmsReq);
+ CMS.debug("RegisterUser authentication successful.");
+ } catch (Exception e) {
+ CMS.debug("RegisterUser: authentication failed.");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ if (authToken == null) {
+ CMS.debug("RegisterUser: authentication failed.");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ AuthzToken authzToken = null;
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
+ CMS.debug("RegisterUser authorization successful.");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ // create user and add certificate
+ String uid = httpReq.getParameter("uid");
+ String name = httpReq.getParameter("name");
+ String certsString = httpReq.getParameter("certificate");
+ CMS.debug("RegisterUser got uid=" + uid);
+ CMS.debug("RegisterUser got name=" + name);
+ CMS.debug("RegisterUser got certsString=" + certsString);
+
+ IUGSubsystem ugsys = (IUGSubsystem)CMS.getSubsystem(CMS.SUBSYSTEM_UG);
+
+ IUser user = null;
+ boolean foundByCert = false;
+ X509Certificate certs[] = new X509Certificate[1];
+ try {
+
+ byte bCert[] = null;
+ X509CertImpl cert = null;
+ bCert = (byte[]) (com.netscape.osutil.OSUtil.AtoB(certsString));
+ cert = new X509CertImpl(bCert);
+ certs[0] = (X509Certificate)cert;
+
+ // test to see if the cert already belongs to a user
+ ICertUserLocator cul = ugsys.getCertUserLocator();
+ com.netscape.certsrv.usrgrp.Certificates c =
+ new com.netscape.certsrv.usrgrp.Certificates(certs);
+ user = (IUser) cul.locateUser(c);
+ } catch (Exception ec) {
+ CMS.debug("RegisterUser: exception thrown: "+ec.toString());
+ }
+ if (user == null) {
+ CMS.debug("RegisterUser NOT found user by cert");
+ try {
+ user = ugsys.getUser(uid);
+ CMS.debug("RegisterUser found user by uid "+uid);
+ } catch (Exception eee) {
+ }
+ } else {
+ foundByCert = true;
+ CMS.debug("RegisterUser found user by cert");
+ }
+
+ try {
+
+ if (user == null) {
+ // create user only if such user does not exist
+ user = ugsys.createUser(uid);
+ user.setFullName(name);
+ user.setState("1");
+ user.setUserType("");
+ user.setEmail("");
+ user.setPhone("");
+ user.setPassword("");
+ ugsys.addUser(user);
+ CMS.debug("RegisterUser created user " + uid);
+ }
+
+ user.setX509Certificates(certs);
+ if (!foundByCert) {
+ ugsys.addUserCert(user);
+ CMS.debug("RegisterUser added user certificate");
+ } else
+ CMS.debug("RegisterUser no need to add user certificate");
+ } catch (Exception eee) {
+ CMS.debug("RegisterUser error " + eee.toString());
+ outputError(httpResp, "Error: Certificate malformed");
+ return;
+ }
+
+
+ // add user to the group
+ Enumeration groups = ugsys.findGroups(mGroupName);
+ IGroup group = (IGroup)groups.nextElement();
+ group.addMemberName(user.getUserID());
+ ugsys.modifyGroup(group);
+ CMS.debug("RegisterUser modified group");
+
+ // send success status back to the requestor
+ try {
+ CMS.debug("RegisterUser: Sending response");
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("RegisterUser: Failed to send the XML output");
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java
new file mode 100644
index 000000000..d9ee171d9
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/RestoreKeyCertPanel.java
@@ -0,0 +1,693 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.security.*;
+import java.math.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.certsrv.base.*;
+import java.util.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.util.*;
+import org.mozilla.jss.pkcs12.*;
+import org.mozilla.jss.pkcs11.*;
+import org.mozilla.jss.asn1.*;
+import org.mozilla.jss.crypto.PrivateKey.Type;
+import org.mozilla.jss.pkix.primitive.*;
+import org.mozilla.jss.pkix.primitive.Attribute;
+import com.netscape.cms.servlet.wizard.*;
+import netscape.ldap.*;
+import java.security.interfaces.*;
+
+public class RestoreKeyCertPanel extends WizardPanelBase {
+
+ public RestoreKeyCertPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Import Keys and Certificates");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Import Keys and Certificates");
+ setId(id);
+ }
+
+ /**
+ * Should we skip this panel for the configuration.
+ */
+ public boolean shouldSkip() {
+ CMS.debug("RestoreKeyCertPanel: should skip");
+
+ IConfigStore cs = CMS.getConfigStore();
+ // if we are root, no need to get the certificate chain.
+
+ try {
+ String select = cs.getString("preop.subsystem.select","");
+ if (select.equals("clone")) {
+ return false;
+ }
+ } catch (EBaseException e) {
+ }
+
+ return true;
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ /* clean up if necessary */
+ try {
+ boolean done = cs.getBoolean("preop.restorekeycert.done");
+ cs.putBoolean("preop.restorekeycert.done", false);
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.restorekeycert.done", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Import Keys and Certificates");
+ IConfigStore config = CMS.getConfigStore();
+
+ if (isPanelDone()) {
+
+ try {
+ String s = config.getString("preop.pk12.path", "");
+ String type = config.getString("preop.subsystem.select", "");
+ context.put("path", s);
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("path", "");
+ }
+
+ context.put("password", "");
+ context.put("panel", "admin/console/config/restorekeycertpanel.vm");
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore config = CMS.getConfigStore();
+ String tokenname = "";
+ try {
+ tokenname = config.getString("preop.module.token", "");
+ } catch (Exception e) {
+ }
+
+ if (!tokenname.equals("Internal Key Storage Token"))
+ return;
+
+ // Path can be empty. If this case, we just want to
+ // get to the next panel. Customer has HSM.
+ String s = HttpInput.getString(request, "path");
+ // if (s == null || s.equals("")) {
+ // CMS.debug("RestoreKeyCertPanel validate: path is empty");
+ // throw new IOException("Path is empty");
+ // }
+
+
+ if (s != null && !s.equals("")) {
+ s = HttpInput.getPassword(request, "__password");
+ if (s == null || s.equals("")) {
+ CMS.debug("RestoreKeyCertPanel validate: password is empty");
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Empty password");
+ }
+ }
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException
+ {
+ IConfigStore config = CMS.getConfigStore();
+ String path = HttpInput.getString(request, "path");
+ if (path == null || path.equals("")) {
+ // skip to next panel
+ config.putBoolean("preop.restorekeycert.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+ getConfigEntriesFromMaster(request, response, context);
+ context.put("updateStatus", "success");
+ return;
+ }
+ String pwd = HttpInput.getPassword(request, "__password");
+
+ String tokenn = "";
+ String instanceRoot = "";
+
+ try {
+ tokenn = config.getString("preop.module.token");
+ instanceRoot = config.getString("instanceRoot");
+ } catch (Exception e) {
+ }
+
+ if (tokenn.equals("Internal Key Storage Token")) {
+ byte b[] = new byte[1000000];
+ FileInputStream fis = new FileInputStream(instanceRoot + "/alias/" + path);
+ while (fis.available() > 0)
+ fis.read(b);
+ fis.close();
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(b);
+ StringBuffer reason = new StringBuffer();
+ Password password = new Password(pwd.toCharArray());
+ PFX pfx = null;
+ boolean verifypfx = false;
+ try {
+ pfx = (PFX)(new PFX.Template()).decode(bis);
+ verifypfx = pfx.verifyAuthSafes(password, reason);
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel update: Exception="+e.toString());
+ }
+
+ if (verifypfx) {
+ CMS.debug("RestoreKeyCertPanel verify the PFX.");
+ AuthenticatedSafes safes = pfx.getAuthSafes();
+ Vector pkeyinfo_collection = new Vector();
+ Vector cert_collection = new Vector();
+ for (int i=0; i<safes.getSize(); i++) {
+ try {
+ SEQUENCE scontent = safes.getSafeContentsAt(null, i);
+ for (int j=0; j<scontent.size(); j++) {
+ SafeBag bag = (SafeBag)scontent.elementAt(j);
+ OBJECT_IDENTIFIER oid = bag.getBagType();
+ if (oid.equals(SafeBag.PKCS8_SHROUDED_KEY_BAG)) {
+ EncryptedPrivateKeyInfo privkeyinfo =
+ (EncryptedPrivateKeyInfo)bag.getInterpretedBagContent();
+ PasswordConverter passConverter = new PasswordConverter();
+ PrivateKeyInfo pkeyinfo = privkeyinfo.decrypt(password, new PasswordConverter());
+ Vector pkeyinfo_v = new Vector();
+ pkeyinfo_v.addElement(pkeyinfo);
+ SET bagAttrs = bag.getBagAttributes();
+ for (int k=0; k<bagAttrs.size(); k++) {
+ Attribute attrs = (Attribute)bagAttrs.elementAt(k);
+ OBJECT_IDENTIFIER aoid = attrs.getType();
+ if (aoid.equals(SafeBag.FRIENDLY_NAME)) {
+ SET val = attrs.getValues();
+ ANY ss = (ANY)val.elementAt(0);
+ ByteArrayInputStream bbis = new ByteArrayInputStream(ss.getEncoded());
+ BMPString sss = (BMPString)(new BMPString.Template()).decode(bbis);
+ String s = sss.toString();
+ pkeyinfo_v.addElement(s);
+ }
+ }
+ pkeyinfo_collection.addElement(pkeyinfo_v);
+ } else if (oid.equals(SafeBag.CERT_BAG)) {
+ CertBag cbag = (CertBag)bag.getInterpretedBagContent();
+ OCTET_STRING str = (OCTET_STRING)cbag.getInterpretedCert();
+ byte[] x509cert = str.toByteArray();
+ Vector cert_v = new Vector();
+ cert_v.addElement(x509cert);
+ SET bagAttrs = bag.getBagAttributes();
+
+ if (bagAttrs != null) {
+ for (int k=0; k<bagAttrs.size(); k++) {
+ Attribute attrs = (Attribute)bagAttrs.elementAt(k);
+ OBJECT_IDENTIFIER aoid = attrs.getType();
+ if (aoid.equals(SafeBag.FRIENDLY_NAME)) {
+ SET val = attrs.getValues();
+ ANY ss = (ANY)val.elementAt(0);
+ ByteArrayInputStream bbis = new ByteArrayInputStream(ss.getEncoded());
+ BMPString sss = (BMPString)(new BMPString.Template()).decode(bbis);
+ String s = sss.toString();
+ cert_v.addElement(s);
+ }
+ }
+ }
+
+ cert_collection.addElement(cert_v);
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel update: Exception="+e.toString());
+ }
+ }
+
+ importkeycert(pkeyinfo_collection, cert_collection);
+ } else {
+ context.put("updateStatus", "failure");
+ throw new IOException("The pkcs12 file is not correct.");
+ }
+ }
+
+ String subsystemtype = "";
+ String cstype = "";
+ try {
+ subsystemtype = config.getString("preop.subsystem.select", "");
+ cstype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ }
+ cstype = toLowerCaseSubsystemType(cstype);
+
+ if (subsystemtype.equals("clone")) {
+ CMS.debug("RestoreKeyCertPanel: this is the clone subsystem");
+ boolean cloneReady = isCertdbCloned(request, context);
+ if (!cloneReady) {
+ CMS.debug("RestoreKeyCertPanel update: clone does not have all the certificates.");
+ context.put("errorString", "Make sure you have copied the certificate database over to the clone");
+ context.put("updateStatus", "failure");
+ throw new IOException("Clone is not ready");
+ }
+ }
+
+ config.putBoolean("preop.restorekeycert.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+
+ getConfigEntriesFromMaster(request, response, context);
+ context.put("updateStatus", "success");
+ }
+
+ private void getConfigEntriesFromMaster(HttpServletRequest request,
+ HttpServletResponse response, Context context) throws IOException {
+ try {
+ IConfigStore config = CMS.getConfigStore();
+ String cstype = "";
+ try {
+ cstype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ }
+ cstype = toLowerCaseSubsystemType(cstype);
+
+ String session_id = CMS.getConfigSDSessionId();
+ String sd_hostname = "";
+ int sd_port = -1;
+ String master_hostname = "";
+ int master_port = -1;
+ int master_ee_port = -1;
+ try {
+ sd_hostname = config.getString("securitydomain.host", "");
+ sd_port = config.getInteger("securitydomain.httpsadminport", -1);
+ master_hostname = config.getString("preop.master.hostname", "");
+ master_port = config.getInteger("preop.master.httpsadminport", -1);
+ master_ee_port = config.getInteger("preop.master.httpsport", -1);
+
+ String content = "";
+ if (cstype.equals("ca") || cstype.equals("kra")) {
+ content = "type=request&xmlOutput=true&sessionID="+session_id;
+ CMS.debug("http content=" + content);
+ updateNumberRange(master_hostname, master_ee_port, true, content, "request", response);
+
+ content = "type=serialNo&xmlOutput=true&sessionID="+session_id;
+ updateNumberRange(master_hostname, master_ee_port, true, content, "serialNo", response);
+
+ content = "type=replicaId&xmlOutput=true&sessionID="+session_id;
+ updateNumberRange(master_hostname, master_ee_port, true, content, "replicaId", response);
+ }
+
+ String list = "";
+ try {
+ list = config.getString("preop.cert.list", "");
+ } catch (Exception e) {
+ }
+
+ StringBuffer c1 = new StringBuffer();
+ StringBuffer s1 = new StringBuffer();
+ StringTokenizer tok = new StringTokenizer(list, ",");
+ while (tok.hasMoreTokens()) {
+ String t1 = tok.nextToken();
+ if (t1.equals("sslserver"))
+ continue;
+ c1.append(",");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".nickname,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".dn,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".keytype,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".keyalgorithm,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".privkey.id,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".pubkey.exponent,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".pubkey.modulus,");
+ c1.append("cloning.");
+ c1.append(t1);
+ c1.append(".pubkey.encoded");
+
+
+ if (s1.length()!=0)
+ s1.append(",");
+
+ s1.append(cstype);
+ s1.append(".");
+ s1.append(t1);
+ }
+
+ if (!cstype.equals("ca")) {
+ c1.append(",cloning.ca.hostname,cloning.ca.httpport,cloning.ca.httpsport,cloning.ca.list,cloning.ca.pkcs7,cloning.ca.type");
+ }
+
+ if (cstype.equals("ca")) {
+ /* get ca connector details */
+ if (s1.length()!=0)
+ s1.append(",");
+ s1.append("ca.connector.KRA");
+ }
+
+ content = "op=get&names=cloning.token,instanceId,internaldb.basedn,internaldb.ldapauth.password,internaldb.replication.password,internaldb.ldapconn.host,internaldb.ldapconn.port,internaldb.ldapauth.bindDN"+c1.toString()+"&substores="+s1.toString()+"&xmlOutput=true&sessionID="+session_id;
+ boolean success = updateConfigEntries(master_hostname, master_port, true,
+ "/"+cstype+"/admin/"+cstype+"/getConfigEntries", content, config, response);
+ if (!success) {
+ context.put("errorString", "Failed to get configuration entries from the master");
+ throw new IOException("Failed to get configuration entries from the master");
+ }
+ config.putString("preop.clone.configuration", "true");
+ try {
+ config.commit(false);
+ } catch (Exception ee) {
+ }
+ } catch (IOException eee) {
+ throw eee;
+ } catch (Exception eee) {
+ CMS.debug("RestoreKeyCertPanel: update exception caught:"+eee.toString());
+ }
+
+ } catch (IOException ee) {
+ throw ee;
+ } catch (Exception ee) {
+ }
+ }
+
+ private void deleteExistingCerts() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String list = cs.getString("preop.cert.list", "");
+ StringTokenizer st = new StringTokenizer(list, ",");
+ while (st.hasMoreTokens()) {
+ String s = st.nextToken();
+ if (s.equals("sslserver"))
+ continue;
+ String name = "preop.master."+s+".nickname";
+ String nickname = cs.getString(name, "");
+ CryptoManager cm = CryptoManager.getInstance();
+ X509Certificate xcert = null;
+ try {
+ xcert = cm.findCertByNickname(nickname);
+ } catch (Exception ee) {
+ CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception="+ee.toString());
+ }
+ CryptoToken ct = cm.getInternalKeyStorageToken();
+ CryptoStore store = ct.getCryptoStore();
+ try {
+ store.deleteCert(xcert);
+ } catch (Exception ee) {
+ CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception="+ee.toString());
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel deleteExistingCerts: Exception="+e.toString());
+ }
+ }
+
+ private org.mozilla.jss.crypto.PrivateKey.Type getPrivateKeyType(PublicKey pubkey) {
+ CMS.debug("Key Algorithm '"+pubkey.getAlgorithm()+"'");
+ if (pubkey.getAlgorithm().equals("EC")) {
+ return org.mozilla.jss.crypto.PrivateKey.Type.EC;
+ }
+ return org.mozilla.jss.crypto.PrivateKey.Type.RSA;
+ }
+
+ private void importkeycert(Vector pkeyinfo_collection,
+ Vector cert_collection) throws IOException {
+ CryptoManager cm = null;
+ try {
+ cm = CryptoManager.getInstance();
+ } catch (Exception e) {
+ }
+
+ // delete all existing certificates first
+ deleteExistingCerts();
+
+ for (int i=0; i<pkeyinfo_collection.size(); i++) {
+ try {
+ Vector pkeyinfo_v = (Vector)pkeyinfo_collection.elementAt(i);
+ PrivateKeyInfo pkeyinfo = (PrivateKeyInfo)pkeyinfo_v.elementAt(0);
+ String nickname = (String)pkeyinfo_v.elementAt(1);
+ byte[] x509cert = getX509Cert(nickname, cert_collection);
+ X509Certificate cert = cm.importCACertPackage(x509cert);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ pkeyinfo.encode(bos);
+ byte[] pkey = bos.toByteArray();
+
+ PublicKey publickey = cert.getPublicKey();
+ CryptoToken token = cm.getInternalKeyStorageToken();
+ CryptoStore store = token.getCryptoStore();
+ CMS.debug("RestoreKeyCertPanel deleteCert: this is pk11store");
+ try {
+ store.deleteCert(cert);
+ } catch (Exception ee) {
+ CMS.debug("RestoreKeyCertPanel importKeyCert: Exception="+ee.toString());
+ }
+
+ KeyGenerator kg = token.getKeyGenerator(KeyGenAlgorithm.DES3);
+ SymmetricKey sk = kg.generate();
+ byte iv[] = {0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1};
+ IVParameterSpec param = new IVParameterSpec(iv);
+ Cipher c = token.getCipherContext(EncryptionAlgorithm.DES3_CBC_PAD);
+ c.initEncrypt(sk, param);
+ byte[] encpkey = c.doFinal(pkey);
+
+ KeyWrapper wrapper = token.getKeyWrapper(KeyWrapAlgorithm.DES3_CBC_PAD);
+ wrapper.initUnwrap(sk, param);
+ org.mozilla.jss.crypto.PrivateKey pp = wrapper.unwrapPrivate(encpkey, getPrivateKeyType(publickey), publickey);
+
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel importkeycert: Exception="+e.toString());
+ }
+ }
+
+ for (int i=0; i<cert_collection.size(); i++) {
+ try {
+ Vector cert_v = (Vector)cert_collection.elementAt(i);
+ byte[] cert = (byte[])cert_v.elementAt(0);
+ if (cert_v.size() > 1) {
+ String name = (String)cert_v.elementAt(1);
+ // we need to delete the trusted CA certificate if it is
+ // the same as the ca signing certificate
+ if (isCASigningCert(name)) {
+ X509Certificate certchain = getX509CertFromToken(cert);
+ if (certchain != null) {
+ CryptoToken token = cm.getInternalKeyStorageToken();
+ CryptoStore store = token.getCryptoStore();
+ CMS.debug("RestoreKeyCertPanel deleteCert: this is pk11store");
+ if (store instanceof PK11Store) {
+ try {
+ PK11Store pk11store = (PK11Store)store;
+ pk11store.deleteCertOnly(certchain);
+ } catch (Exception ee) {
+ CMS.debug("RestoreKeyCertPanel importKeyCert: Exception="+ee.toString());
+ }
+ }
+ }
+ }
+
+ X509Certificate xcert = cm.importUserCACertPackage(cert, name);
+ if (name.startsWith("caSigningCert")) {
+ // we need to change the trust attribute to CT
+ InternalCertificate icert = (InternalCertificate)xcert;
+ icert.setSSLTrust(InternalCertificate.TRUSTED_CA
+ | InternalCertificate.TRUSTED_CLIENT_CA
+ | InternalCertificate.VALID_CA);
+ } else if (name.startsWith("auditSigningCert")) {
+ InternalCertificate icert = (InternalCertificate)xcert;
+ icert.setObjectSigningTrust(InternalCertificate.USER | InternalCertificate.VALID_PEER | InternalCertificate.TRUSTED_PEER);
+ }
+ } else
+ cm.importCACertPackage(cert);
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel importkeycert: Exception="+e.toString());
+ }
+ }
+ }
+
+ private boolean isCASigningCert(String name) {
+ String n = "preop.master.signing.nickname";
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String nickname = cs.getString(n);
+ if (nickname.equals(name))
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+
+ return false;
+ }
+
+ private X509Certificate getX509CertFromToken(byte[] cert)
+ throws IOException {
+ try {
+ X509CertImpl impl = new X509CertImpl(cert);
+ String issuer_impl = impl.getIssuerDN().toString();
+ BigInteger serial_impl = impl.getSerialNumber();
+ CryptoManager cm = CryptoManager.getInstance();
+ X509Certificate[] permcerts = cm.getPermCerts();
+ for (int i=0; i<permcerts.length; i++) {
+ String issuer_p = permcerts[i].getSubjectDN().toString();
+ BigInteger serial_p = permcerts[i].getSerialNumber();
+ if (issuer_p.equals(issuer_impl) && serial_p.compareTo(serial_impl) == 0) {
+ return permcerts[i];
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel getX509CertFromToken: Exception="+e.toString());
+ }
+
+ return null;
+ }
+
+ private byte[] getX509Cert(String nickname, Vector cert_collection)
+ throws IOException {
+ for (int i=0; i<cert_collection.size(); i++) {
+ Vector v = (Vector)cert_collection.elementAt(i);
+ byte[] b = (byte[])v.elementAt(0);
+ X509CertImpl impl = null;
+ try {
+ impl = new X509CertImpl(b);
+ } catch (Exception e) {
+ CMS.debug("RestoreKeyCertPanel getX509Cert: Exception="+e.toString());
+ throw new IOException( e.toString() );
+ }
+ Principal subjectdn = impl.getSubjectDN();
+ if (LDAPDN.equals(subjectdn.toString(), nickname))
+ return b;
+ }
+
+ return null;
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context)
+ {
+ context.put("title", "Import Keys and Certificates");
+ context.put("password", "");
+ context.put("path", "");
+ context.put("panel", "admin/console/config/restorekeycertpanel.vm");
+ }
+
+ private boolean isCertdbCloned(HttpServletRequest request,
+ Context context) {
+ IConfigStore config = CMS.getConfigStore();
+ String certList = "";
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ certList = config.getString("preop.cert.list");
+ StringTokenizer st = new StringTokenizer(certList, ",");
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken();
+ if (token.equals("sslserver"))
+ continue;
+ String tokenname = config.getString("preop.module.token", "");
+ CryptoToken tok = cm.getTokenByName(tokenname);
+ CryptoStore store = tok.getCryptoStore();
+ String name1 = "preop.master."+token+".nickname";
+ String nickname = config.getString(name1, "");
+ if (!tokenname.equals("Internal Key Storage Token") &&
+ !tokenname.equals("internal"))
+ nickname = tokenname+":"+nickname;
+
+ CMS.debug("RestoreKeyCertPanel isCertdbCloned: "+nickname);
+ X509Certificate cert = cm.findCertByNickname(nickname);
+ if (cert == null)
+ return false;
+ }
+ } catch (Exception e) {
+ context.put("errorString", "Check your CS.cfg for cloning");
+ return false;
+ }
+
+ return true;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java
new file mode 100644
index 000000000..f336cd84c
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SavePKCS12Panel.java
@@ -0,0 +1,159 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import org.mozilla.jss.util.Password;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import java.io.*;
+import java.net.URL;
+import com.netscape.certsrv.base.*;
+import java.util.*;
+import java.security.*;
+import java.security.cert.*;
+import java.security.KeyPair;
+import netscape.security.util.*;
+import netscape.security.pkcs.*;
+import netscape.security.x509.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.asn1.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.pkcs12.*;
+import org.mozilla.jss.pkix.primitive.*;
+import org.mozilla.jss.crypto.X509Certificate;
+import org.mozilla.jss.crypto.PrivateKey;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class SavePKCS12Panel extends WizardPanelBase {
+
+ public SavePKCS12Panel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Save Keys and Certificates");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Save Keys and Certificates");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ }
+
+ public boolean shouldSkip() {
+ IConfigStore cs = CMS.getConfigStore();
+
+ try {
+ boolean enable = cs.getBoolean("preop.backupkeys.enable", false);
+ if (!enable)
+ return true;
+ } catch (Exception e) {
+ }
+
+ return false;
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.backupkeycert.done", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ return set;
+ }
+
+ public boolean isSubPanel() {
+ return true;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Save Keys and Certificates");
+ IConfigStore config = CMS.getConfigStore();
+ String subsystemtype = "";
+ try {
+ subsystemtype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ }
+
+ subsystemtype = toLowerCaseSubsystemType(subsystemtype);
+
+ context.put("panel", "admin/console/config/savepkcs12panel.vm");
+ context.put("subsystemtype", subsystemtype);
+ context.put("errorString", "");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response, Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ context.put("title", "Save Keys and Certificates");
+ context.put("panel", "admin/console/config/savepkcs12panel.vm");
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context)
+ {
+ context.put("title", "Save Keys and Certificates");
+ context.put("panel", "admin/console/config/savepkcs12panel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java
new file mode 100644
index 000000000..4f0a19d8b
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainLogin.java
@@ -0,0 +1,81 @@
+// --- 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.util.*;
+import java.net.*;
+import org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.base.*;
+
+public class SecurityDomainLogin extends BaseServlet {
+
+ public boolean authenticate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ return true;
+ }
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ Template template = null;
+
+ try {
+ String url = request.getParameter("url");
+ url = URLDecoder.decode(url, "UTF-8");
+ URL u = null;
+ if (url != null) {
+ u = new URL(url);
+ }
+ int index = url.indexOf("subsystem=");
+ String subsystem = "";
+ if (index > 0) {
+ subsystem = url.substring(index+10);
+ int index1 = subsystem.indexOf("&");
+ if (index1 > 0)
+ subsystem = subsystem.substring(0, index1);
+ }
+ context.put("sd_uid", "");
+ context.put("sd_pwd", "");
+ context.put("url", url);
+ context.put("host", u.getHost());
+ context.put("sdhost", CMS.getEESSLHost());
+ if (subsystem.equals("KRA")) {
+ subsystem = "DRM";
+ }
+ context.put("subsystem", subsystem);
+ // The "securitydomain.name" property ONLY resides in the "CS.cfg"
+ // associated with the CS subsystem hosting the security domain.
+ IConfigStore cs = CMS.getConfigStore();
+ String sdname = cs.getString("securitydomain.name", "");
+ context.put("name", sdname);
+ template = Velocity.getTemplate("admin/console/config/securitydomainloginpanel.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java
new file mode 100644
index 000000000..6abdd8618
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainPanel.java
@@ -0,0 +1,500 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import org.mozilla.jss.crypto.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.cmsutil.crypto.*;
+import java.net.*;
+import java.io.*;
+import java.util.*;
+import java.security.cert.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class SecurityDomainPanel extends WizardPanelBase {
+
+ public SecurityDomainPanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Security Domain");
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Security Domain");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putString("preop.securitydomain.select", "");
+ cs.putString("securitydomain.select", "");
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String s = cs.getString("preop.securitydomain.select", "");
+ if (s == null || s.equals("")) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ context.put("title", "Security Domain");
+ IConfigStore config = CMS.getConfigStore();
+ String errorString = "";
+ String default_admin_url = "";
+ String name = "";
+ String cstype = "";
+
+ try {
+ default_admin_url = config.getString("preop.securitydomain.admin_url", "");
+ name = config.getString("preop.securitydomain.name", "");
+ cstype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ if (isPanelDone()) {
+ try {
+ String s = config.getString("preop.securitydomain.select");
+
+ if (s.equals("new")) {
+ context.put("check_newdomain", "checked");
+ context.put("check_existingdomain", "");
+ } else if (s.equals("existing")) {
+ context.put("check_newdomain", "");
+ context.put("check_existingdomain", "checked");
+ }
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+ } else {
+ context.put("check_newdomain", "checked");
+ context.put("check_existingdomain", "");
+ }
+
+ try {
+ context.put("cstype", config.getString("cs.type"));
+ context.put("wizardname", config.getString("preop.wizard.name"));
+ context.put("panelname", "Security Domain Configuration");
+ context.put("systemname", config.getString("preop.system.name"));
+ context.put("machineName", config.getString("machineName"));
+ context.put("http_ee_port", CMS.getEENonSSLPort());
+ context.put("https_agent_port", CMS.getAgentPort());
+ context.put("https_ee_port", CMS.getEESSLPort());
+ context.put("https_admin_port", CMS.getAdminPort());
+ context.put("sdomainAdminURL", default_admin_url);
+ } catch (EBaseException e) {}
+
+ context.put("panel", "admin/console/config/securitydomainpanel.vm");
+ context.put("errorString", errorString);
+
+ // from default_admin_url, find hostname, if fully qualified, get
+ // network domain name and generate default security domain name
+ if (name.equals("") && (default_admin_url != null)) {
+ try {
+ URL u = new URL(default_admin_url);
+
+ String hostname = u.getHost();
+ StringTokenizer st = new StringTokenizer(hostname, ".");
+ boolean first = true;
+ int numTokens = st.countTokens();
+ int count = 0;
+ String defaultDomain = "";
+ StringBuffer sb = new StringBuffer();
+ while (st.hasMoreTokens()) {
+ count++;
+ String n = st.nextToken();
+ if (first) { //skip the hostname
+ first = false;
+ continue;
+ }
+ if (count == numTokens) // skip the last element (e.g. com)
+ continue;
+ sb.append((defaultDomain.length()==0)? "":" ");
+ sb.append(capitalize(n));
+ }
+ defaultDomain = sb.toString() + " "+ "Domain";
+ name = defaultDomain;
+ CMS.debug("SecurityDomainPanel: defaultDomain generated:"+ name);
+ } catch (MalformedURLException e) {
+ errorString = "Malformed URL";
+ // not being able to come up with default domain name is ok
+ }
+ }
+ context.put("sdomainName", name);
+
+ if( default_admin_url != null ) {
+ String r = null;
+
+ try {
+ // check to see if "default" security domain exists
+ // on local machine
+ URL u = new URL( default_admin_url );
+
+ String hostname = u.getHost();
+ int port = u.getPort();
+ ConfigCertApprovalCallback
+ certApprovalCallback = new ConfigCertApprovalCallback();
+ r = pingCS( hostname, port, true, certApprovalCallback );
+ } catch (Exception e) {
+ CMS.debug( "SecurityDomainPanel: exception caught: "
+ + e.toString() );
+ }
+
+ if( r != null ) {
+ // "default" security domain exists on local machine;
+ // fill "sdomainURL" in with "default" security domain
+ // as an initial "guess"
+ CMS.debug( "SecurityDomainPanel: pingCS returns: "+r );
+ context.put( "sdomainURL", default_admin_url );
+ } else {
+ // "default" security domain does NOT exist on local machine;
+ // leave "sdomainURL" blank
+ CMS.debug( "SecurityDomainPanel: pingCS no successful response" );
+ context.put( "sdomainURL", "" );
+ }
+ }
+
+ // Information for "existing" Security Domain CAs
+ String initDaemon = "pki-cad";
+ String instanceId = "&lt;security_domain_instance_name&gt;";
+ String os = System.getProperty( "os.name" );
+ if( os.equalsIgnoreCase( "Linux" ) ) {
+ context.put( "initCommand", "/sbin/service " + initDaemon );
+ context.put( "instanceId", instanceId );
+ } else {
+ /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
+ context.put( "initCommand", "/etc/init.d/" + initDaemon );
+ context.put( "instanceId", instanceId );
+ }
+ }
+
+ public static String capitalize(String s) {
+ if (s.length() == 0) {
+ return s;
+ } else {
+ return s.substring(0,1).toUpperCase() + s.substring(1);
+ }
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+
+ String select = HttpInput.getID(request, "choice");
+ if (select.equals("newdomain")) {
+ String name = HttpInput.getSecurityDomainName(request, "sdomainName");
+ if (name == null || name.equals("")) {
+ initParams(request, context);
+ context.put("updateStatus", "validate-failure");
+ throw new IOException("Missing name value for the security domain");
+ }
+ } else if (select.equals("existingdomain")) {
+ CMS.debug( "SecurityDomainPanel: validating "
+ + "SSL Admin HTTPS . . ." );
+ String admin_url = HttpInput.getURL( request, "sdomainURL" );
+ if( admin_url == null || admin_url.equals("") ) {
+ initParams( request, context );
+ context.put("updateStatus", "validate-failure");
+ throw new IOException( "Missing SSL Admin HTTPS url value "
+ + "for the security domain" );
+ } else {
+ String r = null;
+
+ try {
+ URL u = new URL( admin_url );
+
+ String hostname = u.getHost();
+ int admin_port = u.getPort();
+ ConfigCertApprovalCallback
+ certApprovalCallback = new ConfigCertApprovalCallback();
+ r = pingCS( hostname, admin_port, true,
+ certApprovalCallback );
+ } catch( Exception e ) {
+ CMS.debug( "SecurityDomainPanel: exception caught: "
+ + e.toString() );
+ context.put("updateStatus", "validate-failure");
+ throw new IOException( "Illegal SSL Admin HTTPS url value "
+ + "for the security domain" );
+ }
+
+ if (r != null) {
+ CMS.debug("SecurityDomainPanel: pingAdminCS returns: "
+ + r );
+ context.put( "sdomainURL", admin_url );
+ } else {
+ CMS.debug( "SecurityDomainPanel: pingAdminCS "
+ + "no successful response for SSL Admin HTTPS" );
+ context.put( "sdomainURL", "" );
+ }
+ }
+ }
+ }
+
+ public void initParams(HttpServletRequest request, Context context)
+ throws IOException
+ {
+ IConfigStore config = CMS.getConfigStore();
+ try {
+ context.put("cstype", config.getString("cs.type"));
+ } catch (Exception e) {
+ }
+
+ String select = request.getParameter("choice");
+ if (select.equals("newdomain")) {
+ context.put("check_newdomain", "checked");
+ context.put("check_existingdomain", "");
+ } else if (select.equals("existingdomain")) {
+ context.put("check_newdomain", "");
+ context.put("check_existingdomain", "checked");
+ }
+
+ String name = request.getParameter("sdomainName");
+ if (name == null)
+ name = "";
+ context.put("sdomainName", name);
+
+ String admin_url = request.getParameter("sdomainURL");
+ if (admin_url == null)
+ admin_url = "";
+ context.put("sdomainURL", admin_url);
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ String errorString = "";
+ String select = HttpInput.getID(request, "choice");
+
+ if (select == null) {
+ CMS.debug("SecurityDomainPanel: choice not found");
+ context.put("updateStatus", "failure");
+ throw new IOException("choice not found");
+ }
+ IConfigStore config = CMS.getConfigStore();
+
+ if (select.equals("newdomain")) {
+ config.putString("preop.securitydomain.select", "new");
+ config.putString("securitydomain.select", "new");
+ config.putString("preop.securitydomain.name",
+ HttpInput.getDomainName(request, "sdomainName"));
+ config.putString("securitydomain.name",
+ HttpInput.getDomainName(request, "sdomainName"));
+ config.putString("securitydomain.host",
+ CMS.getEENonSSLHost());
+ config.putString("securitydomain.httpport",
+ CMS.getEENonSSLPort());
+ config.putString("securitydomain.httpsagentport",
+ CMS.getAgentPort());
+ config.putString("securitydomain.httpseeport",
+ CMS.getEESSLPort());
+ config.putString("securitydomain.httpsadminport",
+ CMS.getAdminPort());
+
+ // make sure the subsystem certificate is issued by the security
+ // domain
+ config.putString("preop.cert.subsystem.type", "local");
+ config.putString("preop.cert.subsystem.profile", "subsystemCert.profile");
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {}
+
+ String instanceRoot = "";
+ try {
+ instanceRoot = config.getString("instanceRoot", "");
+ } catch (Exception e) {
+ }
+
+ } else if (select.equals("existingdomain")) {
+ config.putString("preop.securitydomain.select", "existing");
+ config.putString("securitydomain.select", "existing");
+
+ // make sure the subsystem certificate is issued by the security
+ // domain
+ config.putString("preop.cert.subsystem.type", "remote");
+ config.putString("preop.cert.subsystem.profile", "caInternalAuthSubsystemCert");
+
+ String admin_url = HttpInput.getURL(request, "sdomainURL");
+ String hostname = "";
+ int admin_port = -1;
+
+ if( admin_url != null ) {
+ try {
+ URL admin_u = new URL( admin_url );
+
+ hostname = admin_u.getHost();
+ admin_port = admin_u.getPort();
+ } catch( MalformedURLException e ) {
+ errorString = "Malformed SSL Admin HTTPS URL";
+ context.put("updateStatus", "failure");
+ throw new IOException( errorString );
+ }
+
+ context.put( "sdomainURL", admin_url );
+ config.putString( "securitydomain.host", hostname );
+ config.putInteger( "securitydomain.httpsadminport",
+ admin_port );
+ }
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {}
+
+ ConfigCertApprovalCallback certApprovalCallback = new ConfigCertApprovalCallback();
+ updateCertChain( config, "securitydomain", hostname, admin_port,
+ true, context, certApprovalCallback );
+ } else {
+ CMS.debug("SecurityDomainPanel: invalid choice " + select);
+ errorString = "Invalid choice";
+ context.put("updateStatus", "failure");
+ throw new IOException("invalid choice " + select);
+ }
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+
+ try {
+ context.put("cstype", config.getString("cs.type"));
+ context.put("wizardname", config.getString("preop.wizard.name"));
+ context.put("panelname", "Security Domain Configuration");
+ context.put("systemname", config.getString("preop.system.name"));
+ } catch (EBaseException e) {}
+
+ context.put("errorString", errorString);
+ context.put("updateStatus", "success");
+ }
+
+ /**
+ * If validate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ IConfigStore config = CMS.getConfigStore();
+ String default_admin_url = "";
+ try {
+ initParams(request, context);
+ } catch (IOException e) {
+ }
+
+ try {
+ default_admin_url = config.getString("preop.securitydomain.admin_url", "");
+ } catch (Exception e) {}
+
+ if( default_admin_url != null ) {
+ String r = null;
+
+ try {
+ // check to see if "default" security domain exists
+ // on local machine
+ URL u = new URL( default_admin_url );
+
+ String hostname = u.getHost();
+ int port = u.getPort();
+ ConfigCertApprovalCallback
+ certApprovalCallback = new ConfigCertApprovalCallback();
+ r = pingCS( hostname, port, true, certApprovalCallback );
+ } catch (Exception e) {}
+
+ if( r != null ) {
+ // "default" security domain exists on local machine;
+ // refill "sdomainURL" in with "default" security domain
+ // as an initial "guess"
+ context.put( "sdomainURL", default_admin_url );
+ } else {
+ // "default" security domain does NOT exist on local machine;
+ // leave "sdomainURL" blank
+ context.put( "sdomainURL", "" );
+ }
+ }
+
+ try {
+ context.put("machineName", config.getString("machineName"));
+ context.put("http_ee_port", CMS.getEENonSSLPort());
+ context.put("https_agent_port", CMS.getAgentPort());
+ context.put("https_ee_port", CMS.getEESSLPort());
+ context.put("https_admin_port", CMS.getAdminPort());
+ context.put("sdomainAdminURL",
+ config.getString("preop.securitydomain.admin_url"));
+ } catch (EBaseException e) {}
+
+ // Information for "existing" Security Domain CAs
+ String initDaemon = "pki-cad";
+ String instanceId = "&lt;security_domain_instance_name&gt;";
+ String os = System.getProperty( "os.name" );
+ if( os.equalsIgnoreCase( "Linux" ) ) {
+ context.put( "initCommand", "/sbin/service " + initDaemon );
+ context.put( "instanceId", instanceId );
+ } else {
+ /* default case: e. g. - ( os.equalsIgnoreCase( "SunOS" ) */
+ context.put( "initCommand", "/etc/init.d/" + initDaemon );
+ context.put( "instanceId", instanceId );
+ }
+
+ context.put("title", "Security Domain");
+ context.put("panel", "admin/console/config/securitydomainpanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java
new file mode 100644
index 000000000..dabaee410
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SecurityDomainSessionTable.java
@@ -0,0 +1,100 @@
+// --- 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.util.*;
+import java.io.*;
+import com.netscape.certsrv.base.*;
+
+/**
+ * This object stores the values for IP, uid and group based on the cookie id.
+ */
+public class SecurityDomainSessionTable
+ implements ISecurityDomainSessionTable {
+
+ private Hashtable m_sessions;
+ private long m_timeToLive;
+
+ public SecurityDomainSessionTable(long timeToLive) {
+ m_sessions = new Hashtable();
+ m_timeToLive = timeToLive;
+ }
+
+ public void addEntry(String sessionId, String ip,
+ String uid, String group) {
+ Vector v = new Vector();
+ v.addElement(ip);
+ v.addElement(uid);
+ v.addElement(group);
+ Date d = new Date();
+ long t = d.getTime();
+ v.addElement(Long.valueOf(t));
+ m_sessions.put(sessionId, v);
+ }
+
+ public void removeEntry(String sessionId) {
+ m_sessions.remove(sessionId);
+ }
+
+ public boolean isSessionIdExist(String sessionId) {
+ return m_sessions.containsKey(sessionId);
+ }
+
+ public Enumeration getSessionIds() {
+ return m_sessions.keys();
+ }
+
+ public String getIP(String sessionId) {
+ Vector v = (Vector)m_sessions.get(sessionId);
+ if (v != null)
+ return (String)v.elementAt(0);
+ return null;
+ }
+
+ public String getUID(String sessionId) {
+ Vector v = (Vector)m_sessions.get(sessionId);
+ if (v != null)
+ return (String)v.elementAt(1);
+ return null;
+ }
+
+ public String getGroup(String sessionId) {
+ Vector v = (Vector)m_sessions.get(sessionId);
+ if (v != null)
+ return (String)v.elementAt(2);
+ return null;
+ }
+
+ public long getBeginTime(String sessionId) {
+ Vector v = (Vector)m_sessions.get(sessionId);
+ if (v != null) {
+ Long n = (Long)v.elementAt(3);
+ if (n != null)
+ return n.longValue();
+ }
+ return -1;
+ }
+
+ public long getTimeToLive() {
+ return m_timeToLive;
+ }
+
+ public int getSize() {
+ return m_sessions.size();
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java
new file mode 100644
index 000000000..91564d15e
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SessionTimer.java
@@ -0,0 +1,47 @@
+// --- 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.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.base.*;
+
+public class SessionTimer extends TimerTask {
+ private ISecurityDomainSessionTable m_sessiontable = null;
+
+ public SessionTimer(ISecurityDomainSessionTable table) {
+ super();
+ m_sessiontable = table;
+ }
+
+ public void run() {
+ Enumeration keys = m_sessiontable.getSessionIds();
+ while (keys.hasMoreElements()) {
+ String sessionId = (String)keys.nextElement();
+ long beginTime = m_sessiontable.getBeginTime(sessionId);
+ Date nowDate = new Date();
+ long nowTime = nowDate.getTime();
+ long timeToLive = m_sessiontable.getTimeToLive();
+ if ((nowTime-beginTime) > timeToLive) {
+ m_sessiontable.removeEntry(sessionId);
+ CMS.debug("SessionTimer run: successfully remove the session id entry from the table.");
+ }
+ }
+ }
+}
+
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java
new file mode 100644
index 000000000..0ff27aa01
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/SizePanel.java
@@ -0,0 +1,652 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import java.io.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.util.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.cmsutil.crypto.*;
+
+import java.security.interfaces.RSAPublicKey;
+import java.util.*;
+import java.security.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.crypto.KeyPairGenerator;
+import org.mozilla.jss.pkcs11.PK11KeyPairGenerator;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class SizePanel extends WizardPanelBase {
+ private Vector mCerts = null;
+ private WizardServlet mServlet = null;
+
+ private String default_ecc_curve_name;
+ private String default_rsa_key_size;
+ private boolean mShowSigning = false;
+
+ public SizePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Key Pairs");
+ setId(id);
+ mServlet = servlet;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ Descriptor choiceDesc = new Descriptor(IDescriptor.CHOICE,
+ "default,custom", null, /* no default parameter */
+ "If 'default', the key size will be configured automatically. If 'custom', the key size will be set to the value of the parameter 'custom_size'.");
+
+ set.add("choice", choiceDesc);
+
+ Descriptor customSizeDesc = new Descriptor(IDescriptor.STRING, null, /* no constraint */
+ null, /* no default parameter */
+ "Custom Key Size");
+
+ set.add("custom_size", customSizeDesc);
+
+ return set;
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ /* clean up if necessary*/
+ try {
+ boolean done = cs.getBoolean("preop.SizePanel.done");
+ cs.putBoolean("preop.SizePanel.done", false);
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ boolean s = cs.getBoolean("preop.SizePanel.done", false);
+ if (s != true) {
+ return false;
+ } else {
+ return true;
+ }
+ } catch (EBaseException e) {}
+
+ return false;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ CMS.debug("SizePanel: display()");
+ try {
+ initParams(request, context);
+ } catch (IOException e) {
+ }
+
+ context.put("firsttime", "false");
+ String errorString = "";
+ mCerts = new Vector();
+
+ IConfigStore config = CMS.getConfigStore();
+ try {
+ boolean done = config.getBoolean("preop.SizePanel.done");
+ } catch (Exception e) {
+ context.put("firsttime", "true");
+ }
+
+ try {
+ default_ecc_curve_name = config.getString("keys.ecc.curve.default", "nistp521");
+ } catch (Exception e) {
+ }
+
+ try {
+ default_rsa_key_size = config.getString("keys.rsa.keysize.default", "2048");
+ } catch (Exception e) {
+ }
+
+ try {
+ // same token for now
+ String token = config.getString(PRE_CONF_CA_TOKEN);
+ String certTags = config.getString("preop.cert.list");
+ StringTokenizer st = new StringTokenizer(certTags, ",");
+ mShowSigning = false;
+
+ while (st.hasMoreTokens()) {
+ String certTag = st.nextToken();
+ String nn = config.getString(
+ PCERT_PREFIX + certTag + ".nickname");
+ Cert c = new Cert(token, nn, certTag);
+
+ String s = config.getString(
+ PCERT_PREFIX + certTag + ".keysize.select", "default");
+
+ if (s.equals("default")) {
+ c.setKeyOption("default");
+ }
+ if (s.equals("custom")) {
+ c.setKeyOption("custom");
+ }
+
+ s = config.getString(
+ PCERT_PREFIX + certTag + ".keysize.custom_size",
+ default_rsa_key_size);
+ c.setCustomKeysize(s);
+
+ s = config.getString(
+ PCERT_PREFIX + certTag + ".curvename.custom_name",
+ default_ecc_curve_name);
+ c.setCustomCurvename(s);
+
+ boolean signingRequired = config.getBoolean(
+ PCERT_PREFIX + certTag + ".signing.required",
+ false);
+ c.setSigningRequired(signingRequired);
+ if (signingRequired) mShowSigning = true;
+
+ String userfriendlyname = config.getString(
+ PCERT_PREFIX + certTag + ".userfriendlyname");
+ c.setUserFriendlyName(userfriendlyname);
+ boolean enable = config.getBoolean(PCERT_PREFIX+certTag+".enable", true);
+ c.setEnable(enable);
+ mCerts.addElement(c);
+ }// while
+ } catch (Exception e) {
+ CMS.debug("SizePanel: display() " + e.toString());
+ }
+ CMS.debug("SizePanel: display() 1");
+
+ context.put("show_signing", mShowSigning ? "true" : "false");
+ context.put("certs", mCerts);
+ context.put("errorString", errorString);
+ context.put("default_keysize", default_rsa_key_size);
+ context.put("default_ecc_curvename", default_ecc_curve_name);
+ context.put("panel", "admin/console/config/sizepanel.vm");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException, NumberFormatException {
+ CMS.debug("SizePanel: update()");
+ boolean hasErr = false;
+ IConfigStore config = CMS.getConfigStore();
+ String select1 = "";
+ String val1 = null;
+ boolean hasChanged = false;
+ try {
+ select1 = config.getString("preop.subsystem.select", "");
+ } catch (Exception e) {
+ }
+
+ context.put("firsttime", "false");
+ boolean done = false;
+ try {
+ done = config.getBoolean("preop.SizePanel.done");
+ } catch (Exception e) {
+ context.put("firsttime", "true");
+ if (select1.equals("clone")) {
+ // preset the sslserver dn for cloning case
+ try {
+ String val = config.getString("preop.cert.sslserver.dn", "");
+ config.putString("preop.cert.sslserver.dn", val+",o=clone");
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ String token = "";
+ try {
+ token = config.getString(PRE_CONF_CA_TOKEN, "");
+ Enumeration c = mCerts.elements();
+
+ while (c.hasMoreElements()) {
+ Cert cert = (Cert) c.nextElement();
+ String ct = cert.getCertTag();
+ boolean enable = config.getBoolean(PCERT_PREFIX+ct+".enable", true);
+ if (!enable)
+ continue;
+
+ String keytype = HttpInput.getKeyType(request, ct + "_keytype"); // rsa or ecc
+
+ String keyalgorithm = HttpInput.getString(request, ct + "_keyalgorithm");
+ if (keyalgorithm == null) {
+ if (keytype != null && keytype.equals("ecc")) {
+ keyalgorithm = "SHA256withEC";
+ } else {
+ keyalgorithm = "SHA256withRSA";
+ }
+ }
+
+ String signingalgorithm = HttpInput.getString(request, ct + "_signingalgorithm");
+ if (signingalgorithm == null) {
+ signingalgorithm = keyalgorithm;
+ }
+
+ String select = HttpInput.getID(request, ct + "_choice");
+
+ if (select == null) {
+ CMS.debug("SizePanel: " + ct + "_choice not found");
+ throw new IOException(
+ "SizePanel: " + ct + "_choice not found");
+ }
+ CMS.debug(
+ "SizePanel: update() keysize choice selected:" + select);
+ String oldkeysize =
+ config.getString(PCERT_PREFIX+ct+".keysize.size", "");
+ String oldkeytype =
+ config.getString(PCERT_PREFIX + ct + ".keytype", "");
+ String oldkeyalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".keyalgorithm", "");
+ String oldsigningalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".signingalgorithm", "");
+ String oldcurvename =
+ config.getString(PCERT_PREFIX + ct + ".curvename.name", "");
+
+ if (select.equals("default")) {
+ // XXXrenaming these...keep for now just in case
+ config.putString("preop.keysize.select", "default");
+ if (keytype != null && keytype.equals("ecc")) {
+ config.putString("preop.curvename.custom_name",
+ default_ecc_curve_name);
+ config.putString("preop.curvename.name", default_ecc_curve_name);
+ } else {
+ config.putString("preop.keysize.custom_size",
+ default_rsa_key_size);
+ config.putString("preop.keysize.size", default_rsa_key_size);
+ }
+
+ config.putString(PCERT_PREFIX + ct + ".keytype", keytype);
+ config.putString(PCERT_PREFIX + ct + ".keyalgorithm", keyalgorithm);
+ config.putString(PCERT_PREFIX + ct + ".signingalgorithm", signingalgorithm);
+ config.putString(PCERT_PREFIX + ct + ".keysize.select",
+ "default");
+ if (keytype != null && keytype.equals("ecc")) {
+ config.putString(PCERT_PREFIX + ct +
+ ".curvename.custom_name",
+ default_ecc_curve_name);
+ config.putString(PCERT_PREFIX + ct + ".curvename.name",
+ default_ecc_curve_name);
+ } else {
+ config.putString(PCERT_PREFIX + ct +
+ ".keysize.custom_size",
+ default_rsa_key_size);
+ config.putString(PCERT_PREFIX + ct + ".keysize.size",
+ default_rsa_key_size);
+ }
+ } else if (select.equals("custom")) {
+ // XXXrenaming these...keep for now just in case
+ config.putString("preop.keysize.select", "custom");
+ if (keytype != null && keytype.equals("ecc")) {
+ config.putString("preop.curvename.name",
+ HttpInput.getString(request, ct + "_custom_curvename"));
+ config.putString("preop.curvename.custom_name",
+ HttpInput.getString(request, ct + "_custom_curvename"));
+ } else {
+ config.putString("preop.keysize.size",
+ HttpInput.getKeySize(request, ct + "_custom_size", keytype));
+ config.putString("preop.keysize.custom_size",
+ HttpInput.getKeySize(request, ct + "_custom_size", keytype));
+ }
+
+ config.putString(PCERT_PREFIX + ct + ".keytype", keytype);
+ config.putString(PCERT_PREFIX + ct + ".keyalgorithm", keyalgorithm);
+ config.putString(PCERT_PREFIX + ct + ".signingalgorithm", signingalgorithm);
+ config.putString(PCERT_PREFIX + ct + ".keysize.select",
+ "custom");
+
+ if (keytype != null && keytype.equals("ecc")) {
+ config.putString(PCERT_PREFIX + ct + ".curvename.custom_name",
+ HttpInput.getString(request, ct + "_custom_curvename"));
+ config.putString(PCERT_PREFIX + ct + ".curvename.name",
+ HttpInput.getString(request, ct + "_custom_curvename"));
+ } else {
+ config.putString(PCERT_PREFIX + ct + ".keysize.custom_size",
+ HttpInput.getKeySize(request, ct + "_custom_size"));
+ config.putString(PCERT_PREFIX + ct + ".keysize.size",
+ HttpInput.getKeySize(request, ct + "_custom_size"));
+ }
+ } else {
+ CMS.debug("SizePanel: invalid choice " + select);
+ throw new IOException("invalid choice " + select);
+ }
+
+ String newkeysize =
+ config.getString(PCERT_PREFIX+ct+".keysize.size", "");
+ String newkeytype =
+ config.getString(PCERT_PREFIX + ct + ".keytype", "");
+ String newkeyalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".keyalgorithm", "");
+ String newsigningalgorithm =
+ config.getString(PCERT_PREFIX + ct + ".signingalgorithm", "");
+ String newcurvename =
+ config.getString(PCERT_PREFIX+ct+".curvename.name", "");
+
+ if (!oldkeysize.equals(newkeysize) ||
+ !oldkeytype.equals(newkeytype) ||
+ !oldkeyalgorithm.equals(newkeyalgorithm) ||
+ !oldsigningalgorithm.equals(newsigningalgorithm) ||
+ !oldcurvename.equals(newcurvename))
+ hasChanged = true;
+ }// while
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ CMS.debug("SizePanel: update() Exception caught at config commit: " + e.toString());
+ }
+
+ val1 = HttpInput.getID(request, "generateKeyPair");
+
+ if (hasChanged || (val1 != null && !val1.equals(""))) {
+ mServlet.cleanUpFromPanel(mServlet.getPanelNo(request));
+ } else if (isPanelDone()) {
+ context.put("updateStatus", "success");
+ return;
+ }
+ } catch (IOException e) {
+ CMS.debug("SizePanel: update() IOException caught: " + e.toString());
+ context.put("updateStatus", "failure");
+ throw e;
+ } catch (NumberFormatException e) {
+ CMS.debug("SizePanel: update() NumberFormatException caught: " + e.toString());
+ context.put("updateStatus", "failure");
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("SizePanel: update() Exception caught: " + e.toString());
+ }
+
+ // generate key pair
+ Enumeration c = mCerts.elements();
+
+ while (c.hasMoreElements()) {
+ Cert cert = (Cert) c.nextElement();
+ String ct = cert.getCertTag();
+ String friendlyName = ct;
+ boolean enable = true;
+ try {
+ enable = config.getBoolean(PCERT_PREFIX+ct+".enable", true);
+ friendlyName = config.getString(PCERT_PREFIX + ct + ".userfriendlyname", ct);
+ } catch (Exception e) {
+ }
+
+ if (!enable)
+ continue;
+
+ try {
+ String keytype = config.getString(PCERT_PREFIX + ct + ".keytype");
+ String keyalgorithm = config.getString(PCERT_PREFIX + ct + ".keyalgorithm");
+
+ if (keytype.equals("rsa")) {
+ int keysize = config.getInteger(
+ PCERT_PREFIX + ct + ".keysize.size");
+
+ createRSAKeyPair(token, keysize, config, ct);
+ } else {
+ String curveName = config.getString(
+ PCERT_PREFIX + ct + ".curvename.name", default_ecc_curve_name);
+ createECCKeyPair(token, curveName, config, ct);
+ }
+ config.commit(false);
+ } catch (Exception e) {
+ CMS.debug(e);
+ CMS.debug("SizePanel: key generation failure: " + e.toString());
+ context.put("updateStatus", "failure");
+ throw new IOException("key generation failure for the certificate: " + friendlyName +
+ ". See the logs for details.");
+ }
+ } // while
+
+ if (hasErr == false) {
+ config.putBoolean("preop.SizePanel.done", true);
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ CMS.debug(
+ "SizePanel: update() Exception caught at config commit: "
+ + e.toString());
+ }
+ }
+ CMS.debug("SizePanel: update() done");
+ context.put("updateStatus", "success");
+
+ }
+
+ public void createECCKeyPair(String token, String curveName, IConfigStore config, String ct)
+ throws NoSuchAlgorithmException, NoSuchTokenException, TokenException, CryptoManager.NotInitializedException
+ {
+ CMS.debug("Generating ECC key pair with curvename="+ curveName +
+ ", token="+token);
+ KeyPair pair = null;
+ /*
+ * default ssl server cert to ECDHE unless stated otherwise
+ * note: IE only supports "ECDHE", but "ECDH" is more efficient
+ *
+ * for "ECDHE", server.xml should have the following for ciphers:
+ * +TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ * -TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
+ *
+ * for "ECDH", server.xml should have the following for ciphers:
+ * -TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
+ * +TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
+ */
+ String sslType = "ECDHE";
+ try {
+ sslType = config.getString(PCERT_PREFIX + ct + "ec.type", "ECDHE");
+ } catch (Exception e) {
+ CMS.debug("SizePanel: createECCKeyPair() Exception caught at config.getString for ec type");
+ }
+
+ // ECDHE needs "SIGN" but no "DERIVE"
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage usages_mask[] = {
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.DERIVE
+ };
+
+ // ECDH needs "DERIVE" but no any kind of "SIGN"
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage ECDH_usages_mask[] = {
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN,
+ org.mozilla.jss.crypto.KeyPairGeneratorSpi.Usage.SIGN_RECOVER,
+ };
+
+ do {
+ if (ct.equals("sslserver") && sslType.equalsIgnoreCase("ECDH")) {
+ CMS.debug("SizePanel: createECCKeypair: sslserver cert for ECDH. Make sure server.xml is set properly with -TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,+TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
+ pair = CryptoUtil.generateECCKeyPair(token, curveName,
+ null,
+ ECDH_usages_mask);
+ } else {
+ if (ct.equals("sslserver")) {
+ CMS.debug("SizePanel: createECCKeypair: sslserver cert for ECDHE. Make sure server.xml is set properly with +TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,-TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA");
+ }
+ pair = CryptoUtil.generateECCKeyPair(token, curveName,
+ null,
+ usages_mask);
+ }
+
+ // XXX - store curve , w
+ byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
+ String kid = CryptoUtil.byte2string(id);
+ config.putString(PCERT_PREFIX + ct + ".privkey.id", kid);
+
+ // try to locate the private key
+ org.mozilla.jss.crypto.PrivateKey privk =
+ CryptoUtil.findPrivateKeyFromID(CryptoUtil.string2byte(kid));
+ if (privk == null) {
+ CMS.debug("Found bad ECC key id " + kid);
+ pair = null;
+ }
+ } while (pair == null);
+
+ CMS.debug("Public key class " + pair.getPublic().getClass().getName());
+ byte encoded[] = pair.getPublic().getEncoded();
+ config.putString(PCERT_PREFIX + ct + ".pubkey.encoded",
+ CryptoUtil.byte2string(encoded));
+
+ String keyAlgo = "";
+ try {
+ keyAlgo = config.getString(PCERT_PREFIX + ct + ".signingalgorithm");
+ } catch (Exception e1) {
+ }
+
+ setSigningAlgorithm(ct, keyAlgo, config);
+ }
+
+ public void createRSAKeyPair(String token, int keysize, IConfigStore config, String ct)
+ throws NoSuchAlgorithmException, NoSuchTokenException, TokenException, CryptoManager.NotInitializedException
+ {
+ /* generate key pair */
+ KeyPair pair = null;
+ do {
+ pair = CryptoUtil.generateRSAKeyPair(token, keysize);
+ byte id[] = ((org.mozilla.jss.crypto.PrivateKey) pair.getPrivate()).getUniqueID();
+ String kid = CryptoUtil.byte2string(id);
+ config.putString(PCERT_PREFIX + ct + ".privkey.id", kid);
+ // try to locate the private key
+ org.mozilla.jss.crypto.PrivateKey privk =
+ CryptoUtil.findPrivateKeyFromID(CryptoUtil.string2byte(kid));
+ if (privk == null) {
+ CMS.debug("Found bad RSA key id " + kid);
+ pair = null;
+ }
+ } while (pair == null);
+
+ byte modulus[] = ((RSAPublicKey) pair.getPublic()).getModulus().toByteArray();
+ byte exponent[] = ((RSAPublicKey) pair.getPublic()).getPublicExponent().toByteArray();
+
+ config.putString(PCERT_PREFIX + ct + ".pubkey.modulus",
+ CryptoUtil.byte2string(modulus));
+ config.putString(PCERT_PREFIX + ct + ".pubkey.exponent",
+ CryptoUtil.byte2string(exponent));
+
+ String keyAlgo = "";
+ try {
+ keyAlgo = config.getString(PCERT_PREFIX + ct + ".signingalgorithm");
+ } catch (Exception e1) {
+ }
+
+ setSigningAlgorithm(ct, keyAlgo, config);
+ }
+
+ public void setSigningAlgorithm(String ct, String keyAlgo, IConfigStore config) {
+ String systemType = "";
+ try {
+ systemType = config.getString("preop.system.name");
+ } catch (Exception e1) {
+ }
+ if (systemType.equalsIgnoreCase("CA")) {
+ if (ct.equals("signing")) {
+ config.putString("ca.signing.defaultSigningAlgorithm",
+ keyAlgo);
+ config.putString("ca.crl.MasterCRL.signingAlgorithm",
+ keyAlgo);
+ } else if (ct.equals("ocsp_signing")) {
+ config.putString("ca.ocsp_signing.defaultSigningAlgorithm",
+ keyAlgo);
+ }
+ } else if (systemType.equalsIgnoreCase("OCSP")) {
+ if (ct.equals("signing")) {
+ config.putString("ocsp.signing.defaultSigningAlgorithm",
+ keyAlgo);
+ }
+ } else if (systemType.equalsIgnoreCase("KRA") ||
+ systemType.equalsIgnoreCase("DRM")) {
+ if (ct.equals("transport")) {
+ config.putString("kra.transportUnit.signingAlgorithm", keyAlgo);
+ }
+ }
+ }
+
+ public void initParams(HttpServletRequest request, Context context)
+ throws IOException
+ {
+ IConfigStore config = CMS.getConfigStore();
+ String s = "";
+ try {
+ context.put("title", "Key Pairs");
+
+ s = config.getString("preop.subsystem.select", "");
+ context.put("select", s);
+
+ s = config.getString("preop.hierarchy.select", "root");
+ context.put("hselect", s);
+
+ s = config.getString("preop.ecc.algorithm.list", "SHA256withEC,SHA1withEC,SHA384withEC,SHA512withEC");
+ context.put("ecclist", s);
+
+ s = config.getString("preop.rsa.algorithm.list", "SHA256withRSA,SHA1withRSA,SHA512withRSA,MD5withRSA,MD2withRSA");
+ context.put("rsalist", s);
+
+ s = config.getString("keys.ecc.curve.list", "nistp521");
+ context.put("curvelist", s);
+
+ s = config.getString("pkicreate.subsystem_type");
+ context.put("subsystemtype", s);
+
+ } catch (Exception e) {
+ CMS.debug("SizePanel(): initParams: unable to set all initial parameters:" + e);
+ }
+ }
+
+ /**
+ * 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("certs", mCerts);
+ context.put("show_signing", mShowSigning ? "true" : "false");
+ context.put("default_keysize", default_rsa_key_size);
+ context.put("default_ecc_curvename", default_ecc_curve_name);
+
+ context.put("panel", "admin/console/config/sizepanel.vm");
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java
new file mode 100644
index 000000000..ebcafe86b
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/TokenAuthenticate.java
@@ -0,0 +1,137 @@
+// --- 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.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import javax.servlet.http.*;
+import java.net.*;
+import org.w3c.dom.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.cms.servlet.*;
+import com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import com.netscape.cmsutil.xml.*;
+
+public class TokenAuthenticate extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public TokenAuthenticate() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ super.init(sc);
+ }
+
+ /**
+ * Process the HTTP request.
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+ IConfigStore config = CMS.getConfigStore();
+
+ String sessionId = httpReq.getParameter("sessionID");
+ CMS.debug("TokenAuthentication: sessionId=" + sessionId);
+ String givenHost = httpReq.getParameter("hostname");
+ CMS.debug("TokenAuthentication: givenHost=" + givenHost);
+
+ boolean checkIP = false;
+ try {
+ checkIP = config.getBoolean("securitydomain.checkIP", false);
+ } catch (Exception e) {
+ }
+
+ ISecurityDomainSessionTable table = CMS.getSecurityDomainSessionTable();
+ String uid = "";
+ String gid = "";
+ CMS.debug("TokenAuthentication: checking session in the session table");
+ if (table.isSessionIdExist(sessionId)) {
+ CMS.debug("TokenAuthentication: found session");
+ if (checkIP) {
+ String hostname = table.getIP(sessionId);
+ if (! hostname.equals(givenHost)) {
+ CMS.debug("TokenAuthentication: hostname=" + hostname + " and givenHost="
+ + givenHost + " are different");
+ CMS.debug("TokenAuthenticate authenticate failed, wrong hostname.");
+ outputError(httpResp, "Error: Failed Authentication");
+ return;
+ }
+ }
+
+ uid = table.getUID(sessionId);
+ gid = table.getGroup(sessionId);
+ } else {
+ CMS.debug("TokenAuthentication: session not found");
+ CMS.debug("TokenAuthentication authenticate failed, session id does not exist.");
+ outputError(httpResp, "Error: Failed Authentication");
+ return;
+ }
+
+ CMS.debug("TokenAuthenticate successfully authenticate");
+ try {
+ XMLObject xmlObj = null;
+
+ xmlObj = new XMLObject();
+
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ xmlObj.addItemToContainer(root, "uid", uid);
+ xmlObj.addItemToContainer(root, "gid", gid);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("Failed to send the XML output");
+ }
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java
new file mode 100644
index 000000000..d5c4f017d
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateConnector.java
@@ -0,0 +1,203 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import com.netscape.certsrv.connector.*;
+import com.netscape.certsrv.ca.*;
+
+
+public class UpdateConnector extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public UpdateConnector() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("UpdateConnector: initializing...");
+ super.init(sc);
+ CMS.debug("UpdateConnector: done initializing...");
+ }
+
+ /**
+ * Process the HTTP request.
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateConnector: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ IAuthToken authToken = null;
+ try {
+ authToken = authenticate(cmsReq);
+ CMS.debug("UpdateConnector authentication successful.");
+ } catch (Exception e) {
+ CMS.debug("UpdateConnector: authentication failed.");
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("CMSGW_ERR_BAD_SERV_OUT_STREAM", "",
+ e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ if (authToken == null) {
+ CMS.debug("UpdateConnector: authentication failed.");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+
+ AuthzToken authzToken = null;
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
+ CMS.debug("UpdateConnector authorization successful.");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ Enumeration list = httpReq.getParameterNames();
+ while (list.hasMoreElements()) {
+ String name = (String)list.nextElement();
+ String val = httpReq.getParameter(name);
+ if (name != null && name.startsWith("ca.connector")) {
+ CMS.debug("Adding connector update name=" + name + " val=" + val);
+ cs.putString(name, val);
+ } else {
+ CMS.debug("Skipping connector update name=" + name + " val=" + val);
+ }
+ }
+
+ try {
+ String nickname = cs.getString("ca.subsystem.nickname", "");
+ String tokenname = cs.getString("ca.subsystem.tokenname", "");
+ if (!tokenname.equals("Internal Key Storage Token"))
+ nickname = tokenname+":"+nickname;
+ cs.putString("ca.connector.KRA.nickName", nickname);
+ cs.commit(false);
+ } catch (Exception e) {
+ }
+
+ // start the connector
+ try {
+ ICertificateAuthority ca = (ICertificateAuthority)
+ CMS.getSubsystem("ca");
+ ICAService caService = (ICAService)ca.getCAService();
+ IConnector kraConnector = caService.getConnector(
+ cs.getSubStore("ca.connector.KRA"));
+ caService.setKRAConnector(kraConnector);
+ kraConnector.start();
+ } catch (Exception e) {
+ CMS.debug("Failed to start connector " + e);
+ }
+
+ // send success status back to the requestor
+ try {
+ CMS.debug("UpdateConnector: Sending response");
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("UpdateConnector: Failed to send the XML output");
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java
new file mode 100644
index 000000000..b379a7899
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateDomainXML.java
@@ -0,0 +1,486 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class UpdateDomainXML extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+
+ public UpdateDomainXML() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("UpdateDomainXML: initializing...");
+ super.init(sc);
+ CMS.debug("UpdateDomainXML: done initializing...");
+ }
+
+ private String remove_from_ldap(String dn) {
+ CMS.debug("UpdateDomainXML: delete_from_ldap: starting dn: " + dn);
+ String status = SUCCESS;
+ ILdapConnFactory connFactory = null;
+ LDAPConnection conn = null;
+ IConfigStore cs = CMS.getConfigStore();
+
+ try {
+ IConfigStore ldapConfig = cs.getSubStore("internaldb");
+ connFactory = CMS.getLdapBoundConnFactory();
+ connFactory.init(ldapConfig);
+ conn = connFactory.getConn();
+ conn.delete(dn);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() != LDAPException.NO_SUCH_OBJECT) {
+ status = FAILED;
+ CMS.debug("Failed to delete entry" + e.toString());
+ }
+ } catch (Exception e) {
+ CMS.debug("Failed to delete entry" + e.toString());
+ } finally {
+ try {
+ if ((conn != null) && (connFactory!= null)) {
+ CMS.debug("Releasing ldap connection");
+ connFactory.returnConn(conn);
+ }
+ }
+ catch (Exception e) {
+ CMS.debug("Error releasing the ldap connection" + e.toString());
+ }
+ }
+ return status;
+ }
+
+ private String modify_ldap(String dn, LDAPModification mod) {
+ CMS.debug("UpdateDomainXML: modify_ldap: starting dn: " + dn);
+ String status = SUCCESS;
+ ILdapConnFactory connFactory = null;
+ LDAPConnection conn = null;
+ IConfigStore cs = CMS.getConfigStore();
+
+ try {
+ IConfigStore ldapConfig = cs.getSubStore("internaldb");
+ connFactory = CMS.getLdapBoundConnFactory();
+ connFactory.init(ldapConfig);
+ conn = connFactory.getConn();
+ conn.modify(dn, mod);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() != LDAPException.NO_SUCH_OBJECT) {
+ status = FAILED;
+ CMS.debug("Failed to modify entry" + e.toString());
+ }
+ } catch (Exception e) {
+ CMS.debug("Failed to modify entry" + e.toString());
+ } finally {
+ try {
+ if ((conn != null) && (connFactory!= null)) {
+ CMS.debug("Releasing ldap connection");
+ connFactory.returnConn(conn);
+ }
+ }
+ catch (Exception e) {
+ CMS.debug("Error releasing the ldap connection" + e.toString());
+ }
+ }
+ return status;
+ }
+
+
+ private String add_to_ldap(LDAPEntry entry, String dn) {
+ CMS.debug("UpdateDomainXML: add_to_ldap: starting");
+ String status = SUCCESS;
+ ILdapConnFactory connFactory = null;
+ LDAPConnection conn = null;
+ IConfigStore cs = CMS.getConfigStore();
+
+ try {
+ IConfigStore ldapConfig = cs.getSubStore("internaldb");
+ connFactory = CMS.getLdapBoundConnFactory();
+ connFactory.init(ldapConfig);
+ conn = connFactory.getConn();
+ conn.add(entry);
+ } catch (LDAPException e) {
+ if (e.getLDAPResultCode() == LDAPException.ENTRY_ALREADY_EXISTS) {
+ CMS.debug("UpdateDomainXML: Entry already exists");
+ try {
+ conn.delete(dn);
+ conn.add(entry);
+ } catch (LDAPException ee) {
+ CMS.debug("UpdateDomainXML: Error when replacing existing entry "+ee.toString());
+ status = FAILED;
+ }
+ } else {
+ CMS.debug("UpdateDomainXML: Failed to update ldap domain info. Exception: "+e.toString());
+ status = FAILED;
+ }
+ } catch (Exception e) {
+ CMS.debug("Failed to add entry" + e.toString());
+ } finally {
+ try {
+ if ((conn != null) && (connFactory!= null)) {
+ CMS.debug("Releasing ldap connection");
+ connFactory.returnConn(conn);
+ }
+ }
+ catch (Exception e) {
+ CMS.debug("Error releasing the ldap connection" + e.toString());
+ }
+ }
+ return status;
+ }
+
+
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * </ul>
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateDomainXML: processing...");
+ String status = SUCCESS;
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ CMS.debug("UpdateDomainXML process: authentication starts");
+ IAuthToken authToken = null;
+ try {
+ authToken = authenticate(cmsReq);
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authenticated");
+ return;
+ }
+ if (authToken == null) {
+ CMS.debug("UpdateDomainXML process: authToken is null");
+ outputError(httpResp, AUTH_FAILURE, "Error: not authenticated");
+ return;
+ }
+ CMS.debug("UpdateDomainXML process: authentication done");
+
+ AuthzToken authzToken = null;
+
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ AUTH_FAILURE,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+ if (authzToken == null) {
+ CMS.debug("UpdateDomainXML process: authorization error");
+ outputError(httpResp, AUTH_FAILURE, "Error: Not authorized");
+ return;
+ }
+
+ String list = httpReq.getParameter("list");
+ String type = httpReq.getParameter("type");
+ String host = httpReq.getParameter("host");
+ String name = httpReq.getParameter("name");
+ String sport = httpReq.getParameter("sport");
+ String agentsport = httpReq.getParameter("agentsport");
+ String adminsport = httpReq.getParameter("adminsport");
+ String eecaport = httpReq.getParameter("eeclientauthsport");
+ String httpport = httpReq.getParameter("httpport");
+ String domainmgr = httpReq.getParameter("dm");
+ String clone = httpReq.getParameter("clone");
+ String operation = httpReq.getParameter("operation");
+
+ // ensure required parameters are present
+ // especially important for DS syntax checking
+ String missing = "";
+ if ((host == null) || host.equals("")) {
+ missing += " host ";
+ }
+ if ((name == null) || name.equals("")) {
+ missing += " name ";
+ }
+ if ((sport == null) || sport.equals("")) {
+ missing += " sport ";
+ }
+ if ((clone == null) || clone.equals("")) {
+ clone = "false";
+ }
+
+ if (! missing.equals("")) {
+ CMS.debug("UpdateDomainXML process: required parameters:" + missing + "not provided in request");
+ outputError(httpResp, "Error: required parameters: " + missing + "not provided in request");
+ return;
+ }
+
+ String basedn = null;
+ String secstore = null;
+
+ IConfigStore cs = CMS.getConfigStore();
+
+ try {
+ basedn = cs.getString("internaldb.basedn");
+ secstore = cs.getString("securitydomain.store");
+ }
+ catch (Exception e) {
+ CMS.debug("Unable to determine security domain name or basedn. Please run the domaininfo migration script");
+ }
+
+ if ((basedn != null) && (secstore != null) && (secstore.equals("ldap"))) {
+ // update in ldap
+
+ LDAPEntry entry = null;
+ ILdapConnFactory connFactory = null;
+ LDAPConnection conn = null;
+ String listName = type + "List";
+ String cn = host + ":";
+
+ if ((adminsport!= null) && (adminsport != "")) {
+ cn += adminsport;
+ } else {
+ cn += sport;
+ }
+
+ String dn = "cn=" + cn + ",cn=" + listName + ",ou=Security Domain," + basedn;
+ CMS.debug("UpdateDomainXML: updating LDAP entry: " + dn);
+
+ LDAPAttributeSet attrs = null;
+ attrs = new LDAPAttributeSet();
+ attrs.add(new LDAPAttribute("objectclass", "top"));
+ attrs.add(new LDAPAttribute("objectclass", "pkiSubsystem"));
+ attrs.add(new LDAPAttribute("cn", cn));
+ attrs.add(new LDAPAttribute("Host", host));
+ attrs.add(new LDAPAttribute("SecurePort", sport));
+
+ if ((agentsport != null) && (!agentsport.equals(""))) {
+ attrs.add(new LDAPAttribute("SecureAgentPort", agentsport));
+ }
+ if ((adminsport != null) && (!adminsport.equals(""))) {
+ attrs.add(new LDAPAttribute("SecureAdminPort", adminsport));
+ }
+ if ((httpport != null) && (!httpport.equals(""))) {
+ attrs.add(new LDAPAttribute("UnSecurePort", httpport));
+ }
+ if ((eecaport != null) && (!eecaport.equals(""))) {
+ attrs.add(new LDAPAttribute("SecureEEClientAuthPort", eecaport));
+ }
+ if ((domainmgr != null) && (!domainmgr.equals(""))) {
+ attrs.add(new LDAPAttribute("DomainManager", domainmgr.toUpperCase()));
+ }
+ attrs.add(new LDAPAttribute("clone", clone.toUpperCase()));
+ attrs.add(new LDAPAttribute("SubsystemName", name));
+ entry = new LDAPEntry(dn, attrs);
+
+ if ((operation != null) && (operation.equals("remove"))) {
+ status = remove_from_ldap(dn);
+ String adminUserDN = "uid=" + type + "-" + host + "-" + agentsport + ",ou=People," + basedn;
+ if (status.equals(SUCCESS)) {
+ // remove the client cert for this subsystem's admin
+ status = remove_from_ldap(adminUserDN);
+ if (status.equals(SUCCESS)) {
+ // remove this user from the subsystem group
+ dn = "cn=Subsystem Group, ou=groups," + basedn;
+ LDAPModification mod = new LDAPModification(LDAPModification.DELETE,
+ new LDAPAttribute("uniqueMember", adminUserDN));
+ status = modify_ldap(dn, mod);
+ }
+ }
+ } else {
+ status = add_to_ldap(entry, dn);
+ }
+
+ }
+ else {
+ // update the domain.xml file
+ String path = CMS.getConfigStore().getString("instanceRoot", "")
+ + "/conf/domain.xml";
+
+ CMS.debug("UpdateDomainXML: got path=" + path);
+
+ try {
+ // using domain.xml file
+ CMS.debug("UpdateDomainXML: Inserting new domain info");
+ XMLObject parser = new XMLObject(new FileInputStream(path));
+ Node n = parser.getContainer(list);
+ int count =0;
+
+ if ((operation != null) && (operation.equals("remove"))) {
+ // delete node
+ Document doc = parser.getDocument();
+ NodeList nodeList = doc.getElementsByTagName(type);
+ int len = nodeList.getLength();
+
+ for (int i = 0; i < len; i++) {
+ Node nn = (Node) nodeList.item(i);
+ Vector v_name = parser.getValuesFromContainer(nn, "SubsystemName");
+ Vector v_host = parser.getValuesFromContainer(nn, "Host");
+ Vector v_adminport = parser.getValuesFromContainer(nn, "SecureAdminPort");
+ if ((v_name.elementAt(0).equals(name)) && (v_host.elementAt(0).equals(host))
+ && (v_adminport.elementAt(0).equals(adminsport))) {
+ Node parent = nn.getParentNode();
+ Node remNode = parent.removeChild(nn);
+ count --;
+ break;
+ }
+ }
+ } else {
+ // add node
+ Node parent = parser.createContainer(n, type);
+ parser.addItemToContainer(parent, "SubsystemName", name);
+ parser.addItemToContainer(parent, "Host", host);
+ parser.addItemToContainer(parent, "SecurePort", sport);
+ parser.addItemToContainer(parent, "SecureAgentPort", agentsport);
+ parser.addItemToContainer(parent, "SecureAdminPort", adminsport);
+ parser.addItemToContainer(parent, "SecureEEClientAuthPort", eecaport);
+ parser.addItemToContainer(parent, "UnSecurePort", httpport);
+ parser.addItemToContainer(parent, "DomainManager", domainmgr.toUpperCase());
+ parser.addItemToContainer(parent, "Clone", clone.toUpperCase());
+ count ++;
+ }
+ //update count
+
+ String countS = "";
+ NodeList nlist = n.getChildNodes();
+ Node countnode = null;
+ for (int i=0; i<nlist.getLength(); i++) {
+ Element nn = (Element)nlist.item(i);
+ String tagname = nn.getTagName();
+ if (tagname.equals("SubsystemCount")) {
+ countnode = nn;
+ NodeList nlist1 = nn.getChildNodes();
+ Node nn1 = nlist1.item(0);
+ countS = nn1.getNodeValue();
+ break;
+ }
+ }
+
+ CMS.debug("UpdateDomainXML process: SubsystemCount="+countS);
+ try {
+ count += Integer.parseInt(countS);
+ } catch (Exception ee) {
+ }
+
+ Node nn2 = n.removeChild(countnode);
+ parser.addItemToContainer(n, "SubsystemCount", ""+count);
+
+ // recreate domain.xml
+ CMS.debug("UpdateDomainXML: Recreating domain.xml");
+ byte[] b = parser.toByteArray();
+ FileOutputStream fos = new FileOutputStream(path);
+ fos.write(b);
+ fos.close();
+ } catch (Exception e) {
+ CMS.debug("Failed to update domain.xml file" + e.toString());
+ status = FAILED;
+ }
+ }
+
+ try {
+ // send success status back to the requestor
+ CMS.debug("UpdateDomainXML: Sending response");
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", status);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("UpdateDomainXML: Failed to send the XML output" + e.toString());
+ }
+ }
+
+ protected String securityDomainXMLtoLDAP(String xmltag) {
+ if (xmltag.equals("Host")) return "host";
+ else return xmltag;
+ }
+
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java
new file mode 100644
index 000000000..890d6dfb1
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateNumberRange.java
@@ -0,0 +1,284 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.policy.*;
+import com.netscape.certsrv.request.IRequest;
+import com.netscape.certsrv.dbs.*;
+import com.netscape.certsrv.dbs.certdb.*;
+import com.netscape.certsrv.dbs.repository.*;
+import com.netscape.certsrv.ldap.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.certsrv.ca.*;
+import com.netscape.certsrv.kra.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class UpdateNumberRange extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public UpdateNumberRange() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("UpdateNumberRange: initializing...");
+ super.init(sc);
+ CMS.debug("UpdateNumberRange: done initializing...");
+ }
+
+ /**
+ * Process the HTTP request.
+ * <ul>
+ * <li>http.param op 'downloadBIN' - return the binary certificate chain
+ * <li>http.param op 'displayIND' - display pretty-print of certificate chain components
+ * </ul>
+ * @param cmsReq the object holding the request and response information
+ */
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateNumberRange: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ CMS.debug("UpdateNumberRange process: authentication starts");
+ IAuthToken authToken = authenticate(cmsReq);
+ if (authToken == null) {
+ CMS.debug("UpdateNumberRange process: authToken is null");
+ outputError(httpResp, AUTH_FAILURE, "Error: not authenticated");
+ }
+
+ AuthzToken authzToken = null;
+
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ try {
+ String type = httpReq.getParameter("type");
+ IConfigStore cs = CMS.getConfigStore();
+ String cstype = cs.getString("cs.type", "");
+
+ BigInteger beginNum = null;
+ BigInteger endNum = null;
+ BigInteger oneNum = new BigInteger("1");
+ String endNumConfig = null;
+ String cloneNumConfig = null;
+ String nextEndConfig = null;
+ int radix = 10;
+
+ IRepository repo = null;
+ if (cstype.equals("KRA")) {
+ IKeyRecoveryAuthority kra = (IKeyRecoveryAuthority) CMS.getSubsystem(
+ IKeyRecoveryAuthority.ID);
+ if (type.equals("request")) {
+ repo = kra.getRequestQueue().getRequestRepository();
+ } else if (type.equals("serialNo")) {
+ repo = kra.getKeyRepository();
+ } else if (type.equals("replicaId")) {
+ repo = kra.getReplicaRepository();
+ }
+ } else { // CA
+ ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(
+ ICertificateAuthority.ID);
+ if (type.equals("request")) {
+ repo = ca.getRequestQueue().getRequestRepository();
+ } else if (type.equals("serialNo")) {
+ repo = ca.getCertificateRepository();
+ } else if (type.equals("replicaId")) {
+ repo = ca.getReplicaRepository();
+ }
+ }
+
+ // checkRanges for replicaID - we do this each time a replica is created.
+ // This needs to be done beforehand to ensure that we always have enough
+ // replica numbers
+ if (type.equals("replicaId")) {
+ CMS.debug("Checking replica number ranges");
+ repo.checkRanges();
+ }
+
+ if (type.equals("request")) {
+ radix = 10;
+ endNumConfig = "dbs.endRequestNumber";
+ cloneNumConfig = "dbs.requestCloneTransferNumber";
+ nextEndConfig = "dbs.nextEndRequestNumber";
+ } else if (type.equals("serialNo")) {
+ radix=16;
+ endNumConfig = "dbs.endSerialNumber";
+ cloneNumConfig = "dbs.serialCloneTransferNumber";
+ nextEndConfig = "dbs.nextEndSerialNumber";
+ } else if (type.equals("replicaId")) {
+ radix=10;
+ endNumConfig = "dbs.endReplicaNumber";
+ cloneNumConfig = "dbs.replicaCloneTransferNumber";
+ nextEndConfig = "dbs.nextEndReplicaNumber";
+ }
+
+ String endNumStr = cs.getString(endNumConfig, "");
+ endNum = new BigInteger(endNumStr, radix);
+ if ( endNum == null ) {
+ CMS.debug( "UpdateNumberRange::process() - " +
+ "request endNum is null!" );
+ return;
+ }
+
+ String decrementStr = cs.getString(cloneNumConfig, "");
+ BigInteger decrement = new BigInteger(decrementStr, radix);
+ if (decrement == null) {
+ CMS.debug("UpdateNumberRange::process() - " +
+ "request decrement string is null!" );
+ return;
+ }
+
+ beginNum = endNum.subtract(decrement).add(oneNum);
+
+ if (beginNum.compareTo(repo.getTheSerialNumber()) < 0) {
+ String nextEndNumStr = cs.getString(nextEndConfig, "");
+ BigInteger endNum2 = new BigInteger(nextEndNumStr, radix);
+ if (endNum2 == null) {
+ CMS.debug("UpdateNumberRange::process() - " +
+ "Unused requests less than cloneTransferNumber!" );
+ return;
+ } else {
+ CMS.debug("Transferring from the end of on-deck range");
+ String newValStr = endNum2.subtract(decrement).toString(radix);
+ repo.setNextMaxSerial(newValStr);
+ cs.putString(nextEndConfig, newValStr);
+ beginNum = endNum2.subtract(decrement).add(oneNum);
+ endNum = endNum2;
+ }
+ } else {
+ CMS.debug("Transferring from the end of the current range");
+ String newValStr = beginNum.subtract(oneNum).toString(radix);
+ repo.setMaxSerial(newValStr);
+ cs.putString(endNumConfig, newValStr);
+ }
+
+
+ if( beginNum == null ) {
+ CMS.debug( "UpdateNumberRange::process() - " +
+ "beginNum is null!" );
+ return;
+ }
+
+ if( endNum == null ) {
+ CMS.debug( "UpdateNumberRange::process() - " +
+ "endNum is null!" );
+ return;
+ }
+
+ // Enable serial number management in master for certs and requests
+ if (type.equals("replicaId")) {
+ repo.setEnableSerialMgmt(true);
+ }
+
+ // insert info
+ CMS.debug("UpdateNumberRange: Sending response");
+
+ // send success status back to the requestor
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ xmlObj.addItemToContainer(root, "beginNumber", beginNum.toString(radix));
+ xmlObj.addItemToContainer(root, "endNumber", endNum.toString(radix));
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ cs.commit(false);
+ } catch (Exception e) {
+ CMS.debug("UpdateNumberRange: Failed to update number range. Exception: "+e.toString());
+ outputError(httpResp, "Error: Failed to update number range.");
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java
new file mode 100644
index 000000000..b2b8b5d28
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/UpdateOCSPConfig.java
@@ -0,0 +1,180 @@
+// --- 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 com.netscape.cms.servlet.common.*;
+import com.netscape.cms.servlet.base.*;
+import java.io.*;
+import java.util.*;
+import java.math.*;
+import javax.servlet.*;
+import java.security.cert.*;
+import javax.servlet.http.*;
+import netscape.ldap.*;
+import netscape.security.x509.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.authority.*;
+import com.netscape.certsrv.logging.*;
+import com.netscape.certsrv.apps.CMS;
+import com.netscape.certsrv.authentication.*;
+import com.netscape.certsrv.authorization.*;
+import com.netscape.cms.servlet.*;
+import com.netscape.cmsutil.xml.*;
+import org.w3c.dom.*;
+import org.apache.xerces.parsers.DOMParser;
+import org.apache.xerces.dom.*;
+import javax.xml.parsers.*;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class UpdateOCSPConfig extends CMSServlet {
+
+ private final static String SUCCESS = "0";
+ private final static String FAILED = "1";
+ private final static String AUTH_FAILURE = "2";
+
+ public UpdateOCSPConfig() {
+ super();
+ }
+
+ /**
+ * initialize the servlet.
+ * @param sc servlet configuration, read from the web.xml file
+ */
+ public void init(ServletConfig sc) throws ServletException {
+ CMS.debug("UpdateOCSPConfig: initializing...");
+ super.init(sc);
+ CMS.debug("UpdateOCSPConfig: done initializing...");
+ }
+
+ protected void process(CMSRequest cmsReq) throws EBaseException {
+ CMS.debug("UpdateOCSPConfig: processing...");
+
+ HttpServletRequest httpReq = cmsReq.getHttpReq();
+ HttpServletResponse httpResp = cmsReq.getHttpResp();
+
+ CMS.debug("UpdateOCSPConfig process: authentication starts");
+ IAuthToken authToken = authenticate(cmsReq);
+ if (authToken == null) {
+ CMS.debug("UpdateOCSPConfig process: authToken is null");
+ outputError(httpResp, AUTH_FAILURE, "Error: not authenticated");
+ }
+
+ AuthzToken authzToken = null;
+
+ try {
+ authzToken = authorize(mAclMethod, authToken, mAuthzResourceName,
+ "modify");
+ } catch (EAuthzAccessDenied e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ } catch (Exception e) {
+ log(ILogger.LL_FAILURE,
+ CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
+ outputError(httpResp,
+ "Error: Encountered problem during authorization.");
+ return;
+ }
+ if (authzToken == null) {
+ outputError(httpResp, "Error: Not authorized");
+ return;
+ }
+
+ IConfigStore cs = CMS.getConfigStore();
+ String nickname = "";
+
+ // get nickname
+ try {
+ nickname = cs.getString("ca.subsystem.nickname", "");
+ String tokenname = cs.getString("ca.subsystem.tokenname", "");
+ if (!tokenname.equals("internal") && !tokenname.equals("Internal Key Storage Token"))
+ nickname = tokenname+":"+nickname;
+ } catch (Exception e) {
+ }
+
+ CMS.debug("UpdateOCSPConfig process: nickname="+nickname);
+
+ String ocsphost = httpReq.getParameter("ocsp_host");
+ String ocspport = httpReq.getParameter("ocsp_port");
+ try {
+ cs.putString("ca.publish.enable", "true");
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.host",
+ ocsphost);
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.port",
+ ocspport);
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.nickName",
+ nickname);
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.path",
+ "/ocsp/agent/ocsp/addCRL");
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.pluginName", "OCSPPublisher");
+ cs.putString("ca.publish.publisher.instance.OCSPPublisher.enableClientAuth", "true");
+ cs.putString("ca.publish.rule.instance.ocsprule.enable", "true");
+ cs.putString("ca.publish.rule.instance.ocsprule.mapper", "NoMap");
+ cs.putString("ca.publish.rule.instance.ocsprule.pluginName", "Rule");
+ cs.putString("ca.publish.rule.instance.ocsprule.publisher",
+ "OCSPPublisher");
+ cs.putString("ca.publish.rule.instance.ocsprule.type", "crl");
+ cs.commit(false);
+ // insert info
+ CMS.debug("UpdateOCSPConfig: Sending response");
+
+ // send success status back to the requestor
+ XMLObject xmlObj = new XMLObject();
+ Node root = xmlObj.createRoot("XMLResponse");
+
+ xmlObj.addItemToContainer(root, "Status", SUCCESS);
+ byte[] cb = xmlObj.toByteArray();
+
+ outputResult(httpResp, "application/xml", cb);
+ } catch (Exception e) {
+ CMS.debug("UpdateOCSPConfig: Failed to update OCSP configuration. Exception: "+e.toString());
+ outputError(httpResp, "Error: Failed to update OCSP configuration.");
+ }
+ }
+
+ protected void setDefaultTemplates(ServletConfig sc) {}
+
+ protected void renderTemplate(
+ CMSRequest cmsReq, String templateName, ICMSTemplateFiller filler)
+ throws IOException {// do nothing
+ }
+
+ protected void renderResult(CMSRequest cmsReq) throws IOException {// do nothing, ie, it will not return the default javascript.
+ }
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ protected Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java
new file mode 100644
index 000000000..cb3cf7543
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomePanel.java
@@ -0,0 +1,123 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import java.io.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+
+import com.netscape.cms.servlet.wizard.*;
+
+public class WelcomePanel extends WizardPanelBase {
+
+ public WelcomePanel() {}
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException {
+ setPanelNo(panelno);
+ setName("Welcome");
+ setId(id);
+ }
+
+ public void cleanUp() throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ cs.putBoolean("preop.welcome.done", false);
+ }
+
+ public boolean isPanelDone() {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ return cs.getBoolean("preop.welcome.done");
+ } catch (EBaseException e) {}
+ return false;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = new PropertySet();
+
+ /* XXX */
+
+ return set;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+ IConfigStore cs = CMS.getConfigStore();
+ CMS.debug("WelcomePanel: display()");
+ context.put("title", "Welcome");
+ try {
+ context.put("cstype", cs.getString("cs.type"));
+ context.put("wizardname", cs.getString("preop.wizard.name"));
+ context.put("panelname",
+ cs.getString("preop.system.fullname") + " Configuration Wizard");
+ context.put("systemname",
+ cs.getString("preop.system.name"));
+ context.put("fullsystemname",
+ cs.getString("preop.system.fullname"));
+ context.put("productname",
+ cs.getString("preop.product.name"));
+ context.put("productversion",
+ cs.getString("preop.product.version"));
+ } catch (EBaseException e) {}
+ context.put("panel", "admin/console/config/welcomepanel.vm");
+ }
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ cs.putBoolean("preop.welcome.done", true);
+ cs.commit(false);
+ } catch (EBaseException e) {}
+ }
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {/* This should never be called */}
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java
new file mode 100644
index 000000000..2871b9e41
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WelcomeServlet.java
@@ -0,0 +1,45 @@
+// --- 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 org.apache.velocity.Template;
+import org.apache.velocity.servlet.VelocityServlet;
+import org.apache.velocity.app.Velocity;
+import org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+
+
+public class WelcomeServlet extends BaseServlet {
+
+ public Template process(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {
+
+ Template template = null;
+
+ try {
+ context.put("name", "Velocity Test");
+ template = Velocity.getTemplate("admin/console/config/welcome.vm");
+ } catch (Exception e) {
+ System.err.println("Exception caught: " + e.getMessage());
+ }
+
+ return template;
+ }
+}
diff --git a/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java
new file mode 100644
index 000000000..c34adc408
--- /dev/null
+++ b/pki/base/common/src/com/netscape/cms/servlet/csadmin/WizardPanelBase.java
@@ -0,0 +1,1603 @@
+// --- 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 org.apache.velocity.context.Context;
+import javax.servlet.http.*;
+import javax.servlet.*;
+import java.io.*;
+import java.util.*;
+import java.net.*;
+import com.netscape.certsrv.apps.*;
+import com.netscape.certsrv.property.*;
+import com.netscape.certsrv.base.*;
+import com.netscape.cms.servlet.wizard.*;
+import com.netscape.cms.servlet.base.*;
+import org.mozilla.jss.*;
+import org.mozilla.jss.ssl.*;
+import org.mozilla.jss.crypto.*;
+import org.mozilla.jss.util.Base64OutputStream;
+import org.mozilla.jss.pkcs11.*;
+import netscape.security.x509.*;
+import com.netscape.cmsutil.xml.*;
+import com.netscape.cmsutil.http.*;
+import org.w3c.dom.*;
+import org.xml.sax.*;
+import java.security.cert.*;
+import java.security.*;
+import netscape.ldap.*;
+
+import com.netscape.cmsutil.crypto.*;
+import com.netscape.cms.servlet.wizard.*;
+
+public class WizardPanelBase implements IWizardPanel {
+ public static String PCERT_PREFIX = "preop.cert.";
+ public static String SUCCESS = "0";
+ public static String FAILURE = "1";
+ public static String AUTH_FAILURE = "2";
+
+ /**
+ * Definition for static variables in CS.cfg
+ */
+ public static final String CONF_CA_CERT = "ca.signing.cert";
+ public static final String CONF_CA_CERTREQ = "ca.signing.certreq";
+ public static final String CONF_CA_CERTNICKNAME = "ca.signing.certnickname";
+
+ public static final String PRE_CONF_ADMIN_NAME = "preop.admin.name";
+ public static final String PRE_CONF_AGENT_GROUP = "preop.admin.group";
+
+ /**
+ * Definition for "preop" static variables in CS.cfg
+ * -- "preop" config parameters should not assumed to exist after configuation
+ */
+
+ public static final String PRE_CONF_CA_TOKEN = "preop.module.token";
+ public static final String PRE_CA_TYPE = "preop.ca.type";
+ public static final String PRE_OTHER_CA = "otherca";
+ public static final String PRE_ROOT_CA = "rootca";
+
+ private String mName = null;
+ private int mPanelNo = 0;
+ private String mId = null;
+
+ /**
+ * Initializes this panel.
+ */
+ public void init(ServletConfig config, int panelno)
+ throws ServletException
+ {
+ mPanelNo = panelno;
+ }
+
+ public void init(WizardServlet servlet, ServletConfig config, int panelno, String id)
+ throws ServletException
+ {
+ mPanelNo = panelno;
+ }
+
+ /**
+ * Cleans up this panel so that isPanelDone() will return false.
+ */
+ public void cleanUp() throws IOException {
+ }
+
+ public String getName() {
+ return mName;
+ }
+
+ public int getPanelNo() {
+ return mPanelNo;
+ }
+
+ public void setPanelNo(int num) {
+ mPanelNo = num;
+ }
+
+ public void setName(String name) {
+ mName = name;
+ }
+
+ public void setId(String id) {
+ mId = id;
+ }
+
+ public String getId() {
+ return mId;
+ }
+
+ public PropertySet getUsage() {
+ PropertySet set = null;
+
+ return set;
+ }
+
+ /**
+ * Should we skip this panel?
+ */
+ public boolean shouldSkip() {
+ return false;
+ }
+
+ /**
+ * Is this panel done
+ */
+ public boolean isPanelDone() {
+ return false;
+ }
+
+ /**
+ * Show "Apply" button on frame?
+ */
+ public boolean showApplyButton() {
+ return false;
+ }
+
+ /**
+ * Is this a subPanel?
+ */
+ public boolean isSubPanel() {
+ return false;
+ }
+
+ public boolean isLoopbackPanel() {
+ return false;
+ }
+
+ /**
+ * has subPanels?
+ */
+ public boolean hasSubPanel() {
+ return false;
+ }
+
+ /**
+ * Display the panel.
+ */
+ public void display(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {}
+
+ /**
+ * Checks if the given parameters are valid.
+ */
+ public void validate(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {
+ }
+
+ /**
+ * Commit parameter changes
+ */
+ public void update(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) throws IOException {}
+
+ /**
+ * If validiate() returns false, this method will be called.
+ */
+ public void displayError(HttpServletRequest request,
+ HttpServletResponse response,
+ Context context) {}
+
+ /**
+ * Retrieves locale based on the request.
+ */
+ public Locale getLocale(HttpServletRequest req) {
+ Locale locale = null;
+ String lang = req.getHeader("accept-language");
+
+ if (lang == null) {
+ // use server locale
+ locale = Locale.getDefault();
+ } else {
+ locale = new Locale(UserInfo.getUserLanguage(lang),
+ UserInfo.getUserCountry(lang));
+ }
+ return locale;
+ }
+
+ public String getNickname(IConfigStore config, String certTag) {
+ String instanceID = "";
+
+ try {
+ instanceID = config.getString("instanceId", "");
+ } catch (Exception e) {}
+
+ String nickname = certTag + "Cert cert-" + instanceID;
+ String preferredNickname = null;
+
+ try {
+ preferredNickname = config.getString(
+ PCERT_PREFIX + certTag + ".nickname", null);
+ } catch (Exception e) {}
+
+ if (preferredNickname != null) {
+ nickname = preferredNickname;
+ }
+ return nickname;
+ }
+
+ public void updateDomainXML(String hostname, int port, boolean https,
+ String servlet, String uri) throws IOException {
+ CMS.debug("WizardPanelBase updateDomainXML start hostname=" + hostname + " port=" + port);
+ IConfigStore cs = CMS.getConfigStore();
+ String nickname = "";
+ String tokenname = "";
+ try {
+ nickname = cs.getString("preop.cert.subsystem.nickname", "");
+ tokenname = cs.getString("preop.module.token", "");
+ } catch (Exception e) {}
+
+ if (!tokenname.equals("") &&
+ !tokenname.equals("Internal Key Storage Token") &&
+ !tokenname.equals("internal")) {
+ nickname = tokenname+":"+nickname;
+ }
+
+ CMS.debug("WizardPanelBase updateDomainXML nickname=" + nickname);
+ CMS.debug("WizardPanelBase: start sending updateDomainXML request");
+ String c = getHttpResponse(hostname, port, https, servlet, uri, nickname);
+ CMS.debug("WizardPanelBase: done sending updateDomainXML request");
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject obj = null;
+ try {
+ obj = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::updateDomainXML() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = obj.getValue("Status");
+ CMS.debug("WizardPanelBase updateDomainXML: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ return;
+ } else {
+ String error = obj.getValue("Error");
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: updateDomainXML: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: updateDomainXML: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+ }
+
+ public int getSubsystemCount( String hostname, int https_admin_port,
+ boolean https, String type )
+ throws IOException {
+ CMS.debug("WizardPanelBase getSubsystemCount start");
+ String c = getDomainXML(hostname, https_admin_port, true);
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject obj = new XMLObject(bis);
+ String containerName = type+"List";
+ Node n = obj.getContainer(containerName);
+ NodeList nlist = n.getChildNodes();
+ String countS = "";
+ for (int i=0; i<nlist.getLength(); i++) {
+ Element nn = (Element)nlist.item(i);
+ String tagname = nn.getTagName();
+ if (tagname.equals("SubsystemCount")) {
+ NodeList nlist1 = nn.getChildNodes();
+ Node nn1 = nlist1.item(0);
+ countS = nn1.getNodeValue();
+ break;
+ }
+ }
+ CMS.debug("WizardPanelBase getSubsystemCount: SubsystemCount="+countS);
+ int num = 0;
+
+ if (countS != null && !countS.equals("")) {
+ try {
+ num = Integer.parseInt(countS);
+ } catch (Exception ee) {
+ }
+ }
+
+ return num;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: getSubsystemCount: "+e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return -1;
+ }
+
+ public String getDomainXML( String hostname, int https_admin_port,
+ boolean https )
+ throws IOException {
+ CMS.debug("WizardPanelBase getDomainXML start");
+ String c = getHttpResponse( hostname, https_admin_port, https,
+ "/ca/admin/ca/getDomainXML", null, null );
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::getDomainXML() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase getDomainXML: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ String domainInfo = parser.getValue("DomainInfo");
+
+ CMS.debug(
+ "WizardPanelBase getDomainXML: domainInfo="
+ + domainInfo);
+ return domainInfo;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: getDomainXML: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: getDomainXML: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return null;
+ }
+
+ public String getSubsystemCert(String host, int port, boolean https)
+ throws IOException {
+ CMS.debug("WizardPanelBase getSubsystemCert start");
+ String c = getHttpResponse(host, port, https,
+ "/ca/admin/ca/getSubsystemCert", null, null);
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis =
+ new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::getSubsystemCert() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+ String status = parser.getValue("Status");
+ if (status.equals(SUCCESS)) {
+ String s = parser.getValue("Cert");
+ return s;
+ } else
+ return null;
+ } catch (Exception e) {
+ }
+ }
+
+ return null;
+ }
+
+ public void updateConnectorInfo(String host, int port, boolean https,
+ String content) throws IOException {
+ CMS.debug("WizardPanelBase updateConnectorInfo start");
+ String c = getHttpResponse(host, port, https,
+ "/ca/admin/ca/updateConnector", content, null);
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::updateConnectorInfo() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase updateConnectorInfo: status=" + status);
+
+ if (!status.equals(SUCCESS)) {
+ String error = parser.getValue("Error");
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: updateConnectorInfo: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: updateConnectorInfo: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+ }
+
+ public String getCertChainUsingSecureAdminPort( String hostname,
+ int https_admin_port,
+ boolean https,
+ ConfigCertApprovalCallback
+ certApprovalCallback )
+ throws IOException {
+ CMS.debug("WizardPanelBase getCertChainUsingSecureAdminPort start");
+ String c = getHttpResponse( hostname, https_admin_port, https,
+ "/ca/admin/ca/getCertChain", null, null,
+ certApprovalCallback );
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::getCertChainUsingSecureAdminPort() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase getCertChainUsingSecureAdminPort: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ String certchain = parser.getValue("ChainBase64");
+
+ certchain = CryptoUtil.normalizeCertStr(certchain);
+ CMS.debug(
+ "WizardPanelBase getCertChainUsingSecureAdminPort: certchain="
+ + certchain);
+ return certchain;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: getCertChainUsingSecureAdminPort: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: getCertChainUsingSecureAdminPort: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return null;
+ }
+
+ public String getCertChainUsingSecureEEPort( String hostname,
+ int https_ee_port,
+ boolean https,
+ ConfigCertApprovalCallback
+ certApprovalCallback )
+ throws IOException {
+ CMS.debug("WizardPanelBase getCertChainUsingSecureEEPort start");
+ String c = getHttpResponse( hostname, https_ee_port, https,
+ "/ca/ee/ca/getCertChain", null, null,
+ certApprovalCallback );
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::getCertChainUsingSecureEEPort() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase getCertChainUsingSecureEEPort: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ String certchain = parser.getValue("ChainBase64");
+
+ certchain = CryptoUtil.normalizeCertStr(certchain);
+ CMS.debug(
+ "WizardPanelBase getCertChainUsingSecureEEPort: certchain="
+ + certchain);
+ return certchain;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: getCertChainUsingSecureEEPort: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: getCertChainUsingSecureEEPort: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return null;
+ }
+
+ public boolean updateConfigEntries(String hostname, int port, boolean https,
+ String servlet, String uri, IConfigStore config,
+ HttpServletResponse response) throws IOException {
+ CMS.debug("WizardPanelBase updateConfigEntries start");
+ String c = getHttpResponse(hostname, port, https, servlet, uri, null);
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::updateConfigEntries() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase updateConfigEntries: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ String cstype = "";
+ try {
+ cstype = config.getString("cs.type", "");
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase::updateConfigEntries() - unable to get cs.type: " + e.toString());
+ }
+
+ Document doc = parser.getDocument();
+ NodeList list = doc.getElementsByTagName("name");
+ int len = list.getLength();
+ for (int i=0; i<len; i++) {
+ Node n = list.item(i);
+ NodeList nn = n.getChildNodes();
+ String name = nn.item(0).getNodeValue();
+ Node parent = n.getParentNode();
+ nn = parent.getChildNodes();
+ int len1 = nn.getLength();
+ String v = "";
+ for (int j=0; j<len1; j++) {
+ Node nv = nn.item(j);
+ String val = nv.getNodeName();
+ if (val.equals("value")) {
+ NodeList n2 = nv.getChildNodes();
+ if (n2.getLength() > 0)
+ v = n2.item(0).getNodeValue();
+ break;
+ }
+ }
+
+ if (name.equals("internaldb.ldapconn.host")) {
+ config.putString("preop.internaldb.master.hostname", v);
+ } else if (name.equals("internaldb.ldapconn.port")) {
+ config.putString("preop.internaldb.master.port", v);
+ } else if (name.equals("internaldb.ldapauth.bindDN")) {
+ config.putString("preop.internaldb.master.binddn", v);
+ } else if (name.equals("internaldb.basedn")) {
+ config.putString(name, v);
+ config.putString("preop.internaldb.master.basedn", v);
+ } else if (name.equals("internaldb.ldapauth.password")) {
+ config.putString("preop.internaldb.master.bindpwd", v);
+ } else if (name.equals("internaldb.replication.password")) {
+ config.putString("preop.internaldb.master.replicationpwd", v);
+ } else if (name.equals("instanceId")) {
+ config.putString("preop.master.instanceId", v);
+ } else if (name.equals("cloning.cert.signing.nickname")) {
+ config.putString("preop.master.signing.nickname", v);
+ config.putString("preop.cert.signing.nickname", v);
+ } else if (name.equals("cloning.ocsp_signing.nickname")) {
+ config.putString("preop.master.ocsp_signing.nickname", v);
+ config.putString("preop.cert.ocsp_signing.nickname", v);
+ } else if (name.equals("cloning.subsystem.nickname")) {
+ config.putString("preop.master.subsystem.nickname", v);
+ config.putString("preop.cert.subsystem.nickname", v);
+ } else if (name.equals("cloning.transport.nickname")) {
+ config.putString("preop.master.transport.nickname", v);
+ config.putString("kra.transportUnit.nickName", v);
+ config.putString("preop.cert.transport.nickname", v);
+ } else if (name.equals("cloning.storage.nickname")) {
+ config.putString("preop.master.storage.nickname", v);
+ config.putString("kra.storageUnit.nickName", v);
+ config.putString("preop.cert.storage.nickname", v);
+ } else if (name.equals("cloning.audit_signing.nickname")) {
+ config.putString("preop.master.audit_signing.nickname", v);
+ config.putString("preop.cert.audit_signing.nickname", v);
+ config.putString(name, v);
+ } else if (name.startsWith("cloning.ca")) {
+ config.putString(name.replaceFirst("cloning", "preop"), v);
+ } else if (name.equals("cloning.signing.keyalgorithm")) {
+ config.putString(name.replaceFirst("cloning", "preop.cert"), v);
+ if (cstype.equals("CA")) {
+ config.putString("ca.crl.MasterCRL.signingAlgorithm", v);
+ config.putString("ca.signing.defaultSigningAlgorithm", v);
+ } else if (cstype.equals("OCSP")) {
+ config.putString("ocsp.signing.defaultSigningAlgorithm", v);
+ }
+ } else if (name.equals("cloning.transport.keyalgorithm")) {
+ config.putString(name.replaceFirst("cloning", "preop.cert"), v);
+ config.putString("kra.transportUnit.signingAlgorithm", v);
+ } else if (name.equals("cloning.ocsp_signing.keyalgorithm")) {
+ config.putString(name.replaceFirst("cloning", "preop.cert"), v);
+ if (cstype.equals("CA")) {
+ config.putString("ca.ocsp_signing.defaultSigningAlgorithm", v);
+ }
+ } else if (name.startsWith("cloning")) {
+ config.putString(name.replaceFirst("cloning", "preop.cert"), v);
+ } else {
+ config.putString(name, v);
+ }
+ }
+
+ return true;
+ } else if (status.equals(AUTH_FAILURE)) {
+ reloginSecurityDomain(response);
+ return false;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: updateConfigEntries: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: updateConfigEntries: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return false;
+ }
+
+ public boolean authenticate(String hostname, int port, boolean https,
+ String servlet, String uri) throws IOException {
+ CMS.debug("WizardPanelBase authenticate start");
+ String c = getHttpResponse(hostname, port, https, servlet, uri, null);
+ IConfigStore cs = CMS.getConfigStore();
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::authenticate() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase authenticate: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ String cookie = parser.getValue("Cookie");
+ cs.putString("preop.cookie", cookie);
+ return true;
+ } else {
+ String error = parser.getValue("Error");
+ return false;
+ }
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: authenticate: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return false;
+ }
+
+ public void updateOCSPConfig(String hostname, int port, boolean https,
+ String content, HttpServletResponse response)
+ throws IOException {
+ CMS.debug("WizardPanelBase updateOCSPConfig start");
+ String c = getHttpResponse(hostname, port, https,
+ "/ca/ee/ca/updateOCSPConfig", content, null);
+ if (c == null || c.equals("")) {
+ CMS.debug("WizardPanelBase updateOCSPConfig: content is null.");
+ throw new IOException("The server you want to contact is not available");
+ } else {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::updateOCSPConfig() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase updateOCSPConfig: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ CMS.debug("WizardPanelBase updateOCSPConfig: Successfully update the OCSP configuration in the CA.");
+ } else if (status.equals(AUTH_FAILURE)) {
+ reloginSecurityDomain(response);
+ return;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase updateOCSPConfig: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase updateOCSPConfig: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+ }
+
+ public void updateNumberRange(String hostname, int port, boolean https,
+ String content, String type, HttpServletResponse response)
+ throws IOException {
+ CMS.debug("WizardPanelBase updateNumberRange start host=" + hostname +
+ " port=" + port);
+ IConfigStore cs = CMS.getConfigStore();
+ String cstype = "";
+ try {
+ cstype = cs.getString("cs.type", "");
+ } catch (Exception e) {
+ }
+
+ cstype = toLowerCaseSubsystemType(cstype);
+ String c = getHttpResponse(hostname, port, https,
+ "/"+cstype+"/ee/"+cstype+"/updateNumberRange", content, null);
+ if (c == null || c.equals("")) {
+ CMS.debug("WizardPanelBase updateNumberRange: content is null.");
+ throw new IOException("The server you want to contact is not available");
+ } else {
+ CMS.debug("content="+c);
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::updateNumberRange() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase updateNumberRange: status=" + status);
+ if (status.equals(SUCCESS)) {
+ String beginNum = parser.getValue("beginNumber");
+ String endNum = parser.getValue("endNumber");
+ if (type.equals("request")) {
+ cs.putString("dbs.beginRequestNumber", beginNum);
+ cs.putString("dbs.endRequestNumber", endNum);
+ } else if (type.equals("serialNo")) {
+ cs.putString("dbs.beginSerialNumber", beginNum);
+ cs.putString("dbs.endSerialNumber", endNum);
+ } else if (type.equals("replicaId")) {
+ cs.putString("dbs.beginReplicaNumber", beginNum);
+ cs.putString("dbs.endReplicaNumber", endNum);
+ }
+ // enable serial number management in clone
+ cs.putString("dbs.enableSerialManagement", "true");
+ cs.commit(false);
+ } else if (status.equals(AUTH_FAILURE)) {
+ reloginSecurityDomain(response);
+ return;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: updateNumberRange: " + e.toString());
+ CMS.debug(e);
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: updateNumberRange: " + e.toString());
+ CMS.debug(e);
+ throw new IOException(e.toString());
+ }
+ }
+ }
+
+ public int getPort(String hostname, int port, boolean https,
+ String portServlet, boolean sport)
+ throws IOException {
+ CMS.debug("WizardPanelBase getPort start");
+ String c = getHttpResponse(hostname, port, https, portServlet,
+ "secure=" + sport, null);
+
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::getPort() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase getPort: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ String portStr = parser.getValue("Port");
+
+ port = Integer.parseInt(portStr);
+ return port;
+ } else {
+ String error = parser.getValue("Error");
+
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: getPort: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: getPort: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+
+ return -1;
+ }
+
+ public String getHttpResponse(String hostname, int port, boolean secure,
+ String uri, String content, String clientnickname) throws IOException {
+ return getHttpResponse(hostname, port, secure, uri, content, clientnickname, null);
+ }
+
+ public String getHttpResponse(String hostname, int port, boolean secure,
+ String uri, String content, String clientnickname,
+ SSLCertificateApprovalCallback certApprovalCallback)
+ throws IOException {
+ HttpClient httpclient = null;
+ String c = null;
+
+ try {
+ if (secure) {
+ JssSSLSocketFactory factory = null;
+ if (clientnickname != null && clientnickname.length() > 0)
+ factory = new JssSSLSocketFactory(clientnickname);
+ else
+ factory = new JssSSLSocketFactory();
+
+ httpclient = new HttpClient(factory, certApprovalCallback);
+ } else {
+ httpclient = new HttpClient();
+ }
+ httpclient.connect(hostname, port);
+ HttpRequest httprequest = new HttpRequest();
+
+ httprequest.setMethod(HttpRequest.POST);
+ httprequest.setURI(uri);
+ // httprequest.setURI("/ca/ee/ca/ports");
+ httprequest.setHeader("user-agent", "HTTPTool/1.0");
+ // String content_c = "secure="+secure;
+ httprequest.setHeader("content-type",
+ "application/x-www-form-urlencoded");
+ if (content != null && content.length() > 0) {
+ String content_c = content;
+
+ httprequest.setHeader("content-length", "" + content_c.length());
+ httprequest.setContent(content_c);
+ }
+ HttpResponse httpresponse = httpclient.send(httprequest);
+
+ c = httpresponse.getContent();
+ } catch (ConnectException e) {
+ CMS.debug("WizardPanelBase getHttpResponse: " + e.toString());
+ throw new IOException("The server you tried to contact is not running.");
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase getHttpResponse: " + e.toString());
+ throw new IOException(e.toString());
+ } finally {
+ if (httpclient.connected()) {
+ httpclient.disconnect();
+ }
+ }
+
+ return c;
+ }
+
+ public boolean isSDHostDomainMaster (IConfigStore config) {
+ String dm="false";
+ try {
+ String hostname = config.getString("securitydomain.host");
+ int httpsadminport = config.getInteger("securitydomain.httpsadminport");
+
+ CMS.debug("Getting domain.xml from CA...");
+ String c = getDomainXML(hostname, httpsadminport, true);
+
+ CMS.debug("Getting DomainMaster from security domain");
+
+ ByteArrayInputStream bis = new ByteArrayInputStream( c.getBytes() );
+ XMLObject parser = new XMLObject( bis );
+ Document doc = parser.getDocument();
+ NodeList nodeList = doc.getElementsByTagName( "CA" );
+
+ int len = nodeList.getLength();
+ for( int i = 0; i < len; i++ ) {
+ Vector v_hostname =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "Host" );
+
+ Vector v_https_admin_port =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "SecureAdminPort" );
+
+ Vector v_domain_mgr =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "DomainManager" );
+
+ if( v_hostname.elementAt( 0 ).equals( hostname ) &&
+ v_https_admin_port.elementAt( 0 ).equals( Integer.toString(httpsadminport) ) ) {
+ dm = v_domain_mgr.elementAt( 0 ).toString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug( e.toString() );
+ }
+ return dm.equalsIgnoreCase("true");
+ }
+
+ public Vector getMasterUrlListFromSecurityDomain( IConfigStore config,
+ String type,
+ String portType ) {
+ Vector v = new Vector();
+
+ try {
+ String hostname = config.getString("securitydomain.host");
+ int httpsadminport = config.getInteger("securitydomain.httpsadminport");
+
+ CMS.debug("Getting domain.xml from CA...");
+ String c = getDomainXML(hostname, httpsadminport, true);
+ String list = "";
+
+ CMS.debug("Type " + type);
+ if (type.equals("CA")) {
+ list = "CAList";
+ } else if (type.equals("KRA")) {
+ list = "KRAList";
+ } else if (type.equals("OCSP")) {
+ list = "OCSPList";
+ } else if (type.equals("TKS")) {
+ list = "TKSList";
+ }
+
+ CMS.debug( "Getting " + portType + " from Security Domain ..." );
+ if( !portType.equals( "UnSecurePort" ) &&
+ !portType.equals( "SecureAgentPort" ) &&
+ !portType.equals( "SecurePort" ) &&
+ !portType.equals( "SecureAdminPort" ) ) {
+ CMS.debug( "getPortFromSecurityDomain: " +
+ "unknown port type " + portType );
+ return v;
+ }
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = new XMLObject(bis);
+ Document doc = parser.getDocument();
+ NodeList nodeList = doc.getElementsByTagName(type);
+
+ // save domain name in cfg
+ config.putString("securitydomain.name",
+ parser.getValue("Name"));
+
+ int len = nodeList.getLength();
+
+ CMS.debug("Len " + len);
+ for (int i = 0; i < len; i++) {
+ Vector v_clone = parser.getValuesFromContainer(nodeList.item(i),
+ "Clone");
+ String clone = (String)v_clone.elementAt(0);
+ if (clone.equalsIgnoreCase("true"))
+ continue;
+ Vector v_name = parser.getValuesFromContainer(nodeList.item(i),
+ "SubsystemName");
+ Vector v_host = parser.getValuesFromContainer(nodeList.item(i),
+ "Host");
+ Vector v_port = parser.getValuesFromContainer(nodeList.item(i),
+ portType);
+
+ v.addElement( v_name.elementAt(0)
+ + " - https://"
+ + v_host.elementAt(0)
+ + ":"
+ + v_port.elementAt(0) );
+ }
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+
+ return v;
+ }
+
+ public Vector getUrlListFromSecurityDomain( IConfigStore config,
+ String type,
+ String portType ) {
+ Vector v = new Vector();
+
+ try {
+ String hostname = config.getString("securitydomain.host");
+ int httpsadminport = config.getInteger("securitydomain.httpsadminport");
+
+ CMS.debug("Getting domain.xml from CA...");
+ String c = getDomainXML(hostname, httpsadminport, true);
+ String list = "";
+
+ CMS.debug("Subsystem Type " + type);
+ if (type.equals("CA")) {
+ list = "CAList";
+ } else if (type.equals("KRA")) {
+ list = "KRAList";
+ } else if (type.equals("OCSP")) {
+ list = "OCSPList";
+ } else if (type.equals("TKS")) {
+ list = "TKSList";
+ }
+
+ CMS.debug( "Getting " + portType + " from Security Domain ..." );
+ if( !portType.equals( "UnSecurePort" ) &&
+ !portType.equals( "SecureAgentPort" ) &&
+ !portType.equals( "SecurePort" ) &&
+ !portType.equals( "SecureAdminPort" ) ) {
+ CMS.debug( "getPortFromSecurityDomain: " +
+ "unknown port type " + portType );
+ return v;
+ }
+
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = new XMLObject(bis);
+ Document doc = parser.getDocument();
+ NodeList nodeList = doc.getElementsByTagName(type);
+
+ // save domain name in cfg
+ config.putString("securitydomain.name",
+ parser.getValue("Name"));
+
+ int len = nodeList.getLength();
+
+ CMS.debug("Len " + len);
+ for (int i = 0; i < len; i++) {
+ Vector v_name = parser.getValuesFromContainer(nodeList.item(i),
+ "SubsystemName");
+ Vector v_host = parser.getValuesFromContainer(nodeList.item(i),
+ "Host");
+ Vector v_port = parser.getValuesFromContainer(nodeList.item(i),
+ portType);
+ Vector v_admin_port = parser.getValuesFromContainer(nodeList.item(i),
+ "SecureAdminPort");
+
+ if (v_host.elementAt(0).equals(hostname) && v_admin_port.elementAt(0).equals(new Integer(httpsadminport).toString())) {
+ // add security domain CA to the beginning of list
+ v.add( 0, v_name.elementAt(0)
+ + " - https://"
+ + v_host.elementAt(0)
+ + ":"
+ + v_port.elementAt(0) );
+ } else {
+ v.addElement( v_name.elementAt(0)
+ + " - https://"
+ + v_host.elementAt(0)
+ + ":"
+ + v_port.elementAt(0) );
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug(e.toString());
+ }
+
+ return v;
+ }
+
+ // Given an HTTPS Hostname and EE port,
+ // retrieve the associated HTTPS Admin port
+ public String getSecurityDomainAdminPort( IConfigStore config,
+ String hostname,
+ String https_ee_port,
+ String cstype ) {
+ String https_admin_port = new String();
+
+ try {
+ String sd_hostname = config.getString( "securitydomain.host" );
+ int sd_httpsadminport =
+ config.getInteger( "securitydomain.httpsadminport" );
+
+ CMS.debug( "Getting domain.xml from CA ..." );
+ String c = getDomainXML( sd_hostname, sd_httpsadminport, true );
+
+ CMS.debug( "Getting associated HTTPS Admin port from " +
+ "HTTPS Hostname '" + hostname +
+ "' and EE port '" + https_ee_port + "'" );
+ ByteArrayInputStream bis = new ByteArrayInputStream( c.getBytes() );
+ XMLObject parser = new XMLObject( bis );
+ Document doc = parser.getDocument();
+ NodeList nodeList = doc.getElementsByTagName( cstype.toUpperCase() );
+
+ int len = nodeList.getLength();
+ for( int i = 0; i < len; i++ ) {
+ Vector v_hostname =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "Host" );
+
+ Vector v_https_ee_port =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "SecurePort" );
+
+ Vector v_https_admin_port =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "SecureAdminPort" );
+
+ if( v_hostname.elementAt( 0 ).equals( hostname ) &&
+ v_https_ee_port.elementAt( 0 ).equals( https_ee_port ) ) {
+ https_admin_port =
+ v_https_admin_port.elementAt( 0 ).toString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug( e.toString() );
+ }
+
+ return( https_admin_port );
+ }
+
+ public String getSecurityDomainPort( IConfigStore config,
+ String portType ) {
+ String port = new String();
+
+ try {
+ String hostname = config.getString( "securitydomain.host" );
+ int httpsadminport =
+ config.getInteger( "securitydomain.httpsadminport" );
+
+ CMS.debug( "Getting domain.xml from CA ..." );
+ String c = getDomainXML( hostname, httpsadminport, true );
+
+ CMS.debug( "Getting " + portType + " from Security Domain ..." );
+ if( !portType.equals( "UnSecurePort" ) &&
+ !portType.equals( "SecureAgentPort" ) &&
+ !portType.equals( "SecurePort" ) &&
+ !portType.equals( "SecureAdminPort" ) ) {
+ CMS.debug( "getPortFromSecurityDomain: " +
+ "unknown port type " + portType );
+ return "";
+ }
+
+ ByteArrayInputStream bis = new ByteArrayInputStream( c.getBytes() );
+ XMLObject parser = new XMLObject( bis );
+ Document doc = parser.getDocument();
+ NodeList nodeList = doc.getElementsByTagName( "CA" );
+
+ int len = nodeList.getLength();
+ for( int i = 0; i < len; i++ ) {
+ Vector v_admin_port =
+ parser.getValuesFromContainer( nodeList.item(i),
+ "SecureAdminPort" );
+
+ Vector v_port = null;
+ if( portType.equals( "UnSecurePort" ) ) {
+ v_port = parser.getValuesFromContainer( nodeList.item(i),
+ "UnSecurePort" );
+ } else if( portType.equals( "SecureAgentPort" ) ) {
+ v_port = parser.getValuesFromContainer( nodeList.item(i),
+ "SecureAgentPort" );
+ } else if( portType.equals( "SecurePort" ) ) {
+ v_port = parser.getValuesFromContainer( nodeList.item(i),
+ "SecurePort" );
+ } else if( portType.equals( "SecureAdminPort" ) ) {
+ v_port = parser.getValuesFromContainer( nodeList.item(i),
+ "SecureAdminPort" );
+ }
+
+ if( ( v_port != null ) &&
+ ( v_admin_port.elementAt( 0 ).equals(
+ Integer.toString( httpsadminport ) ) ) ) {
+ port = v_port.elementAt( 0 ).toString();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ CMS.debug( e.toString() );
+ }
+
+ return( port );
+ }
+
+ public String pingCS( String hostname, int port, boolean https,
+ SSLCertificateApprovalCallback certApprovalCallback )
+ throws IOException {
+ CMS.debug( "WizardPanelBase pingCS: started" );
+
+ String c = getHttpResponse( hostname, port, https,
+ "/ca/admin/ca/getStatus",
+ null, null, certApprovalCallback );
+
+ if( c != null ) {
+ try {
+ ByteArrayInputStream bis = new
+ ByteArrayInputStream( c.getBytes() );
+ XMLObject parser = null;
+ String state = null;
+
+ try {
+ parser = new XMLObject( bis );
+ CMS.debug( "WizardPanelBase pingCS: got XML parsed" );
+ state = parser.getValue( "State" );
+
+ if( state != null ) {
+ CMS.debug( "WizardPanelBase pingCS: state=" + state );
+ }
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase: pingCS: parser failed"
+ + e.toString() );
+ }
+
+ return state;
+ } catch( Exception e ) {
+ CMS.debug( "WizardPanelBase: pingCS: " + e.toString() );
+ throw new IOException( e.toString() );
+ }
+ }
+
+ CMS.debug( "WizardPanelBase pingCS: stopped" );
+ return null;
+ }
+
+ public String toLowerCaseSubsystemType(String s) {
+ String x = null;
+ if (s.equals("CA")) {
+ x = "ca";
+ } else if (s.equals("KRA")) {
+ x = "kra";
+ } else if (s.equals("OCSP")) {
+ x = "ocsp";
+ } else if (s.equals("TKS")) {
+ x = "tks";
+ }
+
+ return x;
+ }
+
+ public void getTokenInfo(IConfigStore config, String type, String host,
+ int https_ee_port, boolean https, Context context,
+ ConfigCertApprovalCallback certApprovalCallback) throws IOException {
+ CMS.debug("WizardPanelBase getTokenInfo start");
+ String uri = "/"+type+"/ee/"+type+"/getTokenInfo";
+ CMS.debug("WizardPanelBase getTokenInfo: uri="+uri);
+ String c = getHttpResponse(host, https_ee_port, https, uri, null, null,
+ certApprovalCallback);
+ if (c != null) {
+ try {
+ ByteArrayInputStream bis = new ByteArrayInputStream(c.getBytes());
+ XMLObject parser = null;
+
+ try {
+ parser = new XMLObject(bis);
+ } catch (Exception e) {
+ CMS.debug( "WizardPanelBase::getTokenInfo() - "
+ + "Exception="+e.toString() );
+ throw new IOException( e.toString() );
+ }
+
+ String status = parser.getValue("Status");
+
+ CMS.debug("WizardPanelBase getTokenInfo: status=" + status);
+
+ if (status.equals(SUCCESS)) {
+ Document doc = parser.getDocument();
+ NodeList list = doc.getElementsByTagName("name");
+ int len = list.getLength();
+ for (int i=0; i<len; i++) {
+ Node n = list.item(i);
+ NodeList nn = n.getChildNodes();
+ String name = nn.item(0).getNodeValue();
+ Node parent = n.getParentNode();
+ nn = parent.getChildNodes();
+ int len1 = nn.getLength();
+ String v = "";
+ for (int j=0; j<len1; j++) {
+ Node nv = nn.item(j);
+ String val = nv.getNodeName();
+ if (val.equals("value")) {
+ NodeList n2 = nv.getChildNodes();
+ if (n2.getLength() > 0)
+ v = n2.item(0).getNodeValue();
+ break;
+ }
+ }
+ if (name.equals("cloning.signing.nickname")) {
+ config.putString("preop.master.signing.nickname", v);
+ config.putString(type + ".cert.signing.nickname", v);
+ config.putString(name, v);
+ } else if (name.equals("cloning.ocsp_signing.nickname")) {
+ config.putString("preop.master.ocsp_signing.nickname", v);
+ config.putString(type + ".cert.ocsp_signing.nickname", v);
+ config.putString(name, v);
+ } else if (name.equals("cloning.subsystem.nickname")) {
+ config.putString("preop.master.subsystem.nickname", v);
+ config.putString(type + ".cert.subsystem.nickname", v);
+ config.putString(name, v);
+ } else if (name.equals("cloning.transport.nickname")) {
+ config.putString("preop.master.transport.nickname", v);
+ config.putString("kra.transportUnit.nickName", v);
+ config.putString("kra.cert.transport.nickname", v);
+ config.putString(name, v);
+ } else if (name.equals("cloning.storage.nickname")) {
+ config.putString("preop.master.storage.nickname", v);
+ config.putString("kra.storageUnit.nickName", v);
+ config.putString("kra.cert.storage.nickname", v);
+ config.putString(name, v);
+ } else if (name.equals("cloning.audit_signing.nickname")) {
+ config.putString("preop.master.audit_signing.nickname", v);
+ config.putString(type + ".cert.audit_signing.nickname", v);
+ config.putString(name, v);
+ } else if (name.equals("cloning.module.token")) {
+ config.putString("preop.module.token", v);
+ } else if (name.startsWith("cloning.ca")) {
+ config.putString(name.replaceFirst("cloning", "preop"), v);
+ } else if (name.startsWith("cloning")) {
+ config.putString(name.replaceFirst("cloning", "preop.cert"), v);
+ } else {
+ config.putString(name, v);
+ }
+ }
+ } else {
+ String error = parser.getValue("Error");
+ throw new IOException(error);
+ }
+ } catch (IOException e) {
+ CMS.debug("WizardPanelBase: getTokenInfo: " + e.toString());
+ throw e;
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase: getTokenInfo: " + e.toString());
+ throw new IOException(e.toString());
+ }
+ }
+ }
+
+ public void importCertChain(String id) throws IOException {
+ CMS.debug("DisplayCertChainPanel importCertChain");
+ IConfigStore config = CMS.getConfigStore();
+ String configName = "preop." + id + ".pkcs7";
+ String pkcs7 = "";
+
+ try {
+ pkcs7 = config.getString(configName, "");
+ } catch (Exception e) {}
+
+ if (pkcs7.length() > 0) {
+ try {
+ CryptoUtil.importCertificateChain(pkcs7);
+ } catch (Exception e) {
+ CMS.debug("DisplayCertChainPanel importCertChain: Exception: "+e.toString());
+ }
+ }
+ }
+
+ public void updateCertChain(IConfigStore config, String name, String host,
+ int https_admin_port, boolean https, Context context) throws IOException {
+ updateCertChain( config, name, host, https_admin_port,
+ https, context, null );
+ }
+
+ public void updateCertChain(IConfigStore config, String name, String host,
+ int https_admin_port, boolean https, Context context,
+ ConfigCertApprovalCallback certApprovalCallback) throws IOException {
+ String certchain = getCertChainUsingSecureAdminPort( host,
+ https_admin_port,
+ https,
+ certApprovalCallback );
+ config.putString("preop."+name+".pkcs7", certchain);
+
+ byte[] decoded = CryptoUtil.base64Decode(certchain);
+ java.security.cert.X509Certificate[] b_certchain = null;
+
+ try {
+ b_certchain = CryptoUtil.getX509CertificateFromPKCS7(decoded);
+ } catch (Exception e) {
+ context.put("errorString",
+ "Failed to get the certificate chain.");
+ return;
+ }
+
+ int size = 0;
+ if (b_certchain != null) {
+ size = b_certchain.length;
+ }
+ config.putInteger("preop."+name+".certchain.size", size);
+ for (int i = 0; i < size; i++) {
+ byte[] bb = null;
+
+ try {
+ bb = b_certchain[i].getEncoded();
+ } catch (Exception e) {
+ context.put("errorString",
+ "Failed to get the der-encoded certificate chain.");
+ return;
+ }
+ config.putString("preop."+name+".certchain." + i,
+ CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bb)));
+ }
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+ }
+
+ public void updateCertChainUsingSecureEEPort( IConfigStore config,
+ String name, String host,
+ int https_ee_port,
+ boolean https,
+ Context context,
+ ConfigCertApprovalCallback certApprovalCallback ) throws IOException {
+ String certchain = getCertChainUsingSecureEEPort( host, https_ee_port,
+ https,
+ certApprovalCallback);
+ config.putString("preop."+name+".pkcs7", certchain);
+
+ byte[] decoded = CryptoUtil.base64Decode(certchain);
+ java.security.cert.X509Certificate[] b_certchain = null;
+
+ try {
+ b_certchain = CryptoUtil.getX509CertificateFromPKCS7(decoded);
+ } catch (Exception e) {
+ context.put("errorString",
+ "Failed to get the certificate chain.");
+ return;
+ }
+
+ int size = 0;
+ if (b_certchain != null) {
+ size = b_certchain.length;
+ }
+ config.putInteger("preop."+name+".certchain.size", size);
+ for (int i = 0; i < size; i++) {
+ byte[] bb = null;
+
+ try {
+ bb = b_certchain[i].getEncoded();
+ } catch (Exception e) {
+ context.put("errorString",
+ "Failed to get the der-encoded certificate chain.");
+ return;
+ }
+ config.putString("preop."+name+".certchain." + i,
+ CryptoUtil.normalizeCertStr(CryptoUtil.base64Encode(bb)));
+ }
+
+ try {
+ config.commit(false);
+ } catch (EBaseException e) {
+ }
+ }
+
+ public void deleteCert(String tokenname, String nickname) {
+ try {
+ CryptoManager cm = CryptoManager.getInstance();
+ CryptoToken tok = cm.getTokenByName(tokenname);
+ CryptoStore store = tok.getCryptoStore();
+ String fullnickname = nickname;
+ if (!tokenname.equals("") &&
+ !tokenname.equals("Internal Key Storage Token") &&
+ !tokenname.equals("internal"))
+ fullnickname = tokenname+":"+nickname;
+
+ CMS.debug("WizardPanelBase deleteCert: nickname="+fullnickname);
+ org.mozilla.jss.crypto.X509Certificate cert = cm.findCertByNickname(fullnickname);
+
+ if (store instanceof PK11Store) {
+ CMS.debug("WizardPanelBase deleteCert: this is pk11store");
+ PK11Store pk11store = (PK11Store)store;
+ pk11store.deleteCertOnly(cert);
+ CMS.debug("WizardPanelBase deleteCert: cert deleted successfully");
+ }
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase deleteCert: Exception="+e.toString());
+ }
+ }
+
+ public void deleteEntries(LDAPSearchResults res, LDAPConnection conn,
+ String dn, String[] entries) {
+ String[] attrs = null;
+ LDAPSearchConstraints cons = null;
+ String filter = "objectclass=*";
+
+ try {
+ if (res.getCount() == 0)
+ return;
+ else {
+ while (res.hasMoreElements()) {
+ LDAPEntry entry = res.next();
+ String dn1 = entry.getDN();
+ LDAPSearchResults res1 = conn.search(dn1, 1, filter, attrs, true, cons);
+ deleteEntries(res1, conn, dn1, entries);
+ deleteEntry(conn, dn1, entries);
+ }
+ }
+ } catch (Exception ee) {
+ CMS.debug("WizardPanelBase deleteEntries: Exception="+ee.toString());
+ }
+ }
+
+ public void deleteEntry(LDAPConnection conn, String dn, String[] entries) {
+ try {
+ for (int i=0; i<entries.length; i++) {
+ if (LDAPDN.equals(dn, entries[i])) {
+ CMS.debug("WizardPanelBase deleteEntry: entry with this dn "+dn+" is not deleted.");
+ return;
+ }
+ }
+
+ CMS.debug("WizardPanelBase deleteEntry: deleting dn="+dn);
+ conn.delete(dn);
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase deleteEntry: Exception="+e.toString());
+ }
+ }
+
+ public void reloginSecurityDomain(HttpServletResponse response) {
+ IConfigStore cs = CMS.getConfigStore();
+ try {
+ String hostname = cs.getString("securitydomain.host", "");
+ int port = cs.getInteger("securitydomain.httpsadminport", -1);
+ String cs_hostname = cs.getString("machineName", "");
+ int cs_port = cs.getInteger("pkicreate.admin_secure_port", -1);
+ int panel = getPanelNo();
+ String subsystem = cs.getString("cs.type", "");
+ String urlVal = "https://"+cs_hostname+":"+cs_port+"/"+toLowerCaseSubsystemType(subsystem)+"/admin/console/config/wizard?p="+panel+"&subsystem="+subsystem;
+ String encodedValue = URLEncoder.encode(urlVal, "UTF-8");
+ String sdurl = "https://"+hostname+":"+port+"/ca/admin/ca/securityDomainLogin?url="+encodedValue;
+ response.sendRedirect(sdurl);
+ } catch (Exception e) {
+ CMS.debug("WizardPanelBase reloginSecurityDomain: Exception="+e.toString());
+ }
+ }
+}