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

Java tutorial

Introduction

Here is the source code for mitm.application.djigzo.james.mailets.DKIMSign.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.PrivateKey;

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

import mitm.common.mail.HeaderUtils;
import mitm.common.mail.MailUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.james.jdkim.DKIMCommon;
import org.apache.james.jdkim.DKIMSigner;
import org.apache.james.jdkim.exceptions.FailException;
import org.apache.mailet.Mail;
import org.bouncycastle.openssl.PEMReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Digitally signs a message with the DKIM protocol
 * 
 * @author Martijn Brinkers
 *
 */
public class DKIMSign extends AbstractDjigzoMailet {
    private final static Logger logger = LoggerFactory.getLogger(DKIMSign.class);

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

    /*
     * The mailet initialization parameters used by this mailet.
     */
    private enum Parameter {
        PRIVATE_KEY("privateKey"), CONVERT_TO_7BIT("convertTo7Bit"), DKIM_HEADER("dkimHeader"), SIGNATURE_TEMPLATE(
                "signatureTemplate"), FOLD_SIGNATURE("foldSignature");

        private String name;

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

    /*
     * The private key used to sign the message with
     */
    private PrivateKey privateKey;

    /*
     * If true and the message contains 8bit parts, the message will be converted
     * to 7bit prior to signing.
     */
    private boolean convertTo7Bit;

    /*
     * If true the signature will be folded. Only enable foldSignature if header signing
     * is relaxed otherwise folding will break the DKIM sigature. 
     */
    private boolean foldSignature;

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

    /*
     * The DKIM signature template
     */
    private String signatureTemplate;

    @Override
    protected void initMailet() throws MessagingException {
        convertTo7Bit = getBooleanInitParameter(Parameter.CONVERT_TO_7BIT.name, true);

        foldSignature = getBooleanInitParameter(Parameter.FOLD_SIGNATURE.name, false);

        dkimHeader = getInitParameter(Parameter.DKIM_HEADER.name, DKIMCommon.DEFAULT_DKIM_HEADER);

        signatureTemplate = StringUtils.trimToNull(getInitParameter(Parameter.SIGNATURE_TEMPLATE.name));

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

        loadPrivateKey();
    }

    protected static PrivateKey parseKey(String pkcs8) throws MessagingException {
        PrivateKey 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 PrivateKey) {
                key = (PrivateKey) o;
            } else if (o instanceof KeyPair) {
                key = ((KeyPair) o).getPrivate();
            } 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 PrivateKey or KeyPair but a " + o.getClass());
            }
        }

        return key;
    }

    private void loadPrivateKey() throws MessagingException {
        privateKey = parseKey(getInitParameter(Parameter.PRIVATE_KEY.name));
    }

    protected PrivateKey getPrivateKey(Mail mail) throws MessagingException {
        return privateKey;
    }

    protected String getSignatureTemplate() {
        return signatureTemplate;
    }

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

            if (convertTo7Bit) {
                /*
                 * Before signing, the message should be converted to 7bit to make sure
                 * the signature 'survives' the internet.
                 */
                boolean converted = MailUtils.convertTo7Bit(message);

                if (converted) {
                    message.saveChanges();
                }
            }

            PrivateKey privateKey = getPrivateKey(mail);

            if (privateKey != null) {
                DKIMSigner signer = new DKIMSigner(getSignatureTemplate(), privateKey);

                signer.setDKIMHeader(dkimHeader);

                String signature = signer.sign(message);

                /*
                 * the signature field cannot be folded after signing in the simple mode
                 * because that would break the signature
                 */
                if (foldSignature) {
                    signature = MimeUtility.fold(dkimHeader.length(), signature);
                }

                HeaderUtils.prependHeaderLine(message, signature);

                /*
                 * Validate the message to make sure that James can write the message. 
                 * 
                 * Note: Because normally only a header is added, the message-id is not changed. The
                 * exception to this is when the message is converted from 8bit to 7bit (see above).
                 * When the message is converted from 7bit to 8bit the message-id is changed.
                 */
                MailUtils.validateMessage(message);
            } else {
                logger.warn("Unable to sign the message because the private key is missing.");
            }
        } catch (MessagingException e) {
            logger.error("DKIM signing failed.", e);
        } catch (IOException e) {
            logger.error("DKIM signing failed.", e);
        } catch (FailException e) {
            logger.error("DKIM signing failed.", e);
        }
    }
}