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

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.james.mailets.DKIMVerify.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.io.IOException;
import java.io.StringReader;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import mitm.common.util.Check;
import mitm.common.util.MiscStringUtils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.james.jdkim.DKIMCommon;
import org.apache.james.jdkim.DKIMVerifier;
import org.apache.james.jdkim.api.PublicKeyRecordRetriever;
import org.apache.james.jdkim.api.SignatureRecord;
import org.apache.james.jdkim.exceptions.FailException;
import org.apache.james.jdkim.exceptions.PermFailException;
import org.apache.james.jdkim.exceptions.TempFailException;
import org.apache.mailet.Mail;
import org.bouncycastle.openssl.PEMReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Verifies the digital signature of a DKIM signed message. The current implementation 
 * works with a static public key i.e., the public key is not retrieved from DNS.
 * 
 * @author Martijn Brinkers
 *
 */
public class DKIMVerify extends AbstractDjigzoMailet {
    private final static Logger logger = LoggerFactory.getLogger(DKIMVerify.class);

    @Override
    protected Logger getLogger() {
        return logger;
    }

    /*
     * The mailet initialization parameters used by this mailet.
     */
    private enum Parameter {
        PUBLIC_KEY("publicKey"), DKIM_HEADER("dkimHeader"), RESULT_MAIL_ATTRIBUTE("resultAttribute");

        private String name;

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

    /*
     * Implementation of PublicKeyRecordRetriever that returns a record based on 
     * the provided public key
     */
    private static class StaticPublicKeyRecordRetriever implements PublicKeyRecordRetriever {
        private final List<String> records;

        private StaticPublicKeyRecordRetriever(PublicKey publicKey) {
            Check.notNull(publicKey, "publicKey");

            String record = "p=" + MiscStringUtils.toAsciiString(Base64.encodeBase64(publicKey.getEncoded()));

            records = Arrays.asList(record);
        }

        @Override
        public List<String> getRecords(CharSequence methodAndOption, CharSequence selector, CharSequence token)
                throws TempFailException, PermFailException {
            return records;
        }
    }

    /*
     * The public key used to verify the signature with
     */
    private PublicKey publicKey;

    /*
     * The name of the Mail attribute to store the result in
     */
    private String resultMailAttribute;

    /*
     * The DKIM header to use (defaults to DKIM-Signature)
     */
    private String dkimHeader;

    @Override
    protected void initMailet() throws MessagingException {
        dkimHeader = getInitParameter(Parameter.DKIM_HEADER.name, DKIMCommon.DEFAULT_DKIM_HEADER);

        resultMailAttribute = StringUtils.trimToNull(getInitParameter(Parameter.RESULT_MAIL_ATTRIBUTE.name));

        if (resultMailAttribute == null) {
            throw new MessagingException("resultAttribute is missing.");
        }

        loadPublicKey();
    }

    protected static PublicKey parseKey(String pkcs8) throws MessagingException {
        PublicKey key = null;

        pkcs8 = StringUtils.trimToNull(pkcs8);

        if (pkcs8 != null) {
            PEMReader pem = new PEMReader(new StringReader(pkcs8));

            Object o;

            try {
                o = pem.readObject();
            } catch (IOException e) {
                throw new MessagingException("Unable to read PEM encoded private key", e);
            }

            if (o instanceof PublicKey) {
                key = (PublicKey) o;
            } else if (o instanceof KeyPair) {
                key = ((KeyPair) o).getPublic();
            } else if (o == null) {
                throw new MessagingException("The PEM encoded blob did not return any object.");
            } else {
                throw new MessagingException("The PEM input is not a PublicKey or KeyPair but a " + o.getClass());
            }
        }

        return key;
    }

    private void loadPublicKey() throws MessagingException {
        publicKey = parseKey(getInitParameter(Parameter.PUBLIC_KEY.name));
    }

    protected PublicKey getPublicKey(Mail mail) throws MessagingException {
        return publicKey;
    }

    private void signatureFailure(Mail mail) {
        signatureFailure(mail, null);
    }

    private void signatureFailure(Mail mail, Throwable t) {
        if (t != null) {
            logger.error("DKIM verification failed due to an error.", t);
        } else {
            logger.warn("DKIM verification failed.");
        }

        mail.setAttribute(resultMailAttribute, "failed");
    }

    @Override
    public void serviceMail(Mail mail) {
        try {
            MimeMessage message = mail.getMessage();

            PublicKey publicKey = getPublicKey(mail);

            if (publicKey != null) {
                /*
                 * Use a static PublicKeyRecordRetriever that does not retrieve the public key from
                 * DNS but uses a pre-defined PublicKey. 
                 */
                PublicKeyRecordRetriever retriever = new StaticPublicKeyRecordRetriever(publicKey);

                DKIMVerifier verifier = new DKIMVerifier(retriever);

                verifier.setDKIMHeader(dkimHeader);

                List<SignatureRecord> results = verifier.verify(message);

                if (CollectionUtils.isEmpty(results)) {
                    signatureFailure(mail);
                } else {
                    mail.setAttribute(resultMailAttribute, "verified");
                }
            } else {
                logger.warn("Unable to verify the message because the public key is missing.");
            }
        } catch (MessagingException e) {
            signatureFailure(mail, e);
        } catch (IOException e) {
            signatureFailure(mail, e);
        } catch (FailException e) {
            signatureFailure(mail);
        }
    }
}