org.opensaml.saml.common.xml.SAMLConstants Java Examples

The following examples show how to use org.opensaml.saml.common.xml.SAMLConstants. 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: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Marshal the saml xml object to raw xml.
 *
 * @param object the object
 * @param writer the writer
 * @return the xml string
 */
public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer)  {
    try {
        final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        final Marshaller marshaller = marshallerFactory.getMarshaller(object);
        if (marshaller == null) {
            throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName());
        }
        final Element element = marshaller.marshall(object);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");

        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (final Exception e) {
        throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e);
    }
}
 
Example #2
Source File: AccessFilter.java    From OpenSAML-ref-project-demo-v3 with Apache License 2.0 6 votes vote down vote up
private AuthnRequest buildAuthnRequest() {
    AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
    //请求时间:该对象创建的时间,以判断其时效性
    authnRequest.setIssueInstant(new DateTime());
    //目标URL:目标地址,IDP地址
    authnRequest.setDestination(getIPDSSODestination());
    //传输SAML断言所需要的绑定:也就是用何种协议使用Artifact来取回真正的认证信息,
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI);
    //SP地址: 也就是SAML断言返回的地址
    authnRequest.setAssertionConsumerServiceURL(getAssertionConsumerEndpoint());
    //请求的ID:为当前请求设置ID,一般为随机数
    authnRequest.setID(OpenSAMLUtils.generateSecureRandomId());
    //Issuer: 发行人信息,也就是SP的ID,一般是SP的URL
    authnRequest.setIssuer(buildIssuer());
    //NameID:IDP对于用户身份的标识;NameID policy是SP关于NameID是如何创建的说明
    authnRequest.setNameIDPolicy(buildNameIdPolicy());
    // 请求认证上下文(requested Authentication Context):
    // SP对于认证的要求,包含SP希望IDP如何验证用户,也就是IDP要依据什么来验证用户身份。
    authnRequest.setRequestedAuthnContext(buildRequestedAuthnContext());

    return authnRequest;
}
 
Example #3
Source File: SamlMetadataUIParserAction.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Gets SP SSO descriptor.
 *
 * @param entityDescriptor the entity descriptor
 * @return the sPSSO descriptor
 */
private SPSSODescriptor getSPSSODescriptor(final EntityDescriptor entityDescriptor) {
    logger.debug("Locating SP SSO descriptor for SAML2 protocol...");
    SPSSODescriptor spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
    if (spssoDescriptor == null) {
        logger.debug("Locating SP SSO descriptor for SAML11 protocol...");
        spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML11P_NS);
    }
    if (spssoDescriptor == null) {
        logger.debug("Locating SP SSO descriptor for SAML1 protocol...");
        spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML10P_NS);
    }
    logger.debug("SP SSO descriptor resolved to be [{}]", spssoDescriptor);
    return spssoDescriptor;
}
 
Example #4
Source File: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Gets the xml signature insert location.
 *
 * @param elem the elem
 * @return the xml signature insert location
 */
private static Node getXmlSignatureInsertLocation(final org.w3c.dom.Element elem) {
    org.w3c.dom.Node insertLocation = null;
    org.w3c.dom.NodeList nodeList = elem.getElementsByTagNameNS(
            SAMLConstants.SAML20P_NS, "Extensions");
    if (nodeList.getLength() != 0) {
        insertLocation = nodeList.item(nodeList.getLength() - 1);
    } else {
        nodeList = elem.getElementsByTagNameNS(SAMLConstants.SAML20P_NS, "Status");
        insertLocation = nodeList.item(nodeList.getLength() - 1);
    }
    return insertLocation;
}
 
