Search in sources :

Example 66 with WSS4JAttachment

use of com.helger.phase4.attachment.WSS4JAttachment in project phase4 by phax.

the class MainVerifySignature method _verifyAndDecrypt.

@Nonnull
private static ESuccess _verifyAndDecrypt(@Nonnull final IAS4CryptoFactory aCryptoFactory, @Nonnull final Document aSOAPDoc, @Nonnull final Locale aLocale, @Nonnull final AS4ResourceHelper aResHelper, @Nonnull final ICommonsList<WSS4JAttachment> aAttachments, @Nonnull final ErrorList aErrorList, @Nonnull final Supplier<WSSConfig> aWSSConfigSupplier) {
    // Signing verification and Decryption
    try {
        // Convert to WSS4J attachments
        final Phase4KeyStoreCallbackHandler aKeyStoreCallback = new Phase4KeyStoreCallbackHandler(aCryptoFactory);
        final WSS4JAttachmentCallbackHandler aAttachmentCallbackHandler = new WSS4JAttachmentCallbackHandler(aAttachments, aResHelper);
        // Resolve the WSS config here to ensure the context matches
        final WSSConfig aWSSConfig = aWSSConfigSupplier.get();
        // Configure RequestData needed for the check / decrypt process!
        final RequestData aRequestData = new RequestData();
        aRequestData.setCallbackHandler(aKeyStoreCallback);
        if (aAttachments.isNotEmpty())
            aRequestData.setAttachmentCallbackHandler(aAttachmentCallbackHandler);
        aRequestData.setSigVerCrypto(aCryptoFactory.getCrypto());
        aRequestData.setDecCrypto(aCryptoFactory.getCrypto());
        aRequestData.setWssConfig(aWSSConfig);
        // Upon success, the SOAP document contains the decrypted content
        // afterwards!
        final WSSecurityEngine aSecurityEngine = new WSSecurityEngine();
        aSecurityEngine.setWssConfig(aWSSConfig);
        final WSHandlerResult aHdlRes = aSecurityEngine.processSecurityHeader(aSOAPDoc, aRequestData);
        final List<WSSecurityEngineResult> aResults = aHdlRes.getResults();
        // Collect all unique used certificates
        final ICommonsSet<X509Certificate> aCertSet = new CommonsHashSet<>();
        // Preferred certificate from BinarySecurityToken
        X509Certificate aPreferredCert = null;
        int nWSS4JSecurityActions = 0;
        for (final WSSecurityEngineResult aResult : aResults) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("WSSecurityEngineResult: " + aResult);
            final Integer aAction = (Integer) aResult.get(WSSecurityEngineResult.TAG_ACTION);
            final int nAction = aAction != null ? aAction.intValue() : 0;
            nWSS4JSecurityActions |= nAction;
            final X509Certificate aCert = (X509Certificate) aResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
            if (aCert != null) {
                aCertSet.add(aCert);
                if (nAction == WSConstants.BST && aPreferredCert == null)
                    aPreferredCert = aCert;
            }
        }
        // this determines if a signature check or a decryption happened
        final X509Certificate aUsedCert;
        if (aCertSet.size() > 1) {
            if (aPreferredCert == null) {
                LOGGER.warn("Found " + aCertSet.size() + " different certificates in message. Using the first one.");
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("All gathered certificates: " + aCertSet);
                aUsedCert = aCertSet.getAtIndex(0);
            } else
                aUsedCert = aPreferredCert;
        } else if (aCertSet.size() == 1)
            aUsedCert = aCertSet.getAtIndex(0);
        else
            aUsedCert = null;
        // Remember in State
        // Decrypting the Attachments
        final ICommonsList<WSS4JAttachment> aResponseAttachments = aAttachmentCallbackHandler.getAllResponseAttachments();
        for (final WSS4JAttachment aResponseAttachment : aResponseAttachments) {
            // Always copy to a temporary file, so that decrypted content can be
            // read more than once. By default the stream can only be read once
            // Not nice, but working :)
            final File aTempFile = aResHelper.createTempFile();
            StreamHelper.copyInputStreamToOutputStreamAndCloseOS(aResponseAttachment.getSourceStream(), FileHelper.getBufferedOutputStream(aTempFile));
            aResponseAttachment.setSourceStreamProvider(HasInputStream.multiple(() -> FileHelper.getBufferedInputStream(aTempFile)));
        }
        // Remember in State
        return ESuccess.SUCCESS;
    } catch (final IndexOutOfBoundsException | IllegalStateException | WSSecurityException ex) {
        // Decryption or Signature check failed
        LOGGER.error("Error processing the WSSSecurity Header", ex);
        // TODO we need a way to distinct
        // signature and decrypt WSSecurityException provides no such thing
        aErrorList.add(EEbmsError.EBMS_FAILED_DECRYPTION.getAsError(aLocale));
        return ESuccess.FAILURE;
    } catch (final IOException ex) {
        // Decryption or Signature check failed
        LOGGER.error("IO error processing the WSSSecurity Header", ex);
        aErrorList.add(EEbmsError.EBMS_OTHER.getAsError(aLocale));
        return ESuccess.FAILURE;
    }
}
Also used : WSS4JAttachmentCallbackHandler(com.helger.phase4.attachment.WSS4JAttachmentCallbackHandler) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) WSHandlerResult(org.apache.wss4j.dom.handler.WSHandlerResult) WSSecurityEngineResult(org.apache.wss4j.dom.engine.WSSecurityEngineResult) X509Certificate(java.security.cert.X509Certificate) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) WSSecurityEngine(org.apache.wss4j.dom.engine.WSSecurityEngine) Phase4KeyStoreCallbackHandler(com.helger.phase4.servlet.soap.Phase4KeyStoreCallbackHandler) CommonsHashSet(com.helger.commons.collection.impl.CommonsHashSet) File(java.io.File) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) Nonnull(javax.annotation.Nonnull)

