summaryrefslogtreecommitdiffstats
path: root/base/server/cms/src/com/netscape/cms
diff options
context:
space:
mode:
authorEndi S. Dewata <edewata@redhat.com>2014-02-20 16:58:34 -0500
committerEndi S. Dewata <edewata@redhat.com>2014-02-28 12:54:05 -0500
commitd6d197d1a4513a3262a59c3989845f69285a38ad (patch)
tree4c9becb4c5dc3ef66cf4be6c0bdd2406ab779f03 /base/server/cms/src/com/netscape/cms
parent819fd31d34b3159e895f15bfad41bf483adca79e (diff)
downloadpki-d6d197d1a4513a3262a59c3989845f69285a38ad.tar.gz
pki-d6d197d1a4513a3262a59c3989845f69285a38ad.tar.xz
pki-d6d197d1a4513a3262a59c3989845f69285a38ad.zip
Reorganized REST service classes.
The REST service classes have been moved into org.dogtagpki.server namespace. A new upgrade script has been added to update existing instances. Ticket #114
Diffstat (limited to 'base/server/cms/src/com/netscape/cms')
-rw-r--r--base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java189
-rw-r--r--base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java177
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/account/AccountService.java72
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/admin/GroupService.java447
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/admin/KRAConnectorService.java86
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/admin/SystemCertService.java98
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/admin/UserService.java1178
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/cert/CertService.java654
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java4
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/csadmin/SecurityDomainService.java74
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java1295
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/key/KeyRequestDAO.java17
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/key/KeyService.java559
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/profile/ProfileService.java1033
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/request/CertRequestService.java420
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/request/KeyRequestService.java476
-rw-r--r--base/server/cms/src/com/netscape/cms/servlet/tks/TPSConnectorService.java494
17 files changed, 17 insertions, 7256 deletions
diff --git a/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java b/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java
deleted file mode 100644
index c4b890e12..000000000
--- a/base/server/cms/src/com/netscape/cms/authorization/ACLInterceptor.java
+++ /dev/null
@@ -1,189 +0,0 @@
-//--- BEGIN COPYRIGHT BLOCK ---
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; version 2 of the License.
-//
-//This program is distributed in the hope that it will be useful,
-//but WITHOUT ANY WARRANTY; without even the implied warranty of
-//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-//GNU General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License along
-//with this program; if not, write to the Free Software Foundation, Inc.,
-//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-//(C) 2012 Red Hat, Inc.
-//All rights reserved.
-//--- END COPYRIGHT BLOCK ---
-package com.netscape.cms.authorization;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.security.Principal;
-import java.util.Properties;
-
-import javax.servlet.ServletContext;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.SecurityContext;
-import javax.ws.rs.ext.Provider;
-
-import org.jboss.resteasy.core.ResourceMethodInvoker;
-import org.jboss.resteasy.spi.Failure;
-
-import com.netscape.certsrv.acls.ACLMapping;
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.authentication.IAuthToken;
-import com.netscape.certsrv.authorization.AuthzToken;
-import com.netscape.certsrv.authorization.EAuthzAccessDenied;
-import com.netscape.certsrv.authorization.IAuthzSubsystem;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.ForbiddenException;
-import com.netscape.cms.realm.PKIPrincipal;
-
-/**
- * @author Endi S. Dewata
- */
-@Provider
-public class ACLInterceptor implements ContainerRequestFilter {
-
- Properties properties;
-
- @Context
- ServletContext servletContext;
-
- @Context
- SecurityContext securityContext;
-
- public synchronized void loadProperties() throws IOException {
-
- if (properties != null)
- return;
-
- properties = new Properties();
-
- String context = servletContext.getContextPath();
- String subsystem = context.startsWith("/") ? context.substring(1) : context;
-
- // load default mapping
- String defaultMapping = "/usr/share/pki/" + subsystem + "/conf/acl.properties";
- CMS.debug("ACLInterceptor: loading " + defaultMapping);
- try (FileReader in = new FileReader(defaultMapping)) {
- properties.load(in);
- }
-
- // load custom mapping
- File customMapping = new File(System.getProperty("catalina.base")
- + "/" + subsystem + "/conf/acl.properties");
- CMS.debug("ACLInterceptor: checking " + customMapping);
- if (customMapping.exists()) {
- CMS.debug("ACLInterceptor: loading " + customMapping);
- try (FileReader in = new FileReader(customMapping)) {
- properties.load(in);
- }
- }
- }
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
- ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
- .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
- Method method = methodInvoker.getMethod();
- Class<?> clazz = methodInvoker.getResourceClass();
-
- CMS.debug("ACLInterceptor: " + clazz.getSimpleName() + "." + method.getName() + "()");
-
- ACLMapping aclMapping = method.getAnnotation(ACLMapping.class);
-
- // If not available, get ACL mapping for the class.
- if (aclMapping == null) {
- aclMapping = clazz.getAnnotation(ACLMapping.class);
- }
-
- // If still not available, it's unprotected, allow request.
- if (aclMapping == null) {
- CMS.debug("ACLInterceptor: No ACL mapping.");
- return;
- }
-
- String name = aclMapping.value();
- CMS.debug("ACLInterceptor: mapping: " + name);
-
- Principal principal = securityContext.getUserPrincipal();
-
- // If unauthenticated, reject request.
- if (principal == null) {
- CMS.debug("ACLInterceptor: No user principal provided.");
- throw new ForbiddenException("No user principal provided.");
- }
-
- CMS.debug("ACLInterceptor: principal: " + principal.getName());
-
- // If unrecognized principal, reject request.
- if (!(principal instanceof PKIPrincipal)) {
- CMS.debug("ACLInterceptor: Invalid user principal.");
- throw new ForbiddenException("Invalid user principal.");
- }
-
- PKIPrincipal pkiPrincipal = (PKIPrincipal) principal;
- IAuthToken authToken = pkiPrincipal.getAuthToken();
-
- // If missing auth token, reject request.
- if (authToken == null) {
- CMS.debug("ACLInterceptor: No authorization token present.");
- throw new ForbiddenException("No authorization token present.");
- }
-
- try {
- loadProperties();
-
- String value = properties.getProperty(name);
-
- // If no property defined, allow request.
- if (value == null) {
- CMS.debug("ACLInterceptor: No ACL configuration.");
- return;
- }
-
- String values[] = value.split(",");
-
- // If invalid mapping, reject request.
- if (values.length != 2) {
- CMS.debug("ACLInterceptor: Invalid ACL mapping.");
- throw new ForbiddenException("Invalid ACL mapping.");
- }
-
- CMS.debug("ACLInterceptor: ACL: " + value);
-
- // Check authorization.
- IAuthzSubsystem mAuthz = (IAuthzSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_AUTHZ);
- AuthzToken authzToken = mAuthz.authorize(
- "DirAclAuthz",
- authToken,
- values[0], // resource
- values[1]); // operation
-
- // If not authorized, reject request.
- if (authzToken == null) {
- CMS.debug("ACLInterceptor: No authorization token present.");
- throw new ForbiddenException("No authorization token present.");
- }
-
- CMS.debug("ACLInterceptor: access granted");
-
- } catch (EAuthzAccessDenied e) {
- CMS.debug("ACLInterceptor: " + e.getMessage());
- throw new ForbiddenException(e.toString());
-
- } catch (IOException | EBaseException e) {
- e.printStackTrace();
- throw new Failure(e);
- }
-
- // Allow request.
- return;
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java b/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java
deleted file mode 100644
index 6d26840b6..000000000
--- a/base/server/cms/src/com/netscape/cms/authorization/AuthMethodInterceptor.java
+++ /dev/null
@@ -1,177 +0,0 @@
-//--- 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) 2013 Red Hat, Inc.
-//All rights reserved.
-//--- END COPYRIGHT BLOCK ---
-package com.netscape.cms.authorization;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.security.Principal;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Properties;
-
-import javax.servlet.ServletContext;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.SecurityContext;
-import javax.ws.rs.ext.Provider;
-
-import org.jboss.resteasy.core.ResourceMethodInvoker;
-import org.jboss.resteasy.spi.Failure;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.authentication.AuthMethodMapping;
-import com.netscape.certsrv.authentication.AuthToken;
-import com.netscape.certsrv.authentication.IAuthToken;
-import com.netscape.certsrv.base.ForbiddenException;
-import com.netscape.cms.realm.PKIPrincipal;
-
-/**
- * @author Endi S. Dewata
- */
-@Provider
-public class AuthMethodInterceptor implements ContainerRequestFilter {
-
- Properties properties;
-
- @Context
- ServletContext servletContext;
-
- @Context
- SecurityContext securityContext;
-
- public synchronized void loadProperties() throws IOException {
-
- if (properties != null)
- return;
-
- properties = new Properties();
-
- String context = servletContext.getContextPath();
- String subsystem = context.startsWith("/") ? context.substring(1) : context;
-
- // load default mapping
- String defaultMapping = "/usr/share/pki/" + subsystem + "/conf/auth-method.properties";
- CMS.debug("AuthMethodInterceptor: loading " + defaultMapping);
- try (FileReader in = new FileReader(defaultMapping)) {
- properties.load(in);
- }
-
- // load custom mapping
- File customMapping = new File(System.getProperty("catalina.base") +
- "/" + subsystem + "/conf/auth-method.properties");
- CMS.debug("AuthMethodInterceptor: checking " + customMapping);
- if (customMapping.exists()) {
- CMS.debug("AuthMethodInterceptor: loading " + customMapping);
- try (FileReader in = new FileReader(customMapping)) {
- properties.load(in);
- }
- }
- }
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
- ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker) requestContext
- .getProperty("org.jboss.resteasy.core.ResourceMethodInvoker");
- Method method = methodInvoker.getMethod();
- Class<?> clazz = methodInvoker.getResourceClass();
-
- CMS.debug("AuthMethodInterceptor: " + clazz.getSimpleName() + "." + method.getName() + "()");
-
- // Get authentication mapping for the method.
- AuthMethodMapping authMapping = method.getAnnotation(AuthMethodMapping.class);
-
- // If not available, get authentication mapping for the class.
- if (authMapping == null) {
- authMapping = clazz.getAnnotation(AuthMethodMapping.class);
- }
-
- String name;
- if (authMapping == null) {
- // If not available, use the default mapping.
- name = "default";
- } else {
- // Get the method label
- name = authMapping.value();
- }
-
- CMS.debug("AuthMethodInterceptor: mapping: " + name);
-
- try {
- loadProperties();
-
- String value = properties.getProperty(name);
- Collection<String> authMethods = new HashSet<String>();
- if (value != null) {
- for (String v : value.split(",")) {
- authMethods.add(v.trim());
- }
- }
-
- CMS.debug("AuthMethodInterceptor: required auth methods: " + authMethods);
-
- Principal principal = securityContext.getUserPrincipal();
-
- // If unauthenticated, reject request.
- if (principal == null) {
- if (authMethods.isEmpty() || authMethods.contains("anonymous") || authMethods.contains("*")) {
- CMS.debug("AuthMethodInterceptor: anonymous access allowed");
- return;
- }
- CMS.debug("AuthMethodInterceptor: anonymous access not allowed");
- throw new ForbiddenException("Anonymous access not allowed.");
- }
-
- // If unrecognized principal, reject request.
- if (!(principal instanceof PKIPrincipal)) {
- CMS.debug("AuthMethodInterceptor: unknown principal");
- throw new ForbiddenException("Unknown user principal");
- }
-
- PKIPrincipal pkiPrincipal = (PKIPrincipal) principal;
- IAuthToken authToken = pkiPrincipal.getAuthToken();
-
- // If missing auth token, reject request.
- if (authToken == null) {
- CMS.debug("AuthMethodInterceptor: missing authentication token");
- throw new ForbiddenException("Missing authentication token.");
- }
-
- String authManager = (String) authToken.get(AuthToken.TOKEN_AUTHMGR_INST_NAME);
- CMS.debug("AuthMethodInterceptor: authentication manager: " + authManager);
-
- if (authManager == null) {
- CMS.debug("AuthMethodInterceptor: missing authentication manager");
- throw new ForbiddenException("Missing authentication manager.");
- }
-
- if (authMethods.isEmpty() || authMethods.contains(authManager) || authMethods.contains("*")) {
- CMS.debug("AuthMethodInterceptor: access granted");
- return;
- }
-
- throw new ForbiddenException("Authentication method not allowed.");
-
- } catch (IOException e) {
- e.printStackTrace();
- throw new Failure(e);
- }
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/account/AccountService.java b/base/server/cms/src/com/netscape/cms/servlet/account/AccountService.java
deleted file mode 100644
index 1a07a3a23..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/account/AccountService.java
+++ /dev/null
@@ -1,72 +0,0 @@
-// --- BEGIN COPYRIGHT BLOCK ---
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License along
-// with this program; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// (C) 2012 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.account;
-
-import java.security.Principal;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import com.netscape.certsrv.account.AccountResource;
-import com.netscape.cms.servlet.base.PKIService;
-
-/**
- * @author Endi S. Dewata
- */
-public class AccountService extends PKIService implements AccountResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- @Override
- public Response login() {
- HttpSession session = servletRequest.getSession();
- System.out.println("Creating session "+session.getId());
-
- Principal principal = servletRequest.getUserPrincipal();
- System.out.println("Principal: "+principal);
-
- return createNoContentResponse();
- }
-
- @Override
- public Response logout() {
- HttpSession session = servletRequest.getSession(false);
- if (session == null) return createNoContentResponse();
-
- System.out.println("Destroying session "+session.getId());
- session.invalidate();
-
- return createNoContentResponse();
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/admin/GroupService.java b/base/server/cms/src/com/netscape/cms/servlet/admin/GroupService.java
deleted file mode 100644
index 3af4bae43..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/admin/GroupService.java
+++ /dev/null
@@ -1,447 +0,0 @@
-// --- BEGIN COPYRIGHT BLOCK ---
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License along
-// with this program; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// (C) 2012 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.admin;
-
-import java.net.URI;
-import java.net.URLEncoder;
-import java.util.Enumeration;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.commons.lang.StringUtils;
-import org.jboss.resteasy.plugins.providers.atom.Link;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.ResourceNotFoundException;
-import com.netscape.certsrv.common.OpDef;
-import com.netscape.certsrv.common.ScopeDef;
-import com.netscape.certsrv.group.GroupCollection;
-import com.netscape.certsrv.group.GroupData;
-import com.netscape.certsrv.group.GroupMemberData;
-import com.netscape.certsrv.group.GroupNotFoundException;
-import com.netscape.certsrv.group.GroupResource;
-import com.netscape.certsrv.logging.IAuditor;
-import com.netscape.certsrv.logging.ILogger;
-import com.netscape.certsrv.usrgrp.IGroup;
-import com.netscape.certsrv.usrgrp.IUGSubsystem;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cmsutil.ldap.LDAPUtil;
-
-/**
- * @author Endi S. Dewata
- */
-public class GroupService extends PKIService implements GroupResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- public final static int DEFAULT_SIZE = 20;
-
- public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
-
- public GroupData createGroupData(IGroup group) throws Exception {
-
- GroupData groupData = new GroupData();
-
- String groupID = group.getGroupID();
- if (!StringUtils.isEmpty(groupID)) {
- groupData.setID(groupID);
- groupData.setGroupID(groupID);
- }
-
- String description = group.getDescription();
- if (!StringUtils.isEmpty(description)) groupData.setDescription(description);
-
- String encodedGroupID = URLEncoder.encode(groupData.getID(), "UTF-8");
- URI uri = uriInfo.getBaseUriBuilder().path(GroupResource.class).path("{groupID}").build(encodedGroupID);
- groupData.setLink(new Link("self", uri));
-
- return groupData;
- }
-
- /**
- * Searches for users in LDAP directory.
- *
- * Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- */
- @Override
- public Response findGroups(String filter, Integer start, Integer size) {
- try {
- filter = StringUtils.isEmpty(filter) ? "*" : "*"+LDAPUtil.escapeFilter(filter)+"*";
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- Enumeration<IGroup> groups = userGroupManager.listGroups(filter);
-
- GroupCollection response = new GroupCollection();
- int i = 0;
-
- // skip to the start of the page
- for ( ; i<start && groups.hasMoreElements(); i++) groups.nextElement();
-
- // return entries up to the page size
- for ( ; i<start+size && groups.hasMoreElements(); i++) {
- IGroup group = groups.nextElement();
- response.addEntry(createGroupData(group));
- }
-
- // count the total entries
- for ( ; groups.hasMoreElements(); i++) groups.nextElement();
- response.setTotal(i);
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- response.addLink(new Link("prev", uri));
- }
-
- if (start+size < i) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- response.addLink(new Link("next", uri));
- }
-
- return createOKResponse(response);
-
- } catch (Exception e) {
- throw new PKIException(getUserMessage("CMS_INTERNAL_ERROR", headers));
- }
- }
-
- /**
- * finds a group
- * Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- */
- @Override
- public Response getGroup(String groupID) {
- return createOKResponse(getGroupData(groupID));
- }
-
- public GroupData getGroupData(String groupID) {
-
- try {
- if (groupID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IGroup group = userGroupManager.getGroupFromName(groupID);
- if (group == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST"));
- throw new GroupNotFoundException(groupID);
- }
-
- return createGroupData(group);
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- throw new PKIException(getUserMessage("CMS_INTERNAL_ERROR", headers));
- }
- }
-
- /**
- * Adds a new group in local scope.
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#group
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response addGroup(GroupData groupData) {
-
- if (groupData == null) throw new BadRequestException("Group data is null.");
-
- String groupID = groupData.getGroupID();
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (groupID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IGroup group = userGroupManager.createGroup(groupID);
-
- String description = groupData.getDescription();
- if (description != null) {
- group.set("description", description);
- } else {
- group.set("description", "");
- }
-
- // allow adding a group with no members
- userGroupManager.addGroup(group);
-
- auditAddGroup(groupID, groupData, ILogger.SUCCESS);
-
- // read the data back
- groupData = getGroupData(groupID);
-
- return createCreatedResponse(groupData, groupData.getLink().getHref());
-
- } catch (PKIException e) {
- auditAddGroup(groupID, groupData, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditAddGroup(groupID, groupData, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * modifies a group
- * <P>
- *
- * last person of the super power group "Certificate Server Administrators" can never be removed.
- * <P>
- *
- * http://warp.mcom.com/server/certificate/columbo/design/ ui/admin-protocol-definition.html#group
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response modifyGroup(String groupID, GroupData groupData) {
-
- if (groupData == null) throw new BadRequestException("Group data is null.");
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (groupID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IGroup group = userGroupManager.getGroupFromName(groupID);
-
- if (group == null) {
- throw new ResourceNotFoundException("Group " + groupID + " not found.");
- }
-
- String description = groupData.getDescription();
- if (description != null) {
- group.set("description", description);
- }
-
- // allow adding a group with no members, except "Certificate
- // Server Administrators"
- userGroupManager.modifyGroup(group);
-
- auditModifyGroup(groupID, groupData, ILogger.SUCCESS);
-
- // read the data back
- groupData = getGroupData(groupID);
-
- return createOKResponse(groupData);
-
- } catch (PKIException e) {
- auditModifyGroup(groupID, groupData, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditModifyGroup(groupID, groupData, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * removes a group
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#group
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response removeGroup(String groupID) {
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (groupID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- // if fails, let the exception fall through
- userGroupManager.removeGroup(groupID);
-
- auditDeleteGroup(groupID, ILogger.SUCCESS);
-
- return createNoContentResponse();
-
- } catch (PKIException e) {
- auditDeleteGroup(groupID, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditDeleteGroup(groupID, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- @Override
- public Response findGroupMembers(String groupID, Integer start, Integer size) {
-
- if (groupID == null) throw new BadRequestException("Group ID is null.");
-
- try {
- GroupMemberProcessor processor = new GroupMemberProcessor(getLocale(headers));
- processor.setUriInfo(uriInfo);
- return createOKResponse(processor.findGroupMembers(groupID, start, size));
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- @Override
- public Response getGroupMember(String groupID, String memberID) {
-
- if (groupID == null) throw new BadRequestException("Group ID is null.");
- if (memberID == null) throw new BadRequestException("Member ID is null.");
-
- try {
- GroupMemberProcessor processor = new GroupMemberProcessor(getLocale(headers));
- processor.setUriInfo(uriInfo);
- return createOKResponse(processor.getGroupMember(groupID, memberID));
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- @Override
- public Response addGroupMember(String groupID, String memberID) {
-
- if (groupID == null) throw new BadRequestException("Group ID is null.");
- if (memberID == null) throw new BadRequestException("Member ID is null.");
-
- GroupMemberData groupMemberData = new GroupMemberData();
- groupMemberData.setID(memberID);
- groupMemberData.setGroupID(groupID);
- return addGroupMember(groupMemberData);
- }
-
- public Response addGroupMember(GroupMemberData groupMemberData) {
- try {
- GroupMemberProcessor processor = new GroupMemberProcessor(getLocale(headers));
- processor.setUriInfo(uriInfo);
- groupMemberData = processor.addGroupMember(groupMemberData);
-
- return createCreatedResponse(groupMemberData, groupMemberData.getLink().getHref());
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- @Override
- public Response removeGroupMember(String groupID, String memberID) {
-
- if (groupID == null) throw new BadRequestException("Group ID is null.");
- if (memberID == null) throw new BadRequestException("Member ID is null.");
-
- try {
- GroupMemberProcessor processor = new GroupMemberProcessor(getLocale(headers));
- processor.setUriInfo(uriInfo);
- processor.removeGroupMember(groupID, memberID);
-
- return createNoContentResponse();
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- public void log(int level, String message) {
- log(ILogger.S_USRGRP, level, message);
- }
-
- public void auditAddGroup(String groupID, GroupData groupData, String status) {
- audit(OpDef.OP_ADD, groupID, getParams(groupData), status);
- }
-
- public void auditModifyGroup(String groupID, GroupData groupData, String status) {
- audit(OpDef.OP_MODIFY, groupID, getParams(groupData), status);
- }
-
- public void auditDeleteGroup(String groupID, String status) {
- audit(OpDef.OP_DELETE, groupID, null, status);
- }
-
- public void audit(String type, String id, Map<String, String> params, String status) {
- audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_GROUPS, type, id, params, status);
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/admin/KRAConnectorService.java b/base/server/cms/src/com/netscape/cms/servlet/admin/KRAConnectorService.java
deleted file mode 100644
index 310e08206..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/admin/KRAConnectorService.java
+++ /dev/null
@@ -1,86 +0,0 @@
-// --- 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) 2013 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-package com.netscape.cms.servlet.admin;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.UriInfo;
-
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.system.KRAConnectorInfo;
-import com.netscape.certsrv.system.KRAConnectorResource;
-import com.netscape.cms.servlet.base.PKIService;
-
-/**
- * @author Ade Lee
- */
-public class KRAConnectorService extends PKIService implements KRAConnectorResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- @Override
- public void addConnector(KRAConnectorInfo info) {
-
- if (info == null) throw new BadRequestException("KRA connector info is null.");
-
- try {
- KRAConnectorProcessor processor = new KRAConnectorProcessor(getLocale(headers));
- processor.addConnector(info);
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage());
- }
- }
-
- @Override
- public void removeConnector(String host, String port) {
-
- if (host == null) throw new BadRequestException("KRA connector host is null.");
- if (port == null) throw new BadRequestException("KRA connector port is null.");
-
- try {
- KRAConnectorProcessor processor = new KRAConnectorProcessor(getLocale(headers));
- processor.removeConnector(host, port);
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage());
- }
- }
-
- @Override
- public void addConnector(MultivaluedMap<String, String> form) {
- KRAConnectorInfo info = new KRAConnectorInfo(form);
- addConnector(info);
- }
-
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/admin/SystemCertService.java b/base/server/cms/src/com/netscape/cms/servlet/admin/SystemCertService.java
deleted file mode 100644
index 50df221f9..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/admin/SystemCertService.java
+++ /dev/null
@@ -1,98 +0,0 @@
-// --- BEGIN COPYRIGHT BLOCK ---
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License along
-// with this program; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// (C) 2012 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.admin;
-
-import java.security.cert.CertificateEncodingException;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.ResourceNotFoundException;
-import com.netscape.certsrv.cert.CertData;
-import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
-import com.netscape.certsrv.security.ITransportKeyUnit;
-import com.netscape.certsrv.system.SystemCertResource;
-import com.netscape.cms.servlet.base.PKIService;
-
-/**
- * This is the class used to list, retrieve and modify system certificates for all Java subsystems.
- *
- * @author alee
- *
- */
-public class SystemCertService extends PKIService implements SystemCertResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- public SystemCertService() {
- CMS.debug("SystemCertService.<init>()");
- }
-
- /**
- * Used to retrieve the transport certificate
- */
- public Response getTransportCert() {
- CertData cert = null;
- IKeyRecoveryAuthority kra = null;
-
- // auth and authz
-
- kra = (IKeyRecoveryAuthority) CMS.getSubsystem("kra");
- if (kra == null) {
- // no KRA
- throw new ResourceNotFoundException("KRA subsystem not found.");
- }
-
- ITransportKeyUnit tu = kra.getTransportKeyUnit();
- if (tu == null) {
- CMS.debug("getTransportCert: transport key unit is null");
- throw new PKIException("No transport key unit.");
- }
- org.mozilla.jss.crypto.X509Certificate transportCert = tu.getCertificate();
- if (transportCert == null) {
- CMS.debug("getTransportCert: transport cert is null");
- throw new PKIException("Transport cert not found.");
- }
- try {
- cert = createCertificateData(transportCert);
- } catch (CertificateEncodingException e) {
- CMS.debug("getTransportCert: certificate encoding exception with transport cert");
- e.printStackTrace();
- throw new PKIException("Unable to encode transport cert");
- }
- return sendConditionalGetResponse(DEFAULT_LONG_CACHE_LIFETIME, cert, request);
- }
-
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/admin/UserService.java b/base/server/cms/src/com/netscape/cms/servlet/admin/UserService.java
deleted file mode 100644
index 70124b4f4..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/admin/UserService.java
+++ /dev/null
@@ -1,1178 +0,0 @@
-// --- BEGIN COPYRIGHT BLOCK ---
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License along
-// with this program; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// (C) 2012 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.admin;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateExpiredException;
-import java.security.cert.CertificateNotYetValidException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import netscape.security.pkcs.PKCS7;
-import netscape.security.x509.X509CertImpl;
-
-import org.apache.commons.lang.StringUtils;
-import org.jboss.resteasy.plugins.providers.atom.Link;
-import org.mozilla.jss.CryptoManager;
-import org.mozilla.jss.crypto.InternalCertificate;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.ForbiddenException;
-import com.netscape.certsrv.base.ICertPrettyPrint;
-import com.netscape.certsrv.base.IConfigStore;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.ResourceNotFoundException;
-import com.netscape.certsrv.base.UserNotFoundException;
-import com.netscape.certsrv.common.OpDef;
-import com.netscape.certsrv.common.ScopeDef;
-import com.netscape.certsrv.dbs.certdb.CertId;
-import com.netscape.certsrv.group.GroupMemberData;
-import com.netscape.certsrv.logging.IAuditor;
-import com.netscape.certsrv.logging.ILogger;
-import com.netscape.certsrv.password.IPasswordCheck;
-import com.netscape.certsrv.user.UserCertCollection;
-import com.netscape.certsrv.user.UserCertData;
-import com.netscape.certsrv.user.UserCollection;
-import com.netscape.certsrv.user.UserData;
-import com.netscape.certsrv.user.UserMembershipCollection;
-import com.netscape.certsrv.user.UserMembershipData;
-import com.netscape.certsrv.user.UserResource;
-import com.netscape.certsrv.usrgrp.EUsrGrpException;
-import com.netscape.certsrv.usrgrp.IGroup;
-import com.netscape.certsrv.usrgrp.IUGSubsystem;
-import com.netscape.certsrv.usrgrp.IUser;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cmsutil.ldap.LDAPUtil;
-import com.netscape.cmsutil.util.Cert;
-import com.netscape.cmsutil.util.Utils;
-
-/**
- * @author Endi S. Dewata
- */
-public class UserService extends PKIService implements UserResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- public final static int DEFAULT_SIZE = 20;
-
- public final static String BACK_SLASH = "\\";
- public final static String SYSTEM_USER = "$System$";
-
- public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
-
- public UserData createUserData(IUser user) throws Exception {
-
- UserData userData = new UserData();
-
- String userID = user.getUserID();
- if (!StringUtils.isEmpty(userID)) {
- userData.setID(userID);
- userData.setUserID(userID);
- }
-
- String fullName = user.getFullName();
- if (!StringUtils.isEmpty(fullName)) userData.setFullName(fullName);
-
- String encodedUserID = URLEncoder.encode(userID, "UTF-8");
- URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}").build(encodedUserID);
- userData.setLink(new Link("self", uri));
-
- return userData;
- }
-
- /**
- * Searches for users in LDAP directory.
- *
- * Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- */
- @Override
- public Response findUsers(String filter, Integer start, Integer size) {
- try {
- filter = StringUtils.isEmpty(filter) ? "*" : "*"+LDAPUtil.escapeFilter(filter)+"*";
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- Enumeration<IUser> users = userGroupManager.findUsers(filter);
-
- UserCollection response = new UserCollection();
- int i = 0;
-
- // skip to the start of the page
- for ( ; i<start && users.hasMoreElements(); i++) users.nextElement();
-
- // return entries up to the page size
- for ( ; i<start+size && users.hasMoreElements(); i++) {
- IUser user = users.nextElement();
- response.addEntry(createUserData(user));
- }
-
- // count the total entries
- for ( ; users.hasMoreElements(); i++) users.nextElement();
- response.setTotal(i);
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- response.addLink(new Link("prev", uri));
- }
-
- if (start+size < i) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- response.addLink(new Link("next", uri));
- }
-
- return createOKResponse(response);
-
- } catch (Exception e) {
- throw new PKIException(getUserMessage("CMS_INTERNAL_ERROR", headers));
- }
- }
-
- /**
- * List user information. Certificates covered in a separate
- * protocol for findUserCerts(). List of group memberships are
- * also provided.
- *
- * Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- */
- @Override
- public Response getUser(String userID) {
- return createOKResponse(getUserData(userID));
- }
-
- public UserData getUserData(String userID) {
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
-
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user;
-
- try {
- user = userGroupManager.getUser(userID);
- } catch (Exception e) {
- throw new PKIException(getUserMessage("CMS_INTERNAL_ERROR", headers));
- }
-
- if (user == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST"));
-
- throw new UserNotFoundException(userID);
- }
-
- UserData userData = createUserData(user);
-
- String email = user.getEmail();
- if (!StringUtils.isEmpty(email)) userData.setEmail(email);
-
- String phone = user.getPhone();
- if (!StringUtils.isEmpty(phone)) userData.setPhone(phone);
-
- String state = user.getState();
- if (!StringUtils.isEmpty(state)) userData.setState(state);
-
- String type = user.getUserType();
- if (!StringUtils.isEmpty(type)) userData.setType(type);
-
- List<String> profiles = user.getTpsProfiles();
- if (profiles != null) {
- StringBuilder sb = new StringBuilder();
- String prefix = "";
- for (String profile: profiles) {
- sb.append(prefix);
- prefix = ",";
- sb.append(profile);
- }
-
- userData.setAttribute(ATTR_TPS_PROFILES, sb.toString());
- }
-
- return userData;
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * Adds a new user to LDAP server
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
-
- @Override
- public Response addUser(UserData userData) {
-
- CMS.debug("UserService.addUser()");
-
- if (userData == null) throw new BadRequestException("User data is null.");
-
- IConfigStore cs = CMS.getConfigStore();
- String userID = userData.getUserID();
- CMS.debug("User ID: " + userID);
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- if (userID.indexOf(BACK_SLASH) != -1) {
- // backslashes (BS) are not allowed
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_RS_ID_BS"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_RS_ID_BS", headers));
- }
-
- if (userID.equals(SYSTEM_USER)) {
- // backslashes (BS) are not allowed
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_SPECIAL_ID", userID));
- throw new ForbiddenException(getUserMessage("CMS_ADMIN_SRVLT_SPECIAL_ID", headers, userID));
- }
-
- IUser user = userGroupManager.createUser(userID);
-
- String fname = userData.getFullName();
- CMS.debug("Full name: " + fname);
- if (fname == null || fname.length() == 0) {
- String msg = getUserMessage("CMS_USRGRP_USER_ADD_FAILED_1", headers, "full name");
-
- log(ILogger.LL_FAILURE, msg);
- throw new BadRequestException(msg);
-
- } else {
- user.setFullName(fname);
- }
-
- String email = userData.getEmail();
- CMS.debug("Email: " + email);
- if (email != null) {
- user.setEmail(email);
- } else {
- user.setEmail("");
- }
-
- String pword = userData.getPassword();
- CMS.debug("Password: " + (pword == null ? null : "********"));
- if (pword != null && !pword.equals("")) {
- IPasswordCheck passwdCheck = CMS.getPasswordChecker();
-
- if (!passwdCheck.isGoodPassword(pword)) {
- throw new EUsrGrpException(passwdCheck.getReason(pword));
- }
-
- user.setPassword(pword);
- } else {
- user.setPassword("");
- }
-
- String phone = userData.getPhone();
- CMS.debug("Phone: " + phone);
- if (phone != null) {
- user.setPhone(phone);
- } else {
- user.setPhone("");
- }
-
- String type = userData.getType();
- CMS.debug("Type: " + type);
- if (type != null) {
- user.setUserType(type);
- } else {
- user.setUserType("");
- }
-
- String state = userData.getState();
- CMS.debug("State: " + state);
- if (state != null) {
- user.setState(state);
- }
-
- String tpsProfiles = userData.getAttribute(ATTR_TPS_PROFILES);
- CMS.debug("TPS profiles: " + tpsProfiles);
- String csType = cs.getString("cs.type");
- if (tpsProfiles != null) {
- if (!csType.equals("TPS")) {
- throw new BadRequestException("Cannot set tpsProfiles on a non-TPS subsystem");
- }
- String[] profiles = tpsProfiles.split(",");
- user.setTpsProfiles(Arrays.asList(profiles));
- }
-
- userGroupManager.addUser(user);
-
- auditAddUser(userID, userData, ILogger.SUCCESS);
-
- // read the data back
- userData = getUserData(userID);
-
- return createCreatedResponse(userData, userData.getLink().getHref());
-
- } catch (PKIException e) {
- auditAddUser(userID, userData, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditAddUser(userID, userData, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * Replaces an existing user in local scope.
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response replaceUser(String userID, UserData userData) {
-
- if (userData == null) throw new BadRequestException("User data is null.");
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- IConfigStore cs = CMS.getConfigStore();
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = userGroupManager.createUser(userID);
-
- String fullName = userData.getFullName();
- user.setFullName(fullName);
-
- String email = userData.getEmail();
- user.setEmail(email);
-
- String pword = userData.getPassword();
- IPasswordCheck passwdCheck = CMS.getPasswordChecker();
-
- if (!passwdCheck.isGoodPassword(pword)) {
- throw new EUsrGrpException(passwdCheck.getReason(pword));
- }
-
- user.setPassword(pword);
-
- String phone = userData.getPhone();
- user.setPhone(phone);
-
- String state = userData.getState();
- user.setState(state);
-
- String csType = cs.getString("cs.type");
- if (csType.equals("TPS")) {
- String tpsProfiles = userData.getAttribute(ATTR_TPS_PROFILES);
- String[] profiles = tpsProfiles.split(",");
- user.setTpsProfiles(Arrays.asList(profiles));
- }
-
- userGroupManager.modifyUser(user);
-
- auditModifyUser(userID, userData, ILogger.SUCCESS);
-
- // read the data back
- userData = getUserData(userID);
-
- return createOKResponse(userData);
-
- } catch (PKIException e) {
- auditModifyUser(userID, userData, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditModifyUser(userID, userData, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * Modifies an existing user in local scope.
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response modifyUser(String userID, UserData userData) {
-
- if (userData == null) throw new BadRequestException("User data is null.");
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- IConfigStore cs = CMS.getConfigStore();
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = userGroupManager.createUser(userID);
-
- String fullName = userData.getFullName();
- if (fullName != null) {
- user.setFullName(fullName);
- }
-
- String email = userData.getEmail();
- if (email != null) {
- user.setEmail(email);
- }
-
- String pword = userData.getPassword();
- if (pword != null && !pword.equals("")) {
- IPasswordCheck passwdCheck = CMS.getPasswordChecker();
-
- if (!passwdCheck.isGoodPassword(pword)) {
- throw new EUsrGrpException(passwdCheck.getReason(pword));
- }
-
- user.setPassword(pword);
- }
-
- String phone = userData.getPhone();
- if (phone != null) {
- user.setPhone(phone);
- }
-
- String state = userData.getState();
- if (state != null) {
- user.setState(state);
- }
-
- String tpsProfiles = userData.getAttribute(ATTR_TPS_PROFILES);
- String csType = cs.getString("cs.type");
- if (tpsProfiles != null) {
- if (!csType.equals("TPS")) {
- throw new BadRequestException("Cannot set tpsProfiles on a non-TPS subsystem");
- }
- String[] profiles = tpsProfiles.split(",");
- user.setTpsProfiles(Arrays.asList(profiles));
- }
-
- userGroupManager.modifyUser(user);
-
- auditModifyUser(userID, userData, ILogger.SUCCESS);
-
- // read the data back
- userData = getUserData(userID);
-
- return createOKResponse(userData);
-
- } catch (PKIException e) {
- auditModifyUser(userID, userData, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditModifyUser(userID, userData, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * removes a user. user not removed if belongs to any group
- * (Administrators should remove the user from "uniquemember" of
- * any group he/she belongs to before trying to remove the user
- * itself.
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response removeUser(String userID) {
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- // get list of groups, and see if uid belongs to any
- Enumeration<IGroup> groups = userGroupManager.findGroups("*");
-
- while (groups.hasMoreElements()) {
- IGroup group = groups.nextElement();
- if (!group.isMember(userID)) continue;
-
- userGroupManager.removeUserFromGroup(group, userID);
- }
-
- // comes out clean of group membership...now remove user
- userGroupManager.removeUser(userID);
-
- auditDeleteUser(userID, ILogger.SUCCESS);
-
- return createNoContentResponse();
-
- } catch (PKIException e) {
- auditDeleteUser(userID, ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- auditDeleteUser(userID, ILogger.FAILURE);
- throw new PKIException(e.getMessage());
- }
- }
-
- public UserCertData createUserCertData(String userID, X509Certificate cert) throws Exception {
-
- UserCertData userCertData = new UserCertData();
-
- userCertData.setVersion(cert.getVersion());
- userCertData.setSerialNumber(new CertId(cert.getSerialNumber()));
- userCertData.setIssuerDN(cert.getIssuerDN().toString());
- userCertData.setSubjectDN(cert.getSubjectDN().toString());
-
- userID = URLEncoder.encode(userID, "UTF-8");
- String certID = URLEncoder.encode(userCertData.getID(), "UTF-8");
- URI uri = uriInfo.getBaseUriBuilder()
- .path(UserResource.class)
- .path("{userID}/certs/{certID}")
- .build(userID, certID);
- userCertData.setLink(new Link("self", uri));
-
- return userCertData;
- }
-
- /**
- * List user certificate(s)
- *
- * Request/Response Syntax:
- * http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- */
- @Override
- public Response findUserCerts(String userID, Integer start, Integer size) {
- try {
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = null;
-
- try {
- user = userGroupManager.getUser(userID);
- } catch (Exception e) {
- throw new PKIException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST", headers));
- }
-
- if (user == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST"));
- throw new UserNotFoundException(userID);
- }
-
- X509Certificate[] certs = user.getX509Certificates();
- if (certs == null) certs = new X509Certificate[0];
- Iterator<X509Certificate> entries = Arrays.asList(certs).iterator();
-
- UserCertCollection response = new UserCertCollection();
- int i = 0;
-
- // skip to the start of the page
- for ( ; i<start && entries.hasNext(); i++) entries.next();
-
- // return entries up to the page size
- for ( ; i<start+size && entries.hasNext(); i++) {
- response.addEntry(createUserCertData(userID, entries.next()));
- }
-
- // count the total entries
- for ( ; entries.hasNext(); i++) entries.next();
- response.setTotal(i);
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- response.addLink(new Link("prev", uri));
- }
-
- if (start+size < i) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- response.addLink(new Link("next", uri));
- }
-
- return createOKResponse(response);
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- throw new PKIException(e.getMessage());
- }
- }
-
- @Override
- public Response getUserCert(String userID, String certID) {
- return createOKResponse(getUserCertData(userID, certID));
- }
-
- public UserCertData getUserCertData(String userID, String certID) {
-
- if (certID == null) throw new BadRequestException("Certificate ID is null.");
-
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
-
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = null;
-
- try {
- user = userGroupManager.getUser(userID);
- } catch (Exception e) {
- throw new PKIException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST", headers));
- }
-
- if (user == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST"));
- throw new UserNotFoundException(userID);
- }
-
- X509Certificate[] certs = user.getX509Certificates();
-
- if (certs == null) {
- throw new ResourceNotFoundException("No certificates found for " + userID);
- }
-
- try {
- certID = URLDecoder.decode(certID, "UTF-8");
- } catch (Exception e) {
- throw new PKIException(e.getMessage());
- }
-
- for (X509Certificate cert : certs) {
-
- UserCertData userCertData = createUserCertData(userID, cert);
-
- if (!userCertData.getID().equals(certID)) continue;
-
- ICertPrettyPrint print = CMS.getCertPrettyPrint(cert);
- userCertData.setPrettyPrint(print.toString(getLocale(headers)));
-
- // add base64 encoding
- String base64 = CMS.getEncodedCert(cert);
- userCertData.setEncoded(base64);
-
- return userCertData;
- }
-
- throw new ResourceNotFoundException("No certificates found for " + userID);
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- throw new PKIException(e.getMessage());
- }
- }
-
- /**
- * Adds a certificate to a user
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response addUserCert(String userID, UserCertData userCertData) {
-
- if (userCertData == null) throw new BadRequestException("Certificate data is null.");
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = userGroupManager.createUser(userID);
-
- String encoded = userCertData.getEncoded();
- encoded = Cert.normalizeCertStrAndReq(encoded);
- encoded = Cert.stripBrackets(encoded);
-
- // no cert is a success
- if (encoded == null) {
- auditAddUserCert(userID, userCertData, ILogger.SUCCESS);
- return createOKResponse();
- }
-
- // only one cert added per operation
- X509Certificate cert = null;
-
- // Base64 decode cert
- byte binaryCert[] = Utils.base64decode(encoded);
-
- try {
- cert = new X509CertImpl(binaryCert);
-
- } catch (CertificateException e) {
- // ignore
- }
-
- if (cert == null) {
- // cert chain direction
- boolean assending = true;
-
- // could it be a pkcs7 blob?
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_IS_PK_BLOB"));
-
- try {
- CryptoManager manager = CryptoManager.getInstance();
-
- PKCS7 pkcs7 = new PKCS7(binaryCert);
-
- X509Certificate p7certs[] = pkcs7.getCertificates();
-
- if (p7certs.length == 0) {
- throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers));
- }
-
- // fix for 370099 - cert ordering can not be assumed
- // find out the ordering ...
-
- // self-signed and alone? take it. otherwise test
- // the ordering
- if (p7certs[0].getSubjectDN().toString().equals(
- p7certs[0].getIssuerDN().toString()) &&
- (p7certs.length == 1)) {
- cert = p7certs[0];
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_SINGLE_CERT_IMPORT"));
-
- } else if (p7certs[0].getIssuerDN().toString().equals(p7certs[1].getSubjectDN().toString())) {
- cert = p7certs[0];
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_ACEND_ORD"));
-
- } else if (p7certs[1].getIssuerDN().toString().equals(p7certs[0].getSubjectDN().toString())) {
- assending = false;
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_CHAIN_DESC_ORD"));
- cert = p7certs[p7certs.length - 1];
-
- } else {
- // not a chain, or in random order
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_CERT_BAD_CHAIN"));
- throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers));
- }
-
- CMS.debug("UserCertResourceService: "
- + CMS.getLogMessage("ADMIN_SRVLT_CHAIN_STORED_DB", String.valueOf(p7certs.length)));
-
- int j = 0;
- int jBegin = 0;
- int jEnd = 0;
-
- if (assending == true) {
- jBegin = 1;
- jEnd = p7certs.length;
- } else {
- jBegin = 0;
- jEnd = p7certs.length - 1;
- }
-
- // store the chain into cert db, except for the user cert
- for (j = jBegin; j < jEnd; j++) {
- CMS.debug("UserCertResourceService: "
- + CMS.getLogMessage("ADMIN_SRVLT_CERT_IN_CHAIN", String.valueOf(j),
- String.valueOf(p7certs[j].getSubjectDN())));
- org.mozilla.jss.crypto.X509Certificate leafCert =
- manager.importCACertPackage(p7certs[j].getEncoded());
-
- if (leafCert == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NULL"));
- } else {
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_LEAF_CERT_NON_NULL"));
- }
-
- if (leafCert instanceof InternalCertificate) {
- ((InternalCertificate) leafCert).setSSLTrust(
- InternalCertificate.VALID_CA |
- InternalCertificate.TRUSTED_CA |
- InternalCertificate.TRUSTED_CLIENT_CA);
- } else {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NOT_INTERNAL_CERT",
- String.valueOf(p7certs[j].getSubjectDN())));
- }
- }
-
- /*
- } catch (CryptoManager.UserCertConflictException e) {
- // got a "user cert" in the chain, most likely the CA
- // cert of this instance, which has a private key. Ignore
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_PKS7_IGNORED", e.toString()));
- */
- } catch (PKIException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
- throw e;
- } catch (Exception e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString()));
- throw new PKIException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR", headers));
- }
- }
-
- try {
- CMS.debug("UserCertResourceService: " + CMS.getLogMessage("ADMIN_SRVLT_BEFORE_VALIDITY"));
- cert.checkValidity(); // throw exception if fails
-
- user.setX509Certificates(new X509Certificate[] { cert });
- userGroupManager.addUserCert(user);
-
- auditAddUserCert(userID, userCertData, ILogger.SUCCESS);
-
- // read the data back
-
- userCertData.setVersion(cert.getVersion());
- userCertData.setSerialNumber(new CertId(cert.getSerialNumber()));
- userCertData.setIssuerDN(cert.getIssuerDN().toString());
- userCertData.setSubjectDN(cert.getSubjectDN().toString());
- String certID = userCertData.getID();
-
- userCertData = getUserCertData(userID, URLEncoder.encode(certID, "UTF-8"));
-
- return createCreatedResponse(userCertData, userCertData.getLink().getHref());
-
- } catch (CertificateExpiredException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED",
- String.valueOf(cert.getSubjectDN())));
- throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_EXPIRED", headers));
-
- } catch (CertificateNotYetValidException e) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID",
- String.valueOf(cert.getSubjectDN())));
- throw new BadRequestException(getUserMessage("CMS_USRGRP_SRVLT_CERT_NOT_YET_VALID", headers));
- }
-
- } catch (PKIException e) {
- auditAddUserCert(userID, userCertData, ILogger.FAILURE);
- throw e;
-
- } catch (Exception e) {
- log(ILogger.LL_FAILURE, e.toString());
- auditAddUserCert(userID, userCertData, ILogger.FAILURE);
- throw new PKIException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED", headers));
- }
- }
-
- /**
- * Removes a certificate for a user
- * <P>
- *
- * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/
- * ui/admin-protocol-definition.html#user-admin
- * <P>
- *
- * In this method, "certDN" is actually a combination of version, serialNumber, issuerDN, and SubjectDN.
- * <P>
- *
- * <ul>
- * <li>signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under
- * users/groups)
- * </ul>
- */
- @Override
- public Response removeUserCert(String userID, String certID) {
-
- if (userID == null) throw new BadRequestException("User ID is null.");
- if (certID == null) throw new BadRequestException("Certificate ID is null.");
-
- try {
- certID = URLDecoder.decode(certID, "UTF-8");
- } catch (Exception e) {
- throw new PKIException(e.getMessage());
- }
-
- UserCertData userCertData = new UserCertData();
- userCertData.setID(certID);
- removeUserCert(userID, userCertData);
-
- return createNoContentResponse();
- }
-
- public void removeUserCert(String userID, UserCertData userCertData) {
-
- // ensure that any low-level exceptions are reported
- // to the signed audit log and stored as failures
- try {
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = userGroupManager.createUser(userID);
- String certID = userCertData.getID();
-
- // no certDN is a success
- if (certID == null) {
- auditDeleteUserCert(userID, userCertData, ILogger.SUCCESS);
- return;
- }
-
- user.setCertDN(certID);
-
- userGroupManager.removeUserCert(user);
-
- auditDeleteUserCert(userID, userCertData, ILogger.SUCCESS);
-
- } catch (PKIException e) {
- auditDeleteUserCert(userID, userCertData, ILogger.FAILURE);
- throw e;
-
- } catch (Exception e) {
- log(ILogger.LL_FAILURE, e.toString());
- auditDeleteUserCert(userID, userCertData, ILogger.FAILURE);
- throw new PKIException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED", headers));
- }
- }
-
-
- public UserMembershipData createUserMembershipData(String userID, String groupID) throws UnsupportedEncodingException {
-
- UserMembershipData userMembershipData = new UserMembershipData();
- userMembershipData.setID(groupID);
- userMembershipData.setUserID(userID);
-
- URI uri = uriInfo.getBaseUriBuilder()
- .path(UserResource.class)
- .path("{userID}/memberships/{groupID}")
- .build(
- URLEncoder.encode(userID, "UTF-8"),
- URLEncoder.encode(groupID, "UTF-8"));
-
- userMembershipData.setLink(new Link("self", uri));
-
- return userMembershipData;
- }
-
- @Override
- public Response findUserMemberships(String userID, Integer start, Integer size) {
- try {
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- if (userID == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID"));
- throw new BadRequestException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID", headers));
- }
-
- IUser user = userGroupManager.getUser(userID);
-
- if (user == null) {
- log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST"));
- throw new UserNotFoundException(userID);
- }
-
- Enumeration<IGroup> groups = userGroupManager.findGroupsByUser(user.getUserDN());
-
- UserMembershipCollection response = new UserMembershipCollection();
- int i = 0;
-
- // skip to the start of the page
- for ( ; i<start && groups.hasMoreElements(); i++) groups.nextElement();
-
- // return entries up to the page size
- for ( ; i<start+size && groups.hasMoreElements(); i++) {
- IGroup group = groups.nextElement();
- response.addEntry(createUserMembershipData(userID, group.getName()));
- }
-
- // count the total entries
- for ( ; groups.hasMoreElements(); i++) groups.nextElement();
- response.setTotal(i);
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- response.addLink(new Link("prev", uri));
- }
-
- if (start+size < i) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- response.addLink(new Link("next", uri));
- }
-
- return createOKResponse(response);
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- @Override
- public Response addUserMembership(String userID, String groupID) {
-
- if (userID == null) throw new BadRequestException("User ID is null.");
- if (groupID == null) throw new BadRequestException("Group ID is null.");
-
- try {
- GroupMemberData groupMemberData = new GroupMemberData();
- groupMemberData.setID(userID);
- groupMemberData.setGroupID(groupID);
-
- GroupMemberProcessor processor = new GroupMemberProcessor(getLocale(headers));
- processor.setUriInfo(uriInfo);
- processor.addGroupMember(groupMemberData);
-
- UserMembershipData userMembershipData = createUserMembershipData(userID, groupID);
-
- return createCreatedResponse(userMembershipData, userMembershipData.getLink().getHref());
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- @Override
- public Response removeUserMembership(String userID, String groupID) {
-
- if (userID == null) throw new BadRequestException("User ID is null.");
- if (groupID == null) throw new BadRequestException("Group ID is null.");
-
- try {
- GroupMemberProcessor processor = new GroupMemberProcessor(getLocale(headers));
- processor.setUriInfo(uriInfo);
- processor.removeGroupMember(groupID, userID);
-
- return createNoContentResponse();
-
- } catch (PKIException e) {
- throw e;
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- public void log(int level, String message) {
- log(ILogger.S_USRGRP, level, message);
- }
-
- public void auditAddUser(String id, UserData userData, String status) {
- auditUser(OpDef.OP_ADD, id, getParams(userData), status);
- }
-
- public void auditModifyUser(String id, UserData userData, String status) {
- auditUser(OpDef.OP_MODIFY, id, getParams(userData), status);
- }
-
- public void auditDeleteUser(String id, String status) {
- auditUser(OpDef.OP_DELETE, id, null, status);
- }
-
- public void auditAddUserCert(String id, UserCertData userCertData, String status) {
- auditUserCert(OpDef.OP_ADD, id, getParams(userCertData), status);
- }
-
- public void auditDeleteUserCert(String id, UserCertData userCertData, String status) {
- auditUserCert(OpDef.OP_DELETE, id, getParams(userCertData), status);
- }
-
- public void auditUser(String type, String id, Map<String, String> params, String status) {
- audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_USERS, type, id, params, status);
- }
-
- public void auditUserCert(String type, String id, Map<String, String> params, String status) {
- audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_USER_CERTS, type, id, params, status);
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/cert/CertService.java b/base/server/cms/src/com/netscape/cms/servlet/cert/CertService.java
deleted file mode 100644
index e8e735e46..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/cert/CertService.java
+++ /dev/null
@@ -1,654 +0,0 @@
-// --- 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) 2011 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.cert;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.math.BigInteger;
-import java.net.URI;
-import java.security.InvalidKeyException;
-import java.security.Principal;
-import java.security.PublicKey;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import netscape.security.pkcs.ContentInfo;
-import netscape.security.pkcs.PKCS7;
-import netscape.security.pkcs.SignerInfo;
-import netscape.security.provider.RSAPublicKey;
-import netscape.security.x509.AlgorithmId;
-import netscape.security.x509.RevocationReason;
-import netscape.security.x509.X509CertImpl;
-import netscape.security.x509.X509Key;
-
-import org.jboss.resteasy.plugins.providers.atom.Link;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.ICertPrettyPrint;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.UnauthorizedException;
-import com.netscape.certsrv.ca.ICertificateAuthority;
-import com.netscape.certsrv.cert.CertData;
-import com.netscape.certsrv.cert.CertDataInfo;
-import com.netscape.certsrv.cert.CertDataInfos;
-import com.netscape.certsrv.cert.CertNotFoundException;
-import com.netscape.certsrv.cert.CertResource;
-import com.netscape.certsrv.cert.CertRetrievalRequest;
-import com.netscape.certsrv.cert.CertRevokeRequest;
-import com.netscape.certsrv.cert.CertSearchRequest;
-import com.netscape.certsrv.cert.CertUnrevokeRequest;
-import com.netscape.certsrv.dbs.EDBRecordNotFoundException;
-import com.netscape.certsrv.dbs.certdb.CertId;
-import com.netscape.certsrv.dbs.certdb.ICertRecord;
-import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
-import com.netscape.certsrv.logging.AuditFormat;
-import com.netscape.certsrv.logging.ILogger;
-import com.netscape.certsrv.request.IRequest;
-import com.netscape.cms.realm.PKIPrincipal;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cms.servlet.processors.CAProcessor;
-import com.netscape.cmsutil.ldap.LDAPUtil;
-import com.netscape.cmsutil.util.Utils;
-
-/**
- * @author alee
- *
- */
-public class CertService extends PKIService implements CertResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- ICertificateAuthority authority;
- ICertificateRepository repo;
- Random random;
-
- public static final int DEFAULT_MAXTIME = 0;
- public static final int DEFAULT_MAXRESULTS = 20;
- public final static int DEFAULT_SIZE = 20;
-
- public CertService() {
- authority = (ICertificateAuthority) CMS.getSubsystem("ca");
- if (authority.noncesEnabled()) {
- random = new Random();
- }
- repo = authority.getCertificateRepository();
- }
-
- @Override
- public Response getCert(CertId id) {
- return createOKResponse(getCertData(id));
- }
-
- @Override
- public Response reviewCert(CertId id) {
- return createOKResponse(getCertData(id, true));
- }
-
- public CertData getCertData(CertId id) {
- return getCertData(id, false);
- }
-
- public CertData getCertData(CertId id, boolean generateNonce) {
- if (id == null) {
- throw new BadRequestException("Unable to get certificate: Invalid id.");
- }
-
- CertRetrievalRequest data = new CertRetrievalRequest();
- data.setCertId(id);
-
- CertData certData = null;
-
- try {
- certData = getCert(data, generateNonce);
- } catch (EDBRecordNotFoundException e) {
- throw new CertNotFoundException(id);
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage(), e);
- } catch (CertificateEncodingException e) {
- throw new PKIException(e.getMessage(), e);
- }
-
- return certData;
- }
-
- @Override
- public Response revokeCACert(CertId id, CertRevokeRequest request) {
- return revokeCert(id, request, true);
- }
-
- @Override
- public Response revokeCert(CertId id, CertRevokeRequest request) {
- return revokeCert(id, request, false);
- }
-
- public Response revokeCert(CertId id, CertRevokeRequest request, boolean caCert) {
- if (id == null) {
- CMS.debug("revokeCert: id is null");
- throw new BadRequestException("Unable to revoke cert: invalid id");
- }
- if (request == null) {
- CMS.debug("revokeCert: request is null");
- throw new BadRequestException("Unable to revoke cert: invalid request");
- }
-
- // check cert actually exists. This will throw a CertNotFoundException
- // if the cert does not exist
- @SuppressWarnings("unused")
- CertData data = getCertData(id);
-
- RevocationReason revReason = request.getReason();
- if (revReason == RevocationReason.REMOVE_FROM_CRL) {
- CertUnrevokeRequest unrevRequest = new CertUnrevokeRequest();
- unrevRequest.setRequestID(request.getRequestID());
- return unrevokeCert(id, unrevRequest);
- }
-
- RevocationProcessor processor;
- try {
- processor = new RevocationProcessor("caDoRevoke-agent", getLocale(headers));
- processor.setStartTime(CMS.getCurrentDate().getTime());
-
- // TODO: set initiative based on auth info
- processor.setInitiative(AuditFormat.FROMAGENT);
-
- processor.setSerialNumber(id);
- processor.setRequestID(request.getRequestID());
-
- processor.setRevocationReason(revReason);
- processor.setRequestType(revReason == RevocationReason.CERTIFICATE_HOLD
- ? RevocationProcessor.ON_HOLD : RevocationProcessor.REVOKE);
- processor.setInvalidityDate(request.getInvalidityDate());
- processor.setComments(request.getComments());
-
- processor.setAuthority(authority);
-
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage());
- }
-
- try {
- X509Certificate clientCert = null;
- try {
- clientCert = CAProcessor.getSSLClientCertificate(servletRequest);
- } catch (EBaseException e) {
- // No client certificate, ignore.
- }
-
- ICertRecord clientRecord = null;
- BigInteger clientSerialNumber = null;
- String clientSubjectDN = null;
-
- if (clientCert != null) {
- clientSerialNumber = clientCert.getSerialNumber();
- clientSubjectDN = clientCert.getSubjectDN().toString();
- clientRecord = processor.getCertificateRecord(clientSerialNumber);
-
- // Verify client cert is not revoked.
- // TODO: This should be checked during authentication.
- if (clientRecord.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
- throw new UnauthorizedException(CMS.getLogMessage("CMSGW_UNAUTHORIZED"));
- }
- }
-
- if (authority.noncesEnabled() &&
- !processor.isMemberOfSubsystemGroup(clientCert)) {
- processor.validateNonce(servletRequest, "cert-revoke", id.toBigInteger(), request.getNonce());
-
- }
-
- // Find target cert record if different from client cert.
- ICertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id);
- X509CertImpl targetCert = targetRecord.getCertificate();
-
- processor.createCRLExtension();
-
- PKIPrincipal principal = (PKIPrincipal)servletRequest.getUserPrincipal();
- // TODO: do not hard-code role name
- String subjectDN = principal.hasRole("Certificate Manager Agents") ?
- null : clientSubjectDN;
-
- processor.validateCertificateToRevoke(subjectDN, targetRecord, caCert);
- processor.addCertificateToRevoke(targetCert);
- processor.createRevocationRequest();
-
- processor.auditChangeRequest(ILogger.SUCCESS);
-
- } catch (PKIException e) {
- processor.log(ILogger.LL_FAILURE, e.getMessage());
- processor.auditChangeRequest(ILogger.FAILURE);
- throw e;
-
- } catch (EBaseException e) {
- processor.log(ILogger.LL_FAILURE, "Error " + e);
- processor.auditChangeRequest(ILogger.FAILURE);
-
- throw new PKIException(e.getMessage());
-
- } catch (IOException e) {
- processor.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED_1", e.toString()));
- processor.auditChangeRequest(ILogger.FAILURE);
-
- throw new PKIException(CMS.getLogMessage("CMSGW_ERROR_MARKING_CERT_REVOKED"));
- }
-
- // change audit processing from "REQUEST" to "REQUEST_PROCESSED"
- // to distinguish which type of signed audit log message to save
- // as a failure outcome in case an exception occurs
-
- try {
- processor.processRevocationRequest();
-
- processor.auditChangeRequestProcessed(ILogger.SUCCESS);
-
- } catch (EBaseException e) {
- processor.log(ILogger.LL_FAILURE, "Error " + e);
- processor.auditChangeRequestProcessed(ILogger.FAILURE);
-
- throw new PKIException(e.getMessage());
- }
-
- try {
- IRequest certRequest = processor.getRequest();
- CertRequestDAO dao = new CertRequestDAO();
- return createOKResponse(dao.getRequest(certRequest.getRequestId(), uriInfo));
-
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage());
- }
- }
-
- @Override
- public Response unrevokeCert(CertId id, CertUnrevokeRequest request) {
- if (id == null) {
- CMS.debug("unrevokeCert: id is null");
- throw new BadRequestException("Unable to unrevoke cert: invalid id");
- }
- if (request == null) {
- CMS.debug("unrevokeCert: request is null");
- throw new BadRequestException("Unable to unrevoke cert: invalid request");
- }
-
- // check cert actually exists. This will throw a CertNotFoundException
- // if the cert does not exist
- @SuppressWarnings("unused")
- CertData data = getCertData(id);
-
- RevocationProcessor processor;
- try {
- processor = new RevocationProcessor("caDoUnrevoke", getLocale(headers));
-
- // TODO: set initiative based on auth info
- processor.setInitiative(AuditFormat.FROMAGENT);
-
- processor.setSerialNumber(id);
- processor.setRequestID(request.getRequestID());
- processor.setRevocationReason(RevocationReason.CERTIFICATE_HOLD);
- processor.setAuthority(authority);
-
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage());
- }
-
- try {
- processor.addSerialNumberToUnrevoke(id.toBigInteger());
- processor.createUnrevocationRequest();
-
- processor.auditChangeRequest(ILogger.SUCCESS);
-
- } catch (EBaseException e) {
- processor.log(ILogger.LL_FAILURE, "Error " + e);
- processor.auditChangeRequest(ILogger.FAILURE);
-
- throw new PKIException(e.getMessage());
- }
-
- // change audit processing from "REQUEST" to "REQUEST_PROCESSED"
- // to distinguish which type of signed audit log message to save
- // as a failure outcome in case an exception occurs
-
- try {
- processor.processUnrevocationRequest();
-
- processor.auditChangeRequestProcessed(ILogger.SUCCESS);
-
- } catch (EBaseException e) {
- processor.log(ILogger.LL_FAILURE, "Error " + e);
- processor.auditChangeRequestProcessed(ILogger.FAILURE);
-
- throw new PKIException(e.getMessage());
- }
-
- try {
- IRequest certRequest = processor.getRequest();
- CertRequestDAO dao = new CertRequestDAO();
- return createOKResponse(dao.getRequest(certRequest.getRequestId(), uriInfo));
-
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage());
- }
- }
-
- private String createSearchFilter(String status) {
- String filter = "";
-
- if ((status == null)) {
- filter = "(serialno=*)";
- return filter;
- }
-
- if (status != null) {
- filter += "(certStatus=" + LDAPUtil.escapeFilter(status) + ")";
- }
-
- return filter;
- }
-
- private String createSearchFilter(CertSearchRequest data) {
- if (data == null) {
- return null;
- }
- FilterBuilder builder = new FilterBuilder(data);
- return builder.buildFilter();
- }
-
- @Override
- public Response listCerts(String status, Integer maxResults, Integer maxTime, Integer start, Integer size) {
-
- maxResults = maxResults == null ? DEFAULT_MAXRESULTS : maxResults;
- maxTime = maxTime == null ? DEFAULT_MAXTIME : maxTime;
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- String filter = createSearchFilter(status);
- CMS.debug("listCerts: filter is " + filter);
-
- CertDataInfos infos = new CertDataInfos();
- try {
- Enumeration<ICertRecord> e = repo.searchCertificates(filter, maxResults, maxTime);
- if (e == null) {
- throw new EBaseException("search results are null");
- }
-
- // store non-null results in a list
- List<CertDataInfo> results = new ArrayList<CertDataInfo>();
- while (e.hasMoreElements()) {
- ICertRecord rec = e.nextElement();
- if (rec == null) continue;
- results.add(createCertDataInfo(rec));
- }
-
- int total = results.size();
- infos.setTotal(total);
-
- // return entries in the requested page
- for (int i = start; i < start + size && i < total ; i++) {
- infos.addEntry(results.get(i));
- }
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start - size, 0)).build();
- infos.addLink(new Link("prev", uri));
- }
-
- if (start + size < total) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start + size).build();
- infos.addLink(new Link("next", uri));
- }
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error listing certs in CertService.listCerts!", e);
- }
-
- return createOKResponse(infos);
- }
-
- @Override
- public Response searchCerts(CertSearchRequest data, Integer start, Integer size) {
-
- if (data == null) {
- throw new BadRequestException("Search request is null.");
- }
-
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
- String filter = createSearchFilter(data);
-
- CertDataInfos infos = new CertDataInfos();
- try {
- Enumeration<ICertRecord> e = repo.findCertRecords(filter);
- if (e == null) {
- throw new EBaseException("search results are null");
- }
-
- int i = 0;
-
- // skip to the start of the page
- for (; i < start && e.hasMoreElements(); i++)
- e.nextElement();
-
- // return entries up to the page size
- for (; i < start + size && e.hasMoreElements(); i++) {
- ICertRecord user = e.nextElement();
- infos.addEntry(createCertDataInfo(user));
- }
-
- // count the total entries
- for (; e.hasMoreElements(); i++)
- e.nextElement();
-
- infos.setTotal(i);
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start - size, 0)).build();
- infos.addLink(new Link("prev", uri));
- }
-
- if (start + size < i) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start + size).build();
- infos.addLink(new Link("next", uri));
- }
-
- } catch (Exception e1) {
- throw new PKIException("Error searching certs in CertService.searchCerts!", e1);
- }
-
- return createOKResponse(infos);
- }
-
- public CertData getCert(CertRetrievalRequest data, boolean generateNonce) throws EBaseException, CertificateEncodingException {
- CertId certId = data.getCertId();
-
- //find the cert in question
- ICertRecord record = repo.readCertificateRecord(certId.toBigInteger());
- X509CertImpl cert = record.getCertificate();
-
- CertData certData = new CertData();
-
- certData.setSerialNumber(certId);
-
- Principal issuerDN = cert.getIssuerDN();
- if (issuerDN != null) certData.setIssuerDN(issuerDN.toString());
-
- Principal subjectDN = cert.getSubjectDN();
- if (subjectDN != null) certData.setSubjectDN(subjectDN.toString());
-
- String base64 = CMS.getEncodedCert(cert);
- certData.setEncoded(base64);
-
- ICertPrettyPrint print = CMS.getCertPrettyPrint(cert);
- certData.setPrettyPrint(print.toString(getLocale(headers)));
-
- String p7Str = getCertChainData(cert);
- certData.setPkcs7CertChain(p7Str);
-
- Date notBefore = cert.getNotBefore();
- if (notBefore != null) certData.setNotBefore(notBefore.toString());
-
- Date notAfter = cert.getNotAfter();
- if (notAfter != null) certData.setNotAfter(notAfter.toString());
-
- certData.setStatus(record.getStatus());
-
- if (authority.noncesEnabled() && generateNonce) {
- // generate nonce
- long n = random.nextLong();
- // store nonce in session
- Map<Object, Long> nonces = authority.getNonces(servletRequest, "cert-revoke");
- nonces.put(certId.toBigInteger(), n);
- // return nonce to client
- certData.setNonce(n);
- }
-
- URI uri = uriInfo.getBaseUriBuilder().path(CertResource.class).path("{id}").build(certId.toHexString());
- certData.setLink(new Link("self", uri));
-
- return certData;
- }
-
- private CertDataInfo createCertDataInfo(ICertRecord record) throws EBaseException, InvalidKeyException {
- CertDataInfo info = new CertDataInfo();
-
- CertId id = new CertId(record.getSerialNumber());
- info.setID(id);
-
- X509Certificate cert = record.getCertificate();
- info.setSubjectDN(cert.getSubjectDN().toString());
- info.setStatus(record.getStatus());
- info.setVersion(cert.getVersion());
- info.setType(cert.getType());
-
- PublicKey key = cert.getPublicKey();
- if (key instanceof X509Key) {
- X509Key x509Key = (X509Key)key;
- info.setKeyAlgorithmOID(x509Key.getAlgorithmId().getOID().toString());
-
- if (x509Key.getAlgorithmId().toString().equalsIgnoreCase("RSA")) {
- RSAPublicKey rsaKey = new RSAPublicKey(x509Key.getEncoded());
- info.setKeyLength(rsaKey.getKeySize());
- }
- }
-
- info.setNotValidBefore(cert.getNotBefore());
- info.setNotValidAfter(cert.getNotAfter());
-
- info.setIssuedOn(record.getCreateTime());
- info.setIssuedBy(record.getIssuedBy());
-
- URI uri = uriInfo.getBaseUriBuilder().path(CertResource.class).path("{id}").build(id.toHexString());
- info.setLink(new Link("self", uri));
-
- return info;
- }
-
- private String getCertChainData(X509CertImpl x509cert) {
- X509Certificate mCACerts[];
-
- if (x509cert == null) {
- return null;
- }
-
- try {
- mCACerts = authority.getCACertChain().getChain();
- } catch (Exception e) {
- mCACerts = null;
- }
-
- X509CertImpl[] certsInChain = new X509CertImpl[1];
-
- int mCACertsLength = 0;
- boolean certAlreadyInChain = false;
- int certsInChainLength = 0;
- if (mCACerts != null) {
- mCACertsLength = mCACerts.length;
- for (int i = 0; i < mCACertsLength; i++) {
- if (x509cert.equals(mCACerts[i])) {
- certAlreadyInChain = true;
- break;
- }
- }
-
- if (certAlreadyInChain == true) {
- certsInChainLength = mCACertsLength;
- } else {
- certsInChainLength = mCACertsLength + 1;
- }
-
- certsInChain = new X509CertImpl[certsInChainLength];
-
- }
-
- certsInChain[0] = x509cert;
-
- if (mCACerts != null) {
- int curCount = 1;
- for (int i = 0; i < mCACertsLength; i++) {
- if (!x509cert.equals(mCACerts[i])) {
- certsInChain[curCount] = (X509CertImpl) mCACerts[i];
- curCount++;
- }
-
- }
- }
-
- String p7Str;
-
- try {
- PKCS7 p7 = new PKCS7(new AlgorithmId[0],
- new ContentInfo(new byte[0]),
- certsInChain,
- new SignerInfo[0]);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
-
- p7.encodeSignedData(bos, false);
- byte[] p7Bytes = bos.toByteArray();
-
- p7Str = Utils.base64encode(p7Bytes);
- } catch (Exception e) {
- p7Str = null;
- }
-
- return p7Str;
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java b/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java
index ded7c1eed..2ef7090f6 100644
--- a/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java
+++ b/base/server/cms/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java
@@ -158,11 +158,11 @@ import com.netscape.certsrv.system.InstallToken;
import com.netscape.certsrv.system.SecurityDomainClient;
import com.netscape.certsrv.system.TPSConnectorClient;
import com.netscape.certsrv.system.TPSConnectorData;
+import com.netscape.certsrv.user.UserResource;
import com.netscape.certsrv.usrgrp.EUsrGrpException;
import com.netscape.certsrv.usrgrp.IGroup;
import com.netscape.certsrv.usrgrp.IUGSubsystem;
import com.netscape.certsrv.usrgrp.IUser;
-import com.netscape.cms.servlet.admin.UserService;
import com.netscape.cmsutil.crypto.CryptoUtil;
import com.netscape.cmsutil.http.HttpClient;
import com.netscape.cmsutil.http.HttpRequest;
@@ -3759,7 +3759,7 @@ public class ConfigurationUtils {
IUser user = system.getUser(adminID);
List<String> profiles = new ArrayList<String>();
- profiles.add(UserService.ALL_PROFILES);
+ profiles.add(UserResource.ALL_PROFILES);
user.setTpsProfiles(profiles);
system.modifyUser(user);
diff --git a/base/server/cms/src/com/netscape/cms/servlet/csadmin/SecurityDomainService.java b/base/server/cms/src/com/netscape/cms/servlet/csadmin/SecurityDomainService.java
deleted file mode 100644
index 399c28a35..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/csadmin/SecurityDomainService.java
+++ /dev/null
@@ -1,74 +0,0 @@
-// --- BEGIN COPYRIGHT BLOCK ---
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License along
-// with this program; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// (C) 2012 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-package com.netscape.cms.servlet.csadmin;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.UriInfo;
-
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.system.DomainInfo;
-import com.netscape.certsrv.system.InstallToken;
-import com.netscape.certsrv.system.SecurityDomainResource;
-import com.netscape.cms.servlet.base.PKIService;
-
-/**
- * @author alee
- */
-public class SecurityDomainService extends PKIService implements SecurityDomainResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- @Override
- public InstallToken getInstallToken(String hostname, String subsystem) {
- try {
- // Get uid from realm authentication.
- String user = servletRequest.getUserPrincipal().getName();
-
- SecurityDomainProcessor processor = new SecurityDomainProcessor(getLocale(headers));
- return processor.getInstallToken(user, hostname, subsystem);
-
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage(), e);
- }
- }
-
- @Override
- public DomainInfo getDomainInfo() throws PKIException {
- try {
- SecurityDomainProcessor processor = new SecurityDomainProcessor(getLocale(headers));
- return processor.getDomainInfo();
-
- } catch (EBaseException e) {
- throw new PKIException(e.getMessage(), e);
- }
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java b/base/server/cms/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java
deleted file mode 100644
index a2c7b525b..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java
+++ /dev/null
@@ -1,1295 +0,0 @@
-// --- BEGIN COPYRIGHT BLOCK ---
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; version 2 of the License.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License along
-// with this program; if not, write to the Free Software Foundation, Inc.,
-// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// (C) 2012 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-package com.netscape.cms.servlet.csadmin;
-
-import java.math.BigInteger;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.security.NoSuchAlgorithmException;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.Random;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.UriInfo;
-
-import netscape.security.x509.X509CertImpl;
-
-import org.mozilla.jss.CryptoManager;
-import org.mozilla.jss.CryptoManager.NotInitializedException;
-import org.mozilla.jss.NoSuchTokenException;
-import org.mozilla.jss.crypto.CryptoToken;
-import org.mozilla.jss.crypto.TokenException;
-import org.mozilla.jss.util.IncorrectPasswordException;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.EPropertyNotFound;
-import com.netscape.certsrv.base.IConfigStore;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.ca.ICertificateAuthority;
-import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
-import com.netscape.certsrv.ocsp.IOCSPAuthority;
-import com.netscape.certsrv.system.ConfigurationRequest;
-import com.netscape.certsrv.system.ConfigurationResponse;
-import com.netscape.certsrv.system.SystemCertData;
-import com.netscape.certsrv.system.SystemConfigResource;
-import com.netscape.certsrv.usrgrp.IUGSubsystem;
-import com.netscape.certsrv.usrgrp.IUser;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cmsutil.crypto.CryptoUtil;
-import com.netscape.cmsutil.util.Utils;
-
-/**
- * @author alee
- *
- */
-public class SystemConfigService extends PKIService implements SystemConfigResource {
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- IConfigStore cs;
- String csType;
- String csSubsystem;
- String csState;
- boolean isMasterCA = false;
- String instanceRoot;
-
- public static String SUCCESS = "0";
- public static final String RESTART_SERVER_AFTER_CONFIGURATION =
- "restart_server_after_configuration";
-
- public SystemConfigService() throws EPropertyNotFound, EBaseException {
- cs = CMS.getConfigStore();
- csType = cs.getString("cs.type");
- csSubsystem = csType.toLowerCase();
- csState = cs.getString("cs.state");
- String domainType = cs.getString("securitydomain.select", "existingdomain");
- if (csType.equals("CA") && domainType.equals("new")) {
- isMasterCA = true;
- }
- instanceRoot = cs.getString("instanceRoot");
- }
-
- /* (non-Javadoc)
- * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(javax.ws.rs.core.MultivaluedMap)
- */
- @Override
- public ConfigurationResponse configure(MultivaluedMap<String, String> form) {
- ConfigurationRequest data = new ConfigurationRequest(form);
- return configure(data);
- }
-
- /* (non-Javadoc)
- * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(com.netscape.cms.servlet.csadmin.data.ConfigurationData)
- */
- @Override
- public ConfigurationResponse configure(ConfigurationRequest data) {
- try {
- return configureImpl(data);
- } catch (Throwable t) {
- CMS.debug(t);
- throw t;
- }
- }
-
- public ConfigurationResponse configureImpl(ConfigurationRequest data) {
-
- if (csState.equals("1")) {
- throw new BadRequestException("System is already configured");
- }
-
- String certList;
- try {
- certList = cs.getString("preop.cert.list");
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Unable to get certList from config file");
- }
-
- CMS.debug("SystemConfigService(): configure() called");
- CMS.debug(data.toString());
-
- validateData(data);
- ConfigurationResponse response = new ConfigurationResponse();
-
- if (data.getStandAlone() && data.getStepTwo()) {
- // Stand-alone PKI (Step 2)
- // Special case to import the external CA and its Chain
- certList = "external_signing" + "," + certList;
- }
-
- // specify module and log into token
- CMS.debug("=== Token Panel ===");
- String token = data.getToken();
- if (token == null) {
- token = ConfigurationRequest.TOKEN_DEFAULT;
- }
- tokenPanel(data, token);
-
- //configure security domain
- CMS.debug("=== Security Domain Panel ===");
- String securityDomainType = data.getSecurityDomainType();
- String domainXML = securityDomainPanel(data, securityDomainType);
-
- //subsystem panel
- CMS.debug("=== Subsystem Panel ===");
- cs.putString("preop.subsystem.name", data.getSubsystemName());
-
- // is this a clone of another subsystem?
- if (data.getIsClone().equals("false")) {
- cs.putString("preop.subsystem.select", "new");
- cs.putString("subsystem.select", "New");
- } else {
- cs.putString("preop.subsystem.select", "clone");
- cs.putString("subsystem.select", "Clone");
- getCloningData(data, certList, token, domainXML);
- }
-
- // Hierarchy Panel
- CMS.debug("=== Hierarchy Panel ===");
- hierarchyPanel(data);
-
- // TPS Panels
- if (csType.equals("TPS")) {
-
- // get subsystem certificate nickname
- String subsystemNick = null;
- for (SystemCertData cdata: data.getSystemCerts()) {
- if (cdata.getTag().equals("subsystem")) {
- subsystemNick = cdata.getNickname();
- break;
- }
- }
- if ((subsystemNick == null) || subsystemNick.isEmpty()) {
- throw new BadRequestException("No nickname provided for subsystem certificate");
- }
-
- // CA Info Panel
- caInfoPanel(data, subsystemNick);
-
- // retrieve and import CA cert
-
- // TKS Info Panel
- tksInfoPanel(data, subsystemNick);
-
- //DRM Info Panel
- kraInfoPanel(data, subsystemNick);
-
- //AuthDBPanel
- ConfigurationUtils.updateAuthdbInfo(data.getAuthdbBaseDN(),
- data.getAuthdbHost(), data.getAuthdbPort(),
- data.getAuthdbSecureConn());
-
- }
-
- // Database Panel
- CMS.debug("=== Database Panel ===");
- databasePanel(data);
-
- // SizePanel, NamePanel, CertRequestPanel
- //handle the CA URL
- CMS.debug("=== Size Panel, Name Panel, CertRequest Panel ===");
- try {
- if ((data.getHierarchy() == null) || (data.getHierarchy().equals("join"))) {
- String url = data.getIssuingCA();
- if (url.equals("External CA")) {
- CMS.debug("external CA selected");
- cs.putString("preop.ca.type", "otherca");
- cs.putString("preop.ca.pkcs7", "");
- cs.putInteger("preop.ca.certchain.size", 0);
- if (csType.equals("CA")) {
- cs.putString("preop.cert.signing.type", "remote");
- }
- } else {
- CMS.debug("local CA selected");
- url = url.substring(url.indexOf("https"));
- cs.putString("preop.ca.url", url);
-
- URL urlx = new URL(url);
- String host = urlx.getHost();
- int port = urlx.getPort();
- int admin_port = ConfigurationUtils.getPortFromSecurityDomain(domainXML,
- host, port, "CA", "SecurePort", "SecureAdminPort");
-
- cs.putString("preop.ca.type", "sdca");
- cs.putString("preop.ca.hostname", host);
- cs.putInteger("preop.ca.httpsport", port);
- cs.putInteger("preop.ca.httpsadminport", admin_port);
-
- if (!data.getIsClone().equals("true")) {
- ConfigurationUtils.importCertChain(host, admin_port, "/ca/admin/ca/getCertChain", "ca");
- }
-
- if (csType.equals("CA")) {
- cs.putString("preop.cert.signing.type", "remote");
- cs.putString("preop.cert.signing.profile","caInstallCACert");
- }
- }
- }
- } catch (Exception e) {
- throw new PKIException("Error in obtaining certificate chain from issuing CA: " + e);
- }
-
- boolean generateServerCert = data.getGenerateServerCert().equalsIgnoreCase("false")? false : true;
- boolean hasSigningCert = false;
- Vector<Cert> certs = new Vector<Cert>();
- try {
- StringTokenizer t = new StringTokenizer(certList, ",");
- while (t.hasMoreTokens()) {
- String ct = t.nextToken();
- String certStr;
- boolean enable = cs.getBoolean("preop.cert." + ct + ".enable", true);
- if (!enable) continue;
-
- Collection<SystemCertData> certData = data.getSystemCerts();
- Iterator<SystemCertData> iterator = certData.iterator();
- SystemCertData cdata = null;
- boolean cdata_found = false;
- while (iterator.hasNext()) {
- cdata = iterator.next();
- if (cdata.getTag().equals(ct)) {
- cdata_found = true;
- CMS.debug("Found data for '" + ct + "'");
- break;
- }
- }
- if (!cdata_found) {
- CMS.debug("No data for '" + ct + "' was found!");
- throw new BadRequestException("No data for '" + ct + "' was found!");
- }
-
- if (data.getStandAlone() && data.getStepTwo()) {
- // Stand-alone PKI (Step 2)
- if (ct.equals("external_signing")) {
- String b64 = cdata.getCert();
- if ((b64!= null) && (b64.length()>0) && (!b64.startsWith("..."))) {
- hasSigningCert = true;
- if (data.getIssuingCA().equals("External CA")) {
- String nickname = (cdata.getNickname() != null) ? cdata.getNickname() : "caSigningCert External CA";
- String tokenName = cdata.getToken() != null ? cdata.getToken() : token;
- Cert certObj = new Cert(tokenName, nickname, ct);
- ConfigurationUtils.setExternalCACert(b64, csSubsystem, cs, certObj);
- CMS.debug("Step 2: certStr for '" + ct + "' is " + b64);
- String certChainStr = cdata.getCertChain();
- if (certChainStr != null) {
- ConfigurationUtils.setExternalCACertChain(certChainStr, csSubsystem, cs, certObj);
- CMS.debug("Step 2: certChainStr for '" + ct + "' is " + certChainStr);
- certs.addElement(certObj);
- } else {
- throw new BadRequestException("CertChain not provided");
- }
- }
- continue;
- }
- }
- }
-
- if (!generateServerCert && ct.equals("sslserver")) {
- if (!cdata.getToken().equals("internal")) {
- cs.putString(csSubsystem + ".cert.sslserver.nickname", cdata.getNickname());
- } else {
- cs.putString(csSubsystem + ".cert.sslserver.nickname", data.getToken() +
- ":" + cdata.getNickname());
- }
- cs.putString(csSubsystem + ".sslserver.nickname", cdata.getNickname());
- cs.putString(csSubsystem + ".sslserver.cert", cdata.getCert());
- cs.putString(csSubsystem + ".sslserver.certreq", cdata.getRequest());
- cs.putString(csSubsystem + ".sslserver.tokenname", cdata.getToken());
- continue;
- }
-
- String keytype = (cdata.getKeyType() != null) ? cdata.getKeyType() : "rsa";
-
- String keyalgorithm = cdata.getKeyAlgorithm();
- if (keyalgorithm == null) {
- keyalgorithm = (keytype.equals("ecc")) ? "SHA256withEC" : "SHA256withRSA";
- }
-
- String signingalgorithm = (cdata.getSigningAlgorithm() != null)? cdata.getSigningAlgorithm(): keyalgorithm ;
- String nickname = (cdata.getNickname() != null) ? cdata.getNickname() :
- cs.getString("preop.cert." + ct + ".nickname");
- String dn = (cdata.getSubjectDN() != null)? cdata.getSubjectDN() :
- cs.getString("preop.cert." + ct + ".dn");
-
-
- cs.putString("preop.cert." + ct + ".keytype", keytype);
- cs.putString("preop.cert." + ct + ".keyalgorithm", keyalgorithm);
- cs.putString("preop.cert." + ct + ".signingalgorithm", signingalgorithm);
- cs.putString("preop.cert." + ct + ".nickname", nickname);
- cs.putString("preop.cert." + ct + ".dn", dn);
-
- if (!data.getStepTwo()) {
- if (keytype.equals("ecc")) {
- String curvename = (cdata.getKeyCurveName() != null) ?
- cdata.getKeyCurveName() : cs.getString("keys.ecc.curve.default");
- cs.putString("preop.cert." + ct + ".curvename.name", curvename);
- ConfigurationUtils.createECCKeyPair(token, curvename, cs, ct);
- } else {
- String keysize = cdata.getKeySize() != null ? cdata.getKeySize() : cs
- .getString("keys.rsa.keysize.default");
- cs.putString("preop.cert." + ct + ".keysize.size", keysize);
- ConfigurationUtils.createRSAKeyPair(token, Integer.parseInt(keysize), cs, ct);
- }
- } else {
- CMS.debug("configure(): step two selected. keys will not be generated for '" + ct + "'");
- }
-
- String tokenName = cdata.getToken() != null ? cdata.getToken() : token;
- Cert certObj = new Cert(tokenName, nickname, ct);
- certObj.setDN(dn);
- certObj.setSubsystem(cs.getString("preop.cert." + ct + ".subsystem"));
- certObj.setType(cs.getString("preop.cert." + ct + ".type"));
-
- if (!data.getStepTwo()) {
- ConfigurationUtils.configCert(null, null, null, certObj, null);
- } else {
- String subsystem = cs.getString("preop.cert." + ct + ".subsystem");
- if (data.getStandAlone()) {
- // Stand-alone PKI (Step 2)
- certStr = cdata.getCert();
- certStr = CryptoUtil.stripCertBrackets(certStr.trim());
- certStr = CryptoUtil.normalizeCertStr(certStr);
- cs.putString(subsystem + "." + ct + ".cert", certStr);
- } else {
- certStr = cs.getString(subsystem + "." + ct + ".cert" );
- }
-
- certObj.setCert(certStr);
- CMS.debug("Step 2: certStr for '" + ct + "' is " + certStr);
- }
-
- // Handle Cert Requests for everything EXCEPT Stand-alone PKI (Step 2)
- if (data.getStandAlone()) {
- if (!data.getStepTwo()) {
- // Stand-alone PKI (Step 1)
- ConfigurationUtils.handleCertRequest(cs, ct, certObj);
-
- CMS.debug("Stand-alone " + csType + " Admin CSR");
- String adminSubjectDN = data.getAdminSubjectDN();
- String certreqStr = data.getAdminCertRequest();
- certreqStr = CryptoUtil.normalizeCertAndReq(certreqStr);
- cs.putString("preop.cert.admin.dn", adminSubjectDN);
- cs.putString(csSubsystem + ".admin.certreq", certreqStr);
- cs.putString(csSubsystem + ".admin.cert", "...paste certificate here...");
- }
- } else {
- ConfigurationUtils.handleCertRequest(cs, ct, certObj);
- }
-
- if (data.getIsClone().equals("true")) {
- ConfigurationUtils.updateCloneConfig();
- }
-
- // to determine if we have the signing cert when using an external ca
- // this will only execute on a ca or stand-alone pki
- String b64 = cdata.getCert();
- if ((ct.equals("signing") || ct.equals("external_signing")) && (b64!= null) && (b64.length()>0) && (!b64.startsWith("..."))) {
- hasSigningCert = true;
- if (data.getIssuingCA().equals("External CA")) {
- b64 = CryptoUtil.stripCertBrackets(b64.trim());
- certObj.setCert(CryptoUtil.normalizeCertStr(b64));
-
- if (cdata.getCertChain() != null) {
- certObj.setCertChain(cdata.getCertChain());
- } else {
- throw new BadRequestException("CertChain not provided");
- }
- }
- }
-
- certs.addElement(certObj);
- }
- // make sure to commit changes here for step 1
- cs.commit(false);
-
- } catch (NumberFormatException e) {
- // move these validations to validate()?
- throw new BadRequestException("Non-integer value for key size");
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- throw new BadRequestException("Invalid algorithm " + e);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error in setting certificate names and key sizes: " + e);
- }
-
- // non-Stand-alone PKI submitting CSRs to external ca
- if ((data.getIssuingCA()!= null) && data.getIssuingCA().equals("External CA") && (!hasSigningCert)) {
- CMS.debug("Submit CSRs to external ca . . .");
- response.setSystemCerts(SystemCertDataFactory.create(certs));
- response.setStatus(SUCCESS);
- return response;
- }
-
- Enumeration<Cert> c = certs.elements();
- while (c.hasMoreElements()) {
- Cert cert = c.nextElement();
- int ret;
- try {
- CMS.debug("Processing '" + cert.getCertTag() + "' certificate:");
- ret = ConfigurationUtils.handleCerts(cert);
- ConfigurationUtils.setCertPermissions(cert.getCertTag());
- CMS.debug("Processed '" + cert.getCertTag() + "' certificate.");
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error in configuring system certificates" + e);
- }
- if (ret != 0) {
- throw new PKIException("Error in configuring system certificates");
- }
- }
- response.setSystemCerts(SystemCertDataFactory.create(certs));
-
- // BackupKeyCertPanel/SavePKCS12Panel
- CMS.debug("=== BackupKeyCert Panel/SavePKCS12 Panel ===");
- if (data.getBackupKeys().equals("true")) {
- try {
- ConfigurationUtils.backupKeys(data.getBackupPassword(), data.getBackupFile());
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error in creating pkcs12 to backup keys and certs: " + e);
- }
- }
-
- // AdminPanel
- CMS.debug("=== Admin Panel ===");
- adminPanel(data, response);
-
- // Done Panel
- // Create or update security domain
- CMS.debug("=== Done Panel ===");
- try {
- if (securityDomainType.equals(ConfigurationRequest.NEW_DOMAIN)) {
- ConfigurationUtils.createSecurityDomain();
- } else {
- ConfigurationUtils.updateSecurityDomain();
- }
- cs.putString("service.securityDomainPort", CMS.getAgentPort());
- cs.putString("securitydomain.store", "ldap");
- cs.commit(false);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error while updating security domain: " + e);
- }
-
- // need to push connector information to the CA
- String ca_host="";
- try {
- ca_host = cs.getString("preop.ca.hostname", "");
- } catch (EBaseException e) {
- e.printStackTrace();
- }
-
- // need to push connector information to the CA
- try {
- if (csType.equals("KRA") && (!data.getStandAlone()) && (!ca_host.equals(""))) {
- ConfigurationUtils.updateConnectorInfo(CMS.getAgentHost(), CMS.getAgentPort());
- ConfigurationUtils.setupClientAuthUser();
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Errors in pushing KRA connector information to the CA: " + e);
- }
-
- // import the CA certificate into the OCSP
- // configure the CRL Publishing to OCSP in CA
- try {
- if (csType.equals("OCSP") && (!ca_host.equals(""))) {
- CMS.reinit(IOCSPAuthority.ID);
- ConfigurationUtils.importCACertToOCSP();
- if (!data.getStandAlone()) {
- ConfigurationUtils.updateOCSPConfig();
- ConfigurationUtils.setupClientAuthUser();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Errors in configuring CA publishing to OCSP: " + e);
- }
-
- if (!data.getIsClone().equals("true")) {
- try {
- if (csType.equals("CA") || csType.equals("KRA")) {
- ConfigurationUtils.updateNextRanges();
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Errors in updating next serial number ranges in DB: " + e);
- }
- }
-
- try {
- if (data.getIsClone().equals("true") && csType.equalsIgnoreCase("CA")
- && ConfigurationUtils.isSDHostDomainMaster(cs)) {
- // cloning a domain master CA, the clone is also master of its domain
- cs.putString("securitydomain.host", CMS.getEEHost());
- cs.putString("securitydomain.httpport", CMS.getEENonSSLPort());
- cs.putString("securitydomain.httpsadminport", CMS.getAdminPort());
- cs.putString("securitydomain.httpsagentport", CMS.getAgentPort());
- cs.putString("securitydomain.httpseeport", CMS.getEESSLPort());
- cs.putString("securitydomain.select", "new");
-
- }
- } catch (Exception e1) {
- e1.printStackTrace();
- throw new PKIException("Errors in determining if security domain host is a master CA");
- }
-
- try {
- ConfigurationUtils.setupDBUser();
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Errors in creating or updating dbuser: " + e);
- }
-
- if (csType.equals("TPS")) {
- try {
- ConfigurationUtils.addProfilesToTPSUser(data.getAdminUID());
-
- URI secdomainURI = new URI(data.getSecurityDomainUri());
-
- // register TPS with CA
- URI caURI = new URI(data.getCaUri());
- ConfigurationUtils.registerUser(secdomainURI, caURI, "ca");
-
- // register TPS with TKS
- URI tksURI = new URI(data.getTksUri());
- ConfigurationUtils.registerUser(secdomainURI, tksURI, "tks");
-
- if (data.getEnableServerSideKeyGen().equalsIgnoreCase("true")) {
- URI kraURI = new URI(data.getKraUri());
- ConfigurationUtils.registerUser(secdomainURI, kraURI, "kra");
- String transportCert = ConfigurationUtils.getTransportCert(secdomainURI, kraURI);
- ConfigurationUtils.exportTransportCert(secdomainURI, tksURI, transportCert);
- }
-
- // generate shared secret from the tks
- ConfigurationUtils.getSharedSecret(
- tksURI.getHost(),
- tksURI.getPort(),
- Boolean.getBoolean(data.getImportSharedSecret()));
-
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid URI for CA, TKS or KRA");
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Errors in registering TPS to CA, TKS or KRA: " + e);
- }
- }
-
- cs.putInteger("cs.state", 1);
-
- // update serial numbers for clones
-
- // save some variables, remove remaining preops
- try {
- ConfigurationUtils.removePreopConfigEntries();
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Errors when removing preop config entries: " + e);
- }
-
- // Create an empty file that designates the fact that although
- // this server instance has been configured, it has NOT yet
- // been restarted!
- String restart_server = instanceRoot + "/conf/" + RESTART_SERVER_AFTER_CONFIGURATION;
- Utils.exec("touch " + restart_server);
- Utils.exec("chmod 00660 " + restart_server);
-
- response.setStatus(SUCCESS);
- return response;
- }
-
- private void caInfoPanel(ConfigurationRequest data, String subsystemNick) {
- URI caUri = null;
- try {
- caUri = new URI(data.getCaUri());
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid caURI " + caUri);
- }
- ConfigurationUtils.updateCAConnInfo(caUri, subsystemNick);
- }
-
- private void tksInfoPanel(ConfigurationRequest data, String subsystemNick) {
- URI tksUri = null;
- try {
- tksUri = new URI(data.getTksUri());
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid tksURI " + tksUri);
- }
-
- ConfigurationUtils.updateTKSConnInfo(tksUri, subsystemNick);
- }
-
- private void kraInfoPanel(ConfigurationRequest data, String subsystemNick) {
- URI kraUri = null;
- try {
- kraUri = new URI(data.getCaUri());
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid kraURI " + kraUri);
- }
- boolean keyGen = data.getEnableServerSideKeyGen().equalsIgnoreCase("true");
- ConfigurationUtils.updateKRAConnInfo(keyGen, kraUri, subsystemNick);
- }
-
- private void adminPanel(ConfigurationRequest data, ConfigurationResponse response) {
- if (!data.getIsClone().equals("true")) {
- try {
- X509CertImpl admincerts[] = new X509CertImpl[1];
- ConfigurationUtils.createAdmin(data.getAdminUID(), data.getAdminEmail(),
- data.getAdminName(), data.getAdminPassword());
- if (data.getImportAdminCert().equalsIgnoreCase("true")) {
- String b64 = CryptoUtil.stripCertBrackets(data.getAdminCert().trim());
- if (data.getStandAlone() && data.getStepTwo()) {
- // Stand-alone PKI (Step 2)
- CMS.debug("adminPanel: Stand-alone " + csType + " Admin Cert");
- cs.putString(csSubsystem + ".admin.cert", b64);
- cs.commit(false);
- }
- // Convert Admin Cert to X509CertImpl
- byte[] b = CryptoUtil.base64Decode(b64);
- admincerts[0] = new X509CertImpl(b);
- } else {
- if (csType.equals("CA")) {
- ConfigurationUtils.createAdminCertificate(data.getAdminCertRequest(),
- data.getAdminCertRequestType(), data.getAdminSubjectDN());
-
- String serialno = cs.getString("preop.admincert.serialno.0");
- ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem(ICertificateAuthority.ID);
- ICertificateRepository repo = ca.getCertificateRepository();
- admincerts[0] = repo.getX509Certificate(new BigInteger(serialno, 16));
- } else {
- String type = cs.getString("preop.ca.type", "");
- String ca_hostname = "";
- int ca_port = -1;
- if (type.equals("sdca")) {
- ca_hostname = cs.getString("preop.ca.hostname");
- ca_port = cs.getInteger("preop.ca.httpsport");
- } else {
- ca_hostname = cs.getString("securitydomain.host", "");
- ca_port = cs.getInteger("securitydomain.httpseeport");
- }
- String b64 = ConfigurationUtils.submitAdminCertRequest(ca_hostname, ca_port,
- data.getAdminProfileID(), data.getAdminCertRequestType(),
- data.getAdminCertRequest(), data.getAdminSubjectDN());
- b64 = CryptoUtil.stripCertBrackets(b64.trim());
- byte[] b = CryptoUtil.base64Decode(b64);
- admincerts[0] = new X509CertImpl(b);
- }
- }
- CMS.reinit(IUGSubsystem.ID);
-
- IUGSubsystem ug = (IUGSubsystem) CMS.getSubsystem(IUGSubsystem.ID);
- IUser user = ug.getUser(data.getAdminUID());
- user.setX509Certificates(admincerts);
- ug.addUserCert(user);
- response.setAdminCert(admincerts[0]);
-
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error in creating admin user: " + e);
- }
- }
- }
-
- private void databasePanel(ConfigurationRequest data) {
- cs.putString("internaldb.ldapconn.host", data.getDsHost());
- cs.putString("internaldb.ldapconn.port", data.getDsPort());
- cs.putString("internaldb.database", data.getDatabase());
- cs.putString("internaldb.basedn", data.getBaseDN());
- cs.putString("internaldb.ldapauth.bindDN", data.getBindDN());
- cs.putString("internaldb.ldapconn.secureConn", (data.getSecureConn().equals("on") ? "true" : "false"));
- cs.putString("preop.database.removeData", data.getRemoveData());
-
- if (csType.equals("TPS")) {
- cs.putString("tokendb.activityBaseDN", "ou=Activities," + data.getBaseDN());
- cs.putString("tokendb.baseDN", "ou=Tokens," + data.getBaseDN());
- cs.putString("tokendb.certBaseDN", "ou=Certificates," + data.getBaseDN());
- cs.putString("tokendb.userBaseDN", data.getBaseDN());
- cs.putString("tokendb.hostport", data.getDsHost() + ":" + data.getDsPort());
- }
-
- try {
- cs.commit(false);
- } catch (EBaseException e2) {
- e2.printStackTrace();
- throw new PKIException("Unable to commit config parameters to file");
- }
-
- if (data.getIsClone().equals("true")) {
- String masterhost = "";
- String masterport = "";
- String masterbasedn = "";
- String realhostname = "";
- try {
- masterhost = cs.getString("preop.internaldb.master.ldapconn.host", "");
- masterport = cs.getString("preop.internaldb.master.ldapconn.port", "");
- masterbasedn = cs.getString("preop.internaldb.master.basedn", "");
- realhostname = cs.getString("machineName", "");
- } catch (Exception e) {
- }
-
- if (masterhost.equals(realhostname) && masterport.equals(data.getDsPort())) {
- throw new BadRequestException("Master and clone must not share the same internal database");
- }
-
- if (!masterbasedn.equals(data.getBaseDN())) {
- throw new BadRequestException("Master and clone should have the same base DN");
- }
-
- String masterReplicationPort = data.getMasterReplicationPort();
- if ((masterReplicationPort != null) && (!masterReplicationPort.equals(""))) {
- cs.putString("internaldb.ldapconn.masterReplicationPort", masterReplicationPort);
- } else {
- cs.putString("internaldb.ldapconn.masterReplicationPort", masterport);
- }
-
- String cloneReplicationPort = data.getCloneReplicationPort();
- if ((cloneReplicationPort == null) || (cloneReplicationPort.length() == 0)) {
- cloneReplicationPort = data.getDsPort();
- }
- cs.putString("internaldb.ldapconn.cloneReplicationPort", cloneReplicationPort);
-
- String replicationSecurity = data.getReplicationSecurity();
- if ((cloneReplicationPort == data.getDsPort()) && (data.getSecureConn().equals("on"))) {
- replicationSecurity = "SSL";
- } else if (replicationSecurity == null) {
- replicationSecurity = "None";
- }
- cs.putString("internaldb.ldapconn.replicationSecurity", replicationSecurity);
-
- cs.putString("preop.internaldb.replicateSchema", data.getReplicateSchema());
- }
-
- try {
- /* BZ 430745 create password for replication manager */
- String replicationpwd = Integer.toString(new Random().nextInt());
-
- IConfigStore psStore = null;
- String passwordFile = null;
- passwordFile = cs.getString("passwordFile");
- psStore = CMS.createFileConfigStore(passwordFile);
- psStore.putString("internaldb", data.getBindpwd());
- psStore.putString("replicationdb", replicationpwd);
- psStore.commit(false);
-
- if (!data.getStepTwo()) {
- ConfigurationUtils.populateDB();
-
- cs.putString("preop.internaldb.replicationpwd", replicationpwd);
- cs.putString("preop.database.removeData", "false");
- cs.commit(false);
-
- if (data.getIsClone().equals("true")) {
- CMS.debug("Start setting up replication.");
- ConfigurationUtils.setupReplication();
- }
-
- ConfigurationUtils.reInitSubsystem(csType);
- ConfigurationUtils.populateDBManager();
- ConfigurationUtils.populateVLVIndexes();
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error in populating database: " + e, e);
- }
- }
-
- private void hierarchyPanel(ConfigurationRequest data) {
- if (csType.equals("CA") && data.getIsClone().equals("false")) {
- if (data.getHierarchy().equals("root")) {
- cs.putString("preop.hierarchy.select", "root");
- cs.putString("hierarchy.select", "Root");
- cs.putString("preop.ca.type", "sdca");
- } else if (data.getHierarchy().equals("join")) {
- cs.putString("preop.cert.signing.type", "remote");
- cs.putString("preop.hierarchy.select", "join");
- cs.putString("hierarchy.select", "Subordinate");
- } else {
- throw new BadRequestException("Invalid hierarchy provided");
- }
- }
- }
-
- private void getCloningData(ConfigurationRequest data, String certList, String token, String domainXML) {
- StringTokenizer t = new StringTokenizer(certList, ",");
- while (t.hasMoreTokens()) {
- String tag = t.nextToken();
- if (tag.equals("sslserver")) {
- cs.putBoolean("preop.cert." + tag + ".enable", true);
- } else {
- cs.putBoolean("preop.cert." + tag + ".enable", false);
- }
- }
-
- String cloneUri = data.getCloneUri();
- URL url = null;
- try {
- url = new URL(cloneUri);
- } catch (MalformedURLException e) {
- // should not reach here as this check is done in validate()
- }
- String masterHost = url.getHost();
- int masterPort = url.getPort();
-
- // check and store cloneURI information
- boolean validCloneUri;
- try {
- validCloneUri = ConfigurationUtils.isValidCloneURI(domainXML, masterHost, masterPort);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Error in determining whether clone URI is valid");
- }
-
- if (!validCloneUri) {
- throw new BadRequestException(
- "Invalid clone URI provided. Does not match the available subsystems in the security domain");
- }
-
- if (csType.equals("CA")) {
- try {
- int masterAdminPort = ConfigurationUtils.getPortFromSecurityDomain(domainXML,
- masterHost, masterPort, "CA", "SecurePort", "SecureAdminPort");
- ConfigurationUtils.importCertChain(masterHost, masterAdminPort, "/ca/admin/ca/getCertChain",
- "clone");
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Failed to import certificate chain from master" + e);
- }
- }
-
- try {
- ConfigurationUtils.getConfigEntriesFromMaster();
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Failed to obtain configuration entries from the master for cloning " + e);
- }
-
- // restore certs from P12 file
- if (token.equals(ConfigurationRequest.TOKEN_DEFAULT)) {
- String p12File = data.getP12File();
- String p12Pass = data.getP12Password();
- try {
- ConfigurationUtils.restoreCertsFromP12(p12File, p12Pass);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Failed to restore certificates from p12 file" + e);
- }
- }
-
- boolean cloneReady = ConfigurationUtils.isCertdbCloned();
- if (!cloneReady) {
- CMS.debug("clone does not have all the certificates.");
- throw new PKIException("Clone does not have all the required certificates");
- }
- }
-
- private String securityDomainPanel(ConfigurationRequest data, String securityDomainType) {
- String domainXML = null;
- String securityDomainName = data.getSecurityDomainName();
- String securityDomainURL = data.getSecurityDomainUri();
-
- if (securityDomainType.equals(ConfigurationRequest.NEW_DOMAIN)) {
- CMS.debug("Creating new security domain");
- cs.putString("preop.securitydomain.select", "new");
- cs.putString("securitydomain.select", "new");
- cs.putString("preop.securitydomain.name", securityDomainName);
- cs.putString("securitydomain.name", securityDomainName);
- cs.putString("securitydomain.host", CMS.getEENonSSLHost());
- cs.putString("securitydomain.httpport", CMS.getEENonSSLPort());
- cs.putString("securitydomain.httpsagentport", CMS.getAgentPort());
- cs.putString("securitydomain.httpseeport", CMS.getEESSLPort());
- cs.putString("securitydomain.httpsadminport", CMS.getAdminPort());
- // Stand-alone PKI (Step 1)
- if (data.getStandAlone()) {
- cs.putString("preop.cert.subsystem.type", "remote");
- } else {
- cs.putString("preop.cert.subsystem.type", "local");
- }
- cs.putString("preop.cert.subsystem.profile", "subsystemCert.profile");
-
- } else {
- CMS.debug("Joining existing security domain");
- cs.putString("preop.securitydomain.select", "existing");
- cs.putString("securitydomain.select", "existing");
- cs.putString("preop.cert.subsystem.type", "remote");
- cs.putString("preop.cert.subsystem.profile", "caInternalAuthSubsystemCert");
-
- CMS.debug("Getting certificate chain");
- // contact and log onto security domain
- URL secdomainURL;
- String host;
- int port;
- try {
- secdomainURL = new URL(securityDomainURL);
- host = secdomainURL.getHost();
- port = secdomainURL.getPort();
- cs.putString("securitydomain.host", host);
- cs.putInteger("securitydomain.httpsadminport",port);
- ConfigurationUtils.importCertChain(host, port, "/ca/admin/ca/getCertChain", "securitydomain");
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Failed to import certificate chain from security domain master: " + e);
- }
-
- CMS.debug("Getting install token");
- // log onto security domain and get token
- String user = data.getSecurityDomainUser();
- String pass = data.getSecurityDomainPassword();
- String installToken;
- try {
- installToken = ConfigurationUtils.getInstallToken(host, port, user, pass);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Failed to obtain installation token from security domain: " + e);
- }
-
- if (installToken == null) {
- CMS.debug("Install token is null");
- throw new PKIException("Failed to obtain installation token from security domain");
- }
- CMS.setConfigSDSessionId(installToken);
-
- CMS.debug("Getting domain XML");
- try {
- domainXML = ConfigurationUtils.getDomainXML(host, port, true);
- ConfigurationUtils.getSecurityDomainPorts(domainXML, host, port);
- } catch (Exception e) {
- e.printStackTrace();
- throw new PKIException("Failed to obtain security domain decriptor from security domain master: " + e);
- }
- }
- return domainXML;
- }
-
- private void tokenPanel(ConfigurationRequest data, String token) {
- cs.putString("preop.module.token", token);
-
- if (! token.equals(ConfigurationRequest.TOKEN_DEFAULT)) {
- try {
- CryptoManager cryptoManager = CryptoManager.getInstance();
- CryptoToken ctoken = cryptoManager.getTokenByName(token);
- String tokenpwd = data.getTokenPassword();
- ConfigurationUtils.loginToken(ctoken, tokenpwd);
- } catch (NotInitializedException e) {
- throw new PKIException("Token is not initialized");
- } catch (NoSuchTokenException e) {
- throw new BadRequestException("Invalid Token provided. No such token.");
- } catch (TokenException e) {
- e.printStackTrace();
- throw new PKIException("Token Exception" + e);
- } catch (IncorrectPasswordException e) {
- throw new BadRequestException("Incorrect Password provided for token.");
- }
- }
- }
-
- private void validateData(ConfigurationRequest data) {
- // get required info from CS.cfg
- String preopPin;
- try {
- preopPin = cs.getString("preop.pin");
- } catch (Exception e) {
- CMS.debug("validateData: Failed to get required config form CS.cfg");
- e.printStackTrace();
- throw new PKIException("Unable to retrieve required configuration from configuration files");
- }
-
- // get the preop pin and validate it
- String pin = data.getPin();
- if (pin == null) {
- throw new BadRequestException("No preop pin provided");
- }
- if (!preopPin.equals(pin)) {
- throw new BadRequestException("Incorrect pin provided");
- }
-
- // validate legal stand-alone PKI subsystems
- if (data.getStandAlone()) {
- // ADD checks for valid types of Stand-alone PKI subsystems here
- // AND to the 'checkStandalonePKI()' Python method of
- // the 'ConfigurationFile' Python class in the Python file called
- // 'pkihelper.py'
- if (!csType.equals("KRA")) {
- throw new BadRequestException("Stand-alone PKI " + csType + " subsystems are currently NOT supported!");
- }
- if ((data.getIsClone() != null) && (data.getIsClone().equals("true"))) {
- throw new BadRequestException("A stand-alone PKI subsystem cannot be a clone");
- }
- }
-
- // validate security domain settings
- String domainType = data.getSecurityDomainType();
- if (domainType == null) {
- throw new BadRequestException("Security Domain Type not provided");
- }
-
- if (domainType.equals(ConfigurationRequest.NEW_DOMAIN)) {
- if (!(data.getStandAlone() || csType.equals("CA"))) {
- throw new BadRequestException("New Domain is only valid for stand-alone PKI or CA subsytems");
- }
- if (data.getSecurityDomainName() == null) {
- throw new BadRequestException("Security Domain Name is not provided");
- }
- } else if (domainType.equals(ConfigurationRequest.EXISTING_DOMAIN)) {
- if (data.getStandAlone()) {
- throw new BadRequestException("Existing security domains are not valid for stand-alone PKI subsytems");
- }
-
- String domainURI = data.getSecurityDomainUri();
- if (domainURI == null) {
- throw new BadRequestException("Existing security domain requested, but no security domain URI provided");
- }
-
- try {
- @SuppressWarnings("unused")
- URL admin_u = new URL(domainURI); // check for invalid URL
- } catch (MalformedURLException e) {
- throw new BadRequestException("Invalid security domain URI");
- }
- if ((data.getSecurityDomainUser() == null) || (data.getSecurityDomainPassword() == null)) {
- throw new BadRequestException("Security domain user or password not provided");
- }
-
- } else {
- throw new BadRequestException("Invalid security domain URI provided");
- }
-
- if ((data.getSubsystemName() == null) || (data.getSubsystemName().length() ==0)) {
- throw new BadRequestException("Invalid or no subsystem name provided");
- }
-
- if ((data.getIsClone() != null) && (data.getIsClone().equals("true"))) {
- String cloneUri = data.getCloneUri();
- if (cloneUri == null) {
- throw new BadRequestException("Clone selected, but no clone URI provided");
- }
- try {
- @SuppressWarnings("unused")
- URL url = new URL(cloneUri); // check for invalid URL
- // confirm protocol is https
- } catch (MalformedURLException e) {
- throw new BadRequestException("Invalid clone URI");
- }
-
- if (data.getToken().equals(ConfigurationRequest.TOKEN_DEFAULT)) {
- if (data.getP12File() == null) {
- throw new BadRequestException("P12 filename not provided");
- }
-
- if (data.getP12Password() == null) {
- throw new BadRequestException("P12 password not provided");
- }
- }
- } else {
- data.setIsClone("false");
- }
-
- String dsHost = data.getDsHost();
- if (dsHost == null || dsHost.length() == 0) {
- throw new BadRequestException("Internal database host not provided");
- }
-
- try {
- Integer.parseInt(data.getDsPort()); // check for errors
- } catch (NumberFormatException e) {
- throw new BadRequestException("Internal database port is invalid");
- }
-
- String basedn = data.getBaseDN();
- if (basedn == null || basedn.length() == 0) {
- throw new BadRequestException("Internal database basedn not provided");
- }
-
- String binddn = data.getBindDN();
- if (binddn == null || binddn.length() == 0) {
- throw new BadRequestException("Internal database basedn not provided");
- }
-
- String database = data.getDatabase();
- if (database == null || database.length() == 0) {
- throw new BadRequestException("Internal database database name not provided");
- }
-
- String bindpwd = data.getBindpwd();
- if (bindpwd == null || bindpwd.length() == 0) {
- throw new BadRequestException("Internal database database name not provided");
- }
-
- String masterReplicationPort = data.getMasterReplicationPort();
- if (masterReplicationPort != null && masterReplicationPort.length() > 0) {
- try {
- Integer.parseInt(masterReplicationPort); // check for errors
- } catch (NumberFormatException e) {
- throw new BadRequestException("Master replication port is invalid");
- }
- }
-
- String cloneReplicationPort = data.getCloneReplicationPort();
- if (cloneReplicationPort != null && cloneReplicationPort.length() > 0) {
- try {
- Integer.parseInt(cloneReplicationPort); // check for errors
- } catch (Exception e) {
- throw new BadRequestException("Clone replication port is invalid");
- }
- }
-
- if ((data.getReplicateSchema() != null) && (data.getReplicateSchema().equalsIgnoreCase("false"))) {
- data.setReplicateSchema("false");
- } else {
- data.setReplicateSchema("true");
- }
-
- if ((data.getBackupKeys() != null) && data.getBackupKeys().equals("true")) {
- if ((data.getBackupFile() == null) || (data.getBackupFile().length()<=0)) {
- //TODO: also check for valid path, perhaps by touching file there
- throw new BadRequestException("Invalid key backup file name");
- }
-
- if ((data.getBackupPassword() == null) || (data.getBackupPassword().length()<8)) {
- throw new BadRequestException("key backup password must be at least 8 characters");
- }
- } else {
- data.setBackupKeys("false");
- }
-
- if (csType.equals("CA") && (data.getHierarchy() == null)) {
- throw new BadRequestException("Hierarchy is required for CA, not provided");
- }
-
- if (data.getIsClone().equals("false")) {
- if ((data.getAdminUID() == null) || (data.getAdminUID().length() == 0)) {
- throw new BadRequestException("Admin UID not provided");
- }
- if ((data.getAdminPassword() == null) || (data.getAdminPassword().length() == 0)) {
- throw new BadRequestException("Admin Password not provided");
- }
- if ((data.getAdminEmail() == null) || (data.getAdminEmail().length() == 0)) {
- throw new BadRequestException("Admin UID not provided");
- }
- if ((data.getAdminName() == null) || (data.getAdminName().length() == 0)) {
- throw new BadRequestException("Admin name not provided");
- }
-
- if (data.getImportAdminCert() == null) {
- data.setImportAdminCert("false");
- }
-
- if (data.getImportAdminCert().equalsIgnoreCase("true")) {
- if (data.getAdminCert() == null) {
- throw new BadRequestException("Admin Cert not provided");
- }
- } else {
- if ((data.getAdminCertRequest() == null) || (data.getAdminCertRequest().length() == 0)) {
- throw new BadRequestException("Admin cert request not provided");
- }
- if ((data.getAdminCertRequestType() == null) || (data.getAdminCertRequestType().length() == 0)) {
- throw new BadRequestException("Admin cert request type not provided");
- }
- if ((data.getAdminSubjectDN() == null) || (data.getAdminSubjectDN().length() == 0)) {
- throw new BadRequestException("Admin subjectDN not provided");
- }
- }
- }
-
- if (data.getGenerateServerCert() == null) {
- data.setGenerateServerCert("true");
- }
-
- if (csType.equals("TPS")) {
- if ((data.getCaUri() == null) || data.getCaUri().isEmpty()) {
- throw new BadRequestException("CA URI not provided");
- }
- try {
- @SuppressWarnings("unused")
- URI ca_uri = new URI(data.getCaUri());
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid CA URI");
- }
-
- if ((data.getTksUri() == null) || data.getTksUri().isEmpty()) {
- throw new BadRequestException("TKS URI not provided");
- }
- try {
- @SuppressWarnings("unused")
- URI tks_uri = new URI(data.getTksUri());
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid TKS URI");
- }
-
- if (data.getEnableServerSideKeyGen().equalsIgnoreCase("true")) {
- if ((data.getKraUri() == null) || data.getKraUri().isEmpty()) {
- throw new BadRequestException("KRA URI required if server-side key generation requested");
- }
- try {
- @SuppressWarnings("unused")
- URI kra_uri = new URI(data.getKraUri());
- } catch (URISyntaxException e) {
- throw new BadRequestException("Invalid KRA URI");
- }
- }
-
- if ((data.getAuthdbBaseDN()==null) || data.getAuthdbBaseDN().isEmpty()) {
- throw new BadRequestException("Authentication Database baseDN not provided");
- }
- if ((data.getAuthdbHost()==null) || data.getAuthdbHost().isEmpty()) {
- throw new BadRequestException("Authentication Database hostname not provided");
- }
- if ((data.getAuthdbPort()==null) || data.getAuthdbPort().isEmpty()) {
- throw new BadRequestException("Authentication Database port not provided");
- }
- if ((data.getAuthdbSecureConn()==null) || data.getAuthdbSecureConn().isEmpty()) {
- throw new BadRequestException("Authentication Database secure conn not provided");
- }
-
- try {
- Integer.parseInt(data.getAuthdbPort()); // check for errors
- } catch (NumberFormatException e) {
- throw new BadRequestException("Authdb port is invalid");
- }
-
- // TODO check connection with authdb
-
- if (data.getImportSharedSecret().equalsIgnoreCase("true")) {
- data.setImportSharedSecret("true");
- } else {
- data.setImportSharedSecret("false");
- }
- }
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/key/KeyRequestDAO.java b/base/server/cms/src/com/netscape/cms/servlet/key/KeyRequestDAO.java
index 93e0018c4..f72c4c78b 100644
--- a/base/server/cms/src/com/netscape/cms/servlet/key/KeyRequestDAO.java
+++ b/base/server/cms/src/com/netscape/cms/servlet/key/KeyRequestDAO.java
@@ -19,8 +19,10 @@ package com.netscape.cms.servlet.key;
import java.util.Collection;
import java.util.Enumeration;
+import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
+import java.util.Map;
import javax.ws.rs.Path;
import javax.ws.rs.core.UriBuilder;
@@ -54,7 +56,6 @@ import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cms.servlet.request.CMSRequestDAO;
-import com.netscape.cms.servlet.request.KeyRequestService;
/**
* @author alee
@@ -62,6 +63,18 @@ import com.netscape.cms.servlet.request.KeyRequestService;
*/
public class KeyRequestDAO extends CMSRequestDAO {
+ public static final Map<String, KeyGenAlgorithm> KEYGEN_ALGORITHMS;
+
+ static {
+ KEYGEN_ALGORITHMS = new HashMap<String, KeyGenAlgorithm>();
+ KEYGEN_ALGORITHMS.put(KeyRequestResource.DES_ALGORITHM, KeyGenAlgorithm.DES);
+ KEYGEN_ALGORITHMS.put(KeyRequestResource.DESEDE_ALGORITHM, KeyGenAlgorithm.DESede);
+ KEYGEN_ALGORITHMS.put(KeyRequestResource.DES3_ALGORITHM, KeyGenAlgorithm.DES3);
+ KEYGEN_ALGORITHMS.put(KeyRequestResource.RC2_ALGORITHM, KeyGenAlgorithm.RC2);
+ KEYGEN_ALGORITHMS.put(KeyRequestResource.RC4_ALGORITHM, KeyGenAlgorithm.RC4);
+ KEYGEN_ALGORITHMS.put(KeyRequestResource.AES_ALGORITHM, KeyGenAlgorithm.AES);
+ }
+
private static String REQUEST_ARCHIVE_OPTIONS = IEnrollProfile.REQUEST_ARCHIVE_OPTIONS;
private static String REQUEST_SECURITY_DATA = IEnrollProfile.REQUEST_SECURITY_DATA;
private static String REQUEST_SESSION_KEY = IEnrollProfile.REQUEST_SESSION_KEY;
@@ -266,7 +279,7 @@ public class KeyRequestDAO extends CMSRequestDAO {
keySize = new Integer(128);
}
- KeyGenAlgorithm alg = KeyRequestService.KEYGEN_ALGORITHMS.get(algName);
+ KeyGenAlgorithm alg = KEYGEN_ALGORITHMS.get(algName);
if (alg == null) {
throw new BadRequestException("Invalid Algorithm");
}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/key/KeyService.java b/base/server/cms/src/com/netscape/cms/servlet/key/KeyService.java
deleted file mode 100644
index 520ae4c5a..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/key/KeyService.java
+++ /dev/null
@@ -1,559 +0,0 @@
-// --- 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) 2011 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.key;
-
-
-import java.math.BigInteger;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.Path;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.jboss.resteasy.plugins.providers.atom.Link;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.HTTPGoneException;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.ResourceNotFoundException;
-import com.netscape.certsrv.base.UnauthorizedException;
-import com.netscape.certsrv.dbs.EDBRecordNotFoundException;
-import com.netscape.certsrv.dbs.Modification;
-import com.netscape.certsrv.dbs.ModificationSet;
-import com.netscape.certsrv.dbs.keydb.IKeyRecord;
-import com.netscape.certsrv.dbs.keydb.IKeyRepository;
-import com.netscape.certsrv.dbs.keydb.KeyId;
-import com.netscape.certsrv.key.KeyData;
-import com.netscape.certsrv.key.KeyInfo;
-import com.netscape.certsrv.key.KeyInfoCollection;
-import com.netscape.certsrv.key.KeyNotFoundException;
-import com.netscape.certsrv.key.KeyRecoveryRequest;
-import com.netscape.certsrv.key.KeyRequestInfo;
-import com.netscape.certsrv.key.KeyResource;
-import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
-import com.netscape.certsrv.kra.IKeyService;
-import com.netscape.certsrv.logging.ILogger;
-import com.netscape.certsrv.request.IRequest;
-import com.netscape.certsrv.request.IRequestQueue;
-import com.netscape.certsrv.request.RequestId;
-import com.netscape.certsrv.request.RequestStatus;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cmsutil.ldap.LDAPUtil;
-import com.netscape.cmsutil.util.Utils;
-
-/**
- * @author alee
- *
- */
-public class KeyService extends PKIService implements KeyResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- private final static String LOGGING_SIGNED_AUDIT_SECURITY_DATA_RETRIEVE_KEY =
- "LOGGING_SIGNED_AUDIT_SECURITY_DATA_RETRIEVE_KEY_5";
-
- public static final int DEFAULT_MAXRESULTS = 100;
- public static final int DEFAULT_MAXTIME = 10;
- public final static int DEFAULT_SIZE = 20;
-
- private IKeyRepository repo;
- private IKeyRecoveryAuthority kra;
- private IRequestQueue queue;
- private IKeyService service;
-
- public KeyService() {
- kra = ( IKeyRecoveryAuthority ) CMS.getSubsystem( "kra" );
- repo = kra.getKeyRepository();
- queue = kra.getRequestQueue();
- service = (IKeyService) kra;
- }
-
- /**
- * Used to retrieve a key
- * @param data
- * @return
- */
- @Override
- public Response retrieveKey(KeyRecoveryRequest data) {
- if (data == null) {
- CMS.debug("retrieveKey: data is null");
- throw new BadRequestException("Cannot retrieve key. Invalid request");
- }
- // auth and authz
- RequestId requestID = data.getRequestId();
- IRequest request;
- try {
- request = queue.findRequest(requestID);
- } catch (EBaseException e) {
- e.printStackTrace();
- auditRetrieveKey(ILogger.FAILURE, requestID, null, e.getMessage());
- throw new PKIException(e.getMessage());
- }
- String type = request.getRequestType();
- KeyId keyId = null;
- KeyData keyData;
- try {
- if (IRequest.KEYRECOVERY_REQUEST.equals(type)) {
- keyData = recoverKey(data);
- } else {
- keyId = validateRequest(data);
- keyData = getKey(keyId, data);
- }
- } catch (EBaseException e) {
- e.printStackTrace();
- auditRetrieveKey(ILogger.FAILURE, requestID, keyId, e.getMessage());
- throw new PKIException(e.getMessage());
- }
- if (keyData == null) {
- // no key record
- auditRetrieveKey(ILogger.FAILURE, requestID, keyId, "No key record");
- throw new HTTPGoneException("No key record.");
- }
- auditRetrieveKey(ILogger.SUCCESS, requestID, keyId, "None");
-
- return createOKResponse(keyData);
- }
-
- // retrieval - used to test integration with a browser
- @Override
- public Response retrieveKey(MultivaluedMap<String, String> form) {
- KeyRecoveryRequest data = new KeyRecoveryRequest(form);
- return retrieveKey(data);
- }
-
- public KeyData getKey(KeyId keyId, KeyRecoveryRequest data) throws EBaseException {
- KeyData keyData;
-
- RequestId rId = data.getRequestId();
-
- String transWrappedSessionKey;
- String sessionWrappedPassphrase;
-
- IRequest request = queue.findRequest(rId);
-
- if (request == null) {
- return null;
- }
-
- // get wrapped key
- IKeyRecord rec = repo.readKeyRecord(keyId.toBigInteger());
- if (rec == null) {
- return null;
- }
-
- Hashtable<String, Object> requestParams = kra.getVolatileRequest(
- request.getRequestId());
-
- if(requestParams == null) {
- auditRetrieveKey(ILogger.FAILURE, rId, keyId, "cannot obtain volatile requestParams");
- throw new EBaseException("Can't obtain Volatile requestParams in getKey!");
- }
-
- String sessWrappedKeyData = (String) requestParams.get(IRequest.SECURITY_DATA_SESS_WRAPPED_DATA);
- String passWrappedKeyData = (String) requestParams.get(IRequest.SECURITY_DATA_PASS_WRAPPED_DATA);
- String nonceData = (String) requestParams.get(IRequest.SECURITY_DATA_IV_STRING_OUT);
-
- if (sessWrappedKeyData != null || passWrappedKeyData != null) {
- //The recovery process has already placed a valid recovery
- //package, either session key wrapped or pass wrapped, into the request.
- //Request already has been processed.
- keyData = new KeyData();
-
- } else {
- // The request has not yet been processed, let's see if the RecoveryRequestData contains
- // the info now needed to process the recovery request.
-
- transWrappedSessionKey = data.getTransWrappedSessionKey();
- sessionWrappedPassphrase = data.getSessionWrappedPassphrase();
- nonceData = data.getNonceData();
-
- if (transWrappedSessionKey == null) {
- //There must be at least a transWrappedSessionKey input provided.
- //The command AND the request have provided insufficient data, end of the line.
- auditRetrieveKey(ILogger.FAILURE, rId, keyId, "insufficient input data");
- throw new EBaseException("Can't retrieve key, insufficient input data!");
- }
-
- if (sessionWrappedPassphrase != null) {
- requestParams.put(IRequest.SECURITY_DATA_SESS_PASS_PHRASE, sessionWrappedPassphrase);
- }
-
- if (transWrappedSessionKey != null) {
- requestParams.put(IRequest.SECURITY_DATA_TRANS_SESS_KEY, transWrappedSessionKey);
- }
-
- if (nonceData != null) {
- requestParams.put(IRequest.SECURITY_DATA_IV_STRING_IN, nonceData);
- }
-
- try {
- // Has to be in this state or it won't go anywhere.
- request.setRequestStatus(RequestStatus.BEGIN);
- queue.processRequest(request);
- } catch (EBaseException e) {
- kra.destroyVolatileRequest(request.getRequestId());
- throw new EBaseException(e.toString());
- }
-
- nonceData = null;
- keyData = new KeyData();
-
- sessWrappedKeyData = (String) requestParams.get(IRequest.SECURITY_DATA_SESS_WRAPPED_DATA);
- passWrappedKeyData = (String) requestParams.get(IRequest.SECURITY_DATA_PASS_WRAPPED_DATA);
- nonceData = (String) requestParams.get(IRequest.SECURITY_DATA_IV_STRING_OUT);
-
- }
-
- if (sessWrappedKeyData != null) {
- keyData.setWrappedPrivateData(sessWrappedKeyData);
- }
- if (passWrappedKeyData != null) {
- keyData.setWrappedPrivateData(passWrappedKeyData);
- }
- if (nonceData != null) {
- keyData.setNonceData(nonceData);
- }
-
- String algorithm = rec.getAlgorithm();
- Integer keySize = rec.getKeySize();
-
- if (algorithm != null) {
- keyData.setAlgorithm(algorithm);
- }
-
- if (keySize != null) {
- keyData.setSize(keySize);
- }
-
- kra.destroyVolatileRequest(request.getRequestId());
-
- queue.markAsServiced(request);
-
- return keyData;
- }
-
- private KeyId validateRequest(KeyRecoveryRequest data) {
-
- // confirm request exists
- RequestId reqId = data.getRequestId();
- if (reqId == null) {
- auditRetrieveKey(ILogger.FAILURE, null, null, "Request id not found");
- // log error
- throw new BadRequestException("Request id not found.");
- }
-
- // confirm that at least one wrapping method exists
- // There must be at least the wrapped session key method.
- if ((data.getTransWrappedSessionKey() == null)) {
- auditRetrieveKey(ILogger.FAILURE, reqId, null, "No wrapping method found");
- // log error
- throw new BadRequestException("No wrapping method found.");
- }
-
- KeyRequestDAO reqDAO = new KeyRequestDAO();
- KeyRequestInfo reqInfo;
- try {
- reqInfo = reqDAO.getRequest(reqId, uriInfo);
- } catch (EBaseException e1) {
- auditRetrieveKey(ILogger.FAILURE, reqId, null, "failed to get request");
- // failed to get request
- e1.printStackTrace();
- throw new PKIException(e1.getMessage());
- }
- if (reqInfo == null) {
- auditRetrieveKey(ILogger.FAILURE, reqId, null, "no request info available");
- // request not found
- throw new HTTPGoneException("No request information available.");
- }
-
- //confirm request is of the right type
- String type = reqInfo.getRequestType();
- if (!type.equals(IRequest.SECURITY_DATA_RECOVERY_REQUEST)) {
- auditRetrieveKey(ILogger.FAILURE, reqId, null, "invalid request type");
- // log error
- throw new BadRequestException("Invalid request type");
- }
-
- //confirm that agent is originator of request, else throw 401
- // TO-DO
-
- // confirm request is in approved state
- RequestStatus status = reqInfo.getRequestStatus();
- if (!status.equals(RequestStatus.APPROVED)) {
- auditRetrieveKey(ILogger.FAILURE, reqId, null, "recovery request not approved");
- // log error
- throw new UnauthorizedException("Unauthorized request. Recovery request not approved.");
- }
-
- return reqInfo.getKeyId();
- }
-
- /**
- * Used to generate list of key infos based on the search parameters
- */
- @Override
- public Response listKeys(String clientKeyID, String status, Integer maxResults, Integer maxTime,
- Integer start, Integer size) {
- return createOKResponse(listKeyInfos(clientKeyID, status, maxResults, maxTime, start, size));
- }
-
- public KeyInfoCollection listKeyInfos(String clientKeyID, String status, Integer maxResults, Integer maxTime,
- Integer start, Integer size) {
-
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- // get ldap filter
- String filter = createSearchFilter(status, clientKeyID);
- CMS.debug("listKeys: filter is " + filter);
-
- maxResults = maxResults == null ? DEFAULT_MAXRESULTS : maxResults;
- maxTime = maxTime == null ? DEFAULT_MAXTIME : maxTime;
-
- KeyInfoCollection infos = new KeyInfoCollection();
- try {
- Enumeration<IKeyRecord> e = repo.searchKeys(filter, maxResults, maxTime);
- if (e == null) {
- return infos;
- }
-
- // store non-null results in a list
- List<KeyInfo> results = new ArrayList<KeyInfo>();
- while (e.hasMoreElements()) {
- IKeyRecord rec = e.nextElement();
- if (rec == null) continue;
- results.add(createKeyDataInfo(rec));
- }
-
- int total = results.size();
- infos.setTotal(total);
-
- // return entries in the requested page
- for (int i = start; i < start + size && i < total; i++) {
- infos.addEntry(results.get(i));
- }
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- infos.addLink(new Link("prev", uri));
- }
-
- if (start + size < total) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- infos.addLink(new Link("next", uri));
- }
-
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException(e.getMessage());
- }
-
- return infos;
- }
-
- @Override
- public Response getActiveKeyInfo(String clientKeyID) {
-
- KeyInfoCollection infos = listKeyInfos(
- clientKeyID,
- "active",
- null,
- null,
- null,
- null
- );
-
- Collection<KeyInfo> list = infos.getEntries();
- Iterator<KeyInfo> iter = list.iterator();
-
- while (iter.hasNext()) {
- KeyInfo info = iter.next();
- if (info != null) {
- // return the first one
- return createOKResponse(info);
- }
- }
-
- throw new ResourceNotFoundException("Key not found.");
- }
-
- public KeyInfo createKeyDataInfo(IKeyRecord rec) throws EBaseException {
- KeyInfo ret = new KeyInfo();
- ret.setClientKeyID(rec.getClientId());
- ret.setStatus(rec.getKeyStatus());
- ret.setAlgorithm(rec.getAlgorithm());
- ret.setSize(rec.getKeySize());
- ret.setOwnerName(rec.getOwnerName());
-
- Path keyPath = KeyResource.class.getAnnotation(Path.class);
- BigInteger serial = rec.getSerialNumber();
-
- UriBuilder keyBuilder = uriInfo.getBaseUriBuilder();
- keyBuilder.path(keyPath.value() + "/" + serial);
- ret.setKeyURL(keyBuilder.build().toString());
-
- return ret;
- }
-
- private String createSearchFilter(String status, String clientKeyID) {
- String filter = "";
- int matches = 0;
-
- if ((status == null) && (clientKeyID == null)) {
- filter = "(serialno=*)";
- return filter;
- }
-
- if (status != null) {
- filter += "(status=" + LDAPUtil.escapeFilter(status) + ")";
- matches ++;
- }
-
- if (clientKeyID != null) {
- filter += "(clientID=" + LDAPUtil.escapeFilter(clientKeyID) + ")";
- matches ++;
- }
-
- if (matches > 1) {
- filter = "(&" + filter + ")";
- }
-
- return filter;
- }
-
- public void auditRetrieveKey(String status, RequestId requestID, KeyId keyID, String reason) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SECURITY_DATA_RETRIEVE_KEY,
- servletRequest.getUserPrincipal().getName(),
- status,
- requestID != null ? requestID.toString(): "null",
- keyID != null ? keyID.toString(): "null",
- reason);
- auditor.log(msg);
- }
-
- /**
- * Used to retrieve a key
- * @param data
- * @return
- */
- private KeyData recoverKey(KeyRecoveryRequest data) {
- // confirm request exists
- RequestId reqId = data.getRequestId();
-
- IRequest request = null;
- try {
- request = queue.findRequest(reqId);
- } catch (EBaseException e) {
- }
- if (request == null) {
- throw new HTTPGoneException("No request record.");
- }
- String type = request.getRequestType();
- RequestStatus status = request.getRequestStatus();
- if (!IRequest.KEYRECOVERY_REQUEST.equals(type) ||
- !status.equals(RequestStatus.APPROVED)) {
- auditRetrieveKey(ILogger.FAILURE, reqId, null, "Unauthorized request.");
- throw new UnauthorizedException("Unauthorized request.");
- }
-
- String passphrase = data.getPassphrase();
- byte pkcs12[] = null;
- try {
- pkcs12 = service.doKeyRecovery(reqId.toString(), passphrase);
- } catch (EBaseException e) {
- }
- if (pkcs12 == null) {
- throw new HTTPGoneException("Key not recovered.");
- }
- String pkcs12base64encoded = Utils.base64encode(pkcs12);
-
- KeyData keyData = new KeyData();
- keyData.setP12Data(pkcs12base64encoded);
-
- try {
- queue.processRequest(request);
- queue.markAsServiced(request);
- } catch (EBaseException e) {
- }
-
- return keyData;
- }
-
- @Override
- public Response getKeyInfo(KeyId keyId) {
- IKeyRecord rec = null;
- try {
- rec = repo.readKeyRecord(keyId.toBigInteger());
- KeyInfo info = createKeyDataInfo(rec);
-
- return createOKResponse(info);
- } catch (EDBRecordNotFoundException e) {
- throw new KeyNotFoundException(keyId);
- } catch (Exception e) {
- CMS.debug("Unable to retrieve key record: " + e);
- e.printStackTrace();
- throw new PKIException(e.getMessage());
- }
- }
-
- @Override
- public Response modifyKeyStatus(KeyId keyId, String status) {
- try {
-
- ModificationSet mods = new ModificationSet();
- mods.add(IKeyRecord.ATTR_STATUS, Modification.MOD_REPLACE,
- status);
- repo.modifyKeyRecord(keyId.toBigInteger(), mods);
- return createNoContentResponse();
- } catch (EDBRecordNotFoundException e) {
- throw new KeyNotFoundException(keyId);
- } catch (Exception e) {
- CMS.debug("Unable to retrieve key record: " + e);
- e.printStackTrace();
- throw new PKIException(e.getMessage());
- }
- }
-
-
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/profile/ProfileService.java b/base/server/cms/src/com/netscape/cms/servlet/profile/ProfileService.java
deleted file mode 100644
index eb9dc83df..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/profile/ProfileService.java
+++ /dev/null
@@ -1,1033 +0,0 @@
-//--- 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) 2011 Red Hat, Inc.
-//All rights reserved.
-//--- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.profile;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.commons.lang.StringUtils;
-import org.jboss.resteasy.plugins.providers.atom.Link;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.IConfigStore;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.UnauthorizedException;
-import com.netscape.certsrv.common.NameValuePairs;
-import com.netscape.certsrv.common.OpDef;
-import com.netscape.certsrv.common.ScopeDef;
-import com.netscape.certsrv.logging.ILogger;
-import com.netscape.certsrv.profile.EProfileException;
-import com.netscape.certsrv.profile.IProfile;
-import com.netscape.certsrv.profile.IProfileEx;
-import com.netscape.certsrv.profile.IProfileInput;
-import com.netscape.certsrv.profile.IProfileOutput;
-import com.netscape.certsrv.profile.IProfilePolicy;
-import com.netscape.certsrv.profile.IProfileSubsystem;
-import com.netscape.certsrv.profile.PolicyConstraint;
-import com.netscape.certsrv.profile.PolicyConstraintValue;
-import com.netscape.certsrv.profile.PolicyDefault;
-import com.netscape.certsrv.profile.ProfileData;
-import com.netscape.certsrv.profile.ProfileDataInfo;
-import com.netscape.certsrv.profile.ProfileDataInfos;
-import com.netscape.certsrv.profile.ProfileInput;
-import com.netscape.certsrv.profile.ProfileNotFoundException;
-import com.netscape.certsrv.profile.ProfileOutput;
-import com.netscape.certsrv.profile.ProfileParameter;
-import com.netscape.certsrv.profile.ProfilePolicy;
-import com.netscape.certsrv.profile.ProfileResource;
-import com.netscape.certsrv.property.EPropertyException;
-import com.netscape.certsrv.registry.IPluginInfo;
-import com.netscape.certsrv.registry.IPluginRegistry;
-import com.netscape.cms.realm.PKIPrincipal;
-import com.netscape.cms.servlet.base.PKIService;
-
-/**
- * @author alee
- *
- */
-public class ProfileService extends PKIService implements ProfileResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- public final static int DEFAULT_SIZE = 20;
-
- private IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID);
- private IPluginRegistry registry = (IPluginRegistry) CMS.getSubsystem(CMS.SUBSYSTEM_REGISTRY);
- private IConfigStore cs = CMS.getConfigStore().getSubStore("profile");
-
- private final static String LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL =
- "LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL_4";
- private final static String LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE =
- "LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE_3";
-
- @Override
- public Response listProfiles(Integer start, Integer size) {
-
- start = start == null ? 0 : start;
- size = size == null ? DEFAULT_SIZE : size;
-
- ProfileDataInfos infos = new ProfileDataInfos();
- boolean visibleOnly = true;
-
- if (ps == null) {
- CMS.debug("listProfiles: ps is null");
- throw new PKIException("Error listing profiles. Profile Service not available");
- }
-
- PKIPrincipal principal = (PKIPrincipal) servletRequest.getUserPrincipal();
- if ((principal != null) &&
- (principal.hasRole("Certificate Manager Agents") ||
- principal.hasRole("Certificate Manager Administrators"))) {
- visibleOnly = false;
- }
-
- Enumeration<String> e = ps.getProfileIds();
- if (e == null) return createOKResponse(infos);
-
- // store non-null results in a list
- List<ProfileDataInfo> results = new ArrayList<ProfileDataInfo>();
- while (e.hasMoreElements()) {
- try {
- String id = e.nextElement();
- ProfileDataInfo info = createProfileDataInfo(id, visibleOnly, uriInfo, getLocale(headers));
- if (info == null) continue;
- results.add(info);
- } catch (EBaseException ex) {
- continue;
- }
- }
-
- int total = results.size();
- infos.setTotal(total);
-
- // return entries in the requested page
- for (int i = start; i < start + size && i < total; i++) {
- infos.addEntry(results.get(i));
- }
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- infos.addLink(new Link("prev", uri));
- }
-
- if (start + size < total) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- infos.addLink(new Link("next", uri));
- }
-
- return createOKResponse(infos);
- }
-
- @Override
- public Response retrieveProfile(String profileId) throws ProfileNotFoundException {
- ProfileData data = null;
- boolean visibleOnly = true;
-
- if (profileId == null) {
- CMS.debug("retrieveProfile: profileID is null");
- throw new BadRequestException("Unable to retrieve profile: invalid profile ID");
- }
-
- if (ps == null) {
- CMS.debug("retrieveProfile: ps is null");
- throw new PKIException("Error retrieving profile. Profile Service not available");
- }
-
- PKIPrincipal principal = (PKIPrincipal) servletRequest.getUserPrincipal();
- if ((principal != null) &&
- (principal.hasRole("Certificate Manager Agents") ||
- principal.hasRole("Certificate Manager Administrators"))) {
- visibleOnly = false;
- }
-
- Enumeration<String> profileIds = ps.getProfileIds();
-
- IProfile profile = null;
- if (profileIds != null) {
- while (profileIds.hasMoreElements()) {
- String id = profileIds.nextElement();
-
- if (id.equals(profileId)) {
-
- try {
- profile = ps.getProfile(profileId);
- } catch (EProfileException e) {
- e.printStackTrace();
- throw new ProfileNotFoundException(profileId);
- }
- break;
- }
- }
- }
-
- if (profile == null) {
- throw new ProfileNotFoundException(profileId);
- }
-
- if (visibleOnly && !profile.isVisible()) {
- throw new ProfileNotFoundException(profileId);
- }
-
- try {
- data = createProfileData(profileId);
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new ProfileNotFoundException(profileId);
- }
-
- UriBuilder profileBuilder = uriInfo.getBaseUriBuilder();
- URI uri = profileBuilder.path(ProfileResource.class).path("{id}").
- build(profileId);
- data.setLink(new Link("self", uri));
-
- return createOKResponse(data);
- }
-
- public ProfileData createProfileData(String profileId) throws EBaseException {
-
- IProfile profile;
-
- try {
- profile = ps.getProfile(profileId);
- } catch (EProfileException e) {
- e.printStackTrace();
- throw new ProfileNotFoundException(profileId);
- }
-
- ProfileData data = new ProfileData();
-
- data.setAuthenticatorId(profile.getAuthenticatorId());
- data.setAuthzAcl(profile.getAuthzAcl());
- data.setClassId(cs.getString(profileId + ".class_id"));
- data.setDescription(profile.getDescription(getLocale(headers)));
- data.setEnabled(ps.isProfileEnable(profileId));
- data.setEnabledBy(ps.getProfileEnableBy(profileId));
- data.setId(profileId);
- data.setName(profile.getName(getLocale(headers)));
- data.setRenewal(Boolean.getBoolean(profile.isRenewal()));
- data.setVisible(profile.isVisible());
- data.setXMLOutput(Boolean.getBoolean(profile.isXmlOutput()));
-
- Enumeration<String> inputIds = profile.getProfileInputIds();
- if (inputIds != null) {
- while (inputIds.hasMoreElements()) {
- ProfileInput input = createProfileInput(profile, inputIds.nextElement(), getLocale(headers));
- if (input == null)
- continue;
- data.addProfileInput(input);
- }
- }
-
- // profile outputs
- Enumeration<String> outputIds = profile.getProfileOutputIds();
- if (outputIds != null) {
- while (outputIds.hasMoreElements()) {
- ProfileOutput output = createProfileOutput(profile, outputIds.nextElement(), getLocale(headers));
- if (output == null)
- continue;
- data.addProfileOutput(output);
- }
- }
-
- // profile policies
- Enumeration<String> policySetIds = profile.getProfilePolicySetIds();
- if (policySetIds != null) {
- while (policySetIds.hasMoreElements()) {
- Vector<ProfilePolicy> pset = new Vector<ProfilePolicy>();
- String policySetId = policySetIds.nextElement();
- Enumeration<String> policyIds = profile.getProfilePolicyIds(policySetId);
- while (policyIds.hasMoreElements()) {
- String policyId = policyIds.nextElement();
- pset.add(createProfilePolicy(profile, policySetId, policyId));
- }
-
- if (!pset.isEmpty()) {
- data.addProfilePolicySet(policySetId, pset);
- }
- }
- }
-
- UriBuilder profileBuilder = uriInfo.getBaseUriBuilder();
- URI uri = profileBuilder.path(ProfileResource.class).path("{id}").
- build(profileId);
- data.setLink(new Link("self", uri));
-
- return data;
- }
-
- public ProfilePolicy createProfilePolicy(IProfile profile, String setId, String policyId) throws EBaseException {
- IProfilePolicy policy = profile.getProfilePolicy(setId, policyId);
- IConfigStore policyStore = profile.getConfigStore().getSubStore(
- "policyset." + setId + "." + policy.getId());
-
- ProfilePolicy p = new ProfilePolicy();
- String constraintClassId = policyStore.getString("constraint.class_id");
- p.setConstraint(PolicyConstraintFactory.create(getLocale(headers), policy.getConstraint(), constraintClassId));
- String defaultClassId = policyStore.getString("default.class_id");
- p.setDef(PolicyDefaultFactory.create(getLocale(headers), policy.getDefault(), defaultClassId));
- p.setId(policy.getId());
- return p;
- }
-
- public static ProfileInput createProfileInput(IProfile profile, String inputId, Locale locale) throws EBaseException {
- IProfileInput profileInput = profile.getProfileInput(inputId);
- if (profileInput == null)
- return null;
-
- IConfigStore inputStore = profile.getConfigStore().getSubStore("input");
- String classId = inputStore.getString(inputId + ".class_id");
-
- return new ProfileInput(profileInput, inputId, classId, locale);
- }
-
- public static ProfileOutput createProfileOutput(IProfile profile, String outputId, Locale locale) throws EBaseException {
- IProfileOutput profileOutput = profile.getProfileOutput(outputId);
- if (profileOutput == null)
- return null;
-
- IConfigStore outputStore = profile.getConfigStore().getSubStore("output");
- String classId = outputStore.getString(outputId + ".class_id");
-
- return new ProfileOutput(profileOutput, outputId, classId, locale);
- }
-
- public static ProfileDataInfo createProfileDataInfo(String profileId, boolean visibleOnly, UriInfo uriInfo,
- Locale locale) throws EBaseException {
-
- IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID);
- if (profileId == null) {
- throw new EBaseException("Error creating ProfileDataInfo.");
- }
- ProfileDataInfo ret = null;
-
- IProfile profile = null;
-
- profile = ps.getProfile(profileId);
- if (profile == null) {
- return null;
- }
-
- if (visibleOnly && !profile.isVisible()) {
- return null;
- }
-
- ret = new ProfileDataInfo();
-
- ret.setProfileId(profileId);
- ret.setProfileName(profile.getName(locale));
- ret.setProfileDescription(profile.getDescription(locale));
-
- UriBuilder profileBuilder = uriInfo.getBaseUriBuilder();
- URI uri = profileBuilder.path(ProfileResource.class).path("{id}").
- build(profileId);
-
- ret.setProfileURL(uri.toString());
-
- return ret;
- }
-
- @Override
- public Response modifyProfileState(String profileId, String action) {
- if (profileId == null) {
- CMS.debug("modifyProfileState: invalid request. profileId is null");
- throw new BadRequestException("Unable to modify profile state: Invalid Profile Id");
- }
-
- if (ps == null) {
- CMS.debug("modifyProfileState: ps is null");
- throw new PKIException("Error modifying profile state. Profile Service not available");
- }
-
- try {
- IProfile profile = ps.getProfile(profileId);
- if (profile == null) {
- CMS.debug("Trying to modify profile: " + profileId + ". Profile not found.");
- throw new ProfileNotFoundException(profileId);
- }
- } catch (EProfileException e1) {
- e1.printStackTrace();
- throw new PKIException("Error modifying profile state: unable to get profile");
- }
-
- Principal principal = servletRequest.getUserPrincipal();
-
- switch (action) {
- case "enable":
- if (ps.isProfileEnable(profileId)) {
- throw new BadRequestException("Profile already enabled");
- }
- try {
- ps.enableProfile(profileId, principal.getName());
- auditProfileChangeState(profileId, "approve", ILogger.SUCCESS);
- } catch (EProfileException e) {
- CMS.debug("modifyProfileState: error enabling profile. " + e);
- e.printStackTrace();
- auditProfileChangeState(profileId, "approve", ILogger.FAILURE);
- throw new PKIException("Error enabling profile");
- }
- break;
- case "disable":
- if (!ps.isProfileEnable(profileId)) {
- throw new BadRequestException("Profile already disabled");
- }
- String userid = principal.getName();
- try {
- if (ps.checkOwner()) {
- if (ps.getProfileEnableBy(profileId).equals(userid)) {
- ps.disableProfile(profileId);
- auditProfileChangeState(profileId, "disapprove", ILogger.SUCCESS);
- } else {
- auditProfileChangeState(profileId, "disapprove", ILogger.FAILURE);
- throw new UnauthorizedException(
- "Profile can only be disabled by the agent that enabled it");
- }
- } else {
- ps.disableProfile(profileId);
- auditProfileChangeState(profileId, "disapprove", ILogger.SUCCESS);
- }
- } catch (EProfileException e) {
- CMS.debug("modifyProfileState: Error disabling profile: " + e);
- e.printStackTrace();
- auditProfileChangeState(profileId, "disapprove", ILogger.FAILURE);
- throw new PKIException("Error disabling profile");
- }
- break;
- default:
- auditProfileChangeState(profileId, "invalid", ILogger.FAILURE);
- throw new BadRequestException("Invalid operation");
- }
-
- return createNoContentResponse();
- }
-
- @Override
- public Response createProfile(ProfileData data) {
- if (data == null) {
- CMS.debug("createProfile: profile data is null");
- throw new BadRequestException("Unable to create profile: Invalid profile data.");
- }
-
- if (ps == null) {
- CMS.debug("createProfile: ps is null");
- throw new PKIException("Error creating profile. Profile Service not available");
- }
-
- IProfile profile = null;
- String profileId = data.getId();
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- try {
- profile = ps.getProfile(profileId);
- if (profile != null) {
- throw new BadRequestException("Profile already exists");
- }
-
- auditParams.put("class_id", data.getClassId());
- auditParams.put("name", data.getName());
- auditParams.put("description", data.getDescription());
- auditParams.put("visible", Boolean.toString(data.isVisible()));
-
- String config = CMS.getConfigStore().getString("instanceRoot") + "/ca/profiles/ca/" +
- profileId + ".cfg";
- File configFile = new File(config);
- configFile.createNewFile();
- IPluginInfo info = registry.getPluginInfo("profile", data.getClassId());
-
- profile = ps.createProfile(profileId, data.getClassId(), info.getClassName(), config);
- profile.setName(getLocale(headers), data.getName());
- profile.setDescription(getLocale(headers), data.getDescription());
- profile.setVisible(data.isVisible());
- profile.getConfigStore().commit(false);
- ps.createProfileConfig(profileId, data.getClassId(), config);
-
- if (profile instanceof IProfileEx) {
- // populates profile specific plugins such as
- // policies, inputs and outputs with defaults
- ((IProfileEx) profile).populate();
- }
-
- auditProfileChange(
- ScopeDef.SC_PROFILE_RULES,
- OpDef.OP_ADD,
- profileId,
- ILogger.SUCCESS,
- auditParams);
-
- changeProfileData(data, profile);
-
- ProfileData profileData = createProfileData(profileId);
-
- return createCreatedResponse(profileData, profileData.getLink().getHref());
-
- } catch (EBaseException | IOException e) {
- CMS.debug("createProfile: error in creating profile: " + e);
- e.printStackTrace();
-
- auditProfileChange(
- ScopeDef.SC_PROFILE_RULES,
- OpDef.OP_ADD,
- profileId,
- ILogger.FAILURE,
- auditParams);
-
- throw new PKIException("Error in creating profile");
- }
- }
-
- @Override
- public Response modifyProfile(String profileId, ProfileData data) {
- if (profileId == null) {
- CMS.debug("modifyProfile: invalid request. profileId is null");
- throw new BadRequestException("Unable to modify profile: Invalid Profile Id");
- }
-
- if (data == null) {
- CMS.debug("modifyProfile: invalid request. data is null");
- throw new BadRequestException("Unable to modify profile: Invalid profile data");
- }
-
- if (ps == null) {
- CMS.debug("modifyProfile: ps is null");
- throw new PKIException("Error modifying profile. Profile Service not available");
- }
-
- IProfile profile = null;
- try {
- profile = ps.getProfile(profileId);
- if (profile == null) {
- throw new ProfileNotFoundException(profileId);
- }
-
- changeProfileData(data, profile);
-
- ProfileData profileData = createProfileData(profileId);
-
- return createOKResponse(profileData);
-
- } catch (EBaseException e) {
- CMS.debug("modifyProfile: error obtaining profile `" + profileId + "`: " + e);
- e.printStackTrace();
- throw new PKIException("Error modifying profile. Cannot obtain profile.");
- }
- }
-
- private void changeProfileData(ProfileData data, IProfile profile) {
- String profileId = data.getId();
- if (profile == null) {
- CMS.debug("changeProfileData - profile is null");
- throw new PKIException("Error changing profile data. Profile not available.");
- }
- if (ps.isProfileEnable(profileId)) {
- throw new BadRequestException("Cannot change profile data. Profile must be disabled");
- }
-
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
-
- if (differs(profile.getAuthenticatorId(), data.getAuthenticatorId())) {
- profile.setAuthenticatorId(data.getAuthenticatorId());
- auditParams.put("authenticatorId", data.getAuthenticatorId());
- }
-
- if (differs(profile.getAuthzAcl(), data.getAuthzAcl())) {
- profile.setAuthzAcl(data.getAuthzAcl());
- auditParams.put("authzAcl", data.getAuthzAcl());
- }
-
- if (differs(profile.getDescription(getLocale(headers)), data.getDescription())) {
- profile.setDescription(getLocale(headers), data.getDescription());
- auditParams.put("description", data.getDescription());
- }
-
- if (differs(profile.getId(), data.getId())) {
- profile.setId(data.getId());
- auditParams.put("id", data.getId());
- }
-
- if (differs(profile.getName(getLocale(headers)), data.getName())) {
- profile.setName(getLocale(headers), data.getName());
- auditParams.put("name", data.getName());
- }
-
- // TODO renewal is a string in Profile, should be changed
- if (differs(profile.isRenewal(), Boolean.toString(data.isRenewal()))) {
- profile.setRenewal(data.isRenewal());
- auditParams.put("renewal", Boolean.toString(data.isRenewal()));
- }
-
- if (!profile.isVisible() == data.isVisible()) {
- profile.setVisible(data.isVisible());
- auditParams.put("visible", Boolean.toString(data.isVisible()));
- }
-
- // TODO xmloutput is a string in Profile, should be changed
- if (differs(profile.isXmlOutput(), Boolean.toString(data.isXMLOutput()))) {
- profile.setXMLOutput(data.isXMLOutput());
- auditParams.put("xmloutput", Boolean.toString(data.isXMLOutput()));
- }
-
- if (!auditParams.isEmpty()) {
- auditProfileChange(
- ScopeDef.SC_PROFILE_RULES,
- OpDef.OP_MODIFY,
- profileId,
- ILogger.SUCCESS,
- auditParams);
- }
-
- try {
- populateProfileInputs(data, profile);
- populateProfileOutputs(data, profile);
- populateProfilePolicies(data, profile);
- profile.getConfigStore().commit(false);
- } catch (EBaseException e) {
- CMS.debug("changeProfileData: Error changing profile inputs/outputs/policies: " + e);
- e.printStackTrace();
- throw new PKIException("Error changing profile data");
- }
- }
-
- private boolean differs(String v1, String v2) {
- if (v1 != null) {
- if (!v1.equals(v2)) {
- return true;
- }
- } else {
- if (v2 != null) {
- return true;
- }
- }
- return false;
- }
-
- private void populateProfilePolicies(ProfileData data, IProfile profile) throws EBaseException {
- // get list of changes for auditing
- List<String> auditAdd = new ArrayList<String>();
- List<String> auditModify = new ArrayList<String>();
-
- Enumeration<String> existingSetIds = profile.getProfilePolicySetIds();
- Map<String, ProfilePolicy> existingPolicies = new LinkedHashMap<String, ProfilePolicy>();
- while (existingSetIds.hasMoreElements()) {
- String setId = existingSetIds.nextElement();
- Enumeration<String> policyIds = profile.getProfilePolicyIds(setId);
- while (policyIds.hasMoreElements()) {
- String policyId = policyIds.nextElement();
- existingPolicies.put(
- setId + ":" + policyId,
- createProfilePolicy(profile, setId, policyId));
- }
- }
-
- for (Map.Entry<String, List<ProfilePolicy>> policySet : data.getPolicySets().entrySet()) {
- String setId = policySet.getKey();
- for (ProfilePolicy policy : policySet.getValue()) {
- String id = setId + ":" + policy.getId();
- if (!existingPolicies.containsKey(id)) {
- auditAdd.add(id);
- } else {
- if (!policy.equals(existingPolicies.get(id))) {
- auditModify.add(id);
- }
- }
- existingPolicies.remove(id);
- }
- }
-
- List<String> auditDelete = new ArrayList<String>(existingPolicies.keySet());
-
- //perform actions
- try {
- profile.deleteAllProfilePolicies();
- for (Map.Entry<String, List<ProfilePolicy>> policySet : data.getPolicySets().entrySet()) {
- String setId = policySet.getKey();
- for (ProfilePolicy policy : policySet.getValue()) {
- PolicyDefault def = policy.getDef();
- PolicyConstraint con = policy.getConstraint();
-
- // create policy using defaults for PolicyDefault and PolicyConstraint
- IProfilePolicy p = profile.createProfilePolicy(setId, policy.getId(),
- def.getClassId(), con.getClassId());
-
- // change specific elements to match incoming data for PolicyDefault
- IConfigStore pstore = profile.getConfigStore().getSubStore(
- "policyset." + setId + "." + policy.getId());
- if (!def.getName().isEmpty()) {
- pstore.putString("default.name", def.getName());
- }
- /*if (!def.getText().isEmpty()) {
- pstore.putString("default.description", def.getText());
- }*/
- for (ProfileParameter param : def.getParams()) {
- if (!param.getValue().isEmpty()) {
- p.getDefault().setConfig(param.getName(), param.getValue());
- }
- }
-
- // change specific elements to match incoming data for PolicyConstraint
- if (!con.getName().isEmpty()) {
- pstore.putString("constraint.name", con.getName());
- }
- /*if (!con.getText().isEmpty()) {
- pstore.putString("constraint.description", con.getText());
- }*/
- for (PolicyConstraintValue pcv : con.getConstraints()) {
- if (!pcv.getValue().isEmpty()) {
- p.getConstraint().setConfig(pcv.getName(), pcv.getValue());
- }
- }
- }
- }
-
- if (!auditDelete.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("inputs", StringUtils.join(auditDelete, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_POLICIES,
- OpDef.OP_DELETE,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
-
- if (!auditAdd.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("inputs", StringUtils.join(auditAdd, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_POLICIES,
- OpDef.OP_ADD,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
-
- if (!auditModify.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("inputs", StringUtils.join(auditModify, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_POLICIES,
- OpDef.OP_MODIFY,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
- } catch (EProfileException | EPropertyException e) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("added", StringUtils.join(auditAdd, ","));
- auditParams.put("deleted", StringUtils.join(auditDelete, ","));
- auditParams.put("modified", StringUtils.join(auditModify, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_POLICIES,
- OpDef.OP_MODIFY,
- profile.getId(),
- ILogger.FAILURE,
- auditParams);
- throw e;
- }
- }
-
- private void populateProfileOutputs(ProfileData data, IProfile profile) throws EBaseException {
- // get list of changes for auditing
- List<String> auditAdd = new ArrayList<String>();
- List<String> auditModify = new ArrayList<String>();
-
- Enumeration<String> existingIds = profile.getProfileOutputIds();
- Map<String, ProfileOutput> existingOutputs = new LinkedHashMap<String, ProfileOutput>();
- while (existingIds.hasMoreElements()) {
- String id = existingIds.nextElement();
- ProfileOutput output = createProfileOutput(profile, id, getLocale(headers));
- if (output == null)
- continue;
- existingOutputs.put(id, output);
- }
-
- List<ProfileOutput> outputs = data.getOutputs();
- for (ProfileOutput output : outputs) {
- String id = output.getId();
- if (!existingOutputs.containsKey(id)) {
- auditAdd.add(id);
- } else {
- if (!output.equals(existingOutputs.get(id))) {
- auditModify.add(id);
- }
- existingOutputs.remove(id);
- }
- }
- List<String> auditDelete = new ArrayList<String>(existingOutputs.keySet());
-
- // perform operations
-
- try {
- profile.deleteAllProfileOutputs();
- for (ProfileOutput output : outputs) {
- String id = output.getId();
- String classId = output.getClassId();
-
- NameValuePairs nvp = new NameValuePairs();
- // TODO - add a field for params in ProfileOuput
- // No current examples
- profile.createProfileOutput(id, classId, nvp);
- }
-
- if (!auditDelete.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("outputs", StringUtils.join(auditDelete, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_OUTPUT,
- OpDef.OP_DELETE,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
-
- if (!auditAdd.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("outputs", StringUtils.join(auditAdd, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_OUTPUT,
- OpDef.OP_ADD,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
-
- if (!auditModify.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("outputs", StringUtils.join(auditModify, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_OUTPUT,
- OpDef.OP_MODIFY,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
- } catch (EProfileException e) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
-
- auditParams.put("added", StringUtils.join(auditAdd, ","));
- auditParams.put("deleted", StringUtils.join(auditDelete, ","));
- auditParams.put("modified", StringUtils.join(auditModify, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_OUTPUT,
- OpDef.OP_MODIFY,
- profile.getId(),
- ILogger.FAILURE,
- auditParams);
- throw e;
- }
- }
-
- private void populateProfileInputs(ProfileData data, IProfile profile) throws EBaseException {
- // get list of changes for auditing
- List<String> auditAdd = new ArrayList<String>();
- List<String> auditModify = new ArrayList<String>();
- Enumeration<String> existingIds = profile.getProfileInputIds();
- Map<String, ProfileInput> existingInputs = new LinkedHashMap<String, ProfileInput>();
-
- while (existingIds.hasMoreElements()) {
- String id = existingIds.nextElement();
- ProfileInput input = createProfileInput(profile, id, getLocale(headers));
- if (input == null)
- continue;
- existingInputs.put(id, input);
- }
-
- List<ProfileInput> inputs = data.getInputs();
- for (ProfileInput input : inputs) {
- String id = input.getId();
- if (!existingInputs.containsKey(id)) {
- auditAdd.add(id);
- } else {
- if (!input.equals(existingInputs.get(id))) {
- auditModify.add(id);
- }
- existingInputs.remove(id);
- }
- }
- List<String> auditDelete = new ArrayList<String>(existingInputs.keySet());
-
- try {
- // perform the operations
- profile.deleteAllProfileInputs();
-
- for (ProfileInput input : inputs) {
- String id = input.getId();
- String classId = input.getClassId();
-
- NameValuePairs nvp = new NameValuePairs();
- // TODO - add a field for params in ProfileInput.
- // an example of this is DomainController.cfg
- profile.createProfileInput(id, classId, nvp);
- }
-
- if (!auditDelete.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("inputs", StringUtils.join(auditDelete, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_INPUT,
- OpDef.OP_DELETE,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
-
- if (!auditAdd.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("inputs", StringUtils.join(auditAdd, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_INPUT,
- OpDef.OP_ADD,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
-
- if (!auditModify.isEmpty()) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
- auditParams.put("inputs", StringUtils.join(auditModify, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_INPUT,
- OpDef.OP_MODIFY,
- profile.getId(),
- ILogger.SUCCESS,
- auditParams);
- }
- } catch (EProfileException e) {
- Map<String, String> auditParams = new LinkedHashMap<String, String>();
-
- auditParams.put("added", StringUtils.join(auditAdd, ","));
- auditParams.put("deleted", StringUtils.join(auditDelete, ","));
- auditParams.put("modified", StringUtils.join(auditModify, ","));
- auditProfileChange(
- ScopeDef.SC_PROFILE_INPUT,
- OpDef.OP_MODIFY,
- profile.getId(),
- ILogger.FAILURE,
- auditParams);
- throw e;
- }
- }
-
- @Override
- public Response deleteProfile(@PathParam("id") String profileId) {
- if (profileId == null) {
- CMS.debug("deleteProfile: invalid request. profileId is null");
- throw new BadRequestException("Unable to delete profile: Invalid Profile Id");
- }
-
- if (ps == null) {
- CMS.debug("deleteProfile: ps is null");
- throw new PKIException("Error deleting profile. Profile Service not available");
- }
-
- try {
- IProfile profile = ps.getProfile(profileId);
- if (profile == null) {
- CMS.debug("Trying to delete profile: " + profileId + ". Profile already deleted.");
- throw new ProfileNotFoundException(profileId);
- }
-
- if (ps.isProfileEnable(profileId)) {
- CMS.debug("Delete profile not permitted. Profile must be disabled first.");
- auditProfileChange(
- ScopeDef.SC_PROFILE_RULES,
- OpDef.OP_DELETE,
- profileId,
- ILogger.FAILURE,
- null);
-
- throw new BadRequestException("Cannot delete profile `" + profileId +
- "`. Profile must be disabled first.");
- }
-
- String configFile = CMS.getConfigStore().getString("profile." + profileId + ".config");
-
- ps.deleteProfile(profileId, configFile);
-
- auditProfileChange(
- ScopeDef.SC_PROFILE_RULES,
- OpDef.OP_DELETE,
- profileId,
- ILogger.FAILURE,
- null);
-
- return createNoContentResponse();
-
- } catch (EBaseException e) {
- CMS.debug("deleteProfile: error in deleting profile `" + profileId + "`: " + e);
- e.printStackTrace();
-
- auditProfileChange(
- ScopeDef.SC_PROFILE_RULES,
- OpDef.OP_DELETE,
- profileId,
- ILogger.FAILURE,
- null);
-
- throw new PKIException("Error deleting profile.");
- }
- }
-
- public void auditProfileChangeState(String profileId, String op, String status) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CERT_PROFILE_APPROVAL,
- auditor.getSubjectID(),
- status,
- profileId,
- op);
- auditor.log(msg);
- }
-
- public void auditProfileChange(String scope, String type, String id, String status, Map<String, String> params) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_CONFIG_CERT_PROFILE,
- auditor.getSubjectID(),
- status,
- auditor.getParamString(scope, type, id, params));
- auditor.log(msg);
- }
-
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/request/CertRequestService.java b/base/server/cms/src/com/netscape/cms/servlet/request/CertRequestService.java
deleted file mode 100644
index df50a007e..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/request/CertRequestService.java
+++ /dev/null
@@ -1,420 +0,0 @@
-// --- 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) 2011 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.request;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.jboss.resteasy.plugins.providers.atom.Link;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.authentication.EAuthException;
-import com.netscape.certsrv.authorization.EAuthzException;
-import com.netscape.certsrv.base.BadRequestDataException;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.UnauthorizedException;
-import com.netscape.certsrv.cert.CertEnrollmentRequest;
-import com.netscape.certsrv.cert.CertRequestInfo;
-import com.netscape.certsrv.cert.CertRequestInfos;
-import com.netscape.certsrv.cert.CertRequestResource;
-import com.netscape.certsrv.cert.CertReviewResponse;
-import com.netscape.certsrv.profile.EDeferException;
-import com.netscape.certsrv.profile.EProfileException;
-import com.netscape.certsrv.profile.ERejectException;
-import com.netscape.certsrv.profile.IProfile;
-import com.netscape.certsrv.profile.IProfileSubsystem;
-import com.netscape.certsrv.profile.ProfileAttribute;
-import com.netscape.certsrv.profile.ProfileDataInfo;
-import com.netscape.certsrv.profile.ProfileDataInfos;
-import com.netscape.certsrv.profile.ProfileInput;
-import com.netscape.certsrv.property.EPropertyException;
-import com.netscape.certsrv.request.RequestId;
-import com.netscape.certsrv.request.RequestNotFoundException;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cms.servlet.cert.CertRequestDAO;
-import com.netscape.cms.servlet.profile.ProfileService;
-import com.netscape.cmsutil.ldap.LDAPUtil;
-
-/**
- * @author alee
- *
- */
-public class CertRequestService extends PKIService implements CertRequestResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- public static final int DEFAULT_START = 0;
- public static final int DEFAULT_PAGESIZE = 20;
- public static final int DEFAULT_MAXRESULTS = 100;
- public static final int DEFAULT_MAXTIME = 10;
-
- /**
- * Used to retrieve key request info for a specific request
- */
- @Override
- public Response getRequestInfo(RequestId id) {
- if (id == null) {
- CMS.debug("getRequestInfo: id is null");
- throw new BadRequestException("Unable to get request: invalid id");
- }
- CertRequestInfo info;
-
- CertRequestDAO dao = new CertRequestDAO();
- try {
- info = dao.getRequest(id, uriInfo);
- } catch (EBaseException e) {
- // log error
- e.printStackTrace();
- throw new PKIException("Error getting Cert request info!");
- }
-
- if (info == null) {
- throw new RequestNotFoundException(id);
- }
-
- return createOKResponse(info);
- }
-
- // Enrollment - used to test integration with a browser
- @Override
- public Response enrollCert(MultivaluedMap<String, String> form) {
- CertEnrollmentRequest data = new CertEnrollmentRequest(form);
- return enrollCert(data);
- }
-
- @Override
- public Response enrollCert(CertEnrollmentRequest data) {
-
- if (data == null) {
- CMS.debug("enrollCert: data is null");
- throw new BadRequestException("Unable to create enrollment reequest: Invalid input data");
- }
-
- CertRequestDAO dao = new CertRequestDAO();
-
- CertRequestInfos infos;
- try {
- infos = dao.submitRequest(data, servletRequest, uriInfo, getLocale(headers));
- } catch (EAuthException e) {
- CMS.debug("enrollCert: authentication failed: " + e);
- throw new UnauthorizedException(e.toString());
- } catch (EAuthzException e) {
- CMS.debug("enrollCert: authorization failed: " + e);
- throw new UnauthorizedException(e.toString());
- } catch (BadRequestDataException e) {
- CMS.debug("enrollCert: bad request data: " + e);
- throw new BadRequestException(e.toString());
- } catch (EBaseException e) {
- throw new PKIException(e.toString());
- }
-
- // this will return an error code of 200, instead of 201
- // because it is possible to create more than one request
- // as a result of this enrollment
-
- return createOKResponse(infos);
- }
-
- @Override
- public Response approveRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "approve");
- return createNoContentResponse();
- }
-
- @Override
- public Response rejectRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "reject");
- return createNoContentResponse();
- }
-
- @Override
- public Response cancelRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "cancel");
- return createNoContentResponse();
- }
-
- @Override
- public Response updateRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "update");
- return createNoContentResponse();
- }
-
- @Override
- public Response validateRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "validate");
- return createNoContentResponse();
- }
-
- @Override
- public Response unassignRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "unassign");
- return createNoContentResponse();
- }
-
- @Override
- public Response assignRequest(RequestId id, CertReviewResponse data) {
- changeRequestState(id, data, "assign");
- return createNoContentResponse();
- }
-
- public void changeRequestState(RequestId id, CertReviewResponse data, String op) {
- if (id == null) {
- throw new BadRequestException("Bad data input in CertRequestResourceService. op:" + op);
- }
- CertRequestDAO dao = new CertRequestDAO();
- try {
- dao.changeRequestState(id, servletRequest, data, getLocale(headers), op);
- } catch (ERejectException e) {
- CMS.debug("changeRequestState: execution rejected " + e);
- throw new BadRequestException(CMS.getUserMessage(getLocale(headers), "CMS_PROFILE_REJECTED", e.toString()));
- } catch (EDeferException e) {
- CMS.debug("changeRequestState: execution defered " + e);
- // TODO do we throw an exception here?
- throw new BadRequestException(CMS.getUserMessage(getLocale(headers), "CMS_PROFILE_DEFERRED", e.toString()));
- } catch (BadRequestDataException e) {
- CMS.debug("changeRequestState: bad request data: " + e);
- throw new BadRequestException(e.toString());
- } catch (EPropertyException e) {
- CMS.debug("changeRequestState: execution error " + e);
- throw new PKIException(CMS.getUserMessage(getLocale(headers),
- "CMS_PROFILE_PROPERTY_ERROR", e.toString()));
- } catch (EProfileException e) {
- CMS.debug("ProfileProcessServlet: execution error " + e);
- throw new PKIException(CMS.getUserMessage(getLocale(headers), "CMS_INTERNAL_ERROR"));
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Problem approving request in CertRequestResource.assignRequest! " + e);
- } catch (RequestNotFoundException e) {
- CMS.debug(e);
- throw e;
- }
- }
-
- @Override
- public Response reviewRequest(@PathParam("id") RequestId id) {
- if (id == null) {
- CMS.debug("reviewRequest: id is null");
- throw new BadRequestException("Unable to review request: invalid id");
- }
- CertReviewResponse info;
-
- CertRequestDAO dao = new CertRequestDAO();
- try {
- info = dao.reviewRequest(servletRequest, id, uriInfo, getLocale(headers));
- } catch (EBaseException e) {
- // log error
- e.printStackTrace();
- throw new PKIException("Error getting Cert request info!");
- }
-
- if (info == null) {
- // request does not exist
- throw new RequestNotFoundException(id);
- }
-
- return createOKResponse(info);
- }
-
- /**
- * Used to generate list of cert requests based on the search parameters
- */
- @Override
- public Response listRequests(String requestState, String requestType,
- RequestId start, Integer pageSize, Integer maxResults, Integer maxTime) {
- // get ldap filter
- String filter = createSearchFilter(requestState, requestType);
- CMS.debug("listRequests: filter is " + filter);
-
- start = start == null ? new RequestId(CertRequestService.DEFAULT_START) : start;
- pageSize = pageSize == null ? DEFAULT_PAGESIZE : pageSize;
- maxResults = maxResults == null ? DEFAULT_MAXRESULTS : maxResults;
- maxTime = maxTime == null ? DEFAULT_MAXTIME : maxTime;
-
- CertRequestDAO reqDAO = new CertRequestDAO();
- CertRequestInfos requests;
- try {
- requests = reqDAO.listRequests(filter, start, pageSize, maxResults, maxTime, uriInfo);
- } catch (EBaseException e) {
- CMS.debug("listRequests: error in obtaining request results" + e);
- e.printStackTrace();
- throw new PKIException("Error listing cert requests!");
- }
- return createOKResponse(requests);
- }
-
- private String createSearchFilter(String requestState, String requestType) {
- String filter = "";
- int matches = 0;
-
- if ((requestState == null) && (requestType == null)) {
- filter = "(requeststate=*)";
- return filter;
- }
-
- if (requestState != null) {
- filter += "(requeststate=" + LDAPUtil.escapeFilter(requestState) + ")";
- matches++;
- }
-
- if (requestType != null) {
- filter += "(requesttype=" + LDAPUtil.escapeFilter(requestType) + ")";
- matches++;
- }
-
- if (matches > 1) {
- filter = "(&" + filter + ")";
- }
-
- return filter;
- }
-
- @Override
- public Response getEnrollmentTemplate(String profileId) {
- if (profileId == null) {
- CMS.debug("getEnrollmenTemplate: invalid request. profileId is null");
- throw new BadRequestException("Invalid ProfileId");
- }
-
- IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID);
- if (ps == null) {
- CMS.debug("getEnrollmentTemplate: ps is null");
- throw new PKIException("Error modifying profile state. Profile Service not available");
- }
-
- IProfile profile = null;
- try {
- profile = ps.getProfile(profileId);
- if (profile == null) {
- throw new BadRequestException("Cannot provide enrollment template for profile `" + profileId +
- "`. Profile not found");
- }
- } catch (EBaseException e) {
- CMS.debug("getEnrollmentTemplate(): error obtaining profile `" + profileId + "`: " + e);
- e.printStackTrace();
- throw new PKIException("Error generating enrollment template. Cannot obtain profile.");
- }
-
- if (! profile.isVisible()) {
- CMS.debug("getEnrollmentTemplate(): attempt to get enrollment template for non-visible profile");
- throw new BadRequestException("Cannot provide enrollment template for profile `" + profileId +
- "`. Profile not marked as visible");
- }
-
- CertEnrollmentRequest request = new CertEnrollmentRequest();
- request.setProfileId(profileId);
- request.setRenewal(Boolean.parseBoolean(profile.isRenewal()));
- request.setRemoteAddr("");
- request.setRemoteHost("");
- request.setSerialNum("");
-
- // populate inputs
- Enumeration<String> inputIds = profile.getProfileInputIds();
- while (inputIds.hasMoreElements()) {
- String id = inputIds.nextElement();
- try {
- ProfileInput input = ProfileService.createProfileInput(profile, id, getLocale(headers));
- for (ProfileAttribute attr : input.getAttributes()) {
- attr.setValue("");
- }
- request.addInput(input);
- } catch (EBaseException e) {
- CMS.debug("getEnrollmentTemplate(): Failed to add input " + id + " to request template: " + e);
- e.printStackTrace();
- throw new PKIException("Failed to add input" + id + "to request template");
- }
- }
-
- return createOKResponse(request);
- }
-
- @Override
- public Response listEnrollmentTemplates(Integer start, Integer size) {
-
- start = start == null ? DEFAULT_START : start;
- size = size == null ? DEFAULT_PAGESIZE : size;
-
- IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID);
-
- if (ps == null) {
- throw new PKIException("Profile subsystem unavailable.");
- }
-
- ProfileDataInfos infos = new ProfileDataInfos();
- boolean visibleOnly = true;
-
- Enumeration<String> e = ps.getProfileIds();
- if (e == null) return createOKResponse(infos);
-
- // store non-null results in a list
- List<ProfileDataInfo> results = new ArrayList<ProfileDataInfo>();
- while (e.hasMoreElements()) {
- try {
- String id = e.nextElement();
- ProfileDataInfo info = ProfileService.createProfileDataInfo(id, visibleOnly, uriInfo, getLocale(headers));
- if (info == null) continue;
- results.add(info);
- } catch (EBaseException ex) {
- continue;
- }
- }
-
- int total = results.size();
- infos.setTotal(total);
-
- // return entries in the requested page
- for (int i = start; i < start + size && i < total; i++) {
- infos.addEntry(results.get(i));
- }
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- infos.addLink(new Link("prev", uri));
- }
-
- if (start + size < total) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- infos.addLink(new Link("next", uri));
- }
-
- return createOKResponse(infos);
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/request/KeyRequestService.java b/base/server/cms/src/com/netscape/cms/servlet/request/KeyRequestService.java
deleted file mode 100644
index e2253b6e8..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/request/KeyRequestService.java
+++ /dev/null
@@ -1,476 +0,0 @@
-// --- 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) 2011 Red Hat, Inc.
-// All rights reserved.
-// --- END COPYRIGHT BLOCK ---
-
-package com.netscape.cms.servlet.request;
-
-import java.lang.reflect.InvocationTargetException;
-import java.math.BigInteger;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.cert.CertificateException;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import netscape.security.x509.X509CertImpl;
-
-import org.mozilla.jss.crypto.KeyGenAlgorithm;
-import org.mozilla.jss.crypto.SymmetricKey;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.ResourceMessage;
-import com.netscape.certsrv.dbs.keydb.KeyId;
-import com.netscape.certsrv.key.KeyArchivalRequest;
-import com.netscape.certsrv.key.KeyRecoveryRequest;
-import com.netscape.certsrv.key.KeyRequestInfo;
-import com.netscape.certsrv.key.KeyRequestInfoCollection;
-import com.netscape.certsrv.key.KeyRequestResource;
-import com.netscape.certsrv.key.KeyRequestResponse;
-import com.netscape.certsrv.key.SymKeyGenerationRequest;
-import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
-import com.netscape.certsrv.kra.IKeyService;
-import com.netscape.certsrv.logging.ILogger;
-import com.netscape.certsrv.request.IRequest;
-import com.netscape.certsrv.request.IRequestQueue;
-import com.netscape.certsrv.request.RequestId;
-import com.netscape.certsrv.request.RequestNotFoundException;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cms.servlet.key.KeyRequestDAO;
-import com.netscape.cmsutil.ldap.LDAPUtil;
-import com.netscape.cmsutil.util.Utils;
-
-/**
- * @author alee
- *
- */
-public class KeyRequestService extends PKIService implements KeyRequestResource {
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpHeaders headers;
-
- @Context
- private Request request;
-
- @Context
- private HttpServletRequest servletRequest;
-
- private static final String LOGGING_SIGNED_AUDIT_SECURITY_DATA_ARCHIVAL_REQUEST =
- "LOGGING_SIGNED_AUDIT_SECURITY_DATA_ARCHIVAL_REQUEST_4";
-
- private static final String LOGGING_SIGNED_AUDIT_SYMKEY_GENERATION_REQUEST =
- "LOGGING_SIGNED_AUDIT_SYMKEY_GENERATION_REQUEST_4";
-
- private static final String LOGGING_SIGNED_AUDIT_SECURITY_DATA_RECOVERY_REQUEST =
- "LOGGING_SIGNED_AUDIT_SECURITY_DATA_RECOVERY_REQUEST_4";
-
- private static final String LOGGING_SIGNED_AUDIT_SECURITY_DATA_RECOVERY_REQUEST_STATE_CHANGE =
- "LOGGING_SIGNED_AUDIT_SECURITY_DATA_RECOVERY_REQUEST_STATE_CHANGE_4";
-
- public static final int DEFAULT_START = 0;
- public static final int DEFAULT_PAGESIZE = 20;
- public static final int DEFAULT_MAXRESULTS = 100;
- public static final int DEFAULT_MAXTIME = 10;
-
- private IKeyRecoveryAuthority kra;
- private IRequestQueue queue;
- private IKeyService service;
-
- public static final Map<String, KeyGenAlgorithm> KEYGEN_ALGORITHMS;
-
- static {
- KEYGEN_ALGORITHMS = new HashMap<String, KeyGenAlgorithm>();
- KEYGEN_ALGORITHMS.put(KeyRequestResource.DES_ALGORITHM, KeyGenAlgorithm.DES);
- KEYGEN_ALGORITHMS.put(KeyRequestResource.DESEDE_ALGORITHM, KeyGenAlgorithm.DESede);
- KEYGEN_ALGORITHMS.put(KeyRequestResource.DES3_ALGORITHM, KeyGenAlgorithm.DES3);
- KEYGEN_ALGORITHMS.put(KeyRequestResource.RC2_ALGORITHM, KeyGenAlgorithm.RC2);
- KEYGEN_ALGORITHMS.put(KeyRequestResource.RC4_ALGORITHM, KeyGenAlgorithm.RC4);
- KEYGEN_ALGORITHMS.put(KeyRequestResource.AES_ALGORITHM, KeyGenAlgorithm.AES);
- }
-
- public static final Map<String, SymmetricKey.Type> SYMKEY_TYPES;
- static {
- SYMKEY_TYPES = new HashMap<String, SymmetricKey.Type>();
- SYMKEY_TYPES.put(KeyRequestResource.DES_ALGORITHM, SymmetricKey.DES);
- SYMKEY_TYPES.put(KeyRequestResource.DESEDE_ALGORITHM, SymmetricKey.DES3);
- SYMKEY_TYPES.put(KeyRequestResource.DES3_ALGORITHM, SymmetricKey.DES3);
- SYMKEY_TYPES.put(KeyRequestResource.RC2_ALGORITHM, SymmetricKey.RC2);
- SYMKEY_TYPES.put(KeyRequestResource.RC4_ALGORITHM, SymmetricKey.RC4);
- SYMKEY_TYPES.put(KeyRequestResource.AES_ALGORITHM, SymmetricKey.AES);
- }
-
- public KeyRequestService() {
- kra = ( IKeyRecoveryAuthority ) CMS.getSubsystem( "kra" );
- queue = kra.getRequestQueue();
- service = (IKeyService) kra;
- }
-
- /**
- * Used to retrieve key request info for a specific request
- */
- @Override
- public Response getRequestInfo(RequestId id) {
- if (id == null) {
- CMS.debug("getRequestInfo: is is null");
- throw new BadRequestException("Unable to get Request: invalid ID");
- }
- // auth and authz
- KeyRequestDAO dao = new KeyRequestDAO();
- KeyRequestInfo info;
- try {
- info = dao.getRequest(id, uriInfo);
- } catch (EBaseException e) {
- // log error
- e.printStackTrace();
- throw new PKIException(e.getMessage(), e);
- }
- if (info == null) {
- // request does not exist
- throw new RequestNotFoundException(id);
- }
- return createOKResponse(info);
- }
-
- public Response archiveKey(KeyArchivalRequest data) {
- // auth and authz
- // Catch this before internal server processing has to deal with it
-
- if (data == null || data.getClientKeyId() == null || data.getDataType() == null) {
- throw new BadRequestException("Invalid key archival request.");
- }
-
- if (data.getWrappedPrivateData() != null) {
- if (data.getTransWrappedSessionKey() == null ||
- data.getAlgorithmOID() == null ||
- data.getSymmetricAlgorithmParams() == null) {
- throw new BadRequestException(
- "Invalid key archival request. " +
- "Missing wrapped session key, algoriithmOIS or symmetric key parameters");
- }
- } else if (data.getPKIArchiveOptions() == null) {
- throw new BadRequestException(
- "Invalid key archival request. No data to archive");
- }
-
- if (data.getDataType().equals(KeyRequestResource.SYMMETRIC_KEY_TYPE)) {
- if ((data.getKeyAlgorithm() == null) ||
- (! SYMKEY_TYPES.containsKey(data.getKeyAlgorithm()))) {
- throw new BadRequestException("Invalid key archival request. Bad algorithm.");
- }
- }
-
- KeyRequestDAO dao = new KeyRequestDAO();
- KeyRequestResponse response;
- try {
- response = dao.submitRequest(data, uriInfo);
- auditArchivalRequestMade(response.getRequestInfo().getRequestId(), ILogger.SUCCESS, data.getClientKeyId());
-
- return createCreatedResponse(response, new URI(response.getRequestInfo().getRequestURL()));
-
- } catch (EBaseException | URISyntaxException e) {
- e.printStackTrace();
- auditArchivalRequestMade(null, ILogger.FAILURE, data.getClientKeyId());
- throw new PKIException(e.toString());
- }
- }
-
- public Response recoverKey(KeyRecoveryRequest data) {
- // auth and authz
-
- //Check for entirely illegal data combination here
- //Catch this before the internal server processing has to deal with it
- //If data has been provided, we need at least the wrapped session key,
- //or the command is invalid.
-
- if (data == null) {
- throw new BadRequestException("Invalid request.");
- }
- if (data.getCertificate() == null &&
- data.getTransWrappedSessionKey() == null &&
- data.getSessionWrappedPassphrase() != null) {
- throw new BadRequestException("No wrapped session key.");
- }
- KeyRequestDAO dao = new KeyRequestDAO();
- KeyRequestResponse response;
- try {
- response = (data.getCertificate() != null)?
- requestKeyRecovery(data): dao.submitRequest(data, uriInfo);
- auditRecoveryRequestMade(response.getRequestInfo().getRequestId(),
- ILogger.SUCCESS, data.getKeyId());
-
- return createCreatedResponse(response, new URI(response.getRequestInfo().getRequestURL()));
-
- } catch (EBaseException | URISyntaxException e) {
- e.printStackTrace();
- auditRecoveryRequestMade(null, ILogger.FAILURE, data.getKeyId());
- throw new PKIException(e.toString());
- }
- }
-
- private KeyRequestResponse requestKeyRecovery(KeyRecoveryRequest data) {
- KeyRequestResponse response = null;
- if (data == null) {
- throw new BadRequestException("Invalid request.");
- }
- String keyId = data.getKeyId().toString();
- String b64Certificate = data.getCertificate();
- byte[] certData = Utils.base64decode(b64Certificate);
- String agentID = servletRequest.getUserPrincipal().getName();
- String requestId = null;
- try {
- requestId = service.initAsyncKeyRecovery(new BigInteger(keyId), new X509CertImpl(certData), agentID);
- } catch (EBaseException | CertificateException e) {
- e.printStackTrace();
- throw new PKIException(e.toString());
- }
- IRequest request = null;
- try {
- request = queue.findRequest(new RequestId(requestId));
- } catch (EBaseException e) {
- }
- KeyRequestDAO dao = new KeyRequestDAO();
- response = dao.createCMSRequestResponse(request, uriInfo);
-
- return response;
- }
-
- @Override
- public Response approveRequest(RequestId id) {
- if (id == null) {
- throw new BadRequestException("Invalid request id.");
- }
- // auth and authz
- KeyRequestDAO dao = new KeyRequestDAO();
- try {
- IRequest request = queue.findRequest(id);
- String type = request.getRequestType();
- if (IRequest.KEYRECOVERY_REQUEST.equals(type)) {
- service.addAgentAsyncKeyRecovery(id.toString(), servletRequest.getUserPrincipal().getName());
- auditRecoveryRequestChange(id, ILogger.SUCCESS, "approve");
- } else if (IRequest.SECURITY_DATA_RECOVERY_REQUEST.equals(type)) {
- dao.approveRequest(id);
- auditRecoveryRequestChange(id, ILogger.SUCCESS, "approve");
- }
- } catch (EBaseException e) {
- e.printStackTrace();
- auditRecoveryRequestChange(id, ILogger.FAILURE, "approve");
- throw new PKIException(e.toString());
- }
-
- return createNoContentResponse();
- }
-
- @Override
- public Response rejectRequest(RequestId id) {
- if (id == null) {
- throw new BadRequestException("Invalid request id.");
- }
- // auth and authz
- KeyRequestDAO dao = new KeyRequestDAO();
- try {
- dao.rejectRequest(id);
- auditRecoveryRequestChange(id, ILogger.SUCCESS, "reject");
- } catch (EBaseException e) {
- e.printStackTrace();
- auditRecoveryRequestChange(id, ILogger.FAILURE, "reject");
- throw new PKIException(e.toString());
- }
-
- return createNoContentResponse();
- }
-
- @Override
- public Response cancelRequest(RequestId id) {
- if (id == null) {
- throw new BadRequestException("Invalid request id.");
- }
- // auth and authz
- KeyRequestDAO dao = new KeyRequestDAO();
- try {
- dao.cancelRequest(id);
- auditRecoveryRequestChange(id, ILogger.SUCCESS, "cancel");
- } catch (EBaseException e) {
- e.printStackTrace();
- auditRecoveryRequestChange(id, ILogger.FAILURE, "cancel");
- throw new PKIException(e.toString());
- }
-
- return createNoContentResponse();
- }
-
- /**
- * Used to generate list of key requests based on the search parameters
- */
- @Override
- public Response listRequests(String requestState, String requestType, String clientKeyID,
- RequestId start, Integer pageSize, Integer maxResults, Integer maxTime) {
- // auth and authz
-
- // get ldap filter
- String filter = createSearchFilter(requestState, requestType, clientKeyID);
- CMS.debug("listRequests: filter is " + filter);
-
- start = start == null ? new RequestId(KeyRequestService.DEFAULT_START) : start;
- pageSize = pageSize == null ? DEFAULT_PAGESIZE : pageSize;
- maxResults = maxResults == null ? DEFAULT_MAXRESULTS : maxResults;
- maxTime = maxTime == null ? DEFAULT_MAXTIME : maxTime;
-
- KeyRequestDAO reqDAO = new KeyRequestDAO();
- KeyRequestInfoCollection requests;
- try {
- requests = reqDAO.listRequests(filter, start, pageSize, maxResults, maxTime, uriInfo);
- } catch (EBaseException e) {
- CMS.debug("listRequests: error in obtaining request results" + e);
- e.printStackTrace();
- throw new PKIException(e.toString());
- }
- return createOKResponse(requests);
- }
-
- private String createSearchFilter(String requestState, String requestType, String clientKeyID) {
- String filter = "";
- int matches = 0;
-
- if ((requestState == null) && (requestType == null) && (clientKeyID == null)) {
- filter = "(requeststate=*)";
- return filter;
- }
-
- if (requestState != null) {
- filter += "(requeststate=" + LDAPUtil.escapeFilter(requestState) + ")";
- matches ++;
- }
-
- if (requestType != null) {
- filter += "(requesttype=" + LDAPUtil.escapeFilter(requestType) + ")";
- matches ++;
- }
-
- if (clientKeyID != null) {
- filter += "(clientID=" + LDAPUtil.escapeFilter(clientKeyID) + ")";
- matches ++;
- }
-
- if (matches > 1) {
- filter = "(&" + filter + ")";
- }
-
- return filter;
- }
-
- public void auditRecoveryRequestChange(RequestId requestId, String status, String operation) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SECURITY_DATA_RECOVERY_REQUEST_STATE_CHANGE,
- servletRequest.getUserPrincipal().getName(),
- status,
- requestId.toString(),
- operation);
- auditor.log(msg);
- }
-
- public void auditRecoveryRequestMade(RequestId requestId, String status, KeyId dataId) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SECURITY_DATA_RECOVERY_REQUEST,
- servletRequest.getUserPrincipal().getName(),
- status,
- requestId != null? requestId.toString(): "null",
- dataId.toString());
- auditor.log(msg);
- }
-
- public void auditArchivalRequestMade(RequestId requestId, String status, String clientKeyID) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SECURITY_DATA_ARCHIVAL_REQUEST,
- servletRequest.getUserPrincipal().getName(),
- status,
- requestId != null? requestId.toString(): "null",
- clientKeyID);
- auditor.log(msg);
- }
-
- public void auditSymKeyGenRequestMade(RequestId requestId, String status, String clientKeyID) {
- String msg = CMS.getLogMessage(
- LOGGING_SIGNED_AUDIT_SYMKEY_GENERATION_REQUEST,
- servletRequest.getUserPrincipal().getName(),
- status,
- requestId != null ? requestId.toString() : "null",
- clientKeyID);
- auditor.log(msg);
- }
-
- @Override
- public Response createRequest(MultivaluedMap<String, String> form) {
- ResourceMessage data = new ResourceMessage(form);
- return createRequest(data);
- }
-
- @Override
- public Response createRequest(ResourceMessage data) {
- Object request = null;
- try {
- Class<?> requestClazz = Class.forName(data.getClassName());
- request = requestClazz.getDeclaredConstructor(ResourceMessage.class).newInstance(data);
- } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
- | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- throw new BadRequestException("Invalid request class." + e);
- }
-
- if (request instanceof KeyArchivalRequest) {
- return archiveKey(new KeyArchivalRequest(data));
- } else if (request instanceof KeyRecoveryRequest) {
- return recoverKey(new KeyRecoveryRequest(data));
- } else if (request instanceof SymKeyGenerationRequest) {
- return generateSymKey(new SymKeyGenerationRequest(data));
- } else {
- throw new BadRequestException("Invalid request class.");
- }
- }
-
- public Response generateSymKey(SymKeyGenerationRequest data) {
- if (data == null) {
- throw new BadRequestException("Invalid key generation request.");
- }
-
- KeyRequestDAO dao = new KeyRequestDAO();
- KeyRequestResponse response;
- try {
- response = dao.submitRequest(data, uriInfo);
- auditSymKeyGenRequestMade(response.getRequestInfo().getRequestId(), ILogger.SUCCESS,
- data.getClientKeyId());
-
- return createCreatedResponse(response, new URI(response.getRequestInfo().getRequestURL()));
-
- } catch (EBaseException | URISyntaxException e) {
- e.printStackTrace();
- auditArchivalRequestMade(null, ILogger.FAILURE, data.getClientKeyId());
- throw new PKIException(e.toString());
- }
- }
-}
diff --git a/base/server/cms/src/com/netscape/cms/servlet/tks/TPSConnectorService.java b/base/server/cms/src/com/netscape/cms/servlet/tks/TPSConnectorService.java
deleted file mode 100644
index c11f1239f..000000000
--- a/base/server/cms/src/com/netscape/cms/servlet/tks/TPSConnectorService.java
+++ /dev/null
@@ -1,494 +0,0 @@
-package com.netscape.cms.servlet.tks;
-
-import java.io.IOException;
-import java.net.URI;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.TreeSet;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.commons.lang.StringUtils;
-import org.jboss.resteasy.plugins.providers.atom.Link;
-import org.mozilla.jss.CryptoManager.NotInitializedException;
-import org.mozilla.jss.crypto.InvalidKeyFormatException;
-import org.mozilla.jss.crypto.TokenException;
-
-import com.netscape.certsrv.apps.CMS;
-import com.netscape.certsrv.base.BadRequestException;
-import com.netscape.certsrv.base.EBaseException;
-import com.netscape.certsrv.base.IConfigStore;
-import com.netscape.certsrv.base.PKIException;
-import com.netscape.certsrv.base.ResourceNotFoundException;
-import com.netscape.certsrv.base.UnauthorizedException;
-import com.netscape.certsrv.key.KeyData;
-import com.netscape.certsrv.system.TPSConnectorCollection;
-import com.netscape.certsrv.system.TPSConnectorData;
-import com.netscape.certsrv.system.TPSConnectorResource;
-import com.netscape.certsrv.tps.cert.TPSCertResource;
-import com.netscape.certsrv.usrgrp.IUGSubsystem;
-import com.netscape.certsrv.usrgrp.IUser;
-import com.netscape.cms.realm.PKIPrincipal;
-import com.netscape.cms.servlet.base.PKIService;
-import com.netscape.cmsutil.crypto.CryptoUtil;
-import com.netscape.cmsutil.util.Utils;
-
-public class TPSConnectorService extends PKIService implements TPSConnectorResource {
-
- private static final String TPS_LIST = "tps.list";
-
- IConfigStore cs = CMS.getConfigStore();
-
- @Context
- private UriInfo uriInfo;
-
- @Context
- private HttpServletRequest servletRequest;
-
- public final static int DEFAULT_SIZE = 20;
-
- public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG);
-
- @Override
- public Response findConnectors(Integer start, Integer size) {
- try {
- String tpsList = cs.getString(TPS_LIST, "");
- Iterator<String> entries = Arrays.asList(StringUtils.split(tpsList,",")).iterator();
-
- TPSConnectorCollection response = new TPSConnectorCollection();
- int i = 0;
-
- // skip to the start of the page
- for ( ; i<start && entries.hasNext(); i++) entries.next();
-
- // return entries up to the page size
- for ( ; i<start+size && entries.hasNext(); i++) {
- response.addEntry(createTPSConnectorData(entries.next()));
- }
-
- // count the total entries
- for ( ; entries.hasNext(); i++) entries.next();
- response.setTotal(i);
-
- if (start > 0) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build();
- response.addLink(new Link("prev", uri));
- }
-
- if (start+size < i) {
- URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build();
- response.addLink(new Link("next", uri));
- }
-
- return createOKResponse(response);
-
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Unable to get TPS connection data: " + e);
- }
- }
-
- private TPSConnectorData createTPSConnectorData(String tpsID) throws EBaseException {
- TPSConnectorData data = new TPSConnectorData();
- data.setID(tpsID);
- data.setHost(cs.getString("tps." + tpsID + ".host", ""));
- data.setPort(cs.getString("tps." + tpsID + ".port", ""));
- data.setUserID(cs.getString("tps." + tpsID + ".userid", ""));
- data.setNickname(cs.getString("tps." + tpsID + ".nickname", ""));
- URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class).path("{id}").build(tpsID);
- data.setLink(new Link("self", uri));
- return data;
- }
-
- @Override
- public Response getConnector(String id) {
- return createOKResponse(getConnectorData(id));
- }
-
- public TPSConnectorData getConnectorData(String id) {
-
- if (id == null) throw new BadRequestException("TPS connector ID is null.");
-
- try {
- if (!connectorExists(id))
- throw new ResourceNotFoundException("Connector " + id + " not found.");
-
- return createTPSConnectorData(id);
-
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Unable to get TPS connection data" + e);
- }
- }
-
- @Override
- public Response getConnector(String host, String port) {
-
- if (host == null) throw new BadRequestException("TPS connector host is null.");
- if (port == null) throw new BadRequestException("TPS connector port is null.");
-
- try {
- String id = getConnectorID(host, port);
- if (id == null)
- throw new ResourceNotFoundException(
- "Connector not found for " + host + ":" + port);
-
- return createOKResponse(createTPSConnectorData(id));
-
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Unable to get TPS connection data" + e);
- }
- }
-
- @Override
- public Response createConnector(String tpsHost, String tpsPort) {
-
- if (tpsHost == null) throw new BadRequestException("TPS connector host is null.");
- if (tpsPort == null) throw new BadRequestException("TPS connector port is null.");
-
- try {
- String id = getConnectorID(tpsHost, tpsPort);
- if (id != null) {
- URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class)
- .path("{id}").build(id);
- throw new BadRequestException("TPS connection already exists at " + uri.toString());
- }
- String newID = findNextConnectorID();
-
- TPSConnectorData newData = new TPSConnectorData();
- newData.setID(newID);
- newData.setHost(tpsHost);
- newData.setPort(tpsPort);
- newData.setUserID("TPS-" + tpsHost + "-" + tpsPort);
- URI uri = uriInfo.getBaseUriBuilder().path(TPSCertResource.class).path("{id}").build(newID);
- newData.setLink(new Link("self", uri));
- saveClientData(newData);
-
- addToConnectorList(newID);
- cs.commit(true);
-
- return createCreatedResponse(newData, newData.getLink().getHref());
-
- } catch (EBaseException e) {
- CMS.debug("Unable to create new TPS Connector: " + e);
- e.printStackTrace();
- throw new PKIException("Unable to create new TPS connector: " + e);
- }
- }
-
- @Override
- public Response modifyConnector(String id, TPSConnectorData data) {
- try {
- if (id == null) {
- throw new BadRequestException("Invalid connector ID");
- }
-
- if (data == null) {
- throw new BadRequestException("Invalid connector data");
- }
-
- if (!connectorExists(id)) {
- throw new ResourceNotFoundException("TPS connection does not exist");
- }
-
- // Note: we are deliberately NOT allowing the userid to be modified by the
- // admin here, because this is what maps to a user cert to retrieve the shared
- // secret
- if ((data.getUserID() != null) || (data.getNickname() != null)) {
- throw new UnauthorizedException("Cannot change userid or nickname using this interface");
- }
- TPSConnectorData curData = getConnectorData(id);
- curData.setHost(data.getHost());
- curData.setPort(data.getPort());
-
- saveClientData(curData);
- cs.commit(true);
-
- return createOKResponse(curData);
-
- } catch (EBaseException e) {
- CMS.debug("Unable to modify TPS Connector: " + e);
- e.printStackTrace();
- throw new PKIException("Unable to modify TPS Connector: " + e);
- }
- }
-
- private void saveClientData(TPSConnectorData newData) throws EBaseException {
- String id = newData.getID();
- if (StringUtils.isEmpty(id)) {
- CMS.debug("saveClientData: Attempt to save tps connection with null or empty id");
- return;
- }
- String prefix = "tps." + id + ".";
-
- if (newData.getHost() != null)
- cs.putString(prefix + "host", newData.getHost());
- if (newData.getPort() != null)
- cs.putString(prefix + "port", newData.getPort());
- if (newData.getUserID() != null)
- cs.putString(prefix + "userid", newData.getUserID());
- if (newData.getNickname() != null)
- cs.putString(prefix + "nickname", newData.getNickname());
- }
-
- @Override
- public Response deleteConnector(String id) {
- try {
- if (StringUtils.isEmpty(id))
- throw new BadRequestException("Attempt to delete TPS connection with null or empty id");
-
- if (!connectorExists(id)) return createNoContentResponse();
-
- deleteSharedSecret(id);
- cs.removeSubStore("tps." + id);
- removeFromConnectorList(id);
- cs.commit(true);
-
- return createNoContentResponse();
-
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Failed to delete TPS connection" + e);
- }
- }
-
- @Override
- public Response deleteConnector(String host, String port) {
-
- if (host == null) throw new BadRequestException("TPS connector host is null.");
- if (port == null) throw new BadRequestException("TPS connector port is null.");
-
- String id;
- try {
- id = getConnectorID(host, port);
- deleteConnector(id);
- } catch (EBaseException e) {
- e.printStackTrace();
- throw new PKIException("Failed to delete TPS connector: " + e);
- }
-
- return createNoContentResponse();
- }
-
- @Override
- public Response createSharedSecret(String id) {
-
- if (id == null) throw new BadRequestException("TPS connector ID is null.");
-
- try {
- if (!connectorExists(id)) {
- throw new ResourceNotFoundException("TPS connection does not exist");
- }
-
- // get and validate user
- String userid = validateUser(id);
-
- // get user cert
- IUser user = userGroupManager.getUser(userid);
- X509Certificate[] certs = user.getX509Certificates();
-
- String nickname = userid + " sharedSecret";
- if (CryptoUtil.sharedSecretExists(nickname)) {
- throw new BadRequestException("Shared secret already exists");
- }
-
- CryptoUtil.createSharedSecret(nickname);
-
- cs.putString("tps." + id + ".nickname", nickname);
- cs.commit(true);
-
- byte[] wrappedKey = CryptoUtil.exportSharedSecret(nickname, certs[0]);
- KeyData keyData = new KeyData();
- keyData.setWrappedPrivateData(Utils.base64encode(wrappedKey));
-
- return createOKResponse(keyData);
-
- } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException
- | InvalidAlgorithmParameterException | EBaseException
- | NotInitializedException | TokenException | IOException | InvalidKeyFormatException e) {
- e.printStackTrace();
- CMS.debug("Error in generating and exporting shared secret: " + e);
- throw new PKIException("Error in generating and exporting shared secret: " + e);
- }
- }
-
- private String validateUser(String id) throws EBaseException {
- String userid = cs.getString("tps." + id + ".userid", "");
- if (userid.isEmpty()) {
- throw new PKIException("Bad TPS connection configuration: userid not defined");
- }
-
- PKIPrincipal principal = (PKIPrincipal) servletRequest.getUserPrincipal();
- if (principal == null) {
- throw new UnauthorizedException("User credentials not provided");
- }
-
- String uid = principal.getName();
- if (!uid.equals(userid)) {
- throw new UnauthorizedException("TPS Connection belongs to another user");
- }
- return userid;
- }
-
- @Override
- public Response replaceSharedSecret(String id) {
-
- if (id == null) throw new BadRequestException("TPS connector ID is null.");
-
- try {
- if (!connectorExists(id)) {
- throw new ResourceNotFoundException("TPS connection does not exist");
- }
-
- // get and validate user
- String userid = validateUser(id);
-
- String nickname = userid + " sharedSecret";
- if (!CryptoUtil.sharedSecretExists(nickname)) {
- throw new BadRequestException("Cannot replace. Shared secret does not exist");
- }
-
- // get user cert
- IUser user = userGroupManager.getUser(userid);
- X509Certificate[] certs = user.getX509Certificates();
-
- CryptoUtil.deleteSharedSecret(nickname);
- CryptoUtil.createSharedSecret(nickname);
- byte[] wrappedKey = CryptoUtil.exportSharedSecret(nickname, certs[0]);
- KeyData keyData = new KeyData();
- keyData.setWrappedPrivateData(Utils.base64encode(wrappedKey));
-
- return createOKResponse(keyData);
-
- } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException
- | InvalidAlgorithmParameterException | EBaseException
- | NotInitializedException | TokenException | IOException | InvalidKeyFormatException e) {
- e.printStackTrace();
- CMS.debug("Error in replacing shared secret: " + e);
- throw new PKIException("Error in replacing shared secret: " + e);
- }
- }
-
- @Override
- public Response deleteSharedSecret(String id) {
-
- if (id == null) throw new BadRequestException("TPS connector ID is null.");
-
- try {
- if (!connectorExists(id)) {
- throw new ResourceNotFoundException("TPS connection does not exist");
- }
-
- // get user
- String userid = cs.getString("tps." + id + ".userid", "");
- if (userid.isEmpty()) {
- throw new PKIException("Bad TPS connection configuration: userid not defined");
- }
-
- String nickname = userid + " sharedSecret";
- if (!CryptoUtil.sharedSecretExists(nickname)) {
- return createNoContentResponse();
- }
- CryptoUtil.deleteSharedSecret(nickname);
-
- cs.putString("tps." + id + ".nickname", "");
- cs.commit(true);
-
- return createNoContentResponse();
-
- } catch (InvalidKeyException | IllegalStateException | EBaseException
- | NotInitializedException | TokenException e) {
- e.printStackTrace();
- CMS.debug("Error in deleting shared secret: " + e);
- throw new PKIException("Error in deleting shared secret: " + e);
- }
- }
-
- @Override
- public Response getSharedSecret(String id) {
-
- if (id == null) throw new BadRequestException("TPS connector ID is null.");
-
- try {
- if (!connectorExists(id)) {
- throw new ResourceNotFoundException("TPS connection does not exist");
- }
-
- // get and validate user
- String userid = validateUser(id);
-
- String nickname = userid + " sharedSecret";
- if (!CryptoUtil.sharedSecretExists(nickname)) {
- return createNoContentResponse();
- }
-
- // get user cert
- IUser user = userGroupManager.getUser(userid);
- X509Certificate[] certs = user.getX509Certificates();
-
- byte[] wrappedKey = CryptoUtil.exportSharedSecret(nickname, certs[0]);
- KeyData keyData = new KeyData();
- keyData.setWrappedPrivateData(Utils.base64encode(wrappedKey));
-
- return createOKResponse(keyData);
-
- } catch (InvalidKeyException | IllegalStateException | NoSuchAlgorithmException
- | InvalidAlgorithmParameterException | EBaseException
- | NotInitializedException | TokenException | IOException | InvalidKeyFormatException e) {
- e.printStackTrace();
- CMS.debug("Error in obtaining shared secret: " + e);
- throw new PKIException("Error in obtaining shared secret: " + e);
- }
- }
-
- private boolean connectorExists(String id) throws EBaseException {
- String tpsList = cs.getString(TPS_LIST, "");
- return ArrayUtils.contains(StringUtils.split(tpsList, ","), id);
- }
-
- private String getConnectorID(String host, String port) throws EBaseException {
- String tpsList = cs.getString(TPS_LIST, "");
- for (String tpsID : StringUtils.split(tpsList,",")) {
- TPSConnectorData data = createTPSConnectorData(tpsID);
- if (data.getHost().equals(host) && data.getPort().equals(port))
- return tpsID;
- }
- return null;
- }
-
- private void addToConnectorList(String id) throws EBaseException {
- String tpsList = cs.getString(TPS_LIST, "");
- Collection<String> sorted = new TreeSet<String>();
- sorted.addAll(Arrays.asList(StringUtils.split(tpsList, ",")));
- sorted.add(id);
- cs.putString(TPS_LIST, StringUtils.join(sorted, ","));
- }
-
- private void removeFromConnectorList(String id) throws EBaseException {
- String tpsList = cs.getString(TPS_LIST, "");
- Collection<String> sorted = new TreeSet<String>();
- sorted.addAll(Arrays.asList(StringUtils.split(tpsList, ",")));
- sorted.remove(id);
- cs.putString(TPS_LIST, StringUtils.join(sorted, ","));
- }
-
- private String findNextConnectorID() throws EBaseException {
- String tpsList = cs.getString(TPS_LIST, "");
- Collection<String> sorted = new TreeSet<String>();
- sorted.addAll(Arrays.asList(StringUtils.split(tpsList, ",")));
-
- int index = 0;
- while (sorted.contains(Integer.toString(index))) index++;
- return Integer.toString(index);
- }
-}