From d41848a5881db3d12f65e078b945829f1fe296a5 Mon Sep 17 00:00:00 2001 From: Endi Sukma Dewata Date: Sat, 11 Aug 2012 05:09:02 -0500 Subject: Cleaned up REST server class names. The REST server classes have been renamed for better clarity and consistency. Ticket #259 --- .../ca/CertificateAuthorityApplication.java | 36 +- .../servlet/admin/GroupMemberResourceService.java | 380 --------- .../cms/servlet/admin/GroupMemberService.java | 380 +++++++++ .../cms/servlet/admin/GroupResourceService.java | 335 -------- .../netscape/cms/servlet/admin/GroupService.java | 335 ++++++++ .../cms/servlet/admin/SystemCertService.java | 75 ++ .../admin/SystemCertificateResourceService.java | 75 -- .../cms/servlet/admin/UserCertResourceService.java | 485 ----------- .../cms/servlet/admin/UserCertService.java | 485 +++++++++++ .../cms/servlet/admin/UserResourceService.java | 483 ----------- .../netscape/cms/servlet/admin/UserService.java | 483 +++++++++++ .../cms/servlet/base/CMSResourceService.java | 168 ---- .../com/netscape/cms/servlet/base/PKIService.java | 168 ++++ .../cms/servlet/cert/CertResourceService.java | 541 ------------ .../com/netscape/cms/servlet/cert/CertService.java | 541 ++++++++++++ .../cms/servlet/cert/EnrollmentProcessor.java | 4 +- .../cms/servlet/cert/RenewalProcessor.java | 4 +- .../cms/servlet/cert/RequestProcessor.java | 4 +- .../cms/servlet/csadmin/SystemConfigService.java | 948 +++++++++++++++++++++ .../SystemConfigurationResourceService.java | 948 --------------------- .../cms/servlet/key/KeyResourceService.java | 319 ------- .../com/netscape/cms/servlet/key/KeyService.java | 319 +++++++ .../servlet/profile/ProfileResourceService.java | 203 ----- .../cms/servlet/profile/ProfileService.java | 203 +++++ .../request/CertRequestResourceService.java | 245 ------ .../cms/servlet/request/CertRequestService.java | 245 ++++++ .../servlet/request/KeyRequestResourceService.java | 224 ----- .../cms/servlet/request/KeyRequestService.java | 224 +++++ .../model/AgentEnrollmentRequestDataFactory.java | 174 ---- .../model/CertEnrollmentRequestFactory.java | 51 ++ .../cms/servlet/request/model/CertRequestDAO.java | 2 +- .../request/model/CertReviewResponseFactory.java | 174 ++++ .../model/EnrollmentRequestDataFactory.java | 51 -- .../src/com/netscape/cms/servlet/test/DRMTest.java | 6 +- .../kra/KeyRecoveryAuthorityApplication.java | 32 +- .../src/com/netscape/ocsp/OCSPApplication.java | 24 +- base/tks/src/com/netscape/tks/TKSApplication.java | 24 +- 37 files changed, 4699 insertions(+), 4699 deletions(-) delete mode 100644 base/common/src/com/netscape/cms/servlet/admin/GroupMemberResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/admin/GroupMemberService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/admin/GroupResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/admin/GroupService.java create mode 100644 base/common/src/com/netscape/cms/servlet/admin/SystemCertService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/admin/SystemCertificateResourceService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/admin/UserCertResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/admin/UserCertService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/admin/UserResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/admin/UserService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/base/CMSResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/base/PKIService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/cert/CertResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/cert/CertService.java create mode 100644 base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigurationResourceService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/key/KeyResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/key/KeyService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/profile/ProfileResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/profile/ProfileService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/request/CertRequestResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/request/CertRequestService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/request/KeyRequestResourceService.java create mode 100644 base/common/src/com/netscape/cms/servlet/request/KeyRequestService.java delete mode 100644 base/common/src/com/netscape/cms/servlet/request/model/AgentEnrollmentRequestDataFactory.java create mode 100644 base/common/src/com/netscape/cms/servlet/request/model/CertEnrollmentRequestFactory.java create mode 100644 base/common/src/com/netscape/cms/servlet/request/model/CertReviewResponseFactory.java delete mode 100644 base/common/src/com/netscape/cms/servlet/request/model/EnrollmentRequestDataFactory.java diff --git a/base/ca/src/com/netscape/ca/CertificateAuthorityApplication.java b/base/ca/src/com/netscape/ca/CertificateAuthorityApplication.java index d539bdb44..fe08e299b 100644 --- a/base/ca/src/com/netscape/ca/CertificateAuthorityApplication.java +++ b/base/ca/src/com/netscape/ca/CertificateAuthorityApplication.java @@ -5,16 +5,16 @@ import java.util.Set; import javax.ws.rs.core.Application; -import com.netscape.cms.servlet.admin.GroupMemberResourceService; -import com.netscape.cms.servlet.admin.GroupResourceService; -import com.netscape.cms.servlet.admin.SystemCertificateResourceService; -import com.netscape.cms.servlet.admin.UserCertResourceService; -import com.netscape.cms.servlet.admin.UserResourceService; +import com.netscape.cms.servlet.admin.GroupMemberService; +import com.netscape.cms.servlet.admin.GroupService; +import com.netscape.cms.servlet.admin.SystemCertService; +import com.netscape.cms.servlet.admin.UserCertService; +import com.netscape.cms.servlet.admin.UserService; import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.cert.CertResourceService; -import com.netscape.cms.servlet.csadmin.SystemConfigurationResourceService; -import com.netscape.cms.servlet.profile.ProfileResourceService; -import com.netscape.cms.servlet.request.CertRequestResourceService; +import com.netscape.cms.servlet.cert.CertService; +import com.netscape.cms.servlet.csadmin.SystemConfigService; +import com.netscape.cms.servlet.profile.ProfileService; +import com.netscape.cms.servlet.request.CertRequestService; public class CertificateAuthorityApplication extends Application { private Set singletons = new HashSet(); @@ -22,23 +22,23 @@ public class CertificateAuthorityApplication extends Application { public CertificateAuthorityApplication() { // installer - classes.add(SystemConfigurationResourceService.class); + classes.add(SystemConfigService.class); // certs and requests - classes.add(CertResourceService.class); - classes.add(CertRequestResourceService.class); + classes.add(CertService.class); + classes.add(CertRequestService.class); // profile management - classes.add(ProfileResourceService.class); + classes.add(ProfileService.class); // user and group management - classes.add(GroupMemberResourceService.class); - classes.add(GroupResourceService.class); - classes.add(UserCertResourceService.class); - classes.add(UserResourceService.class); + classes.add(GroupMemberService.class); + classes.add(GroupService.class); + classes.add(UserCertService.class); + classes.add(UserService.class); // system certs - classes.add(SystemCertificateResourceService.class); + classes.add(SystemCertService.class); // exception mapper classes.add(CMSException.Mapper.class); diff --git a/base/common/src/com/netscape/cms/servlet/admin/GroupMemberResourceService.java b/base/common/src/com/netscape/cms/servlet/admin/GroupMemberResourceService.java deleted file mode 100644 index c192815aa..000000000 --- a/base/common/src/com/netscape/cms/servlet/admin/GroupMemberResourceService.java +++ /dev/null @@ -1,380 +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.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.jboss.resteasy.plugins.providers.atom.Link; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.base.EBaseException; -import com.netscape.certsrv.base.IConfigStore; -import com.netscape.certsrv.base.SessionContext; -import com.netscape.certsrv.common.OpDef; -import com.netscape.certsrv.common.ScopeDef; -import com.netscape.certsrv.group.GroupMemberCollection; -import com.netscape.certsrv.group.GroupMemberData; -import com.netscape.certsrv.group.GroupMemberResource; -import com.netscape.certsrv.logging.AuditFormat; -import com.netscape.certsrv.logging.IAuditor; -import com.netscape.certsrv.logging.ILogger; -import com.netscape.certsrv.user.UserResource; -import com.netscape.certsrv.usrgrp.IGroup; -import com.netscape.certsrv.usrgrp.IUGSubsystem; -import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; - -/** - * @author Endi S. Dewata - */ -public class GroupMemberResourceService extends CMSResourceService implements GroupMemberResource { - - public final static int DEFAULT_SIZE = 20; - - public final static String MULTI_ROLE_ENABLE = "multiroles.enable"; - public final static String MULTI_ROLE_ENFORCE_GROUP_LIST = "multiroles.false.groupEnforceList"; - - public static String[] multiRoleGroupEnforceList; - - public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG); - - public GroupMemberData createGroupMemberData(String memberID) throws Exception { - - GroupMemberData groupMemberData = new GroupMemberData(); - - groupMemberData.setID(memberID); - - String userID = URLEncoder.encode(memberID, "UTF-8"); - URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}").build(userID); - groupMemberData.setLink(new Link("self", uri)); - - return groupMemberData; - } - - @Override - public GroupMemberCollection findGroupMembers(String groupID, Integer start, Integer size) { - try { - start = start == null ? 0 : start; - size = size == null ? DEFAULT_SIZE : size; - - if (groupID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IGroup group = userGroupManager.getGroupFromName(groupID); - if (group == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); - } - - GroupMemberCollection response = new GroupMemberCollection(); - - Enumeration members = group.getMemberNames(); - - int i = 0; - - // skip to the start of the page - for ( ; i 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 response; - - } catch (CMSException e) { - throw e; - - } catch (Exception e) { - CMS.debug(e); - throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); - } - } - - @Override - public Response addGroupMember(String groupID, String memberID) { - GroupMemberData groupMemberData = new GroupMemberData(); - groupMemberData.setID(memberID); - return addGroupMember(groupID, groupMemberData); - } - - public Response addGroupMember(String groupID, GroupMemberData groupMemberData) { - - try { - if (groupID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IGroup group = userGroupManager.getGroupFromName(groupID); - if (group == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); - } - - String memberID = groupMemberData.getID(); - boolean multiRole = true; - - try { - IConfigStore config = CMS.getConfigStore(); - multiRole = config.getBoolean(MULTI_ROLE_ENABLE); - } catch (Exception e) { - // ignore - } - - if (multiRole) { - // a user can be a member of multiple groups - userGroupManager.addUserToGroup(group, memberID); - - } else { - // a user can be a member of at most one group in the enforce list - if (isGroupInMultiRoleEnforceList(groupID)) { - // make sure the user is not already a member in another group in the list - if (!isDuplicate(groupID, memberID)) { - userGroupManager.addUserToGroup(group, memberID); - } else { - throw new EBaseException(CMS.getUserMessage("CMS_BASE_DUPLICATE_ROLES", memberID)); - } - - } else { - // the user can be a member of multiple groups outside the list - userGroupManager.addUserToGroup(group, memberID); - } - } - - // for audit log - SessionContext sContext = SessionContext.getContext(); - String adminId = (String) sContext.get(SessionContext.USER_ID); - - logger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP, - AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT, - new Object[] { adminId, memberID, groupID }); - - auditAddGroupMember(groupID, groupMemberData, ILogger.SUCCESS); - - // read the data back - groupMemberData = getGroupMember(groupID, memberID); - - return Response - .created(groupMemberData.getLink().getHref()) - .entity(groupMemberData) - .type(MediaType.APPLICATION_XML) - .build(); - - } catch (CMSException e) { - auditAddGroupMember(groupID, groupMemberData, ILogger.FAILURE); - throw e; - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - auditAddGroupMember(groupID, groupMemberData, ILogger.FAILURE); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); - } - } - - public boolean isGroupInMultiRoleEnforceList(String groupID) { - - if (groupID == null || groupID.equals("")) { - return true; - } - - String groupList = null; - if (multiRoleGroupEnforceList == null) { - try { - IConfigStore config = CMS.getConfigStore(); - groupList = config.getString(MULTI_ROLE_ENFORCE_GROUP_LIST); - } catch (Exception e) { - // ignore - } - - if (groupList != null && !groupList.equals("")) { - multiRoleGroupEnforceList = groupList.split(","); - for (int j = 0; j < multiRoleGroupEnforceList.length; j++) { - multiRoleGroupEnforceList[j] = multiRoleGroupEnforceList[j].trim(); - } - } - } - - if (multiRoleGroupEnforceList == null) - return true; - - for (int i = 0; i < multiRoleGroupEnforceList.length; i++) { - if (groupID.equals(multiRoleGroupEnforceList[i])) { - return true; - } - } - - return false; - } - - public boolean isDuplicate(String groupID, String memberID) { - - // Let's not mess with users that are already a member of this group - try { - boolean isMember = userGroupManager.isMemberOf(memberID, groupID); - if (isMember == true) return false; - - } catch (Exception e) { - // ignore - } - - try { - Enumeration groups = userGroupManager.listGroups("*"); - while (groups.hasMoreElements()) { - IGroup group = groups.nextElement(); - String name = group.getName(); - - Enumeration g = userGroupManager.findGroups(name); - IGroup g1 = g.nextElement(); - - if (!name.equals(groupID)) { - if (isGroupInMultiRoleEnforceList(name)) { - Enumeration members = g1.getMemberNames(); - while (members.hasMoreElements()) { - String m1 = members.nextElement(); - if (m1.equals(memberID)) - return true; - } - } - } - } - } catch (Exception e) { - // ignore - } - - return false; - } - - @Override - public GroupMemberData getGroupMember(String groupID, String memberID) { - - try { - if (groupID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IGroup group = userGroupManager.getGroupFromName(groupID); - if (group == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); - } - - Enumeration e = group.getMemberNames(); - while (e.hasMoreElements()) { - String memberName = e.nextElement(); - if (!memberName.equals(memberID)) continue; - - GroupMemberData groupMemberData = createGroupMemberData(memberID); - return groupMemberData; - } - - throw new CMSException("Group member not found"); - - } catch (CMSException e) { - throw e; - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - throw new CMSException(e.getMessage()); - } - } - - @Override - public void removeGroupMember(String groupID, String memberID) { - GroupMemberData groupMemberData = new GroupMemberData(); - groupMemberData.setID(memberID); - removeGroupMember(groupID, groupMemberData); - } - - public void removeGroupMember(String groupID, GroupMemberData groupMemberData) { - try { - if (groupID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IGroup group = userGroupManager.getGroupFromName(groupID); - if (group == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); - } - - String member = groupMemberData.getID(); - userGroupManager.removeUserFromGroup(group, member); - - // for audit log - SessionContext sContext = SessionContext.getContext(); - String adminId = (String) sContext.get(SessionContext.USER_ID); - - logger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP, - AuditFormat.LEVEL, AuditFormat.REMOVEUSERGROUPFORMAT, - new Object[] { adminId, member, groupID }); - - auditDeleteGroupMember(groupID, groupMemberData, ILogger.SUCCESS); - - } catch (CMSException e) { - auditDeleteGroupMember(groupID, groupMemberData, ILogger.FAILURE); - throw e; - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - auditDeleteGroupMember(groupID, groupMemberData, ILogger.FAILURE); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); - } - } - - public void log(int level, String message) { - log(ILogger.S_USRGRP, level, message); - } - - public void auditAddGroupMember(String groupID, GroupMemberData groupMemberData, String status) { - audit(OpDef.OP_ADD, groupID, getParams(groupMemberData), status); - } - - public void auditDeleteGroupMember(String groupID, GroupMemberData groupMemberData, String status) { - audit(OpDef.OP_DELETE, groupID, getParams(groupMemberData), status); - } - - public void audit(String type, String id, Map params, String status) { - audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_GROUP_MEMBERS, type, id, params, status); - } -} diff --git a/base/common/src/com/netscape/cms/servlet/admin/GroupMemberService.java b/base/common/src/com/netscape/cms/servlet/admin/GroupMemberService.java new file mode 100644 index 000000000..2a7419d33 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/admin/GroupMemberService.java @@ -0,0 +1,380 @@ +// --- 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.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.EBaseException; +import com.netscape.certsrv.base.IConfigStore; +import com.netscape.certsrv.base.SessionContext; +import com.netscape.certsrv.common.OpDef; +import com.netscape.certsrv.common.ScopeDef; +import com.netscape.certsrv.group.GroupMemberCollection; +import com.netscape.certsrv.group.GroupMemberData; +import com.netscape.certsrv.group.GroupMemberResource; +import com.netscape.certsrv.logging.AuditFormat; +import com.netscape.certsrv.logging.IAuditor; +import com.netscape.certsrv.logging.ILogger; +import com.netscape.certsrv.user.UserResource; +import com.netscape.certsrv.usrgrp.IGroup; +import com.netscape.certsrv.usrgrp.IUGSubsystem; +import com.netscape.cms.servlet.base.CMSException; +import com.netscape.cms.servlet.base.PKIService; + +/** + * @author Endi S. Dewata + */ +public class GroupMemberService extends PKIService implements GroupMemberResource { + + public final static int DEFAULT_SIZE = 20; + + public final static String MULTI_ROLE_ENABLE = "multiroles.enable"; + public final static String MULTI_ROLE_ENFORCE_GROUP_LIST = "multiroles.false.groupEnforceList"; + + public static String[] multiRoleGroupEnforceList; + + public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG); + + public GroupMemberData createGroupMemberData(String memberID) throws Exception { + + GroupMemberData groupMemberData = new GroupMemberData(); + + groupMemberData.setID(memberID); + + String userID = URLEncoder.encode(memberID, "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}").build(userID); + groupMemberData.setLink(new Link("self", uri)); + + return groupMemberData; + } + + @Override + public GroupMemberCollection findGroupMembers(String groupID, Integer start, Integer size) { + try { + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + + if (groupID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IGroup group = userGroupManager.getGroupFromName(groupID); + if (group == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); + } + + GroupMemberCollection response = new GroupMemberCollection(); + + Enumeration members = group.getMemberNames(); + + int i = 0; + + // skip to the start of the page + for ( ; i 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 response; + + } catch (CMSException e) { + throw e; + + } catch (Exception e) { + CMS.debug(e); + throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); + } + } + + @Override + public Response addGroupMember(String groupID, String memberID) { + GroupMemberData groupMemberData = new GroupMemberData(); + groupMemberData.setID(memberID); + return addGroupMember(groupID, groupMemberData); + } + + public Response addGroupMember(String groupID, GroupMemberData groupMemberData) { + + try { + if (groupID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IGroup group = userGroupManager.getGroupFromName(groupID); + if (group == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); + } + + String memberID = groupMemberData.getID(); + boolean multiRole = true; + + try { + IConfigStore config = CMS.getConfigStore(); + multiRole = config.getBoolean(MULTI_ROLE_ENABLE); + } catch (Exception e) { + // ignore + } + + if (multiRole) { + // a user can be a member of multiple groups + userGroupManager.addUserToGroup(group, memberID); + + } else { + // a user can be a member of at most one group in the enforce list + if (isGroupInMultiRoleEnforceList(groupID)) { + // make sure the user is not already a member in another group in the list + if (!isDuplicate(groupID, memberID)) { + userGroupManager.addUserToGroup(group, memberID); + } else { + throw new EBaseException(CMS.getUserMessage("CMS_BASE_DUPLICATE_ROLES", memberID)); + } + + } else { + // the user can be a member of multiple groups outside the list + userGroupManager.addUserToGroup(group, memberID); + } + } + + // for audit log + SessionContext sContext = SessionContext.getContext(); + String adminId = (String) sContext.get(SessionContext.USER_ID); + + logger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP, + AuditFormat.LEVEL, AuditFormat.ADDUSERGROUPFORMAT, + new Object[] { adminId, memberID, groupID }); + + auditAddGroupMember(groupID, groupMemberData, ILogger.SUCCESS); + + // read the data back + groupMemberData = getGroupMember(groupID, memberID); + + return Response + .created(groupMemberData.getLink().getHref()) + .entity(groupMemberData) + .type(MediaType.APPLICATION_XML) + .build(); + + } catch (CMSException e) { + auditAddGroupMember(groupID, groupMemberData, ILogger.FAILURE); + throw e; + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + auditAddGroupMember(groupID, groupMemberData, ILogger.FAILURE); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); + } + } + + public boolean isGroupInMultiRoleEnforceList(String groupID) { + + if (groupID == null || groupID.equals("")) { + return true; + } + + String groupList = null; + if (multiRoleGroupEnforceList == null) { + try { + IConfigStore config = CMS.getConfigStore(); + groupList = config.getString(MULTI_ROLE_ENFORCE_GROUP_LIST); + } catch (Exception e) { + // ignore + } + + if (groupList != null && !groupList.equals("")) { + multiRoleGroupEnforceList = groupList.split(","); + for (int j = 0; j < multiRoleGroupEnforceList.length; j++) { + multiRoleGroupEnforceList[j] = multiRoleGroupEnforceList[j].trim(); + } + } + } + + if (multiRoleGroupEnforceList == null) + return true; + + for (int i = 0; i < multiRoleGroupEnforceList.length; i++) { + if (groupID.equals(multiRoleGroupEnforceList[i])) { + return true; + } + } + + return false; + } + + public boolean isDuplicate(String groupID, String memberID) { + + // Let's not mess with users that are already a member of this group + try { + boolean isMember = userGroupManager.isMemberOf(memberID, groupID); + if (isMember == true) return false; + + } catch (Exception e) { + // ignore + } + + try { + Enumeration groups = userGroupManager.listGroups("*"); + while (groups.hasMoreElements()) { + IGroup group = groups.nextElement(); + String name = group.getName(); + + Enumeration g = userGroupManager.findGroups(name); + IGroup g1 = g.nextElement(); + + if (!name.equals(groupID)) { + if (isGroupInMultiRoleEnforceList(name)) { + Enumeration members = g1.getMemberNames(); + while (members.hasMoreElements()) { + String m1 = members.nextElement(); + if (m1.equals(memberID)) + return true; + } + } + } + } + } catch (Exception e) { + // ignore + } + + return false; + } + + @Override + public GroupMemberData getGroupMember(String groupID, String memberID) { + + try { + if (groupID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IGroup group = userGroupManager.getGroupFromName(groupID); + if (group == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); + } + + Enumeration e = group.getMemberNames(); + while (e.hasMoreElements()) { + String memberName = e.nextElement(); + if (!memberName.equals(memberID)) continue; + + GroupMemberData groupMemberData = createGroupMemberData(memberID); + return groupMemberData; + } + + throw new CMSException("Group member not found"); + + } catch (CMSException e) { + throw e; + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + throw new CMSException(e.getMessage()); + } + } + + @Override + public void removeGroupMember(String groupID, String memberID) { + GroupMemberData groupMemberData = new GroupMemberData(); + groupMemberData.setID(memberID); + removeGroupMember(groupID, groupMemberData); + } + + public void removeGroupMember(String groupID, GroupMemberData groupMemberData) { + try { + if (groupID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IGroup group = userGroupManager.getGroupFromName(groupID); + if (group == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); + } + + String member = groupMemberData.getID(); + userGroupManager.removeUserFromGroup(group, member); + + // for audit log + SessionContext sContext = SessionContext.getContext(); + String adminId = (String) sContext.get(SessionContext.USER_ID); + + logger.log(ILogger.EV_AUDIT, ILogger.S_USRGRP, + AuditFormat.LEVEL, AuditFormat.REMOVEUSERGROUPFORMAT, + new Object[] { adminId, member, groupID }); + + auditDeleteGroupMember(groupID, groupMemberData, ILogger.SUCCESS); + + } catch (CMSException e) { + auditDeleteGroupMember(groupID, groupMemberData, ILogger.FAILURE); + throw e; + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + auditDeleteGroupMember(groupID, groupMemberData, ILogger.FAILURE); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); + } + } + + public void log(int level, String message) { + log(ILogger.S_USRGRP, level, message); + } + + public void auditAddGroupMember(String groupID, GroupMemberData groupMemberData, String status) { + audit(OpDef.OP_ADD, groupID, getParams(groupMemberData), status); + } + + public void auditDeleteGroupMember(String groupID, GroupMemberData groupMemberData, String status) { + audit(OpDef.OP_DELETE, groupID, getParams(groupMemberData), status); + } + + public void audit(String type, String id, Map params, String status) { + audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_GROUP_MEMBERS, type, id, params, status); + } +} diff --git a/base/common/src/com/netscape/cms/servlet/admin/GroupResourceService.java b/base/common/src/com/netscape/cms/servlet/admin/GroupResourceService.java deleted file mode 100644 index ce665ae3e..000000000 --- a/base/common/src/com/netscape/cms/servlet/admin/GroupResourceService.java +++ /dev/null @@ -1,335 +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.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -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.EBaseException; -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.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.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cmsutil.ldap.LDAPUtil; - -/** - * @author Endi S. Dewata - */ -public class GroupResourceService extends CMSResourceService implements GroupResource { - - 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 id = group.getGroupID(); - if (!StringUtils.isEmpty(id)) groupData.setID(id); - - String description = group.getDescription(); - if (!StringUtils.isEmpty(description)) groupData.setDescription(description); - - String groupID = URLEncoder.encode(groupData.getID(), "UTF-8"); - URI uri = uriInfo.getBaseUriBuilder().path(GroupResource.class).path("{groupID}").build(groupID); - 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 GroupCollection 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 groups = userGroupManager.listGroups(filter); - - GroupCollection response = new GroupCollection(); - - int i = 0; - - // skip to the start of the page - for ( ; i 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 response; - - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); - } - } - - /** - * finds a group - * Request/Response Syntax: - * http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#user-admin - */ - @Override - public GroupData getGroup(String groupID) { - - try { - if (groupID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IGroup group = userGroupManager.getGroupFromName(groupID); - if (group == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); - } - - return createGroupData(group); - - } catch (CMSException e) { - throw e; - - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); - } - } - - /** - * Adds a new group in local scope. - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#group - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public Response addGroup(GroupData groupData) { - - String groupID = groupData.getID(); - - // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - 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 - try { - userGroupManager.addGroup(group); - - auditAddGroup(groupID, groupData, ILogger.SUCCESS); - - // read the data back - groupData = getGroup(groupID); - - return Response - .created(groupData.getLink().getHref()) - .entity(groupData) - .type(MediaType.APPLICATION_XML) - .build(); - - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_USRGRP_GROUP_ADD_FAILED")); - } - - } catch (CMSException e) { - auditAddGroup(groupID, groupData, ILogger.FAILURE); - throw e; - - } catch (EBaseException e) { - auditAddGroup(groupID, groupData, ILogger.FAILURE); - throw new CMSException(e.getMessage()); - } - } - - /** - * modifies a group - *

