Java Code Examples for org.apache.wss4j.common.saml.SamlAssertionWrapper#signAssertion()

The following examples show how to use org.apache.wss4j.common.saml.SamlAssertionWrapper#signAssertion() . 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: 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 2
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 3
Source File: SAMLUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static SamlAssertionWrapper createAssertion(CallbackHandler handler,
                                               SelfSignInfo info) throws Fault {

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(handler, samlCallback);

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
        assertion.signAssertion(info.getUser(),
                                info.getPassword(),
                                info.getCrypto(),
                                false);
        return assertion;
    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 4
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 5
Source File: SCTSAMLTokenProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
private SamlAssertionWrapper createSamlToken(
    TokenProviderParameters tokenParameters, byte[] secret, Document doc
) throws Exception {
    SamlCallbackHandler handler = createCallbackHandler(tokenParameters, secret, doc);

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

    if (signToken) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();

        // Get the password
        String alias = stsProperties.getSignatureUsername();
        WSPasswordCallback[] cb = {new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)};
        LOG.fine("Creating SAML Token");
        stsProperties.getCallbackHandler().handle(cb);
        String password = cb[0].getPassword();

        LOG.fine("Signing SAML Token");
        boolean useKeyValue = stsProperties.getSignatureProperties().isUseKeyValue();
        assertion.signAssertion(alias, password, stsProperties.getSignatureCrypto(), useKeyValue);
    }

    return assertion;
}
 
Example 6
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 7
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 8
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 9
Source File: AbstractPolicySecurityTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void runOutInterceptorAndValidateSamlTokenAttached(String policyDoc) throws Exception {
    // create the request message
    final Document document = this.readDocument("wsse-request-clean.xml");
    final Element outPolicyElement =
        this.readDocument(policyDoc).getDocumentElement();
    final Policy policy = this.policyBuilder.getPolicy(outPolicyElement);

    AssertionInfoMap aim = new AssertionInfoMap(policy);
    SoapMessage msg = this.getOutSoapMessageForDom(document, aim);

    // add an "issued" assertion into the message exchange
    Element issuedAssertion =
        this.readDocument("example-sts-issued-saml-assertion.xml").getDocumentElement();

    Properties cryptoProps = new Properties();
    URL url = ClassLoader.getSystemResource("outsecurity.properties");
    cryptoProps.load(url.openStream());
    Crypto crypto = CryptoFactory.getInstance(cryptoProps);

    // Sign the "issued" assertion
    SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(issuedAssertion);
    assertionWrapper.signAssertion("myalias", "myAliasPassword", crypto, false);

    Document doc = DOMUtils.newDocument();
    issuedAssertion = OpenSAMLUtil.toDom(assertionWrapper.getSaml1(), doc);
    String assertionId = issuedAssertion.getAttributeNodeNS(null, "AssertionID").getNodeValue();

    SecurityToken issuedToken =
        new SecurityToken(assertionId, issuedAssertion, null);

    String alias = cryptoProps.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(alias);
    issuedToken.setX509Certificate(crypto.getX509Certificates(cryptoType)[0], crypto);

    msg.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID,
            issuedToken.getId());
    msg.getExchange().put(SecurityConstants.TOKEN_ID, issuedToken.getId());

    TokenStore tokenStore = new MemoryTokenStore();
    msg.getExchange().getEndpoint().getEndpointInfo()
        .setProperty(TokenStore.class.getName(), tokenStore);
    tokenStore.add(issuedToken);

    // fire the interceptor and verify results
    final Document signedDoc = this.runOutInterceptorAndValidate(
            msg, policy, aim, null, null);

    this.runInInterceptorAndValidate(signedDoc,
                                     policy, Collections.singletonList(SP12Constants.ISSUED_TOKEN), null,
                                     Collections.singletonList(CoverageType.SIGNED));
}
 
