org.opensaml.common.SAMLObject Java Examples

The following examples show how to use org.opensaml.common.SAMLObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public VelocityContext encodeMsgContext(MessageContext messageContext)
		throws MessageEncodingException {


	SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

	SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage();
	if (outboundMessage == null) {
		throw new MessageEncodingException(
				"No outbound SAML message contained in message context");
	}

	signMessage(samlMsgCtx);
	samlMsgCtx.setOutboundMessage(outboundMessage);

	return encodeMsgContext(samlMsgCtx);
}
 
Example #2
Source File: SAML2AuthnRequestsSignedRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine whether the inbound message is signed.
 * 
 * @param messageContext the message context being evaluated
 * @return true if the inbound message is signed, otherwise false
 */
protected boolean isMessageSigned(SAMLMessageContext messageContext) {
    // TODO this really should be determined by the decoders and supplied to the rule
    // in some fashion, to handle binding-specific signature mechanisms. See JIRA issue JOWS-4.
    //
    // For now evaluate here inline for XML Signature and HTTP-Redirect and HTTP-Post-SimpleSign.
    
    SAMLObject samlMessage = messageContext.getInboundSAMLMessage();
    if (samlMessage instanceof SignableSAMLObject) {
        SignableSAMLObject signableMessage = (SignableSAMLObject) samlMessage;
        if (signableMessage.isSigned()) {
            return true;
        }
    }
    
    // This handles HTTP-Redirect and HTTP-POST-SimpleSign bindings.
    HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport();
    String sigParam = inTransport.getParameterValue("Signature");
    return !DatatypeHelper.isEmpty(sigParam);
}
 
Example #3
Source File: CasHTTPSOAP11Encoder.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
protected Envelope buildSOAPMessage(final SAMLObject samlMessage) {
    final XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    final SOAPObjectBuilder<Envelope> envBuilder =
            (SOAPObjectBuilder<Envelope>) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    final Envelope envelope = envBuilder.buildObject(
            SOAPConstants.SOAP11_NS, Envelope.DEFAULT_ELEMENT_LOCAL_NAME, OPENSAML_11_SOAP_NS_PREFIX);

    final SOAPObjectBuilder<Body> bodyBuilder =
            (SOAPObjectBuilder<Body>) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
    final Body body = bodyBuilder.buildObject(
            SOAPConstants.SOAP11_NS, Body.DEFAULT_ELEMENT_LOCAL_NAME, OPENSAML_11_SOAP_NS_PREFIX);

    body.getUnknownXMLObjects().add(samlMessage);
    envelope.setBody(body);

    return envelope;
}
 
Example #4
Source File: SAML2ArtifactType0004Builder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the source location used to for the artifacts created by this encoder.
 * 
 * @param requestContext current request context
 * 
 * @return source location used to for the artifacts created by this encoder
 */
protected Endpoint getAcsEndpoint(SAMLMessageContext<SAMLObject, SAMLObject, NameID> requestContext) {
    BasicEndpointSelector selector = new BasicEndpointSelector();
    selector.setEndpointType(ArtifactResolutionService.DEFAULT_ELEMENT_NAME);
    selector.getSupportedIssuerBindings().add(SAMLConstants.SAML2_SOAP11_BINDING_URI);
    selector.setMetadataProvider(requestContext.getMetadataProvider());
    selector.setEntityMetadata(requestContext.getLocalEntityMetadata());
    selector.setEntityRoleMetadata(requestContext.getLocalEntityRoleMetadata());

    Endpoint acsEndpoint = selector.selectEndpoint();

    if (acsEndpoint == null) {
        log.error("No artifact resolution service endpoint defined for the entity "
                + requestContext.getOutboundMessageIssuer());
        return null;
    }

    return acsEndpoint;
}
 
Example #5
Source File: HTTPRedirectDeflateEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * DEFLATE (RFC1951) compresses the given SAML message.
 * 
 * @param message SAML message
 * 
 * @return DEFLATE compressed message
 * 
 * @throws MessageEncodingException thrown if there is a problem compressing the message
 */
protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException {
    log.debug("Deflating and Base64 encoding SAML message");
    try {
        String messageStr = XMLHelper.nodeToString(marshallMessage(message));

        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
        deflaterStream.write(messageStr.getBytes("UTF-8"));
        deflaterStream.finish();

        return Base64.encodeBytes(bytesOut.toByteArray(), Base64.DONT_BREAK_LINES);
    } catch (IOException e) {
        throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
    }
}
 
