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 File: SSOAgentUtils.java    From carbon-identity with 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 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 #3
Source File: SAML2TokenBuilder.java    From carbon-identity with 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 #4
Source File: StatusResponseTypeUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    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 #5
Source File: ArtifactResponseUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    ArtifactResponse artifactResponse = (ArtifactResponse) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        artifactResponse.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        artifactResponse.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        artifactResponse.setExtensions((Extensions) childSAMLObject);
    } else if (childSAMLObject instanceof Status) {
        artifactResponse.setStatus((Status) childSAMLObject);
    } else {
        artifactResponse.setMessage((SAMLObject) childSAMLObject);
    }
}
 
Example #6
Source File: AssertionUnmarshaller.java    From lams with 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 #7
Source File: EntitiesDescriptorUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    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 File: EntityDescriptorUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    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 #9
Source File: AffiliationDescriptorUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    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 #10
Source File: RoleDescriptorUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    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 #11
Source File: SAML1TokenBuilder.java    From carbon-identity with 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 #12
Source File: SSOAgentUtils.java    From carbon-identity with 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 #13
Source File: SSOAgentUtils.java    From carbon-identity with 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 #14
Source File: SamlHelper.java    From secure-data-service with 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 #15
Source File: AssertionUnmarshaller.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {

    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 #16
Source File: SignatureValidationFilter.java    From lams with 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);
    }
}
 
Example #17
Source File: WSXACMLEntitlementServiceClient.java    From micro-integrator with 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 #18
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
private void validateSignatureFormat(Signature signature) {
    SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();

    try {
        profileValidator.validate(signature);
    } catch (ValidationException e) {
        handleSignatureValidationErrors(e);
    }
}
 
Example #19
Source File: RequestAbstractTypeUnmarshaller.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentSAMLObject, XMLObject childSAMLObject)
        throws UnmarshallingException {
    RequestAbstractType req = (RequestAbstractType) parentSAMLObject;

    if (childSAMLObject instanceof Issuer) {
        req.setIssuer((Issuer) childSAMLObject);
    } else if (childSAMLObject instanceof Signature) {
        req.setSignature((Signature) childSAMLObject);
    } else if (childSAMLObject instanceof Extensions) {
        req.setExtensions((Extensions) childSAMLObject);
    } else {
        super.processChildElement(parentSAMLObject, childSAMLObject);
    }
}
 
Example #20
Source File: SamlHelper.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
protected void validateFormatAndCertificate(Signature signature, org.w3c.dom.Element element, String issuer) {
    validateSignatureFormat(signature);

    try {
        if (!validator.isDocumentTrusted(element, issuer)) {
            throw new APIAccessDeniedException("Invalid SAML message: Certificate is not trusted");
        }
    } catch (Exception e) {
        // chg Jan 2014, rc - passing exception into error-handling allows it to make a better error message.
        handleSignatureValidationErrors(e);
    }
}
 
Example #21
Source File: ExplicitKeySignatureTrustEngine.java    From lams with 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 #22
Source File: SignatureUnmarshaller.java    From lams with 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 #23
Source File: BaseSignatureTrustEngine.java    From lams with 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 #24
Source File: BaseSignatureTrustEngine.java    From lams with 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 #25
Source File: BaseSignatureTrustEngine.java    From lams with 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 #26
Source File: WSXACMLEntitlementServiceClient.java    From carbon-identity with 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 #27
Source File: SSOAgentUtils.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Sign the SAML AuthnRequest message
 *
 * @param authnRequest
 * @param signatureAlgorithm
 * @param cred
 * @return
 * @throws org.wso2.carbon.identity.sso.agent.SSOAgentException
 */
public static AuthnRequest setSignature(AuthnRequest authnRequest, String signatureAlgorithm,
                                    X509Credential cred) throws SSOAgentException {
    doBootstrap();
    try {
        Signature signature = setSignatureRaw(signatureAlgorithm,cred);


        authnRequest.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(authnRequest);

        marshaller.marshall(authnRequest);

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

    } catch (Exception e) {
        throw new SSOAgentException("Error while signing the SAML Request message", e);
    }
}
 
Example #28
Source File: ChainingSignatureTrustEngine.java    From lams with 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 #29
Source File: SignatureValidationFilter.java    From lams with 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 File: PKIXSignatureTrustEngine.java    From lams with 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;
}