Search in sources :

Example 6 with ETriState

use of com.helger.commons.state.ETriState 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)

Example 7 with ETriState

use of com.helger.commons.state.ETriState in project as2-lib by phax.

the class AS2Helper method createMDN.

/**
 * Create a new MDN
 *
 * @param aSession
 *        AS2 session to be used. May not be <code>null</code>.
 * @param aMsg
 *        The source AS2 message for which the MDN is to be created. May not
 *        be <code>null</code>.
 * @param aDisposition
 *        The disposition - either success or error. May not be
 *        <code>null</code>.
 * @param sText
 *        The text to be send. May not be <code>null</code>.
 * @return The created MDN object which is already attached to the passed
 *         source AS2 message.
 * @throws Exception
 *         In case of an error
 */
@Nonnull
public static IMessageMDN createMDN(@Nonnull final IAS2Session aSession, @Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nonnull final String sText) throws Exception {
    ValueEnforcer.notNull(aSession, "AS2Session");
    ValueEnforcer.notNull(aMsg, "AS2Message");
    ValueEnforcer.notNull(aDisposition, "Disposition");
    ValueEnforcer.notNull(sText, "Text");
    final Partnership aPartnership = aMsg.partnership();
    final AS2MessageMDN aMDN = new AS2MessageMDN(aMsg);
    aMDN.headers().setHeader(CHttpHeader.AS2_VERSION, aSession.getAS2VersionID());
    aMDN.headers().setHeader(CHttpHeader.DATE, AS2DateHelper.getFormattedDateNow(CAS2Header.DEFAULT_DATE_FORMAT));
    aMDN.headers().setHeader(CHttpHeader.SERVER, CAS2Info.NAME_VERSION);
    aMDN.headers().setHeader(CHttpHeader.MIME_VERSION, CAS2Header.DEFAULT_MIME_VERSION);
    aMDN.headers().setHeader(CHttpHeader.AS2_FROM, aPartnership.getReceiverAS2ID());
    aMDN.headers().setHeader(CHttpHeader.AS2_TO, aPartnership.getSenderAS2ID());
    // 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(aPartnership.getReceiverX509Alias());
    aMDN.partnership().setReceiverX509Alias(aPartnership.getSenderX509Alias());
    // Update the partnership
    try {
        aSession.getPartnershipFactory().updatePartnership(aMDN, true);
    } catch (final AS2PartnershipNotFoundException ex) {
    // This would block sending an MDN in case a PartnershipNotFoundException
    // was the reason for sending the MDN :)
    }
    aMDN.headers().setHeader(CHttpHeader.FROM, aPartnership.getReceiverEmail());
    final String sSubject = aMDN.partnership().getMDNSubject();
    if (sSubject != null) {
        aMDN.headers().setHeader(CHttpHeader.SUBJECT, new MessageParameters(aMsg).format(sSubject));
    } else {
        aMDN.headers().setHeader(CHttpHeader.SUBJECT, "Your Requested MDN Response");
    }
    // Content-Transfer-Encoding for outgoing MDNs
    final String sCTE = aPartnership.getContentTransferEncodingSend(EContentTransferEncoding.AS2_DEFAULT.getID());
    aMDN.headers().addHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, sCTE);
    aMDN.setText(new MessageParameters(aMsg).format(sText));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_REPORTING_UA, CAS2Info.NAME_VERSION + "@" + aMsg.attrs().getAsString(CNetAttribute.MA_DESTINATION_IP) + ":" + aMsg.attrs().getAsString(CNetAttribute.MA_DESTINATION_PORT));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_ORIG_RECIPIENT, "rfc822; " + aMsg.getHeader(CHttpHeader.AS2_TO));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_FINAL_RECIPIENT, "rfc822; " + aPartnership.getReceiverAS2ID());
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_ORIG_MESSAGEID, aMsg.getHeader(CHttpHeader.MESSAGE_ID));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_DISPOSITION, aDisposition.getAsString());
    final String sDispositionOptions = aMsg.getHeader(CHttpHeader.DISPOSITION_NOTIFICATION_OPTIONS);
    final DispositionOptions aDispositionOptions = DispositionOptions.createFromString(sDispositionOptions);
    ECryptoAlgorithmSign eSigningAlgorithm = aDispositionOptions.getFirstMICAlg();
    if (eSigningAlgorithm == null) {
        // Try from partnership (#93)
        final String sSigningAlgorithm = aPartnership.getSigningAlgorithm();
        eSigningAlgorithm = ECryptoAlgorithmSign.getFromIDOrNull(sSigningAlgorithm);
        if (eSigningAlgorithm == null) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("The partnership signing algorithm name '" + sSigningAlgorithm + "' is unknown.");
        }
    }
    MIC aMIC = null;
    if (eSigningAlgorithm != null) {
        // If the source message was signed or encrypted, include the headers -
        // see message sending for details
        final boolean bIncludeHeadersInMIC = aPartnership.getSigningAlgorithm() != null || aPartnership.getEncryptAlgorithm() != null || aPartnership.getCompressionType() != null;
        aMIC = getCryptoHelper().calculateMIC(aMsg.getData(), eSigningAlgorithm, bIncludeHeadersInMIC);
    }
    if (aMIC != null)
        aMDN.attrs().putIn(AS2MessageMDN.MDNA_MIC, aMIC.getAsAS2String());
    boolean bSignMDN = false;
    boolean bIncludeCertificateInSignedContent = false;
    if (aDispositionOptions.getProtocol() != null) {
        if (aDispositionOptions.isProtocolRequired() || aDispositionOptions.hasMICAlg()) {
            // Sign if required or if optional and a MIC algorithm is present
            bSignMDN = true;
            // Include certificate in signed content?
            final ETriState eIncludeCertificateInSignedContent = aPartnership.getIncludeCertificateInSignedContent();
            if (eIncludeCertificateInSignedContent.isDefined()) {
                // Use per partnership
                bIncludeCertificateInSignedContent = eIncludeCertificateInSignedContent.getAsBooleanValue();
            } else {
                // Use global value
                bIncludeCertificateInSignedContent = aSession.isCryptoSignIncludeCertificateInBodyPart();
            }
        }
    }
    final boolean bUseOldRFC3851MicAlgs = aPartnership.isRFC3851MICAlgs();
    final boolean bRemoveCmsAlgorithmProtect = aPartnership.isRemoveCmsAlgorithmProtect();
    createMDNData(aSession, aMDN, bSignMDN, bIncludeCertificateInSignedContent, aDispositionOptions.getFirstMICAlg(), bUseOldRFC3851MicAlgs, bRemoveCmsAlgorithmProtect);
    aMDN.updateMessageID();
    // store MDN into msg in case AsynchMDN is sent fails, needs to be resent by
    // send module
    aMsg.setMDN(aMDN);
    return aMDN;
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) Partnership(com.helger.as2lib.partner.Partnership) ETriState(com.helger.commons.state.ETriState) DispositionOptions(com.helger.as2lib.disposition.DispositionOptions) MIC(com.helger.as2lib.crypto.MIC) MessageParameters(com.helger.as2lib.params.MessageParameters) AS2PartnershipNotFoundException(com.helger.as2lib.partner.AS2PartnershipNotFoundException) ECryptoAlgorithmSign(com.helger.as2lib.crypto.ECryptoAlgorithmSign) Nonnull(javax.annotation.Nonnull)