Example #5
Source File: GoogleSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
public final QName getSamlObjectQName(final Class objectType) throws RuntimeException {
    try {
        final Field f = objectType.getField(DEFAULT_ELEMENT_LOCAL_NAME_FIELD);
        final String name = f.get(null).toString();

        if (objectType.equals(Response.class) || objectType.equals(Status.class)
                || objectType.equals(StatusCode.class)) {
            return new QName(SAMLConstants.SAML20P_NS, name, "samlp");
        }
        return new QName(SAMLConstants.SAML20_NS, name, XMLConstants.DEFAULT_NS_PREFIX);
    } catch (final Exception e){
        throw new IllegalStateException("Cannot access field " + objectType.getName() + '.' + DEFAULT_ELEMENT_LOCAL_NAME_FIELD);
    }
}
 
Example #6
Source File: AccessFilter.java    From OpenSAML-ref-project-demo-v3 with Apache License 2.0 5 votes vote down vote up
private Endpoint getIPDEndpoint() {
    SingleSignOnService endpoint = OpenSAMLUtils.buildSAMLObject(SingleSignOnService.class);
    endpoint.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    endpoint.setLocation(getIPDSSODestination());

    return endpoint;
}
 
Example #7
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 5 votes vote down vote up
private AuthnRequest buildAuthnRequest() {
    AuthnRequest authnRequest = Helpers.buildSAMLObject(AuthnRequest.class);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setDestination(saml2ConfigService.getSaml2IDPDestination());
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    // Entity ID
    authnRequest.setAssertionConsumerServiceURL(saml2ConfigService.getACSURL());
    authnRequest.setID(Helpers.generateSecureRandomId());
    authnRequest.setIssuer(buildIssuer());
    authnRequest.setNameIDPolicy(buildNameIdPolicy());
    return authnRequest;
}
 
