org.opensaml.ws.security.SecurityPolicyException Java Examples

The following examples show how to use org.opensaml.ws.security.SecurityPolicyException. 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: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the raw request parameters and build a string representation of
 * the content that was signed.
 *
 * @param queryString the raw HTTP query string from the request
 * @return a string representation of the signed content
 * @throws SecurityPolicyException thrown if there is an error during request processing
 */
private static String buildSignedContentString(String queryString) throws SecurityPolicyException {
    StringBuilder builder = new StringBuilder();

    // One of these two is mandatory
    if (!appendParameter(builder, queryString, "SAMLRequest") && !appendParameter(builder, queryString, "SAMLResponse")) {
        throw new SecurityPolicyException(
                "Extract of SAMLRequest or SAMLResponse from query string failed");
    }
    // This is optional
    appendParameter(builder, queryString, "RelayState");
    // This is mandatory, but has already been checked in superclass
    appendParameter(builder, queryString, "SigAlg");

    return builder.toString();
}
 
Example #2
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the signature value from the request, in the form suitable for
 * input into
 * {@link SignatureTrustEngine#validate(byte[], byte[], String, CriteriaSet, Credential)}
 * .
 * <p/>
 * Defaults to the Base64-decoded value of the HTTP request parameter named
 * <code>Signature</code>.
 *
 * @param queryString
 * @return
 * @throws SecurityPolicyException
 * @throws IdentitySAML2SSOException
 */
protected static byte[] getSignature(String queryString) throws SecurityPolicyException {
    String signatureQueryParam = HTTPTransportUtils.getRawQueryStringParameter(queryString, "Signature");
    if (DatatypeHelper.isEmpty(signatureQueryParam)) {
        throw new SecurityPolicyException("Could not extract the Signature from query string");
    }
    String signature = null;
    try {
        /* Split 'Signature=<sig_value>' query param using '=' as the delimiter,
    and get the Signature value */
        signature = URLDecoder.decode(signatureQueryParam.split("=")[1], "UTF-8");
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Encoding not supported.", e);
        }
        // JVM is required to support UTF-8
        return new byte[0];
    }
    return Base64.decode(signature);
}
 
Example #3
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param queryString
 * @return
 * @throws SecurityPolicyException
 * @throws IdentitySAML2SSOException
 */
private static String getSigAlg(String queryString) throws SecurityPolicyException {
    String sigAlgQueryParam = HTTPTransportUtils.getRawQueryStringParameter(queryString, "SigAlg");
    if (DatatypeHelper.isEmpty(sigAlgQueryParam)) {
        throw new SecurityPolicyException(
                "Could not extract Signature Algorithm from query string");
    }
    String sigAlg = null;
    try {
        /* Split 'SigAlg=<sigalg_value>' query param using '=' as the delimiter,
        and get the Signature Algorithm */
        sigAlg = URLDecoder.decode(sigAlgQueryParam.split("=")[1], "UTF-8");
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Encoding not supported.", e);
        }
        // JVM is required to support UTF-8
        return null;
    }
    return sigAlg;
}
 
Example #4
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 #5
Source File: SignatureSecurityPolicyRule.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
private void checkMessageSignature(MessageContext messageContext,SignableSAMLObject samlMessage) throws SecurityPolicyException {
	CriteriaSet criteriaSet = new CriteriaSet();
	logger.debug("Inbound issuer is {}", messageContext.getInboundMessageIssuer());
	// System.out.println("Inbound issuer is {} "+ messageContext.getInboundMessageIssuer());
	//https://localhost-dev-ed.my.salesforce.com
	criteriaSet.add( new EntityIDCriteria(messageContext.getInboundMessageIssuer()));	
	//criteriaSet.add( new EntityIDCriteria("https://localhost-dev-ed.my.salesforce.com"));
	criteriaSet.add( new UsageCriteria(UsageType.SIGNING) );

	try {
		if (!trustEngine.validate( samlMessage.getSignature(), criteriaSet)) {
			throw new SecurityPolicyException("Signature was either invalid or signing key could not be established as trusted");
		}
	} catch (SecurityException se) {
		// System.out.println("Error evaluating the signature"+se.toString());
		throw new SecurityPolicyException("Error evaluating the signature",se);
	}
}
 
