org.opensaml.common.binding.SAMLMessageContext Java Examples

The following examples show how to use org.opensaml.common.binding.SAMLMessageContext. 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: BaseSAML1MessageEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the response URL from the relying party endpoint. If the SAML message is a {@link Response} and the relying
 * party endpoint contains a response location then that location is returned otherwise the normal endpoint location
 * is returned.
 * 
 * @param messageContext current message context
 * 
 * @return response URL from the relying party endpoint
 * 
 * @throws MessageEncodingException throw if no relying party endpoint is available
 */
protected URLBuilder getEndpointURL(SAMLMessageContext messageContext) throws MessageEncodingException {
    Endpoint endpoint = messageContext.getPeerEntityEndpoint();
    if (endpoint == null) {
        throw new MessageEncodingException("Endpoint for relying party was null.");
    }

    URLBuilder urlBuilder;
    if (messageContext.getOutboundSAMLMessage() instanceof Response
            && !DatatypeHelper.isEmpty(endpoint.getResponseLocation())) {
        urlBuilder = new URLBuilder(endpoint.getResponseLocation());
    } else {
        if (DatatypeHelper.isEmpty(endpoint.getLocation())) {
            throw new MessageEncodingException("Relying party endpoint location was null or empty.");
        }
        urlBuilder = new URLBuilder(endpoint.getLocation());
    }
    
    if(!getAllowedURLSchemes().contains(urlBuilder.getScheme())){
       throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme()); 
    }
    return urlBuilder;
}
 
Example #3
Source File: HTTPArtifactDecoder.java    From lams with GNU General Public License v2.0 6 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;
    
    decodeTarget(samlMsgCtx);
    processArtifacts(samlMsgCtx);

    populateMessageContext(samlMsgCtx);
}
 
Example #4
Source File: SAML1ArtifactType0002Builder.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 String getSourceLocation(SAMLMessageContext<RequestAbstractType, Response, NameIdentifier> requestContext) {
    BasicEndpointSelector selector = new BasicEndpointSelector();
    selector.setEndpointType(ArtifactResolutionService.DEFAULT_ELEMENT_NAME);
    selector.getSupportedIssuerBindings().add(SAMLConstants.SAML1_SOAP11_BINDING_URI);
    selector.setMetadataProvider(requestContext.getMetadataProvider());
    selector.setEntityMetadata(requestContext.getLocalEntityMetadata());
    selector.setEntityRoleMetadata(requestContext.getLocalEntityRoleMetadata());

    Endpoint acsEndpoint = selector.selectEndpoint();

    if (acsEndpoint == null) {
        log.error("Unable to select source location for artifact.  No artifact resolution service defined for issuer.");
        return null;
    }

    return acsEndpoint.getLocation();
}
 
Example #5
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 #6
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract information from a SAML RequestAbstractType message.
 * 
 * @param messageContext current message context
 * @param abstractRequest the SAML message to process
 */
protected void extractRequestInfo(SAMLMessageContext messageContext, RequestAbstractType abstractRequest) {
    messageContext.setInboundSAMLMessageId(abstractRequest.getID());
    messageContext.setInboundSAMLMessageIssueInstant(abstractRequest.getIssueInstant());

    if (abstractRequest instanceof Request) {
        Request request = (Request) abstractRequest;
        if (request.getAttributeQuery() != null) {
            extractAttributeQueryInfo(messageContext, request.getAttributeQuery());
        }

        if (request.getAuthorizationDecisionQuery() != null) {
            extractAuthorizationDecisionQueryInfo(messageContext, request.getAuthorizationDecisionQuery());
        }

        if (request.getAssertionArtifacts() != null) {
            extractAssertionArtifactInfo(messageContext, request.getAssertionArtifacts());
        }
    }
}
 
