Search in sources :

Example 6 with ICertificateFactory

use of com.helger.as2lib.cert.ICertificateFactory in project as2-lib by phax.

the class AS2ReceiverHandler method decrypt.

protected void decrypt(@Nonnull final IMessage aMsg, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception {
    final ICertificateFactory aCertFactory = m_aReceiverModule.getSession().getCertificateFactory();
    final ICryptoHelper aCryptoHelper = AS2Helper.getCryptoHelper();
    try {
        final boolean bDisableDecrypt = aMsg.partnership().isDisableDecrypt();
        final boolean bMsgIsEncrypted = aCryptoHelper.isEncrypted(aMsg.getData());
        final boolean bForceDecrypt = aMsg.partnership().isForceDecrypt();
        if (bMsgIsEncrypted && bDisableDecrypt) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Message claims to be encrypted but decryption is disabled" + aMsg.getLoggingText());
        } else if (bMsgIsEncrypted || bForceDecrypt) {
            // Decrypt
            if (bForceDecrypt && !bMsgIsEncrypted) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("Forced decrypting" + aMsg.getLoggingText());
            } else if (LOGGER.isDebugEnabled())
                LOGGER.debug("Decrypting" + aMsg.getLoggingText());
            final X509Certificate aReceiverCert = aCertFactory.getCertificate(aMsg, ECertificatePartnershipType.RECEIVER);
            final PrivateKey aReceiverKey = aCertFactory.getPrivateKey(aReceiverCert);
            final MimeBodyPart aDecryptedData = aCryptoHelper.decrypt(aMsg.getData(), aReceiverCert, aReceiverKey, bForceDecrypt, aResHelper);
            aMsg.setData(aDecryptedData);
            // Remember that message was encrypted
            aMsg.attrs().putIn(AS2Message.ATTRIBUTE_RECEIVED_ENCRYPTED, true);
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Successfully decrypted incoming AS2 message" + aMsg.getLoggingText());
        }
    } catch (final AS2DispositionException ex) {
        // Re-throw "as is"
        throw ex;
    } catch (final Exception ex) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Error decrypting " + aMsg.getLoggingText() + ": " + ex.getMessage());
        throw new AS2DispositionException(DispositionType.createError("decryption-failed"), AbstractActiveNetModule.DISP_DECRYPTION_ERROR, ex);
    }
}
Also used : AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) PrivateKey(java.security.PrivateKey) ICertificateFactory(com.helger.as2lib.cert.ICertificateFactory) ICryptoHelper(com.helger.as2lib.crypto.ICryptoHelper) MimeBodyPart(javax.mail.internet.MimeBodyPart) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2ProcessorException(com.helger.as2lib.processor.AS2ProcessorException) CMSException(org.bouncycastle.cms.CMSException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException)

Example 7 with ICertificateFactory

use of com.helger.as2lib.cert.ICertificateFactory in project as2-lib by phax.

the class AS2SenderModule method receiveSyncMDN.

/**
 * @param aMsg
 *        AS2Message
 * @param aHttpClient
 *        URLConnection
 * @param aOriginalMIC
 *        mic value from original msg
 * @param aIncomingDumper
 *        Incoming dumper. May be <code>null</code>.
 * @param aResHelper
 *        Resource helper
 * @throws AS2Exception
 *         in case of an error
 * @throws IOException
 *         in case of an IO error
 */