Example #8
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRespondMetadataWithoutAuthentication() throws Exception {
    final AggregatedHttpResponse resp = client.get("/saml/metadata").aggregate().join();
    assertThat(resp.status()).isEqualTo(HttpStatus.OK);
    assertThat(resp.contentType()).isEqualTo(CONTENT_TYPE_SAML_METADATA);

    final EntityDescriptor metadata =
            (EntityDescriptor) deserialize(resp.contentUtf8().getBytes());
    assertThat(metadata).isNotNull();

    final SPSSODescriptor sp = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
    assertThat(sp.isAuthnRequestsSigned()).isTrue();
    assertThat(sp.getWantAssertionsSigned()).isTrue();

    final List<KeyDescriptor> kd = sp.getKeyDescriptors();
    assertThat(kd.get(0).getUse().name()).isEqualToIgnoringCase("signing");
    assertThat(kd.get(1).getUse().name()).isEqualToIgnoringCase("encryption");

    final List<SingleLogoutService> slo = sp.getSingleLogoutServices();
    assertThat(slo.get(0).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/slo/post");
    assertThat(slo.get(0).getBinding()).isEqualTo(SAMLConstants.SAML2_POST_BINDING_URI);
    assertThat(slo.get(1).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/slo/redirect");
    assertThat(slo.get(1).getBinding()).isEqualTo(SAMLConstants.SAML2_REDIRECT_BINDING_URI);

    final List<AssertionConsumerService> acs = sp.getAssertionConsumerServices();
    // index 0 (default)
    assertThat(acs.get(0).getIndex()).isEqualTo(0);
    assertThat(acs.get(0).isDefault()).isTrue();
    assertThat(acs.get(0).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/acs/post");
    assertThat(acs.get(0).getBinding()).isEqualTo(SAMLConstants.SAML2_POST_BINDING_URI);
    // index 1
    assertThat(acs.get(1).getIndex()).isEqualTo(1);
    assertThat(acs.get(1).isDefault()).isFalse();
    assertThat(acs.get(1).getLocation())
            .isEqualTo("http://" + spHostname + ':' + rule.httpPort() + "/saml/acs/redirect");
    assertThat(acs.get(1).getBinding()).isEqualTo(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
}
 
Example #9
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());
}
 
Example #10
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void handleSloGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof LogoutRequest)) {
            throw new RuntimeException("Expected LogoutRequest; received: " + messageContext.getMessage());
        }

        LogoutRequest logoutRequest = (LogoutRequest) messageContext.getMessage();

        SAML2HTTPRedirectDeflateSignatureSecurityHandler signatureSecurityHandler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
        SignatureValidationParameters validationParams = new SignatureValidationParameters();
        SecurityParametersContext securityParametersContext = messageContext
                .getSubcontext(SecurityParametersContext.class, true);

        SAMLPeerEntityContext peerEntityContext = messageContext.getSubcontext(SAMLPeerEntityContext.class, true);
        peerEntityContext.setEntityId(idpEntityId);
        peerEntityContext.setRole(org.opensaml.saml.saml2.metadata.SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        SAMLProtocolContext protocolContext = messageContext.getSubcontext(SAMLProtocolContext.class, true);
        protocolContext.setProtocol(SAMLConstants.SAML20P_NS);

        validationParams.setSignatureTrustEngine(buildSignatureTrustEngine(this.spSignatureCertificate));
        securityParametersContext.setSignatureValidationParameters(validationParams);
        signatureSecurityHandler.setHttpServletRequest(httpServletRequest);
        signatureSecurityHandler.initialize();
        signatureSecurityHandler.invoke(messageContext);

        if (!this.authenticateUser.equals(logoutRequest.getNameID().getValue())) {
            throw new RuntimeException("Unexpected NameID in LogoutRequest: " + logoutRequest);
        }

    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException
            | MessageHandlerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
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 #12
Source File: SAMLBatchUnitTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testBatchSAMLTokens() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = SAMLBatchUnitTest.class.getResource("cxf-client-unit.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    String wsdlLocation =
        "https://localhost:" + test.getStsPort() + "/SecurityTokenService/Transport?wsdl";

    List<BatchRequest> requestList = new ArrayList<>();
    BatchRequest request = new BatchRequest();
    request.setAppliesTo("https://localhost:8081/doubleit/services/doubleittransportsaml1");
    request.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1");
    request.setKeyType("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer");
    requestList.add(request);

    request = new BatchRequest();
    request.setAppliesTo("https://localhost:8081/doubleit/services/doubleittransportsaml2");
    request.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
    request.setKeyType("http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer");
    requestList.add(request);

    String action = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/BatchIssue";
    String requestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/BatchIssue";
    String port = "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port";

    // Request the token
    List<SecurityToken> tokens =
        requestSecurityTokens(bus, wsdlLocation, requestList, action, requestType, port);
    assertTrue(tokens != null && tokens.size() == 2);

    assertEquals("Assertion", tokens.get(0).getToken().getLocalName());
    assertEquals(tokens.get(0).getToken().getNamespaceURI(), SAMLConstants.SAML1_NS);
    assertEquals("Assertion", tokens.get(1).getToken().getLocalName());
    assertEquals(tokens.get(1).getToken().getNamespaceURI(), SAMLConstants.SAML20_NS);

    // Now validate the tokens
    requestList.get(0).setValidateTarget(tokens.get(0).getToken());
    requestList.get(0).setTokenType(STSUtils.WST_NS_05_12 + "/RSTR/Status");
    requestList.get(1).setValidateTarget(tokens.get(1).getToken());
    requestList.get(1).setTokenType(STSUtils.WST_NS_05_12 + "/RSTR/Status");
    action = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/BatchValidate";
    requestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/BatchValidate";
    port = "{http://docs.oasis-open.org/ws-sx/ws-trust/200512/}Transport_Port2";

    validateSecurityTokens(bus, wsdlLocation, requestList, action, requestType, port);

    bus.shutdown(true);
}
 
Example #13
Source File: SAMLSSORelyingPartyObject.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Validate the saml response and its contained assertion-check the response element count and assertion count
 * is 1 and check the assertion validity period
 *
 * @param cx
 * @param thisObj
 * @param args
 * @param funObj
 * @return
 * @throws Exception
 */
public static boolean jsFunction_validateSAMLResponseSchema(Context cx, Scriptable thisObj,
                                                            Object[] args,
                                                            Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. The SAML response is missing.");
    }

    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    String encoded = getSSOSamlEncodingProperty(relyingPartyObject);
    boolean isEncoded = true;
    if (encoded != null) {
        try {
            isEncoded = Boolean.parseBoolean(encoded);
        } catch (Exception e) {
            throw new ScriptException("Invalid property value found for " +
                    "" + SSOConstants.SAML_ENCODED + " " + encoded);
        }
    }

    String decodedString = isEncoded ? Util.decode((String) args[0]) : (String) args[0];
    XMLObject samlObject = Util.unmarshall(decodedString);

    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;

        // Check for duplicate saml:Response
        NodeList list = samlResponse.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20P_NS, "Response");
        if (list.getLength() > 0) {
            log.error("Invalid schema for the SAML2 response.");
            return false;
        }

        //Check for duplicate saml:assertions
        NodeList assertionList = samlResponse.getDOM().getElementsByTagNameNS(SAMLConstants.SAML20_NS, "Assertion");
        if (assertionList == null || assertionList.getLength() > 1) {
            log.error("Invalid schema for the SAML2 response. Invalid number of assertions  detected.");
            return false;
        }
        return true;

    }
    return false;
}
 
