static void validateSignature(Credential validationCredential, SignableSAMLObject signableObj) { requireNonNull(validationCredential, "validationCredential"); requireNonNull(signableObj, "signableObj"); // Skip signature validation if the object is not signed. if (!signableObj.isSigned()) { return; } final Signature signature = signableObj.getSignature(); if (signature == null) { throw new SamlException("failed to validate a signature because no signature exists"); } try { signatureProfileValidator.validate(signature); SignatureValidator.validate(signature, validationCredential); } catch (SignatureException e) { throw new SamlException("failed to validate a signature", e); } }
/** * Signs the specified {@link SignableSAMLObject} with the specified {@link Credential} and * {@code signatureAlgorithm}. */ static void sign(SignableSAMLObject signableObj, Credential signingCredential, String signatureAlgorithm) { requireNonNull(signableObj, "signableObj"); requireNonNull(signingCredential, "signingCredential"); requireNonNull(signatureAlgorithm, "signatureAlgorithm"); final Signature signature = signatureBuilder.buildObject(); signature.setSignatureAlgorithm(signatureAlgorithm); signature.setSigningCredential(signingCredential); signature.setCanonicalizationAlgorithm(ALGO_ID_C14N_EXCL_OMIT_COMMENTS); try { signature.setKeyInfo(keyInfoGenerator.generate(signingCredential)); } catch (SecurityException e) { throw new SamlException("failed to create a key info of signing credential", e); } signableObj.setSignature(signature); serialize(signableObj); try { Signer.signObject(signature); } catch (SignatureException e) { throw new SamlException("failed to sign a SAML object", e); } }
/** * Validate the Reference URI and parent ID attribute values. * * The URI must either be null or empty (indicating that the entire enclosing document was signed), or else it must * be a local document fragment reference and point to the SAMLObject parent via the latter's ID attribute value. * * @param uri the Signature Reference URI attribute value * @param id the Signature parents ID attribute value * @throws SignatureException thrown if the URI or ID attribute values are invalid */ protected void validateReferenceURI(String uri, String id) throws SignatureException { if (!Strings.isNullOrEmpty(uri)) { if (!uri.startsWith("#")) { log.error("Signature Reference URI was not a document fragment reference: " + uri); throw new SignatureException("Signature Reference URI was not a document fragment reference"); } else if (Strings.isNullOrEmpty(id)) { log.error("SignableSAMLObject did not contain an ID attribute"); throw new SignatureException("SignableSAMLObject did not contain an ID attribute"); } else if (uri.length() < 2 || !id.equals(uri.substring(1))) { log.error("Reference URI '{}' did not point to SignableSAMLObject with ID '{}'", uri, id); throw new SignatureException("Reference URI did not point to parent ID"); } } }
validator.validate(signature); } catch (SignatureException ex) { LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity"); SignatureValidator.validate(signature, credential); } catch (SignatureException ex) { LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
signaturePrevalidator.validate(signature); } catch (SignatureException e) { String msg = String.format("Assertion Signature failed pre-validation: %s", e.getMessage()); log.warn(msg); context.setValidationFailureMessage(msg); if (trustEngine.validate(signature, criteriaSet)) { log.debug("Validation of signature of Assertion '{}' from Issuer '{}' was successful", token.getID(), tokenIssuer);
validator.validate(signature); } catch (SignatureException ex) { LOG.log(Level.FINE, "Error in validating the SAML Signature: " + ex.getMessage(), ex); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity"); new ApacheSantuarioSignatureValidationProviderImpl(); responseSignatureValidator.validate(signature, credential); } catch (SignatureException ex) { LOG.log(Level.FINE, "Error in validating the SAML Signature: " + ex.getMessage(), ex); throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
public void signObject(SignableSAMLObject signable, SimpleKey key, AlgorithmMethod algorithm, DigestMethod digest) { KeyStoreCredentialResolver resolver = getCredentialsResolver(key); Credential credential = getCredential(key, resolver); XMLObjectBuilder<org.opensaml.xmlsec.signature.Signature> signatureBuilder = (XMLObjectBuilder<org.opensaml.xmlsec.signature.Signature>) getBuilderFactory() .getBuilder(org.opensaml.xmlsec.signature.Signature.DEFAULT_ELEMENT_NAME); org.opensaml.xmlsec.signature.Signature signature = signatureBuilder.buildObject(org.opensaml.xmlsec .signature.Signature.DEFAULT_ELEMENT_NAME); signable.setSignature(signature); SignatureSigningParameters parameters = new SignatureSigningParameters(); parameters.setSigningCredential(credential); parameters.setKeyInfoGenerator(getKeyInfoGenerator(credential)); parameters.setSignatureAlgorithm(algorithm.toString()); parameters.setSignatureReferenceDigestMethod(digest.toString()); parameters.setSignatureCanonicalizationAlgorithm( CanonicalizationMethod.ALGO_ID_C14N_EXCL_OMIT_COMMENTS.toString() ); try { SignatureSupport.prepareSignatureParams(signature, parameters); Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(signable); marshaller.marshall(signable); Signer.signObject(signature); } catch (SecurityException | MarshallingException | SignatureException e) { throw new SamlKeyException(e); } }
/** * Validate the given digital signature by checking its profile and value. * * @param signature the signature * @param idpEntityId the idp entity id * @param trustEngine the trust engine */ protected final void validateSignature(final Signature signature, final String idpEntityId, final SignatureTrustEngine trustEngine) { final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator(); try { validator.validate(signature); } catch (final SignatureException e) { throw new SAMLSignatureValidationException("SAMLSignatureProfileValidator failed to validate signature", e); } final CriteriaSet criteriaSet = new CriteriaSet(); criteriaSet.add(new UsageCriterion(UsageType.SIGNING)); criteriaSet.add(new EntityRoleCriterion(IDPSSODescriptor.DEFAULT_ELEMENT_NAME)); criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS)); criteriaSet.add(new EntityIdCriterion(idpEntityId)); final boolean valid; try { valid = trustEngine.validate(signature, criteriaSet); } catch (final SecurityException e) { throw new SAMLSignatureValidationException("An error occurred during signature validation", e); } if (!valid) { throw new SAMLSignatureValidationException("Signature is not trusted"); } }
/** * Perform pre-validation on the Signature token. * * @param signature the signature to evaluate * @throws MessageHandlerException thrown if the signature element fails pre-validation */ protected void performPrevalidation(@Nonnull final Signature signature) throws MessageHandlerException { if (getSignaturePrevalidator() != null) { try { getSignaturePrevalidator().validate(signature); } catch (final SignatureException e) { log.debug("{} Protocol message signature failed signature pre-validation", getLogPrefix(), e); throw new MessageHandlerException("Protocol message signature failed signature pre-validation", e); } } }
/** * Signs the SAML message represented in the message context if it is a {@link SignableXMLObject} * and the message context contains signing parameters as determined * by {@link #getContextSigningParameters(MessageContext)}. * * @param messageContext current message context * * @throws SecurityException if there is a problem preparing the signature * @throws MarshallingException if there is a problem marshalling the SAMLObject * @throws SignatureException if there is a problem with the signature operation * */ public static void signMessage(@Nonnull final MessageContext<SAMLObject> messageContext) throws SecurityException, MarshallingException, SignatureException { Constraint.isNotNull(messageContext, "Message context cannot be null"); final SAMLObject outboundSAML = messageContext.getMessage(); final SignatureSigningParameters parameters = getContextSigningParameters(messageContext); if (outboundSAML instanceof SignableXMLObject && parameters != null) { SignatureSupport.signObject((SignableXMLObject) outboundSAML, parameters); } }
static void validateSignature(Credential validationCredential, SignableSAMLObject signableObj) { requireNonNull(validationCredential, "validationCredential"); requireNonNull(signableObj, "signableObj"); // Skip signature validation if the object is not signed. if (!signableObj.isSigned()) { return; } final Signature signature = signableObj.getSignature(); if (signature == null) { throw new SamlException("failed to validate a signature because no signature exists"); } try { signatureProfileValidator.validate(signature); SignatureValidator.validate(signature, validationCredential); } catch (SignatureException e) { throw new SamlException("failed to validate a signature", e); } }
private static void signObject(Signature signature) throws WSSecurityException { if (signature != null) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(SignerProvider.class.getClassLoader()); Signer.signObject(signature); } catch (SignatureException ex) { throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, ex, "empty", new Object[] {"Error signing a SAML assertion"}); } finally { Thread.currentThread().setContextClassLoader(loader); } } }
/** * Perform pre-validation on the Signature token. * * @param signature the signature to evaluate * @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). * @throws FilterException thrown if the signature element fails pre-validation */ protected void performPreValidation(@Nonnull final Signature signature, @Nonnull @NotEmpty final String metadataEntryName) throws FilterException { if (getSignaturePrevalidator() != null) { try { getSignaturePrevalidator().validate(signature); } catch (final SignatureException e) { log.error("Signature on metadata entry '{}' failed signature pre-validation", metadataEntryName); throw new FilterException("Metadata instance signature failed signature pre-validation", e); } } }
/** {@inheritDoc} */ @Override protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext) { try { // TODO Maybe the response should not be logged ? if (log.isTraceEnabled()) { logResponse("Response before signing:"); } if (response instanceof org.opensaml.saml.saml1.core.Response) { for (final org.opensaml.saml.saml1.core.Assertion assertion : ((org.opensaml.saml.saml1.core.Response) response).getAssertions()) { SignatureSupport.signObject(assertion, signatureSigningParameters); } } else if (response instanceof org.opensaml.saml.saml2.core.Response) { for (final org.opensaml.saml.saml2.core.Assertion assertion : ((org.opensaml.saml.saml2.core.Response) response).getAssertions()) { SignatureSupport.signObject(assertion, signatureSigningParameters); } } // TODO Maybe the response should not be logged ? if (log.isTraceEnabled()) { logResponse("Response after signing:"); } } catch (final SecurityException | MarshallingException | SignatureException e) { log.warn("{} Error encountered while signing assertions", getLogPrefix(), e); ActionSupport.buildEvent(profileRequestContext, EventIds.UNABLE_TO_SIGN); } }
/** * Validate that the Signature instance does not contain any ds:Object children. * * @param apacheSig the Apache XML Signature instance * @throws SignatureException if the signature contains ds:Object children */ protected void validateObjectChildren(XMLSignature apacheSig) throws SignatureException { if (apacheSig.getObjectLength() > 0) { log.error("Signature contained {} ds:Object child element(s)", apacheSig.getObjectLength()); throw new SignatureException("Signature contained illegal ds:Object children"); } } }
/** * Validate the signature of an assertion * * @param request SAML Assertion, this could be either a SAML Request or a * LogoutRequest * @param alias Certificate alias against which the signature is validated. * @param domainName domain name of the subject * @return true, if the signature is valid. * @throws IdentitySAML2QueryException When signature is invalid or unable to load credential information */ public static boolean validateXMLSignature(RequestAbstractType request, String alias, String domainName) throws IdentitySAML2QueryException { boolean isSignatureValid = false; if (request.getSignature() != null) { try { X509Credential cred = OpenSAML3Util.getX509CredentialImplForTenant(domainName, alias); SignatureValidator.validate(request.getSignature(), cred); return true; } catch (SignatureException e) { log.error("Unable to validate Signature of the request id:"+request.getID()+" with alias:" +alias+" ,domainname: "+domainName,e); throw new IdentitySAML2QueryException("Unable to validate Signature of the request id:"+request.getID()+" with alias:" +alias+" ,domainname: "+domainName,e); } } return isSignatureValid; }
/** * Validate the Signature's SignedInfo Reference. * * The SignedInfo must contain exactly 1 Reference. * * @param apacheSig the Apache XML Signature instance * @return the valid Reference contained within the SignedInfo * @throws SignatureException thrown if the Signature does not contain exactly 1 Reference, or if there is an error * obtaining the Reference instance */ protected Reference validateReference(XMLSignature apacheSig) throws SignatureException { int numReferences = apacheSig.getSignedInfo().getLength(); if (numReferences != 1) { log.error("Signature SignedInfo had invalid number of References: " + numReferences); throw new SignatureException("Signature SignedInfo must have exactly 1 Reference element"); } Reference ref = null; try { ref = apacheSig.getSignedInfo().item(0); } catch (XMLSecurityException e) { log.error("Apache XML Security exception obtaining Reference", e); throw new SignatureException("Could not obtain Reference from Signature/SignedInfo", e); } if (ref == null) { log.error("Signature Reference was null"); throw new SignatureException("Signature Reference was null"); } return ref; }
} else { try { org.opensaml.xmlsec.signature.support.SignatureValidator.validate(response.getSignature(), new X509CredentialImplementation(ssoX509Credential.getEntityCertificate())); } catch (SignatureException e) { } else { try { org.opensaml.xmlsec.signature.support.SignatureValidator.validate(assertion.getSignature(), new X509CredentialImplementation(ssoX509Credential.getEntityCertificate())); } catch (SignatureException e) {
/** * Validate an instance of {@link SignatureImpl}, which is in turn based on underlying Apache XML Security * <code>XMLSignature</code> instance. * * @param sigImpl the signature implementation object to validate * @throws SignatureException thrown if the signature is not valid with respect to the profile */ protected void validateSignatureImpl(SignatureImpl sigImpl) throws SignatureException { if (sigImpl.getXMLSignature() == null) { log.error("SignatureImpl did not contain the an Apache XMLSignature child"); throw new SignatureException("Apache XMLSignature does not exist on SignatureImpl"); } XMLSignature apacheSig = sigImpl.getXMLSignature(); if (!(sigImpl.getParent() instanceof SignableSAMLObject)) { log.error("Signature is not an immedidate child of a SignableSAMLObject"); throw new SignatureException("Signature is not an immediate child of a SignableSAMLObject."); } SignableSAMLObject signableObject = (SignableSAMLObject) sigImpl.getParent(); Reference ref = validateReference(apacheSig); validateReferenceURI(ref.getURI(), signableObject); validateTransforms(ref); validateObjectChildren(apacheSig); }