From 108bd269ab0eb512c334939fabde68eeab5b0b67 Mon Sep 17 00:00:00 2001 From: Endi Sukma Dewata Date: Sat, 11 Aug 2012 05:34:59 -0500 Subject: Reorganized REST client classes. The REST client classes have been moved into the com.netscape.cms.client. packages. Ticket #215 --- .../com/netscape/cms/servlet/test/CAClient.java | 141 ---------- .../src/com/netscape/cms/servlet/test/CATest.java | 3 +- .../cms/servlet/test/ConfigurationTest.java | 6 +- .../src/com/netscape/cms/client/ClientConfig.java | 189 +++++++++++++ .../src/com/netscape/cms/client/PKIClient.java | 304 ++++++++++++++++++++ .../netscape/cms/client/PKIErrorInterceptor.java | 62 +++++ .../src/com/netscape/cms/client/ca/CAClient.java | 141 ++++++++++ .../com/netscape/cms/client/cert/CertClient.java | 4 +- .../com/netscape/cms/client/cli/ClientConfig.java | 189 ------------- .../src/com/netscape/cms/client/cli/MainCLI.java | 1 + .../com/netscape/cms/client/group/GroupClient.java | 4 +- .../src/com/netscape/cms/client/kra/DRMClient.java | 130 +++++++++ .../cms/client/system/SystemConfigClient.java | 52 ++++ .../com/netscape/cms/client/user/UserClient.java | 4 +- .../cms/servlet/csadmin/ConfigurationUtils.java | 3 +- .../netscape/cms/servlet/csadmin/PKIClient.java | 305 --------------------- .../cms/servlet/csadmin/PKIErrorInterceptor.java | 62 ----- .../cms/servlet/csadmin/SystemConfigClient.java | 50 ---- base/deploy/src/scriptlets/configuration.jy | 2 +- base/deploy/src/scriptlets/pkijython.py | 2 +- .../com/netscape/cms/servlet/test/DRMClient.java | 130 --------- .../src/com/netscape/cms/servlet/test/DRMTest.java | 3 +- 22 files changed, 896 insertions(+), 891 deletions(-) delete mode 100644 base/ca/functional/src/com/netscape/cms/servlet/test/CAClient.java create mode 100644 base/common/src/com/netscape/cms/client/ClientConfig.java create mode 100644 base/common/src/com/netscape/cms/client/PKIClient.java create mode 100644 base/common/src/com/netscape/cms/client/PKIErrorInterceptor.java create mode 100644 base/common/src/com/netscape/cms/client/ca/CAClient.java delete mode 100644 base/common/src/com/netscape/cms/client/cli/ClientConfig.java create mode 100644 base/common/src/com/netscape/cms/client/kra/DRMClient.java create mode 100644 base/common/src/com/netscape/cms/client/system/SystemConfigClient.java delete mode 100644 base/common/src/com/netscape/cms/servlet/csadmin/PKIClient.java delete mode 100644 base/common/src/com/netscape/cms/servlet/csadmin/PKIErrorInterceptor.java delete mode 100644 base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigClient.java delete mode 100644 base/kra/functional/src/com/netscape/cms/servlet/test/DRMClient.java diff --git a/base/ca/functional/src/com/netscape/cms/servlet/test/CAClient.java b/base/ca/functional/src/com/netscape/cms/servlet/test/CAClient.java deleted file mode 100644 index 24c53b137..000000000 --- a/base/ca/functional/src/com/netscape/cms/servlet/test/CAClient.java +++ /dev/null @@ -1,141 +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.test; - -import java.net.URISyntaxException; -import java.util.Collection; - -import com.netscape.certsrv.dbs.certdb.CertId; -import com.netscape.certsrv.request.RequestId; -import com.netscape.cms.client.cli.ClientConfig; -import com.netscape.cms.servlet.cert.CertResource; -import com.netscape.cms.servlet.cert.model.CertDataInfos; -import com.netscape.cms.servlet.cert.model.CertSearchRequest; -import com.netscape.cms.servlet.cert.model.CertData; -import com.netscape.cms.servlet.csadmin.PKIClient; -import com.netscape.cms.servlet.profile.ProfileResource; -import com.netscape.cms.servlet.profile.model.ProfileData; -import com.netscape.cms.servlet.profile.model.ProfileDataInfos; -import com.netscape.cms.servlet.request.CertRequestResource; -import com.netscape.cms.servlet.request.model.CertReviewResponse; -import com.netscape.cms.servlet.request.model.CertRequestInfo; -import com.netscape.cms.servlet.request.model.CertRequestInfos; -import com.netscape.cms.servlet.request.model.CertEnrollmentRequest; - -public class CAClient extends PKIClient { - - private CertResource certClient; - private CertRequestResource certRequestClient; - private ProfileResource profileClient; - - public CAClient(ClientConfig config) throws URISyntaxException { - super(config); - - certRequestClient = createProxy(CertRequestResource.class); - certClient = createProxy(CertResource.class); - profileClient = createProxy(ProfileResource.class); - } - - public Collection listRequests(String requestState, String requestType) { - CertRequestInfos infos = null; - Collection list = null; - infos = certRequestClient.listRequests( - requestState, requestType, new RequestId(0), 100, 100, 10); - list = infos.getRequests(); - - return list; - } - - public CertDataInfos listCerts(String status) { - return certClient.listCerts(status, 100, 10); - } - - public CertDataInfos searchCerts(CertSearchRequest data) { - return certClient.searchCerts(data, 100, 10); - } - - public ProfileDataInfos listProfiles() { - return profileClient.listProfiles(); - } - - public ProfileData getProfile(String id) { - - if (id == null) { - return null; - } - - return profileClient.retrieveProfile(id); - } - - public CertData getCertData(CertId id) { - - if (id == null) { - return null; - } - - return certClient.getCert(id); - - } - - public CertRequestInfos enrollCertificate(CertEnrollmentRequest data) { - if (data == null) { - return null; - } - - return certRequestClient.enrollCert(data); - } - - public CertRequestInfo getRequest(RequestId id) { - if (id == null) { - return null; - } - return certRequestClient.getRequestInfo(id); - } - - public CertReviewResponse reviewRequest(RequestId id) { - if (id == null) { - return null; - } - return certRequestClient.reviewRequest(id); - } - - public void approveRequest(RequestId id, CertReviewResponse data) { - certRequestClient.approveRequest(id, data); - } - - public void rejectRequest(RequestId id, CertReviewResponse data) { - certRequestClient.rejectRequest(id, data); - } - - public void cancelRequest(RequestId id, CertReviewResponse data) { - certRequestClient.cancelRequest(id, data); - } - - public void updateRequest(RequestId id, CertReviewResponse data) { - certRequestClient.updateRequest(id, data); - } - - public void validateRequest(RequestId id, CertReviewResponse data) { - certRequestClient.validateRequest(id, data); - } - - public void unassignRequest(RequestId id, CertReviewResponse data) { - certRequestClient.unassignRequest(id, data); - } - -} diff --git a/base/ca/functional/src/com/netscape/cms/servlet/test/CATest.java b/base/ca/functional/src/com/netscape/cms/servlet/test/CATest.java index 8e67f5d5f..a230b468a 100644 --- a/base/ca/functional/src/com/netscape/cms/servlet/test/CATest.java +++ b/base/ca/functional/src/com/netscape/cms/servlet/test/CATest.java @@ -35,7 +35,8 @@ import org.mozilla.jss.util.Password; import com.netscape.certsrv.dbs.certdb.CertId; import com.netscape.certsrv.request.RequestId; -import com.netscape.cms.client.cli.ClientConfig; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.ca.CAClient; import com.netscape.cms.servlet.cert.CertNotFoundException; import com.netscape.cms.servlet.cert.model.CertDataInfo; import com.netscape.cms.servlet.cert.model.CertDataInfos; diff --git a/base/common/functional/src/com/netscape/cms/servlet/test/ConfigurationTest.java b/base/common/functional/src/com/netscape/cms/servlet/test/ConfigurationTest.java index fd951d9f8..f9fa62d0a 100644 --- a/base/common/functional/src/com/netscape/cms/servlet/test/ConfigurationTest.java +++ b/base/common/functional/src/com/netscape/cms/servlet/test/ConfigurationTest.java @@ -56,11 +56,11 @@ import org.mozilla.jss.pkix.primitive.Name; import org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo; import org.mozilla.jss.util.Password; -import com.netscape.cms.client.cli.ClientConfig; -import com.netscape.cms.servlet.csadmin.SystemConfigClient; -import com.netscape.cms.servlet.csadmin.model.SystemCertData; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.system.SystemConfigClient; import com.netscape.cms.servlet.csadmin.model.ConfigurationRequest; import com.netscape.cms.servlet.csadmin.model.ConfigurationResponse; +import com.netscape.cms.servlet.csadmin.model.SystemCertData; import com.netscape.cmsutil.util.Utils; /** diff --git a/base/common/src/com/netscape/cms/client/ClientConfig.java b/base/common/src/com/netscape/cms/client/ClientConfig.java new file mode 100644 index 000000000..7299d4d22 --- /dev/null +++ b/base/common/src/com/netscape/cms/client/ClientConfig.java @@ -0,0 +1,189 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2012 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- + +package com.netscape.cms.client; + +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * @author Endi S. Dewata + */ +@XmlRootElement(name="Client") +public class ClientConfig { + + public static Marshaller marshaller; + public static Unmarshaller unmarshaller; + + static { + try { + marshaller = JAXBContext.newInstance(ClientConfig.class).createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + unmarshaller = JAXBContext.newInstance(ClientConfig.class).createUnmarshaller(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + URI serverURI; + + String certDatabase; + String certNickname; + String username; + String password; + + @XmlElement(name="ServerURI") + public URI getServerURI() { + return serverURI; + } + + public void setServerURI(String serverUri) throws URISyntaxException { + this.serverURI = new URI(serverUri); + } + + public void setServerURI(URI serverUri) { + this.serverURI = serverUri; + } + + @XmlElement(name="CertDatabase") + public String getCertDatabase() { + return certDatabase; + } + + public void setCertDatabase(String certDatabase) { + this.certDatabase = certDatabase; + } + + @XmlElement(name="CertNickname") + public String getCertNickname() { + return certNickname; + } + + public void setCertNickname(String certNickname) { + this.certNickname = certNickname; + } + + @XmlElement(name="Username") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @XmlElement(name="Password") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((certDatabase == null) ? 0 : certDatabase.hashCode()); + result = prime * result + ((certNickname == null) ? 0 : certNickname.hashCode()); + result = prime * result + ((password == null) ? 0 : password.hashCode()); + result = prime * result + ((serverURI == null) ? 0 : serverURI.hashCode()); + result = prime * result + ((username == null) ? 0 : username.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ClientConfig other = (ClientConfig) obj; + if (certDatabase == null) { + if (other.certDatabase != null) + return false; + } else if (!certDatabase.equals(other.certDatabase)) + return false; + if (certNickname == null) { + if (other.certNickname != null) + return false; + } else if (!certNickname.equals(other.certNickname)) + return false; + if (password == null) { + if (other.password != null) + return false; + } else if (!password.equals(other.password)) + return false; + if (serverURI == null) { + if (other.serverURI != null) + return false; + } else if (!serverURI.equals(other.serverURI)) + return false; + if (username == null) { + if (other.username != null) + return false; + } else if (!username.equals(other.username)) + return false; + return true; + } + + public String toString() { + try { + StringWriter sw = new StringWriter(); + marshaller.marshal(this, sw); + return sw.toString(); + + } catch (Exception e) { + return super.toString(); + } + } + + public static ClientConfig valueOf(String string) throws Exception { + try { + return (ClientConfig)unmarshaller.unmarshal(new StringReader(string)); + } catch (Exception e) { + return null; + } + } + + public static void main(String args[]) throws Exception { + + ClientConfig before = new ClientConfig(); + before.setServerURI("http://localhost:9180/ca"); + before.setCertDatabase("certs"); + before.setCertNickname("caadmin"); + before.setPassword("12345"); + + String string = before.toString(); + System.out.println(string); + + ClientConfig after = ClientConfig.valueOf(string); + System.out.println(before.equals(after)); + } +} diff --git a/base/common/src/com/netscape/cms/client/PKIClient.java b/base/common/src/com/netscape/cms/client/PKIClient.java new file mode 100644 index 000000000..ddd47dab6 --- /dev/null +++ b/base/common/src/com/netscape/cms/client/PKIClient.java @@ -0,0 +1,304 @@ +package com.netscape.cms.client; + +import java.io.File; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.http.Header; +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.HttpException; +import org.apache.http.HttpRequest; +import org.apache.http.HttpRequestInterceptor; +import org.apache.http.HttpResponse; +import org.apache.http.HttpResponseInterceptor; +import org.apache.http.ProtocolException; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.auth.params.AuthPNames; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.params.AuthPolicy; +import org.apache.http.client.params.HttpClientParams; +import org.apache.http.conn.scheme.LayeredSchemeSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeSocketFactory; +import org.apache.http.impl.client.ClientParamsStack; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.DefaultRedirectStrategy; +import org.apache.http.impl.client.EntityEnclosingRequestWrapper; +import org.apache.http.impl.client.RequestWrapper; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HttpContext; +import org.jboss.resteasy.client.ClientExecutor; +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.client.ClientResponseFailure; +import org.jboss.resteasy.client.ProxyFactory; +import org.jboss.resteasy.client.core.BaseClientResponse; +import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; +import org.jboss.resteasy.client.core.extractors.ClientErrorHandler; +import org.jboss.resteasy.spi.ResteasyProviderFactory; +import org.mozilla.jss.CryptoManager; +import org.mozilla.jss.crypto.AlreadyInitializedException; +import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; +import org.mozilla.jss.ssl.SSLSocket; + + +public abstract class PKIClient { + + protected boolean verbose; + + protected ClientConfig config; + + protected ResteasyProviderFactory providerFactory; + protected ClientErrorHandler errorHandler; + protected ClientExecutor executor; + + public PKIClient(ClientConfig config) { + this.config = config; + + DefaultHttpClient httpClient = new DefaultHttpClient(); + + // Register https scheme. + Scheme scheme = new Scheme("https", 443, new JSSProtocolSocketFactory()); + httpClient.getConnectionManager().getSchemeRegistry().register(scheme); + + if (config.getUsername() != null && config.getPassword() != null) { + List authPref = new ArrayList(); + authPref.add(AuthPolicy.BASIC); + httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref); + + httpClient.getCredentialsProvider().setCredentials( + AuthScope.ANY, + new UsernamePasswordCredentials(config.getUsername(), config.getPassword())); + } + + httpClient.addRequestInterceptor(new HttpRequestInterceptor() { + @Override + public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { + if (verbose) { + System.out.println("HTTP request: "+request.getRequestLine()); + for (Header header : request.getAllHeaders()) { + System.out.println(" "+header.getName()+": "+header.getValue()); + } + } + + // Set the request parameter to follow redirections. + HttpParams params = request.getParams(); + if (params instanceof ClientParamsStack) { + ClientParamsStack paramsStack = (ClientParamsStack)request.getParams(); + params = paramsStack.getRequestParams(); + } + HttpClientParams.setRedirecting(params, true); + } + }); + + httpClient.addResponseInterceptor(new HttpResponseInterceptor() { + @Override + public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { + if (verbose) { + System.out.println("HTTP response: "+response.getStatusLine()); + for (Header header : response.getAllHeaders()) { + System.out.println(" "+header.getName()+": "+header.getValue()); + } + } + } + }); + + httpClient.setRedirectStrategy(new DefaultRedirectStrategy() { + @Override + public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) + throws ProtocolException { + + HttpUriRequest uriRequest = super.getRedirect(request, response, context); + + URI uri = uriRequest.getURI(); + if (verbose) System.out.println("HTTP redirect: "+uri); + + // Redirect the original request to the new URI. + RequestWrapper wrapper; + if (request instanceof HttpEntityEnclosingRequest) { + wrapper = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest)request); + } else { + wrapper = new RequestWrapper(request); + } + wrapper.setURI(uri); + + return wrapper; + } + + @Override + public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) + throws ProtocolException { + + // The default redirection policy does not redirect POST or PUT. + // This overrides the policy to follow redirections for all HTTP methods. + return response.getStatusLine().getStatusCode() == 302; + } + }); + + executor = new ApacheHttpClient4Executor(httpClient); + providerFactory = ResteasyProviderFactory.getInstance(); + providerFactory.addClientErrorInterceptor(new PKIErrorInterceptor()); + errorHandler = new ClientErrorHandler(providerFactory.getClientErrorInterceptors()); + } + + private class ServerCertApprovalCB implements SSLCertificateApprovalCallback { + + // Callback to approve or deny returned SSL server cert. + // Right now, simply approve the cert. + public boolean approve(org.mozilla.jss.crypto.X509Certificate serverCert, + SSLCertificateApprovalCallback.ValidityStatus status) { + + if (verbose) System.out.println("Server certificate: "+serverCert.getSubjectDN()); + + SSLCertificateApprovalCallback.ValidityItem item; + + Enumeration errors = status.getReasons(); + while (errors.hasMoreElements()) { + item = (SSLCertificateApprovalCallback.ValidityItem) errors.nextElement(); + int reason = item.getReason(); + + if (reason == SSLCertificateApprovalCallback.ValidityStatus.UNTRUSTED_ISSUER || + reason == SSLCertificateApprovalCallback.ValidityStatus.BAD_CERT_DOMAIN) { + + // Allow these two since we haven't installed the CA cert for trust. + + return true; + + } + } + + // For other errors return false. + + return false; + } + } + + private class JSSProtocolSocketFactory implements SchemeSocketFactory, LayeredSchemeSocketFactory { + + @Override + public Socket createSocket(HttpParams params) throws IOException { + return null; + } + + @Override + public Socket connectSocket(Socket sock, + InetSocketAddress remoteAddress, + InetSocketAddress localAddress, + HttpParams params) + throws IOException, + UnknownHostException, + ConnectTimeoutException { + + // Initialize JSS before using SSLSocket, + // otherwise it will throw UnsatisfiedLinkError. + if (config.getCertDatabase() == null) { + try { + // No database specified, use $HOME/.pki/nssdb. + File homeDir = new File(System.getProperty("user.home")); + File pkiDir = new File(homeDir, ".pki"); + File nssdbDir = new File(pkiDir, "nssdb"); + nssdbDir.mkdirs(); + + CryptoManager.initialize(nssdbDir.getAbsolutePath()); + + } catch (AlreadyInitializedException e) { + // ignore + + } catch (Exception e) { + throw new Error(e); + } + + } else { + // Database specified, already initialized by the main program. + } + + String hostName = null; + int port = 0; + if (remoteAddress != null) { + hostName = remoteAddress.getHostName(); + port = remoteAddress.getPort(); + } + + int localPort = 0; + InetAddress localAddr = null; + + if (localAddress != null) { + localPort = localAddress.getPort(); + localAddr = localAddress.getAddress(); + } + + SSLSocket socket; + if (sock == null) { + socket = new SSLSocket(InetAddress.getByName(hostName), + port, + localAddr, + localPort, + new ServerCertApprovalCB(), + null); + + } else { + socket = new SSLSocket(sock, hostName, new ServerCertApprovalCB(), null); + } + + String certNickname = config.getCertNickname(); + if (certNickname != null) { + if (verbose) System.out.println("Client certificate: "+certNickname); + socket.setClientCertNickname(certNickname); + } + + return socket; + } + + @Override + public boolean isSecure(Socket sock) { + // We only use this factory in the case of SSL Connections. + return true; + } + + @Override + public Socket createLayeredSocket(Socket socket, String target, int port, boolean autoClose) + throws IOException, UnknownHostException { + // This method implementation is required to get SSL working. + return null; + } + + } + + public T createProxy(Class clazz) throws URISyntaxException { + URI uri = new URI(config.getServerURI()+"/rest"); + return ProxyFactory.create(clazz, uri, executor, providerFactory); + } + + @SuppressWarnings("unchecked") + public T getEntity(ClientResponse response) { + BaseClientResponse clientResponse = (BaseClientResponse)response; + try { + clientResponse.checkFailureStatus(); + + } catch (ClientResponseFailure e) { + errorHandler.clientErrorHandling((BaseClientResponse) e.getResponse(), e); + + } catch (RuntimeException e) { + errorHandler.clientErrorHandling(clientResponse, e); + } + + return response.getEntity(); + } + + public boolean isVerbose() { + return verbose; + } + + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } +} diff --git a/base/common/src/com/netscape/cms/client/PKIErrorInterceptor.java b/base/common/src/com/netscape/cms/client/PKIErrorInterceptor.java new file mode 100644 index 000000000..2c1936a6f --- /dev/null +++ b/base/common/src/com/netscape/cms/client/PKIErrorInterceptor.java @@ -0,0 +1,62 @@ +// --- BEGIN COPYRIGHT BLOCK --- +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; version 2 of the License. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// (C) 2007 Red Hat, Inc. +// All rights reserved. +// --- END COPYRIGHT BLOCK --- +package com.netscape.cms.client; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; + +import org.jboss.resteasy.client.ClientResponse; +import org.jboss.resteasy.client.core.ClientErrorInterceptor; + +import com.netscape.cms.servlet.base.PKIException; + +public class PKIErrorInterceptor implements ClientErrorInterceptor { + + public void handle(ClientResponse response) { + + // handle HTTP code 4xx and 5xx + int code = response.getResponseStatus().getStatusCode(); + if (code < 400) + return; + + MultivaluedMap headers = response.getHeaders(); + String contentType = headers.getFirst("Content-Type"); + + // handle XML content only + if (contentType == null || !contentType.startsWith(MediaType.APPLICATION_XML)) + return; + + PKIException exception; + + try { + // Requires RESTEasy 2.3.2 + // https://issues.jboss.org/browse/RESTEASY-652 + PKIException.Data data = response.getEntity(PKIException.Data.class); + + Class clazz = Class.forName(data.className); + exception = (PKIException) clazz.getConstructor(PKIException.Data.class).newInstance(data); + + } catch (Exception e) { + e.printStackTrace(); + return; + } + + throw exception; + } + +} diff --git a/base/common/src/com/netscape/cms/client/ca/CAClient.java b/base/common/src/com/netscape/cms/client/ca/CAClient.java new file mode 100644 index 000000000..17d017cce --- /dev/null +++ b/base/common/src/com/netscape/cms/client/ca/CAClient.java @@ -0,0 +1,141 @@ +//--- 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.client.ca; + +import java.net.URISyntaxException; +import java.util.Collection; + +import com.netscape.certsrv.dbs.certdb.CertId; +import com.netscape.certsrv.request.RequestId; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.PKIClient; +import com.netscape.cms.servlet.cert.CertResource; +import com.netscape.cms.servlet.cert.model.CertDataInfos; +import com.netscape.cms.servlet.cert.model.CertSearchRequest; +import com.netscape.cms.servlet.cert.model.CertData; +import com.netscape.cms.servlet.profile.ProfileResource; +import com.netscape.cms.servlet.profile.model.ProfileData; +import com.netscape.cms.servlet.profile.model.ProfileDataInfos; +import com.netscape.cms.servlet.request.CertRequestResource; +import com.netscape.cms.servlet.request.model.CertReviewResponse; +import com.netscape.cms.servlet.request.model.CertRequestInfo; +import com.netscape.cms.servlet.request.model.CertRequestInfos; +import com.netscape.cms.servlet.request.model.CertEnrollmentRequest; + +public class CAClient extends PKIClient { + + private CertResource certClient; + private CertRequestResource certRequestClient; + private ProfileResource profileClient; + + public CAClient(ClientConfig config) throws URISyntaxException { + super(config); + + certRequestClient = createProxy(CertRequestResource.class); + certClient = createProxy(CertResource.class); + profileClient = createProxy(ProfileResource.class); + } + + public Collection listRequests(String requestState, String requestType) { + CertRequestInfos infos = null; + Collection list = null; + infos = certRequestClient.listRequests( + requestState, requestType, new RequestId(0), 100, 100, 10); + list = infos.getRequests(); + + return list; + } + + public CertDataInfos listCerts(String status) { + return certClient.listCerts(status, 100, 10); + } + + public CertDataInfos searchCerts(CertSearchRequest data) { + return certClient.searchCerts(data, 100, 10); + } + + public ProfileDataInfos listProfiles() { + return profileClient.listProfiles(); + } + + public ProfileData getProfile(String id) { + + if (id == null) { + return null; + } + + return profileClient.retrieveProfile(id); + } + + public CertData getCertData(CertId id) { + + if (id == null) { + return null; + } + + return certClient.getCert(id); + + } + + public CertRequestInfos enrollCertificate(CertEnrollmentRequest data) { + if (data == null) { + return null; + } + + return certRequestClient.enrollCert(data); + } + + public CertRequestInfo getRequest(RequestId id) { + if (id == null) { + return null; + } + return certRequestClient.getRequestInfo(id); + } + + public CertReviewResponse reviewRequest(RequestId id) { + if (id == null) { + return null; + } + return certRequestClient.reviewRequest(id); + } + + public void approveRequest(RequestId id, CertReviewResponse data) { + certRequestClient.approveRequest(id, data); + } + + public void rejectRequest(RequestId id, CertReviewResponse data) { + certRequestClient.rejectRequest(id, data); + } + + public void cancelRequest(RequestId id, CertReviewResponse data) { + certRequestClient.cancelRequest(id, data); + } + + public void updateRequest(RequestId id, CertReviewResponse data) { + certRequestClient.updateRequest(id, data); + } + + public void validateRequest(RequestId id, CertReviewResponse data) { + certRequestClient.validateRequest(id, data); + } + + public void unassignRequest(RequestId id, CertReviewResponse data) { + certRequestClient.unassignRequest(id, data); + } + +} diff --git a/base/common/src/com/netscape/cms/client/cert/CertClient.java b/base/common/src/com/netscape/cms/client/cert/CertClient.java index fb2f61c75..254e8a143 100644 --- a/base/common/src/com/netscape/cms/client/cert/CertClient.java +++ b/base/common/src/com/netscape/cms/client/cert/CertClient.java @@ -21,14 +21,14 @@ import java.net.URISyntaxException; import com.netscape.certsrv.dbs.certdb.CertId; import com.netscape.certsrv.request.RequestId; -import com.netscape.cms.client.cli.ClientConfig; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.PKIClient; import com.netscape.cms.servlet.cert.CertResource; import com.netscape.cms.servlet.cert.model.CertDataInfos; import com.netscape.cms.servlet.cert.model.CertRevokeRequest; import com.netscape.cms.servlet.cert.model.CertSearchRequest; import com.netscape.cms.servlet.cert.model.CertUnrevokeRequest; import com.netscape.cms.servlet.cert.model.CertData; -import com.netscape.cms.servlet.csadmin.PKIClient; import com.netscape.cms.servlet.request.CertRequestResource; import com.netscape.cms.servlet.request.model.CertReviewResponse; import com.netscape.cms.servlet.request.model.CertRequestInfo; diff --git a/base/common/src/com/netscape/cms/client/cli/ClientConfig.java b/base/common/src/com/netscape/cms/client/cli/ClientConfig.java deleted file mode 100644 index 8b5380805..000000000 --- a/base/common/src/com/netscape/cms/client/cli/ClientConfig.java +++ /dev/null @@ -1,189 +0,0 @@ -// --- BEGIN COPYRIGHT BLOCK --- -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; version 2 of the License. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License along -// with this program; if not, write to the Free Software Foundation, Inc., -// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -// -// (C) 2012 Red Hat, Inc. -// All rights reserved. -// --- END COPYRIGHT BLOCK --- - -package com.netscape.cms.client.cli; - -import java.io.StringReader; -import java.io.StringWriter; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @author Endi S. Dewata - */ -@XmlRootElement(name="Client") -public class ClientConfig { - - public static Marshaller marshaller; - public static Unmarshaller unmarshaller; - - static { - try { - marshaller = JAXBContext.newInstance(ClientConfig.class).createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - unmarshaller = JAXBContext.newInstance(ClientConfig.class).createUnmarshaller(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - URI serverURI; - - String certDatabase; - String certNickname; - String username; - String password; - - @XmlElement(name="ServerURI") - public URI getServerURI() { - return serverURI; - } - - public void setServerURI(String serverUri) throws URISyntaxException { - this.serverURI = new URI(serverUri); - } - - public void setServerURI(URI serverUri) { - this.serverURI = serverUri; - } - - @XmlElement(name="CertDatabase") - public String getCertDatabase() { - return certDatabase; - } - - public void setCertDatabase(String certDatabase) { - this.certDatabase = certDatabase; - } - - @XmlElement(name="CertNickname") - public String getCertNickname() { - return certNickname; - } - - public void setCertNickname(String certNickname) { - this.certNickname = certNickname; - } - - @XmlElement(name="Username") - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - @XmlElement(name="Password") - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((certDatabase == null) ? 0 : certDatabase.hashCode()); - result = prime * result + ((certNickname == null) ? 0 : certNickname.hashCode()); - result = prime * result + ((password == null) ? 0 : password.hashCode()); - result = prime * result + ((serverURI == null) ? 0 : serverURI.hashCode()); - result = prime * result + ((username == null) ? 0 : username.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ClientConfig other = (ClientConfig) obj; - if (certDatabase == null) { - if (other.certDatabase != null) - return false; - } else if (!certDatabase.equals(other.certDatabase)) - return false; - if (certNickname == null) { - if (other.certNickname != null) - return false; - } else if (!certNickname.equals(other.certNickname)) - return false; - if (password == null) { - if (other.password != null) - return false; - } else if (!password.equals(other.password)) - return false; - if (serverURI == null) { - if (other.serverURI != null) - return false; - } else if (!serverURI.equals(other.serverURI)) - return false; - if (username == null) { - if (other.username != null) - return false; - } else if (!username.equals(other.username)) - return false; - return true; - } - - public String toString() { - try { - StringWriter sw = new StringWriter(); - marshaller.marshal(this, sw); - return sw.toString(); - - } catch (Exception e) { - return super.toString(); - } - } - - public static ClientConfig valueOf(String string) throws Exception { - try { - return (ClientConfig)unmarshaller.unmarshal(new StringReader(string)); - } catch (Exception e) { - return null; - } - } - - public static void main(String args[]) throws Exception { - - ClientConfig before = new ClientConfig(); - before.setServerURI("http://localhost:9180/ca"); - before.setCertDatabase("certs"); - before.setCertNickname("caadmin"); - before.setPassword("12345"); - - String string = before.toString(); - System.out.println(string); - - ClientConfig after = ClientConfig.valueOf(string); - System.out.println(before.equals(after)); - } -} diff --git a/base/common/src/com/netscape/cms/client/cli/MainCLI.java b/base/common/src/com/netscape/cms/client/cli/MainCLI.java index 50c90d892..2398a3837 100644 --- a/base/common/src/com/netscape/cms/client/cli/MainCLI.java +++ b/base/common/src/com/netscape/cms/client/cli/MainCLI.java @@ -30,6 +30,7 @@ import org.mozilla.jss.crypto.CryptoToken; import org.mozilla.jss.util.IncorrectPasswordException; import org.mozilla.jss.util.Password; +import com.netscape.cms.client.ClientConfig; import com.netscape.cms.client.cert.CertCLI; import com.netscape.cms.client.group.GroupCLI; import com.netscape.cms.client.user.UserCLI; diff --git a/base/common/src/com/netscape/cms/client/group/GroupClient.java b/base/common/src/com/netscape/cms/client/group/GroupClient.java index 410c1ad3d..b3784ef46 100644 --- a/base/common/src/com/netscape/cms/client/group/GroupClient.java +++ b/base/common/src/com/netscape/cms/client/group/GroupClient.java @@ -27,8 +27,8 @@ import com.netscape.certsrv.group.GroupMemberCollection; import com.netscape.certsrv.group.GroupMemberData; import com.netscape.certsrv.group.GroupMemberResource; import com.netscape.certsrv.group.GroupResource; -import com.netscape.cms.client.cli.ClientConfig; -import com.netscape.cms.servlet.csadmin.PKIClient; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.PKIClient; /** * @author Endi S. Dewata diff --git a/base/common/src/com/netscape/cms/client/kra/DRMClient.java b/base/common/src/com/netscape/cms/client/kra/DRMClient.java new file mode 100644 index 000000000..2332eacb2 --- /dev/null +++ b/base/common/src/com/netscape/cms/client/kra/DRMClient.java @@ -0,0 +1,130 @@ +package com.netscape.cms.client.kra; + +import java.net.URISyntaxException; +import java.util.Collection; +import java.util.Iterator; + +import org.jboss.resteasy.client.ClientResponse; + +import com.netscape.certsrv.dbs.keydb.KeyId; +import com.netscape.certsrv.request.RequestId; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.PKIClient; +import com.netscape.cms.servlet.admin.SystemCertificateResource; +import com.netscape.cms.servlet.cert.model.CertData; +import com.netscape.cms.servlet.key.KeyResource; +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.KeyRequestResource; +import com.netscape.cms.servlet.request.model.KeyArchivalRequest; +import com.netscape.cms.servlet.request.model.KeyRequestInfo; +import com.netscape.cms.servlet.request.model.KeyRequestInfos; +import com.netscape.cms.servlet.request.model.KeyRecoveryRequest; +import com.netscape.cmsutil.util.Utils; + +public class DRMClient extends PKIClient { + + private KeyResource keyClient; + private KeyRequestResource keyRequestClient; + private SystemCertificateResource systemCertClient; + + public DRMClient(ClientConfig config) throws URISyntaxException { + super(config); + + systemCertClient = createProxy(SystemCertificateResource.class); + keyRequestClient = createProxy(KeyRequestResource.class); + keyClient = createProxy(KeyResource.class); + } + + public String getTransportCert() { + @SuppressWarnings("unchecked") + ClientResponse response = (ClientResponse) systemCertClient + .getTransportCert(); + CertData certData = getEntity(response); + String transportCert = certData.getEncoded(); + return transportCert; + } + + public Collection listRequests(String requestState, String requestType) { + KeyRequestInfos infos = keyRequestClient.listRequests( + requestState, requestType, null, new RequestId(0), 100, 100, 10 + ); + Collection list = infos.getRequests(); + return list; + } + + public KeyRequestInfo archiveSecurityData(byte[] encoded, String clientId, String dataType) { + // create archival request + KeyArchivalRequest data = new KeyArchivalRequest(); + String req1 = Utils.base64encode(encoded); + data.setWrappedPrivateData(req1); + data.setClientId(clientId); + data.setDataType(dataType); + + KeyRequestInfo info = keyRequestClient.archiveKey(data); + return info; + } + + public KeyDataInfo getKeyData(String clientId, String status) { + KeyDataInfos infos = keyClient.listKeys(clientId, status, 100, 10); + Collection list = infos.getKeyInfos(); + Iterator iter = list.iterator(); + + while (iter.hasNext()) { + KeyDataInfo info = iter.next(); + if (info != null) { + // return the first one + return info; + } + } + return null; + } + + public KeyRequestInfo requestRecovery(KeyId keyId, byte[] rpwd, byte[] rkey, byte[] nonceData) { + // create recovery request + KeyRecoveryRequest data = new KeyRecoveryRequest(); + data.setKeyId(keyId); + if (rpwd != null) { + data.setSessionWrappedPassphrase(Utils.base64encode(rpwd)); + } + if (rkey != null) { + data.setTransWrappedSessionKey(Utils.base64encode(rkey)); + } + + if (nonceData != null) { + data.setNonceData(Utils.base64encode(nonceData)); + } + + KeyRequestInfo info = keyRequestClient.recoverKey(data); + return info; + } + + public void approveRecovery(RequestId recoveryId) { + keyRequestClient.approveRequest(recoveryId); + } + + public KeyData retrieveKey(KeyId keyId, RequestId requestId, byte[] rpwd, byte[] rkey, byte[] nonceData) { + // create recovery request + KeyRecoveryRequest data = new KeyRecoveryRequest(); + data.setKeyId(keyId); + data.setRequestId(requestId); + if (rkey != null) { + data.setTransWrappedSessionKey(Utils.base64encode(rkey)); + } + if (rpwd != null) { + data.setSessionWrappedPassphrase(Utils.base64encode(rpwd)); + } + + if (nonceData != null) { + data.setNonceData(Utils.base64encode(nonceData)); + } + + KeyData key = keyClient.retrieveKey(data); + return key; + } + + public KeyRequestInfo getRequest(RequestId id) { + return keyRequestClient.getRequestInfo(id); + } +} diff --git a/base/common/src/com/netscape/cms/client/system/SystemConfigClient.java b/base/common/src/com/netscape/cms/client/system/SystemConfigClient.java new file mode 100644 index 000000000..c01558ed3 --- /dev/null +++ b/base/common/src/com/netscape/cms/client/system/SystemConfigClient.java @@ -0,0 +1,52 @@ +// --- 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.client.system; + +import java.net.URISyntaxException; + +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.PKIClient; +import com.netscape.cms.servlet.csadmin.SystemConfigResource; +import com.netscape.cms.servlet.csadmin.model.ConfigurationRequest; +import com.netscape.cms.servlet.csadmin.model.ConfigurationResponse; +import com.netscape.cms.servlet.csadmin.model.InstallToken; +import com.netscape.cms.servlet.csadmin.model.InstallTokenRequest; + + +/** + * @author alee + * + */ +public class SystemConfigClient extends PKIClient { + + private SystemConfigResource configClient; + + public SystemConfigClient(ClientConfig config) throws URISyntaxException { + super(config); + + configClient = createProxy(SystemConfigResource.class); + } + + public ConfigurationResponse configure(ConfigurationRequest data) { + return configClient.configure(data); + } + + public InstallToken getInstallToken(InstallTokenRequest data) { + return configClient.getInstallToken(data); + } +} diff --git a/base/common/src/com/netscape/cms/client/user/UserClient.java b/base/common/src/com/netscape/cms/client/user/UserClient.java index ea2991ac8..010468e8a 100644 --- a/base/common/src/com/netscape/cms/client/user/UserClient.java +++ b/base/common/src/com/netscape/cms/client/user/UserClient.java @@ -27,8 +27,8 @@ import com.netscape.certsrv.user.UserCertResource; import com.netscape.certsrv.user.UserCollection; import com.netscape.certsrv.user.UserData; import com.netscape.certsrv.user.UserResource; -import com.netscape.cms.client.cli.ClientConfig; -import com.netscape.cms.servlet.csadmin.PKIClient; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.PKIClient; /** * @author Endi S. Dewata diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java b/base/common/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java index be66f5cf7..4c9caf5c1 100644 --- a/base/common/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java +++ b/base/common/src/com/netscape/cms/servlet/csadmin/ConfigurationUtils.java @@ -143,7 +143,8 @@ import com.netscape.certsrv.ocsp.IOCSPAuthority; import com.netscape.certsrv.usrgrp.IGroup; import com.netscape.certsrv.usrgrp.IUGSubsystem; import com.netscape.certsrv.usrgrp.IUser; -import com.netscape.cms.client.cli.ClientConfig; +import com.netscape.cms.client.ClientConfig; +import com.netscape.cms.client.system.SystemConfigClient; import com.netscape.cms.servlet.csadmin.model.InstallToken; import com.netscape.cms.servlet.csadmin.model.InstallTokenRequest; import com.netscape.cmsutil.crypto.CryptoUtil; diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/PKIClient.java b/base/common/src/com/netscape/cms/servlet/csadmin/PKIClient.java deleted file mode 100644 index 647056bd1..000000000 --- a/base/common/src/com/netscape/cms/servlet/csadmin/PKIClient.java +++ /dev/null @@ -1,305 +0,0 @@ -package com.netscape.cms.servlet.csadmin; - -import java.io.File; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.http.Header; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.ProtocolException; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.auth.params.AuthPNames; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.params.AuthPolicy; -import org.apache.http.client.params.HttpClientParams; -import org.apache.http.conn.scheme.LayeredSchemeSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeSocketFactory; -import org.apache.http.impl.client.ClientParamsStack; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.client.DefaultRedirectStrategy; -import org.apache.http.impl.client.EntityEnclosingRequestWrapper; -import org.apache.http.impl.client.RequestWrapper; -import org.apache.http.params.HttpParams; -import org.apache.http.protocol.HttpContext; -import org.jboss.resteasy.client.ClientExecutor; -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.ClientResponseFailure; -import org.jboss.resteasy.client.ProxyFactory; -import org.jboss.resteasy.client.core.BaseClientResponse; -import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor; -import org.jboss.resteasy.client.core.extractors.ClientErrorHandler; -import org.jboss.resteasy.spi.ResteasyProviderFactory; -import org.mozilla.jss.CryptoManager; -import org.mozilla.jss.crypto.AlreadyInitializedException; -import org.mozilla.jss.ssl.SSLCertificateApprovalCallback; -import org.mozilla.jss.ssl.SSLSocket; - -import com.netscape.cms.client.cli.ClientConfig; - -public abstract class PKIClient { - - protected boolean verbose; - - protected ClientConfig config; - - protected ResteasyProviderFactory providerFactory; - protected ClientErrorHandler errorHandler; - protected ClientExecutor executor; - - public PKIClient(ClientConfig config) { - this.config = config; - - DefaultHttpClient httpClient = new DefaultHttpClient(); - - // Register https scheme. - Scheme scheme = new Scheme("https", 443, new JSSProtocolSocketFactory()); - httpClient.getConnectionManager().getSchemeRegistry().register(scheme); - - if (config.getUsername() != null && config.getPassword() != null) { - List authPref = new ArrayList(); - authPref.add(AuthPolicy.BASIC); - httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref); - - httpClient.getCredentialsProvider().setCredentials( - AuthScope.ANY, - new UsernamePasswordCredentials(config.getUsername(), config.getPassword())); - } - - httpClient.addRequestInterceptor(new HttpRequestInterceptor() { - @Override - public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { - if (verbose) { - System.out.println("HTTP request: "+request.getRequestLine()); - for (Header header : request.getAllHeaders()) { - System.out.println(" "+header.getName()+": "+header.getValue()); - } - } - - // Set the request parameter to follow redirections. - HttpParams params = request.getParams(); - if (params instanceof ClientParamsStack) { - ClientParamsStack paramsStack = (ClientParamsStack)request.getParams(); - params = paramsStack.getRequestParams(); - } - HttpClientParams.setRedirecting(params, true); - } - }); - - httpClient.addResponseInterceptor(new HttpResponseInterceptor() { - @Override - public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { - if (verbose) { - System.out.println("HTTP response: "+response.getStatusLine()); - for (Header header : response.getAllHeaders()) { - System.out.println(" "+header.getName()+": "+header.getValue()); - } - } - } - }); - - httpClient.setRedirectStrategy(new DefaultRedirectStrategy() { - @Override - public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) - throws ProtocolException { - - HttpUriRequest uriRequest = super.getRedirect(request, response, context); - - URI uri = uriRequest.getURI(); - if (verbose) System.out.println("HTTP redirect: "+uri); - - // Redirect the original request to the new URI. - RequestWrapper wrapper; - if (request instanceof HttpEntityEnclosingRequest) { - wrapper = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest)request); - } else { - wrapper = new RequestWrapper(request); - } - wrapper.setURI(uri); - - return wrapper; - } - - @Override - public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) - throws ProtocolException { - - // The default redirection policy does not redirect POST or PUT. - // This overrides the policy to follow redirections for all HTTP methods. - return response.getStatusLine().getStatusCode() == 302; - } - }); - - executor = new ApacheHttpClient4Executor(httpClient); - providerFactory = ResteasyProviderFactory.getInstance(); - providerFactory.addClientErrorInterceptor(new PKIErrorInterceptor()); - errorHandler = new ClientErrorHandler(providerFactory.getClientErrorInterceptors()); - } - - private class ServerCertApprovalCB implements SSLCertificateApprovalCallback { - - // Callback to approve or deny returned SSL server cert. - // Right now, simply approve the cert. - public boolean approve(org.mozilla.jss.crypto.X509Certificate serverCert, - SSLCertificateApprovalCallback.ValidityStatus status) { - - if (verbose) System.out.println("Server certificate: "+serverCert.getSubjectDN()); - - SSLCertificateApprovalCallback.ValidityItem item; - - Enumeration errors = status.getReasons(); - while (errors.hasMoreElements()) { - item = (SSLCertificateApprovalCallback.ValidityItem) errors.nextElement(); - int reason = item.getReason(); - - if (reason == SSLCertificateApprovalCallback.ValidityStatus.UNTRUSTED_ISSUER || - reason == SSLCertificateApprovalCallback.ValidityStatus.BAD_CERT_DOMAIN) { - - // Allow these two since we haven't installed the CA cert for trust. - - return true; - - } - } - - // For other errors return false. - - return false; - } - } - - private class JSSProtocolSocketFactory implements SchemeSocketFactory, LayeredSchemeSocketFactory { - - @Override - public Socket createSocket(HttpParams params) throws IOException { - return null; - } - - @Override - public Socket connectSocket(Socket sock, - InetSocketAddress remoteAddress, - InetSocketAddress localAddress, - HttpParams params) - throws IOException, - UnknownHostException, - ConnectTimeoutException { - - // Initialize JSS before using SSLSocket, - // otherwise it will throw UnsatisfiedLinkError. - if (config.getCertDatabase() == null) { - try { - // No database specified, use $HOME/.pki/nssdb. - File homeDir = new File(System.getProperty("user.home")); - File pkiDir = new File(homeDir, ".pki"); - File nssdbDir = new File(pkiDir, "nssdb"); - nssdbDir.mkdirs(); - - CryptoManager.initialize(nssdbDir.getAbsolutePath()); - - } catch (AlreadyInitializedException e) { - // ignore - - } catch (Exception e) { - throw new Error(e); - } - - } else { - // Database specified, already initialized by the main program. - } - - String hostName = null; - int port = 0; - if (remoteAddress != null) { - hostName = remoteAddress.getHostName(); - port = remoteAddress.getPort(); - } - - int localPort = 0; - InetAddress localAddr = null; - - if (localAddress != null) { - localPort = localAddress.getPort(); - localAddr = localAddress.getAddress(); - } - - SSLSocket socket; - if (sock == null) { - socket = new SSLSocket(InetAddress.getByName(hostName), - port, - localAddr, - localPort, - new ServerCertApprovalCB(), - null); - - } else { - socket = new SSLSocket(sock, hostName, new ServerCertApprovalCB(), null); - } - - String certNickname = config.getCertNickname(); - if (certNickname != null) { - if (verbose) System.out.println("Client certificate: "+certNickname); - socket.setClientCertNickname(certNickname); - } - - return socket; - } - - @Override - public boolean isSecure(Socket sock) { - // We only use this factory in the case of SSL Connections. - return true; - } - - @Override - public Socket createLayeredSocket(Socket socket, String target, int port, boolean autoClose) - throws IOException, UnknownHostException { - // This method implementation is required to get SSL working. - return null; - } - - } - - public T createProxy(Class clazz) throws URISyntaxException { - URI uri = new URI(config.getServerURI()+"/rest"); - return ProxyFactory.create(clazz, uri, executor, providerFactory); - } - - @SuppressWarnings("unchecked") - public T getEntity(ClientResponse response) { - BaseClientResponse clientResponse = (BaseClientResponse)response; - try { - clientResponse.checkFailureStatus(); - - } catch (ClientResponseFailure e) { - errorHandler.clientErrorHandling((BaseClientResponse) e.getResponse(), e); - - } catch (RuntimeException e) { - errorHandler.clientErrorHandling(clientResponse, e); - } - - return response.getEntity(); - } - - public boolean isVerbose() { - return verbose; - } - - public void setVerbose(boolean verbose) { - this.verbose = verbose; - } -} diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/PKIErrorInterceptor.java b/base/common/src/com/netscape/cms/servlet/csadmin/PKIErrorInterceptor.java deleted file mode 100644 index 795c0fda3..000000000 --- a/base/common/src/com/netscape/cms/servlet/csadmin/PKIErrorInterceptor.java +++ /dev/null @@ -1,62 +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) 2007 Red Hat, Inc. -// All rights reserved. -// --- END COPYRIGHT BLOCK --- -package com.netscape.cms.servlet.csadmin; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; - -import org.jboss.resteasy.client.ClientResponse; -import org.jboss.resteasy.client.core.ClientErrorInterceptor; - -import com.netscape.cms.servlet.base.PKIException; - -public class PKIErrorInterceptor implements ClientErrorInterceptor { - - public void handle(ClientResponse response) { - - // handle HTTP code 4xx and 5xx - int code = response.getResponseStatus().getStatusCode(); - if (code < 400) - return; - - MultivaluedMap headers = response.getHeaders(); - String contentType = headers.getFirst("Content-Type"); - - // handle XML content only - if (contentType == null || !contentType.startsWith(MediaType.APPLICATION_XML)) - return; - - PKIException exception; - - try { - // Requires RESTEasy 2.3.2 - // https://issues.jboss.org/browse/RESTEASY-652 - PKIException.Data data = response.getEntity(PKIException.Data.class); - - Class clazz = Class.forName(data.className); - exception = (PKIException) clazz.getConstructor(PKIException.Data.class).newInstance(data); - - } catch (Exception e) { - e.printStackTrace(); - return; - } - - throw exception; - } - -} diff --git a/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigClient.java b/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigClient.java deleted file mode 100644 index 11815a65b..000000000 --- a/base/common/src/com/netscape/cms/servlet/csadmin/SystemConfigClient.java +++ /dev/null @@ -1,50 +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.net.URISyntaxException; - -import com.netscape.cms.client.cli.ClientConfig; -import com.netscape.cms.servlet.csadmin.model.ConfigurationRequest; -import com.netscape.cms.servlet.csadmin.model.ConfigurationResponse; -import com.netscape.cms.servlet.csadmin.model.InstallToken; -import com.netscape.cms.servlet.csadmin.model.InstallTokenRequest; - - -/** - * @author alee - * - */ -public class SystemConfigClient extends PKIClient { - - private SystemConfigResource configClient; - - public SystemConfigClient(ClientConfig config) throws URISyntaxException { - super(config); - - configClient = createProxy(SystemConfigResource.class); - } - - public ConfigurationResponse configure(ConfigurationRequest data) { - return configClient.configure(data); - } - - public InstallToken getInstallToken(InstallTokenRequest data) { - return configClient.getInstallToken(data); - } -} diff --git a/base/deploy/src/scriptlets/configuration.jy b/base/deploy/src/scriptlets/configuration.jy index 290a2cc65..7433ae463 100644 --- a/base/deploy/src/scriptlets/configuration.jy +++ b/base/deploy/src/scriptlets/configuration.jy @@ -17,7 +17,7 @@ from java.lang import System as javasystem # PKI Java Imports -from com.netscape.cms.client.cli import ClientConfig +from com.netscape.cms.client import ClientConfig def main(argv): diff --git a/base/deploy/src/scriptlets/pkijython.py b/base/deploy/src/scriptlets/pkijython.py index 18fabf9be..d2e7889ff 100644 --- a/base/deploy/src/scriptlets/pkijython.py +++ b/base/deploy/src/scriptlets/pkijython.py @@ -140,7 +140,7 @@ from org.mozilla.jss.util import Password # PKI Java Imports -from com.netscape.cms.servlet.csadmin import SystemConfigClient +from com.netscape.cms.client.system import SystemConfigClient from com.netscape.cms.servlet.csadmin.model import SystemCertData from com.netscape.cms.servlet.csadmin.model import ConfigurationRequest from com.netscape.cms.servlet.csadmin.model import ConfigurationResponse diff --git a/base/kra/functional/src/com/netscape/cms/servlet/test/DRMClient.java b/base/kra/functional/src/com/netscape/cms/servlet/test/DRMClient.java deleted file mode 100644 index dfb34ed13..000000000 --- a/base/kra/functional/src/com/netscape/cms/servlet/test/DRMClient.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.netscape.cms.servlet.test; - -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.Iterator; - -import org.jboss.resteasy.client.ClientResponse; - -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.admin.SystemCertificateResource; -import com.netscape.cms.servlet.cert.model.CertData; -import com.netscape.cms.servlet.csadmin.PKIClient; -import com.netscape.cms.servlet.key.KeyResource; -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.KeyRequestResource; -import com.netscape.cms.servlet.request.model.KeyArchivalRequest; -import com.netscape.cms.servlet.request.model.KeyRequestInfo; -import com.netscape.cms.servlet.request.model.KeyRequestInfos; -import com.netscape.cms.servlet.request.model.KeyRecoveryRequest; -import com.netscape.cmsutil.util.Utils; - -public class DRMClient extends PKIClient { - - private KeyResource keyClient; - private KeyRequestResource keyRequestClient; - private SystemCertificateResource systemCertClient; - - public DRMClient(ClientConfig config) throws URISyntaxException { - super(config); - - systemCertClient = createProxy(SystemCertificateResource.class); - keyRequestClient = createProxy(KeyRequestResource.class); - keyClient = createProxy(KeyResource.class); - } - - public String getTransportCert() { - @SuppressWarnings("unchecked") - ClientResponse response = (ClientResponse) systemCertClient - .getTransportCert(); - CertData certData = getEntity(response); - String transportCert = certData.getEncoded(); - return transportCert; - } - - public Collection listRequests(String requestState, String requestType) { - KeyRequestInfos infos = keyRequestClient.listRequests( - requestState, requestType, null, new RequestId(0), 100, 100, 10 - ); - Collection list = infos.getRequests(); - return list; - } - - public KeyRequestInfo archiveSecurityData(byte[] encoded, String clientId, String dataType) { - // create archival request - KeyArchivalRequest data = new KeyArchivalRequest(); - String req1 = Utils.base64encode(encoded); - data.setWrappedPrivateData(req1); - data.setClientId(clientId); - data.setDataType(dataType); - - KeyRequestInfo info = keyRequestClient.archiveKey(data); - return info; - } - - public KeyDataInfo getKeyData(String clientId, String status) { - KeyDataInfos infos = keyClient.listKeys(clientId, status, 100, 10); - Collection list = infos.getKeyInfos(); - Iterator iter = list.iterator(); - - while (iter.hasNext()) { - KeyDataInfo info = iter.next(); - if (info != null) { - // return the first one - return info; - } - } - return null; - } - - public KeyRequestInfo requestRecovery(KeyId keyId, byte[] rpwd, byte[] rkey, byte[] nonceData) { - // create recovery request - KeyRecoveryRequest data = new KeyRecoveryRequest(); - data.setKeyId(keyId); - if (rpwd != null) { - data.setSessionWrappedPassphrase(Utils.base64encode(rpwd)); - } - if (rkey != null) { - data.setTransWrappedSessionKey(Utils.base64encode(rkey)); - } - - if (nonceData != null) { - data.setNonceData(Utils.base64encode(nonceData)); - } - - KeyRequestInfo info = keyRequestClient.recoverKey(data); - return info; - } - - public void approveRecovery(RequestId recoveryId) { - keyRequestClient.approveRequest(recoveryId); - } - - public KeyData retrieveKey(KeyId keyId, RequestId requestId, byte[] rpwd, byte[] rkey, byte[] nonceData) { - // create recovery request - KeyRecoveryRequest data = new KeyRecoveryRequest(); - data.setKeyId(keyId); - data.setRequestId(requestId); - if (rkey != null) { - data.setTransWrappedSessionKey(Utils.base64encode(rkey)); - } - if (rpwd != null) { - data.setSessionWrappedPassphrase(Utils.base64encode(rpwd)); - } - - if (nonceData != null) { - data.setNonceData(Utils.base64encode(nonceData)); - } - - KeyData key = keyClient.retrieveKey(data); - return key; - } - - public KeyRequestInfo getRequest(RequestId id) { - return keyRequestClient.getRequestInfo(id); - } -} 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 3ccde1cd2..5a2013a60 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 @@ -39,7 +39,8 @@ 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.client.ClientConfig; +import com.netscape.cms.client.kra.DRMClient; import com.netscape.cms.servlet.base.PKIService; import com.netscape.cms.servlet.key.model.KeyData; import com.netscape.cms.servlet.key.model.KeyDataInfo; -- cgit