Example #14
Source File: SAML2IdPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
private List<SAML2IdPTO> importIdPs(final InputStream input) throws Exception {
    List<EntityDescriptor> idpEntityDescriptors = new ArrayList<>();

    Element root = OpenSAMLUtil.getParserPool().parse(new InputStreamReader(input)).getDocumentElement();
    if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom(root));
    } else if (SAMLConstants.SAML20MD_NS.equals(root.getNamespaceURI())
            && EntitiesDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(root.getLocalName())) {

        NodeList children = root.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if (SAMLConstants.SAML20MD_NS.equals(child.getNamespaceURI())
                    && EntityDescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(child.getLocalName())) {

                NodeList descendants = child.getChildNodes();
                for (int j = 0; j < descendants.getLength(); j++) {
                    Node descendant = descendants.item(j);
                    if (SAMLConstants.SAML20MD_NS.equals(descendant.getNamespaceURI())
                            && IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME.equals(descendant.getLocalName())) {

                        idpEntityDescriptors.add((EntityDescriptor) OpenSAMLUtil.fromDom((Element) child));
                    }
                }
            }
        }
    }

    List<SAML2IdPTO> result = new ArrayList<>(idpEntityDescriptors.size());
    for (EntityDescriptor idpEntityDescriptor : idpEntityDescriptors) {
        SAML2IdPTO idpTO = new SAML2IdPTO();
        idpTO.setEntityID(idpEntityDescriptor.getEntityID());
        idpTO.setName(idpEntityDescriptor.getEntityID());
        idpTO.setUseDeflateEncoding(false);

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            SAML2ReaderWriter.write(new OutputStreamWriter(baos), idpEntityDescriptor, false);
            idpTO.setMetadata(Base64.getEncoder().encodeToString(baos.toByteArray()));
        }

        ItemTO connObjectKeyItem = new ItemTO();
        connObjectKeyItem.setIntAttrName("username");
        connObjectKeyItem.setExtAttrName(NameID.DEFAULT_ELEMENT_LOCAL_NAME);
        idpTO.setConnObjectKeyItem(connObjectKeyItem);

        SAML2IdPEntity idp = cache.put(idpEntityDescriptor, idpTO);
        if (idp.getSSOLocation(SAML2BindingType.POST) != null) {
            idpTO.setBindingType(SAML2BindingType.POST);
        } else if (idp.getSSOLocation(SAML2BindingType.REDIRECT) != null) {
            idpTO.setBindingType(SAML2BindingType.REDIRECT);
        } else {
            throw new IllegalArgumentException("Neither POST nor REDIRECT artifacts supported by " + idp.getId());
        }

        result.add(idpTO);
    }

    return result;
}
 