Example #6
Source File: SignatureSecurityPolicyRule.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
@Override
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {
	
	logger.debug("evaluating signature of {}", messageContext);
	
	if(!( messageContext.getInboundMessage() instanceof SignableSAMLObject)) {
		throw new SecurityPolicyException("Inbound Message is not a SignableSAMLObject");
	}
	
	SignableSAMLObject samlMessage = (SignableSAMLObject) messageContext.getInboundMessage();
	//TODO:POST NEED Signed,but some is not
	if( !samlMessage.isSigned()) {
		logger.debug("evaluating signature POST NEED Signed,but some is not.");
		throw new SecurityPolicyException("InboundMessage was not signed.");
	}
			
	checkSignatureProfile(samlMessage);

	checkMessageSignature(messageContext, samlMessage);

}
 
Example #7
Source File: SAML2HTTPRedirectDeflateSignatureRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract the raw request parameters and build a string representation of the content that was signed.
 * 
 * @param queryString the raw HTTP query string from the request
 * @return a string representation of the signed content
 * @throws SecurityPolicyException thrown if there is an error during request processing
 */
private String buildSignedContentString(String queryString) throws SecurityPolicyException {
    StringBuilder builder = new StringBuilder();

    // One of these two is mandatory
    if (!appendParameter(builder, queryString, "SAMLRequest")) {
        if (!appendParameter(builder, queryString, "SAMLResponse")) {
            log.warn("Could not extract either a SAMLRequest or a SAMLResponse from the query string");
            throw new SecurityPolicyException("Extract of SAMLRequest or SAMLResponse from query string failed");
        }
    }
    // This is optional
    appendParameter(builder, queryString, "RelayState");
    // This is mandatory, but has already been checked in superclass
    appendParameter(builder, queryString, "SigAlg");

    return builder.toString();
}
 
Example #8
Source File: SAML2HTTPRedirectDeflateSignatureRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected byte[] getSignedContent(HttpServletRequest request) throws SecurityPolicyException {
    // We need the raw non-URL-decoded query string param values for HTTP-Redirect DEFLATE simple signature
    // validation.
    // We have to construct a string containing the signature input by accessing the
    // request directly. We can't use the decoded parameters because we need the raw
    // data and URL-encoding isn't canonical.
    String queryString = request.getQueryString();
    log.debug("Constructing signed content string from URL query string {}", queryString);

    String constructed = buildSignedContentString(queryString);
    if (DatatypeHelper.isEmpty(constructed)) {
        log.warn("Could not extract signed content string from query string");
        return null;
    }
    log.debug("Constructed signed content string for HTTP-Redirect DEFLATE {}", constructed);

    try {
        return constructed.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        // JVM is required to support UTF-8
    }
    return null;
}
 
Example #9
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Evaluate the presenter entity ID as derived from the cert subject DN.
 * 
 * @param requestCredential the X509Credential derived from the request
 * @param messageContext the message context being evaluated
 * @return a presenter entity ID which was successfully evaluated by the trust engine
 * @throws SecurityPolicyException thrown if there is error during processing
 */
protected String evaluateSubjectDN(X509Credential requestCredential, MessageContext messageContext)
        throws SecurityPolicyException {

    log.debug("Evaluating client cert by deriving presenter as cert subject DN");
    X509Certificate certificate = requestCredential.getEntityCertificate();
    String candidatePresenter = getSubjectName(certificate);
    if (candidatePresenter != null) {
        if (evaluate(requestCredential, candidatePresenter, messageContext)) {
            log.info("Authentication succeeded for presenter entity ID derived from subject DN {}",
                    candidatePresenter);
            return candidatePresenter;
        }
    }
    return null;
}
 
Example #10
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 #11
Source File: BaseSAMLXMLSignatureSecurityPolicyRule.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 = 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 #12
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 #13
Source File: BaseSAMLSimpleSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Validate the simple signature.
 * 
 * @param signature the signature value
 * @param signedContent the content that was signed
 * @param algorithmURI the signature algorithm URI which was used to sign the content
 * @param criteriaSet criteria used to describe and/or resolve the information which serves as the basis for trust
 *            evaluation
 * @param candidateCredentials the request-derived candidate credential(s) containing the validation key for the
 *            signature (optional)
 * @return true if signature can be verified successfully, false otherwise
 * 
 * @throws SecurityPolicyException thrown if there are errors during the signature validation process
 * 
 */