Example #7
Source File: SAML1ArtifactType0002Builder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public SAML1ArtifactType0002 buildArtifact(
        SAMLMessageContext<RequestAbstractType, Response, NameIdentifier> requestContext, Assertion assertion) {
    try {
        String sourceLocation = getSourceLocation(requestContext);
        if (sourceLocation == null) {
            return null;
        }

        SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
        byte[] assertionHandle = new byte[20];
        handleGenerator.nextBytes(assertionHandle);
        return new SAML1ArtifactType0002(assertionHandle, sourceLocation);
    } catch (NoSuchAlgorithmException e) {
        log.error("JVM does not support required cryptography algorithms: SHA1PRNG.", e);
        throw new InternalError("JVM does not support required cryptography algorithms: SHA1PRNG.");
    }
}
 
Example #8
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populates the peer's entity metadata if a metadata provide is present in the message context. Populates the
 * peer's role descriptor if the entity metadata was available and the role name is present in the message context.
 * 
 * @param messageContext current message context
 * 
 * @throws MessageDecodingException thrown if there is a problem populating the message context
 */
protected void populateRelyingPartyMetadata(SAMLMessageContext messageContext) throws MessageDecodingException {
    MetadataProvider metadataProvider = messageContext.getMetadataProvider();
    try {
        if (metadataProvider != null) {
            EntityDescriptor relyingPartyMD = metadataProvider.getEntityDescriptor(messageContext
                    .getInboundMessageIssuer());
            messageContext.setPeerEntityMetadata(relyingPartyMD);

            QName relyingPartyRole = messageContext.getPeerEntityRole();
            if (relyingPartyMD != null && relyingPartyRole != null) {
                List<RoleDescriptor> roles = relyingPartyMD.getRoleDescriptors(relyingPartyRole,
                        SAMLConstants.SAML11P_NS);
                if (roles != null && roles.size() > 0) {
                    messageContext.setPeerEntityRoleMetadata(roles.get(0));
                }
            }
        }
    } catch (MetadataProviderException e) {
        log.error("Error retrieving metadata for relying party " + messageContext.getInboundMessageIssuer(), e);
        throw new MessageDecodingException("Error retrieving metadata for relying party "
                + messageContext.getInboundMessageIssuer(), e);
    }
}
 
Example #9
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 #10
Source File: BaseSAMLSimpleSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Build a criteria set suitable for input to the trust engine.
 * 
 * @param entityID the candidate issuer entity ID which is being evaluated
 * @param samlContext the message context which is being evaluated
 * @return a newly constructly set of criteria suitable for the configured trust engine
 * @throws SecurityPolicyException thrown if criteria set can not be constructed
 */
protected CriteriaSet buildCriteriaSet(String entityID, SAMLMessageContext samlContext)
        throws SecurityPolicyException {

    CriteriaSet criteriaSet = new CriteriaSet();
    if (!DatatypeHelper.isEmpty(entityID)) {
        criteriaSet.add(new EntityIDCriteria(entityID));
    }

    MetadataCriteria mdCriteria = new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext
            .getInboundSAMLProtocol());
    criteriaSet.add(mdCriteria);

    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

    return criteriaSet;
}
 
Example #11
Source File: SAMLMDClientCertAuthRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected CriteriaSet buildCriteriaSet(String entityID, MessageContext messageContext) 
    throws SecurityPolicyException {
    
    if (!(messageContext instanceof SAMLMessageContext)) {
        log.error("Supplied message context was not an instance of SAMLMessageContext, can not build criteria set from SAML metadata parameters");
        throw new SecurityPolicyException("Supplied message context was not an instance of SAMLMessageContext");
    }
    
    SAMLMessageContext samlContext = (SAMLMessageContext) messageContext;

    CriteriaSet criteriaSet = super.buildCriteriaSet(entityID, messageContext);
    MetadataCriteria mdCriteria = 
        new MetadataCriteria(samlContext.getPeerEntityRole(), samlContext.getInboundSAMLProtocol());
    criteriaSet.add(mdCriteria);

    return criteriaSet;
}
 
Example #12
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 #13
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 #14
Source File: HTTPArtifactEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Performs HTTP GET based encoding.
 * 
 * @param artifactContext current request context
 * @param outTransport outbound HTTP transport
 * 
 * @throws MessageEncodingException thrown if there is a problem GET encoding the artifact
 */
