Java Code Examples for org.apache.wss4j.common.saml.OpenSAMLUtil#fromDom()

The following examples show how to use org.apache.wss4j.common.saml.OpenSAMLUtil#fromDom() . 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: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static XMLObject read(final boolean useDeflateEncoding, final String response)
        throws DataFormatException, UnsupportedEncodingException, XMLStreamException, WSSecurityException {

    InputStream tokenStream;
    byte[] deflatedToken = Base64.getDecoder().decode(response);
    tokenStream = useDeflateEncoding
            ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
            : new ByteArrayInputStream(deflatedToken);

    // parse the provided SAML response
    Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    XMLObject responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());

    if (LOG.isDebugEnabled()) {
        try {
            StringWriter writer = new StringWriter();
            write(writer, responseObject, false);
            writer.close();

            LOG.debug("Parsed SAML response: {}", writer.toString());
        } catch (Exception e) {
            LOG.error("Could not log the received SAML response", e);
        }
    }

    return responseObject;
}
 
Example 2
Source File: SAML2IdPCache.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public SAML2IdPEntity put(final SAML2IdP idp)
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, WSSecurityException,
        XMLParserException {

    Element element = OpenSAMLUtil.getParserPool().parse(
            new InputStreamReader(new ByteArrayInputStream(idp.getMetadata()))).getDocumentElement();
    EntityDescriptor entityDescriptor = (EntityDescriptor) OpenSAMLUtil.fromDom(element);
    return put(entityDescriptor, binder.getIdPTO(idp));
}
 
Example 3
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testInvalidStatusCode() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML1_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid SAML code");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 4
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected AuthnRequest extractRequest(String samlRequest) throws Base64Exception,
    DataFormatException, XMLStreamException, IOException, WSSecurityException {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);

    final Document responseDoc;
    try (InputStream tokenStream = new DeflateEncoderDecoder().inflateToken(deflatedToken)) {
        responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    }
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    System.out.println(DOM2Writer.nodeToString(responseDoc));
    return request;
}
 
Example 5
Source File: AuthnRequestParser.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected RequestAbstractType extractRequest(RequestContext context, String samlRequest) throws Exception {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);
    String httpMethod = WebUtils.getHttpServletRequest(context).getMethod();

    InputStream tokenStream = supportDeflateEncoding || "GET".equals(httpMethod)
         ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
             : new ByteArrayInputStream(deflatedToken);

    Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    if (LOG.isDebugEnabled()) {
        LOG.debug(DOM2Writer.nodeToString(responseDoc));
    }
    return (RequestAbstractType)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
}
 
Example 6
Source File: SAMLRequestTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCustomSAMLAuthnRequest() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("CUSTOM_REQUEST");

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
    EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
    EasyMock.expect(req.getRequestURI()).andReturn(TEST_REQUEST_URI).times(1, 2);
    EasyMock.replay(req);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    RedirectionResponse response = wfProc.createSignInRequest(req, config);

    String redirectionURL = response.getRedirectionURL();
    String samlRequest =
        redirectionURL.substring(redirectionURL.indexOf("SAMLRequest=") + "SAMLRequest=".length(),
                                 redirectionURL.indexOf("RelayState=") - 1);

    byte[] deflatedToken = Base64.getDecoder().decode(URLDecoder.decode(samlRequest, "UTF-8"));
    InputStream tokenStream = CompressionUtils.inflate(deflatedToken);

    Document requestDoc = DOMUtils.readXml(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(requestDoc.getDocumentElement());

    Assert.assertEquals(TEST_REQUEST_URL, request.getIssuer().getValue());
    Assert.assertEquals(TEST_REQUEST_URL, request.getAssertionConsumerServiceURL());
    Assert.assertEquals("1.1",  request.getVersion().toString());
}
 
Example 7
Source File: SAMLRequestTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void createSAMLLogoutRequest() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
    EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
    EasyMock.expect(req.getRequestURI()).andReturn(TEST_REQUEST_URI).times(1, 2);
    EasyMock.replay(req);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    RedirectionResponse response = wfProc.createSignOutRequest(req, null, config);

    String redirectionURL = response.getRedirectionURL();
    String samlRequest =
        redirectionURL.substring(redirectionURL.indexOf("SAMLRequest=") + "SAMLRequest=".length(),
                                 redirectionURL.indexOf("RelayState=") - 1);

    byte[] deflatedToken = Base64.getDecoder().decode(URLDecoder.decode(samlRequest, "UTF-8"));
    InputStream tokenStream = CompressionUtils.inflate(deflatedToken);

    Document requestDoc = DOMUtils.readXml(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    LogoutRequest request =
        (LogoutRequest)OpenSAMLUtil.fromDom(requestDoc.getDocumentElement());

    Assert.assertEquals(TEST_REQUEST_URL, request.getIssuer().getValue());
}
 
