mitm.common.security.ca.handlers.comodo.CollectCustomClientCert.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.security.ca.handlers.comodo.CollectCustomClientCert.java

Source

/*
 * Copyright (c) 2010-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.security.ca.handlers.comodo;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collection;

import mitm.common.net.HTTPMethodExecutor;
import mitm.common.net.HTTPMethodExecutor.ResponseHandler;
import mitm.common.scheduler.TaskScheduler;
import mitm.common.security.certificate.CertificateUtils;
import mitm.common.util.Check;
import mitm.common.util.MiscStringUtils;
import mitm.common.util.SizeLimitedInputStream;
import mitm.common.util.SizeUtils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Used to retrieve a certificate from Comodo's EPKI
 * 
 * @author Martijn Brinkers
 *
 */
public class CollectCustomClientCert {
    private final static Logger logger = LoggerFactory.getLogger(CollectCustomClientCert.class);

    /*
     * Maximum allowed response size returned from a call to the Comodo service
     */
    private final static int MAX_HTTP_RESPONSE_SIZE = 100 * SizeUtils.KB;

    /*
     * Tier account username (max 64 chars)
     */
    private String loginName;

    /*
     * Tier account password.
     */
    private String loginPassword;

    /*
     * The order number to retrieve.
     */
    private String orderNumber;

    /*
     * The connection settings
     */
    private final ComodoConnectionSettings connectionSettings;

    /*
     * True if an error occurred.
     */
    private boolean error;

    /*
     * The status code
     */
    private CustomClientStatusCode errorCode;

    /*
     * The error message if error is true
     */
    private String errorMessage;

    /*
     * The collected certificate, if available, or null if not available.
     */
    private X509Certificate certificate;

    private ResponseHandler responseHandler = new ResponseHandler() {
        @Override
        public void handleResponse(int statusCode, HttpMethod httpMethod, TaskScheduler watchdog)
                throws IOException, HttpException {
            CollectCustomClientCert.this.handleResponse(statusCode, httpMethod);
        }
    };

    public CollectCustomClientCert(ComodoConnectionSettings connectionSettings) {
        Check.notNull(connectionSettings, "connectionSettings");
        Check.notNull(connectionSettings.getCollectCustomClientCertURL(), "url");

        this.connectionSettings = connectionSettings;
    }

    private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("Error Collecting certificate. Message: " + httpMethod.getStatusLine());
        }

        InputStream input = httpMethod.getResponseBodyAsStream();

        if (input == null) {
            throw new IOException("Response body is null.");
        }

        /*
         * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
         */
        InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

        String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

        if (logger.isDebugEnabled()) {
            logger.debug("Response:\r\n" + response);
        }

        LineNumberReader lineReader = new LineNumberReader(new StringReader(response));

        String statusParameter = lineReader.readLine();

        errorCode = CustomClientStatusCode.fromCode(statusParameter);

        if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) {
            error = true;

            errorMessage = lineReader.readLine();
        } else {
            error = false;

            if (errorCode == CustomClientStatusCode.CERTIFICATES_ATTACHED) {
                /*
                 * The certificate is base64 encoded between -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----
                 */

                StrBuilder base64 = new StrBuilder(4096);

                /* 
                 * Skip -----BEGIN CERTIFICATE-----
                 */
                String line = lineReader.readLine();

                if (!"-----BEGIN CERTIFICATE-----".equalsIgnoreCase(line)) {
                    throw new IOException("-----BEGIN CERTIFICATE----- expected but got: " + line);
                }

                do {
                    line = lineReader.readLine();

                    if ("-----END CERTIFICATE-----".equalsIgnoreCase(line)) {
                        break;
                    }

                    if (line != null) {
                        base64.append(line);
                    }
                } while (line != null);

                try {
                    byte[] decoded = Base64.decodeBase64(MiscStringUtils.toAsciiBytes(base64.toString()));

                    Collection<X509Certificate> certificates = CertificateUtils
                            .readX509Certificates(new ByteArrayInputStream(decoded));

                    if (certificates != null && certificates.size() > 0) {
                        certificate = certificates.iterator().next();
                    }
                } catch (CertificateException e) {
                    throw new IOException(e);
                } catch (NoSuchProviderException e) {
                    throw new IOException(e);
                }
            }
        }
    }

    private void reset() {
        error = false;
        errorCode = null;
        errorMessage = null;
        certificate = null;
    }

    /**
     * Collects the certificate with the given orderNummer. 
     * @return true if successful, false if an error occurs
     * @throws CustomClientCertException
     */
    public boolean collectCertificate() throws CustomClientCertException {
        reset();

        if (StringUtils.isEmpty(loginName)) {
            throw new CustomClientCertException("loginName must be specified.");
        }

        if (StringUtils.isEmpty(loginPassword)) {
            throw new CustomClientCertException("loginPassword must be specified.");
        }

        if (StringUtils.isEmpty(orderNumber)) {
            throw new CustomClientCertException("orderNumber must be specified.");
        }

        PostMethod postMethod = new PostMethod(connectionSettings.getCollectCustomClientCertURL());

        NameValuePair[] data = { new NameValuePair("loginName", loginName),
                new NameValuePair("loginPassword", loginPassword), new NameValuePair("orderNumber", orderNumber),
                new NameValuePair("queryType", /* status and cert only */ "2"),
                new NameValuePair("responseType", /* Individually encoded */ "3"),
                new NameValuePair("responseEncoding", /* base64 */ "0") };

        postMethod.setRequestBody(data);

        HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
                connectionSettings.getProxyInjector());

        executor.setConnectTimeout(connectionSettings.getConnectTimeout());
        executor.setReadTimeout(connectionSettings.getReadTimeout());

        try {
            executor.executeMethod(postMethod, responseHandler);
        } catch (IOException e) {
            throw new CustomClientCertException(e);
        }

        return !error;
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }

    public String getLoginPassword() {
        return loginPassword;
    }

    public void setLoginPassword(String loginPassword) {
        this.loginPassword = loginPassword;
    }

    public String getOrderNumber() {
        return orderNumber;
    }

    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }

    public boolean isError() {
        return error;
    }

    public CustomClientStatusCode getErrorCode() {
        return errorCode;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public X509Certificate getCertificate() {
        return certificate;
    }
}