protected void getEncode(SAMLMessageContext artifactContext, HTTPOutTransport outTransport)
        throws MessageEncodingException {
    log.debug("Performing HTTP GET SAML 2 artifact encoding");

    URLBuilder urlBuilder = getEndpointURL(artifactContext);

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

    AbstractSAMLArtifact artifact = buildArtifact(artifactContext);
    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");
    }
    params.add(new Pair<String, String>("SAMLart", artifact.base64Encode()));

    if (checkRelayState(artifactContext.getRelayState())) {
        params.add(new Pair<String, String>("RelayState", artifactContext.getRelayState()));
    }

    outTransport.sendRedirect(urlBuilder.buildURL());
}
 
Example #15
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Base64 and POST encodes the outbound message and writes it to the outbound transport.
 * 
 * @param messageContext current message context
 * @param endpointURL endpoint URL to which to encode message
 * 
 * @throws MessageEncodingException thrown if there is a problem encoding the message
 */
protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException {
    log.debug("Invoking Velocity template to create POST body");
    try {
        VelocityContext context = new VelocityContext();

        populateVelocityContext(context, messageContext, endpointURL);

        HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport();
        HTTPTransportUtils.addNoCacheHeaders(outTransport);
        HTTPTransportUtils.setUTF8Encoding(outTransport);
        HTTPTransportUtils.setContentType(outTransport, "text/html");

        Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8");
        velocityEngine.mergeTemplate(velocityTemplateId, "UTF-8", context, out);
        out.flush();
    } catch (Exception e) {
        log.error("Error invoking Velocity template", e);
        throw new MessageEncodingException("Error creating output document", e);
    }
}
 
Example #16
Source File: HTTPPostEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populate the Velocity context instance which will be used to render the POST body.
 * 
 * @param velocityContext the Velocity context instance to populate with data
 * @param messageContext the SAML message context source of data
 * @param endpointURL endpoint URL to which to encode message
 * @throws MessageEncodingException thrown if there is a problem encoding the message
 */
protected void populateVelocityContext(VelocityContext velocityContext, SAMLMessageContext messageContext,
        String endpointURL) throws MessageEncodingException {
    
    Encoder esapiEncoder = ESAPI.encoder();

    String encodedEndpointURL = esapiEncoder.encodeForHTMLAttribute(endpointURL);
    log.debug("Encoding action url of '{}' with encoded value '{}'", endpointURL, encodedEndpointURL);
    velocityContext.put("action", encodedEndpointURL);
    velocityContext.put("binding", getBindingURI());

    log.debug("Marshalling and Base64 encoding SAML message");
    if (messageContext.getOutboundSAMLMessage().getDOM() == null) {
        marshallMessage(messageContext.getOutboundSAMLMessage());
    }
    try {
        String messageXML = XMLHelper.nodeToString(messageContext.getOutboundSAMLMessage().getDOM());
        String encodedMessage = Base64.encodeBytes(messageXML.getBytes("UTF-8"), Base64.DONT_BREAK_LINES);
        if (messageContext.getOutboundSAMLMessage() instanceof RequestAbstractType) {
            velocityContext.put("SAMLRequest", encodedMessage);
        } else if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType) {
            velocityContext.put("SAMLResponse", encodedMessage);
        } else {
            throw new MessageEncodingException(
                    "SAML message is neither a SAML RequestAbstractType or StatusResponseType");
        }
    } catch (UnsupportedEncodingException e) {
        log.error("UTF-8 encoding is not supported, this VM is not Java compliant.");
        throw new MessageEncodingException("Unable to encode message, UTF-8 encoding is not supported");
    }

    String relayState = messageContext.getRelayState();
    if (checkRelayState(relayState)) {
        String encodedRelayState = esapiEncoder.encodeForHTMLAttribute(relayState);
        log.debug("Setting RelayState parameter to: '{}', encoded as '{}'", relayState, encodedRelayState);
        velocityContext.put("RelayState", encodedRelayState);
    }
}
 
Example #17
Source File: HandlerChainAwareHTTPSOAP11Encoder.java    From lams with GNU General Public License v2.0 6 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");
    }

    prepareMessageContext(messageContext);
    
    processOutboundHandlerChain(messageContext);
    
    encodeToTransport(messageContext);
}
 