Example #6
Source File: HTTPSOAP11Encoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds the SOAP message to be encoded.
 * 
 * @param samlMessage body of the SOAP message
 * 
 * @return the SOAP message
 */
@SuppressWarnings("unchecked")
protected Envelope buildSOAPMessage(SAMLObject samlMessage) {
    if (log.isDebugEnabled()) {
        log.debug("Building SOAP message");
    }
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SOAPObjectBuilder<Envelope> envBuilder = (SOAPObjectBuilder<Envelope>) builderFactory
            .getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    Envelope envelope = envBuilder.buildObject();

    if (log.isDebugEnabled()) {
        log.debug("Adding SAML message to the SOAP message's body");
    }
    SOAPObjectBuilder<Body> bodyBuilder = (SOAPObjectBuilder<Body>) builderFactory
            .getBuilder(Body.DEFAULT_ELEMENT_NAME);
    Body body = bodyBuilder.buildObject();
    body.getUnknownXMLObjects().add(samlMessage);
    envelope.setBody(body);

    return envelope;
}
 
Example #7
Source File: HandlerChainAwareHTTPSOAP11Encoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Perform final binding-specific processing of message context and prepare it for encoding
 * to the transport.  
 * 
 * <p>
 * This should include constructing and populating all binding-specific structure and data that needs to be
 * reflected by the message context's properties.
 * </p>
 * 
 * <p>
 * This method is called prior to {@link #processOutboundHandlerChain(MessageContext)}.
 * </p>
 * 
 * @param messageContext the message context to process
 * @throws MessageEncodingException thrown if there is a problem preparing the message context
 *              for encoding
 */
protected void prepareMessageContext(MessageContext messageContext) throws MessageEncodingException {
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject samlMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (samlMessage == null) {
        throw new MessageEncodingException("No outbound SAML message contained in message context");
    }

    signMessage(samlMsgCtx);

    log.debug("Building SOAP envelope");

    Envelope envelope = envBuilder.buildObject();
    Body body = bodyBuilder.buildObject();
    envelope.setBody(body);
    body.getUnknownXMLObjects().add(samlMessage);

    messageContext.setOutboundMessage(envelope);
}
 
Example #8
Source File: BaseSAML2MessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc} 
 * 
 * <p>This SAML 2-specific implementation extracts the value of the protocol message Destination attribute.</p>
 * 
 * */
protected String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) throws MessageDecodingException {
    SAMLObject samlMessage = samlMsgCtx.getInboundSAMLMessage();
    String messageDestination = null;
    if (samlMessage instanceof RequestAbstractType) {
        RequestAbstractType request =  (RequestAbstractType) samlMessage;
        messageDestination = DatatypeHelper.safeTrimOrNullString(request.getDestination());
    } else if (samlMessage instanceof StatusResponseType) {
        StatusResponseType response = (StatusResponseType) samlMessage;
        messageDestination = DatatypeHelper.safeTrimOrNullString(response.getDestination());
    } else {
        log.error("Invalid SAML message type encountered: {}", samlMessage.getElementQName().toString());
        throw new MessageDecodingException("Invalid SAML message type encountered");
    }
    return messageDestination;
}
 
Example #9
Source File: SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.debug("Invalid message context type, this policy rule only supports SAMLMessageContext");
        return;
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject samlMsg = samlMsgCtx.getInboundSAMLMessage();
    if (!(samlMsg instanceof SignableSAMLObject)) {
        log.debug("Extracted SAML message was not a SignableSAMLObject, can not process signature");
        return;
    }
    SignableSAMLObject signableObject = (SignableSAMLObject) samlMsg;
    if (!signableObject.isSigned()) {
        log.info("SAML protocol message was not signed, skipping XML signature processing");
        return;
    }
    Signature signature = signableObject.getSignature();

    performPreValidation(signature);

    doEvaluate(signature, signableObject, samlMsgCtx);
}
 
Example #10
Source File: Decrypter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decrypt the specified instance of EncryptedElementType, and return it as an instance 
 * of the specified QName.
 * 
 * 
 * @param encElement the EncryptedElementType to decrypt
 * @return the decrypted SAMLObject
 * @throws DecryptionException thrown when decryption generates an error
 */