protected void receiveSyncMDN(@Nonnull final AS2Message aMsg, @Nonnull final AS2HttpClient aHttpClient, @Nonnull final MIC aOriginalMIC, @Nullable final IHTTPIncomingDumper aIncomingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Receiving synchronous MDN for message" + aMsg.getLoggingText());
    try {
        // Create a MessageMDN and copy HTTP headers
        final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
        // Bug in ph-commons 9.1.3 in addAllHeaders!
        aMDN.headers().addAllHeaders(aHttpClient.getResponseHeaderFields());
        // Receive the MDN data
        final InputStream aConnIS = aHttpClient.getInputStream();
        final NonBlockingByteArrayOutputStream aMDNStream = new NonBlockingByteArrayOutputStream();
        // Retrieve the whole MDN content
        StreamHelper.copyByteStream().from(aConnIS).closeFrom(true).to(aMDNStream).closeTo(true).limit(StringParser.parseLong(aMDN.getHeader(CHttpHeader.CONTENT_LENGTH), -1)).build();
        // Dump collected message
        if (aIncomingDumper != null)
            aIncomingDumper.dumpIncomingRequest(aMDN.headers().getAllHeaderLines(true), aMDNStream.getBufferOrCopy(), aMDN);
        if (LOGGER.isTraceEnabled()) {
            // Debug print the whole MDN stream
            LOGGER.trace("Retrieved MDN stream data:\n" + aMDNStream.getAsString(StandardCharsets.ISO_8859_1));
        }
        final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), aMDNStream.getBufferOrCopy());
        aMDN.setData(aPart);
        // get the MDN partnership info
        aMDN.partnership().setSenderAS2ID(aMDN.getHeader(CHttpHeader.AS2_FROM));
        aMDN.partnership().setReceiverAS2ID(aMDN.getHeader(CHttpHeader.AS2_TO));
        // Set the appropriate key store aliases
        aMDN.partnership().setSenderX509Alias(aMsg.partnership().getReceiverX509Alias());
        aMDN.partnership().setReceiverX509Alias(aMsg.partnership().getSenderX509Alias());
        // Update the partnership
        getSession().getPartnershipFactory().updatePartnership(aMDN, false);
        final ICertificateFactory aCertFactory = getSession().getCertificateFactory();
        final X509Certificate aSenderCert = aCertFactory.getCertificate(aMDN, ECertificatePartnershipType.SENDER);
        boolean bUseCertificateInBodyPart;
        final ETriState eUseCertificateInBodyPart = aMsg.partnership().getVerifyUseCertificateInBodyPart();
        if (eUseCertificateInBodyPart.isDefined()) {
            // Use per partnership
            bUseCertificateInBodyPart = eUseCertificateInBodyPart.getAsBooleanValue();
        } else {
            // Use global value
            bUseCertificateInBodyPart = getSession().isCryptoVerifyUseCertificateInBodyPart();
        }
        AS2Helper.parseMDN(aMsg, aSenderCert, bUseCertificateInBodyPart, m_aVerificationCertificateConsumer, aResHelper);
        try {
            getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
        } catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
        // No message processor found
        // Or no module found in message processor
        }
        final String sDisposition = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Received synchronous AS2 MDN [" + sDisposition + "]" + aMsg.getLoggingText());
        // Asynch MDN 2007-03-12
        // Verify if the original mic is equal to the mic in returned MDN
        final String sReturnMIC = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC);
        final MIC aReturnMIC = MIC.parse(sReturnMIC);
        // Catch ReturnMIC == null in case the attribute is simply missing
        final boolean bMICMatch = aOriginalMIC != null && aReturnMIC != null && aReturnMIC.equals(aOriginalMIC);
        if (bMICMatch) {
            // MIC was matched - all good
            m_aMICMatchingHandler.onMICMatch(aMsg, sReturnMIC);
        } else {
            // file was sent completely but the returned mic was not matched,
            m_aMICMatchingHandler.onMICMismatch(aMsg, aOriginalMIC == null ? null : aOriginalMIC.getAsAS2String(), sReturnMIC);
        }
        if (m_aIncomingMDNCallback != null)
            m_aIncomingMDNCallback.onIncomingMDN(true, aMDN, aMDN.getHeader(CHttpHeader.AS2_FROM), aMDN.getHeader(CHttpHeader.AS2_TO), sDisposition, aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC), aMDN.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID), aMDN.attrs().getAsBoolean(AS2Message.ATTRIBUTE_RECEIVED_SIGNED, false), bMICMatch);
        DispositionType.createFromString(sDisposition).validate(aMsg, aMDN.getText());
    } catch (final IOException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg);
    }
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) ETriState(com.helger.commons.state.ETriState) InputStream(java.io.InputStream) MIC(com.helger.as2lib.crypto.MIC) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) ICertificateFactory(com.helger.as2lib.cert.ICertificateFactory) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) AS2InvalidParameterException(com.helger.as2lib.params.AS2InvalidParameterException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IMessageMDN(com.helger.as2lib.message.IMessageMDN) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 8 with ICertificateFactory

use of com.helger.as2lib.cert.ICertificateFactory in project as2-lib by phax.

the class AS2Helper method createMDNData.

/**
 * Create and fill the MDN parameter
 *
 * @param aSession
 *        Session to retrieve the certificate factory for signing
 * @param aMdn
 *        The MDN object to be filled
 * @param bSignMDN
 *        <code>true</code> to sign the MDN
 * @param bIncludeCertificateInSignedContent
 *        <code>true</code> if the passed certificate should be part of the
 *        signed content, <code>false</code> if the certificate should not be
 *        put in the content. E.g. for PEPPOL this must be <code>true</code>.
 * @param eMICAlg
 *        The MIC algorithm to be used. Must be present if bSignMDN is
 *        <code>true</code>.
 * @param bUseOldRFC3851MicAlgs
 *        <code>true</code> to use the old RFC 3851 MIC algorithm names (e.g.
 *        <code>sha1</code>), <code>false</code> to use the new RFC 5751 MIC
 *        algorithm names (e.g. <code>sha-1</code>).
 * @param bRemoveCmsAlgorithmProtect
 *        if <code>true</code>, the CMS attribute "AlgorithmProtect" will be
 *        removed. This is needed in compatibility with e.g. IBM Sterling.
 *        Default value should be <code>false</code>. Since 4.10.1. See Issue
 *        #137.
 * @throws Exception
 *         In case something internally goes wrong
 */
public static void createMDNData(@Nonnull final IAS2Session aSession, @Nonnull final IMessageMDN aMdn, final boolean bSignMDN, final boolean bIncludeCertificateInSignedContent, @Nullable final ECryptoAlgorithmSign eMICAlg, final boolean bUseOldRFC3851MicAlgs, final boolean bRemoveCmsAlgorithmProtect) throws Exception {
    ValueEnforcer.notNull(aSession, "AS2Session");
    ValueEnforcer.notNull(aMdn, "MDN");
    if (bSignMDN)
        ValueEnforcer.notNull(eMICAlg, "MICAlg");
    // Create the report and sub-body parts
    final MimeMultipart aReportParts = new MimeMultipart();
    // Create the text part
    final MimeBodyPart aTextPart = new MimeBodyPart();
    final String sText = aMdn.getText() + CHttp.EOL;
    aTextPart.setContent(sText, CMimeType.TEXT_PLAIN.getAsString());
    aTextPart.setHeader(CHttpHeader.CONTENT_TYPE, CMimeType.TEXT_PLAIN.getAsString());
    aReportParts.addBodyPart(aTextPart);
    // Create the report part
    final MimeBodyPart aReportPart = new MimeBodyPart();
    {
        final InternetHeaders aReportValues = new InternetHeaders();
        aReportValues.setHeader(HEADER_REPORTING_UA, aMdn.attrs().getAsString(AS2MessageMDN.MDNA_REPORTING_UA));
        aReportValues.setHeader(HEADER_ORIGINAL_RECIPIENT, aMdn.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_RECIPIENT));
        aReportValues.setHeader(HEADER_FINAL_RECIPIENT, aMdn.attrs().getAsString(AS2MessageMDN.MDNA_FINAL_RECIPIENT));
        aReportValues.setHeader(HEADER_ORIGINAL_MESSAGE_ID, aMdn.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
        aReportValues.setHeader(HEADER_DISPOSITION, aMdn.attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION));
        aReportValues.setHeader(HEADER_RECEIVED_CONTENT_MIC, aMdn.attrs().getAsString(AS2MessageMDN.MDNA_MIC));
        final StringBuilder aReportData = new StringBuilder();
        final Enumeration<?> aReportEn = aReportValues.getAllHeaderLines();
        while (aReportEn.hasMoreElements()) aReportData.append((String) aReportEn.nextElement()).append(CHttp.EOL);
        aReportData.append(CHttp.EOL);
        aReportPart.setContent(aReportData.toString(), "message/disposition-notification");
    }
    aReportPart.setHeader(CHttpHeader.CONTENT_TYPE, "message/disposition-notification");
    aReportParts.addBodyPart(aReportPart);
    // Convert report parts to MimeBodyPart
    final MimeBodyPart aReport = new MimeBodyPart();
    aReportParts.setSubType("report; report-type=disposition-notification");
    aReport.setContent(aReportParts);
    aReport.setHeader(CHttpHeader.CONTENT_TYPE, aReportParts.getContentType());
    // Sign the MDN data if needed
    if (bSignMDN) {
        final ICertificateFactory aCertFactory = aSession.getCertificateFactory();
        try {
            final X509Certificate aSenderCert = aCertFactory.getCertificate(aMdn, ECertificatePartnershipType.SENDER);
            final PrivateKey aSenderKey = aCertFactory.getPrivateKey(aSenderCert);
            final MimeBodyPart aSignedReport = getCryptoHelper().sign(aReport, aSenderCert, aSenderKey, eMICAlg, bIncludeCertificateInSignedContent, bUseOldRFC3851MicAlgs, bRemoveCmsAlgorithmProtect, EContentTransferEncoding.BASE64);
            aMdn.setData(aSignedReport);
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Successfully signed outgoing MDN message" + aMdn.getLoggingText());
        } catch (final AS2CertificateNotFoundException | AS2KeyNotFoundException ex) {
            ex.terminate();
            LOGGER.warn("Failed to sign MDN - using an unsigned MDN instead");
            aMdn.setData(aReport);
        }
    } else {
        // No signing needed
        aMdn.setData(aReport);
    }
    // Update the MDN headers with content information
    final MimeBodyPart aData = aMdn.getData();
    aMdn.headers().setContentType(aData.getContentType());
// final int size = getSize (aData);
// aMdn.setHeader (CAS2Header.HEADER_CONTENT_LENGTH, Integer.toString
// (size));
}
Also used : AS2KeyNotFoundException(com.helger.as2lib.cert.AS2KeyNotFoundException) Enumeration(java.util.Enumeration) PrivateKey(java.security.PrivateKey) InternetHeaders(javax.mail.internet.InternetHeaders) MimeMultipart(javax.mail.internet.MimeMultipart) ICertificateFactory(com.helger.as2lib.cert.ICertificateFactory) AS2CertificateNotFoundException(com.helger.as2lib.cert.AS2CertificateNotFoundException) MimeBodyPart(javax.mail.internet.MimeBodyPart) X509Certificate(java.security.cert.X509Certificate)