Example #18
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 #19
Source File: HTTPArtifactEncoder.java    From lams with GNU General Public License v2.0 6 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 artifactContext = (SAMLMessageContext) messageContext;
    HTTPOutTransport outTransport = (HTTPOutTransport) artifactContext.getOutboundMessageTransport();
    outTransport.setCharacterEncoding("UTF-8");

    if (postEncoding) {
        postEncode(artifactContext, outTransport);
    } else {
        getEncode(artifactContext, outTransport);
    }
}
 
Example #20
Source File: BaseSAML2MessageEncoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the response URL from the relying party endpoint. If the SAML message is a {@link StatusResponseType} and the relying
 * party endpoint contains a response location then that location is returned otherwise the normal endpoint location
 * is returned.
 * 
 * @param messageContext current message context
 * 
 * @return response URL from the relying party endpoint
 * 
 * @throws MessageEncodingException throw if no relying party endpoint is available
 */
protected URLBuilder getEndpointURL(SAMLMessageContext messageContext) throws MessageEncodingException {
    Endpoint endpoint = messageContext.getPeerEntityEndpoint();
    if (endpoint == null) {
        throw new MessageEncodingException("Endpoint for relying party was null.");
    }
    
    URLBuilder urlBuilder;
    if (messageContext.getOutboundSAMLMessage() instanceof StatusResponseType
            && !DatatypeHelper.isEmpty(endpoint.getResponseLocation())) {
        urlBuilder = new URLBuilder(endpoint.getResponseLocation());
    } else {
        if (DatatypeHelper.isEmpty(endpoint.getLocation())) {
            throw new MessageEncodingException("Relying party endpoint location was null or empty.");
        }
        urlBuilder = new URLBuilder(endpoint.getLocation());
    }
    
    if(!getAllowedURLSchemes().contains(urlBuilder.getScheme())){
       throw new MessageEncodingException("Relying party endpoint used the untrusted URL scheme " + urlBuilder.getScheme()); 
    }
    return urlBuilder;
}
 
Example #21
Source File: OpenHTTPPostDecoder.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
protected String getActualReceiverEndpointURI(SAMLMessageContext messageContext) throws MessageDecodingException {
    InTransport inTransport = messageContext.getInboundMessageTransport();
    if (!(inTransport instanceof HttpServletRequestAdapter)) {
        throw new MessageDecodingException("Message context InTransport instance was an unsupported type");
    }
    HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();

    StringBuffer urlBuilder = httpRequest.getRequestURL();

    String tempUrl = urlBuilder.toString();
    // 从http协议头开始,跳过前面两个斜杠
    tempUrl = tempUrl.substring(tempUrl.indexOf("/", 8) + 1);
    return receiverEndpoint + tempUrl;
}
 
Example #22
Source File: OpenHTTPPostSimpleSignDecoder.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
protected String getActualReceiverEndpointURI(
		SAMLMessageContext messageContext) throws MessageDecodingException {
	InTransport inTransport = messageContext.getInboundMessageTransport();
	if (!(inTransport instanceof HttpServletRequestAdapter)) {
		throw new MessageDecodingException("Message context InTransport instance was an unsupported type");
	}
	HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();

	StringBuffer urlBuilder = httpRequest.getRequestURL();

	String tempUrl = urlBuilder.toString();
	// 从http协议头开始,跳过前面两个斜杠
	tempUrl = tempUrl.substring(tempUrl.indexOf("/", 8) + 1);
	return receiverEndpoint + tempUrl;
}
 
Example #23
Source File: OpenHTTPRedirectDecoder.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
protected String getActualReceiverEndpointURI(SAMLMessageContext messageContext) throws MessageDecodingException {
	InTransport inTransport = messageContext.getInboundMessageTransport();
	if (!(inTransport instanceof HttpServletRequestAdapter)) {
		throw new MessageDecodingException(
				"Message context InTransport instance was an unsupported type");
	}
	HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport)
			.getWrappedRequest();

	StringBuffer urlBuilder = httpRequest.getRequestURL();

	String tempUrl = urlBuilder.toString();
	// 从http协议头开始,跳过前面两个斜杠
	tempUrl = tempUrl.substring(tempUrl.indexOf("/", 8) + 1);
	return receiverEndpoint + tempUrl;
}
 