Example 67 with WSS4JAttachment

use of com.helger.phase4.attachment.WSS4JAttachment in project phase4 by phax.

the class AS4CEFOneWayFuncTest method testAS4_TA08.

/**
 * Prerequisite:<br>
 * SMSH and RMSH are configured to exchange AS4 messages according to the
 * e-SENS profile (One-Way/Push MEP). Producer submits a message to the SMSH
 * with payload (ex: xml document) and metadata information including a
 * property element with name "MimeType" and value ("application/xml").<br>
 * <br>
 * Predicate: <br>
 * The SMSH generates an AS4 message with the property "MimeType" present and
 * set to the value specified by the producer ("application/xml").
 *
 * @throws Exception
 *         In case of error
 */
@Test
public void testAS4_TA08() throws Exception {
    final ICommonsList<WSS4JAttachment> aAttachments = new CommonsArrayList<>();
    aAttachments.add(WSS4JAttachment.createOutgoingFileAttachment(Phase4OutgoingAttachment.builder().data(ClassPathResource.getAsFile(AS4TestConstants.ATTACHMENT_SHORTXML_XML)).mimeTypeXML().compressionGZIP().build(), s_aResMgr));
    final Document aDoc = createTestSignedUserMessage(m_eSoapVersion, m_aPayload, aAttachments, s_aResMgr);
    final NodeList aNL = aDoc.getElementsByTagName("eb:PartProperties");
    assertNotNull(aNL);
    assertEquals(1, aNL.getLength());
    assertEquals("MimeType", aNL.item(0).getFirstChild().getAttributes().getNamedItem("name").getTextContent());
    assertEquals("application/xml", aNL.item(0).getFirstChild().getTextContent());
}
Also used : NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) Test(org.junit.Test)

Example 68 with WSS4JAttachment

use of com.helger.phase4.attachment.WSS4JAttachment in project phase4 by phax.

the class AS4CEFOneWayFuncTest method testAS4_TA15.