private SAMLObject decryptData(EncryptedElementType encElement) throws DecryptionException {
    
    if (encElement.getEncryptedData() == null) {
        throw new DecryptionException("Element had no EncryptedData child");
    }
    
    XMLObject xmlObject = null;
    try {
        xmlObject = decryptData(encElement.getEncryptedData(), isRootInNewDocument());
    } catch (DecryptionException e) {
        log.error("SAML Decrypter encountered an error decrypting element content", e);
        throw e; 
    }
    
    if (! (xmlObject instanceof SAMLObject)) {
        throw new DecryptionException("Decrypted XMLObject was not an instance of SAMLObject");
    }
    
    return (SAMLObject) xmlObject;
}
 
Example #11
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc} 
 * 
 * <p>This SAML 1-specific implementation extracts the value of the ResponseAbstractType 
 * protocol message Recipient attribute.</p>
 * 
 * */
protected String getIntendedDestinationEndpointURI(SAMLMessageContext samlMsgCtx) throws MessageDecodingException {
    SAMLObject samlMessage = samlMsgCtx.getInboundSAMLMessage();
    String messageDestination = null;
    if (samlMessage instanceof ResponseAbstractType) {
        ResponseAbstractType response = (ResponseAbstractType) samlMessage;
        messageDestination = DatatypeHelper.safeTrimOrNullString(response.getRecipient());
    } else if (samlMessage instanceof RequestAbstractType) {
        // don't treat as an error, just return null
        return null;
    } else {
        log.error("Invalid SAML message type encountered: {}", samlMessage.getElementQName().toString());
        throw new MessageDecodingException("Invalid SAML message type encountered");
    }
    return messageDestination;
}
 
Example #12
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extracts the message ID, issue instant, and issuer from the incoming SAML message and populates the message
 * context with it.
 * 
 * @param messageContext current message context
 * 
 * @throws MessageDecodingException thrown if there is a problem populating the message context
 */
protected void populateMessageIdIssueInstantIssuer(SAMLMessageContext messageContext)
        throws MessageDecodingException {
    SAMLObject samlMsg = messageContext.getInboundSAMLMessage();
    if (samlMsg == null) {
        return;
    }

    if (samlMsg instanceof RequestAbstractType) {
        log.debug("Extracting ID, issuer and issue instant from request");
        extractRequestInfo(messageContext, (RequestAbstractType) samlMsg);
    } else if (samlMsg instanceof Response) {
        log.debug("Extracting ID, issuer and issue instant from response");
        extractResponseInfo(messageContext, (Response) samlMsg);
    } else {
        throw new MessageDecodingException("SAML 1.x message was not a request or a response");
    }
}
 
Example #13
Source File: HTTPSOAP11Encoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds the SOAP message to be encoded.
 * 
 * @param samlMessage body of the SOAP message
 * 
 * @return the SOAP message
 */
@SuppressWarnings("unchecked")
protected Envelope buildSOAPMessage(SAMLObject samlMessage) {
    log.debug("Building SOAP message");
    XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();

    SOAPObjectBuilder<Envelope> envBuilder = (SOAPObjectBuilder<Envelope>) builderFactory
            .getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    Envelope envelope = envBuilder.buildObject();

    log.debug("Adding SAML message to the SOAP message's body");
    SOAPObjectBuilder<Body> bodyBuilder = (SOAPObjectBuilder<Body>) builderFactory
            .getBuilder(Body.DEFAULT_ELEMENT_NAME);
    Body body = bodyBuilder.buildObject();
    body.getUnknownXMLObjects().add(samlMessage);
    envelope.setBody(body);

    return envelope;
}
 
Example #14
Source File: ArtifactResponseUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    ArtifactResponse artifactResponse = (ArtifactResponse) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        artifactResponse.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        artifactResponse.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        artifactResponse.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Status) {
        artifactResponse.setStatus((Status) childSAMLObject);
    } else {
        artifactResponse.setMessage((SAMLObject) childSAMLObject);
    }
}
 
Example #15
Source File: Decrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypt the specified EncryptedAttribute.
 * 
 * @param encryptedAttribute the EncryptedAttribute to decrypt
 * @return an Attribute
 * @throws DecryptionException thrown when decryption generates an error
 */
