Search in sources :

Example 11 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class AbstractAS2ReceiveXServletHandler method onServletInit.

@Override
public void onServletInit(@Nonnull final ICommonsMap<String, String> aInitParams) throws ServletException {
    super.onServletInit(aInitParams);
    try {
        m_aReceiver = getSession().getMessageProcessor().getModuleOfClass(AS2ServletReceiverModule.class);
        if (m_aReceiver == null)
            throw new ServletException("Failed to retrieve 'AS2ServletReceiverModule' which is a mandatory module! Please ensure your configuration file contains at least the module '" + AS2ServletReceiverModule.class.getName() + "'");
    } catch (final AS2Exception ex) {
        throw new ServletException("Failed to init AS2 configuration", ex);
    }
    LOGGER.info("Successfully initialized AS2 configuration");
}
Also used : ServletException(javax.servlet.ServletException) AS2Exception(com.helger.as2lib.exception.AS2Exception) AS2ServletReceiverModule(com.helger.as2servlet.util.AS2ServletReceiverModule)

Example 12 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class XMLCommandRegistry method load.

public void load(@Nonnull final InputStream in) throws AS2Exception {
    final IMicroDocument aDoc = MicroReader.readMicroXML(in);
    final IMicroElement eRoot = aDoc.getDocumentElement();
    clearCommands();
    for (final IMicroElement eElement : eRoot.getAllChildElements()) {
        final String sNodeName = eElement.getTagName();
        if (sNodeName.equals("command"))
            loadCommand(eElement, null);
        else if (sNodeName.equals("multicommand"))
            loadMultiCommand(eElement, null);
        else
            throw new AS2Exception("Undefined tag: " + sNodeName);
    }
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) IMicroElement(com.helger.xml.microdom.IMicroElement) IMicroDocument(com.helger.xml.microdom.IMicroDocument)

Example 13 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class XMLCommandRegistry method loadMultiCommand.

protected void loadMultiCommand(@Nonnull final IMicroElement aCommand, @Nullable final MultiCommand parent) throws AS2Exception {
    final MultiCommand cmd = new MultiCommand();
    cmd.initDynamicComponent(getSession(), AS2XMLHelper.getAllAttrsWithLowercaseName(aCommand));
    if (parent != null)
        parent.getCommands().add(cmd);
    else
        addCommand(cmd);
    for (final IMicroElement aChildElement : aCommand.getAllChildElements()) {
        final String sChildName = aChildElement.getNodeName();
        if (sChildName.equals("command"))
            loadCommand(aChildElement, cmd);
        else if (sChildName.equals("multicommand"))
            loadMultiCommand(aChildElement, cmd);
        else
            throw new AS2Exception("Undefined child tag: " + sChildName);
    }
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) IMicroElement(com.helger.xml.microdom.IMicroElement)

Example 14 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class AS2MDNReceiverHandler method receiveMDN.

// Asynch MDN 2007-03-12
/**
 * method for receiving and processing Async MDN sent from receiver.
 *
 * @param aMsg
 *        The MDN message
 * @param aData
 *        The MDN content
 * @param aResponseHandler
 *        The HTTP response handler for setting the correct HTTP response code
 * @param aResHelper
 *        Resource helper
 * @throws AS2Exception
 *         In case of error
 * @throws IOException
 *         In case of IO error
 */