Example 10
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 11
Source File: JAXRSOAuth2Test.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testSAMLBadSubjectName() throws Exception {
    String address = "https://localhost:" + port + "/oauth2-auth/token";
    WebClient wc = createWebClient(address);

    String audienceURI = "https://localhost:" + port + "/oauth2-auth/token";

    // Create the SAML Assertion
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setSubjectName("bob");
    samlCallbackHandler.setAudience(audienceURI);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);

    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
    if (samlCallback.isSignAssertion()) {
        samlAssertion.signAssertion(
            samlCallback.getIssuerKeyName(),
            samlCallback.getIssuerKeyPassword(),
            samlCallback.getIssuerCrypto(),
            samlCallback.isSendKeyValue(),
            samlCallback.getCanonicalizationAlgorithm(),
            samlCallback.getSignatureAlgorithm()
        );
    }

    String assertion = samlAssertion.assertionToString();

    String encodedAssertion = Base64UrlUtility.encode(assertion);

    Map<String, String> extraParams = new HashMap<>();
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_TYPE, Constants.CLIENT_AUTH_SAML2_BEARER);
    extraParams.put(Constants.CLIENT_AUTH_ASSERTION_PARAM, encodedAssertion);

    try {
        OAuthClientUtils.getAccessToken(wc, new CustomGrant(), extraParams);
        fail("Failure expected on a bad subject name");
    } catch (OAuthServiceException ex) {
        // expected
    }
}
 
Example 12
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSAMLUnauthenticatedSignature() throws Exception {
    URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Create the SAML Assertion
    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(true);
    samlCallbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    samlCallbackHandler.setAudience(address + "token");
    samlCallbackHandler.setIssuerKeyName("smallkey");
    samlCallbackHandler.setIssuerKeyPassword("security");
    samlCallbackHandler.setCryptoPropertiesFile("org/apache/cxf/systest/jaxrs/security/smallkey.properties");

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(samlCallbackHandler, samlCallback);

    SamlAssertionWrapper samlAssertion = new SamlAssertionWrapper(samlCallback);
    samlAssertion.signAssertion(
        samlCallback.getIssuerKeyName(),
        samlCallback.getIssuerKeyPassword(),
        samlCallback.getIssuerCrypto(),
        samlCallback.isSendKeyValue(),
        samlCallback.getCanonicalizationAlgorithm(),
        samlCallback.getSignatureAlgorithm()
    );
    String assertion = samlAssertion.assertionToString();

    // Get Access Token
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    form.param("assertion", Base64UrlUtility.encode(assertion));
    form.param("client_id", "consumer-id");

    try {
        Response response = client.post(form);
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on an incorrect subject confirmation method");
    } catch (Exception ex) {
        // expected
    }
}
 
Example 13
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 14
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
protected Element createResponse(String requestID, String racs, String requestIssuer) throws Exception {
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    String issuer = messageContext.getUriInfo().getAbsolutePath().toString();
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID, issuer, status);

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setIssuer(issuer);
    String user = messageContext.getSecurityContext().getUserPrincipal().getName();
    callbackHandler.setSubjectName(user);

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(messageContext.getHttpServletRequest().getRemoteAddr());
    subjectConfirmationData.setInResponseTo(requestID);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(racs);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    // Audience Restriction
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

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

    Crypto issuerCrypto = CryptoFactory.getInstance("stsKeystoreB.properties");
    assertion.signAssertion("realmb", "realmb", issuerCrypto, false);

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

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

    return policyElement;
}
 
Example 15
Source File: AbstractTrustedIdpOAuth2ProtocolHandler.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
protected SamlAssertionWrapper createSamlAssertion(Idp idp, TrustedIdp trustedIdp, JsonMapObject claims, 
                                                 String subjectName,
                                                 Instant notBefore,
                                                 Instant expires) throws Exception {
    SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
    String issuer = idp.getServiceDisplayName();
    if (issuer == null) {
        issuer = idp.getRealm();
    }
    if (issuer != null) {
        callbackHandler.setIssuer(issuer);
    }

    // Subject
    SubjectBean subjectBean =
        new SubjectBean(subjectName, SAML2Constants.NAMEID_FORMAT_UNSPECIFIED, SAML2Constants.CONF_BEARER);
    callbackHandler.setSubjectBean(subjectBean);

    // Conditions
    ConditionsBean conditionsBean = new ConditionsBean();
    conditionsBean.setNotAfter(new DateTime(Date.from(expires)));
    if (notBefore != null) {
        DateTime notBeforeDT = new DateTime(Date.from(notBefore));
        conditionsBean.setNotBefore(notBeforeDT);
    } else {
        conditionsBean.setNotBefore(new DateTime());
    }
    callbackHandler.setConditionsBean(conditionsBean);

    // Claims
    String claimsHandler = getProperty(trustedIdp, CLAIMS_HANDLER);
    if (claimsHandler != null) {
        ClaimsHandler claimsHandlerImpl = (ClaimsHandler)Loader.loadClass(claimsHandler).newInstance();
        AttributeStatementBean attrStatementBean = claimsHandlerImpl.handleClaims(claims);
        callbackHandler.setAttrBean(attrStatementBean);
    }

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

    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto crypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
    assertion.signAssertion(crypto.getDefaultX509Identifier(), idp.getCertificatePassword(),
                            crypto, false);

    return assertion;
}
 