public Attribute decrypt(EncryptedAttribute encryptedAttribute) throws DecryptionException {
    SAMLObject samlObject = decryptData(encryptedAttribute);
    if (! (samlObject instanceof Attribute)) {
        throw new DecryptionException("Decrypted SAMLObject was not an instance of Attribute");
    }
    return (Attribute) samlObject;
}
 
Example #16
Source File: Decrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypt the specified EncryptedAssertion.
 * 
 * @param encryptedAssertion the EncryptedAssertion to decrypt
 * @return an Assertion 
 * @throws DecryptionException thrown when decryption generates an error
 */
public Assertion decrypt(EncryptedAssertion encryptedAssertion) throws DecryptionException {
    SAMLObject samlObject = decryptData(encryptedAssertion);
    if (! (samlObject instanceof Assertion)) {
        throw new DecryptionException("Decrypted SAMLObject was not an instance of Assertion");
    }
    return (Assertion) samlObject;
}
 
Example #17
Source File: HTTPPostDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void doDecode(MessageContext messageContext) throws MessageDecodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this decoder only support SAMLMessageContext");
        throw new MessageDecodingException(
                "Invalid message context type, this decoder only support SAMLMessageContext");
    }

    if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) {
        log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport");
        throw new MessageDecodingException(
                "Invalid inbound message transport type, this decoder only support HTTPInTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) {
        throw new MessageDecodingException("This message decoder only supports the HTTP POST method");
    }

    String relayState = inTransport.getParameterValue("RelayState");
    samlMsgCtx.setRelayState(relayState);
    log.debug("Decoded SAML relay state of: {}", relayState);

    InputStream base64DecodedMessage = getBase64DecodedMessage(inTransport);
    SAMLObject inboundMessage = (SAMLObject) unmarshallMessage(base64DecodedMessage);
    samlMsgCtx.setInboundMessage(inboundMessage);
    samlMsgCtx.setInboundSAMLMessage(inboundMessage);
    log.debug("Decoded SAML message");

    populateMessageContext(samlMsgCtx);
}
 
Example #18
Source File: Decrypter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decrypt the specified NewEncryptedID.
 * 
 * @param newEncryptedID the NewEncryptedID to decrypt
 * @return a NewID
 * @throws DecryptionException thrown when decryption generates an error
 */
public NewID decrypt(NewEncryptedID newEncryptedID) throws DecryptionException {
    SAMLObject samlObject = decryptData(newEncryptedID);
    if (! (samlObject instanceof NewID)) {
        throw new DecryptionException("Decrypted SAMLObject was not an instance of NewID");
    }
    return (NewID) samlObject;
}
 
Example #19
Source File: BaseSAML2MessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extracts the message ID, issue instant, and issuer from the incoming SAML message and populates the message
 * context with it.
 * 
 * @param messageContext current message context
 * 
 * @throws MessageDecodingException thrown if there is a problem populating the message context
 */
protected void populateMessageIdIssueInstantIssuer(SAMLMessageContext messageContext)
        throws MessageDecodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.debug("Invalid message context type, this policy rule only support SAMLMessageContext");
        return;
    }
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject samlMsg = samlMsgCtx.getInboundSAMLMessage();
    if (samlMsg == null) {
        log.error("Message context did not contain inbound SAML message");
        throw new MessageDecodingException("Message context did not contain inbound SAML message");
    }

    if (samlMsg instanceof RequestAbstractType) {
        log.debug("Extracting ID, issuer and issue instant from request");
        extractRequestInfo(samlMsgCtx, (RequestAbstractType) samlMsg);
    } else if (samlMsg instanceof StatusResponseType) {
        log.debug("Extracting ID, issuer and issue instant from status response");
        extractResponseInfo(samlMsgCtx, (StatusResponseType) samlMsg);
    } else {
        throw new MessageDecodingException("SAML 2 message was not a request or a response");
    }

    if (samlMsgCtx.getInboundMessageIssuer() == null) {
        log.warn("Issuer could not be extracted from SAML 2 message");
    }

}
 
