Java Code Examples for org.apache.wss4j.common.ext.WSPasswordCallback#SIGNATURE

The following examples show how to use org.apache.wss4j.common.ext.WSPasswordCallback#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: STSCallbackHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks) throws IOException,
        UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof WSPasswordCallback) {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
            if (pc.getUsage() == WSPasswordCallback.DECRYPT
                || pc.getUsage() == WSPasswordCallback.SIGNATURE) {
                if ("mystskey".equals(pc.getIdentifier())) {
                    pc.setPassword("stskpass");
                }
            } else if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {
                if ("alice".equals(pc.getIdentifier())) {
                    pc.setPassword("clarinet");
                }
            }
        }
    }
}
 
Example 2
Source File: ClientCallbackHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks) throws IOException,
        UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof WSPasswordCallback) {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
            if (pc.getUsage() == WSPasswordCallback.DECRYPT
                || pc.getUsage() == WSPasswordCallback.SIGNATURE) {
                if ("myclientkey".equals(pc.getIdentifier())) {
                    pc.setPassword("ckpass");
                }
            } else if (pc.getUsage() == WSPasswordCallback.USERNAME_TOKEN) {
                if ("alice".equals(pc.getIdentifier())) {
                    pc.setPassword("clarinet");
                    break;
                } else if ("bob".equals(pc.getIdentifier())) {
                    pc.setPassword("trombone");
                    break;
                }
            }
        }
    }
}
 
Example 3
Source File: RSSecurityUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String getSignaturePassword(Message message, String userName,
                                          Class<?> callingClass) throws WSSecurityException {
    CallbackHandler handler = getCallbackHandler(message, callingClass);
    if (handler == null) {
        // See if we have a signature password we can use here instead
        return (String)SecurityUtils.getSecurityPropertyValue(SecurityConstants.SIGNATURE_PASSWORD, message);
    }

    WSPasswordCallback[] cb = {new WSPasswordCallback(userName, WSPasswordCallback.SIGNATURE)};
    try {
        handler.handle(cb);
    } catch (Exception e) {
        return null;
    }

    //get the password
    String password = cb[0].getPassword();
    return password == null ? "" : password;
}
 
Example 4
Source File: ClaimsProcessorTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, SAXException,
    ParserConfigurationException {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example 5
Source File: SAMLTokenValidatorOldTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example 6
Source File: RequestedClaimsTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example 7
Source File: AudienceRestrictionTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example 8
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example 9
Source File: SAMLResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createSamlResponse(SamlAssertionWrapper assertion, String alias,
                                  boolean sign, String requestID)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                                                          assertion.getIssuerString(),
                                                          status);
    response.getAssertions().add(assertion.getSaml2());

    Document doc = docBuilder.newDocument();
    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 10
Source File: AbstractBindingBuilder.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String getPassword(String userName, Assertion info, int usage) {
    //Then try to get the password from the given callback handler
    Object o = SecurityUtils.getSecurityPropertyValue(SecurityConstants.CALLBACK_HANDLER, message);
    CallbackHandler handler = null;
    try {
        handler = SecurityUtils.getCallbackHandler(o);
        if (handler == null) {
            // Don't unassert for signature as we might get the password from the crypto properties
            if (usage == WSPasswordCallback.SIGNATURE) {
                LOG.info("No CallbackHandler available to retrieve a password. We will now try the crypto "
                         + "properties file for a private password");
            } else {
                unassertPolicy(info, "No callback handler and no password available");
            }
            return null;
        }
    } catch (Exception ex) {
        // Don't unassert for signature as we might get the password from the crypto properties
        if (usage == WSPasswordCallback.SIGNATURE) {
            LOG.info("No CallbackHandler available to retrieve a password. We will now try the crypto "
                     + "properties file for a private password");
        } else {
            unassertPolicy(info, "No callback handler and no password available");
        }
        return null;
    }

    WSPasswordCallback[] cb = {new WSPasswordCallback(userName, usage)};
    try {
        handler.handle(cb);
    } catch (Exception e) {
        unassertPolicy(info, e);
    }

    //get the password
    return cb[0].getPassword();
}
 