- * - * last person of the super power group "Certificate Server Administrators" can never be removed. - *

- * - * http://warp.mcom.com/server/certificate/columbo/design/ ui/admin-protocol-definition.html#group - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public Response modifyGroup(String groupID, GroupData groupData) { - - // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IGroup group = userGroupManager.getGroupFromName(groupID); - - group.set("description", groupData.getDescription()); - - // allow adding a group with no members, except "Certificate - // Server Administrators" - try { - userGroupManager.modifyGroup(group); - - auditModifyGroup(groupID, groupData, ILogger.SUCCESS); - - // read the data back - groupData = getGroup(groupID); - - return Response - .ok(groupData) - .type(MediaType.APPLICATION_XML) - .build(); - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - throw new CMSException(getUserMessage("CMS_USRGRP_GROUP_MODIFY_FAILED")); - } - - } catch (CMSException e) { - auditModifyGroup(groupID, groupData, ILogger.FAILURE); - throw e; - - } catch (EBaseException e) { - auditModifyGroup(groupID, groupData, ILogger.FAILURE); - throw new CMSException(e.getMessage()); - } - } - - /** - * removes a group - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#group - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public void 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - // if fails, let the exception fall through - userGroupManager.removeGroup(groupID); - - auditDeleteGroup(groupID, ILogger.SUCCESS); - - } catch (CMSException e) { - auditDeleteGroup(groupID, ILogger.FAILURE); - throw e; - - } catch (EBaseException e) { - auditDeleteGroup(groupID, ILogger.FAILURE); - throw new CMSException(e.getMessage()); - } - } - - 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 params, String status) { - audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_GROUPS, type, id, params, status); - } -} diff --git a/base/common/src/com/netscape/cms/servlet/admin/GroupService.java b/base/common/src/com/netscape/cms/servlet/admin/GroupService.java new file mode 100644 index 000000000..868f142c8 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/admin/GroupService.java @@ -0,0 +1,335 @@ +// --- 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.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +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.EBaseException; +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.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.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cmsutil.ldap.LDAPUtil; + +/** + * @author Endi S. Dewata + */ +public class GroupService extends PKIService implements GroupResource { + + 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 id = group.getGroupID(); + if (!StringUtils.isEmpty(id)) groupData.setID(id); + + String description = group.getDescription(); + if (!StringUtils.isEmpty(description)) groupData.setDescription(description); + + String groupID = URLEncoder.encode(groupData.getID(), "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(GroupResource.class).path("{groupID}").build(groupID); + 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 GroupCollection 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 groups = userGroupManager.listGroups(filter); + + GroupCollection response = new GroupCollection(); + + int i = 0; + + // skip to the start of the page + for ( ; i 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 response; + + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); + } + } + + /** + * finds a group + * Request/Response Syntax: + * http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#user-admin + */ + @Override + public GroupData getGroup(String groupID) { + + try { + if (groupID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IGroup group = userGroupManager.getGroupFromName(groupID); + if (group == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_GROUP_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_GROUP_NOT_EXIST")); + } + + return createGroupData(group); + + } catch (CMSException e) { + throw e; + + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); + } + } + + /** + * Adds a new group in local scope. + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#group + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public Response addGroup(GroupData groupData) { + + String groupID = groupData.getID(); + + // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + 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 + try { + userGroupManager.addGroup(group); + + auditAddGroup(groupID, groupData, ILogger.SUCCESS); + + // read the data back + groupData = getGroup(groupID); + + return Response + .created(groupData.getLink().getHref()) + .entity(groupData) + .type(MediaType.APPLICATION_XML) + .build(); + + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_USRGRP_GROUP_ADD_FAILED")); + } + + } catch (CMSException e) { + auditAddGroup(groupID, groupData, ILogger.FAILURE); + throw e; + + } catch (EBaseException e) { + auditAddGroup(groupID, groupData, ILogger.FAILURE); + throw new CMSException(e.getMessage()); + } + } + + /** + * modifies a group + *

+ * + * last person of the super power group "Certificate Server Administrators" can never be removed. + *

+ * + * http://warp.mcom.com/server/certificate/columbo/design/ ui/admin-protocol-definition.html#group + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public Response modifyGroup(String groupID, GroupData groupData) { + + // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IGroup group = userGroupManager.getGroupFromName(groupID); + + group.set("description", groupData.getDescription()); + + // allow adding a group with no members, except "Certificate + // Server Administrators" + try { + userGroupManager.modifyGroup(group); + + auditModifyGroup(groupID, groupData, ILogger.SUCCESS); + + // read the data back + groupData = getGroup(groupID); + + return Response + .ok(groupData) + .type(MediaType.APPLICATION_XML) + .build(); + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + throw new CMSException(getUserMessage("CMS_USRGRP_GROUP_MODIFY_FAILED")); + } + + } catch (CMSException e) { + auditModifyGroup(groupID, groupData, ILogger.FAILURE); + throw e; + + } catch (EBaseException e) { + auditModifyGroup(groupID, groupData, ILogger.FAILURE); + throw new CMSException(e.getMessage()); + } + } + + /** + * removes a group + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#group + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public void 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + // if fails, let the exception fall through + userGroupManager.removeGroup(groupID); + + auditDeleteGroup(groupID, ILogger.SUCCESS); + + } catch (CMSException e) { + auditDeleteGroup(groupID, ILogger.FAILURE); + throw e; + + } catch (EBaseException e) { + auditDeleteGroup(groupID, ILogger.FAILURE); + throw new CMSException(e.getMessage()); + } + } + + 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 params, String status) { + audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_GROUPS, type, id, params, status); + } +} diff --git a/base/common/src/com/netscape/cms/servlet/admin/SystemCertService.java b/base/common/src/com/netscape/cms/servlet/admin/SystemCertService.java new file mode 100644 index 000000000..2d86d71ea --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/admin/SystemCertService.java @@ -0,0 +1,75 @@ +// --- 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.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.kra.IKeyRecoveryAuthority; +import com.netscape.certsrv.security.ITransportKeyUnit; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cms.servlet.cert.model.CertificateData; + +/** + * This is the class used to list, retrieve and modify system certificates for all Java subsystems. + * + * @author alee + * + */ +public class SystemCertService extends PKIService implements SystemCertificateResource { + + /** + * Used to retrieve the transport certificate + */ + public Response getTransportCert() { + CertificateData cert = null; + IKeyRecoveryAuthority kra = null; + + // auth and authz + + kra = (IKeyRecoveryAuthority) CMS.getSubsystem("kra"); + if (kra == null) { + // no KRA + throw new WebApplicationException(Response.Status.NOT_FOUND); + } + + ITransportKeyUnit tu = kra.getTransportKeyUnit(); + if (tu == null) { + CMS.debug("getTransportCert: transport key unit is null"); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + org.mozilla.jss.crypto.X509Certificate transportCert = tu.getCertificate(); + if (transportCert == null) { + CMS.debug("getTransportCert: transport cert is null"); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + try { + cert = createCertificateData(transportCert); + } catch (CertificateEncodingException e) { + CMS.debug("getTransportCert: certificate encoding exception with transport cert"); + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + return sendConditionalGetResponse(DEFAULT_LONG_CACHE_LIFETIME, cert); + } + +} diff --git a/base/common/src/com/netscape/cms/servlet/admin/SystemCertificateResourceService.java b/base/common/src/com/netscape/cms/servlet/admin/SystemCertificateResourceService.java deleted file mode 100644 index 72106a903..000000000 --- a/base/common/src/com/netscape/cms/servlet/admin/SystemCertificateResourceService.java +++ /dev/null @@ -1,75 +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.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.kra.IKeyRecoveryAuthority; -import com.netscape.certsrv.security.ITransportKeyUnit; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cms.servlet.cert.model.CertificateData; - -/** - * This is the class used to list, retrieve and modify system certificates for all Java subsystems. - * - * @author alee - * - */ -public class SystemCertificateResourceService extends CMSResourceService implements SystemCertificateResource { - - /** - * Used to retrieve the transport certificate - */ - public Response getTransportCert() { - CertificateData cert = null; - IKeyRecoveryAuthority kra = null; - - // auth and authz - - kra = (IKeyRecoveryAuthority) CMS.getSubsystem("kra"); - if (kra == null) { - // no KRA - throw new WebApplicationException(Response.Status.NOT_FOUND); - } - - ITransportKeyUnit tu = kra.getTransportKeyUnit(); - if (tu == null) { - CMS.debug("getTransportCert: transport key unit is null"); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - org.mozilla.jss.crypto.X509Certificate transportCert = tu.getCertificate(); - if (transportCert == null) { - CMS.debug("getTransportCert: transport cert is null"); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - try { - cert = createCertificateData(transportCert); - } catch (CertificateEncodingException e) { - CMS.debug("getTransportCert: certificate encoding exception with transport cert"); - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - return sendConditionalGetResponse(DEFAULT_LONG_CACHE_LIFETIME, cert); - } - -} diff --git a/base/common/src/com/netscape/cms/servlet/admin/UserCertResourceService.java b/base/common/src/com/netscape/cms/servlet/admin/UserCertResourceService.java deleted file mode 100644 index e0e2ddfde..000000000 --- a/base/common/src/com/netscape/cms/servlet/admin/UserCertResourceService.java +++ /dev/null @@ -1,485 +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.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.Map; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import netscape.ldap.LDAPException; -import netscape.security.pkcs.PKCS7; -import netscape.security.x509.X509CertImpl; - -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.ICertPrettyPrint; -import com.netscape.certsrv.common.OpDef; -import com.netscape.certsrv.common.ScopeDef; -import com.netscape.certsrv.dbs.certdb.CertId; -import com.netscape.certsrv.logging.IAuditor; -import com.netscape.certsrv.logging.ILogger; -import com.netscape.certsrv.user.UserCertCollection; -import com.netscape.certsrv.user.UserCertData; -import com.netscape.certsrv.user.UserCertResource; -import com.netscape.certsrv.usrgrp.IUGSubsystem; -import com.netscape.certsrv.usrgrp.IUser; -import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cmsutil.util.Cert; -import com.netscape.cmsutil.util.Utils; - -/** - * @author Endi S. Dewata - */ -public class UserCertResourceService extends CMSResourceService implements UserCertResource { - - public final static int DEFAULT_SIZE = 20; - - public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG); - - 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(UserCertResource.class).path("{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 UserCertCollection 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IUser user = null; - - try { - user = userGroupManager.getUser(userID); - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); - } - - if (user == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); - } - - UserCertCollection response = new UserCertCollection(); - - X509Certificate[] certs = user.getX509Certificates(); - if (certs != null) { - for (int i=start; i 0) { - URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); - response.addLink(new Link("prev", uri)); - } - - if (start+size < certs.length) { - URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); - response.addLink(new Link("next", uri)); - } - } - - return response; - - } catch (CMSException e) { - throw e; - - } catch (Exception e) { - throw new CMSException(e.getMessage()); - } - } - - @Override - public UserCertData getUserCert(String userID, String certID) { - try { - if (userID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IUser user = null; - - try { - user = userGroupManager.getUser(userID); - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); - } - - if (user == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST")); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); - } - - X509Certificate[] certs = user.getX509Certificates(); - - if (certs == null) { - throw new CMSException("Certificate not found"); - } - - try { - certID = URLDecoder.decode(certID, "UTF-8"); - } catch (Exception e) { - throw new CMSException(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())); - - // add base64 encoding - String base64 = CMS.getEncodedCert(cert); - userCertData.setEncoded(base64); - - return userCertData; - } - - throw new CMSException("Certificate not found"); - - } catch (CMSException e) { - throw e; - - } catch (Exception e) { - throw new CMSException(e.getMessage()); - } - } - - /** - * Adds a certificate to a user - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#user-admin - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public Response addUserCert(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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - 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 Response.ok().build(); - } - - // 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 CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR")); - } - - // 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 CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR")); - } - - 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 (Exception e) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString())); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR")); - } - } - - 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 = getUserCert(userID, URLEncoder.encode(certID, "UTF-8")); - - return Response - .created(userCertData.getLink().getHref()) - .entity(userCertData) - .type(MediaType.APPLICATION_XML) - .build(); - - } catch (CertificateExpiredException e) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED", - String.valueOf(cert.getSubjectDN()))); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_EXPIRED")); - - } catch (CertificateNotYetValidException e) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID", - String.valueOf(cert.getSubjectDN()))); - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_NOT_YET_VALID")); - - } catch (LDAPException e) { - if (e.getLDAPResultCode() == LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) { - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_CERT_EXISTS")); - } else { - throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); - } - } - - } catch (CMSException e) { - auditAddUserCert(userID, userCertData, ILogger.FAILURE); - throw e; - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - auditAddUserCert(userID, userCertData, ILogger.FAILURE); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); - } - } - - /** - * Removes a certificate for a user - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#user-admin - *

- * - * In this method, "certDN" is actually a combination of version, serialNumber, issuerDN, and SubjectDN. - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public void removeUserCert(String userID, String certID) { - - try { - certID = URLDecoder.decode(certID, "UTF-8"); - } catch (Exception e) { - throw new CMSException(e.getMessage()); - } - - UserCertData userCertData = new UserCertData(); - userCertData.setID(certID); - removeUserCert(userID, userCertData); - } - - 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - 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 (CMSException e) { - auditDeleteUserCert(userID, userCertData, ILogger.FAILURE); - throw e; - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - auditDeleteUserCert(userID, userCertData, ILogger.FAILURE); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); - } - } - - public void log(int level, String message) { - log(ILogger.S_USRGRP, level, message); - } - - public void auditAddUserCert(String id, UserCertData userCertData, String status) { - audit(OpDef.OP_ADD, id, getParams(userCertData), status); - } - - public void auditDeleteUserCert(String id, UserCertData userCertData, String status) { - audit(OpDef.OP_DELETE, id, getParams(userCertData), status); - } - - public void audit(String type, String id, Map params, String status) { - audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_USER_CERTS, type, id, params, status); - } -} diff --git a/base/common/src/com/netscape/cms/servlet/admin/UserCertService.java b/base/common/src/com/netscape/cms/servlet/admin/UserCertService.java new file mode 100644 index 000000000..4f2304a97 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/admin/UserCertService.java @@ -0,0 +1,485 @@ +// --- 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.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.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import netscape.ldap.LDAPException; +import netscape.security.pkcs.PKCS7; +import netscape.security.x509.X509CertImpl; + +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.ICertPrettyPrint; +import com.netscape.certsrv.common.OpDef; +import com.netscape.certsrv.common.ScopeDef; +import com.netscape.certsrv.dbs.certdb.CertId; +import com.netscape.certsrv.logging.IAuditor; +import com.netscape.certsrv.logging.ILogger; +import com.netscape.certsrv.user.UserCertCollection; +import com.netscape.certsrv.user.UserCertData; +import com.netscape.certsrv.user.UserCertResource; +import com.netscape.certsrv.usrgrp.IUGSubsystem; +import com.netscape.certsrv.usrgrp.IUser; +import com.netscape.cms.servlet.base.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cmsutil.util.Cert; +import com.netscape.cmsutil.util.Utils; + +/** + * @author Endi S. Dewata + */ +public class UserCertService extends PKIService implements UserCertResource { + + public final static int DEFAULT_SIZE = 20; + + public IUGSubsystem userGroupManager = (IUGSubsystem) CMS.getSubsystem(CMS.SUBSYSTEM_UG); + + 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(UserCertResource.class).path("{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 UserCertCollection 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IUser user = null; + + try { + user = userGroupManager.getUser(userID); + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); + } + + if (user == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); + } + + UserCertCollection response = new UserCertCollection(); + + X509Certificate[] certs = user.getX509Certificates(); + if (certs != null) { + for (int i=start; i 0) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", Math.max(start-size, 0)).build(); + response.addLink(new Link("prev", uri)); + } + + if (start+size < certs.length) { + URI uri = uriInfo.getRequestUriBuilder().replaceQueryParam("start", start+size).build(); + response.addLink(new Link("next", uri)); + } + } + + return response; + + } catch (CMSException e) { + throw e; + + } catch (Exception e) { + throw new CMSException(e.getMessage()); + } + } + + @Override + public UserCertData getUserCert(String userID, String certID) { + try { + if (userID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IUser user = null; + + try { + user = userGroupManager.getUser(userID); + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); + } + + if (user == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST")); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); + } + + X509Certificate[] certs = user.getX509Certificates(); + + if (certs == null) { + throw new CMSException("Certificate not found"); + } + + try { + certID = URLDecoder.decode(certID, "UTF-8"); + } catch (Exception e) { + throw new CMSException(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())); + + // add base64 encoding + String base64 = CMS.getEncodedCert(cert); + userCertData.setEncoded(base64); + + return userCertData; + } + + throw new CMSException("Certificate not found"); + + } catch (CMSException e) { + throw e; + + } catch (Exception e) { + throw new CMSException(e.getMessage()); + } + } + + /** + * Adds a certificate to a user + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#user-admin + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public Response addUserCert(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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + 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 Response.ok().build(); + } + + // 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 CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR")); + } + + // 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 CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR")); + } + + 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 (Exception e) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_ERROR", e.toString())); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_ERROR")); + } + } + + 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 = getUserCert(userID, URLEncoder.encode(certID, "UTF-8")); + + return Response + .created(userCertData.getLink().getHref()) + .entity(userCertData) + .type(MediaType.APPLICATION_XML) + .build(); + + } catch (CertificateExpiredException e) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ADD_CERT_EXPIRED", + String.valueOf(cert.getSubjectDN()))); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_EXPIRED")); + + } catch (CertificateNotYetValidException e) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_CERT_NOT_YET_VALID", + String.valueOf(cert.getSubjectDN()))); + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_CERT_NOT_YET_VALID")); + + } catch (LDAPException e) { + if (e.getLDAPResultCode() == LDAPException.ATTRIBUTE_OR_VALUE_EXISTS) { + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_CERT_EXISTS")); + } else { + throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); + } + } + + } catch (CMSException e) { + auditAddUserCert(userID, userCertData, ILogger.FAILURE); + throw e; + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + auditAddUserCert(userID, userCertData, ILogger.FAILURE); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); + } + } + + /** + * Removes a certificate for a user + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#user-admin + *