Example 9 with ICertificateFactory

use of com.helger.as2lib.cert.ICertificateFactory in project as2-server by phax.

the class AS2ServerXMLSession method loadCertificates.

protected void loadCertificates(@Nonnull final IMicroElement aElement) throws OpenAS2Exception {
    LOGGER.info("  loading certificates");
    final ICertificateFactory certFx = AS2XMLHelper.createComponent(aElement, ICertificateFactory.class, this, m_sBaseDirectory);
    setCertificateFactory(certFx);
}
Also used : ICertificateFactory(com.helger.as2lib.cert.ICertificateFactory)

Aggregations

ICertificateFactory (com.helger.as2lib.cert.ICertificateFactory)9 X509Certificate (java.security.cert.X509Certificate)6 MimeBodyPart (javax.mail.internet.MimeBodyPart)6 AS2Exception (com.helger.as2lib.exception.AS2Exception)5 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)5 AS2NoModuleException (com.helger.as2lib.processor.AS2NoModuleException)4 AS2ComponentNotFoundException (com.helger.as2lib.session.AS2ComponentNotFoundException)4 ETriState (com.helger.commons.state.ETriState)4 IOException (java.io.IOException)4 MessagingException (javax.mail.MessagingException)4 AS2DispositionException (com.helger.as2lib.disposition.AS2DispositionException)3 PrivateKey (java.security.PrivateKey)3 SMIMEException (org.bouncycastle.mail.smime.SMIMEException)3 ICryptoHelper (com.helger.as2lib.crypto.ICryptoHelper)2 AS2MessageMDN (com.helger.as2lib.message.AS2MessageMDN)2 IMessageMDN (com.helger.as2lib.message.IMessageMDN)2 AS2ProcessorException (com.helger.as2lib.processor.AS2ProcessorException)2 CMSException (org.bouncycastle.cms.CMSException)2 AS2CertificateNotFoundException (com.helger.as2lib.cert.AS2CertificateNotFoundException)1 AS2KeyNotFoundException (com.helger.as2lib.cert.AS2KeyNotFoundException)1