Example 16
Source File: SamlResponseCreator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Assertion createSAML2Assertion(RequestContext context, Idp idp, SamlAssertionWrapper receivedToken,
                                       String requestID, String requestIssuer,
                                       String remoteAddr, String racs) throws Exception {
    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    String issuer = isUseRealmForIssuer() ? idp.getRealm() : idp.getIdpUrl().toString();
    callbackHandler.setIssuer(issuer);
    callbackHandler.setSubject(receivedToken.getSaml2().getSubject());

    // Test Subject against received Subject (if applicable)
    SAMLAuthnRequest authnRequest =
        (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
    if (authnRequest.getSubjectNameId() != null && receivedToken.getSaml2().getSubject().getNameID() != null) {
        NameID issuedNameId = receivedToken.getSaml2().getSubject().getNameID();
        if (!authnRequest.getSubjectNameId().equals(issuedNameId.getValue())) {
            LOG.debug("Received NameID value of {} does not match issued value {}",
                      authnRequest.getSubjectNameId(), issuedNameId.getValue());
            throw new ProcessingException(ProcessingException.TYPE.INVALID_REQUEST);
        }
    }

    // Subject Confirmation Data
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress(remoteAddr);
    subjectConfirmationData.setInResponseTo(requestID);
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient(racs);
    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    // Audience Restriction
    ConditionsBean conditions = new ConditionsBean();
    conditions.setTokenPeriodMinutes(5);

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
    conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(conditions);

    // Attributes
    callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());

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

    Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
    assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(),
                            issuerCrypto, false);

    return assertion.getSaml2();
}
 
Example 17
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a HolderOfKey SAML 2 token
 */
@org.junit.Test
public void validateHOKSAML2Token() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    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);

    Crypto clientCrypto = CryptoFactory.getInstance("client-crypto.properties");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    X509Certificate[] certs = clientCrypto.getX509Certificates(cryptoType);
    callbackHandler.setCerts(certs);

    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);

    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_DECRYPTION");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on missing client certs");
    } catch (ProcessingException ex) {
        // expected
    }

    // Now set client certs
    wfReq.setCerts(certs);
    wfProc.processRequest(wfReq, config);
}
 
Example 18
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
private static org.opensaml.saml.saml2.core.Response createResponse(
        final String inResponseTo, final boolean signAssertion, final String subjectConfMethod,
        final String issuer) throws Exception {

    Status status = SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null);
    org.opensaml.saml.saml2.core.Response response = SAML2PResponseComponentBuilder.createSAMLResponse(
            inResponseTo, issuer, status);
    response.setDestination("http://recipient.apache.org");

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setIssuer(issuer);
    callbackHandler.setSubjectName("puccini");
    callbackHandler.setSubjectConfirmationMethod(subjectConfMethod);

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

    ConditionsBean conditions = new ConditionsBean();
    conditions.setNotBefore(new DateTime());
    conditions.setNotAfter(new DateTime().plusMinutes(5));

    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.setAudienceURIs(List.of("http://recipient.apache.org/"));
    conditions.setAudienceRestrictions(List.of(audienceRestriction));
    callbackHandler.setConditions(conditions);

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

    if (signAssertion) {
        Crypto issuerCrypto = new Merlin();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream input = Files.newInputStream(keystorePath);
        keyStore.load(input, "security".toCharArray());
        ((Merlin) issuerCrypto).setKeyStore(keyStore);

        assertion.signAssertion("subject", "security", issuerCrypto, false);
    }

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

    return response;
}
 
Example 19
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 20
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
    }
}