Example 8 with ETriState

use of com.helger.commons.state.ETriState in project phase4 by phax.

the class ENTSOGPMode method generatePModeReceptionAwareness.

@Nonnull
public static PModeReceptionAwareness generatePModeReceptionAwareness() {
    final ETriState eReceptionAwareness = ETriState.TRUE;
    final ETriState eRetry = ETriState.TRUE;
    final int nMaxRetries = 1;
    final int nRetryIntervalMS = 10_000;
    final ETriState eDuplicateDetection = ETriState.TRUE;
    return new PModeReceptionAwareness(eReceptionAwareness, eRetry, nMaxRetries, nRetryIntervalMS, eDuplicateDetection);
}
Also used : ETriState(com.helger.commons.state.ETriState) PModeReceptionAwareness(com.helger.phase4.model.pmode.PModeReceptionAwareness) Nonnull(javax.annotation.Nonnull)

Example 9 with ETriState

use of com.helger.commons.state.ETriState in project phase4 by phax.

the class ENTSOGPMode method generatePModeLegErrorHandling.

@Nonnull
public static PModeLegErrorHandling generatePModeLegErrorHandling() {
    final PModeAddressList aReportSenderErrorsTo = null;
    final PModeAddressList aReportReceiverErrorsTo = null;
    final ETriState eReportAsResponse = ETriState.TRUE;
    final ETriState eReportProcessErrorNotifyConsumer = ETriState.TRUE;
    final ETriState eReportProcessErrorNotifyProducer = ETriState.TRUE;
    final ETriState eReportDeliveryFailuresNotifyProducer = ETriState.TRUE;
    return new PModeLegErrorHandling(aReportSenderErrorsTo, aReportReceiverErrorsTo, eReportAsResponse, eReportProcessErrorNotifyConsumer, eReportProcessErrorNotifyProducer, eReportDeliveryFailuresNotifyProducer);
}
Also used : ETriState(com.helger.commons.state.ETriState) PModeLegErrorHandling(com.helger.phase4.model.pmode.leg.PModeLegErrorHandling) PModeAddressList(com.helger.phase4.model.pmode.leg.PModeAddressList) Nonnull(javax.annotation.Nonnull)