protected boolean validateSignature(byte[] signature, byte[] signedContent, String algorithmURI,
        CriteriaSet criteriaSet, List<Credential> candidateCredentials) throws SecurityPolicyException {

    SignatureTrustEngine engine = getTrustEngine();

    // Some bindings allow candidate signing credentials to be supplied (e.g. via ds:KeyInfo), some do not.
    // So have 2 slightly different cases.
    try {
        if (candidateCredentials == null || candidateCredentials.isEmpty()) {
            if (engine.validate(signature, signedContent, algorithmURI, criteriaSet, null)) {
                log.debug("Simple signature validation (with no request-derived credentials) was successful");
                return true;
            } else {
                log.warn("Simple signature validation (with no request-derived credentials) failed");
                return false;
            }
        } else {
            for (Credential cred : candidateCredentials) {
                if (engine.validate(signature, signedContent, algorithmURI, criteriaSet, cred)) {
                    log.debug("Simple signature validation succeeded with a request-derived credential");
                    return true;
                }
            }
            log.warn("Signature validation using request-derived credentials failed");
            return false;
        }
    } catch (SecurityException e) {
        log.warn("There was an error evaluating the request's simple signature using the trust engine", e);
        throw new SecurityPolicyException("Error during trust engine evaluation of the simple signature", e);
    }
}
 
Example #14
Source File: HTTPRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {

    if (!(messageContext.getInboundMessageTransport() instanceof HTTPTransport)) {
        log.debug("Message context was did not contain an HTTP transport, unable to evaluate security rule");
        return;
    }

    doEvaluate(messageContext);
}
 
Example #15
Source File: IssueInstantRule.java    From lams with GNU General Public License v2.0 5 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;

    if (samlMsgCtx.getInboundSAMLMessageIssueInstant() == null) {
        if(requiredRule){
            log.warn("Inbound SAML message issue instant not present in message context");
            throw new SecurityPolicyException("Inbound SAML message issue instant not present in message context");
        }else{
            return;
        }
    }

    DateTime issueInstant = samlMsgCtx.getInboundSAMLMessageIssueInstant();
    DateTime now = new DateTime();
    DateTime latestValid = now.plusSeconds(clockSkew);
    DateTime expiration = issueInstant.plusSeconds(clockSkew + expires);

    // Check message wasn't issued in the future
    if (issueInstant.isAfter(latestValid)) {
        log.warn("Message was not yet valid: message time was {}, latest valid is: {}", issueInstant, latestValid);
        throw new SecurityPolicyException("Message was rejected because was issued in the future");
    }

    // Check message has not expired
    if (expiration.isBefore(now)) {
        log.warn("Message was expired: message issue time was '" + issueInstant + "', message expired at: '"
                + expiration + "', current time: '" + now + "'");
        throw new SecurityPolicyException("Message was rejected due to issue instant expiration");
    }

}
 
Example #16
Source File: MessageReplayRule.java    From lams with GNU General Public License v2.0 5 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;

    String messageIsuer = DatatypeHelper.safeTrimOrNullString(samlMsgCtx.getInboundMessageIssuer());
    if (messageIsuer == null) {
        if (requiredRule) {
            log.warn("Message contained no Issuer ID, replay check not possible");
            throw new SecurityPolicyException("Message contained no Issuer ID, replay check not possible");
        }
        return;
    }

    String messageId = DatatypeHelper.safeTrimOrNullString(samlMsgCtx.getInboundSAMLMessageId());
    if (messageId == null) {
        if (requiredRule) {
            log.warn("Message contained no ID, replay check not possible");
            throw new SecurityPolicyException("SAML message from issuer " + messageIsuer + " did not contain an ID");
        }
        return;
    }

    if (replayCache.isReplay(messageIsuer, messageId)) {
        log.warn("Replay detected of message '" + messageId + "' from issuer " + messageIsuer);
        throw new SecurityPolicyException("Rejecting replayed message ID '" + messageId + "' from issuer "
                + messageIsuer);
    }

}
 