Example 11
Source File: ClientPasswordCallback.java    From eet-client with MIT License 5 votes vote down vote up
@Override
public void handle(final Callback[] callbacks) throws IOException, UnsupportedCallbackException {

    for (final Callback thisCallback : callbacks) {
        final WSPasswordCallback pwcb = (WSPasswordCallback) thisCallback;
        final String user = pwcb.getIdentifier();
        final int usage = pwcb.getUsage();
        if (usage == WSPasswordCallback.SIGNATURE && alias.equals(user)) {
            pwcb.setPassword(password);
        }
    }

}
 
Example 12
Source File: SAMLResponseConformanceTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createSamlResponse(SamlAssertionWrapper assertion, String alias,
                                  boolean sign, String requestID, Issuer issuer)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );

    Issuer responseIssuer = issuer;
    if (responseIssuer == null) {
        responseIssuer = SAML2PResponseComponentBuilder.createIssuer(assertion.getIssuerString());
    }
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                                                          responseIssuer,
                                                          status);

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

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

    return policyElement;
}
 
Example 13
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createResponseWithMultipleAssertions(SamlAssertionWrapper assertion1,
                                      boolean signFirstAssertion,
                                      SamlAssertionWrapper assertion2,
                                      boolean signSecondAssertion,
                                      String alias) throws Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (signFirstAssertion) {
        assertion1.signAssertion(alias, password, crypto, false);
    }
    if (signSecondAssertion) {
        assertion2.signAssertion(alias, password, crypto, false);
    }

    Document doc = STSUtil.toSOAPPart(SAMPLE_MULTIPLE_RSTR_COLL_MSG);
    Element token1 = assertion1.toDOM(doc);
    Element token2 = assertion2.toDOM(doc);

    List<Element> requestedTokenElements =
        XMLUtils.findElements(doc, "RequestedSecurityToken", FederationConstants.WS_TRUST_13_NS);
    Assert.assertEquals(2, requestedTokenElements.size());
    requestedTokenElements.get(0).appendChild(token1);
    requestedTokenElements.get(1).appendChild(token2);

    return doc.getDocumentElement();
}
 
Example 14
Source File: SAMLEncryptedResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createSamlResponse(SamlAssertionWrapper assertion, String alias,
                                  boolean sign, String requestID)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                                                          assertion.getIssuerString(),
                                                          status);
    response.getAssertions().add(assertion.getSaml2());

    Document doc = docBuilder.newDocument();
    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

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

    String requestId = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");

    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
    RequestState requestState = new RequestState(TEST_REQUEST_URL,
                                                 TEST_IDP_ISSUER,
                                                 requestId,
                                                 TEST_REQUEST_URL,
                                                 (String)config.getProtocol().getIssuer(),
                                                 null,
                                                 relayState,
                                                 System.currentTimeMillis());

    // Create SAML Response
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setAlsoAddAuthnStatement(true);
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_IDP_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);

    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_REQUEST_URL);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(TEST_CLIENT_ADDRESS);
    subjectConfirmationData.setInResponseTo(requestId);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(TEST_REQUEST_URL);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

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

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestId,
                                                          assertion.getIssuerString(),
                                                          status);

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

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

    NodeList assertionNodes =
        policyElement.getElementsByTagNameNS(WSConstants.SAML2_NS, "Assertion");
    assertTrue(assertionNodes != null && assertionNodes.getLength() == 1);

    Element assertionElement = (Element)assertionNodes.item(0);

    // Change IssueInstant attribute
    String issueInstance = assertionElement.getAttributeNS(null, "IssueInstant");
    DateTime issueDateTime = new DateTime(issueInstance, DateTimeZone.UTC);
    issueDateTime = issueDateTime.plusSeconds(1);
    assertionElement.setAttributeNS(null, "IssueInstant", issueDateTime.toString());

    String responseStr = encodeResponse(policyElement);

    HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
    EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL));
    EasyMock.expect(req.getRemoteAddr()).andReturn(TEST_CLIENT_ADDRESS);
    EasyMock.replay(req);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setResponseToken(responseStr);
    wfReq.setState(relayState);
    wfReq.setRequest(req);
    wfReq.setRequestState(requestState);

    FedizProcessor wfProc = new SAMLProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on modified Signature");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example 16
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private String encryptAndSignToken(
    SamlAssertionWrapper assertion
) throws Exception {

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);

    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);

    WSSecEncrypt builder = new WSSecEncrypt(token.getOwnerDocument());
    builder.setUserInfo("mystskey");

    builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
    builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
    builder.setKeyEncAlgo(WSConstants.KEYTRANSPORT_RSAOAEP);
    builder.setEmbedEncryptedKey(true);

    WSEncryptionPart encryptionPart = new WSEncryptionPart(assertion.getId(), "Element");
    encryptionPart.setElement(token);

    Crypto encrCrypto = CryptoFactory.getInstance("signature.properties");
    builder.prepare(encrCrypto);
    builder.encryptForRef(null, Collections.singletonList(encryptionPart));

    // return doc.getDocumentElement();
    return DOM2Writer.nodeToString(doc);
}
 
