org.opensaml.xml.signature.Signature Java Examples

The following examples show how to use org.opensaml.xml.signature.Signature. 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 Project: carbon-identity   Author: wso2-attic   File: SSOAgentUtils.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * Sign the SAML AuthnRequest message
 *
 * @param logoutRequest
 * @param signatureAlgorithm
 * @param cred
 * @return
 * @throws SSOAgentException
 */
public static LogoutRequest setSignature(LogoutRequest logoutRequest, String signatureAlgorithm,
                                         X509Credential cred) throws SSOAgentException {
    try {
        Signature signature = setSignatureRaw(signatureAlgorithm,cred);

        logoutRequest.setSignature(signature);

        List<Signature> signatureList = new ArrayList<Signature>();
        signatureList.add(signature);

        // Marshall and Sign
        MarshallerFactory marshallerFactory =
                org.opensaml.xml.Configuration.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(logoutRequest);

        marshaller.marshall(logoutRequest);

        org.apache.xml.security.Init.init();
        Signer.signObjects(signatureList);
        return logoutRequest;

    } catch (Exception e) {
        throw new SSOAgentException("Error while signing the Logout Request message", e);
    }
}
 
Example #2
Source Project: lams   Author: lamsfoundation   File: AssertionUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {

    Assertion assertion = (Assertion) parentSAMLObject;

    if (childSAMLObject instanceof Signature) {
        assertion.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Conditions) {
        assertion.setConditions((Conditions) childSAMLObject);
    } else if (childSAMLObject instanceof Advice) {
        assertion.setAdvice((Advice) childSAMLObject);
    } else if (childSAMLObject instanceof Statement) {
        assertion.getStatements().add((Statement) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java    License: 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 #4
Source Project: lams   Author: lamsfoundation   File: RoleDescriptorUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    RoleDescriptor roleDescriptor = (RoleDescriptor) parentSAMLObject;

    if (childSAMLObject instanceof Extensions) {
        roleDescriptor.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        roleDescriptor.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof KeyDescriptor) {
        roleDescriptor.getKeyDescriptors().add((KeyDescriptor) childSAMLObject);
    } else if (childSAMLObject instanceof Organization) {
        roleDescriptor.setOrganization((Organization) childSAMLObject);
    } else if (childSAMLObject instanceof ContactPerson) {
        roleDescriptor.getContactPersons().add((ContactPerson) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #5
Source Project: lams   Author: lamsfoundation   File: AffiliationDescriptorUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    AffiliationDescriptor descriptor = (AffiliationDescriptor) parentSAMLObject;

    if (childSAMLObject instanceof Extensions) {
        descriptor.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        descriptor.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof AffiliateMember) {
        descriptor.getMembers().add((AffiliateMember) childSAMLObject);
    } else if (childSAMLObject instanceof KeyDescriptor) {
        descriptor.getKeyDescriptors().add((KeyDescriptor) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #6
Source Project: lams   Author: lamsfoundation   File: EntityDescriptorUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    EntityDescriptor entityDescriptor = (EntityDescriptor) parentSAMLObject;

    if (childSAMLObject instanceof Extensions) {
        entityDescriptor.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        entityDescriptor.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof RoleDescriptor) {
        entityDescriptor.getRoleDescriptors().add((RoleDescriptor) childSAMLObject);
    } else if (childSAMLObject instanceof AffiliationDescriptor) {
        entityDescriptor.setAffiliationDescriptor((AffiliationDescriptor) childSAMLObject);
    } else if (childSAMLObject instanceof Organization) {
        entityDescriptor.setOrganization((Organization) childSAMLObject);
    } else if (childSAMLObject instanceof ContactPerson) {
        entityDescriptor.getContactPersons().add((ContactPerson) childSAMLObject);
    } else if (childSAMLObject instanceof AdditionalMetadataLocation) {
        entityDescriptor.getAdditionalMetadataLocations().add((AdditionalMetadataLocation) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: EntitiesDescriptorUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) parentSAMLObject;

    if (childSAMLObject instanceof Extensions) {
        entitiesDescriptor.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof EntitiesDescriptor) {
        entitiesDescriptor.getEntitiesDescriptors().add((EntitiesDescriptor) childSAMLObject);
    } else if (childSAMLObject instanceof EntityDescriptor) {
        entitiesDescriptor.getEntityDescriptors().add((EntityDescriptor) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        entitiesDescriptor.setSignature((Signature) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #8
Source Project: lams   Author: lamsfoundation   File: AssertionUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException {
    Assertion assertion = (Assertion) parentObject;

    if (childObject instanceof Issuer) {
        assertion.setIssuer((Issuer) childObject);
    } else if (childObject instanceof Signature) {
        assertion.setSignature((Signature) childObject);
    } else if (childObject instanceof Subject) {
        assertion.setSubject((Subject) childObject);
    } else if (childObject instanceof Conditions) {
        assertion.setConditions((Conditions) childObject);
    } else if (childObject instanceof Advice) {
        assertion.setAdvice((Advice) childObject);
    } else if (childObject instanceof Statement) {
        assertion.getStatements().add((Statement) childObject);
    } else {
        super.processChildElement(parentObject, childObject);
    }
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: ArtifactResponseUnmarshaller.java    License: 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 #10
Source Project: lams   Author: lamsfoundation   File: StatusResponseTypeUnmarshaller.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    StatusResponseType sr = (StatusResponseType) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        sr.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        sr.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        sr.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Status) {
        sr.setStatus((Status) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #11
Source Project: carbon-identity   Author: wso2-attic   File: SAML2TokenBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setSignature(String signatureAlgorithm, X509Credential cred) throws IdentityProviderException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        String value = Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
    } catch (CertificateEncodingException e) {
        log.error("Failed to get encoded certificate", e);
        throw new IdentityProviderException("Error while getting encoded certificate");
    }

    assertion.setSignature(signature);
    signatureList.add(signature);
}
 
Example #12
Source Project: carbon-identity   Author: wso2-attic   File: SAML1TokenBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setSignature(String signatureAlgorithm, X509Credential cred) throws IdentityProviderException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        X509Certificate cert = (X509Certificate) buildXMLObject(X509Certificate.DEFAULT_ELEMENT_NAME);
        String value = Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
    } catch (CertificateEncodingException e) {
        log.error("Error while getting the encoded certificate", e);
        throw new IdentityProviderException("Error while getting the encoded certificate");
    }

    assertion.setSignature(signature);
    signatureList.add(signature);
}
 
Example #13
Source Project: carbon-identity   Author: wso2-attic   File: SSOAgentUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static Signature setSignatureRaw(String signatureAlgorithm, X509Credential cred) throws SSOAgentException {
    Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
    signature.setSigningCredential(cred);
    signature.setSignatureAlgorithm(signatureAlgorithm);
    signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    try {
        KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
        X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
        org.opensaml.xml.signature.X509Certificate cert =
                (org.opensaml.xml.signature.X509Certificate) buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
        String value =
                org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
        cert.setValue(value);
        data.getX509Certificates().add(cert);
        keyInfo.getX509Datas().add(data);
        signature.setKeyInfo(keyInfo);
        return signature;

    } catch (CertificateEncodingException e) {
        throw new SSOAgentException("Error getting certificate", e);
    }
}
 
Example #14
Source Project: carbon-identity   Author: wso2-attic   File: SSOAgentUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void addDeflateSignatureToHTTPQueryString(StringBuilder httpQueryString,
                                                        X509Credential cred) throws SSOAgentException {
    doBootstrap();
    try {
        httpQueryString.append("&SigAlg="
                + URLEncoder.encode(XMLSignature.ALGO_ID_SIGNATURE_RSA, "UTF-8").trim());

        java.security.Signature signature = java.security.Signature.getInstance("SHA1withRSA");
        signature.initSign(cred.getPrivateKey());
        signature.update(httpQueryString.toString().getBytes(Charset.forName("UTF-8")));
        byte[] signatureByteArray = signature.sign();

        String signatureBase64encodedString = Base64.encodeBytes(signatureByteArray,
                Base64.DONT_BREAK_LINES);
        httpQueryString.append("&Signature="
                + URLEncoder.encode(signatureBase64encodedString, "UTF-8").trim());
    } catch (Exception e) {
        throw new SSOAgentException("Error applying SAML2 Redirect Binding signature", e);
    }
}
 
Example #15
Source Project: secure-data-service   Author: inbloom   File: SamlHelper.java    License: Apache License 2.0 6 votes vote down vote up
public Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry) {
    Signature signature = (Signature) Configuration.getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME)
            .buildObject(Signature.DEFAULT_ELEMENT_NAME);

    Credential signingCredential = initializeCredentialsFromKeystore(keystoreEntry);
    signature.setSigningCredential(signingCredential);

    signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);

    SecurityConfiguration secConfig = Configuration.getGlobalSecurityConfiguration();
    try {
        SecurityHelper.prepareSignatureParams(signature, signingCredential, secConfig, null);
    } catch (org.opensaml.xml.security.SecurityException  ex) {
        LOG.error("Error composing artifact resolution request: Failed to generate digital signature");
        throw new IllegalArgumentException("Couldn't compose artifact resolution request", ex);
    }

    return signature;
}
 
Example #16
Source Project: micro-integrator   Author: wso2   File: WSXACMLEntitlementServiceClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check the validity of the Signature
 *
 * @param signature : XML Signature that authenticates the assertion
 * @return whether the signature is valid
 * @throws Exception
 */
private boolean validateSignature(Signature signature) throws EntitlementProxyException {

    boolean isSignatureValid = false;

    try {
        SignatureValidator validator = new SignatureValidator(getPublicX509CredentialImpl());
        validator.validate(signature);
        isSignatureValid = true;
    } catch (ValidationException e) {
        log.warn("Signature validation failed.", e);
    }

    return isSignatureValid;
}
 
Example #17
Source Project: lams   Author: lamsfoundation   File: ExplicitKeySignatureTrustEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(Signature signature, CriteriaSet trustBasisCriteria) throws SecurityException {

    checkParams(signature, trustBasisCriteria);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.addAll(trustBasisCriteria);
    if (!criteriaSet.contains(UsageCriteria.class)) {
        criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    }
    String jcaAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(signature.getSignatureAlgorithm());
    if (!DatatypeHelper.isEmpty(jcaAlgorithm)) {
        criteriaSet.add(new KeyAlgorithmCriteria(jcaAlgorithm), true);
    }

    Iterable<Credential> trustedCredentials = getCredentialResolver().resolve(criteriaSet);

    if (validate(signature, trustedCredentials)) {
        return true;
    }

    // If the credentials extracted from Signature's KeyInfo (if any) did not verify the
    // signature and/or establish trust, as a fall back attempt to verify the signature with
    // the trusted credentials directly.
    log.debug("Attempting to verify signature using trusted credentials");

    for (Credential trustedCredential : trustedCredentials) {
        if (verifySignature(signature, trustedCredential)) {
            log.debug("Successfully verified signature using resolved trusted credential");
            return true;
        }
    }
    log.debug("Failed to verify signature using either KeyInfo-derived or directly trusted credentials");
    return false;
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: SignatureUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public Signature unmarshall(Element signatureElement) throws UnmarshallingException {
    log.debug("Starting to unmarshall Apache XML-Security-based SignatureImpl element");

    SignatureImpl signature = new SignatureImpl(signatureElement.getNamespaceURI(),
            signatureElement.getLocalName(), signatureElement.getPrefix());

    try {
        log.debug("Constructing Apache XMLSignature object");

        XMLSignature xmlSignature = new XMLSignature(signatureElement, "");

        SignedInfo signedInfo = xmlSignature.getSignedInfo();

        log.debug("Adding canonicalization and signing algorithms, and HMAC output length to Signature");
        signature.setCanonicalizationAlgorithm(signedInfo.getCanonicalizationMethodURI());
        signature.setSignatureAlgorithm(signedInfo.getSignatureMethodURI());
        signature.setHMACOutputLength(getHMACOutputLengthValue(signedInfo.getSignatureMethodElement()));

        org.apache.xml.security.keys.KeyInfo xmlSecKeyInfo = xmlSignature.getKeyInfo();
        if (xmlSecKeyInfo != null) {
            log.debug("Adding KeyInfo to Signature");
            Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(
                    xmlSecKeyInfo.getElement());
            KeyInfo keyInfo = (KeyInfo) unmarshaller.unmarshall(xmlSecKeyInfo.getElement());
            signature.setKeyInfo(keyInfo);
        }
        signature.setXMLSignature(xmlSignature);
        signature.setDOM(signatureElement);
        return signature;
    } catch (XMLSecurityException e) {
        log.error("Error constructing Apache XMLSignature instance from Signature element: {}", e.getMessage());
        throw new UnmarshallingException("Unable to unmarshall Signature with Apache XMLSignature", e);
    }
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: BaseSignatureTrustEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempt to establish trust by resolving signature verification credentials from the Signature's KeyInfo. If any
 * credentials so resolved correctly verify the signature, attempt to establish trust using subclass-specific trust
 * logic against trusted information as implemented in {@link #evaluateTrust(Credential, Object)}.
 * 
 * @param signature the Signature to evaluate
 * @param trustBasis the information which serves as the basis for trust evaluation
 * @return true if the signature is verified by any KeyInfo-derived credential which can be established as trusted,
 *         otherwise false
 * @throws SecurityException if an error occurs during signature verification or trust processing
 */
protected boolean validate(Signature signature, TrustBasisType trustBasis) throws SecurityException {

    log.debug("Attempting to verify signature and establish trust using KeyInfo-derived credentials");

    if (signature.getKeyInfo() != null) {

        KeyInfoCriteria keyInfoCriteria = new KeyInfoCriteria(signature.getKeyInfo());
        CriteriaSet keyInfoCriteriaSet = new CriteriaSet(keyInfoCriteria);

        for (Credential kiCred : getKeyInfoResolver().resolve(keyInfoCriteriaSet)) {
            if (verifySignature(signature, kiCred)) {
                log.debug("Successfully verified signature using KeyInfo-derived credential");
                log.debug("Attempting to establish trust of KeyInfo-derived credential");
                if (evaluateTrust(kiCred, trustBasis)) {
                    log.debug("Successfully established trust of KeyInfo-derived credential");
                    return true;
                } else {
                    log.debug("Failed to establish trust of KeyInfo-derived credential");
                }
            }
        }
    } else {
        log.debug("Signature contained no KeyInfo element, could not resolve verification credentials");
    }

    log.debug("Failed to verify signature and/or establish trust using any KeyInfo-derived credentials");
    return false;
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: BaseSignatureTrustEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Attempt to verify a signature using the key from the supplied credential.
 * 
 * @param signature the signature on which to attempt verification
 * @param credential the credential containing the candidate validation key
 * @return true if the signature can be verified using the key from the credential, otherwise false
 */
protected boolean verifySignature(Signature signature, Credential credential) {
    SignatureValidator validator = new SignatureValidator(credential);
    try {
        validator.validate(signature);
    } catch (ValidationException e) {
        log.debug("Signature validation using candidate validation credential failed", e);
        return false;
    }
    
    log.debug("Signature validation using candidate credential was successful");
    return true;
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: BaseSignatureTrustEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check the signature and credential criteria for required values.
 * 
 * @param signature the signature to be evaluated
 * @param trustBasisCriteria the set of trusted credential criteria
 * @throws SecurityException thrown if required values are absent or otherwise invalid
 */
protected void checkParams(Signature signature, CriteriaSet trustBasisCriteria) throws SecurityException {

    if (signature == null) {
        throw new SecurityException("Signature was null");
    }
    if (trustBasisCriteria == null) {
        throw new SecurityException("Trust basis criteria set was null");
    }
    if (trustBasisCriteria.isEmpty()) {
        throw new SecurityException("Trust basis criteria set was empty");
    }
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: ChainingSignatureTrustEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(Signature token, CriteriaSet trustBasisCriteria) throws SecurityException {
    for (SignatureTrustEngine engine : engines) {
        if (engine.validate(token, trustBasisCriteria)) {
            log.debug("Signature was trusted by chain member: {}", engine.getClass().getName());
            return true;
        }
    }
    return false;
}
 
Example #23
Source Project: lams   Author: lamsfoundation   File: PKIXSignatureTrustEngine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public boolean validate(Signature signature, CriteriaSet trustBasisCriteria) throws SecurityException {

    checkParams(signature, trustBasisCriteria);

    Pair<Set<String>, Iterable<PKIXValidationInformation>> validationPair  = 
        resolveValidationInfo(trustBasisCriteria);

    if (validate(signature, validationPair)) {
        return true;
    }

    log.debug("PKIX validation of signature failed, unable to resolve valid and trusted signing key");
    return false;
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: SAMLSignatureProfileValidator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
public void validate(Signature signature) throws ValidationException {

    if (!(signature instanceof SignatureImpl)) {
        log.info("Signature was not an instance of SignatureImpl, was {} validation not supported", signature
                .getClass().getName());
        return;
    }

    validateSignatureImpl((SignatureImpl) signature);
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: ResponseAbstractTypeUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    ResponseAbstractType response = (ResponseAbstractType) parentSAMLObject;

    if (childSAMLObject instanceof Signature) {
        response.setSignature((Signature) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #26
Source Project: lams   Author: lamsfoundation   File: RequestAbstractTypeUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    RequestAbstractType request = (RequestAbstractType) parentSAMLObject;

    if (childSAMLObject instanceof Signature) {
        request.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof RespondWith) {
        request.getRespondWiths().add((RespondWith) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java    License: 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 #28
Source Project: lams   Author: lamsfoundation   File: SAMLProtocolMessageXMLSignatureSecurityPolicyRule.java    License: 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 #29
Source Project: lams   Author: lamsfoundation   File: SignatureValidationFilter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param engine the trust engine used to validate signatures on incoming metadata.
 * @param signatureValidator optional pre-validator used to validate Signature elements prior to the actual
 *            cryptographic validation operation
 */
public SignatureValidationFilter(SignatureTrustEngine engine, Validator<Signature> signatureValidator) {
    if (engine == null) {
        throw new IllegalArgumentException("Signature trust engine may not be null");
    }

    signatureTrustEngine = engine;
    sigValidator = signatureValidator;
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: SignatureValidationFilter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Evaluate the signature on the signed metadata instance.
 * 
 * @param signedMetadata the metadata object whose signature is to be verified
 * @param metadataEntryName the EntityDescriptor entityID, EntitiesDescriptor Name,
 *                          AffiliationDescriptor affiliationOwnerID, 
 *                          or RoleDescriptor {@link #getRoleIDToken(String, RoleDescriptor)}
 *                          corresponding to the element whose signature is being evaluated.
 *                          This is used exclusively for logging/debugging purposes and
 *                          should not be used operationally (e.g. for building a criteria set).
 * @param isEntityGroup flag indicating whether the signed object is a metadata group (EntitiesDescriptor),
 *                      primarily useful for constructing a criteria set for the trust engine
 * @throws FilterException thrown if the metadata entry's signature can not be established as trusted,
 *                         or if an error occurs during the signature verification process
 */
protected void verifySignature(SignableXMLObject signedMetadata, String metadataEntryName, 
        boolean isEntityGroup) throws FilterException {
    
    log.debug("Verifying signature on metadata entry: {}", metadataEntryName);
    
    Signature signature = signedMetadata.getSignature();
    if (signature == null) {
        // We shouldn't ever be calling this on things that aren't actually signed, but just to be safe...
        log.warn("Signature was null, skipping processing on metadata entry: {}", metadataEntryName);
        return;
    }
    
    performPreValidation(signature, metadataEntryName);
    
    CriteriaSet criteriaSet = buildCriteriaSet(signedMetadata, metadataEntryName, isEntityGroup);
    
    try {
        if ( getSignatureTrustEngine().validate(signature, criteriaSet) ) {
            log.trace("Signature trust establishment succeeded for metadata entry {}", metadataEntryName);
            return;
        } else {
            log.error("Signature trust establishment failed for metadata entry {}", metadataEntryName);
            throw new FilterException("Signature trust establishment failed for metadata entry");
        }
    } catch (SecurityException e) {
        // Treat evaluation errors as fatal
        log.error("Error processing signature verification for metadata entry '{}': {} ",
                metadataEntryName, e.getMessage());
        throw new FilterException("Error processing signature verification for metadata entry", e);
    }
}