Example #17
Source File: SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform cryptographic validation and trust evaluation on the Signature token using the configured Signature trust
 * engine.
 * 
 * @param signature the signature which is being evaluated
 * @param signableObject the signable object which contained the signature
 * @param samlMsgCtx the SAML message context being processed
 * @throws SecurityPolicyException thrown if the signature fails validation
 */
protected void doEvaluate(Signature signature, SignableSAMLObject signableObject, SAMLMessageContext samlMsgCtx)
        throws SecurityPolicyException {

    String contextIssuer = samlMsgCtx.getInboundMessageIssuer();
    if (contextIssuer != null) {
        String msgType = signableObject.getElementQName().toString();
        log.debug("Attempting to verify signature on signed SAML protocol message using context issuer message type: {}",
                        msgType);

        if (evaluate(signature, contextIssuer, samlMsgCtx)) {
            log.info("Validation of protocol message signature succeeded, message type: {}", msgType);
            if (!samlMsgCtx.isInboundSAMLMessageAuthenticated()) {
                log.debug("Authentication via protocol message signature succeeded for context issuer entity ID {}",
                        contextIssuer);
                samlMsgCtx.setInboundSAMLMessageAuthenticated(true);
            }
        } else {
            log.debug("Validation of protocol message signature failed for context issuer '" + contextIssuer
                    + "', message type: " + msgType);
            throw new SecurityPolicyException("Validation of protocol message signature failed");
        }
    } else {
        log.debug("Context issuer unavailable, can not attempt SAML protocol message signature validation");
        throw new SecurityPolicyException("Context issuer unavailable, can not validate signature");
    }
}
 
Example #18
Source File: SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform pre-validation on the Signature token.
 * 
 * @param signature the signature to evaluate
 * @throws SecurityPolicyException thrown if the signature element fails pre-validation
 */
protected void performPreValidation(Signature signature) throws SecurityPolicyException {
    if (getSignaturePrevalidator() != null) {
        try {
            getSignaturePrevalidator().validate(signature);
        } catch (ValidationException e) {
            log.debug("Protocol message signature failed signature pre-validation", e);
            throw new SecurityPolicyException("Protocol message signature failed signature pre-validation", e);
        }
    }
}
 
Example #19
Source File: SignatureSecurityPolicyRule.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
private void checkSignatureProfile(SignableSAMLObject samlMessage)throws SecurityPolicyException {
	try {
		samlSignatureProfileValidator.validate(samlMessage.getSignature());
	} catch (ValidationException ve) {
	   
		throw new SecurityPolicyException("Signature did not conform to SAML Signature profile",ve);
	}
}
 
Example #20
Source File: SAML2HTTPRedirectDeflateSignatureValidator.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * @param queryString
 * @return
 * @throws SecurityPolicyException
 */
protected static byte[] getSignedContent(String queryString) throws SecurityPolicyException {
    // We need the raw non-URL-decoded query string param values for
    // HTTP-Redirect DEFLATE simple signature
    // validation.
    // We have to construct a string containing the signature input by
    // accessing the
    // request directly. We can't use the decoded parameters because we need
    // the raw
    // data and URL-encoding isn't canonical.
    if (log.isDebugEnabled()) {
        log.debug("Constructing signed content string from URL query string " + queryString);
    }
    String constructed = buildSignedContentString(queryString);
    if (DatatypeHelper.isEmpty(constructed)) {
        throw new SecurityPolicyException(
                "Could not extract signed content string from query string");
    }
    if (log.isDebugEnabled()) {
        log.debug("Constructed signed content string for HTTP-Redirect DEFLATE " + constructed);
    }
    try {
        return constructed.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        if (log.isDebugEnabled()) {
            log.debug("Encoding not supported.", e);
        }
        // JVM is required to support UTF-8
        return new byte[0];
    }
}
 
Example #21
Source File: BaseTrustEngineRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate the token against the specified criteria using the configured trust engine.
 * 
 * @param token the token to be evaluated
 * @param criteriaSet the set of criteria against which to evaluate the token
 * @return true if the token satisfies the criteria as determined by the trust engine, otherwise false
 * @throws SecurityPolicyException thrown if there is a fatal error during trust engine evaluation
 */