Example #20
Source File: HTTPRedirectDeflateDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void doDecode(MessageContext messageContext) throws MessageDecodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this decoder only support SAMLMessageContext");
        throw new MessageDecodingException(
                "Invalid message context type, this decoder only support SAMLMessageContext");
    }

    if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) {
        log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport");
        throw new MessageDecodingException(
                "Invalid inbound message transport type, this decoder only support HTTPInTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    String relayState = inTransport.getParameterValue("RelayState");
    samlMsgCtx.setRelayState(relayState);
    log.debug("Decoded RelayState: {}", relayState);

    InputStream samlMessageIns;
    if (!DatatypeHelper.isEmpty(inTransport.getParameterValue("SAMLRequest"))) {
        samlMessageIns = decodeMessage(inTransport.getParameterValue("SAMLRequest"));
    } else if (!DatatypeHelper.isEmpty(inTransport.getParameterValue("SAMLResponse"))) {
        samlMessageIns = decodeMessage(inTransport.getParameterValue("SAMLResponse"));
    } else {
        throw new MessageDecodingException(
                "No SAMLRequest or SAMLResponse query path parameter, invalid SAML 2 HTTP Redirect message");
    }

    SAMLObject samlMessage = (SAMLObject) unmarshallMessage(samlMessageIns);
    samlMsgCtx.setInboundSAMLMessage(samlMessage);
    samlMsgCtx.setInboundMessage(samlMessage);
    log.debug("Decoded SAML message");

    populateMessageContext(samlMsgCtx);
}
 
Example #21
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void doEncode(MessageContext messageContext) throws MessageEncodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this encoder only support SAMLMessageContext");
        throw new MessageEncodingException(
                "Invalid message context type, this encoder only support SAMLMessageContext");
    }

    if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) {
        log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
        throw new MessageEncodingException(
                "Invalid outbound message transport type, this encoder only support HTTPOutTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (outboundMessage == null) {
        throw new MessageEncodingException("No outbound SAML message contained in message context");
    }
    String endpointURL = getEndpointURL(samlMsgCtx).buildURL();

    if (samlMsgCtx.getOutboundSAMLMessage() instanceof StatusResponseType) {
        ((StatusResponseType) samlMsgCtx.getOutboundSAMLMessage()).setDestination(endpointURL);
    }

    signMessage(samlMsgCtx);
    samlMsgCtx.setOutboundMessage(outboundMessage);

    postEncode(samlMsgCtx, endpointURL);
}
 
Example #22
Source File: SAML2ArtifactType0004Builder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public SAML2ArtifactType0004 buildArtifact(SAMLMessageContext<SAMLObject, SAMLObject, NameID> requestContext) {
    try {
        IndexedEndpoint acsEndpoint = (IndexedEndpoint) getAcsEndpoint(requestContext);
        if (acsEndpoint == null) {
            return null;
        }

        byte[] endpointIndex = DatatypeHelper.intToByteArray(acsEndpoint.getIndex());
        byte[] trimmedIndex = new byte[2];
        trimmedIndex[0] = endpointIndex[2];
        trimmedIndex[1] = endpointIndex[3];

        MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
        byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes());

        SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
        byte[] assertionHandle;
        assertionHandle = new byte[20];
        handleGenerator.nextBytes(assertionHandle);

        return new SAML2ArtifactType0004(trimmedIndex, source, assertionHandle);
    } catch (NoSuchAlgorithmException e) {
        log.error("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.", e);
        throw new InternalError("JVM does not support required cryptography algorithms: SHA-1/SHA1PRNG.");
    }
}
 
Example #23
Source File: BasicSAMLArtifactMapEntry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the SAML message mapped to the artifact.
 * 
 * @param saml SAML message mapped to the artifact
 */
void setSAMLMessage(SAMLObject saml) {
    if (saml == null) {
        throw new IllegalArgumentException("SAMLObject message may not be null");
    }
    message = saml;
    // Clear the cached serialized version 
    serializedMessage = null;
}
 
Example #24
Source File: BasicSAMLArtifactMapEntry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public SAMLObject getSamlMessage() {
    if (message == null) {
        try {
            deserializeMessage();
        } catch (IOException e) {
            throw new XMLRuntimeException("Error deserializaing SAML message data", e);
        }
    }
    return message;
}
 