+ * + * In this method, "certDN" is actually a combination of version, serialNumber, issuerDN, and SubjectDN. + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public void removeUserCert(String userID, String certID) { + + try { + certID = URLDecoder.decode(certID, "UTF-8"); + } catch (Exception e) { + throw new CMSException(e.getMessage()); + } + + UserCertData userCertData = new UserCertData(); + userCertData.setID(certID); + removeUserCert(userID, userCertData); + } + + 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + 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 (CMSException e) { + auditDeleteUserCert(userID, userCertData, ILogger.FAILURE); + throw e; + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + auditDeleteUserCert(userID, userCertData, ILogger.FAILURE); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); + } + } + + public void log(int level, String message) { + log(ILogger.S_USRGRP, level, message); + } + + public void auditAddUserCert(String id, UserCertData userCertData, String status) { + audit(OpDef.OP_ADD, id, getParams(userCertData), status); + } + + public void auditDeleteUserCert(String id, UserCertData userCertData, String status) { + audit(OpDef.OP_DELETE, id, getParams(userCertData), status); + } + + public void audit(String type, String id, Map params, String status) { + audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_USER_CERTS, type, id, params, status); + } +} diff --git a/base/common/src/com/netscape/cms/servlet/admin/UserResourceService.java b/base/common/src/com/netscape/cms/servlet/admin/UserResourceService.java deleted file mode 100644 index 1639c5912..000000000 --- a/base/common/src/com/netscape/cms/servlet/admin/UserResourceService.java +++ /dev/null @@ -1,483 +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.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import netscape.ldap.LDAPException; - -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.EBaseException; -import com.netscape.certsrv.common.OpDef; -import com.netscape.certsrv.common.ScopeDef; -import com.netscape.certsrv.logging.IAuditor; -import com.netscape.certsrv.logging.ILogger; -import com.netscape.certsrv.password.IPasswordCheck; -import com.netscape.certsrv.user.UserCollection; -import com.netscape.certsrv.user.UserData; -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.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cmsutil.ldap.LDAPUtil; - -/** - * @author Endi S. Dewata - */ -public class UserResourceService extends CMSResourceService implements UserResource { - - 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 id = user.getUserID(); - if (!StringUtils.isEmpty(id)) userData.setID(id); - - String fullName = user.getFullName(); - if (!StringUtils.isEmpty(fullName)) userData.setFullName(fullName); - - String userID = URLEncoder.encode(id, "UTF-8"); - URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}").build(userID); - 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 UserCollection 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 users = userGroupManager.findUsers(filter); - - UserCollection response = new UserCollection(); - - int i = 0; - - // skip to the start of the page - for ( ; i 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 response; - - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); - } - } - - /** - * 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 UserData getUser(String userID) { - try { - if (userID == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); - - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - IUser user; - - try { - user = userGroupManager.getUser(userID); - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); - } - - if (user == null) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST")); - - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); - } - - 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); - - return userData; - - } catch (CMSException e) { - throw e; - - } catch (Exception e) { - throw new CMSException(e.getMessage()); - } - } - - /** - * Adds a new user to LDAP server - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#user-admin - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - - @Override - public Response addUser(UserData userData) { - - String userID = userData.getID(); - - // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - if (userID.indexOf(BACK_SLASH) != -1) { - // backslashes (BS) are not allowed - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_RS_ID_BS")); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_RS_ID_BS")); - } - - if (userID.equals(SYSTEM_USER)) { - // backslashes (BS) are not allowed - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_SPECIAL_ID", userID)); - throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_SPECIAL_ID", userID)); - } - - IUser user = userGroupManager.createUser(userID); - - String fname = userData.getFullName(); - if (fname == null || fname.length() == 0) { - String msg = getUserMessage("CMS_USRGRP_USER_ADD_FAILED_1", "full name"); - - log(ILogger.LL_FAILURE, msg); - throw new CMSException(msg); - - } else { - user.setFullName(fname); - } - - String email = userData.getEmail(); - if (email != null) { - user.setEmail(email); - } else { - user.setEmail(""); - } - - 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); - } else { - user.setPassword(""); - } - - String phone = userData.getPhone(); - if (phone != null) { - user.setPhone(phone); - } else { - user.setPhone(""); - } - - String type = userData.getType(); - if (type != null) { - user.setUserType(type); - } else { - user.setUserType(""); - } - - String state = userData.getState(); - if (state != null) { - user.setState(state); - } - - try { - userGroupManager.addUser(user); - - auditAddUser(userID, userData, ILogger.SUCCESS); - - // read the data back - userData = getUser(userID); - - return Response - .created(userData.getLink().getHref()) - .entity(userData) - .type(MediaType.APPLICATION_XML) - .build(); - - } catch (EUsrGrpException e) { - log(ILogger.LL_FAILURE, e.toString()); - - if (user.getUserID() == null) { - throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED_1", "uid")); - } else { - throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); - } - - } catch (LDAPException e) { - log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ADD_USER_FAIL", e.toString())); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); - } - - } catch (CMSException e) { - auditAddUser(userID, userData, ILogger.FAILURE); - throw e; - - } catch (EBaseException e) { - auditAddUser(userID, userData, ILogger.FAILURE); - throw new CMSException(e.getMessage()); - } - } - - /** - * Modifies an existing user in local scope. - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#user-admin - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public Response modifyUser(String userID, UserData userData) { - - // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - 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); - } - - try { - userGroupManager.modifyUser(user); - - auditModifyUser(userID, userData, ILogger.SUCCESS); - - // read the data back - userData = getUser(userID); - - return Response - .ok(userData) - .type(MediaType.APPLICATION_XML) - .build(); - - } catch (Exception e) { - log(ILogger.LL_FAILURE, e.toString()); - throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); - } - - } catch (CMSException e) { - auditModifyUser(userID, userData, ILogger.FAILURE); - throw e; - - } catch (EBaseException e) { - auditModifyUser(userID, userData, ILogger.FAILURE); - throw new CMSException(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. - *

- * - * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ - * ui/admin-protocol-definition.html#user-admin - *

- * - *

    - *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under - * users/groups) - *
- */ - @Override - public void 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); - } - - // get list of groups, and see if uid belongs to any - Enumeration groups; - - try { - groups = userGroupManager.findGroups("*"); - - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); - } - - try { - 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); - - } catch (Exception e) { - throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_FAIL_USER_RMV")); - } - - } catch (CMSException e) { - auditDeleteUser(userID, ILogger.FAILURE); - throw e; - } - } - - public void log(int level, String message) { - log(ILogger.S_USRGRP, level, message); - } - - public void auditAddUser(String id, UserData userData, String status) { - audit(OpDef.OP_ADD, id, getParams(userData), status); - } - - public void auditModifyUser(String id, UserData userData, String status) { - audit(OpDef.OP_MODIFY, id, getParams(userData), status); - } - - public void auditDeleteUser(String id, String status) { - audit(OpDef.OP_DELETE, id, null, status); - } - - public void audit(String type, String id, Map params, String status) { - audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_USERS, type, id, params, status); - } -} diff --git a/base/common/src/com/netscape/cms/servlet/admin/UserService.java b/base/common/src/com/netscape/cms/servlet/admin/UserService.java new file mode 100644 index 000000000..1128e09e7 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/admin/UserService.java @@ -0,0 +1,483 @@ +// --- 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.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import netscape.ldap.LDAPException; + +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.EBaseException; +import com.netscape.certsrv.common.OpDef; +import com.netscape.certsrv.common.ScopeDef; +import com.netscape.certsrv.logging.IAuditor; +import com.netscape.certsrv.logging.ILogger; +import com.netscape.certsrv.password.IPasswordCheck; +import com.netscape.certsrv.user.UserCollection; +import com.netscape.certsrv.user.UserData; +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.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cmsutil.ldap.LDAPUtil; + +/** + * @author Endi S. Dewata + */ +public class UserService extends PKIService implements UserResource { + + 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 id = user.getUserID(); + if (!StringUtils.isEmpty(id)) userData.setID(id); + + String fullName = user.getFullName(); + if (!StringUtils.isEmpty(fullName)) userData.setFullName(fullName); + + String userID = URLEncoder.encode(id, "UTF-8"); + URI uri = uriInfo.getBaseUriBuilder().path(UserResource.class).path("{userID}").build(userID); + 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 UserCollection 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 users = userGroupManager.findUsers(filter); + + UserCollection response = new UserCollection(); + + int i = 0; + + // skip to the start of the page + for ( ; i 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 response; + + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); + } + } + + /** + * 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 UserData getUser(String userID) { + try { + if (userID == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_NULL_RS_ID")); + + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + IUser user; + + try { + user = userGroupManager.getUser(userID); + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); + } + + if (user == null) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("USRGRP_SRVLT_USER_NOT_EXIST")); + + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_USER_NOT_EXIST")); + } + + 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); + + return userData; + + } catch (CMSException e) { + throw e; + + } catch (Exception e) { + throw new CMSException(e.getMessage()); + } + } + + /** + * Adds a new user to LDAP server + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#user-admin + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + + @Override + public Response addUser(UserData userData) { + + String userID = userData.getID(); + + // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + if (userID.indexOf(BACK_SLASH) != -1) { + // backslashes (BS) are not allowed + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_RS_ID_BS")); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_RS_ID_BS")); + } + + if (userID.equals(SYSTEM_USER)) { + // backslashes (BS) are not allowed + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_SPECIAL_ID", userID)); + throw new CMSException(getUserMessage("CMS_ADMIN_SRVLT_SPECIAL_ID", userID)); + } + + IUser user = userGroupManager.createUser(userID); + + String fname = userData.getFullName(); + if (fname == null || fname.length() == 0) { + String msg = getUserMessage("CMS_USRGRP_USER_ADD_FAILED_1", "full name"); + + log(ILogger.LL_FAILURE, msg); + throw new CMSException(msg); + + } else { + user.setFullName(fname); + } + + String email = userData.getEmail(); + if (email != null) { + user.setEmail(email); + } else { + user.setEmail(""); + } + + 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); + } else { + user.setPassword(""); + } + + String phone = userData.getPhone(); + if (phone != null) { + user.setPhone(phone); + } else { + user.setPhone(""); + } + + String type = userData.getType(); + if (type != null) { + user.setUserType(type); + } else { + user.setUserType(""); + } + + String state = userData.getState(); + if (state != null) { + user.setState(state); + } + + try { + userGroupManager.addUser(user); + + auditAddUser(userID, userData, ILogger.SUCCESS); + + // read the data back + userData = getUser(userID); + + return Response + .created(userData.getLink().getHref()) + .entity(userData) + .type(MediaType.APPLICATION_XML) + .build(); + + } catch (EUsrGrpException e) { + log(ILogger.LL_FAILURE, e.toString()); + + if (user.getUserID() == null) { + throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED_1", "uid")); + } else { + throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); + } + + } catch (LDAPException e) { + log(ILogger.LL_FAILURE, CMS.getLogMessage("ADMIN_SRVLT_ADD_USER_FAIL", e.toString())); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_ADD_FAILED")); + } + + } catch (CMSException e) { + auditAddUser(userID, userData, ILogger.FAILURE); + throw e; + + } catch (EBaseException e) { + auditAddUser(userID, userData, ILogger.FAILURE); + throw new CMSException(e.getMessage()); + } + } + + /** + * Modifies an existing user in local scope. + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#user-admin + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public Response modifyUser(String userID, UserData userData) { + + // 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + 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); + } + + try { + userGroupManager.modifyUser(user); + + auditModifyUser(userID, userData, ILogger.SUCCESS); + + // read the data back + userData = getUser(userID); + + return Response + .ok(userData) + .type(MediaType.APPLICATION_XML) + .build(); + + } catch (Exception e) { + log(ILogger.LL_FAILURE, e.toString()); + throw new CMSException(getUserMessage("CMS_USRGRP_USER_MOD_FAILED")); + } + + } catch (CMSException e) { + auditModifyUser(userID, userData, ILogger.FAILURE); + throw e; + + } catch (EBaseException e) { + auditModifyUser(userID, userData, ILogger.FAILURE); + throw new CMSException(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. + *

+ * + * Request/Response Syntax: http://warp.mcom.com/server/certificate/columbo/design/ + * ui/admin-protocol-definition.html#user-admin + *

+ * + *

    + *
  • signed.audit LOGGING_SIGNED_AUDIT_CONFIG_ROLE used when configuring role information (anything under + * users/groups) + *
