mitm.application.djigzo.james.mailets.AbstractAddAdditionalCertificates.java Source code

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.james.mailets.AbstractAddAdditionalCertificates.java

Source

/*
 * Copyright (c) 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.application.djigzo.james.mailets;

import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.mail.MessagingException;

import mitm.application.djigzo.NamedCertificateCategories;
import mitm.application.djigzo.User;
import mitm.application.djigzo.UserPreferences;
import mitm.application.djigzo.impl.NamedCertificateUtils;
import mitm.application.djigzo.james.Certificates;
import mitm.application.djigzo.james.DjigzoMailAttributes;
import mitm.application.djigzo.james.DjigzoMailAttributesImpl;
import mitm.application.djigzo.service.SystemServices;
import mitm.application.djigzo.workflow.UserWorkflow;
import mitm.common.hibernate.DatabaseAction;
import mitm.common.hibernate.DatabaseActionExecutor;
import mitm.common.hibernate.DatabaseActionExecutorBuilder;
import mitm.common.hibernate.DatabaseException;
import mitm.common.hibernate.SessionManager;
import mitm.common.security.PKISecurityServices;
import mitm.common.security.certificate.validator.CertificateValidatorChain;
import mitm.common.security.certificate.validator.IsValidForSMIMEEncryption;
import mitm.common.util.Check;

import org.apache.commons.collections.CollectionUtils;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.hibernate.Session;

/**
 * Mailet that adds additional certificates to the {@link DjigzoMailAttributes#Certificates} collection
 * 
 * @author Martijn Brinkers
 *
 */
public abstract class AbstractAddAdditionalCertificates extends AbstractDjigzoMailet {
    /*
     * The number of times a database action should be retried when a ConstraintViolation occurs
     */
    private final static int ACTION_RETRIES = 3;

    /*
     * The activation context key
     */
    protected final static String ACTIVATION_CONTEXT_KEY = "context";

    /*
     * manages database sessions
     */
    private SessionManager sessionManager;

    /*
     * Used for adding and retrieving users
     */
    private UserWorkflow userWorkflow;

    /*
     * Used to execute database actions in a transaction
     */
    private DatabaseActionExecutor actionExecutor;

    /*
     * For validating the certificates
     */
    private PKISecurityServices pKISecurityServices;

    /*
     * If true, only valid additional certificates are used 
     */
    private boolean validateCertificates = true;

    /*
     * Callback used to track user objects.
     */
    protected static class ActivationContext {
        /*
         * The additional certificates
         */
        private final Set<X509Certificate> additionalCertificates = new HashSet<X509Certificate>();

        public Set<X509Certificate> getAdditionalCertificates() {
            return additionalCertificates;
        }
    }

    /*
     * The mailet initialization parameters used by this mailet.
     */
    private enum Parameter {
        VALIDATE_CERTS("validateCertificates");

        private String name;

        private Parameter(String name) {
            this.name = name;
        }
    };

    @Override
    public void initMailet() throws MessagingException {
        super.initMailet();

        validateCertificates = getBooleanInitParameter(Parameter.VALIDATE_CERTS.name, validateCertificates);

        sessionManager = SystemServices.getSessionManager();

        userWorkflow = SystemServices.getUserWorkflow();

        pKISecurityServices = SystemServices.getPKISecurityServices();

        actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);

        assert (actionExecutor != null);
    }

    /*
     * Gets called by MailAddressHandler#handleRecipients to handle the user
     */
    protected void onHandleUserEvent(User user) throws MessagingException {
        ActivationContext activationContext = getActivationContext().get(ACTIVATION_CONTEXT_KEY,
                ActivationContext.class);

        Check.notNull(activationContext, "activationContext");

        UserPreferences userPreferences = user.getUserPreferences();

        Set<X509Certificate> additionalCertificates = NamedCertificateUtils
                .getByName(NamedCertificateCategories.ADDITIONAL, userPreferences.getNamedCertificates());

        /*
         * Add the inherited certificates
         */
        additionalCertificates.addAll(NamedCertificateUtils.getByName(NamedCertificateCategories.ADDITIONAL,
                userPreferences.getInheritedNamedCertificates()));

        activationContext.getAdditionalCertificates().addAll(additionalCertificates);
    }

    protected abstract Collection<MailAddress> getMailAddresses(Mail mail) throws MessagingException;

    private Set<X509Certificate> validateCertificatesTransacted(Set<X509Certificate> certificates) {
        Set<X509Certificate> validated = new HashSet<X509Certificate>();

        for (X509Certificate certificate : certificates) {
            CertificateValidatorChain chain = new CertificateValidatorChain();

            /*
             * Add the following CertificateValidators to the chain so we can check if the certificate is
             * trusted, not revoked and can be used for S/MIME encryption.
             */
            chain.addValidators(new IsValidForSMIMEEncryption());
            chain.addValidators(
                    pKISecurityServices.getPKITrustCheckCertificateValidatorFactory().createValidator(null));

            try {
                if (chain.isValid(certificate)) {
                    validated.add(certificate);
                }
            } catch (Exception e) {
                getLogger().debug("Error validating certificate.", e);
            }
        }

        return validated;
    }

    private Set<X509Certificate> validateCertificates(final Set<X509Certificate> certificates) {
        Set<X509Certificate> validated = null;

        try {
            validated = actionExecutor.executeTransaction(new DatabaseAction<Set<X509Certificate>>() {
                @Override
                public Set<X509Certificate> doAction(Session session) throws DatabaseException {
                    Session previousSession = sessionManager.getSession();

                    sessionManager.setSession(session);

                    try {
                        return validateCertificatesTransacted(certificates);
                    } finally {
                        sessionManager.setSession(previousSession);
                    }
                }
            });
        } catch (DatabaseException e) {
            getLogger().error("Error validating certificates.", e);
        }

        if (validated == null) {
            validated = Collections.emptySet();
        }

        return validated;
    }

    @Override
    public void serviceMail(Mail mail) {
        try {
            ActivationContext activationContext = new ActivationContext();

            getActivationContext().set(ACTIVATION_CONTEXT_KEY, activationContext);

            MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() {
                @Override
                public void handleUser(User user) throws MessagingException {
                    onHandleUserEvent(user);
                }
            };

            MailAddressHandler mailAddressHandler = new MailAddressHandler(sessionManager, userWorkflow,
                    actionExecutor, eventHandler, ACTION_RETRIES);

            mailAddressHandler.handleMailAddresses(getMailAddresses(mail));

            DjigzoMailAttributes mailAttributes = new DjigzoMailAttributesImpl(mail);

            Certificates certificateContainer = mailAttributes.getCertificates();

            if (certificateContainer != null) {
                Set<X509Certificate> certificates = certificateContainer.getCertificates();

                if (CollectionUtils.isNotEmpty(certificates)) {
                    Set<X509Certificate> additionalCertificates = activationContext.additionalCertificates;

                    certificates.addAll(validateCertificates ? validateCertificates(additionalCertificates)
                            : additionalCertificates);

                    /*
                     * Need to set the collection again to make it persistent
                     */
                    mailAttributes.setCertificates(certificateContainer);
                }
            }
        } catch (MessagingException e) {
            getLogger().error("Error adding additional certificates.", e);
        }
    }
}