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

Java tutorial

Introduction

Here is the source code for mitm.common.security.ca.handlers.comodo.ApplyCustomClientCert.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.IOException;
import java.io.InputStream;
import java.util.Map;

import mitm.common.net.HTTPMethodExecutor;
import mitm.common.net.NetUtils;
import mitm.common.net.HTTPMethodExecutor.ResponseHandler;
import mitm.common.scheduler.TaskScheduler;
import mitm.common.util.Check;
import mitm.common.util.MiscArrayUtils;
import mitm.common.util.SizeLimitedInputStream;
import mitm.common.util.SizeUtils;

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.ArrayUtils;
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ApplyCustomClientCert is used to request a Comodo Custom Client Certificate.
 * 
 * @author Martijn Brinkers
 *
 */
public class ApplyCustomClientCert {
    private final static Logger logger = LoggerFactory.getLogger(ApplyCustomClientCert.class);

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

    /*
     * Alliance Partner Name (case insensitive)
     * 
     * If you don't know what to use here, you will find it in all of your Reseller Ordering URLs as the "ap=xxxx" 
     * parameter.
     * 
     * max length 64 chars. 
     */
    private String ap;

    /*
     * The particular CA to use. Leave blank to use the default.
     */
    private Integer cACertificateID;

    /*
     * Validity Period (in days)
     * 
     * 365, 730 or 1095 days.
     */
    private int days;

    /*
     * Base64 encoded PKCS#10 certificate request
     */
    private String pkcs10;

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

    /*
     * The error code if error is true
     */
    private CustomClientStatusCode errorCode;

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

    /*
     * The returned order number (if no error occurred)
     */
    private String orderNumber;

    /*
     * The returned collection code (if no error occurred)
     */
    private String collectionCode;

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

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

    public ApplyCustomClientCert(ComodoConnectionSettings connectionSettings) {
        Check.notNull(connectionSettings, "connectionSettings");
        Check.notNull(connectionSettings.getApplyCustomClientCertURL(), "url");

        this.connectionSettings = connectionSettings;
    }

    private String getValue(Map<String, String[]> parameters, String name) {
        return MiscArrayUtils.safeGet(parameters.get(name.toLowerCase()), 0);
    }

    private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
        if (statusCode != HttpStatus.SC_OK) {
            throw new IOException("Error applying for Custom Client Cert. 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);
        }

        Map<String, String[]> parameters = NetUtils.parseQuery(response);

        String errorCodeParam = getValue(parameters, "errorCode");

        if (!StringUtils.isEmpty(errorCodeParam)) {
            errorCode = CustomClientStatusCode.fromCode(errorCodeParam);

            error = true;

            errorMessage = getValue(parameters, "errorMessage");
        } else {
            error = false;

            orderNumber = getValue(parameters, "orderNumber");
            collectionCode = getValue(parameters, "collectionCode");

            if (StringUtils.isEmpty(orderNumber)) {
                throw new IOException(new CustomClientCertException("orderNumber is missing."));
            }
        }
    }

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

    /**
     *     
     */
    /**
     * Requests a certificate. Returns true if a certificate was successfully requested. 
     * @return true if successful, false if an error occurs
     * @throws CustomClientCertException
     */
    public boolean apply() throws CustomClientCertException {
        reset();

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

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

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

        NameValuePair[] data = { new NameValuePair("ap", ap), new NameValuePair("days", Integer.toString(days)),
                new NameValuePair("pkcs10", pkcs10), new NameValuePair("successURL", "none"),
                new NameValuePair("errorURL", "none") };

        if (cACertificateID != null) {
            data = (NameValuePair[]) ArrayUtils.add(data,
                    new NameValuePair("caCertificateID", cACertificateID.toString()));
        }

        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;
    }

    protected String getAP() {
        return ap;
    }

    protected void setAP(String ap) {
        this.ap = ap;
    }

    public Integer getCACertificateID() {
        return cACertificateID;
    }

    public void setCACertificateID(Integer certificateID) {
        cACertificateID = certificateID;
    }

    protected int getDays() {
        return days;
    }

    protected void setDays(int days) {
        /*
         * Days can only be 1, 2 or 3 years
         */
        if (days <= 365) {
            days = 365;
        } else if (days <= (365 * 2)) {
            days = 365 * 2;
        } else {
            days = 365 * 3;
        }

        this.days = days;
    }

    protected String getPkcs10() {
        return pkcs10;
    }

    protected void setPkcs10(String pkcs10) {
        this.pkcs10 = pkcs10;
    }

    protected boolean isError() {
        return error;
    }

    protected CustomClientStatusCode getErrorCode() {
        return errorCode;
    }

    protected String getErrorMessage() {
        return errorMessage;
    }

    protected String getOrderNumber() {
        return orderNumber;
    }

    protected String getCollectionCode() {
        return collectionCode;
    }
}