Example #24
Source File: BaseSAML2MessageDecoder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populates the peer's entity metadata if a metadata provide is present in the message context. Populates the
 * peer's role descriptor if the entity metadata was available and the role name is present in the message context.
 * 
 * @param messageContext current message context
 * 
 * @throws MessageDecodingException thrown if there is a problem populating the message context
 */
protected void populateRelyingPartyMetadata(SAMLMessageContext messageContext) throws MessageDecodingException {
    MetadataProvider metadataProvider = messageContext.getMetadataProvider();
    try {
        if (metadataProvider != null) {
            EntityDescriptor relyingPartyMD = metadataProvider.getEntityDescriptor(messageContext
                    .getInboundMessageIssuer());
            messageContext.setPeerEntityMetadata(relyingPartyMD);

            QName relyingPartyRole = messageContext.getPeerEntityRole();
            if (relyingPartyMD != null && relyingPartyRole != null) {
                List<RoleDescriptor> roles = relyingPartyMD.getRoleDescriptors(relyingPartyRole,
                        SAMLConstants.SAML11P_NS);
                if (roles != null && roles.size() > 0) {
                    messageContext.setPeerEntityRoleMetadata(roles.get(0));
                }
            }
        }
    } catch (MetadataProviderException e) {
        log.error("Error retrieving metadata for relying party " + messageContext.getInboundMessageIssuer(), e);
        throw new MessageDecodingException("Error retrieving metadata for relying party "
                + messageContext.getInboundMessageIssuer(), e);
    }
}
 
Example #25
Source File: SAML1ArtifactType0001Builder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public SAML1ArtifactType0001 buildArtifact(
        SAMLMessageContext<RequestAbstractType, Response, NameIdentifier> requestContext, Assertion assertion) {
    try {
        MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
        byte[] source = sha1Digester.digest(requestContext.getLocalEntityId().getBytes());

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

        return new SAML1ArtifactType0001(source, assertionHandle);
    } catch (NoSuchAlgorithmException e) {
        log.error("JVM does not support required cryptography algorithms.", e);
        throw new InternalError("JVM does not support required cryptography algorithms: SHA-1 and/or SHA1PRNG.");
    }
}
 
Example #26
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException {
    super.decode(messageContext);
    
    SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext;
    if (samlMsgCtx.getInboundSAMLMessage() instanceof ResponseAbstractType) {
        checkEndpointURI(samlMsgCtx);
    }
}
 
Example #27
Source File: BaseSAML1MessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Extract information from a SAML StatusResponse message.
 * 
 * @param messageContext current message context
 * @param response the SAML message to process
 * 
 * @throws MessageDecodingException thrown if the assertions within the response contain differening issuer IDs
 */
protected void extractResponseInfo(SAMLMessageContext messageContext, Response response)
        throws MessageDecodingException {

    messageContext.setInboundSAMLMessageId(response.getID());
    messageContext.setInboundSAMLMessageIssueInstant(response.getIssueInstant());

    String issuer = null;
    List<Assertion> assertions = ((Response) response).getAssertions();
    if (assertions != null && assertions.size() > 0) {
        log.info("Attempting to extract issuer from enclosed SAML 1.x Assertion(s)");
        for (Assertion assertion : assertions) {
            if (assertion != null && assertion.getIssuer() != null) {
                if (issuer != null && !issuer.equals(assertion.getIssuer())) {
                    throw new MessageDecodingException("SAML 1.x assertions, within response " + response.getID()
                            + " contain different issuer IDs");
                }
                issuer = assertion.getIssuer();
            }
        }
    }

    if (issuer == null) {
        log.warn("Issuer could not be extracted from standard SAML 1.x response message");
    }

    messageContext.setInboundMessageIssuer(issuer);
}
 