Example #25
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void doEncode(MessageContext messageContext) throws MessageEncodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this encoder only support SAMLMessageContext");
        throw new MessageEncodingException(
                "Invalid message context type, this encoder only support SAMLMessageContext");
    }

    if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) {
        log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
        throw new MessageEncodingException(
                "Invalid outbound message transport type, this encoder only support HTTPOutTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    SAMLObject outboundMessage = samlMsgCtx.getOutboundSAMLMessage();
    if (outboundMessage == null) {
        throw new MessageEncodingException("No outbound SAML message contained in message context");
    }
    String endpointURL = getEndpointURL(samlMsgCtx).buildURL();

    if (samlMsgCtx.getOutboundSAMLMessage() instanceof ResponseAbstractType) {
        ((ResponseAbstractType) samlMsgCtx.getOutboundSAMLMessage()).setRecipient(endpointURL);
    }

    signMessage(samlMsgCtx);
    samlMsgCtx.setOutboundMessage(outboundMessage);

    postEncode(samlMsgCtx, endpointURL);
}
 
Example #26
Source File: BasicSAMLArtifactMapEntryFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public SAMLArtifactMapEntry newEntry(String artifact, String issuerId, String relyingPartyId,
        SAMLObject samlMessage, long lifetime) {
    
    SAMLObject newSAMLMessage = getStorableSAMLMessage(samlMessage);
    
    BasicSAMLArtifactMapEntry  entry = 
        new BasicSAMLArtifactMapEntry(artifact, issuerId, relyingPartyId, newSAMLMessage , lifetime);
    
    if (serializeMessage) {
        entry.serializeMessage();
    }
    return entry;
}
 
Example #27
Source File: BasicSAMLArtifactMap.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void put(String artifact, String relyingPartyId, String issuerId, SAMLObject samlMessage)
        throws MarshallingException {

    SAMLArtifactMapEntry artifactEntry = entryFactory.newEntry(artifact, issuerId, relyingPartyId, 
            samlMessage, artifactLifetime);
    
    if (log.isDebugEnabled()) {
        log.debug("Storing new artifact entry '{}' for relying party '{}', expiring at '{}'", 
                new Object[] {artifact, relyingPartyId, artifactEntry.getExpirationTime()});
    }
    
    artifactStore.put(partition, artifact, artifactEntry);
}
 
Example #28
Source File: HTTPPostDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void doDecode(MessageContext messageContext) throws MessageDecodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this decoder only support SAMLMessageContext");
        throw new MessageDecodingException(
                "Invalid message context type, this decoder only support SAMLMessageContext");
    }

    if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) {
        log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport");
        throw new MessageDecodingException(
                "Invalid inbound message transport type, this decoder only support HTTPInTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) {
        throw new MessageDecodingException("This message decoder only supports the HTTP POST method");
    }

    String relayState = inTransport.getParameterValue("TARGET");
    samlMsgCtx.setRelayState(relayState);
    log.debug("Decoded SAML relay state (TARGET parameter) of: {}", relayState);

    String base64Message = inTransport.getParameterValue("SAMLResponse");
    byte[] decodedBytes = Base64.decode(base64Message);
    if (decodedBytes == null) {
        log.error("Unable to Base64 decode SAML message");
        throw new MessageDecodingException("Unable to Base64 decode SAML message");
    }

    SAMLObject inboundMessage = (SAMLObject) unmarshallMessage(new ByteArrayInputStream(decodedBytes));
    samlMsgCtx.setInboundMessage(inboundMessage);
    samlMsgCtx.setInboundSAMLMessage(inboundMessage);
    log.debug("Decoded SAML message");

    populateMessageContext(samlMsgCtx);
}
 