+ */ + @Override + public void 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 CMSException(getUserMessage("CMS_ADMIN_SRVLT_NULL_RS_ID")); + } + + // get list of groups, and see if uid belongs to any + Enumeration groups; + + try { + groups = userGroupManager.findGroups("*"); + + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_INTERNAL_ERROR")); + } + + try { + 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); + + } catch (Exception e) { + throw new CMSException(getUserMessage("CMS_USRGRP_SRVLT_FAIL_USER_RMV")); + } + + } catch (CMSException e) { + auditDeleteUser(userID, ILogger.FAILURE); + throw e; + } + } + + public void log(int level, String message) { + log(ILogger.S_USRGRP, level, message); + } + + public void auditAddUser(String id, UserData userData, String status) { + audit(OpDef.OP_ADD, id, getParams(userData), status); + } + + public void auditModifyUser(String id, UserData userData, String status) { + audit(OpDef.OP_MODIFY, id, getParams(userData), status); + } + + public void auditDeleteUser(String id, String status) { + audit(OpDef.OP_DELETE, id, null, status); + } + + public void audit(String type, String id, Map params, String status) { + audit(IAuditor.LOGGING_SIGNED_AUDIT_CONFIG_ROLE, ScopeDef.SC_USERS, type, id, params, status); + } +} diff --git a/base/common/src/com/netscape/cms/servlet/base/CMSResourceService.java b/base/common/src/com/netscape/cms/servlet/base/CMSResourceService.java deleted file mode 100644 index 48daeca6e..000000000 --- a/base/common/src/com/netscape/cms/servlet/base/CMSResourceService.java +++ /dev/null @@ -1,168 +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.base; - -import java.lang.reflect.Method; -import java.security.cert.CertificateEncodingException; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.FormParam; -import javax.ws.rs.core.CacheControl; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.EntityTag; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.Request; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import javax.ws.rs.core.UriInfo; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.logging.IAuditor; -import com.netscape.certsrv.logging.ILogger; -import com.netscape.cms.servlet.cert.model.CertificateData; - -/** - * Base class for CMS RESTful resources - * - * @author alee - * - */ -public class CMSResourceService { - - public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----"; - public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----"; - - // caching parameters - public static final int DEFAULT_LONG_CACHE_LIFETIME = 1000; - - @Context - protected UriInfo uriInfo; - - @Context - protected HttpHeaders headers; - - @Context - protected Request request; - - @Context - protected HttpServletRequest servletRequest; - - public ILogger logger = CMS.getLogger(); - public IAuditor auditor = CMS.getAuditor(); - - public Response createOKResponse(Object object) { - return Response.ok(object).build(); - } - - public Response sendConditionalGetResponse(int ctime, Object object) { - CacheControl cc = new CacheControl(); - cc.setMaxAge(ctime); - EntityTag tag = new EntityTag(Integer.toString(object.hashCode())); - - ResponseBuilder builder = request.evaluatePreconditions(tag); - if (builder != null) { - builder.cacheControl(cc); - return builder.build(); - } - - builder = Response.ok(object); - builder.cacheControl(cc); - builder.tag(tag); - return builder.build(); - } - - public CertificateData createCertificateData(org.mozilla.jss.crypto.X509Certificate cert) - throws CertificateEncodingException { - CertificateData data = new CertificateData(); - String b64 = HEADER + CMS.BtoA(cert.getEncoded()) + TRAILER; - data.setEncoded(b64); - return data; - } - - public Locale getLocale() { - - if (headers == null) return Locale.getDefault(); - - List locales = headers.getAcceptableLanguages(); - if (locales == null || locales.isEmpty()) return Locale.getDefault(); - - return locales.get(0); - } - - public String getUserMessage(String messageId, String... params) { - return CMS.getUserMessage(getLocale(), messageId, params); - } - - public void log(int source, int level, String message) { - - if (logger == null) return; - - logger.log(ILogger.EV_SYSTEM, - null, - source, - level, - getClass().getSimpleName() + ": " + message); - } - - public void audit(String message, String scope, String type, String id, Map params, String status) { - - if (auditor == null) return; - - String auditMessage = CMS.getLogMessage( - message, - auditor.getSubjectID(), - status, - auditor.getParamString(scope, type, id, params)); - - auditor.log(auditMessage); - } - - /** - * Get the values of the fields annotated with @FormParam. - */ - public Map getParams(Object object) { - - Map map = new HashMap(); - - // for each fields in the object - for (Method method : object.getClass().getMethods()) { - FormParam element = method.getAnnotation(FormParam.class); - if (element == null) continue; - - String name = element.value(); - - try { - // get the value from the object - Object value = method.invoke(object); - - // put the value in the map - map.put(name, value == null ? null : value.toString()); - - } catch (Exception e) { - // ignore inaccessible fields - e.printStackTrace(); - } - } - - return map; - } -} diff --git a/base/common/src/com/netscape/cms/servlet/base/PKIService.java b/base/common/src/com/netscape/cms/servlet/base/PKIService.java new file mode 100644 index 000000000..de92d290a --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/base/PKIService.java @@ -0,0 +1,168 @@ +// --- 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.base; + +import java.lang.reflect.Method; +import java.security.cert.CertificateEncodingException; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.FormParam; +import javax.ws.rs.core.CacheControl; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.EntityTag; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.UriInfo; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.logging.IAuditor; +import com.netscape.certsrv.logging.ILogger; +import com.netscape.cms.servlet.cert.model.CertificateData; + +/** + * Base class for CMS RESTful resources + * + * @author alee + * + */ +public class PKIService { + + public static final String HEADER = "-----BEGIN NEW CERTIFICATE REQUEST-----"; + public static final String TRAILER = "-----END NEW CERTIFICATE REQUEST-----"; + + // caching parameters + public static final int DEFAULT_LONG_CACHE_LIFETIME = 1000; + + @Context + protected UriInfo uriInfo; + + @Context + protected HttpHeaders headers; + + @Context + protected Request request; + + @Context + protected HttpServletRequest servletRequest; + + public ILogger logger = CMS.getLogger(); + public IAuditor auditor = CMS.getAuditor(); + + public Response createOKResponse(Object object) { + return Response.ok(object).build(); + } + + public Response sendConditionalGetResponse(int ctime, Object object) { + CacheControl cc = new CacheControl(); + cc.setMaxAge(ctime); + EntityTag tag = new EntityTag(Integer.toString(object.hashCode())); + + ResponseBuilder builder = request.evaluatePreconditions(tag); + if (builder != null) { + builder.cacheControl(cc); + return builder.build(); + } + + builder = Response.ok(object); + builder.cacheControl(cc); + builder.tag(tag); + return builder.build(); + } + + public CertificateData createCertificateData(org.mozilla.jss.crypto.X509Certificate cert) + throws CertificateEncodingException { + CertificateData data = new CertificateData(); + String b64 = HEADER + CMS.BtoA(cert.getEncoded()) + TRAILER; + data.setEncoded(b64); + return data; + } + + public Locale getLocale() { + + if (headers == null) return Locale.getDefault(); + + List locales = headers.getAcceptableLanguages(); + if (locales == null || locales.isEmpty()) return Locale.getDefault(); + + return locales.get(0); + } + + public String getUserMessage(String messageId, String... params) { + return CMS.getUserMessage(getLocale(), messageId, params); + } + + public void log(int source, int level, String message) { + + if (logger == null) return; + + logger.log(ILogger.EV_SYSTEM, + null, + source, + level, + getClass().getSimpleName() + ": " + message); + } + + public void audit(String message, String scope, String type, String id, Map params, String status) { + + if (auditor == null) return; + + String auditMessage = CMS.getLogMessage( + message, + auditor.getSubjectID(), + status, + auditor.getParamString(scope, type, id, params)); + + auditor.log(auditMessage); + } + + /** + * Get the values of the fields annotated with @FormParam. + */ + public Map getParams(Object object) { + + Map map = new HashMap(); + + // for each fields in the object + for (Method method : object.getClass().getMethods()) { + FormParam element = method.getAnnotation(FormParam.class); + if (element == null) continue; + + String name = element.value(); + + try { + // get the value from the object + Object value = method.invoke(object); + + // put the value in the map + map.put(name, value == null ? null : value.toString()); + + } catch (Exception e) { + // ignore inaccessible fields + e.printStackTrace(); + } + } + + return map; + } +} diff --git a/base/common/src/com/netscape/cms/servlet/cert/CertResourceService.java b/base/common/src/com/netscape/cms/servlet/cert/CertResourceService.java deleted file mode 100644 index 6a3f0d79a..000000000 --- a/base/common/src/com/netscape/cms/servlet/cert/CertResourceService.java +++ /dev/null @@ -1,541 +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.Principal; -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 javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.Response; - -import netscape.security.pkcs.ContentInfo; -import netscape.security.pkcs.PKCS7; -import netscape.security.pkcs.SignerInfo; -import netscape.security.x509.AlgorithmId; -import netscape.security.x509.RevocationReason; -import netscape.security.x509.X509CertImpl; - -import org.jboss.resteasy.plugins.providers.atom.Link; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.base.EBaseException; -import com.netscape.certsrv.base.ICertPrettyPrint; -import com.netscape.certsrv.ca.ICertificateAuthority; -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.servlet.base.BadRequestException; -import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cms.servlet.base.UnauthorizedException; -import com.netscape.cms.servlet.cert.model.CertDataInfo; -import com.netscape.cms.servlet.cert.model.CertDataInfos; -import com.netscape.cms.servlet.cert.model.CertRevokeRequest; -import com.netscape.cms.servlet.cert.model.CertSearchData; -import com.netscape.cms.servlet.cert.model.CertUnrevokeRequest; -import com.netscape.cms.servlet.cert.model.CertificateData; -import com.netscape.cms.servlet.processors.Processor; -import com.netscape.cms.servlet.request.model.CertRequestDAO; -import com.netscape.cms.servlet.request.model.CertRequestInfo; -import com.netscape.cms.servlet.request.model.CertRetrievalRequestData; -import com.netscape.cmsutil.ldap.LDAPUtil; -import com.netscape.cmsutil.util.Utils; - -/** - * @author alee - * - */ -public class CertResourceService extends CMSResourceService implements CertResource { - - ICertificateAuthority authority; - ICertificateRepository repo; - - public final static int DEFAULT_SIZE = 20; - - public CertResourceService() { - authority = (ICertificateAuthority) CMS.getSubsystem("ca"); - repo = authority.getCertificateRepository(); - } - - private void validateRequest(CertId id) { - if (id == null) { - throw new BadRequestException("Invalid id in CertResourceService.validateRequest."); - } - } - - @Override - public CertificateData getCert(CertId id) { - validateRequest(id); - - CertRetrievalRequestData data = new CertRetrievalRequestData(); - data.setCertId(id); - - CertificateData certData = null; - - try { - certData = getCert(data); - } catch (EDBRecordNotFoundException e) { - throw new CertNotFoundException(id); - } catch (EBaseException e) { - throw new CMSException("Problem returning certificate: " + id); - } catch (CertificateEncodingException e) { - throw new CMSException("Problem encoding certificate searched for: " + id); - } - - return certData; - } - - @Override - public CertRequestInfo revokeCACert(CertId id, CertRevokeRequest request) { - return revokeCert(id, request, true); - } - - @Override - public CertRequestInfo revokeCert(CertId id, CertRevokeRequest request) { - return revokeCert(id, request, false); - } - - public CertRequestInfo revokeCert(CertId id, CertRevokeRequest request, boolean caCert) { - 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()); - 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 CMSException(e.getMessage()); - } - - try { - X509Certificate clientCert = null; - try { - clientCert = Processor.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")); - } - } - - // Find target cert record if different from client cert. - ICertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id); - X509CertImpl targetCert = targetRecord.getCertificate(); - - processor.createCRLExtension(); - processor.validateCertificateToRevoke(clientSubjectDN, targetRecord, caCert); - processor.addCertificateToRevoke(targetCert); - processor.createRevocationRequest(); - - processor.auditChangeRequest(ILogger.SUCCESS); - - } catch (CMSException 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 CMSException(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 CMSException(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 CMSException(e.getMessage()); - } - - try { - IRequest certRequest = processor.getRequest(); - CertRequestDAO dao = new CertRequestDAO(); - return dao.getRequest(certRequest.getRequestId(), uriInfo); - - } catch (EBaseException e) { - throw new CMSException(e.getMessage()); - } - } - - @Override - public CertRequestInfo unrevokeCert(CertId id, CertUnrevokeRequest request) { - RevocationProcessor processor; - try { - processor = new RevocationProcessor("caDoUnrevoke", getLocale()); - - // 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 CMSException(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 CMSException(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 CMSException(e.getMessage()); - } - - try { - IRequest certRequest = processor.getRequest(); - CertRequestDAO dao = new CertRequestDAO(); - return dao.getRequest(certRequest.getRequestId(), uriInfo); - - } catch (EBaseException e) { - throw new CMSException(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(CertSearchData data) { - if (data == null) { - return null; - } - - return data.buildFilter(); - } - - @Override - public CertDataInfos listCerts(String status, int maxResults, int maxTime) { - // get ldap filter - String filter = createSearchFilter(status); - CMS.debug("listKeys: filter is " + filter); - - CertDataInfos infos; - try { - infos = getCertList(filter, maxResults, maxTime); - } catch (EBaseException e) { - e.printStackTrace(); - throw new CMSException("Error listing certs in CertsResourceService.listCerts!"); - } - return infos; - } - - @Override - public CertDataInfos searchCerts(CertSearchData data, Integer start, Integer size) { - if (data == null) { - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - start = start == null ? 0 : start; - size = size == null ? DEFAULT_SIZE : size; - String filter = createSearchFilter(data); - - CertDataInfos infos = new CertDataInfos(); - - Enumeration e = null; - try { - - e = repo.findCertRecords(filter); - - 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.addCertData(createCertDataInfo(user)); - } - - // count the total entries - for (; e.hasMoreElements(); i++) - e.nextElement(); - - 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 (EBaseException e1) { - throw new CMSException("Error listing certs in CertsResourceService.listCerts!" + e.toString()); - } - - return infos; - } - - /** - * Returns list of certs meeting specified search filter. - * Currently, vlv searches are not used for certs. - * - * @param filter - * @param maxResults - * @param maxTime - * @param uriInfo - * @return - * @throws EBaseException - */ - private CertDataInfos getCertList(String filter, int maxResults, int maxTime) - throws EBaseException { - List list = new ArrayList(); - Enumeration e = null; - - e = repo.searchCertificates(filter, maxResults, maxTime); - if (e == null) { - throw new EBaseException("search results are null"); - } - - while (e.hasMoreElements()) { - ICertRecord rec = e.nextElement(); - if (rec != null) { - list.add(createCertDataInfo(rec)); - } - } - - CertDataInfos ret = new CertDataInfos(); - ret.setCertInfos(list); - - return ret; - } - - public CertificateData getCert(CertRetrievalRequestData data) throws EBaseException, CertificateEncodingException { - CertId certId = data.getCertId(); - - //find the cert in question - ICertRecord record = repo.readCertificateRecord(certId.toBigInteger()); - X509CertImpl cert = record.getCertificate(); - - CertificateData certData = new CertificateData(); - - 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())); - - 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()); - - 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 { - 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()); - - 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/common/src/com/netscape/cms/servlet/cert/CertService.java b/base/common/src/com/netscape/cms/servlet/cert/CertService.java new file mode 100644 index 000000000..08a621529 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/cert/CertService.java @@ -0,0 +1,541 @@ +// --- 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.Principal; +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 javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +import netscape.security.pkcs.ContentInfo; +import netscape.security.pkcs.PKCS7; +import netscape.security.pkcs.SignerInfo; +import netscape.security.x509.AlgorithmId; +import netscape.security.x509.RevocationReason; +import netscape.security.x509.X509CertImpl; + +import org.jboss.resteasy.plugins.providers.atom.Link; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.EBaseException; +import com.netscape.certsrv.base.ICertPrettyPrint; +import com.netscape.certsrv.ca.ICertificateAuthority; +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.servlet.base.BadRequestException; +import com.netscape.cms.servlet.base.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cms.servlet.base.UnauthorizedException; +import com.netscape.cms.servlet.cert.model.CertDataInfo; +import com.netscape.cms.servlet.cert.model.CertDataInfos; +import com.netscape.cms.servlet.cert.model.CertRevokeRequest; +import com.netscape.cms.servlet.cert.model.CertSearchData; +import com.netscape.cms.servlet.cert.model.CertUnrevokeRequest; +import com.netscape.cms.servlet.cert.model.CertificateData; +import com.netscape.cms.servlet.processors.Processor; +import com.netscape.cms.servlet.request.model.CertRequestDAO; +import com.netscape.cms.servlet.request.model.CertRequestInfo; +import com.netscape.cms.servlet.request.model.CertRetrievalRequestData; +import com.netscape.cmsutil.ldap.LDAPUtil; +import com.netscape.cmsutil.util.Utils; + +/** + * @author alee + * + */ +public class CertService extends PKIService implements CertResource { + + ICertificateAuthority authority; + ICertificateRepository repo; + + public final static int DEFAULT_SIZE = 20; + + public CertService() { + authority = (ICertificateAuthority) CMS.getSubsystem("ca"); + repo = authority.getCertificateRepository(); + } + + private void validateRequest(CertId id) { + if (id == null) { + throw new BadRequestException("Invalid id in CertResourceService.validateRequest."); + } + } + + @Override + public CertificateData getCert(CertId id) { + validateRequest(id); + + CertRetrievalRequestData data = new CertRetrievalRequestData(); + data.setCertId(id); + + CertificateData certData = null; + + try { + certData = getCert(data); + } catch (EDBRecordNotFoundException e) { + throw new CertNotFoundException(id); + } catch (EBaseException e) { + throw new CMSException("Problem returning certificate: " + id); + } catch (CertificateEncodingException e) { + throw new CMSException("Problem encoding certificate searched for: " + id); + } + + return certData; + } + + @Override + public CertRequestInfo revokeCACert(CertId id, CertRevokeRequest request) { + return revokeCert(id, request, true); + } + + @Override + public CertRequestInfo revokeCert(CertId id, CertRevokeRequest request) { + return revokeCert(id, request, false); + } + + public CertRequestInfo revokeCert(CertId id, CertRevokeRequest request, boolean caCert) { + 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()); + 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 CMSException(e.getMessage()); + } + + try { + X509Certificate clientCert = null; + try { + clientCert = Processor.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")); + } + } + + // Find target cert record if different from client cert. + ICertRecord targetRecord = id.equals(clientSerialNumber) ? clientRecord : processor.getCertificateRecord(id); + X509CertImpl targetCert = targetRecord.getCertificate(); + + processor.createCRLExtension(); + processor.validateCertificateToRevoke(clientSubjectDN, targetRecord, caCert); + processor.addCertificateToRevoke(targetCert); + processor.createRevocationRequest(); + + processor.auditChangeRequest(ILogger.SUCCESS); + + } catch (CMSException 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 CMSException(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 CMSException(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 CMSException(e.getMessage()); + } + + try { + IRequest certRequest = processor.getRequest(); + CertRequestDAO dao = new CertRequestDAO(); + return dao.getRequest(certRequest.getRequestId(), uriInfo); + + } catch (EBaseException e) { + throw new CMSException(e.getMessage()); + } + } + + @Override + public CertRequestInfo unrevokeCert(CertId id, CertUnrevokeRequest request) { + RevocationProcessor processor; + try { + processor = new RevocationProcessor("caDoUnrevoke", getLocale()); + + // 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 CMSException(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 CMSException(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 CMSException(e.getMessage()); + } + + try { + IRequest certRequest = processor.getRequest(); + CertRequestDAO dao = new CertRequestDAO(); + return dao.getRequest(certRequest.getRequestId(), uriInfo); + + } catch (EBaseException e) { + throw new CMSException(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(CertSearchData data) { + if (data == null) { + return null; + } + + return data.buildFilter(); + } + + @Override + public CertDataInfos listCerts(String status, int maxResults, int maxTime) { + // get ldap filter + String filter = createSearchFilter(status); + CMS.debug("listKeys: filter is " + filter); + + CertDataInfos infos; + try { + infos = getCertList(filter, maxResults, maxTime); + } catch (EBaseException e) { + e.printStackTrace(); + throw new CMSException("Error listing certs in CertsResourceService.listCerts!"); + } + return infos; + } + + @Override + public CertDataInfos searchCerts(CertSearchData data, Integer start, Integer size) { + if (data == null) { + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + start = start == null ? 0 : start; + size = size == null ? DEFAULT_SIZE : size; + String filter = createSearchFilter(data); + + CertDataInfos infos = new CertDataInfos(); + + Enumeration e = null; + try { + + e = repo.findCertRecords(filter); + + 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.addCertData(createCertDataInfo(user)); + } + + // count the total entries + for (; e.hasMoreElements(); i++) + e.nextElement(); + + 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 (EBaseException e1) { + throw new CMSException("Error listing certs in CertsResourceService.listCerts!" + e.toString()); + } + + return infos; + } + + /** + * Returns list of certs meeting specified search filter. + * Currently, vlv searches are not used for certs. + * + * @param filter + * @param maxResults + * @param maxTime + * @param uriInfo + * @return + * @throws EBaseException + */ + private CertDataInfos getCertList(String filter, int maxResults, int maxTime) + throws EBaseException { + List list = new ArrayList(); + Enumeration e = null; + + e = repo.searchCertificates(filter, maxResults, maxTime); + if (e == null) { + throw new EBaseException("search results are null"); + } + + while (e.hasMoreElements()) { + ICertRecord rec = e.nextElement(); + if (rec != null) { + list.add(createCertDataInfo(rec)); + } + } + + CertDataInfos ret = new CertDataInfos(); + ret.setCertInfos(list); + + return ret; + } + + public CertificateData getCert(CertRetrievalRequestData data) throws EBaseException, CertificateEncodingException { + CertId certId = data.getCertId(); + + //find the cert in question + ICertRecord record = repo.readCertificateRecord(certId.toBigInteger()); + X509CertImpl cert = record.getCertificate(); + + CertificateData certData = new CertificateData(); + + 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())); + + 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()); + + 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 { + 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()); + + 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/common/src/com/netscape/cms/servlet/cert/EnrollmentProcessor.java b/base/common/src/com/netscape/cms/servlet/cert/EnrollmentProcessor.java index 8b48f0d73..c1841051b 100644 --- a/base/common/src/com/netscape/cms/servlet/cert/EnrollmentProcessor.java +++ b/base/common/src/com/netscape/cms/servlet/cert/EnrollmentProcessor.java @@ -39,7 +39,7 @@ import com.netscape.cms.servlet.common.CMSRequest; import com.netscape.cms.servlet.profile.SSLClientCertProvider; import com.netscape.cms.servlet.profile.model.ProfileInput; import com.netscape.cms.servlet.request.model.EnrollmentRequestData; -import com.netscape.cms.servlet.request.model.EnrollmentRequestDataFactory; +import com.netscape.cms.servlet.request.model.CertEnrollmentRequestFactory; public class EnrollmentProcessor extends CertProcessor { @@ -97,7 +97,7 @@ public class EnrollmentProcessor extends CertProcessor { throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", profileId)); } - EnrollmentRequestData data = EnrollmentRequestDataFactory.create(cmsReq, profile, locale); + EnrollmentRequestData data = CertEnrollmentRequestFactory.create(cmsReq, profile, locale); return processEnrollment(data, cmsReq.getHttpReq()); } diff --git a/base/common/src/com/netscape/cms/servlet/cert/RenewalProcessor.java b/base/common/src/com/netscape/cms/servlet/cert/RenewalProcessor.java index cc4dd12ae..3e6c77fbf 100644 --- a/base/common/src/com/netscape/cms/servlet/cert/RenewalProcessor.java +++ b/base/common/src/com/netscape/cms/servlet/cert/RenewalProcessor.java @@ -45,7 +45,7 @@ import com.netscape.certsrv.request.IRequest; import com.netscape.cms.servlet.common.CMSRequest; import com.netscape.cms.servlet.profile.SSLClientCertProvider; import com.netscape.cms.servlet.request.model.EnrollmentRequestData; -import com.netscape.cms.servlet.request.model.EnrollmentRequestDataFactory; +import com.netscape.cms.servlet.request.model.CertEnrollmentRequestFactory; public class RenewalProcessor extends CertProcessor { @@ -61,7 +61,7 @@ public class RenewalProcessor extends CertProcessor { throw new BadRequestDataException(CMS.getUserMessage(locale, "CMS_PROFILE_NOT_FOUND", profileId)); } - EnrollmentRequestData data = EnrollmentRequestDataFactory.create(cmsReq, profile, locale); + EnrollmentRequestData data = CertEnrollmentRequestFactory.create(cmsReq, profile, locale); //only used in renewal data.setSerialNum(req.getParameter("serial_num")); diff --git a/base/common/src/com/netscape/cms/servlet/cert/RequestProcessor.java b/base/common/src/com/netscape/cms/servlet/cert/RequestProcessor.java index 57e33f3a5..8822be2b2 100644 --- a/base/common/src/com/netscape/cms/servlet/cert/RequestProcessor.java +++ b/base/common/src/com/netscape/cms/servlet/cert/RequestProcessor.java @@ -58,7 +58,7 @@ import com.netscape.cms.servlet.profile.model.ProfileOutput; import com.netscape.cms.servlet.profile.model.ProfileOutputFactory; import com.netscape.cms.servlet.profile.model.ProfilePolicySet; import com.netscape.cms.servlet.request.model.AgentEnrollmentRequestData; -import com.netscape.cms.servlet.request.model.AgentEnrollmentRequestDataFactory; +import com.netscape.cms.servlet.request.model.CertReviewResponseFactory; public class RequestProcessor extends CertProcessor { @@ -72,7 +72,7 @@ public class RequestProcessor extends CertProcessor { String profileId = ireq.getExtDataInString("profileId"); IProfile profile = ps.getProfile(profileId); - AgentEnrollmentRequestData data = AgentEnrollmentRequestDataFactory.create(cmsReq, profile, nonces, locale); + AgentEnrollmentRequestData data = CertReviewResponseFactory.create(cmsReq, profile, nonces, locale); processRequest(req, data, request, op); return data; diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java b/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java new file mode 100644 index 000000000..cee8e86e3 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigService.java @@ -0,0 +1,948 @@ +// --- 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.InetAddress; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.UnknownHostException; +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.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +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.EBaseException; +import com.netscape.certsrv.base.EPropertyNotFound; +import com.netscape.certsrv.base.IConfigStore; +import com.netscape.certsrv.base.ISecurityDomainSessionTable; +import com.netscape.certsrv.ca.ICertificateAuthority; +import com.netscape.certsrv.dbs.certdb.ICertificateRepository; +import com.netscape.certsrv.ocsp.IOCSPAuthority; +import com.netscape.certsrv.usrgrp.IUGSubsystem; +import com.netscape.certsrv.usrgrp.IUser; +import com.netscape.cms.servlet.base.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cms.servlet.csadmin.model.CertData; +import com.netscape.cms.servlet.csadmin.model.ConfigurationData; +import com.netscape.cms.servlet.csadmin.model.ConfigurationResponseData; +import com.netscape.cms.servlet.csadmin.model.DomainInfo; +import com.netscape.cms.servlet.csadmin.model.InstallToken; +import com.netscape.cms.servlet.csadmin.model.InstallTokenRequest; +import com.netscape.cmsutil.crypto.CryptoUtil; +import com.netscape.cmsutil.util.Utils; + +/** + * @author alee + * + */ +public class SystemConfigService extends PKIService implements SystemConfigurationResource { + IConfigStore cs; + String csType; + String csState; + boolean isMasterCA = false; + String instanceRoot; + + public static String SUCCESS = "0"; + public static final String RESTART_SERVER_AFTER_CONFIGURATION = + "restart_server_after_configuration"; + private Random random = null; + + public SystemConfigService() throws EPropertyNotFound, EBaseException { + cs = CMS.getConfigStore(); + csType = cs.getString("cs.type"); + 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"); + random = new Random(); + } + + /* (non-Javadoc) + * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(javax.ws.rs.core.MultivaluedMap) + */ + @Override + public ConfigurationResponseData configure(MultivaluedMap form) { + ConfigurationData data = new ConfigurationData(form); + return configure(data); + } + + /* (non-Javadoc) + * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(com.netscape.cms.servlet.csadmin.data.ConfigurationData) + */ + @Override + public ConfigurationResponseData configure(ConfigurationData data){ + if (csState.equals("1")) { + throw new CMSException(Response.Status.BAD_REQUEST, "System is already configured"); + } + + String certList; + try { + certList = cs.getString("preop.cert.list"); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Unable to get certList from config file"); + } + + validateData(data); + ConfigurationResponseData response = new ConfigurationResponseData(); + + // specify module and log into token + String token = data.getToken(); + if (token == null) { + token = ConfigurationData.TOKEN_DEFAULT; + } + cs.putString("preop.module.token", token); + + if (! token.equals(ConfigurationData.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 CMSException("Token is not initialized"); + } catch (NoSuchTokenException e) { + throw new CMSException(Response.Status.BAD_REQUEST, "Invalid Token provided. No such token."); + } catch (TokenException e) { + e.printStackTrace(); + throw new CMSException("Token Exception" + e); + } catch (IncorrectPasswordException e) { + throw new CMSException(Response.Status.BAD_REQUEST, "Incorrect Password provided for token."); + } + } + + //configure security domain + String securityDomainType = data.getSecurityDomainType(); + String securityDomainName = data.getSecurityDomainName(); + String securityDomainURL = data.getSecurityDomainUri(); + String domainXML = null; + if (securityDomainType.equals(ConfigurationData.NEW_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()); + cs.putString("preop.cert.subsystem.type", "local"); + cs.putString("preop.cert.subsystem.profile", "subsystemCert.profile"); + } else { + 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"); + + // 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 CMSException("Failed to import certificate chain from security domain master: " + e); + } + + // 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 CMSException("Failed to obtain installation token from security domain: " + e); + } + + if (installToken == null) { + throw new CMSException("Failed to obtain installation token from security domain"); + } + CMS.setConfigSDSessionId(installToken); + + try { + domainXML = ConfigurationUtils.getDomainXML(host, port, true); + ConfigurationUtils.getSecurityDomainPorts(domainXML, host, port); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Failed to obtain security domain decriptor from security domain master: " + e); + } + } + + 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"); + + 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 CMSException("Error in determining whether clone URI is valid"); + } + + if (!validCloneUri) { + throw new CMSException(Response.Status.BAD_REQUEST, + "Invalid clone URI provided. Does not match the available subsystems in the security domain"); + } + + if (csType.equals("CA")) { + try { + ConfigurationUtils.importCertChain(masterHost, masterPort, "/ca/ee/ca/getCertChain", "clone"); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Failed to import certificate chain from master" + e); + } + } + + try { + ConfigurationUtils.getConfigEntriesFromMaster(); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Failed to obtain configuration entries from the master for cloning " + e); + } + + // restore certs from P12 file + if (token.equals(ConfigurationData.TOKEN_DEFAULT)) { + String p12File = data.getP12File(); + String p12Pass = data.getP12Password(); + try { + ConfigurationUtils.restoreCertsFromP12(p12File, p12Pass); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("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 CMSException("Clone does not have all the required certificates"); + } + } + + // Hierarchy Panel + 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 CMSException(Response.Status.BAD_REQUEST, "Invalid hierarchy provided"); + } + } + + // Database Panel + 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()); + + try { + cs.commit(false); + } catch (EBaseException e2) { + e2.printStackTrace(); + throw new CMSException("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 CMSException(Response.Status.BAD_REQUEST, + "Master and clone must not share the same internal database"); + } + + if (!masterbasedn.equals(data.getBaseDN())) { + throw new CMSException(Response.Status.BAD_REQUEST, "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); + } + + 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); + + ConfigurationUtils.populateDB(); + + cs.putString("preop.internaldb.replicationpwd", replicationpwd); + cs.putString("preop.database.removeData", "false"); + cs.commit(false); + + ConfigurationUtils.reInitSubsystem(csType); + ConfigurationUtils.populateIndexes(); + + if (data.getIsClone().equals("true")) { + CMS.debug("Start setting up replication."); + ConfigurationUtils.setupReplication(); + ConfigurationUtils.reInitSubsystem(csType); + } + } catch (Exception e) { + throw new CMSException("Error in populating database" + e); + } + + // SizePanel, NamePanel, CertRequestPanel + //handle the CA URL + 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 CMSException("Error in obtaining certificate chain from issuing CA: " + e); + } + + boolean hasSigningCert = false; + Vector certs = new Vector(); + try { + StringTokenizer t = new StringTokenizer(certList, ","); + while (t.hasMoreTokens()) { + String ct = t.nextToken(); + boolean enable = cs.getBoolean("preop.cert." + ct + ".enable", true); + if (!enable) continue; + + Collection certData = data.getSystemCerts(); + Iterator iterator = certData.iterator(); + CertData cdata = null; + while (iterator.hasNext()) { + cdata = iterator.next(); + if (cdata.getTag().equals(ct)) break; + } + + 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() == null) { + 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"); + } + + 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() == null) { + ConfigurationUtils.configCert(null, null, null, certObj, null); + } else { + String subsystem = cs.getString("preop.cert." + ct + ".subsystem"); + String certStr = cs.getString(subsystem + "." + ct + ".cert" ); + certObj.setCert(certStr); + CMS.debug("Step 2: certStr for " + ct + " is " + certStr); + } + 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 + String b64 = cdata.getCert(); + if (ct.equals("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 CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "Non-integer value for key size"); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + throw new CMSException(Response.Status.BAD_REQUEST, "Invalid algorithm " + e); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Error in setting certificate names and key sizes: " + e); + } + + // submitting to external ca + if ((data.getIssuingCA()!= null) && data.getIssuingCA().equals("External CA") && (!hasSigningCert)) { + response.setSystemCerts(certs); + return response; + } + + Enumeration c = certs.elements(); + while (c.hasMoreElements()) { + Cert cert = c.nextElement(); + int ret; + try { + ret = ConfigurationUtils.handleCerts(cert); + ConfigurationUtils.setCertPermissions(cert.getCertTag()); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Error in confguring system certificates" + e); + } + if (ret != 0) { + throw new CMSException("Error in confguring system certificates"); + } + } + response.setSystemCerts(certs); + + // BackupKeyCertPanel/SavePKCS12Panel + if (data.getBackupKeys().equals("true")) { + try { + ConfigurationUtils.backupKeys(data.getBackupPassword(), data.getBackupFile()); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Error in creating pkcs12 to backup keys and certs: " + e); + } + } + + // AdminPanel + if (!data.getIsClone().equals("true")) { + try { + X509CertImpl admincerts[] = new X509CertImpl[1]; + ConfigurationUtils.createAdmin(data.getAdminUID(), data.getAdminEmail(), + data.getAdminName(), data.getAdminPassword()); + 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 CMSException("Error in creating admin user: " + e); + } + } + + // Done Panel + // Create or update security domain + try { + if (securityDomainType.equals(ConfigurationData.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 CMSException("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") && (!ca_host.equals(""))) { + ConfigurationUtils.updateConnectorInfo(CMS.getAgentHost(), CMS.getAgentPort()); + ConfigurationUtils.setupClientAuthUser(); + } + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("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(); + ConfigurationUtils.updateOCSPConfig(); + ConfigurationUtils.setupClientAuthUser(); + } + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("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 CMSException("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 CMSException("Errors in determining if security domain host is a master CA"); + } + + try { + String dbuser = csType + "-" + CMS.getEEHost() + "-" + CMS.getEESSLPort(); + if (! securityDomainType.equals(ConfigurationData.NEW_DOMAIN)) { + ConfigurationUtils.setupDBUser(dbuser); + } + IUGSubsystem system = (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID)); + IUser user = system.getUser(dbuser); + system.addCertSubjectDN(user); + } catch (Exception e) { + e.printStackTrace(); + throw new CMSException("Errors in creating or updating dbuser: " + 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 CMSException("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 validateData(ConfigurationData 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 CMSException("Unable to retrieve required configuration from configuration files"); + } + + // get the preop pin and validate it + String pin = data.getPin(); + if (pin == null) { + throw new CMSException(Response.Status.BAD_REQUEST, "No preop pin provided"); + } + if (!preopPin.equals(pin)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Incorrect pin provided"); + } + + // validate security domain settings + String domainType = data.getSecurityDomainType(); + if (domainType == null) { + throw new CMSException(Response.Status.BAD_REQUEST, "Security Domain Type not provided"); + } + + if (domainType.equals(ConfigurationData.NEW_DOMAIN)) { + if (!csType.equals("CA")) { + throw new CMSException(Response.Status.BAD_REQUEST, "New Domain is only valid for CA subsytems"); + } + if (data.getSecurityDomainName() == null) { + throw new CMSException(Response.Status.BAD_REQUEST, "Security Domain Name is not provided"); + } + } else if (domainType.equals(ConfigurationData.EXISTING_DOMAIN)) { + String domainURI = data.getSecurityDomainUri(); + if (domainURI == null) { + throw new CMSException(Response.Status.BAD_REQUEST, + "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 CMSException(Response.Status.BAD_REQUEST, "Invalid security domain URI"); + } + if ((data.getSecurityDomainUser() == null) || (data.getSecurityDomainPassword() == null)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Security domain user or password not provided"); + } + + } else { + throw new CMSException(Response.Status.BAD_REQUEST, "Invalid security domain URI provided"); + } + + if ((data.getSubsystemName() == null) || (data.getSubsystemName().length() ==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Invalid or no subsystem name provided"); + } + + if ((data.getIsClone() != null) && (data.getIsClone().equals("true"))) { + String cloneUri = data.getCloneUri(); + if (cloneUri == null) { + throw new CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "Invalid clone URI"); + } + + if (data.getToken().equals(ConfigurationData.TOKEN_DEFAULT)) { + if (data.getP12File() == null) { + throw new CMSException(Response.Status.BAD_REQUEST, "P12 filename not provided"); + } + + if (data.getP12Password() == null) { + throw new CMSException(Response.Status.BAD_REQUEST, "P12 password not provided"); + } + } + } else { + data.setIsClone("false"); + } + + String dsHost = data.getDsHost(); + if (dsHost == null || dsHost.length() == 0) { + throw new CMSException(Response.Status.BAD_REQUEST, "Internal database host not provided"); + } + + try { + Integer.parseInt(data.getDsPort()); // check for errors + } catch (NumberFormatException e) { + throw new CMSException(Response.Status.BAD_REQUEST, "Internal database port is invalid"); + } + + String basedn = data.getBaseDN(); + if (basedn == null || basedn.length() == 0) { + throw new CMSException(Response.Status.BAD_REQUEST, "Internal database basedn not provided"); + } + + String binddn = data.getBindDN(); + if (binddn == null || binddn.length() == 0) { + throw new CMSException(Response.Status.BAD_REQUEST, "Internal database basedn not provided"); + } + + String database = data.getDatabase(); + if (database == null || database.length() == 0) { + throw new CMSException(Response.Status.BAD_REQUEST, "Internal database database name not provided"); + } + + String bindpwd = data.getBindpwd(); + if (bindpwd == null || bindpwd.length() == 0) { + throw new CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "Clone replication port is invalid"); + } + } + + 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 CMSException(Response.Status.BAD_REQUEST, "Invalid key backup file name"); + } + + if ((data.getBackupPassword() == null) || (data.getBackupPassword().length()<8)) { + throw new CMSException(Response.Status.BAD_REQUEST, "key backup password must be at least 8 characters"); + } + } else { + data.setBackupKeys("false"); + } + + if (csType.equals("CA") && (data.getHierarchy() == null)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Hierarchy is requred for CA, not provided"); + } + + if (data.getIsClone().equals("false")) { + if ((data.getAdminUID() == null) || (data.getAdminUID().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin UID not provided"); + } + if ((data.getAdminPassword() == null) || (data.getAdminPassword().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin Password not provided"); + } + if ((data.getAdminEmail() == null) || (data.getAdminEmail().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin UID not provided"); + } + if ((data.getAdminName() == null) || (data.getAdminName().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin name not provided"); + } + if ((data.getAdminCertRequest() == null) || (data.getAdminCertRequest().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin cert request not provided"); + } + if ((data.getAdminCertRequestType() == null) || (data.getAdminCertRequestType().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin cert request type not provided"); + } + if ((data.getAdminSubjectDN() == null) || (data.getAdminSubjectDN().length()==0)) { + throw new CMSException(Response.Status.BAD_REQUEST, "Admin subjectDN not provided"); + } + } + + } + + @Override + public InstallToken getInstallToken(InstallTokenRequest data) { + // TODO Figure out how to do authentication here based on user/pass + // For now, allow all user/pass to be valid + CMS.debug("getInstallToken(): starting"); + String user = data.getUser(); + String host = data.getHost(); + String subsystem = data.getSubsystem(); + String groupname = ConfigurationUtils.getGroupName(user, subsystem); + + // assign cookie + long num = random.nextLong(); + String cookie = num + ""; + ISecurityDomainSessionTable ctable = CMS.getSecurityDomainSessionTable(); + String ip; + try { + ip = InetAddress.getByName(host).toString(); + } catch (UnknownHostException e) { + throw new CMSException(Response.Status.BAD_REQUEST, "Unable to resolve host " + host + + "to an IP address: " + e); + } + int index = ip.indexOf("/"); + if (index > 0) ip = ip.substring(index + 1); + + ctable.addEntry(cookie, ip, user, groupname); + + return new InstallToken(cookie); + } + + @Override + public DomainInfo getDomainInfo() { + // TODO Auto-generated method stub for a RESTful method that returns the security domain + return null; + } + +} diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigurationResourceService.java b/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigurationResourceService.java deleted file mode 100644 index 9747eb12c..000000000 --- a/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigurationResourceService.java +++ /dev/null @@ -1,948 +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.InetAddress; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.UnknownHostException; -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.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -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.EBaseException; -import com.netscape.certsrv.base.EPropertyNotFound; -import com.netscape.certsrv.base.IConfigStore; -import com.netscape.certsrv.base.ISecurityDomainSessionTable; -import com.netscape.certsrv.ca.ICertificateAuthority; -import com.netscape.certsrv.dbs.certdb.ICertificateRepository; -import com.netscape.certsrv.ocsp.IOCSPAuthority; -import com.netscape.certsrv.usrgrp.IUGSubsystem; -import com.netscape.certsrv.usrgrp.IUser; -import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cms.servlet.csadmin.model.CertData; -import com.netscape.cms.servlet.csadmin.model.ConfigurationData; -import com.netscape.cms.servlet.csadmin.model.ConfigurationResponseData; -import com.netscape.cms.servlet.csadmin.model.DomainInfo; -import com.netscape.cms.servlet.csadmin.model.InstallToken; -import com.netscape.cms.servlet.csadmin.model.InstallTokenRequest; -import com.netscape.cmsutil.crypto.CryptoUtil; -import com.netscape.cmsutil.util.Utils; - -/** - * @author alee - * - */ -public class SystemConfigurationResourceService extends CMSResourceService implements SystemConfigurationResource { - IConfigStore cs; - String csType; - String csState; - boolean isMasterCA = false; - String instanceRoot; - - public static String SUCCESS = "0"; - public static final String RESTART_SERVER_AFTER_CONFIGURATION = - "restart_server_after_configuration"; - private Random random = null; - - public SystemConfigurationResourceService() throws EPropertyNotFound, EBaseException { - cs = CMS.getConfigStore(); - csType = cs.getString("cs.type"); - 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"); - random = new Random(); - } - - /* (non-Javadoc) - * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(javax.ws.rs.core.MultivaluedMap) - */ - @Override - public ConfigurationResponseData configure(MultivaluedMap form) { - ConfigurationData data = new ConfigurationData(form); - return configure(data); - } - - /* (non-Javadoc) - * @see com.netscape.cms.servlet.csadmin.SystemConfigurationResource#configure(com.netscape.cms.servlet.csadmin.data.ConfigurationData) - */ - @Override - public ConfigurationResponseData configure(ConfigurationData data){ - if (csState.equals("1")) { - throw new CMSException(Response.Status.BAD_REQUEST, "System is already configured"); - } - - String certList; - try { - certList = cs.getString("preop.cert.list"); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Unable to get certList from config file"); - } - - validateData(data); - ConfigurationResponseData response = new ConfigurationResponseData(); - - // specify module and log into token - String token = data.getToken(); - if (token == null) { - token = ConfigurationData.TOKEN_DEFAULT; - } - cs.putString("preop.module.token", token); - - if (! token.equals(ConfigurationData.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 CMSException("Token is not initialized"); - } catch (NoSuchTokenException e) { - throw new CMSException(Response.Status.BAD_REQUEST, "Invalid Token provided. No such token."); - } catch (TokenException e) { - e.printStackTrace(); - throw new CMSException("Token Exception" + e); - } catch (IncorrectPasswordException e) { - throw new CMSException(Response.Status.BAD_REQUEST, "Incorrect Password provided for token."); - } - } - - //configure security domain - String securityDomainType = data.getSecurityDomainType(); - String securityDomainName = data.getSecurityDomainName(); - String securityDomainURL = data.getSecurityDomainUri(); - String domainXML = null; - if (securityDomainType.equals(ConfigurationData.NEW_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()); - cs.putString("preop.cert.subsystem.type", "local"); - cs.putString("preop.cert.subsystem.profile", "subsystemCert.profile"); - } else { - 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"); - - // 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 CMSException("Failed to import certificate chain from security domain master: " + e); - } - - // 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 CMSException("Failed to obtain installation token from security domain: " + e); - } - - if (installToken == null) { - throw new CMSException("Failed to obtain installation token from security domain"); - } - CMS.setConfigSDSessionId(installToken); - - try { - domainXML = ConfigurationUtils.getDomainXML(host, port, true); - ConfigurationUtils.getSecurityDomainPorts(domainXML, host, port); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Failed to obtain security domain decriptor from security domain master: " + e); - } - } - - 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"); - - 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 CMSException("Error in determining whether clone URI is valid"); - } - - if (!validCloneUri) { - throw new CMSException(Response.Status.BAD_REQUEST, - "Invalid clone URI provided. Does not match the available subsystems in the security domain"); - } - - if (csType.equals("CA")) { - try { - ConfigurationUtils.importCertChain(masterHost, masterPort, "/ca/ee/ca/getCertChain", "clone"); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Failed to import certificate chain from master" + e); - } - } - - try { - ConfigurationUtils.getConfigEntriesFromMaster(); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Failed to obtain configuration entries from the master for cloning " + e); - } - - // restore certs from P12 file - if (token.equals(ConfigurationData.TOKEN_DEFAULT)) { - String p12File = data.getP12File(); - String p12Pass = data.getP12Password(); - try { - ConfigurationUtils.restoreCertsFromP12(p12File, p12Pass); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("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 CMSException("Clone does not have all the required certificates"); - } - } - - // Hierarchy Panel - 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 CMSException(Response.Status.BAD_REQUEST, "Invalid hierarchy provided"); - } - } - - // Database Panel - 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()); - - try { - cs.commit(false); - } catch (EBaseException e2) { - e2.printStackTrace(); - throw new CMSException("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 CMSException(Response.Status.BAD_REQUEST, - "Master and clone must not share the same internal database"); - } - - if (!masterbasedn.equals(data.getBaseDN())) { - throw new CMSException(Response.Status.BAD_REQUEST, "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); - } - - 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); - - ConfigurationUtils.populateDB(); - - cs.putString("preop.internaldb.replicationpwd", replicationpwd); - cs.putString("preop.database.removeData", "false"); - cs.commit(false); - - ConfigurationUtils.reInitSubsystem(csType); - ConfigurationUtils.populateIndexes(); - - if (data.getIsClone().equals("true")) { - CMS.debug("Start setting up replication."); - ConfigurationUtils.setupReplication(); - ConfigurationUtils.reInitSubsystem(csType); - } - } catch (Exception e) { - throw new CMSException("Error in populating database" + e); - } - - // SizePanel, NamePanel, CertRequestPanel - //handle the CA URL - 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 CMSException("Error in obtaining certificate chain from issuing CA: " + e); - } - - boolean hasSigningCert = false; - Vector certs = new Vector(); - try { - StringTokenizer t = new StringTokenizer(certList, ","); - while (t.hasMoreTokens()) { - String ct = t.nextToken(); - boolean enable = cs.getBoolean("preop.cert." + ct + ".enable", true); - if (!enable) continue; - - Collection certData = data.getSystemCerts(); - Iterator iterator = certData.iterator(); - CertData cdata = null; - while (iterator.hasNext()) { - cdata = iterator.next(); - if (cdata.getTag().equals(ct)) break; - } - - 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() == null) { - 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"); - } - - 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() == null) { - ConfigurationUtils.configCert(null, null, null, certObj, null); - } else { - String subsystem = cs.getString("preop.cert." + ct + ".subsystem"); - String certStr = cs.getString(subsystem + "." + ct + ".cert" ); - certObj.setCert(certStr); - CMS.debug("Step 2: certStr for " + ct + " is " + certStr); - } - 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 - String b64 = cdata.getCert(); - if (ct.equals("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 CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "Non-integer value for key size"); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - throw new CMSException(Response.Status.BAD_REQUEST, "Invalid algorithm " + e); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Error in setting certificate names and key sizes: " + e); - } - - // submitting to external ca - if ((data.getIssuingCA()!= null) && data.getIssuingCA().equals("External CA") && (!hasSigningCert)) { - response.setSystemCerts(certs); - return response; - } - - Enumeration c = certs.elements(); - while (c.hasMoreElements()) { - Cert cert = c.nextElement(); - int ret; - try { - ret = ConfigurationUtils.handleCerts(cert); - ConfigurationUtils.setCertPermissions(cert.getCertTag()); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Error in confguring system certificates" + e); - } - if (ret != 0) { - throw new CMSException("Error in confguring system certificates"); - } - } - response.setSystemCerts(certs); - - // BackupKeyCertPanel/SavePKCS12Panel - if (data.getBackupKeys().equals("true")) { - try { - ConfigurationUtils.backupKeys(data.getBackupPassword(), data.getBackupFile()); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Error in creating pkcs12 to backup keys and certs: " + e); - } - } - - // AdminPanel - if (!data.getIsClone().equals("true")) { - try { - X509CertImpl admincerts[] = new X509CertImpl[1]; - ConfigurationUtils.createAdmin(data.getAdminUID(), data.getAdminEmail(), - data.getAdminName(), data.getAdminPassword()); - 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 CMSException("Error in creating admin user: " + e); - } - } - - // Done Panel - // Create or update security domain - try { - if (securityDomainType.equals(ConfigurationData.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 CMSException("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") && (!ca_host.equals(""))) { - ConfigurationUtils.updateConnectorInfo(CMS.getAgentHost(), CMS.getAgentPort()); - ConfigurationUtils.setupClientAuthUser(); - } - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("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(); - ConfigurationUtils.updateOCSPConfig(); - ConfigurationUtils.setupClientAuthUser(); - } - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("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 CMSException("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 CMSException("Errors in determining if security domain host is a master CA"); - } - - try { - String dbuser = csType + "-" + CMS.getEEHost() + "-" + CMS.getEESSLPort(); - if (! securityDomainType.equals(ConfigurationData.NEW_DOMAIN)) { - ConfigurationUtils.setupDBUser(dbuser); - } - IUGSubsystem system = (IUGSubsystem) (CMS.getSubsystem(IUGSubsystem.ID)); - IUser user = system.getUser(dbuser); - system.addCertSubjectDN(user); - } catch (Exception e) { - e.printStackTrace(); - throw new CMSException("Errors in creating or updating dbuser: " + 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 CMSException("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 validateData(ConfigurationData 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 CMSException("Unable to retrieve required configuration from configuration files"); - } - - // get the preop pin and validate it - String pin = data.getPin(); - if (pin == null) { - throw new CMSException(Response.Status.BAD_REQUEST, "No preop pin provided"); - } - if (!preopPin.equals(pin)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Incorrect pin provided"); - } - - // validate security domain settings - String domainType = data.getSecurityDomainType(); - if (domainType == null) { - throw new CMSException(Response.Status.BAD_REQUEST, "Security Domain Type not provided"); - } - - if (domainType.equals(ConfigurationData.NEW_DOMAIN)) { - if (!csType.equals("CA")) { - throw new CMSException(Response.Status.BAD_REQUEST, "New Domain is only valid for CA subsytems"); - } - if (data.getSecurityDomainName() == null) { - throw new CMSException(Response.Status.BAD_REQUEST, "Security Domain Name is not provided"); - } - } else if (domainType.equals(ConfigurationData.EXISTING_DOMAIN)) { - String domainURI = data.getSecurityDomainUri(); - if (domainURI == null) { - throw new CMSException(Response.Status.BAD_REQUEST, - "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 CMSException(Response.Status.BAD_REQUEST, "Invalid security domain URI"); - } - if ((data.getSecurityDomainUser() == null) || (data.getSecurityDomainPassword() == null)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Security domain user or password not provided"); - } - - } else { - throw new CMSException(Response.Status.BAD_REQUEST, "Invalid security domain URI provided"); - } - - if ((data.getSubsystemName() == null) || (data.getSubsystemName().length() ==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Invalid or no subsystem name provided"); - } - - if ((data.getIsClone() != null) && (data.getIsClone().equals("true"))) { - String cloneUri = data.getCloneUri(); - if (cloneUri == null) { - throw new CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "Invalid clone URI"); - } - - if (data.getToken().equals(ConfigurationData.TOKEN_DEFAULT)) { - if (data.getP12File() == null) { - throw new CMSException(Response.Status.BAD_REQUEST, "P12 filename not provided"); - } - - if (data.getP12Password() == null) { - throw new CMSException(Response.Status.BAD_REQUEST, "P12 password not provided"); - } - } - } else { - data.setIsClone("false"); - } - - String dsHost = data.getDsHost(); - if (dsHost == null || dsHost.length() == 0) { - throw new CMSException(Response.Status.BAD_REQUEST, "Internal database host not provided"); - } - - try { - Integer.parseInt(data.getDsPort()); // check for errors - } catch (NumberFormatException e) { - throw new CMSException(Response.Status.BAD_REQUEST, "Internal database port is invalid"); - } - - String basedn = data.getBaseDN(); - if (basedn == null || basedn.length() == 0) { - throw new CMSException(Response.Status.BAD_REQUEST, "Internal database basedn not provided"); - } - - String binddn = data.getBindDN(); - if (binddn == null || binddn.length() == 0) { - throw new CMSException(Response.Status.BAD_REQUEST, "Internal database basedn not provided"); - } - - String database = data.getDatabase(); - if (database == null || database.length() == 0) { - throw new CMSException(Response.Status.BAD_REQUEST, "Internal database database name not provided"); - } - - String bindpwd = data.getBindpwd(); - if (bindpwd == null || bindpwd.length() == 0) { - throw new CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "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 CMSException(Response.Status.BAD_REQUEST, "Clone replication port is invalid"); - } - } - - 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 CMSException(Response.Status.BAD_REQUEST, "Invalid key backup file name"); - } - - if ((data.getBackupPassword() == null) || (data.getBackupPassword().length()<8)) { - throw new CMSException(Response.Status.BAD_REQUEST, "key backup password must be at least 8 characters"); - } - } else { - data.setBackupKeys("false"); - } - - if (csType.equals("CA") && (data.getHierarchy() == null)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Hierarchy is requred for CA, not provided"); - } - - if (data.getIsClone().equals("false")) { - if ((data.getAdminUID() == null) || (data.getAdminUID().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin UID not provided"); - } - if ((data.getAdminPassword() == null) || (data.getAdminPassword().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin Password not provided"); - } - if ((data.getAdminEmail() == null) || (data.getAdminEmail().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin UID not provided"); - } - if ((data.getAdminName() == null) || (data.getAdminName().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin name not provided"); - } - if ((data.getAdminCertRequest() == null) || (data.getAdminCertRequest().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin cert request not provided"); - } - if ((data.getAdminCertRequestType() == null) || (data.getAdminCertRequestType().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin cert request type not provided"); - } - if ((data.getAdminSubjectDN() == null) || (data.getAdminSubjectDN().length()==0)) { - throw new CMSException(Response.Status.BAD_REQUEST, "Admin subjectDN not provided"); - } - } - - } - - @Override - public InstallToken getInstallToken(InstallTokenRequest data) { - // TODO Figure out how to do authentication here based on user/pass - // For now, allow all user/pass to be valid - CMS.debug("getInstallToken(): starting"); - String user = data.getUser(); - String host = data.getHost(); - String subsystem = data.getSubsystem(); - String groupname = ConfigurationUtils.getGroupName(user, subsystem); - - // assign cookie - long num = random.nextLong(); - String cookie = num + ""; - ISecurityDomainSessionTable ctable = CMS.getSecurityDomainSessionTable(); - String ip; - try { - ip = InetAddress.getByName(host).toString(); - } catch (UnknownHostException e) { - throw new CMSException(Response.Status.BAD_REQUEST, "Unable to resolve host " + host + - "to an IP address: " + e); - } - int index = ip.indexOf("/"); - if (index > 0) ip = ip.substring(index + 1); - - ctable.addEntry(cookie, ip, user, groupname); - - return new InstallToken(cookie); - } - - @Override - public DomainInfo getDomainInfo() { - // TODO Auto-generated method stub for a RESTful method that returns the security domain - return null; - } - -} diff --git a/base/common/src/com/netscape/cms/servlet/key/KeyResourceService.java b/base/common/src/com/netscape/cms/servlet/key/KeyResourceService.java deleted file mode 100644 index 560d7f9f8..000000000 --- a/base/common/src/com/netscape/cms/servlet/key/KeyResourceService.java +++ /dev/null @@ -1,319 +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.util.ArrayList; -import java.util.Enumeration; -import java.util.Hashtable; -import java.util.List; - -import javax.ws.rs.Path; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriBuilder; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.base.EBaseException; -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.kra.IKeyRecoveryAuthority; -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.CMSResourceService; -import com.netscape.cms.servlet.key.model.KeyData; -import com.netscape.cms.servlet.key.model.KeyDataInfo; -import com.netscape.cms.servlet.key.model.KeyDataInfos; -import com.netscape.cms.servlet.request.model.KeyRequestDAO; -import com.netscape.cms.servlet.request.model.KeyRequestInfo; -import com.netscape.cms.servlet.request.model.RecoveryRequestData; -import com.netscape.cmsutil.ldap.LDAPUtil; - -/** - * @author alee - * - */ -public class KeyResourceService extends CMSResourceService implements KeyResource{ - - private IKeyRepository repo; - private IKeyRecoveryAuthority kra; - private IRequestQueue queue; - - public KeyResourceService() { - kra = ( IKeyRecoveryAuthority ) CMS.getSubsystem( "kra" ); - repo = kra.getKeyRepository(); - queue = kra.getRequestQueue(); - } - - /** - * Used to retrieve a key - * @param data - * @return - */ - public KeyData retrieveKey(RecoveryRequestData data) { - // auth and authz - KeyId keyId = validateRequest(data); - KeyData keyData; - try { - keyData = getKey(keyId, data); - } catch (EBaseException e) { - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - if (keyData == null) { - // no key record - throw new WebApplicationException(Response.Status.GONE); - } - return keyData; - } - - // retrieval - used to test integration with a browser - public KeyData retrieveKey(MultivaluedMap form) { - RecoveryRequestData data = new RecoveryRequestData(form); - return retrieveKey(data); - } - - public KeyData getKey(KeyId keyId, RecoveryRequestData 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 requestParams = kra.getVolatileRequest( - request.getRequestId()); - - if(requestParams == null) { - 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. - 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); - } - - kra.destroyVolatileRequest(request.getRequestId()); - - queue.markAsServiced(request); - - return keyData; - } - - private KeyId validateRequest(RecoveryRequestData data) { - - // confirm request exists - RequestId reqId = data.getRequestId(); - if (reqId == null) { - // log error - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - - // confirm that at least one wrapping method exists - // There must be at least the wrapped session key method. - if ((data.getTransWrappedSessionKey() == null)) { - // log error - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - - KeyRequestDAO reqDAO = new KeyRequestDAO(); - KeyRequestInfo reqInfo; - try { - reqInfo = reqDAO.getRequest(reqId, uriInfo); - } catch (EBaseException e1) { - // failed to get request - e1.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - if (reqInfo == null) { - // request not found - throw new WebApplicationException(Response.Status.GONE); - } - - //confirm request is of the right type - String type = reqInfo.getRequestType(); - if (!type.equals(IRequest.SECURITY_DATA_RECOVERY_REQUEST)) { - // log error - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - - //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)) { - // log error - throw new WebApplicationException(Response.Status.UNAUTHORIZED); - } - - return reqInfo.getKeyId(); - } - - /** - * Used to generate list of key infos based on the search parameters - */ - public KeyDataInfos listKeys(String clientID, String status, int maxResults, int maxTime) { - // auth and authz - - // get ldap filter - String filter = createSearchFilter(status, clientID); - CMS.debug("listKeys: filter is " + filter); - - KeyDataInfos infos = new KeyDataInfos(); - try { - List list = new ArrayList(); - Enumeration e = null; - - e = repo.searchKeys(filter, maxResults, maxTime); - if (e == null) { - throw new EBaseException("search results are null"); - } - - while (e.hasMoreElements()) { - IKeyRecord rec = e.nextElement(); - if (rec != null) { - list.add(createKeyDataInfo(rec)); - } - } - - infos.setKeyInfos(list); - } catch (EBaseException e) { - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - return infos; - } - - - public KeyDataInfo createKeyDataInfo(IKeyRecord rec) throws EBaseException { - KeyDataInfo ret = new KeyDataInfo(); - - 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 clientID) { - String filter = ""; - int matches = 0; - - if ((status == null) && (clientID == null)) { - filter = "(serialno=*)"; - return filter; - } - - if (status != null) { - filter += "(status=" + LDAPUtil.escapeFilter(status) + ")"; - matches ++; - } - - if (clientID != null) { - filter += "(clientID=" + LDAPUtil.escapeFilter(clientID) + ")"; - matches ++; - } - - if (matches > 1) { - filter = "(&" + filter + ")"; - } - - return filter; - } -} diff --git a/base/common/src/com/netscape/cms/servlet/key/KeyService.java b/base/common/src/com/netscape/cms/servlet/key/KeyService.java new file mode 100644 index 000000000..59847da1c --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/key/KeyService.java @@ -0,0 +1,319 @@ +// --- 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.util.ArrayList; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.List; + +import javax.ws.rs.Path; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.EBaseException; +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.kra.IKeyRecoveryAuthority; +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.cms.servlet.key.model.KeyData; +import com.netscape.cms.servlet.key.model.KeyDataInfo; +import com.netscape.cms.servlet.key.model.KeyDataInfos; +import com.netscape.cms.servlet.request.model.KeyRequestDAO; +import com.netscape.cms.servlet.request.model.KeyRequestInfo; +import com.netscape.cms.servlet.request.model.RecoveryRequestData; +import com.netscape.cmsutil.ldap.LDAPUtil; + +/** + * @author alee + * + */ +public class KeyService extends PKIService implements KeyResource{ + + private IKeyRepository repo; + private IKeyRecoveryAuthority kra; + private IRequestQueue queue; + + public KeyService() { + kra = ( IKeyRecoveryAuthority ) CMS.getSubsystem( "kra" ); + repo = kra.getKeyRepository(); + queue = kra.getRequestQueue(); + } + + /** + * Used to retrieve a key + * @param data + * @return + */ + public KeyData retrieveKey(RecoveryRequestData data) { + // auth and authz + KeyId keyId = validateRequest(data); + KeyData keyData; + try { + keyData = getKey(keyId, data); + } catch (EBaseException e) { + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + if (keyData == null) { + // no key record + throw new WebApplicationException(Response.Status.GONE); + } + return keyData; + } + + // retrieval - used to test integration with a browser + public KeyData retrieveKey(MultivaluedMap form) { + RecoveryRequestData data = new RecoveryRequestData(form); + return retrieveKey(data); + } + + public KeyData getKey(KeyId keyId, RecoveryRequestData 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 requestParams = kra.getVolatileRequest( + request.getRequestId()); + + if(requestParams == null) { + 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. + 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); + } + + kra.destroyVolatileRequest(request.getRequestId()); + + queue.markAsServiced(request); + + return keyData; + } + + private KeyId validateRequest(RecoveryRequestData data) { + + // confirm request exists + RequestId reqId = data.getRequestId(); + if (reqId == null) { + // log error + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + + // confirm that at least one wrapping method exists + // There must be at least the wrapped session key method. + if ((data.getTransWrappedSessionKey() == null)) { + // log error + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + + KeyRequestDAO reqDAO = new KeyRequestDAO(); + KeyRequestInfo reqInfo; + try { + reqInfo = reqDAO.getRequest(reqId, uriInfo); + } catch (EBaseException e1) { + // failed to get request + e1.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + if (reqInfo == null) { + // request not found + throw new WebApplicationException(Response.Status.GONE); + } + + //confirm request is of the right type + String type = reqInfo.getRequestType(); + if (!type.equals(IRequest.SECURITY_DATA_RECOVERY_REQUEST)) { + // log error + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + + //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)) { + // log error + throw new WebApplicationException(Response.Status.UNAUTHORIZED); + } + + return reqInfo.getKeyId(); + } + + /** + * Used to generate list of key infos based on the search parameters + */ + public KeyDataInfos listKeys(String clientID, String status, int maxResults, int maxTime) { + // auth and authz + + // get ldap filter + String filter = createSearchFilter(status, clientID); + CMS.debug("listKeys: filter is " + filter); + + KeyDataInfos infos = new KeyDataInfos(); + try { + List list = new ArrayList(); + Enumeration e = null; + + e = repo.searchKeys(filter, maxResults, maxTime); + if (e == null) { + throw new EBaseException("search results are null"); + } + + while (e.hasMoreElements()) { + IKeyRecord rec = e.nextElement(); + if (rec != null) { + list.add(createKeyDataInfo(rec)); + } + } + + infos.setKeyInfos(list); + } catch (EBaseException e) { + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + return infos; + } + + + public KeyDataInfo createKeyDataInfo(IKeyRecord rec) throws EBaseException { + KeyDataInfo ret = new KeyDataInfo(); + + 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 clientID) { + String filter = ""; + int matches = 0; + + if ((status == null) && (clientID == null)) { + filter = "(serialno=*)"; + return filter; + } + + if (status != null) { + filter += "(status=" + LDAPUtil.escapeFilter(status) + ")"; + matches ++; + } + + if (clientID != null) { + filter += "(clientID=" + LDAPUtil.escapeFilter(clientID) + ")"; + matches ++; + } + + if (matches > 1) { + filter = "(&" + filter + ")"; + } + + return filter; + } +} diff --git a/base/common/src/com/netscape/cms/servlet/profile/ProfileResourceService.java b/base/common/src/com/netscape/cms/servlet/profile/ProfileResourceService.java deleted file mode 100644 index c39125876..000000000 --- a/base/common/src/com/netscape/cms/servlet/profile/ProfileResourceService.java +++ /dev/null @@ -1,203 +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.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; - -import javax.ws.rs.Path; -import javax.ws.rs.core.UriBuilder; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.base.EBaseException; -import com.netscape.certsrv.profile.EProfileException; -import com.netscape.certsrv.profile.IProfile; -import com.netscape.certsrv.profile.IProfileInput; -import com.netscape.certsrv.profile.IProfileSubsystem; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cms.servlet.profile.model.ProfileData; -import com.netscape.cms.servlet.profile.model.ProfileDataInfo; -import com.netscape.cms.servlet.profile.model.ProfileDataInfos; -import com.netscape.cms.servlet.profile.model.ProfileInput; - -/** - * @author alee - * - */ -public class ProfileResourceService extends CMSResourceService implements ProfileResource { - - private IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID); - - public ProfileDataInfos listProfiles() { - List list = new ArrayList(); - ProfileDataInfos infos = new ProfileDataInfos(); - - if (ps == null) { - return null; - } - - Enumeration profileIds = ps.getProfileIds(); - if (profileIds != null) { - while (profileIds.hasMoreElements()) { - String id = profileIds.nextElement(); - ProfileDataInfo info = null; - try { - info = createProfileDataInfo(id); - } catch (EBaseException e) { - continue; - } - - if (info != null) { - list.add(info); - } - } - } - - infos.setProfileInfos(list); - return infos; - } - - public ProfileData retrieveProfile(String profileId) throws ProfileNotFoundException { - ProfileData data = null; - - if (ps == null) { - return null; - } - - Enumeration 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); - } - - try { - data = createProfileData(profileId); - } catch (EBaseException e) { - e.printStackTrace(); - throw new ProfileNotFoundException(profileId); - } - - return 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(); - - Locale locale = Locale.getDefault(); - String name = profile.getName(locale); - String desc = profile.getDescription(locale); - - data.setName(name); - data.setDescription(desc); - data.setIsEnabled(ps.isProfileEnable(profileId)); - data.setIsVisible(profile.isVisible()); - data.setEnabledBy(ps.getProfileEnableBy(profileId)); - data.setId(profileId); - - Enumeration inputIds = profile.getProfileInputIds(); - - String inputName = null; - - if (inputIds != null) { - while (inputIds.hasMoreElements()) { - String inputId = inputIds.nextElement(); - IProfileInput profileInput = profile.getProfileInput(inputId); - - if (profileInput == null) { - continue; - } - inputName = profileInput.getName(locale); - - Enumeration inputNames = profileInput.getValueNames(); - - ProfileInput input = data.addProfileInput(inputName); - - String curInputName = null; - while (inputNames.hasMoreElements()) { - curInputName = inputNames.nextElement(); - - if (curInputName != null && !curInputName.equals("")) { - input.setInputAttr(curInputName, ""); - } - - } - } - } - - return data; - - } - - public ProfileDataInfo createProfileDataInfo(String profileId) throws EBaseException { - - if (profileId == null) { - throw new EBaseException("Error creating ProfileDataInfo."); - } - ProfileDataInfo ret = null; - - IProfile profile = null; - - profile = ps.getProfile(profileId); - if (profile == null) { - return null; - } - - ret = new ProfileDataInfo(); - - ret.setProfileId(profileId); - - Path profilePath = ProfileResource.class.getAnnotation(Path.class); - - UriBuilder profileBuilder = uriInfo.getBaseUriBuilder(); - profileBuilder.path(profilePath.value() + "/" + profileId); - ret.setProfileURL(profileBuilder.build().toString()); - - return ret; - } -} diff --git a/base/common/src/com/netscape/cms/servlet/profile/ProfileService.java b/base/common/src/com/netscape/cms/servlet/profile/ProfileService.java new file mode 100644 index 000000000..0c13b8bba --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/profile/ProfileService.java @@ -0,0 +1,203 @@ +//--- BEGIN COPYRIGHT BLOCK --- +//This program is free software; you can redistribute it and/or modify +//it under the terms of the GNU General Public License as published by +//the Free Software Foundation; version 2 of the License. +// +//This program is distributed in the hope that it will be useful, +//but WITHOUT ANY WARRANTY; without even the implied warranty of +//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +//GNU General Public License for more details. +// +//You should have received a copy of the GNU General Public License along +//with this program; if not, write to the Free Software Foundation, Inc., +//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +//(C) 2011 Red Hat, Inc. +//All rights reserved. +//--- END COPYRIGHT BLOCK --- + +package com.netscape.cms.servlet.profile; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Locale; + +import javax.ws.rs.Path; +import javax.ws.rs.core.UriBuilder; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.EBaseException; +import com.netscape.certsrv.profile.EProfileException; +import com.netscape.certsrv.profile.IProfile; +import com.netscape.certsrv.profile.IProfileInput; +import com.netscape.certsrv.profile.IProfileSubsystem; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cms.servlet.profile.model.ProfileData; +import com.netscape.cms.servlet.profile.model.ProfileDataInfo; +import com.netscape.cms.servlet.profile.model.ProfileDataInfos; +import com.netscape.cms.servlet.profile.model.ProfileInput; + +/** + * @author alee + * + */ +public class ProfileService extends PKIService implements ProfileResource { + + private IProfileSubsystem ps = (IProfileSubsystem) CMS.getSubsystem(IProfileSubsystem.ID); + + public ProfileDataInfos listProfiles() { + List list = new ArrayList(); + ProfileDataInfos infos = new ProfileDataInfos(); + + if (ps == null) { + return null; + } + + Enumeration profileIds = ps.getProfileIds(); + if (profileIds != null) { + while (profileIds.hasMoreElements()) { + String id = profileIds.nextElement(); + ProfileDataInfo info = null; + try { + info = createProfileDataInfo(id); + } catch (EBaseException e) { + continue; + } + + if (info != null) { + list.add(info); + } + } + } + + infos.setProfileInfos(list); + return infos; + } + + public ProfileData retrieveProfile(String profileId) throws ProfileNotFoundException { + ProfileData data = null; + + if (ps == null) { + return null; + } + + Enumeration 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); + } + + try { + data = createProfileData(profileId); + } catch (EBaseException e) { + e.printStackTrace(); + throw new ProfileNotFoundException(profileId); + } + + return 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(); + + Locale locale = Locale.getDefault(); + String name = profile.getName(locale); + String desc = profile.getDescription(locale); + + data.setName(name); + data.setDescription(desc); + data.setIsEnabled(ps.isProfileEnable(profileId)); + data.setIsVisible(profile.isVisible()); + data.setEnabledBy(ps.getProfileEnableBy(profileId)); + data.setId(profileId); + + Enumeration inputIds = profile.getProfileInputIds(); + + String inputName = null; + + if (inputIds != null) { + while (inputIds.hasMoreElements()) { + String inputId = inputIds.nextElement(); + IProfileInput profileInput = profile.getProfileInput(inputId); + + if (profileInput == null) { + continue; + } + inputName = profileInput.getName(locale); + + Enumeration inputNames = profileInput.getValueNames(); + + ProfileInput input = data.addProfileInput(inputName); + + String curInputName = null; + while (inputNames.hasMoreElements()) { + curInputName = inputNames.nextElement(); + + if (curInputName != null && !curInputName.equals("")) { + input.setInputAttr(curInputName, ""); + } + + } + } + } + + return data; + + } + + public ProfileDataInfo createProfileDataInfo(String profileId) throws EBaseException { + + if (profileId == null) { + throw new EBaseException("Error creating ProfileDataInfo."); + } + ProfileDataInfo ret = null; + + IProfile profile = null; + + profile = ps.getProfile(profileId); + if (profile == null) { + return null; + } + + ret = new ProfileDataInfo(); + + ret.setProfileId(profileId); + + Path profilePath = ProfileResource.class.getAnnotation(Path.class); + + UriBuilder profileBuilder = uriInfo.getBaseUriBuilder(); + profileBuilder.path(profilePath.value() + "/" + profileId); + ret.setProfileURL(profileBuilder.build().toString()); + + return ret; + } +} diff --git a/base/common/src/com/netscape/cms/servlet/request/CertRequestResourceService.java b/base/common/src/com/netscape/cms/servlet/request/CertRequestResourceService.java deleted file mode 100644 index d107e2191..000000000 --- a/base/common/src/com/netscape/cms/servlet/request/CertRequestResourceService.java +++ /dev/null @@ -1,245 +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 javax.ws.rs.PathParam; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -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.EBaseException; -import com.netscape.certsrv.profile.EDeferException; -import com.netscape.certsrv.profile.EProfileException; -import com.netscape.certsrv.profile.ERejectException; -import com.netscape.certsrv.property.EPropertyException; -import com.netscape.certsrv.request.RequestId; -import com.netscape.cms.servlet.base.BadRequestException; -import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cms.servlet.request.model.AgentEnrollmentRequestData; -import com.netscape.cms.servlet.request.model.CertRequestDAO; -import com.netscape.cms.servlet.request.model.CertRequestInfo; -import com.netscape.cms.servlet.request.model.CertRequestInfos; -import com.netscape.cms.servlet.request.model.EnrollmentRequestData; -import com.netscape.cmsutil.ldap.LDAPUtil; - -/** - * @author alee - * - */ -public class CertRequestResourceService extends CMSResourceService implements CertRequestResource { - - /** - * Used to retrieve key request info for a specific request - */ - public CertRequestInfo getRequestInfo(RequestId id) { - // auth and authz - CertRequestInfo info; - - CertRequestDAO dao = new CertRequestDAO(); - try { - info = dao.getRequest(id, uriInfo); - } catch (EBaseException e) { - // log error - e.printStackTrace(); - throw new CMSException("Error getting Cert request info!"); - } - - if (info == null) { - // request does not exist - throw new RequestNotFoundException(id); - } - - return info; - } - - // Enrollment - used to test integration with a browser - public CertRequestInfos enrollCert(MultivaluedMap form) { - EnrollmentRequestData data = new EnrollmentRequestData(form); - return enrollCert(data); - } - - public CertRequestInfos enrollCert(EnrollmentRequestData data) { - CertRequestInfos infos; - if (data == null) { - throw new BadRequestException("Bad data input into CertRequestResourceService.enrollCert!"); - } - CertRequestDAO dao = new CertRequestDAO(); - - try { - infos = dao.submitRequest(data, servletRequest, uriInfo, getLocale()); - } catch (EAuthException e) { - CMS.debug("enrollCert: authentication failed: " + e); - throw new CMSException(Response.Status.UNAUTHORIZED, e.toString()); - } catch (EAuthzException e) { - CMS.debug("enrollCert: authorization failed: " + e); - throw new CMSException(Response.Status.UNAUTHORIZED, e.toString()); - } catch (BadRequestDataException e) { - CMS.debug("enrollCert: bad request data: " + e); - throw new CMSException(Response.Status.BAD_REQUEST, e.toString()); - } catch (EBaseException e) { - throw new CMSException(e.toString()); - } - - return infos; - } - - public void approveRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "approve"); - } - - public void rejectRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "reject"); - } - - public void cancelRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "cancel"); - } - - public void updateRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "update"); - } - - public void validateRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "validate"); - } - - public void unassignRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "unassign"); - } - - public void assignRequest(RequestId id, AgentEnrollmentRequestData data) { - changeRequestState(id, data, "assign"); - } - - public void changeRequestState(RequestId id, AgentEnrollmentRequestData 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(), op); - } catch (ERejectException e) { - CMS.debug("changeRequestState: execution rejected " + e); - throw new CMSException(Response.Status.BAD_REQUEST, - CMS.getUserMessage(getLocale(), "CMS_PROFILE_REJECTED", e.toString())); - } catch (EDeferException e) { - CMS.debug("changeRequestState: execution defered " + e); - // TODO do we throw an exception here? - throw new CMSException(Response.Status.BAD_REQUEST, - CMS.getUserMessage(getLocale(), "CMS_PROFILE_DEFERRED", e.toString())); - } catch (BadRequestDataException e) { - CMS.debug("changeRequestState: bad request data: " + e); - throw new CMSException(Response.Status.BAD_REQUEST, e.toString()); - } catch (EPropertyException e) { - CMS.debug("changeRequestState: execution error " + e); - throw new CMSException(CMS.getUserMessage(getLocale(), - "CMS_PROFILE_PROPERTY_ERROR", e.toString())); - } catch (EProfileException e) { - CMS.debug("ProfileProcessServlet: execution error " + e); - throw new CMSException(CMS.getUserMessage(getLocale(), "CMS_INTERNAL_ERROR")); - } catch (EBaseException e) { - e.printStackTrace(); - throw new CMSException("Problem approving request in CertRequestResource.assignRequest! " + e); - } catch (RequestNotFoundException e) { - CMS.debug(e); - throw new CMSException(Response.Status.BAD_REQUEST, - CMS.getUserMessage(getLocale(), "CMS_REQUEST_NOT_FOUND", id.toString())); - } - } - - public AgentEnrollmentRequestData reviewRequest(@PathParam("id") RequestId id) { - // auth and authz - AgentEnrollmentRequestData info; - - CertRequestDAO dao = new CertRequestDAO(); - try { - info = dao.reviewRequest(servletRequest, id, uriInfo, getLocale()); - } catch (EBaseException e) { - // log error - e.printStackTrace(); - throw new CMSException("Error getting Cert request info!"); - } - - if (info == null) { - // request does not exist - throw new RequestNotFoundException(id); - } - - return info; - } - - /** - * Used to generate list of cert requests based on the search parameters - */ - public CertRequestInfos listRequests(String requestState, String requestType, - RequestId start, int pageSize, int maxResults, int maxTime) { - // auth and authz - - // get ldap filter - String filter = createSearchFilter(requestState, requestType); - CMS.debug("listRequests: filter is " + filter); - - // get start marker - if (start == null) { - start = new RequestId(CertRequestResource.DEFAULT_START); - } - - 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 CMSException("Error listing cert requests!"); - } - return 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; - } - -} diff --git a/base/common/src/com/netscape/cms/servlet/request/CertRequestService.java b/base/common/src/com/netscape/cms/servlet/request/CertRequestService.java new file mode 100644 index 000000000..9178d4c9e --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/request/CertRequestService.java @@ -0,0 +1,245 @@ +// --- 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 javax.ws.rs.PathParam; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +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.EBaseException; +import com.netscape.certsrv.profile.EDeferException; +import com.netscape.certsrv.profile.EProfileException; +import com.netscape.certsrv.profile.ERejectException; +import com.netscape.certsrv.property.EPropertyException; +import com.netscape.certsrv.request.RequestId; +import com.netscape.cms.servlet.base.BadRequestException; +import com.netscape.cms.servlet.base.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cms.servlet.request.model.AgentEnrollmentRequestData; +import com.netscape.cms.servlet.request.model.CertRequestDAO; +import com.netscape.cms.servlet.request.model.CertRequestInfo; +import com.netscape.cms.servlet.request.model.CertRequestInfos; +import com.netscape.cms.servlet.request.model.EnrollmentRequestData; +import com.netscape.cmsutil.ldap.LDAPUtil; + +/** + * @author alee + * + */ +public class CertRequestService extends PKIService implements CertRequestResource { + + /** + * Used to retrieve key request info for a specific request + */ + public CertRequestInfo getRequestInfo(RequestId id) { + // auth and authz + CertRequestInfo info; + + CertRequestDAO dao = new CertRequestDAO(); + try { + info = dao.getRequest(id, uriInfo); + } catch (EBaseException e) { + // log error + e.printStackTrace(); + throw new CMSException("Error getting Cert request info!"); + } + + if (info == null) { + // request does not exist + throw new RequestNotFoundException(id); + } + + return info; + } + + // Enrollment - used to test integration with a browser + public CertRequestInfos enrollCert(MultivaluedMap form) { + EnrollmentRequestData data = new EnrollmentRequestData(form); + return enrollCert(data); + } + + public CertRequestInfos enrollCert(EnrollmentRequestData data) { + CertRequestInfos infos; + if (data == null) { + throw new BadRequestException("Bad data input into CertRequestResourceService.enrollCert!"); + } + CertRequestDAO dao = new CertRequestDAO(); + + try { + infos = dao.submitRequest(data, servletRequest, uriInfo, getLocale()); + } catch (EAuthException e) { + CMS.debug("enrollCert: authentication failed: " + e); + throw new CMSException(Response.Status.UNAUTHORIZED, e.toString()); + } catch (EAuthzException e) { + CMS.debug("enrollCert: authorization failed: " + e); + throw new CMSException(Response.Status.UNAUTHORIZED, e.toString()); + } catch (BadRequestDataException e) { + CMS.debug("enrollCert: bad request data: " + e); + throw new CMSException(Response.Status.BAD_REQUEST, e.toString()); + } catch (EBaseException e) { + throw new CMSException(e.toString()); + } + + return infos; + } + + public void approveRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "approve"); + } + + public void rejectRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "reject"); + } + + public void cancelRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "cancel"); + } + + public void updateRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "update"); + } + + public void validateRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "validate"); + } + + public void unassignRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "unassign"); + } + + public void assignRequest(RequestId id, AgentEnrollmentRequestData data) { + changeRequestState(id, data, "assign"); + } + + public void changeRequestState(RequestId id, AgentEnrollmentRequestData 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(), op); + } catch (ERejectException e) { + CMS.debug("changeRequestState: execution rejected " + e); + throw new CMSException(Response.Status.BAD_REQUEST, + CMS.getUserMessage(getLocale(), "CMS_PROFILE_REJECTED", e.toString())); + } catch (EDeferException e) { + CMS.debug("changeRequestState: execution defered " + e); + // TODO do we throw an exception here? + throw new CMSException(Response.Status.BAD_REQUEST, + CMS.getUserMessage(getLocale(), "CMS_PROFILE_DEFERRED", e.toString())); + } catch (BadRequestDataException e) { + CMS.debug("changeRequestState: bad request data: " + e); + throw new CMSException(Response.Status.BAD_REQUEST, e.toString()); + } catch (EPropertyException e) { + CMS.debug("changeRequestState: execution error " + e); + throw new CMSException(CMS.getUserMessage(getLocale(), + "CMS_PROFILE_PROPERTY_ERROR", e.toString())); + } catch (EProfileException e) { + CMS.debug("ProfileProcessServlet: execution error " + e); + throw new CMSException(CMS.getUserMessage(getLocale(), "CMS_INTERNAL_ERROR")); + } catch (EBaseException e) { + e.printStackTrace(); + throw new CMSException("Problem approving request in CertRequestResource.assignRequest! " + e); + } catch (RequestNotFoundException e) { + CMS.debug(e); + throw new CMSException(Response.Status.BAD_REQUEST, + CMS.getUserMessage(getLocale(), "CMS_REQUEST_NOT_FOUND", id.toString())); + } + } + + public AgentEnrollmentRequestData reviewRequest(@PathParam("id") RequestId id) { + // auth and authz + AgentEnrollmentRequestData info; + + CertRequestDAO dao = new CertRequestDAO(); + try { + info = dao.reviewRequest(servletRequest, id, uriInfo, getLocale()); + } catch (EBaseException e) { + // log error + e.printStackTrace(); + throw new CMSException("Error getting Cert request info!"); + } + + if (info == null) { + // request does not exist + throw new RequestNotFoundException(id); + } + + return info; + } + + /** + * Used to generate list of cert requests based on the search parameters + */ + public CertRequestInfos listRequests(String requestState, String requestType, + RequestId start, int pageSize, int maxResults, int maxTime) { + // auth and authz + + // get ldap filter + String filter = createSearchFilter(requestState, requestType); + CMS.debug("listRequests: filter is " + filter); + + // get start marker + if (start == null) { + start = new RequestId(CertRequestResource.DEFAULT_START); + } + + 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 CMSException("Error listing cert requests!"); + } + return 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; + } + +} diff --git a/base/common/src/com/netscape/cms/servlet/request/KeyRequestResourceService.java b/base/common/src/com/netscape/cms/servlet/request/KeyRequestResourceService.java deleted file mode 100644 index d98938b7a..000000000 --- a/base/common/src/com/netscape/cms/servlet/request/KeyRequestResourceService.java +++ /dev/null @@ -1,224 +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 javax.ws.rs.WebApplicationException; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.base.EBaseException; -import com.netscape.certsrv.request.RequestId; -import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.base.CMSResourceService; -import com.netscape.cms.servlet.request.model.ArchivalRequestData; -import com.netscape.cms.servlet.request.model.KeyRequestDAO; -import com.netscape.cms.servlet.request.model.KeyRequestInfo; -import com.netscape.cms.servlet.request.model.KeyRequestInfos; -import com.netscape.cms.servlet.request.model.RecoveryRequestData; -import com.netscape.cmsutil.ldap.LDAPUtil; - -/** - * @author alee - * - */ -public class KeyRequestResourceService extends CMSResourceService implements KeyRequestResource { - - /** - * Used to retrieve key request info for a specific request - */ - public KeyRequestInfo getRequestInfo(RequestId 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 CMSException(e.getMessage(), e); - } - if (info == null) { - // request does not exist - throw new RequestNotFoundException(id); - } - return info; - } - - // Archiving - used to test integration with a browser - public KeyRequestInfo archiveKey(MultivaluedMap form) { - ArchivalRequestData data = new ArchivalRequestData(form); - return archiveKey(data); - } - - public KeyRequestInfo archiveKey(ArchivalRequestData data) { - // auth and authz - // Catch this before internal server processing has to deal with it - - if (data == null || data.getClientId() == null - || data.getWrappedPrivateData() == null - || data.getDataType() == null) { - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - - KeyRequestDAO dao = new KeyRequestDAO(); - KeyRequestInfo info; - try { - info = dao.submitRequest(data, uriInfo); - } catch (EBaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - return info; - } - - //Recovery - used to test integration with a browser - public KeyRequestInfo recoverKey(MultivaluedMap form) { - RecoveryRequestData data = new RecoveryRequestData(form); - return recoverKey(data); - } - - public KeyRequestInfo recoverKey(RecoveryRequestData 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 || (data.getTransWrappedSessionKey() == null - && data.getSessionWrappedPassphrase() != null)) { - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - KeyRequestDAO dao = new KeyRequestDAO(); - KeyRequestInfo info; - try { - info = dao.submitRequest(data, uriInfo); - } catch (EBaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - return info; - } - - public void approveRequest(RequestId id) { - if (id == null) { - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - // auth and authz - KeyRequestDAO dao = new KeyRequestDAO(); - try { - dao.approveRequest(id); - } catch (EBaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - } - - public void rejectRequest(RequestId id) { - if (id == null) { - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - // auth and authz - KeyRequestDAO dao = new KeyRequestDAO(); - try { - dao.rejectRequest(id); - } catch (EBaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - } - - public void cancelRequest(RequestId id) { - if (id == null) { - throw new WebApplicationException(Response.Status.BAD_REQUEST); - } - // auth and authz - KeyRequestDAO dao = new KeyRequestDAO(); - try { - dao.cancelRequest(id); - } catch (EBaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - } - - /** - * Used to generate list of key requests based on the search parameters - */ - public KeyRequestInfos listRequests(String requestState, String requestType, String clientID, - RequestId start, int pageSize, int maxResults, int maxTime) { - // auth and authz - - // get ldap filter - String filter = createSearchFilter(requestState, requestType, clientID); - CMS.debug("listRequests: filter is " + filter); - - // get start marker - if (start == null) { - start = new RequestId(KeyRequestResource.DEFAULT_START); - } - - KeyRequestDAO reqDAO = new KeyRequestDAO(); - KeyRequestInfos 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 WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); - } - return requests; - } - - private String createSearchFilter(String requestState, String requestType, String clientID) { - String filter = ""; - int matches = 0; - - if ((requestState == null) && (requestType == null) && (clientID == null)) { - filter = "(requeststate=*)"; - return filter; - } - - if (requestState != null) { - filter += "(requeststate=" + LDAPUtil.escapeFilter(requestState) + ")"; - matches ++; - } - - if (requestType != null) { - filter += "(requesttype=" + LDAPUtil.escapeFilter(requestType) + ")"; - matches ++; - } - - if (clientID != null) { - filter += "(clientID=" + LDAPUtil.escapeFilter(clientID) + ")"; - matches ++; - } - - if (matches > 1) { - filter = "(&" + filter + ")"; - } - - return filter; - } -} diff --git a/base/common/src/com/netscape/cms/servlet/request/KeyRequestService.java b/base/common/src/com/netscape/cms/servlet/request/KeyRequestService.java new file mode 100644 index 000000000..ebe6062c8 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/request/KeyRequestService.java @@ -0,0 +1,224 @@ +// --- 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 javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.EBaseException; +import com.netscape.certsrv.request.RequestId; +import com.netscape.cms.servlet.base.CMSException; +import com.netscape.cms.servlet.base.PKIService; +import com.netscape.cms.servlet.request.model.ArchivalRequestData; +import com.netscape.cms.servlet.request.model.KeyRequestDAO; +import com.netscape.cms.servlet.request.model.KeyRequestInfo; +import com.netscape.cms.servlet.request.model.KeyRequestInfos; +import com.netscape.cms.servlet.request.model.RecoveryRequestData; +import com.netscape.cmsutil.ldap.LDAPUtil; + +/** + * @author alee + * + */ +public class KeyRequestService extends PKIService implements KeyRequestResource { + + /** + * Used to retrieve key request info for a specific request + */ + public KeyRequestInfo getRequestInfo(RequestId 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 CMSException(e.getMessage(), e); + } + if (info == null) { + // request does not exist + throw new RequestNotFoundException(id); + } + return info; + } + + // Archiving - used to test integration with a browser + public KeyRequestInfo archiveKey(MultivaluedMap form) { + ArchivalRequestData data = new ArchivalRequestData(form); + return archiveKey(data); + } + + public KeyRequestInfo archiveKey(ArchivalRequestData data) { + // auth and authz + // Catch this before internal server processing has to deal with it + + if (data == null || data.getClientId() == null + || data.getWrappedPrivateData() == null + || data.getDataType() == null) { + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + + KeyRequestDAO dao = new KeyRequestDAO(); + KeyRequestInfo info; + try { + info = dao.submitRequest(data, uriInfo); + } catch (EBaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + return info; + } + + //Recovery - used to test integration with a browser + public KeyRequestInfo recoverKey(MultivaluedMap form) { + RecoveryRequestData data = new RecoveryRequestData(form); + return recoverKey(data); + } + + public KeyRequestInfo recoverKey(RecoveryRequestData 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 || (data.getTransWrappedSessionKey() == null + && data.getSessionWrappedPassphrase() != null)) { + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + KeyRequestDAO dao = new KeyRequestDAO(); + KeyRequestInfo info; + try { + info = dao.submitRequest(data, uriInfo); + } catch (EBaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + return info; + } + + public void approveRequest(RequestId id) { + if (id == null) { + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + // auth and authz + KeyRequestDAO dao = new KeyRequestDAO(); + try { + dao.approveRequest(id); + } catch (EBaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + } + + public void rejectRequest(RequestId id) { + if (id == null) { + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + // auth and authz + KeyRequestDAO dao = new KeyRequestDAO(); + try { + dao.rejectRequest(id); + } catch (EBaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + } + + public void cancelRequest(RequestId id) { + if (id == null) { + throw new WebApplicationException(Response.Status.BAD_REQUEST); + } + // auth and authz + KeyRequestDAO dao = new KeyRequestDAO(); + try { + dao.cancelRequest(id); + } catch (EBaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + } + + /** + * Used to generate list of key requests based on the search parameters + */ + public KeyRequestInfos listRequests(String requestState, String requestType, String clientID, + RequestId start, int pageSize, int maxResults, int maxTime) { + // auth and authz + + // get ldap filter + String filter = createSearchFilter(requestState, requestType, clientID); + CMS.debug("listRequests: filter is " + filter); + + // get start marker + if (start == null) { + start = new RequestId(KeyRequestResource.DEFAULT_START); + } + + KeyRequestDAO reqDAO = new KeyRequestDAO(); + KeyRequestInfos 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 WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); + } + return requests; + } + + private String createSearchFilter(String requestState, String requestType, String clientID) { + String filter = ""; + int matches = 0; + + if ((requestState == null) && (requestType == null) && (clientID == null)) { + filter = "(requeststate=*)"; + return filter; + } + + if (requestState != null) { + filter += "(requeststate=" + LDAPUtil.escapeFilter(requestState) + ")"; + matches ++; + } + + if (requestType != null) { + filter += "(requesttype=" + LDAPUtil.escapeFilter(requestType) + ")"; + matches ++; + } + + if (clientID != null) { + filter += "(clientID=" + LDAPUtil.escapeFilter(clientID) + ")"; + matches ++; + } + + if (matches > 1) { + filter = "(&" + filter + ")"; + } + + return filter; + } +} diff --git a/base/common/src/com/netscape/cms/servlet/request/model/AgentEnrollmentRequestDataFactory.java b/base/common/src/com/netscape/cms/servlet/request/model/AgentEnrollmentRequestDataFactory.java deleted file mode 100644 index fff1a59df..000000000 --- a/base/common/src/com/netscape/cms/servlet/request/model/AgentEnrollmentRequestDataFactory.java +++ /dev/null @@ -1,174 +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.request.model; - -import java.util.Enumeration; -import java.util.Locale; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.UriInfo; - -import com.netscape.certsrv.apps.CMS; -import com.netscape.certsrv.base.EBaseException; -import com.netscape.certsrv.base.IArgBlock; -import com.netscape.certsrv.base.Nonces; -import com.netscape.certsrv.profile.EProfileException; -import com.netscape.certsrv.profile.IPolicyDefault; -import com.netscape.certsrv.profile.IProfile; -import com.netscape.certsrv.profile.IProfileInput; -import com.netscape.certsrv.profile.IProfilePolicy; -import com.netscape.certsrv.property.EPropertyException; -import com.netscape.certsrv.request.IRequest; -import com.netscape.cms.servlet.common.CMSRequest; -import com.netscape.cms.servlet.processors.Processor; -import com.netscape.cms.servlet.profile.model.PolicyConstraint; -import com.netscape.cms.servlet.profile.model.PolicyConstraintFactory; -import com.netscape.cms.servlet.profile.model.PolicyDefault; -import com.netscape.cms.servlet.profile.model.PolicyDefaultFactory; -import com.netscape.cms.servlet.profile.model.ProfileInput; -import com.netscape.cms.servlet.profile.model.ProfileInputFactory; -import com.netscape.cms.servlet.profile.model.ProfilePolicy; -import com.netscape.cms.servlet.profile.model.ProfilePolicySet; - -public class AgentEnrollmentRequestDataFactory { - - public static AgentEnrollmentRequestData create(IRequest request, IProfile profile, UriInfo uriInfo, Locale locale) throws EBaseException { - AgentEnrollmentRequestData ret = new AgentEnrollmentRequestData(); - - if (request.getRequestType().equals("renewal")) { - ret.setIsRenewal(true); - } else { - ret.setIsRenewal(false); - } - - ret.setRequestId(request.getRequestId()); - ret.setRequestType(request.getRequestType()); - ret.setRequestStatus(request.getRequestStatus().toString()); - if (request.getRequestOwner() == null) { - ret.setRequestOwner(""); - } else { - ret.setRequestOwner(request.getRequestOwner()); - } - ret.setRequestCreationTime(request.getCreationTime().toString()); - ret.setRequestModificationTime(request.getModificationTime().toString()); - - ret.setProfileId(profile.getId()); - ret.setProfileApprovedBy(request.getExtDataInString("profileApprovedBy")); - ret.setProfileSetId(request.getExtDataInString("profileSetId")); - if (profile.isVisible()) { - ret.setProfileIsVisible("true"); - } else { - ret.setProfileIsVisible("false"); - } - - ret.setProfileName(profile.getName(locale)); - ret.setProfileDescription(profile.getDescription(locale)); - ret.setProfileRemoteHost(request.getExtDataInString("profileRemoteHost")); - ret.setProfileRemoteAddr(request.getExtDataInString("profileRemoteAddr")); - if (request.getExtDataInString("requestNotes") == null) { - ret.setRequestNotes(""); - } else { - ret.setRequestNotes(request.getExtDataInString("requestNotes")); - } - - // populate profile inputs - Enumeration inputIds = profile.getProfileInputIds(); - while (inputIds.hasMoreElements()) { - IProfileInput input = profile.getProfileInput(inputIds.nextElement()); - ProfileInput addInput = ProfileInputFactory.create(input, request, locale); - ret.addInput(addInput); - } - - String profileSetId = request.getExtDataInString("profileSetId"); - CMS.debug("createAgentCertRequestInfo: profileSetId=" + profileSetId); - Enumeration policyIds = (profileSetId != null && profileSetId.length() > 0) ? - profile.getProfilePolicyIds(profileSetId) : null; - ProfilePolicySet dataPolicySet = new ProfilePolicySet(); - - if (policyIds != null) { - while (policyIds.hasMoreElements()) { - String id = policyIds.nextElement(); - CMS.debug("policyId:" + id); - IProfilePolicy policy = profile.getProfilePolicy(profileSetId, id); - ProfilePolicy dataPolicy = new ProfilePolicy(); - - //populate defaults - IPolicyDefault def = policy.getDefault(); - PolicyDefault dataDef = PolicyDefaultFactory.create(request, locale, def); - dataPolicy.setDef(dataDef); - - //populate constraints - PolicyConstraint dataCons = PolicyConstraintFactory.create(locale, policy.getConstraint()); - dataPolicy.setConstraint(dataCons); - - dataPolicySet.addPolicy(dataPolicy); - } - } - - - ret.addProfilePolicySet(dataPolicySet); - - // TODO populate profile outputs - return ret; - } - - public static AgentEnrollmentRequestData create(CMSRequest cmsReq, IProfile profile, Nonces nonces, Locale locale) - throws EPropertyException, EProfileException { - HttpServletRequest req = cmsReq.getHttpReq(); - IRequest ireq = cmsReq.getIRequest(); - IArgBlock params = cmsReq.getHttpParams(); - - AgentEnrollmentRequestData ret = new AgentEnrollmentRequestData(); - ret.setProfileId(profile.getId()); - ret.setRequestNotes(req.getParameter("requestNotes")); - ret.setRequestId(ireq.getRequestId()); - - if (nonces != null) { - ret.setNonce(req.getParameter(Processor.ARG_REQUEST_NONCE)); - } - - // populate profile policy values - String profileSetId = ireq.getExtDataInString("profileSetId"); - Enumeration policyIds = (profileSetId != null && profileSetId.length() > 0) ? - profile.getProfilePolicyIds(profileSetId) : null; - ProfilePolicySet dataPolicySet = new ProfilePolicySet(); - - if (policyIds != null) { - while (policyIds.hasMoreElements()) { - String id = policyIds.nextElement(); - CMS.debug("policyId:" + id); - IProfilePolicy policy = profile.getProfilePolicy(profileSetId, id); - com.netscape.cms.servlet.profile.model.ProfilePolicy dataPolicy = - new com.netscape.cms.servlet.profile.model.ProfilePolicy(); - - //populate defaults - IPolicyDefault def = policy.getDefault(); - PolicyDefault dataDef = PolicyDefaultFactory.create(params, locale, def); - dataPolicy.setDef(dataDef); - - dataPolicySet.addPolicy(dataPolicy); - CMS.debug(dataPolicy.toString()); - } - } - - ret.addProfilePolicySet(dataPolicySet); - - return ret; - } - -} diff --git a/base/common/src/com/netscape/cms/servlet/request/model/CertEnrollmentRequestFactory.java b/base/common/src/com/netscape/cms/servlet/request/model/CertEnrollmentRequestFactory.java new file mode 100644 index 000000000..51582d13c --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/request/model/CertEnrollmentRequestFactory.java @@ -0,0 +1,51 @@ +//--- 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.request.model; + +import java.util.Enumeration; +import java.util.Locale; + +import com.netscape.certsrv.base.IArgBlock; +import com.netscape.certsrv.profile.EProfileException; +import com.netscape.certsrv.profile.IProfile; +import com.netscape.certsrv.profile.IProfileInput; +import com.netscape.cms.servlet.common.CMSRequest; +import com.netscape.cms.servlet.profile.model.ProfileInput; +import com.netscape.cms.servlet.profile.model.ProfileInputFactory; + +public class CertEnrollmentRequestFactory { + + public static EnrollmentRequestData create(CMSRequest cmsReq, IProfile profile, Locale locale) + throws EProfileException { + IArgBlock params = cmsReq.getHttpParams(); + + EnrollmentRequestData ret = new EnrollmentRequestData(); + ret.setProfileId(profile.getId()); + + // populate profile inputs + Enumeration inputIds = profile.getProfileInputIds(); + while (inputIds.hasMoreElements()) { + IProfileInput input = profile.getProfileInput(inputIds.nextElement()); + ProfileInput addInput = ProfileInputFactory.create(input, params, locale); + ret.addInput(addInput); + } + + return ret; + } + +} diff --git a/base/common/src/com/netscape/cms/servlet/request/model/CertRequestDAO.java b/base/common/src/com/netscape/cms/servlet/request/model/CertRequestDAO.java index 4ebfc251f..f662a6c89 100644 --- a/base/common/src/com/netscape/cms/servlet/request/model/CertRequestDAO.java +++ b/base/common/src/com/netscape/cms/servlet/request/model/CertRequestDAO.java @@ -146,7 +146,7 @@ public class CertRequestDAO extends CMSRequestDAO { } String profileId = request.getExtDataInString("profileId"); IProfile profile = ps.getProfile(profileId); - AgentEnrollmentRequestData info = AgentEnrollmentRequestDataFactory.create(request, profile, uriInfo, locale); + AgentEnrollmentRequestData info = CertReviewResponseFactory.create(request, profile, uriInfo, locale); if (ca.noncesEnabled()) { addNonce(info, servletRequest); } diff --git a/base/common/src/com/netscape/cms/servlet/request/model/CertReviewResponseFactory.java b/base/common/src/com/netscape/cms/servlet/request/model/CertReviewResponseFactory.java new file mode 100644 index 000000000..5c2106802 --- /dev/null +++ b/base/common/src/com/netscape/cms/servlet/request/model/CertReviewResponseFactory.java @@ -0,0 +1,174 @@ +//--- 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.request.model; + +import java.util.Enumeration; +import java.util.Locale; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.UriInfo; + +import com.netscape.certsrv.apps.CMS; +import com.netscape.certsrv.base.EBaseException; +import com.netscape.certsrv.base.IArgBlock; +import com.netscape.certsrv.base.Nonces; +import com.netscape.certsrv.profile.EProfileException; +import com.netscape.certsrv.profile.IPolicyDefault; +import com.netscape.certsrv.profile.IProfile; +import com.netscape.certsrv.profile.IProfileInput; +import com.netscape.certsrv.profile.IProfilePolicy; +import com.netscape.certsrv.property.EPropertyException; +import com.netscape.certsrv.request.IRequest; +import com.netscape.cms.servlet.common.CMSRequest; +import com.netscape.cms.servlet.processors.Processor; +import com.netscape.cms.servlet.profile.model.PolicyConstraint; +import com.netscape.cms.servlet.profile.model.PolicyConstraintFactory; +import com.netscape.cms.servlet.profile.model.PolicyDefault; +import com.netscape.cms.servlet.profile.model.PolicyDefaultFactory; +import com.netscape.cms.servlet.profile.model.ProfileInput; +import com.netscape.cms.servlet.profile.model.ProfileInputFactory; +import com.netscape.cms.servlet.profile.model.ProfilePolicy; +import com.netscape.cms.servlet.profile.model.ProfilePolicySet; + +public class CertReviewResponseFactory { + + public static AgentEnrollmentRequestData create(IRequest request, IProfile profile, UriInfo uriInfo, Locale locale) throws EBaseException { + AgentEnrollmentRequestData ret = new AgentEnrollmentRequestData(); + + if (request.getRequestType().equals("renewal")) { + ret.setIsRenewal(true); + } else { + ret.setIsRenewal(false); + } + + ret.setRequestId(request.getRequestId()); + ret.setRequestType(request.getRequestType()); + ret.setRequestStatus(request.getRequestStatus().toString()); + if (request.getRequestOwner() == null) { + ret.setRequestOwner(""); + } else { + ret.setRequestOwner(request.getRequestOwner()); + } + ret.setRequestCreationTime(request.getCreationTime().toString()); + ret.setRequestModificationTime(request.getModificationTime().toString()); + + ret.setProfileId(profile.getId()); + ret.setProfileApprovedBy(request.getExtDataInString("profileApprovedBy")); + ret.setProfileSetId(request.getExtDataInString("profileSetId")); + if (profile.isVisible()) { + ret.setProfileIsVisible("true"); + } else { + ret.setProfileIsVisible("false"); + } + + ret.setProfileName(profile.getName(locale)); + ret.setProfileDescription(profile.getDescription(locale)); + ret.setProfileRemoteHost(request.getExtDataInString("profileRemoteHost")); + ret.setProfileRemoteAddr(request.getExtDataInString("profileRemoteAddr")); + if (request.getExtDataInString("requestNotes") == null) { + ret.setRequestNotes(""); + } else { + ret.setRequestNotes(request.getExtDataInString("requestNotes")); + } + + // populate profile inputs + Enumeration inputIds = profile.getProfileInputIds(); + while (inputIds.hasMoreElements()) { + IProfileInput input = profile.getProfileInput(inputIds.nextElement()); + ProfileInput addInput = ProfileInputFactory.create(input, request, locale); + ret.addInput(addInput); + } + + String profileSetId = request.getExtDataInString("profileSetId"); + CMS.debug("createAgentCertRequestInfo: profileSetId=" + profileSetId); + Enumeration policyIds = (profileSetId != null && profileSetId.length() > 0) ? + profile.getProfilePolicyIds(profileSetId) : null; + ProfilePolicySet dataPolicySet = new ProfilePolicySet(); + + if (policyIds != null) { + while (policyIds.hasMoreElements()) { + String id = policyIds.nextElement(); + CMS.debug("policyId:" + id); + IProfilePolicy policy = profile.getProfilePolicy(profileSetId, id); + ProfilePolicy dataPolicy = new ProfilePolicy(); + + //populate defaults + IPolicyDefault def = policy.getDefault(); + PolicyDefault dataDef = PolicyDefaultFactory.create(request, locale, def); + dataPolicy.setDef(dataDef); + + //populate constraints + PolicyConstraint dataCons = PolicyConstraintFactory.create(locale, policy.getConstraint()); + dataPolicy.setConstraint(dataCons); + + dataPolicySet.addPolicy(dataPolicy); + } + } + + + ret.addProfilePolicySet(dataPolicySet); + + // TODO populate profile outputs + return ret; + } + + public static AgentEnrollmentRequestData create(CMSRequest cmsReq, IProfile profile, Nonces nonces, Locale locale) + throws EPropertyException, EProfileException { + HttpServletRequest req = cmsReq.getHttpReq(); + IRequest ireq = cmsReq.getIRequest(); + IArgBlock params = cmsReq.getHttpParams(); + + AgentEnrollmentRequestData ret = new AgentEnrollmentRequestData(); + ret.setProfileId(profile.getId()); + ret.setRequestNotes(req.getParameter("requestNotes")); + ret.setRequestId(ireq.getRequestId()); + + if (nonces != null) { + ret.setNonce(req.getParameter(Processor.ARG_REQUEST_NONCE)); + } + + // populate profile policy values + String profileSetId = ireq.getExtDataInString("profileSetId"); + Enumeration policyIds = (profileSetId != null && profileSetId.length() > 0) ? + profile.getProfilePolicyIds(profileSetId) : null; + ProfilePolicySet dataPolicySet = new ProfilePolicySet(); + + if (policyIds != null) { + while (policyIds.hasMoreElements()) { + String id = policyIds.nextElement(); + CMS.debug("policyId:" + id); + IProfilePolicy policy = profile.getProfilePolicy(profileSetId, id); + com.netscape.cms.servlet.profile.model.ProfilePolicy dataPolicy = + new com.netscape.cms.servlet.profile.model.ProfilePolicy(); + + //populate defaults + IPolicyDefault def = policy.getDefault(); + PolicyDefault dataDef = PolicyDefaultFactory.create(params, locale, def); + dataPolicy.setDef(dataDef); + + dataPolicySet.addPolicy(dataPolicy); + CMS.debug(dataPolicy.toString()); + } + } + + ret.addProfilePolicySet(dataPolicySet); + + return ret; + } + +} diff --git a/base/common/src/com/netscape/cms/servlet/request/model/EnrollmentRequestDataFactory.java b/base/common/src/com/netscape/cms/servlet/request/model/EnrollmentRequestDataFactory.java deleted file mode 100644 index 3a09b7608..000000000 --- a/base/common/src/com/netscape/cms/servlet/request/model/EnrollmentRequestDataFactory.java +++ /dev/null @@ -1,51 +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.request.model; - -import java.util.Enumeration; -import java.util.Locale; - -import com.netscape.certsrv.base.IArgBlock; -import com.netscape.certsrv.profile.EProfileException; -import com.netscape.certsrv.profile.IProfile; -import com.netscape.certsrv.profile.IProfileInput; -import com.netscape.cms.servlet.common.CMSRequest; -import com.netscape.cms.servlet.profile.model.ProfileInput; -import com.netscape.cms.servlet.profile.model.ProfileInputFactory; - -public class EnrollmentRequestDataFactory { - - public static EnrollmentRequestData create(CMSRequest cmsReq, IProfile profile, Locale locale) - throws EProfileException { - IArgBlock params = cmsReq.getHttpParams(); - - EnrollmentRequestData ret = new EnrollmentRequestData(); - ret.setProfileId(profile.getId()); - - // populate profile inputs - Enumeration inputIds = profile.getProfileInputIds(); - while (inputIds.hasMoreElements()) { - IProfileInput input = profile.getProfileInput(inputIds.nextElement()); - ProfileInput addInput = ProfileInputFactory.create(input, params, locale); - ret.addInput(addInput); - } - - return ret; - } - -} diff --git a/base/kra/functional/src/com/netscape/cms/servlet/test/DRMTest.java b/base/kra/functional/src/com/netscape/cms/servlet/test/DRMTest.java index 9954ba94f..3ccde1cd2 100644 --- a/base/kra/functional/src/com/netscape/cms/servlet/test/DRMTest.java +++ b/base/kra/functional/src/com/netscape/cms/servlet/test/DRMTest.java @@ -40,7 +40,7 @@ import org.mozilla.jss.util.Password; import com.netscape.certsrv.dbs.keydb.KeyId; import com.netscape.certsrv.request.RequestId; import com.netscape.cms.client.cli.ClientConfig; -import com.netscape.cms.servlet.base.CMSResourceService; +import com.netscape.cms.servlet.base.PKIService; import com.netscape.cms.servlet.key.model.KeyData; import com.netscape.cms.servlet.key.model.KeyDataInfo; import com.netscape.cms.servlet.request.KeyRequestResource; @@ -209,8 +209,8 @@ public class DRMTest { // Test 1: Get transport certificate from DRM transportCert = client.getTransportCert(); - transportCert = transportCert.substring(CMSResourceService.HEADER.length(), - transportCert.indexOf(CMSResourceService.TRAILER)); + transportCert = transportCert.substring(PKIService.HEADER.length(), + transportCert.indexOf(PKIService.TRAILER)); log("Transport Cert retrieved from DRM: " + transportCert); diff --git a/base/kra/src/com/netscape/kra/KeyRecoveryAuthorityApplication.java b/base/kra/src/com/netscape/kra/KeyRecoveryAuthorityApplication.java index 612b0ff18..9a884f872 100644 --- a/base/kra/src/com/netscape/kra/KeyRecoveryAuthorityApplication.java +++ b/base/kra/src/com/netscape/kra/KeyRecoveryAuthorityApplication.java @@ -5,15 +5,15 @@ import java.util.Set; import javax.ws.rs.core.Application; -import com.netscape.cms.servlet.admin.GroupMemberResourceService; -import com.netscape.cms.servlet.admin.GroupResourceService; -import com.netscape.cms.servlet.admin.SystemCertificateResourceService; -import com.netscape.cms.servlet.admin.UserCertResourceService; -import com.netscape.cms.servlet.admin.UserResourceService; +import com.netscape.cms.servlet.admin.GroupMemberService; +import com.netscape.cms.servlet.admin.GroupService; +import com.netscape.cms.servlet.admin.SystemCertService; +import com.netscape.cms.servlet.admin.UserCertService; +import com.netscape.cms.servlet.admin.UserService; import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.csadmin.SystemConfigurationResourceService; -import com.netscape.cms.servlet.key.KeyResourceService; -import com.netscape.cms.servlet.request.KeyRequestResourceService; +import com.netscape.cms.servlet.csadmin.SystemConfigService; +import com.netscape.cms.servlet.key.KeyService; +import com.netscape.cms.servlet.request.KeyRequestService; public class KeyRecoveryAuthorityApplication extends Application { @@ -22,20 +22,20 @@ public class KeyRecoveryAuthorityApplication extends Application { public KeyRecoveryAuthorityApplication() { // installer - classes.add(SystemConfigurationResourceService.class); + classes.add(SystemConfigService.class); // keys and keyrequests - classes.add(KeyResourceService.class); - classes.add(KeyRequestResourceService.class); + classes.add(KeyService.class); + classes.add(KeyRequestService.class); // user and group management - classes.add(GroupMemberResourceService.class); - classes.add(GroupResourceService.class); - classes.add(UserCertResourceService.class); - classes.add(UserResourceService.class); + classes.add(GroupMemberService.class); + classes.add(GroupService.class); + classes.add(UserCertService.class); + classes.add(UserService.class); // system certs - classes.add(SystemCertificateResourceService.class); + classes.add(SystemCertService.class); // exception mapper classes.add(CMSException.Mapper.class); diff --git a/base/ocsp/src/com/netscape/ocsp/OCSPApplication.java b/base/ocsp/src/com/netscape/ocsp/OCSPApplication.java index 5e70fe49f..7331c38d6 100644 --- a/base/ocsp/src/com/netscape/ocsp/OCSPApplication.java +++ b/base/ocsp/src/com/netscape/ocsp/OCSPApplication.java @@ -5,13 +5,13 @@ import java.util.Set; import javax.ws.rs.core.Application; -import com.netscape.cms.servlet.admin.GroupMemberResourceService; -import com.netscape.cms.servlet.admin.GroupResourceService; -import com.netscape.cms.servlet.admin.SystemCertificateResourceService; -import com.netscape.cms.servlet.admin.UserCertResourceService; -import com.netscape.cms.servlet.admin.UserResourceService; +import com.netscape.cms.servlet.admin.GroupMemberService; +import com.netscape.cms.servlet.admin.GroupService; +import com.netscape.cms.servlet.admin.SystemCertService; +import com.netscape.cms.servlet.admin.UserCertService; +import com.netscape.cms.servlet.admin.UserService; import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.csadmin.SystemConfigurationResourceService; +import com.netscape.cms.servlet.csadmin.SystemConfigService; public class OCSPApplication extends Application { @@ -20,16 +20,16 @@ public class OCSPApplication extends Application { public OCSPApplication() { // installer - classes.add(SystemConfigurationResourceService.class); + classes.add(SystemConfigService.class); // user and group management - classes.add(GroupMemberResourceService.class); - classes.add(GroupResourceService.class); - classes.add(UserCertResourceService.class); - classes.add(UserResourceService.class); + classes.add(GroupMemberService.class); + classes.add(GroupService.class); + classes.add(UserCertService.class); + classes.add(UserService.class); // system certs - classes.add(SystemCertificateResourceService.class); + classes.add(SystemCertService.class); // exception mapper classes.add(CMSException.Mapper.class); diff --git a/base/tks/src/com/netscape/tks/TKSApplication.java b/base/tks/src/com/netscape/tks/TKSApplication.java index df3c293bd..2afdf1297 100644 --- a/base/tks/src/com/netscape/tks/TKSApplication.java +++ b/base/tks/src/com/netscape/tks/TKSApplication.java @@ -5,13 +5,13 @@ import java.util.Set; import javax.ws.rs.core.Application; -import com.netscape.cms.servlet.admin.GroupMemberResourceService; -import com.netscape.cms.servlet.admin.GroupResourceService; -import com.netscape.cms.servlet.admin.SystemCertificateResourceService; -import com.netscape.cms.servlet.admin.UserCertResourceService; -import com.netscape.cms.servlet.admin.UserResourceService; +import com.netscape.cms.servlet.admin.GroupMemberService; +import com.netscape.cms.servlet.admin.GroupService; +import com.netscape.cms.servlet.admin.SystemCertService; +import com.netscape.cms.servlet.admin.UserCertService; +import com.netscape.cms.servlet.admin.UserService; import com.netscape.cms.servlet.base.CMSException; -import com.netscape.cms.servlet.csadmin.SystemConfigurationResourceService; +import com.netscape.cms.servlet.csadmin.SystemConfigService; public class TKSApplication extends Application { @@ -20,16 +20,16 @@ public class TKSApplication extends Application { public TKSApplication() { // installer - classes.add(SystemConfigurationResourceService.class); + classes.add(SystemConfigService.class); // user and group management - classes.add(GroupMemberResourceService.class); - classes.add(GroupResourceService.class); - classes.add(UserCertResourceService.class); - classes.add(UserResourceService.class); + classes.add(GroupMemberService.class); + classes.add(GroupService.class); + classes.add(UserCertService.class); + classes.add(UserService.class); // system certs - classes.add(SystemCertificateResourceService.class); + classes.add(SystemCertService.class); // exception mapper classes.add(CMSException.Mapper.class); -- cgit