Example #28
Source File: WebServicePostEncoder.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
/**
 * Build the form control data string over which the signature is computed.
 * 
 * @param velocityContext
 *            the Velocity context which is already populated with the
 *            values for SAML message and relay state
 * @param messageContext
 *            the SAML message context being processed
 * @param sigAlgURI
 *            the signature algorithm URI
 * 
 * @return the form control data string for signature computation
 */
@SuppressWarnings("rawtypes")
protected String buildFormDataToSign(VelocityContext velocityContext,
		SAMLMessageContext messageContext, String sigAlgURI) {
	StringBuilder builder = new StringBuilder();

	boolean isRequest = false;
	if (velocityContext.get("SAMLRequest") != null) {
		isRequest = true;
	}

	String msgB64;
	if (isRequest) {
		msgB64 = (String) velocityContext.get("SAMLRequest");
	} else {
		msgB64 = (String) velocityContext.get("SAMLResponse");
	}

	String msg = null;
	try {
		msg = new String(Base64.decode(msgB64), "UTF-8");
	} catch (UnsupportedEncodingException e) {
		// All JVM's required to support UTF-8
	}

	if (isRequest) {
		builder.append("SAMLRequest=" + msg);
	} else {
		builder.append("SAMLResponse=" + msg);
	}

	if (messageContext.getRelayState() != null) {
		builder.append("&RelayState=" + messageContext.getRelayState());
	}

	builder.append("&SigAlg=" + sigAlgURI);

	return builder.toString();
}
 
Example #29
Source File: BaseSAMLMessageDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the validity of the SAML protocol message receiver endpoint against
 * requirements indicated in the message.
 * 
 * @param messageContext current message context
 * 
 * @throws SecurityException thrown if the message Destination attribute is invalid
 *                                  with respect to the receiver's endpoint
 * @throws MessageDecodingException thrown if there is a problem decoding and processing
 *                                  the message Destination or receiver
 *                                  endpoint information
 */
protected void checkEndpointURI(SAMLMessageContext messageContext) 
        throws SecurityException, MessageDecodingException {
    
    log.debug("Checking SAML message intended destination endpoint against receiver endpoint");
    
    String messageDestination = 
        DatatypeHelper.safeTrimOrNullString(getIntendedDestinationEndpointURI(messageContext));
    
    boolean bindingRequires = isIntendedDestinationEndpointURIRequired(messageContext);
    
    if (messageDestination == null) {
        if (bindingRequires) {
            log.error("SAML message intended destination endpoint URI required by binding was empty");
            throw new SecurityException("SAML message intended destination (required by binding) was not present");
        } else {
            log.debug("SAML message intended destination endpoint in message was empty, not required by binding, skipping");
            return;
        }
    }
    
    String receiverEndpoint = DatatypeHelper.safeTrimOrNullString(getActualReceiverEndpointURI(messageContext));
    
    log.debug("Intended message destination endpoint: {}", messageDestination);
    log.debug("Actual message receiver endpoint: {}", receiverEndpoint);
    
    boolean matched = compareEndpointURIs(messageDestination, receiverEndpoint);
    if (!matched) {
        log.error("SAML message intended destination endpoint '{}' did not match the recipient endpoint '{}'",
                messageDestination, receiverEndpoint);
        throw new SecurityException("SAML message intended destination endpoint did not match recipient endpoint");
    } else {
        log.debug("SAML message intended destination endpoint matched recipient endpoint");
    }
}
 
Example #30
Source File: HTTPArtifactDecoder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Decodes the TARGET parameter and adds it to the message context.
 * 
 * @param samlMsgCtx current message context
 * 
 * @throws MessageDecodingException thrown if there is a problem decoding the TARGET parameter.
 */
protected void decodeTarget(SAMLMessageContext samlMsgCtx) throws MessageDecodingException {
    HTTPInTransport inTransport = (HTTPInTransport) samlMsgCtx.getInboundMessageTransport();

    String target = DatatypeHelper.safeTrim(inTransport.getParameterValue("TARGET"));
    if (target == null) {
        log.error("URL TARGET parameter was missing or did not contain a value.");
        throw new MessageDecodingException("URL TARGET parameter was missing or did not contain a value.");
    }
    samlMsgCtx.setRelayState(target);
}