protected boolean evaluate(TokenType token, CriteriaSet criteriaSet) throws SecurityPolicyException {
    try {
        return getTrustEngine().validate(token, criteriaSet);
    } catch (SecurityException e) {
        log.error("There was an error evaluating the request's token using the trust engine", e);
        throw new SecurityPolicyException("Error during trust engine evaluation of the token", e);
    }
}
 
Example #22
Source File: BaseTrustEngineRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate the token using the configured trust engine against criteria built using
 * the specified candidate issuer entity ID and message context information.
 * 
 * @param token the token to be evaluated
 * @param entityID the candidate issuer entity ID which is being evaluated 
 * @param messageContext the message context which is being evaluated
 * @return true if the token satisfies the criteria as determined by the trust engine, otherwise false
 * @throws SecurityPolicyException thrown if there is a fatal error during trust engine evaluation
 */
protected boolean evaluate(TokenType token, String entityID, MessageContext messageContext)
    throws SecurityPolicyException {
    
    CriteriaSet criteriaSet = buildCriteriaSet(entityID, messageContext);
    if (criteriaSet == null) {
        log.error("Returned criteria set was null, can not perform trust engine evaluation of token");
        throw new SecurityPolicyException("Returned criteria set was null");
    }
    
    return evaluate(token, criteriaSet);
}
 
Example #23
Source File: MandatoryAuthenticatedMessageRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {
    if(!messageContext.isIssuerAuthenticated()) {
        log.error("Inbound message issuer was not authenticated.");
        throw new SecurityPolicyException("Inbound message issuer was not authenticated.");
    }
}
 
Example #24
Source File: HTTPRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if the transport is of the correct content type.
 * 
 * @param transport transport being evalauted
 * 
 * @throws SecurityPolicyException thrown if the content type was an unexpected value
 */
protected void evaluateContentType(HTTPTransport transport) throws SecurityPolicyException {
    String transportContentType = transport.getHeaderValue("Content-Type");
    if (requiredContentType != null && !transportContentType.startsWith(requiredContentType)) {
        log.error("Invalid content type, expected " + requiredContentType + " but was " + transportContentType);
        throw new SecurityPolicyException("Invalid content type, expected " + requiredContentType + " but was "
                + transportContentType);
    }
}
 
Example #25
Source File: HTTPRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if the transport is of the correct request method.
 * 
 * @param transport transport being evalauted
 * 
 * @throws SecurityPolicyException thrown if the request method was an unexpected value
 */
protected void evaluateRequestMethod(HTTPTransport transport) throws SecurityPolicyException {
    String transportMethod = transport.getHTTPMethod();
    if (requiredRequestMethod != null && !transportMethod.equalsIgnoreCase(requiredRequestMethod)) {
        log.error("Invalid request method, expected " + requiredRequestMethod + " but was " + transportMethod);
        throw new SecurityPolicyException("Invalid request method, expected " + requiredRequestMethod + " but was "
                + transportMethod);
    }
}
 
Example #26
Source File: MandatoryIssuerRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {

    if (DatatypeHelper.isEmpty(messageContext.getInboundMessageIssuer())) {
        log.error("Mandatory inbound message context issuer was not present");
        throw new SecurityPolicyException("Mandatory inbound message context issuer not present");
    }

}
 
Example #27
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void evaluate(MessageContext messageContext) throws SecurityPolicyException {

    Credential peerCredential = messageContext.getInboundMessageTransport().getPeerCredential();

    if (peerCredential == null) {
        log.info("Inbound message transport did not contain a peer credential, "
                + "skipping client certificate authentication");
        return;
    }
    if (!(peerCredential instanceof X509Credential)) {
        log.info("Inbound message transport did not contain an X509Credential, "
                + "skipping client certificate authentication");
        return;
    }

    X509Credential requestCredential = (X509Credential) peerCredential;
    if (log.isDebugEnabled()) {
        try {
            log.debug("Attempting to authenticate inbound connection that presented the certificate:");
            log.debug(Base64.encodeBytes(requestCredential.getEntityCertificate().getEncoded()));
        } catch (CertificateEncodingException e) {
            // do nothing
        }
    }
    doEvaluate(requestCredential, messageContext);
}
 