Example 8
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Response createResponse(
    SubjectConfirmationDataBean subjectConfirmationData,
    SAML2CallbackHandler callbackHandler
) throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    return (Response)OpenSAMLUtil.fromDom(policyElement);
}
 
Example 9
Source File: SAMLRequestTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSAMLAuthnRequest() throws Exception {
    // Mock up a Request
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
    EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
    EasyMock.expect(req.getRequestURI()).andReturn(TEST_REQUEST_URI).times(1, 2);
    EasyMock.replay(req);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    RedirectionResponse response = wfProc.createSignInRequest(req, config);

    String redirectionURL = response.getRedirectionURL();
    String samlRequest =
        redirectionURL.substring(redirectionURL.indexOf("SAMLRequest=") + "SAMLRequest=".length(),
                                 redirectionURL.indexOf("RelayState=") - 1);

    byte[] deflatedToken = Base64.getDecoder().decode(URLDecoder.decode(samlRequest, "UTF-8"));
    InputStream tokenStream = CompressionUtils.inflate(deflatedToken);

    Document requestDoc = DOMUtils.readXml(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    AuthnRequest request =
        (AuthnRequest)OpenSAMLUtil.fromDom(requestDoc.getDocumentElement());

    Assert.assertEquals(TEST_REQUEST_URL, request.getIssuer().getValue());
    Assert.assertEquals(TEST_REQUEST_URL, request.getAssertionConsumerServiceURL());
    Assert.assertEquals("2.0",  request.getVersion().toString());
}
 
Example 10
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulValidation() throws Exception {

    Document doc = DOMUtils.createDocument();

    Response response = createResponse(doc);

    Element responseElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(responseElement);
    assertNotNull(responseElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(responseElement);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(CombinedValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );

    // Test SSO validation
    SAMLSSOResponseValidator ssoValidator = new SAMLSSOResponseValidator();
    ssoValidator.setIssuerIDP("http://cxf.apache.org/issuer");
    ssoValidator.setAssertionConsumerURL("http://recipient.apache.org");
    ssoValidator.setClientAddress("http://apache.org");
    ssoValidator.setRequestId("12345");
    ssoValidator.setSpIdentifier("http://service.apache.org");

    // Parse the response
    SSOValidatorResponse ssoResponse =
        ssoValidator.validateSamlResponse(marshalledResponse, false);
    SamlAssertionWrapper parsedAssertion =
        new SamlAssertionWrapper(ssoResponse.getAssertionElement());

    assertEquals("alice", parsedAssertion.getSubjectName());
}
 
Example 11
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignedResponseInvalidDestination() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setNotBefore(new DateTime());
    conditions.setNotAfter(new DateTime().plusMinutes(5));
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList("http://service.apache.org"));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());
    response.setDestination("xyz");

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    signResponse(response, "alice", "password", issuerCrypto, true);

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(marshalledResponse, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 12
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testInvalidSubjectLocality() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
    callbackHandler.setSubjectLocality("xyz.123", null);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid SessionNotOnOrAfter");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 13
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testFutureAuthnInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
    callbackHandler.setAuthnInstant(new DateTime().plusDays(1));

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Assertion AuthnInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 14
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAssertionIssueInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    assertion.getSaml2().setIssueInstant(new DateTime().plusMinutes(5));

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Assertion IssueInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 15
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testResponseIssueInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    response.setIssueInstant(new DateTime().plusMinutes(5));

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Response IssueInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 16
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignedResponseNoKeyInfo() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);
    issuerCrypto.setDefaultX509Identifier("alice");

    response.getAssertions().add(assertion.getSaml2());
    signResponse(response, "alice", "password", issuerCrypto, false);

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.setKeyInfoMustBeAvailable(false);
    try {
        validator.validateSamlResponse(marshalledResponse, null, new KeystorePasswordCallback());
        fail("Expected failure on no Signature Crypto");
    } catch (WSSecurityException ex) {
        // expected
    }

    // Validate the Response
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );
}
 