Example #29
Source File: HTTPSOAP11Decoder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
protected void doDecode(MessageContext messageContext) throws MessageDecodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this decoder only support SAMLMessageContext");
        throw new MessageDecodingException(
                "Invalid message context type, this decoder only support SAMLMessageContext");
    }

    if (!(messageContext.getInboundMessageTransport() instanceof HTTPInTransport)) {
        log.error("Invalid inbound message transport type, this decoder only support HTTPInTransport");
        throw new MessageDecodingException(
                "Invalid inbound message transport type, this decoder only support HTTPInTransport");
    }

    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;

    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();
    if (!inTransport.getHTTPMethod().equalsIgnoreCase("POST")) {
        throw new MessageDecodingException("This message decoder only supports the HTTP POST method");
    }

    log.debug("Unmarshalling SOAP message");
    Envelope soapMessage = (Envelope) unmarshallMessage(inTransport.getIncomingStream());
    samlMsgCtx.setInboundMessage(soapMessage);

    Header messageHeader = soapMessage.getHeader();
    if (messageHeader != null) {
        checkUnderstoodSOAPHeaders(soapMessage.getHeader().getUnknownXMLObjects());
    }

    List<XMLObject> soapBodyChildren = soapMessage.getBody().getUnknownXMLObjects();
    if (soapBodyChildren.size() < 1 || soapBodyChildren.size() > 1) {
        log.error("Unexpected number of children in the SOAP body, " + soapBodyChildren.size()
                + ".  Unable to extract SAML message");
        throw new MessageDecodingException(
                "Unexpected number of children in the SOAP body, unable to extract SAML message");
    }

    XMLObject incommingMessage = soapBodyChildren.get(0);
    if (!(incommingMessage instanceof SAMLObject)) {
        log.error("Unexpected SOAP body content.  Expected a SAML request but recieved {}", incommingMessage
                .getElementQName());
        throw new MessageDecodingException("Unexpected SOAP body content.  Expected a SAML request but recieved "
                + incommingMessage.getElementQName());
    }

    SAMLObject samlMessage = (SAMLObject) incommingMessage;
    log.debug("Decoded SOAP messaged which included SAML message of type {}", samlMessage.getElementQName());
    samlMsgCtx.setInboundSAMLMessage(samlMessage);

    populateMessageContext(samlMsgCtx);
}
 
Example #30
Source File: HTTPArtifactEncoder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/** {@inheritDoc} */
protected void doEncode(MessageContext messageContext) throws MessageEncodingException {
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Invalid message context type, this encoder only support SAMLMessageContext");
        throw new MessageEncodingException(
                "Invalid message context type, this encoder only support SAMLMessageContext");
    }

    if (!(messageContext.getOutboundMessageTransport() instanceof HTTPOutTransport)) {
        log.error("Invalid outbound message transport type, this encoder only support HTTPOutTransport");
        throw new MessageEncodingException(
                "Invalid outbound message transport type, this encoder only support HTTPOutTransport");
    }

    SAMLMessageContext<SAMLObject, Response, NameIdentifier> artifactContext = (SAMLMessageContext) messageContext;
    HTTPOutTransport outTransport = (HTTPOutTransport) artifactContext.getOutboundMessageTransport();

    URLBuilder urlBuilder = getEndpointURL(artifactContext);

    List<Pair<String, String>> params = urlBuilder.getQueryParams();

    params.add(new Pair<String, String>("TARGET", artifactContext.getRelayState()));

    SAML1ArtifactBuilder artifactBuilder;
    if (artifactContext.getOutboundMessageArtifactType() != null) {
        artifactBuilder = Configuration.getSAML1ArtifactBuilderFactory().getArtifactBuilder(
                artifactContext.getOutboundMessageArtifactType());
    } else {
        artifactBuilder = Configuration.getSAML1ArtifactBuilderFactory().getArtifactBuilder(defaultArtifactType);
        artifactContext.setOutboundMessageArtifactType(defaultArtifactType);
    }

    AbstractSAML1Artifact artifact;
    String artifactString;
    for (Assertion assertion : artifactContext.getOutboundSAMLMessage().getAssertions()) {
        artifact = artifactBuilder.buildArtifact(artifactContext, assertion);
        if(artifact == null){
            log.error("Unable to build artifact for message to relying party");
            throw new MessageEncodingException("Unable to builder artifact for message to relying party");
        }

        try {
            artifactMap.put(artifact.base64Encode(), messageContext.getInboundMessageIssuer(), messageContext
                    .getOutboundMessageIssuer(), assertion);
        } catch (MarshallingException e) {
            log.error("Unable to marshall assertion to be represented as an artifact", e);
            throw new MessageEncodingException("Unable to marshall assertion to be represented as an artifact", e);
        }
        artifactString = artifact.base64Encode();
        params.add(new Pair<String, String>("SAMLart", artifactString));
    }

    String redirectUrl = urlBuilder.buildURL();

    log.debug("Sending redirect to URL {} to relying party {}", redirectUrl, artifactContext
            .getInboundMessageIssuer());
    outTransport.sendRedirect(urlBuilder.buildURL());
}