Example #15
Source File: SAML2SPLogic.java    From syncope with Apache License 2.0 4 votes vote down vote up
@PreAuthorize("isAuthenticated()")
public void getMetadata(final String spEntityID, final String urlContext, final OutputStream os) {
    check();

    try {
        EntityDescriptor spEntityDescriptor = new EntityDescriptorBuilder().buildObject();
        spEntityDescriptor.setEntityID(spEntityID);

        SPSSODescriptor spSSODescriptor = new SPSSODescriptorBuilder().buildObject();
        spSSODescriptor.setWantAssertionsSigned(true);
        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        keyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();
        keyInfoGenerator.generate(loader.getCredential());

        KeyDescriptor keyDescriptor = new KeyDescriptorBuilder().buildObject();
        keyDescriptor.setKeyInfo(keyInfoGenerator.generate(loader.getCredential()));
        spSSODescriptor.getKeyDescriptors().add(keyDescriptor);

        NameIDFormat nameIDFormat = new NameIDFormatBuilder().buildObject();
        nameIDFormat.setFormat(NameIDType.PERSISTENT);
        spSSODescriptor.getNameIDFormats().add(nameIDFormat);
        nameIDFormat = new NameIDFormatBuilder().buildObject();
        nameIDFormat.setFormat(NameIDType.TRANSIENT);
        spSSODescriptor.getNameIDFormats().add(nameIDFormat);

        for (SAML2BindingType bindingType : SAML2BindingType.values()) {
            AssertionConsumerService assertionConsumerService = new AssertionConsumerServiceBuilder().buildObject();
            assertionConsumerService.setIndex(bindingType.ordinal());
            assertionConsumerService.setBinding(bindingType.getUri());
            assertionConsumerService.setLocation(getAssertionConsumerURL(spEntityID, urlContext));
            spSSODescriptor.getAssertionConsumerServices().add(assertionConsumerService);
            spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

            String sloUrl = spEntityID + urlContext + "/logout";
            validateUrl(sloUrl);

            SingleLogoutService singleLogoutService = new SingleLogoutServiceBuilder().buildObject();
            singleLogoutService.setBinding(bindingType.getUri());
            singleLogoutService.setLocation(sloUrl);
            singleLogoutService.setResponseLocation(sloUrl);
            spSSODescriptor.getSingleLogoutServices().add(singleLogoutService);
        }

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);
        saml2rw.sign(spEntityDescriptor);

        SAML2ReaderWriter.write(new OutputStreamWriter(os), spEntityDescriptor, true);
    } catch (Exception e) {
        LOG.error("While getting SP metadata", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
}
 
Example #16
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void loginResponseWrappingAttack() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    // Get a valid login request for the Fediz realm
    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);
    SAML2RequestTO loginRequest = saml2Service.createLoginRequest(ADDRESS, "urn:org:apache:cxf:fediz:idp:realm-A");
    assertNotNull(loginRequest);

    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");
    response.setRelayState(loginRequest.getRelayState());

    // Create a SAML Response using WSS4J
    JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
    String inResponseTo = relayState.getJwtClaims().getSubject();

    org.opensaml.saml.saml2.core.Response samlResponse = createResponse(inResponseTo);

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    assertNotNull(responseElement);
    doc.appendChild(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(WSConstants.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("verdi");

    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 after the other assertion
    responseElement.insertBefore(clonedAssertion, null);

    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsigned Assertion");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}
 
Example #17
Source File: SamlMetadataServiceFunction.java    From armeria with Apache License 2.0 4 votes vote down vote up
private EntityDescriptor buildMetadataEntityDescriptorElement(
        String defaultHostname, SamlPortConfig portConfig) {
    final EntityDescriptor entityDescriptor = build(EntityDescriptor.DEFAULT_ELEMENT_NAME);
    entityDescriptor.setEntityID(entityId);

    final SPSSODescriptor spSsoDescriptor = build(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    spSsoDescriptor.setAuthnRequestsSigned(true);
    spSsoDescriptor.setWantAssertionsSigned(true);
    spSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

    final List<String> nameIdFormats = idpConfigs.values().stream()
                                                 .map(p -> p.nameIdPolicy().format())
                                                 .distinct()
                                                 .map(SamlNameIdFormat::urn)
                                                 .collect(Collectors.toList());
    spSsoDescriptor.getNameIDFormats().addAll(buildNameIdFormatElements(nameIdFormats));

    final List<SingleLogoutService> sloList = spSsoDescriptor.getSingleLogoutServices();
    singleLogoutEndpoints.forEach(endpoint -> {
        final SingleLogoutService slo = build(SingleLogoutService.DEFAULT_ELEMENT_NAME);
        slo.setBinding(endpoint.bindingProtocol().urn());
        slo.setLocation(endpoint.toUriString(portConfig.scheme().uriText(),
                                             defaultHostname,
                                             portConfig.port()));
        sloList.add(slo);
    });

    int acsIndex = 0;
    final List<AssertionConsumerService> services = spSsoDescriptor.getAssertionConsumerServices();
    for (final SamlAssertionConsumerConfig acs : assertionConsumerConfigs) {
        services.add(buildAssertionConsumerServiceElement(acs, portConfig, defaultHostname, acsIndex++));
    }

    final X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    keyInfoGeneratorFactory.setEmitEntityCertificate(true);
    keyInfoGeneratorFactory.setEmitEntityCertificateChain(true);
    final KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

    try {
        spSsoDescriptor.getKeyDescriptors().add(
                buildKeyDescriptorElement(UsageType.SIGNING,
                                          keyInfoGenerator.generate(signingCredential)));
        spSsoDescriptor.getKeyDescriptors().add(
                buildKeyDescriptorElement(UsageType.ENCRYPTION,
                                          keyInfoGenerator.generate(encryptionCredential)));
    } catch (SecurityException e) {
        throw new SamlException("failed to generate KeyInfo element", e);
    }

    entityDescriptor.getRoleDescriptors().add(spSsoDescriptor);
    return entityDescriptor;
}
 
Example #18
Source File: AuthenticationHandlerSAML2.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
private Endpoint getIPDEndpoint() {
    SingleSignOnService endpoint = Helpers.buildSAMLObject(SingleSignOnService.class);
    endpoint.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    endpoint.setLocation(saml2ConfigService.getSaml2IDPDestination());
    return endpoint;
}
 
Example #19
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
private String createMetadata() {
    try {
        EntityDescriptor idpEntityDescriptor = createSamlElement(EntityDescriptor.class);
        idpEntityDescriptor.setEntityID(idpEntityId);

        IDPSSODescriptor idpSsoDescriptor = createSamlElement(IDPSSODescriptor.class);
        idpEntityDescriptor.getRoleDescriptors().add(idpSsoDescriptor);

        idpSsoDescriptor.setWantAuthnRequestsSigned(wantAuthnRequestsSigned);
        idpSsoDescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        SingleLogoutService redirectSingleLogoutService = createSamlElement(SingleLogoutService.class);
        idpSsoDescriptor.getSingleLogoutServices().add(redirectSingleLogoutService);

        redirectSingleLogoutService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
        redirectSingleLogoutService.setLocation(getSamlSloUri());

        idpSsoDescriptor.getNameIDFormats()
                .add(createNameIDFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"));

        SingleSignOnService redirectSingleSignOnService = createSamlElement(SingleSignOnService.class);
        idpSsoDescriptor.getSingleSignOnServices().add(redirectSingleSignOnService);

        redirectSingleSignOnService.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
        redirectSingleSignOnService.setLocation(getSamlSsoUri());

        X509KeyInfoGeneratorFactory keyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
        keyInfoGeneratorFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoGeneratorFactory.newInstance();

        KeyDescriptor signingKeyDescriptor = createSamlElement(KeyDescriptor.class);
        idpSsoDescriptor.getKeyDescriptors().add(signingKeyDescriptor);

        signingKeyDescriptor.setUse(UsageType.SIGNING);

        signingKeyDescriptor
                .setKeyInfo(keyInfoGenerator.generate(new BasicX509Credential(this.signingCertificate)));

        return marshallSamlXml(idpEntityDescriptor);
    } catch (org.opensaml.security.SecurityException e) {
        throw new RuntimeException(e);
    }
}