Example 17
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testResponseModifiedSignedAssertion() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    assertion.signAssertion("alice", "password", issuerCrypto, false);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    List<Element> assertions =
        DOMUtils.findAllElementsByTagNameNS(policyElement, SAMLConstants.SAML20_NS, "Assertion");
    assertNotNull(assertions);
    assertTrue(assertions.size() == 1);
    assertions.get(0).setAttributeNS(null, "newattr", "http://apache.org");

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
       // Validate the Response
        validator.validateSamlResponse(
            marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
        );
        fail("Expected failure on a bad signature");
    } catch (WSSecurityException ex) {
        // expected
    }

}
 
Example 18
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testResponseSignedAssertion() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    assertion.signAssertion("alice", "password", issuerCrypto, false);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, new KeystorePasswordCallback());
        fail("Expected failure on no Signature Crypto");
    } catch (WSSecurityException ex) {
        // expected
    }

    // Validate the Response
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );
}
 
Example 19
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testEnforceResponseSigned() throws Exception {

    Document doc = DOMUtils.createDocument();

    Response response = createResponse(doc);

    Element responseElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(responseElement);
    assertNotNull(responseElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(responseElement);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(CombinedValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );

    // Test SSO validation
    SAMLSSOResponseValidator ssoValidator = new SAMLSSOResponseValidator();
    ssoValidator.setIssuerIDP("http://cxf.apache.org/issuer");
    ssoValidator.setAssertionConsumerURL("http://recipient.apache.org");
    ssoValidator.setClientAddress("http://apache.org");
    ssoValidator.setRequestId("12345");
    ssoValidator.setSpIdentifier("http://service.apache.org");
    ssoValidator.setEnforceResponseSigned(true);

    // Parse the response
    try {
        ssoValidator.validateSamlResponse(marshalledResponse, false);
        fail("Failure expected on an unsigned Response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 20
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testWrappingAttack3() throws Exception {
    Document doc = DOMUtils.createDocument();
    Response response = createResponse(doc);

    Element responseElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(responseElement);
    assertNotNull(responseElement);

    // Get Assertion Element
    Element assertionElement =
        (Element)responseElement.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Assertion").item(0);
    assertNotNull(assertionElement);

    // Clone it, strip the Signature, modify the Subject, change Subj Conf
    Element clonedAssertion = (Element)assertionElement.cloneNode(true);
    clonedAssertion.setAttributeNS(null, "ID", "_12345623562");
    Element sigElement =
        (Element)clonedAssertion.getElementsByTagNameNS(WSS4JConstants.SIG_NS, "Signature").item(0);
    clonedAssertion.removeChild(sigElement);

    Element subjElement =
        (Element)clonedAssertion.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Subject").item(0);
    Element subjNameIdElement =
        (Element)subjElement.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "NameID").item(0);
    subjNameIdElement.setTextContent("bob");

    Element subjConfElement =
        (Element)subjElement.getElementsByTagNameNS(SAMLConstants.SAML20_NS, "SubjectConfirmation").item(0);
    subjConfElement.setAttributeNS(null, "Method", SAML2Constants.CONF_SENDER_VOUCHES);

    // Now insert the modified cloned Assertion into the Response before actual assertion
    responseElement.insertBefore(clonedAssertion, assertionElement);

    // System.out.println(DOM2Writer.nodeToString(responseElement));

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(responseElement);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(CombinedValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );

    // Test SSO validation
    SAMLSSOResponseValidator ssoValidator = new SAMLSSOResponseValidator();
    ssoValidator.setEnforceAssertionsSigned(false);
    ssoValidator.setIssuerIDP("http://cxf.apache.org/issuer");
    ssoValidator.setAssertionConsumerURL("http://recipient.apache.org");
    ssoValidator.setClientAddress("http://apache.org");
    ssoValidator.setRequestId("12345");
    ssoValidator.setSpIdentifier("http://service.apache.org");

    // Parse the response
    SSOValidatorResponse ssoResponse =
        ssoValidator.validateSamlResponse(marshalledResponse, false);
    SamlAssertionWrapper parsedAssertion =
        new SamlAssertionWrapper(ssoResponse.getAssertionElement());

    assertEquals("alice", parsedAssertion.getSubjectName());
}