/**
 * Prerequisite:<br>
 * SMSH and RMSH are configured to exchange AS4 messages according to the
 * e-SENS profile (One-Way/Push MEP). SMSH sends an AS4 User Message with a
 * compressed payload to the RMSH.<br>
 * <br>
 * Predicate: <br>
 * The RMSH delivers the message with decompressed payload to the consumer.
 *
 * @throws Exception
 *         In case of error
 */
@Test
public void testAS4_TA15() throws Exception {
    final ICommonsList<WSS4JAttachment> aAttachments = new CommonsArrayList<>();
    aAttachments.add(WSS4JAttachment.createOutgoingFileAttachment(Phase4OutgoingAttachment.builder().data(ClassPathResource.getAsFile(AS4TestConstants.ATTACHMENT_SHORTXML_XML)).mimeTypeXML().compressionGZIP().build(), s_aResMgr));
    final Document aDoc = createTestSignedUserMessage(m_eSoapVersion, m_aPayload, aAttachments, s_aResMgr);
    final AS4MimeMessage aMsg = MimeMessageCreator.generateMimeMessage(m_eSoapVersion, aDoc, aAttachments);
    sendMimeMessage(new HttpMimeMessageEntity(aMsg), true, null);
// How to check message if it is decompressed hmm?
}
Also used : AS4MimeMessage(com.helger.phase4.messaging.mime.AS4MimeMessage) Document(org.w3c.dom.Document) HttpMimeMessageEntity(com.helger.phase4.http.HttpMimeMessageEntity) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) Test(org.junit.Test)

Example 69 with WSS4JAttachment

use of com.helger.phase4.attachment.WSS4JAttachment in project phase4 by phax.

the class AS4CEFOneWayFuncTest method testAS4_TA18.

/**
 * Prerequisite:<br>
 * eSENS_TA13<br>
 * Simulated SMSH sends a signed AS4 User Message with a signed then
 * compressed payload to the RMSH.<br>
 * <br>
 * Predicate: <br>
 * The SMSH receives a WS-Security SOAP Fault.
 *
 * @throws Exception
 *         In case of error
 */
@Test
public void testAS4_TA18() throws Exception {
    // signed then compressed
    // Should return an error because the uncompressed attachment was signed and
    // not the compressed one
    ICommonsList<WSS4JAttachment> aAttachments = new CommonsArrayList<>();
    aAttachments.add(WSS4JAttachment.createOutgoingFileAttachment(Phase4OutgoingAttachment.builder().data(ClassPathResource.getAsFile(AS4TestConstants.ATTACHMENT_SHORTXML_XML)).mimeTypeXML().build(), s_aResMgr));
    final Document aDoc = createTestSignedUserMessage(m_eSoapVersion, m_aPayload, aAttachments, s_aResMgr);
    aAttachments = new CommonsArrayList<>();
    aAttachments.add(WSS4JAttachment.createOutgoingFileAttachment(Phase4OutgoingAttachment.builder().data(ClassPathResource.getAsFile(AS4TestConstants.ATTACHMENT_SHORTXML_XML)).mimeTypeXML().compressionGZIP().build(), s_aResMgr));
    final AS4MimeMessage aMsg = MimeMessageCreator.generateMimeMessage(m_eSoapVersion, aDoc, aAttachments);
    sendMimeMessage(new HttpMimeMessageEntity(aMsg), false, EEbmsError.EBMS_VALUE_INCONSISTENT.getErrorCode());
}
Also used : AS4MimeMessage(com.helger.phase4.messaging.mime.AS4MimeMessage) Document(org.w3c.dom.Document) HttpMimeMessageEntity(com.helger.phase4.http.HttpMimeMessageEntity) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) Test(org.junit.Test)

Example 70 with WSS4JAttachment

use of com.helger.phase4.attachment.WSS4JAttachment in project phase4 by phax.

the class MockMessages method testUserMessageNotSignedNotPModeConform.