Example #28
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate the presenter entity ID as derived from the cert subject alternative names specified by types enumerated
 * in {@link CertificateNameOptions#getSubjectAltNames()}.
 * 
 * @param requestCredential the X509Credential derived from the request
 * @param messageContext the message context being evaluated
 * @return a presenter entity ID which was successfully evaluated by the trust engine
 * @throws SecurityPolicyException thrown if there is error during processing
 */
protected String evaluateSubjectAltNames(X509Credential requestCredential, MessageContext messageContext)
        throws SecurityPolicyException {

    log.debug("Evaluating client cert by deriving presenter from subject alt names");
    X509Certificate certificate = requestCredential.getEntityCertificate();
    for (Integer altNameType : certNameOptions.getSubjectAltNames()) {
        log.debug("Evaluating alt names of type: {}", altNameType.toString());
        List<String> altNames = getAltNames(certificate, altNameType);
        for (String altName : altNames) {
            if (evaluate(requestCredential, altName, messageContext)) {
                log.info("Authentication succeeded for presenter entity ID derived from subject alt name {}",
                        altName);
                return altName;
            }
        }
    }
    return null;
}
 
Example #29
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate the presenter entity ID as derived from the cert subject common name (CN).
 * 
 * Only the first CN value from the subject DN is evaluated.
 * 
 * @param requestCredential the X509Credential derived from the request
 * @param messageContext the message context being evaluated
 * @return a presenter entity ID which was successfully evaluated by the trust engine
 * @throws SecurityPolicyException thrown if there is error during processing
 */
protected String evaluateSubjectCommonName(X509Credential requestCredential, MessageContext messageContext)
        throws SecurityPolicyException {

    log.debug("Evaluating client cert by deriving presenter as cert CN");
    X509Certificate certificate = requestCredential.getEntityCertificate();
    String candidatePresenter = getCommonName(certificate);
    if (candidatePresenter != null) {
        if (evaluate(requestCredential, candidatePresenter, messageContext)) {
            log.info("Authentication succeeded for presenter entity ID derived from CN {}", candidatePresenter);
            return candidatePresenter;
        }
    }
    return null;
}
 
Example #30
Source File: ClientCertAuthRule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate candidate presenter entity ID's which may be derived from the request credential's entity certificate
 * according to the options supplied via {@link CertificateNameOptions}.
 * 
 * <p>
 * Configured certificate name types are derived as candidate presenter entity ID's and processed in the following
 * order:
 * <ol>
 * <li>The certificate subject DN string as serialized by the X500DNHandler obtained via
 * {@link CertificateNameOptions#getX500DNHandler()} and using the output format indicated by
 * {@link CertificateNameOptions#getX500SubjectDNFormat()}.</li>
 * <li>Subject alternative names of the types configured via {@link CertificateNameOptions#getSubjectAltNames()}.
 * Note that this is a LinkedHashSet, so the order of evaluation is the order of insertion.</li>
 * <li>The first common name (CN) value appearing in the certificate subject DN.</li>
 * </ol>
 * </p>
 * 
 * <p>
 * The first one of the above which is successfully evaluated by the trust engine using criteria built from
 * {@link BaseTrustEngineRule#buildCriteriaSet(String, MessageContext)} will be returned.
 * </p>
 * 
 * @param requestCredential the X509Credential derived from the request
 * @param messageContext the message context being evaluated
 * @return a certificate presenter entity ID which was successfully evaluated by the trust engine
 * @throws SecurityPolicyException thrown if there is error during processing
 */
protected String evaluateCertificateNameDerivedPresenters(X509Credential requestCredential,
        MessageContext messageContext) throws SecurityPolicyException {

    String candidatePresenter = null;

    if (certNameOptions.evaluateSubjectDN()) {
        candidatePresenter = evaluateSubjectDN(requestCredential, messageContext);
        if (candidatePresenter != null) {
            return candidatePresenter;
        }
    }

    if (!certNameOptions.getSubjectAltNames().isEmpty()) {
        candidatePresenter = evaluateSubjectAltNames(requestCredential, messageContext);
        if (candidatePresenter != null) {
            return candidatePresenter;
        }
    }

    if (certNameOptions.evaluateSubjectCommonName()) {
        candidatePresenter = evaluateSubjectCommonName(requestCredential, messageContext);
        if (candidatePresenter != null) {
            return candidatePresenter;
        }
    }

    return null;
}