Example 17
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testModifiedSignature() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

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

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);
    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);
    Element token = assertion.toDOM(doc);

    // Change IssueInstant attribute
    String issueInstance = token.getAttributeNS(null, "IssueInstant");
    DateTime issueDateTime = new DateTime(issueInstance, DateTimeZone.UTC);
    issueDateTime = issueDateTime.plusSeconds(1);
    token.setAttributeNS(null, "IssueInstant", issueDateTime.toString());

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                   FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                               FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    String rstr = DOM2Writer.nodeToString(doc);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on signature validation");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example 18
Source File: SAMLEncryptedResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Element createEncryptedSamlResponse(SamlAssertionWrapper assertion, String alias,
                                   boolean sign, String requestID)
        throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)};
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Status status =
            SAML2PResponseComponentBuilder.createStatus(
                    "urn:oasis:names:tc:SAML:2.0:status:Success", null
            );
    Response response =
            SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                    assertion.getIssuerString(),
                    status);

    Document assertionDoc = docBuilder.newDocument();
    Element elem = assertion.toDOM(assertionDoc);

    Element encryptedAssertionElement =
            assertionDoc.createElementNS(WSConstants.SAML2_NS, WSConstants.ENCRYPED_ASSERTION_LN);
    encryptedAssertionElement.setAttributeNS(
            WSConstants.XMLNS_NS, "xmlns", WSConstants.SAML2_NS
    );
    encryptedAssertionElement.appendChild(elem);
    assertionDoc.appendChild(encryptedAssertionElement);

    // Encrypt the Assertion
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(256);
    SecretKey secretKey = keygen.generateKey();
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("mystskey");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    assertTrue(certs != null && certs.length > 0 && certs[0] != null);

    encryptElement(assertionDoc, elem, WSConstants.AES_256, secretKey,
            WSConstants.KEYTRANSPORT_RSAOAEP, certs[0], false);

    Document doc = docBuilder.newDocument();
    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    Element statusElement =
            (Element)policyElement.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
                    "Status").item(0);
    assertNotNull(statusElement);
    policyElement.appendChild(doc.importNode(encryptedAssertionElement, true));

    return policyElement;
}
 