protected final void receiveMDN(@Nonnull final AS2Message aMsg, final byte[] aData, @Nonnull final IAS2HttpResponseHandler aResponseHandler, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException {
    try {
        // Create a MessageMDN and copy HTTP headers
        final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
        // copy headers from msg to MDN from msg
        aMDN.headers().setAllHeaders(aMsg.headers());
        final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), aData);
        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 keystore aliases
        aMDN.partnership().setSenderX509Alias(aMsg.partnership().getReceiverX509Alias());
        aMDN.partnership().setReceiverX509Alias(aMsg.partnership().getSenderX509Alias());
        // Update the partnership
        getModule().getSession().getPartnershipFactory().updatePartnership(aMDN, false);
        final ICertificateFactory aCertFactory = getModule().getSession().getCertificateFactory();
        final X509Certificate aSenderCert = aCertFactory.getCertificate(aMDN, ECertificatePartnershipType.SENDER);
        final boolean bUseCertificateInBodyPart;
        final ETriState eUseCertificateInBodyPart = aMsg.partnership().getVerifyUseCertificateInBodyPart();
        if (eUseCertificateInBodyPart.isDefined()) {
            // Use per partnership
            bUseCertificateInBodyPart = eUseCertificateInBodyPart.getAsBooleanValue();
        } else {
            // Use global value
            bUseCertificateInBodyPart = getModule().getSession().isCryptoVerifyUseCertificateInBodyPart();
        }
        AS2Helper.parseMDN(aMsg, aSenderCert, bUseCertificateInBodyPart, getVerificationCertificateConsumer(), aResHelper);
        // in order to name & save the mdn with the original AS2-From + AS2-To +
        // Message id.,
        // the 3 msg attributes have to be reset before calling MDNFileModule
        aMsg.partnership().setSenderAS2ID(aMDN.getHeader(CHttpHeader.AS2_TO));
        aMsg.partnership().setReceiverAS2ID(aMDN.getHeader(CHttpHeader.AS2_FROM));
        getModule().getSession().getPartnershipFactory().updatePartnership(aMsg, false);
        aMsg.setMessageID(aMDN.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
        try {
            getModule().getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
        } catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
        // No message processor found
        // Or no module found in message processor
        }
        // check if the mic (message integrity check) is correct
        final boolean bMICMatch = checkAsyncMDN(aMsg);
        HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, bMICMatch ? CHttp.HTTP_OK : CHttp.HTTP_NOT_FOUND);
        final String sDisposition = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION);
        if (m_aIncomingMDNCallback != null)
            m_aIncomingMDNCallback.onIncomingMDN(false, 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) {
        HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, CHttp.HTTP_BAD_REQUEST);
        throw ex;
    } catch (final Exception ex) {
        HTTPHelper.sendSimpleHTTPResponse(aResponseHandler, CHttp.HTTP_BAD_REQUEST);
        throw WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg);
    }
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) ETriState(com.helger.commons.state.ETriState) 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) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) 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 15 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class AS2SenderModule method secure.

