mitm.application.djigzo.ws.impl.X509CertStoreWSImpl.java Source code

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.ws.impl.X509CertStoreWSImpl.java

Source

/*
 * Copyright (c) 2008-2012, 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.application.djigzo.ws.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.NoSuchProviderException;
import java.security.cert.CertStoreException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.jws.WebParam;

import mitm.application.djigzo.ws.WSExceptionUtils;
import mitm.application.djigzo.ws.X509CertStoreWS;
import mitm.application.djigzo.ws.X509CertificateDTO;
import mitm.application.djigzo.ws.X509CertificateDTOBuilder;
import mitm.common.hibernate.annotations.StartTransaction;
import mitm.common.security.SecurityFactoryFactoryException;
import mitm.common.security.asn1.ObjectEncoding;
import mitm.common.security.certificate.CertificateEncoder;
import mitm.common.security.certificate.CertificateUtils;
import mitm.common.security.certstore.CertificateAlreadyExistsException;
import mitm.common.security.certstore.Expired;
import mitm.common.security.certstore.Match;
import mitm.common.security.certstore.MissingKeyAlias;
import mitm.common.security.certstore.X509CertStoreEntry;
import mitm.common.security.certstore.X509CertStoreExt;
import mitm.common.util.Check;
import mitm.common.util.CloseableIterator;
import mitm.common.util.CloseableIteratorException;
import mitm.common.ws.WebServiceCheckedException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class X509CertStoreWSImpl implements X509CertStoreWS {
    private final static Logger logger = LoggerFactory.getLogger(HierarchicalPropertiesWSImpl.class);

    /*
     * Store with all the certificates
     */
    private final X509CertStoreExt certStore;

    /*
     * For building X509 Certificate DTOs
     */
    private final X509CertificateDTOBuilder certificateDTOBuilder;

    public X509CertStoreWSImpl(X509CertStoreExt certStore, X509CertificateDTOBuilder certificateDTOBuilder) {
        Check.notNull(certStore, "certStore");
        Check.notNull(certificateDTOBuilder, "certificateDTOBuilder");

        this.certStore = certStore;
        this.certificateDTOBuilder = certificateDTOBuilder;
    }

    @Override
    @StartTransaction
    public List<X509CertificateDTO> getByEmail(String email, Match match, Expired expired,
            MissingKeyAlias missingKeyAlias, Integer firstResult, Integer maxResults)
            throws WebServiceCheckedException {
        if (match == null) {
            throw new WebServiceCheckedException("match is missing.");
        }

        if (expired == null) {
            throw new WebServiceCheckedException("expired is missing.");
        }

        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            List<X509CertificateDTO> certificates = getByEmailAction(email, match, expired, missingKeyAlias,
                    firstResult, maxResults);

            return certificates;
        } catch (WebServiceCheckedException e) {
            logger.error("getByEmail failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getByEmail failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public long getByEmailCount(String email, Match match, Expired expired, MissingKeyAlias missingKeyAlias)
            throws WebServiceCheckedException {
        if (match == null) {
            throw new WebServiceCheckedException("match is missing.");
        }

        if (expired == null) {
            throw new WebServiceCheckedException("expired is missing.");
        }

        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            return certStore.getByEmailCount(email, match, expired, missingKeyAlias);
        } catch (CertStoreException e) {
            logger.error("getByEmailCount failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getByEmailCount failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public List<X509CertificateDTO> getCertificates(Expired expired, MissingKeyAlias missingKeyAlias,
            Integer firstResult, Integer maxResults) throws WebServiceCheckedException {
        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            return getCertificatesAction(expired, missingKeyAlias, firstResult, maxResults);
        } catch (WebServiceCheckedException e) {
            logger.error("getCertificates failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getCertificates failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public byte[] getEncodedCertificate(String thumbprint, ObjectEncoding encoding)
            throws WebServiceCheckedException {
        if (thumbprint == null) {
            throw new WebServiceCheckedException("thumbprint is missing.");
        }

        if (encoding == null) {
            encoding = ObjectEncoding.PEM;
        }

        try {
            byte[] encodedCertificate = getEncodedCertificateAction(thumbprint, encoding);

            return encodedCertificate;
        } catch (WebServiceCheckedException e) {
            logger.error("getCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public byte[] getEncodedCertificates(List<String> thumbprints, ObjectEncoding encoding)
            throws WebServiceCheckedException {
        if (thumbprints == null) {
            throw new WebServiceCheckedException("thumbprints are missing.");
        }

        if (encoding == null) {
            encoding = ObjectEncoding.PEM;
        }

        try {
            byte[] encodedCertificate = getEncodedCertificatesAction(thumbprints, encoding);

            return encodedCertificate;
        } catch (WebServiceCheckedException e) {
            logger.error("getCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    /**
     * Adds certificates to the store. The certificates are added in one transaction. If you want each
     * certificate to be added in it's own transaction call it multiple times or use 
     * KeyAndCertificateWorkflowWS
     */
    @Override
    @StartTransaction
    public int addCertificates(byte[] encodedCertificates) throws WebServiceCheckedException {
        if (encodedCertificates == null || encodedCertificates.length == 0) {
            throw new WebServiceCheckedException("encodedCertificate is missing.");
        }

        try {
            return addCertificatesAction(encodedCertificates);
        } catch (WebServiceCheckedException e) {
            logger.error("addCertificates failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("addCertificates failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public void removeCertificate(String thumbprint) throws WebServiceCheckedException {
        if (thumbprint == null) {
            throw new WebServiceCheckedException("thumbprint is missing.");
        }

        try {
            removeCertificateAction(thumbprint);
        } catch (WebServiceCheckedException e) {
            logger.error("removeCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("removeCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public X509CertificateDTO getCertificate(String thumbprint) throws WebServiceCheckedException {
        if (thumbprint == null) {
            throw new WebServiceCheckedException("thumbprint is missing.");
        }

        try {
            return getCertificateAction(thumbprint);
        } catch (WebServiceCheckedException e) {
            logger.error("getCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getCertificate failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public long size(@WebParam(name = "expired") Expired expired,
            @WebParam(name = "missingKeyAlias") MissingKeyAlias missingKeyAlias) throws WebServiceCheckedException {
        return certStore.size(expired, missingKeyAlias);
    }

    @Override
    @StartTransaction
    public List<X509CertificateDTO> searchBySubject(String subject, Expired expired,
            MissingKeyAlias missingKeyAlias, Integer firstResult, Integer maxResults)
            throws WebServiceCheckedException {
        subject = StringUtils.defaultString(subject);

        if (expired == null) {
            throw new WebServiceCheckedException("expired is missing.");
        }

        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            return searchBySubjectAction(subject, expired, missingKeyAlias, firstResult, maxResults);
        } catch (WebServiceCheckedException e) {
            logger.error("searchBySubject failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("searchBySubject failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public long getSearchBySubjectCount(String subject, Expired expired, MissingKeyAlias missingKeyAlias)
            throws WebServiceCheckedException {
        subject = StringUtils.defaultString(subject);

        if (expired == null) {
            throw new WebServiceCheckedException("expired is missing.");
        }

        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            return certStore.getSearchBySubjectCount(subject, expired, missingKeyAlias);
        } catch (CertStoreException e) {
            logger.error("getSearchBySubjectCount failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getSearchBySubjectCount failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public List<X509CertificateDTO> searchByIssuer(String issuer, Expired expired, MissingKeyAlias missingKeyAlias,
            Integer firstResult, Integer maxResults) throws WebServiceCheckedException {
        issuer = StringUtils.defaultString(issuer);

        if (expired == null) {
            throw new WebServiceCheckedException("expired is missing.");
        }

        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            return searchByIssuerAction(issuer, expired, missingKeyAlias, firstResult, maxResults);
        } catch (WebServiceCheckedException e) {
            logger.error("searchByIssuer failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("searchByIssuer failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    @Override
    @StartTransaction
    public long getSearchByIssuerCount(String issuer, Expired expired, MissingKeyAlias missingKeyAlias)
            throws WebServiceCheckedException {
        issuer = StringUtils.defaultString(issuer);

        if (expired == null) {
            throw new WebServiceCheckedException("expired is missing.");
        }

        if (missingKeyAlias == null) {
            throw new WebServiceCheckedException("missingKeyAlias is missing.");
        }

        try {
            return certStore.getSearchByIssuerCount(issuer, expired, missingKeyAlias);
        } catch (CertStoreException e) {
            logger.error("getSearchByIssuerCount failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        } catch (RuntimeException e) {
            logger.error("getSearchByIssuerCount failed.", e);

            throw new WebServiceCheckedException(WSExceptionUtils.getExceptionMessage(e));
        }
    }

    private List<X509CertificateDTO> getByEmailAction(String email, Match match, Expired expired,
            MissingKeyAlias missingKeyAlias, Integer firstResult, Integer maxResults)
            throws WebServiceCheckedException {
        List<X509CertificateDTO> certificates = new LinkedList<X509CertificateDTO>();

        try {
            CloseableIterator<? extends X509CertStoreEntry> iterator = certStore.getByEmail(email, match, expired,
                    missingKeyAlias, firstResult, maxResults);

            try {
                while (iterator.hasNext()) {
                    X509CertStoreEntry entry = iterator.next();

                    certificates.add(
                            certificateDTOBuilder.buildCertificateDTO(entry.getCertificate(), entry.getKeyAlias()));
                }
            } finally {
                iterator.close();
            }

            return certificates;
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        } catch (CloseableIteratorException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private List<X509CertificateDTO> getCertificatesAction(Expired expired, MissingKeyAlias missingKeyAlias,
            Integer firstResult, Integer maxResults) throws WebServiceCheckedException {
        List<X509CertificateDTO> certificates = new LinkedList<X509CertificateDTO>();

        try {
            X509CertSelector certSelector = new X509CertSelector();

            if (expired == Expired.NOT_ALLOWED) {
                certSelector.setCertificateValid(new Date());
            }

            CloseableIterator<? extends X509CertStoreEntry> iterator = certStore.getCertStoreIterator(certSelector,
                    missingKeyAlias, firstResult, maxResults);

            try {
                while (iterator.hasNext()) {
                    X509CertStoreEntry certStoreEntry = iterator.next();

                    certificates.add(certificateDTOBuilder.buildCertificateDTO(certStoreEntry.getCertificate(),
                            certStoreEntry.getKeyAlias()));
                }
            } finally {
                iterator.close();
            }

            return certificates;
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        } catch (CloseableIteratorException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private byte[] getEncodedCertificateAction(String thumbprint, ObjectEncoding encoding)
            throws WebServiceCheckedException {
        try {
            X509CertStoreEntry certStoreEntry = getCertStoreEntry(thumbprint);

            if (certStoreEntry == null || certStoreEntry.getCertificate() == null) {
                throw new WebServiceCheckedException("Certificate could not be found.");
            }

            byte[] encoded = CertificateEncoder.encode(certStoreEntry.getCertificate(), encoding);

            return encoded;
        } catch (CertificateEncodingException e) {
            throw new WebServiceCheckedException(e);
        } catch (IOException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private byte[] getEncodedCertificatesAction(List<String> thumbprints, ObjectEncoding encoding)
            throws WebServiceCheckedException {
        try {
            List<X509Certificate> certificates = new LinkedList<X509Certificate>();

            for (String thumbprint : thumbprints) {
                X509CertStoreEntry entry = getCertStoreEntry(thumbprint);

                if (entry == null || entry.getCertificate() == null) {
                    logger.warn("Certificate with thumbprint " + thumbprint + " could not be found.");

                    continue;
                }

                certificates.add(entry.getCertificate());
            }

            byte[] encoded = null;

            if (certificates.size() > 0) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                CertificateUtils.writeCertificates(certificates, bos, encoding);

                encoded = bos.toByteArray();
            }

            return encoded;
        } catch (CertificateEncodingException e) {
            throw new WebServiceCheckedException(e);
        } catch (IOException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private X509CertStoreEntry getCertStoreEntry(String thumbprint) throws WebServiceCheckedException {
        try {
            X509CertStoreEntry entry = certStore.getByThumbprint(thumbprint);

            return entry;
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private int addCertificatesAction(byte[] encodedCertificates) throws WebServiceCheckedException {
        try {
            int addedCount = 0;

            ByteArrayInputStream bis = new ByteArrayInputStream(encodedCertificates);

            Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates(bis);

            if (certificates.size() == 0) {
                throw new WebServiceCheckedException(
                        "encodedCertificates does not conatain any valid certificates.");
            }

            for (X509Certificate certificate : certificates) {
                if (!certStore.contains(certificate)) {
                    certStore.addCertificate(certificate);

                    addedCount++;
                }
            }

            return addedCount;
        } catch (CertificateEncodingException e) {
            throw new WebServiceCheckedException(e);
        } catch (CertificateException e) {
            throw new WebServiceCheckedException(e);
        } catch (NoSuchProviderException e) {
            throw new WebServiceCheckedException(e);
        } catch (SecurityFactoryFactoryException e) {
            throw new WebServiceCheckedException(e);
        } catch (CertificateAlreadyExistsException e) {
            throw new WebServiceCheckedException(e);
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private void removeCertificateAction(String thumbprint) throws WebServiceCheckedException {
        X509CertStoreEntry certStoreEntry = getCertStoreEntry(thumbprint);

        try {
            if (certStoreEntry != null && certStoreEntry.getCertificate() != null) {
                certStore.removeCertificate(certStoreEntry.getCertificate());
            }
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private X509CertificateDTO getCertificateAction(String thumbprint) throws WebServiceCheckedException {
        X509CertStoreEntry certStoreEntry = getCertStoreEntry(thumbprint);

        X509CertificateDTO certificateDTO = null;

        if (certStoreEntry != null && certStoreEntry.getCertificate() != null) {
            certificateDTO = certificateDTOBuilder.buildCertificateDTO(certStoreEntry.getCertificate(),
                    certStoreEntry.getKeyAlias());
        }

        return certificateDTO;
    }

    private List<X509CertificateDTO> searchBySubjectAction(String subject, Expired expired,
            MissingKeyAlias missingKeyAlias, Integer firstResult, Integer maxResults)
            throws WebServiceCheckedException {
        List<X509CertificateDTO> certificates = new LinkedList<X509CertificateDTO>();

        try {
            CloseableIterator<? extends X509CertStoreEntry> iterator = certStore.searchBySubject(subject, expired,
                    missingKeyAlias, firstResult, maxResults);

            try {
                while (iterator.hasNext()) {
                    X509CertStoreEntry entry = iterator.next();

                    certificates.add(
                            certificateDTOBuilder.buildCertificateDTO(entry.getCertificate(), entry.getKeyAlias()));
                }
            } finally {
                iterator.close();
            }

            return certificates;
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        } catch (CloseableIteratorException e) {
            throw new WebServiceCheckedException(e);
        }
    }

    private List<X509CertificateDTO> searchByIssuerAction(String issuer, Expired expired,
            MissingKeyAlias missingKeyAlias, Integer firstResult, Integer maxResults)
            throws WebServiceCheckedException {
        List<X509CertificateDTO> certificates = new LinkedList<X509CertificateDTO>();

        try {
            CloseableIterator<? extends X509CertStoreEntry> iterator = certStore.searchByIssuer(issuer, expired,
                    missingKeyAlias, firstResult, maxResults);

            try {
                while (iterator.hasNext()) {
                    X509CertStoreEntry entry = iterator.next();

                    certificates.add(
                            certificateDTOBuilder.buildCertificateDTO(entry.getCertificate(), entry.getKeyAlias()));
                }
            } finally {
                iterator.close();
            }

            return certificates;
        } catch (CertStoreException e) {
            throw new WebServiceCheckedException(e);
        } catch (CloseableIteratorException e) {
            throw new WebServiceCheckedException(e);
        }
    }
}