@Nonnull
public static Document testUserMessageNotSignedNotPModeConform(@Nonnull final ESoapVersion eSOAPVersion, @Nullable final Node aPayload, @Nullable final ICommonsList<WSS4JAttachment> aAttachments) {
    // Add properties
    final ICommonsList<Ebms3Property> aEbms3Properties = AS4TestConstants.getEBMSProperties();
    final String sPModeID = CAS4.DEFAULT_INITIATOR_URL + "-" + CAS4.DEFAULT_RESPONDER_URL;
    final Ebms3MessageInfo aEbms3MessageInfo = MessageHelperMethods.createEbms3MessageInfo();
    final Ebms3PayloadInfo aEbms3PayloadInfo = MessageHelperMethods.createEbms3PayloadInfo(aPayload != null, aAttachments);
    final Ebms3CollaborationInfo aEbms3CollaborationInfo = MessageHelperMethods.createEbms3CollaborationInfo(sPModeID + "x", DEFAULT_AGREEMENT, AS4TestConstants.TEST_SERVICE_TYPE, AS4TestConstants.TEST_SERVICE, MockMessageProcessorCheckingStreamsSPI.ACTION_FAILURE, AS4TestConstants.TEST_CONVERSATION_ID);
    final Ebms3PartyInfo aEbms3PartyInfo = MessageHelperMethods.createEbms3PartyInfo(CAS4.DEFAULT_INITIATOR_URL, "testt", CAS4.DEFAULT_RESPONDER_URL, "testt");
    final Ebms3MessageProperties aEbms3MessageProperties = MessageHelperMethods.createEbms3MessageProperties(aEbms3Properties);
    final AS4UserMessage aDoc = AS4UserMessage.create(aEbms3MessageInfo, aEbms3PayloadInfo, aEbms3CollaborationInfo, aEbms3PartyInfo, aEbms3MessageProperties, eSOAPVersion).setMustUnderstand(true);
    return aDoc.getAsSoapDocument(aPayload);
}
Also used : Ebms3MessageProperties(com.helger.phase4.ebms3header.Ebms3MessageProperties) Ebms3PayloadInfo(com.helger.phase4.ebms3header.Ebms3PayloadInfo) Ebms3CollaborationInfo(com.helger.phase4.ebms3header.Ebms3CollaborationInfo) Ebms3MessageInfo(com.helger.phase4.ebms3header.Ebms3MessageInfo) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) Ebms3PartyInfo(com.helger.phase4.ebms3header.Ebms3PartyInfo) Ebms3Property(com.helger.phase4.ebms3header.Ebms3Property) Nonnull(javax.annotation.Nonnull)

Aggregations

WSS4JAttachment (com.helger.phase4.attachment.WSS4JAttachment)57 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)56 Test (org.junit.Test)44 AS4MimeMessage (com.helger.phase4.messaging.mime.AS4MimeMessage)39 HttpMimeMessageEntity (com.helger.phase4.http.HttpMimeMessageEntity)36 Document (org.w3c.dom.Document)36 Nonnull (javax.annotation.Nonnull)29 AS4UserMessage (com.helger.phase4.messaging.domain.AS4UserMessage)23 Ebms3Property (com.helger.phase4.ebms3header.Ebms3Property)15 Ebms3CollaborationInfo (com.helger.phase4.ebms3header.Ebms3CollaborationInfo)13 Ebms3MessageInfo (com.helger.phase4.ebms3header.Ebms3MessageInfo)13 Ebms3PayloadInfo (com.helger.phase4.ebms3header.Ebms3PayloadInfo)13 Ebms3PartyInfo (com.helger.phase4.ebms3header.Ebms3PartyInfo)12 Ebms3MessageProperties (com.helger.phase4.ebms3header.Ebms3MessageProperties)11 IOException (java.io.IOException)11 Node (org.w3c.dom.Node)11 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)9 ClassPathResource (com.helger.commons.io.resource.ClassPathResource)7 Phase4Exception (com.helger.phase4.util.Phase4Exception)7 MessagingException (javax.mail.MessagingException)7