Example 19
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testWrappingAttack() throws Exception {
    // First assertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

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

    // Second assertion
    SAML2CallbackHandler callbackHandler2 = new SAML2CallbackHandler();
    callbackHandler2.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler2.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler2.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler2.setSubjectName("bob");
    ConditionsBean cp2 = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction2 = new AudienceRestrictionBean();
    audienceRestriction2.getAudienceURIs().add(TEST_AUDIENCE);
    cp2.setAudienceRestrictions(Collections.singletonList(audienceRestriction2));
    callbackHandler2.setConditions(cp2);

    SAMLCallback samlCallback2 = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler2, samlCallback2);
    SamlAssertionWrapper assertion2 = new SamlAssertionWrapper(samlCallback2);

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion1.signAssertion("mystskey", password, crypto, false);
    assertion2.signAssertion("mystskey", password, crypto, false);

    Document doc = STSUtil.toSOAPPart(SAMPLE_MULTIPLE_RSTR_COLL_MSG);
    Element token1 = assertion2.toDOM(doc);
    Element token2 = assertion1.toDOM(doc);

    // Now modify the first Signature to point to the other Element
    Element sig1 = XMLUtils.findElement(token1, "Signature", WSConstants.SIG_NS);
    Element sig2 = XMLUtils.findElement(token2, "Signature", WSConstants.SIG_NS);
    sig1.getParentNode().replaceChild(sig2.cloneNode(true), sig1);

    List<Element> requestedTokenElements =
        XMLUtils.findElements(doc, "RequestedSecurityToken", FederationConstants.WS_TRUST_13_NS);
    Assert.assertEquals(2, requestedTokenElements.size());
    requestedTokenElements.get(0).appendChild(token1);
    requestedTokenElements.get(1).appendChild(token2);

    Element rstrElement = doc.getDocumentElement();

    String rstr = DOM2Writer.nodeToString(rstrElement);
    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    // Load and update the config to enforce an error
    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        Assert.fail("Processing must fail because of bad signature");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example 20
Source File: SamlRedirectBindingFilter.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Sign a request according to the redirect binding spec for Web SSO
 */
private void signRequest(
    String authnRequest,
    String relayState,
    UriBuilder ub
) throws Exception {
    Crypto crypto = getSignatureCrypto();
    if (crypto == null) {
        LOG.warning("No crypto instance of properties file configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    String signatureUser = getSignatureUsername();
    if (signatureUser == null) {
        LOG.warning("No user configured for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }
    CallbackHandler callbackHandler = getCallbackHandler();
    if (callbackHandler == null) {
        LOG.warning("No CallbackHandler configured to supply a password for signature");
        throw ExceptionUtils.toInternalServerErrorException(null, null);
    }

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(signatureUser);
    X509Certificate[] issuerCerts = crypto.getX509Certificates(cryptoType);
    if (issuerCerts == null) {
        throw new Exception(
            "No issuer certs were found to sign the request using name: " + signatureUser
        );
    }

    String sigAlgo = getSignatureAlgorithm();
    String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
    LOG.fine("automatic sig algo detection: " + pubKeyAlgo);
    if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
        sigAlgo = SSOConstants.DSA_SHA1;
    }

    LOG.fine("Using Signature algorithm " + sigAlgo);
    ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name()));

    // Get the password
    WSPasswordCallback[] cb = {new WSPasswordCallback(signatureUser, WSPasswordCallback.SIGNATURE)};
    callbackHandler.handle(cb);
    String password = cb[0].getPassword();

    // Get the private key
    PrivateKey privateKey = crypto.getPrivateKey(signatureUser, password);

    // Sign the request
    String jceSigAlgo = JCEMapper.translateURItoJCEID(sigAlgo);
    Signature signature = Signature.getInstance(jceSigAlgo);
    signature.initSign(privateKey);

    String requestToSign =
        SSOConstants.SAML_REQUEST + "=" + authnRequest + "&"
        + SSOConstants.RELAY_STATE + "=" + relayState + "&"
        + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, StandardCharsets.UTF_8.name());

    signature.update(requestToSign.getBytes(StandardCharsets.UTF_8));
    byte[] signBytes = signature.sign();

    String encodedSignature = Base64.getEncoder().encodeToString(signBytes);

    // Clean the private key from memory when we're done
    try {
        privateKey.destroy();
    } catch (DestroyFailedException ex) {
        // ignore
    }

    ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, StandardCharsets.UTF_8.name()));

}