Example 10 with ETriState

use of com.helger.commons.state.ETriState in project phase4 by phax.

the class CEFPMode method generatePModeLegErrorHandling.

@Nonnull
public static PModeLegErrorHandling generatePModeLegErrorHandling() {
    final PModeAddressList aReportSenderErrorsTo = null;
    final PModeAddressList aReportReceiverErrorsTo = null;
    final ETriState eReportAsResponse = ETriState.TRUE;
    final ETriState eReportProcessErrorNotifyConsumer = ETriState.TRUE;
    final ETriState eReportProcessErrorNotifyProducer = ETriState.TRUE;
    final ETriState eReportDeliveryFailuresNotifyProducer = ETriState.TRUE;
    return new PModeLegErrorHandling(aReportSenderErrorsTo, aReportReceiverErrorsTo, eReportAsResponse, eReportProcessErrorNotifyConsumer, eReportProcessErrorNotifyProducer, eReportDeliveryFailuresNotifyProducer);
}
Also used : ETriState(com.helger.commons.state.ETriState) PModeLegErrorHandling(com.helger.phase4.model.pmode.leg.PModeLegErrorHandling) PModeAddressList(com.helger.phase4.model.pmode.leg.PModeAddressList) Nonnull(javax.annotation.Nonnull)

Aggregations

ETriState (com.helger.commons.state.ETriState)32 Nonnull (javax.annotation.Nonnull)24 Nullable (javax.annotation.Nullable)10 ValueEnforcer (com.helger.commons.ValueEnforcer)7 ErrorList (com.helger.commons.error.list.ErrorList)7 Consumer (java.util.function.Consumer)7 AmountType (un.unece.uncefact.data.standard.unqualifieddatatype._100.AmountType)7 CGlobal (com.helger.commons.CGlobal)6 CollectionHelper (com.helger.commons.collection.CollectionHelper)6 EqualsHelper (com.helger.commons.equals.EqualsHelper)6 IErrorList (com.helger.commons.error.list.IErrorList)6 MathHelper (com.helger.commons.math.MathHelper)6 StringHelper (com.helger.commons.string.StringHelper)6 Serializable (java.io.Serializable)6 BigDecimal (java.math.BigDecimal)6 LocalDate (java.time.LocalDate)6 CrossIndustryInvoiceType (un.unece.uncefact.data.standard.crossindustryinvoice._100.CrossIndustryInvoiceType)6 FormattedDateTimeType (un.unece.uncefact.data.standard.qualifieddatatype._100.FormattedDateTimeType)6 un.unece.uncefact.data.standard.reusableaggregatebusinessinformationentity._100 (un.unece.uncefact.data.standard.reusableaggregatebusinessinformationentity._100)6 BinaryObjectType (un.unece.uncefact.data.standard.unqualifieddatatype._100.BinaryObjectType)6