org.opensaml.xmlsec.signature.support.SignatureException Java Examples

The following examples show how to use org.opensaml.xmlsec.signature.support.SignatureException. 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: ConsumerServlet.java    From OpenSAML-ref-project-demo-v3 with Apache License 2.0 6 votes vote down vote up
private void verifyAssertionSignature(Assertion assertion) {

        if (!assertion.isSigned()) {
            throw new RuntimeException("The SAML Assertion was not signed");
        }

        try {
            SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
            profileValidator.validate(assertion.getSignature());

            SignatureValidator.validate(assertion.getSignature(), IDPCredentials.getCredential());

            logger.info("SAML Assertion signature verified");
        } catch (SignatureException e) {
            e.printStackTrace();
        }

    }
 
Example #2
Source File: AuthnRequestFactory.java    From verify-service-provider with MIT License 6 votes vote down vote up
public AuthnRequest build(String serviceEntityId) {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID(String.format("_%s", UUID.randomUUID()));
    authnRequest.setIssueInstant(DateTime.now());
    authnRequest.setForceAuthn(false);
    authnRequest.setDestination(destination.toString());
    authnRequest.setExtensions(createExtensions());

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(serviceEntityId);
    authnRequest.setIssuer(issuer);

    authnRequest.setSignature(createSignature());

    try {
        XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest).marshall(authnRequest);
        Signer.signObject(authnRequest.getSignature());
    } catch (SignatureException | MarshallingException e) {
        throw new SAMLRuntimeException("Unknown problem while signing SAML object", e);
    }

    return authnRequest;
}
 
Example #3
Source File: ValidatorUtils.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Validate boolean.
 *
 * @param signature   the signature
 * @param credentials the credentials
 * @return the boolean
 */
private static boolean validate(Signature signature, List<Credential> credentials) {
  if (signature == null) {
    return false;
  }

  // It's fine if any of the credentials match the signature
  return credentials
      .stream()
      .anyMatch(
          credential -> {
            try {
              SignatureValidator.validate(signature, credential);
              return true;
            } catch (SignatureException ex) {
              return false;
            }
          });
}
 
Example #4
Source File: SamlMessageUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
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 InvalidSamlRequestException("failed to validate a signature because no signature exists");
    }

    try {
        signatureProfileValidator.validate(signature);
        SignatureValidator.validate(signature, validationCredential);
    } catch (SignatureException e) {
        throw new InvalidSamlRequestException("failed to validate a signature", e);
    }
}
 
Example #5
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: NonMatchingEidasAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenAssertionContainsAnInvalidSignature() throws MarshallingException, SignatureException {
    String base64Response = xmlToB64Transformer.apply(
            anInvalidAssertionSignatureEidasResponse("requestId", appWithEidasEnabled.getCountryEntityId()).build()
    );
    Response response = appWithEidasEnabled.client().target(format("http://localhost:%s/translate-response", appWithEidasEnabled.getLocalPort())).request().post(
            Entity.json(new TranslateSamlResponseBody(base64Response, "requestId", LEVEL_2, null))
    );

    assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);

    String responseBody = response.readEntity(String.class);
    assertThat(responseBody).contains("Signature was not valid.");
}
 
Example #7
Source File: NonMatchingEidasAcceptanceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldReturn400WhenAssertionSignedByCountryNotInTrustAnchor() throws MarshallingException, SignatureException {
    String base64Response = xmlToB64Transformer.apply(
            aValidEidasResponse("requestId", STUB_COUNTRY_ONE).build()
    );
    Response response = appWithEidasEnabled.client().target(format("http://localhost:%s/translate-response", appWithEidasEnabled.getLocalPort())).request().post(
            Entity.json(new TranslateSamlResponseBody(base64Response, "requestId", LEVEL_2, null))
    );

    assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_BAD_REQUEST);
}
 
Example #8
Source File: ResponseServiceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
private EntityDescriptor createEntityDescriptorWithSigningCertificate(String signingCert) throws MarshallingException, SignatureException {
    return anEntityDescriptor()
        .addSpServiceDescriptor(anSpServiceDescriptor()
            .withoutDefaultSigningKey()
            .addKeyDescriptor(aKeyDescriptor().withX509ForSigning(signingCert).build())
            .build()
        )
        .build();
}
 
Example #9
Source File: MockMsaServer.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static String msaMetadata() {
    EntityDescriptor entityDescriptor = new EntityDescriptorFactory().idpEntityDescriptor(MSA_ENTITY_ID);
    try {
        return new MetadataFactory().metadata(anEntitiesDescriptor()
                .withEntityDescriptors(ImmutableList.of(entityDescriptor))
                .withValidUntil(DateTime.now().plusWeeks(2)).build());
    } catch (MarshallingException | SignatureException e) {
        Throwables.throwIfUnchecked(e);
        throw new RuntimeException(e);
    }

}
 
Example #10
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private void verifyAssertionSignature(final Assertion assertion) {
    if (!assertion.isSigned()) {
        logger.error("Halting");
        throw new RuntimeException("The SAML Assertion was not signed!");
    }
    try {
        SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator();
        profileValidator.validate(assertion.getSignature());
        // use IDP Cert to verify signature
        SignatureValidator.validate(assertion.getSignature(), this.getIdpVerificationCert());
        logger.info("SAML Assertion signature verified");
    } catch (SignatureException e) {
        throw new RuntimeException("SAML Assertion signature problem", e);
    }
}
 
Example #11
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
/** Sign a SamlObject with default settings.
 * Note that this method is a no-op if spCredential is unset.
 * @param samlObject The object to sign
 *
 * @throws SamlException if {@link SignatureSupport#signObject(SignableXMLObject, SignatureSigningParameters) signObject} fails
 * */
private void signSAMLObject(SignableSAMLObject samlObject) throws SamlException {
  if (spCredential != null) {
    try {
      // Describe how we're going to sign the request
      SignatureBuilder signer = new SignatureBuilder();
      Signature signature = signer.buildObject(Signature.DEFAULT_ELEMENT_NAME);
      signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
      signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
      signature.setKeyInfo(
          new X509KeyInfoGeneratorFactory().newInstance().generate(spCredential));
      signature.setSigningCredential(spCredential);
      samlObject.setSignature(signature);

      // Actually sign the request
      SignatureSigningParameters signingParameters = new SignatureSigningParameters();
      signingParameters.setSigningCredential(spCredential);
      signingParameters.setSignatureCanonicalizationAlgorithm(
          SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
      signingParameters.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
      signingParameters.setKeyInfoGenerator(new X509KeyInfoGeneratorFactory().newInstance());
      SignatureSupport.signObject(samlObject, signingParameters);
    } catch (SecurityException | MarshallingException | SignatureException e) {
      throw new SamlException("Failed to sign request", e);
    }
  }
}
 
Example #12
Source File: ResponseServiceTest.java    From verify-service-provider with MIT License 4 votes vote down vote up
private Response signResponse(ResponseBuilder responseBuilder, Credential signingCredential) throws MarshallingException, SignatureException {
    return responseBuilder
        .withSigningCredential(signingCredential).build();
}