@Nonnull
protected MimeBodyPart secure(@Nonnull final IMessage aMsg, @Nonnull final EContentTransferEncoding eCTE) throws Exception {
    final Partnership aPartnership = aMsg.partnership();
    final ICertificateFactory aCertFactory = getSession().getCertificateFactory();
    // Get compression parameters
    // If compression is enabled, by default is is compressed before signing
    ECompressionType eCompressionType = null;
    boolean bCompressBeforeSign = true;
    Consumer<MimeBodyPart> aCompressBeforeSignCallback = null;
    {
        final String sCompressionType = aPartnership.getCompressionType();
        if (sCompressionType != null) {
            eCompressionType = ECompressionType.getFromIDCaseInsensitiveOrNull(sCompressionType);
            if (eCompressionType == null)
                throw new AS2Exception("The compression type '" + sCompressionType + "' is not supported!");
            bCompressBeforeSign = aPartnership.isCompressBeforeSign();
            if (bCompressBeforeSign) {
                // Replace the message data, because it is the basis for the MIC
                aCompressBeforeSignCallback = aMsg::setData;
            }
        }
    }
    // Get signing parameters
    ECryptoAlgorithmSign eSignAlgorithm = null;
    X509Certificate aSenderCert = null;
    PrivateKey aSenderKey = null;
    boolean bIncludeCertificateInSignedContent = false;
    boolean bUseRFC3851MICAlg = false;
    boolean bRemoveCmsAlgorithmProtect = false;
    {
        final String sSignAlgorithm = aPartnership.getSigningAlgorithm();
        if (sSignAlgorithm != null) {
            aSenderCert = aCertFactory.getCertificate(aMsg, ECertificatePartnershipType.SENDER);
            aSenderKey = aCertFactory.getPrivateKey(aSenderCert);
            eSignAlgorithm = ECryptoAlgorithmSign.getFromIDOrNull(sSignAlgorithm);
            if (eSignAlgorithm == null)
                throw new AS2Exception("The signing algorithm '" + sSignAlgorithm + "' is not supported!");
            // Include certificate in signed content?
            final ETriState eIncludeCertificateInSignedContent = aMsg.partnership().getIncludeCertificateInSignedContent();
            if (eIncludeCertificateInSignedContent.isDefined()) {
                // Use per partnership
                bIncludeCertificateInSignedContent = eIncludeCertificateInSignedContent.getAsBooleanValue();
            } else {
                // Use global value
                bIncludeCertificateInSignedContent = getSession().isCryptoSignIncludeCertificateInBodyPart();
            }
            // Use old MIC algorithms?
            bUseRFC3851MICAlg = aPartnership.isRFC3851MICAlgs();
            // Remove CMS attributes?
            bRemoveCmsAlgorithmProtect = aPartnership.isRemoveCmsAlgorithmProtect();
        }
    }
    // Get encryption parameters
    ECryptoAlgorithmCrypt eCryptAlgorithm = null;
    X509Certificate aReceiverCert = null;
    {
        final String sCryptAlgorithm = aPartnership.getEncryptAlgorithm();
        if (sCryptAlgorithm != null) {
            aReceiverCert = aCertFactory.getCertificate(aMsg, ECertificatePartnershipType.RECEIVER);
            eCryptAlgorithm = ECryptoAlgorithmCrypt.getFromIDOrNull(sCryptAlgorithm);
            if (eCryptAlgorithm == null)
                throw new AS2Exception("The crypting algorithm '" + sCryptAlgorithm + "' is not supported!");
        }
    }
    // Set CTE once here - required for stream creation later on!
    aMsg.headers().setHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, eCTE.getID());
    if (eCompressionType != null || eCryptAlgorithm != null) {
        // Header is needed when compression or encryption is enabled
        if (aMsg.getData().getHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING) == null)
            aMsg.getData().setHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, eCTE.getID());
    }
    if (eCompressionType != null && eSignAlgorithm == null && eCryptAlgorithm == null) {
        // Compression only - set the respective content type
        aMsg.headers().setHeader(CHttpHeader.CONTENT_TYPE, CMimeType.APPLICATION_OCTET_STREAM.getAsStringWithoutParameters());
    }
    return secureMimeBodyPart(aMsg.getData(), eCTE, eCompressionType, bCompressBeforeSign, aCompressBeforeSignCallback, eSignAlgorithm, aSenderCert, aSenderKey, bIncludeCertificateInSignedContent, bUseRFC3851MICAlg, bRemoveCmsAlgorithmProtect, eCryptAlgorithm, aReceiverCert, aMsg.getLoggingText());
}
Also used : PrivateKey(java.security.PrivateKey) ETriState(com.helger.commons.state.ETriState) ICertificateFactory(com.helger.as2lib.cert.ICertificateFactory) X509Certificate(java.security.cert.X509Certificate) ECryptoAlgorithmCrypt(com.helger.as2lib.crypto.ECryptoAlgorithmCrypt) Partnership(com.helger.as2lib.partner.Partnership) ECompressionType(com.helger.as2lib.crypto.ECompressionType) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) MimeBodyPart(javax.mail.internet.MimeBodyPart) ECryptoAlgorithmSign(com.helger.as2lib.crypto.ECryptoAlgorithmSign) Nonnull(javax.annotation.Nonnull)

Aggregations

AS2Exception (com.helger.as2lib.exception.AS2Exception)42 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)23 IOException (java.io.IOException)16 IMicroElement (com.helger.xml.microdom.IMicroElement)8 Nonnull (javax.annotation.Nonnull)8 AS2DispositionException (com.helger.as2lib.disposition.AS2DispositionException)7 AS2NoModuleException (com.helger.as2lib.processor.AS2NoModuleException)7 File (java.io.File)7 MimeBodyPart (javax.mail.internet.MimeBodyPart)7 AS2ComponentNotFoundException (com.helger.as2lib.session.AS2ComponentNotFoundException)6 X509Certificate (java.security.cert.X509Certificate)6 MessagingException (javax.mail.MessagingException)6 ICertificateFactory (com.helger.as2lib.cert.ICertificateFactory)5 IMicroDocument (com.helger.xml.microdom.IMicroDocument)5 InputStream (java.io.InputStream)5 SMIMEException (org.bouncycastle.mail.smime.SMIMEException)5 AS2InvalidParameterException (com.helger.as2lib.params.AS2InvalidParameterException)4 Partnership (com.helger.as2lib.partner.Partnership)4 AS2ProcessorException (com.helger.as2lib.processor.AS2ProcessorException)4 ETriState (com.helger.commons.state.ETriState)4