Search in sources :

Example 21 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class SamlServletExtension method handleDeployment.

@Override
@SuppressWarnings("UseSpecificCatch")
public void handleDeployment(DeploymentInfo deploymentInfo, final ServletContext servletContext) {
    if (!isAuthenticationMechanismPresent(deploymentInfo, "KEYCLOAK-SAML")) {
        log.debug("auth-method is not keycloak saml!");
        return;
    }
    log.debug("SamlServletException initialization");
    // Possible scenarios:
    // 1) The deployment has a keycloak.config.resolver specified and it exists:
    // Outcome: adapter uses the resolver
    // 2) The deployment has a keycloak.config.resolver and isn't valid (doesn't exist, isn't a resolver, ...) :
    // Outcome: adapter is left unconfigured
    // 3) The deployment doesn't have a keycloak.config.resolver , but has a keycloak.json (or equivalent)
    // Outcome: adapter uses it
    // 4) The deployment doesn't have a keycloak.config.resolver nor keycloak.json (or equivalent)
    // Outcome: adapter is left unconfigured
    SamlConfigResolver configResolver;
    String configResolverClass = servletContext.getInitParameter("keycloak.config.resolver");
    SamlDeploymentContext deploymentContext = null;
    if (configResolverClass != null) {
        try {
            configResolver = (SamlConfigResolver) deploymentInfo.getClassLoader().loadClass(configResolverClass).newInstance();
            deploymentContext = new SamlDeploymentContext(configResolver);
            log.infov("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
        } catch (Exception ex) {
            log.warn("The specified resolver " + configResolverClass + " could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: " + ex.getMessage());
            deploymentContext = new SamlDeploymentContext(new DefaultSamlDeployment());
        }
    } else {
        InputStream is = getConfigInputStream(servletContext);
        final SamlDeployment deployment;
        if (is == null) {
            log.warn("No adapter configuration.  Keycloak is unconfigured and will deny all requests.");
            deployment = new DefaultSamlDeployment();
        } else {
            try {
                ResourceLoader loader = new ResourceLoader() {

                    @Override
                    public InputStream getResourceAsStream(String resource) {
                        return servletContext.getResourceAsStream(resource);
                    }
                };
                deployment = new DeploymentBuilder().build(is, loader);
            } catch (ParsingException e) {
                throw new RuntimeException(e);
            }
        }
        deploymentContext = new SamlDeploymentContext(deployment);
        log.debug("Keycloak is using a per-deployment configuration.");
    }
    servletContext.setAttribute(SamlDeploymentContext.class.getName(), deploymentContext);
    UndertowUserSessionManagement userSessionManagement = new UndertowUserSessionManagement();
    final ServletSamlAuthMech mech = createAuthMech(deploymentInfo, deploymentContext, userSessionManagement);
    mech.addTokenStoreUpdaters(deploymentInfo);
    // setup handlers
    deploymentInfo.addAuthenticationMechanism("KEYCLOAK-SAML", new AuthenticationMechanismFactory() {

        @Override
        public AuthenticationMechanism create(String s, FormParserFactory formParserFactory, Map<String, String> stringStringMap) {
            return mech;
        }
    });
    // authentication
    deploymentInfo.setIdentityManager(new IdentityManager() {

        @Override
        public Account verify(Account account) {
            return account;
        }

        @Override
        public Account verify(String id, Credential credential) {
            throw new IllegalStateException("Should never be called in Keycloak flow");
        }

        @Override
        public Account verify(Credential credential) {
            throw new IllegalStateException("Should never be called in Keycloak flow");
        }
    });
    ServletSessionConfig cookieConfig = deploymentInfo.getServletSessionConfig();
    if (cookieConfig == null) {
        cookieConfig = new ServletSessionConfig();
    }
    if (cookieConfig.getPath() == null) {
        log.debug("Setting jsession cookie path to: " + deploymentInfo.getContextPath());
        cookieConfig.setPath(deploymentInfo.getContextPath());
        deploymentInfo.setServletSessionConfig(cookieConfig);
    }
    addEndpointConstraint(deploymentInfo);
    ChangeSessionId.turnOffChangeSessionIdOnLogin(deploymentInfo);
}
Also used : SamlDeploymentContext(org.keycloak.adapters.saml.SamlDeploymentContext) ResourceLoader(org.keycloak.adapters.saml.config.parsers.ResourceLoader) Account(io.undertow.security.idm.Account) IdentityManager(io.undertow.security.idm.IdentityManager) Credential(io.undertow.security.idm.Credential) DefaultSamlDeployment(org.keycloak.adapters.saml.DefaultSamlDeployment) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AuthenticationMechanism(io.undertow.security.api.AuthenticationMechanism) DefaultSamlDeployment(org.keycloak.adapters.saml.DefaultSamlDeployment) SamlDeployment(org.keycloak.adapters.saml.SamlDeployment) ServletSessionConfig(io.undertow.servlet.api.ServletSessionConfig) FileNotFoundException(java.io.FileNotFoundException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) FormParserFactory(io.undertow.server.handlers.form.FormParserFactory) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) UndertowUserSessionManagement(org.keycloak.adapters.undertow.UndertowUserSessionManagement) SamlConfigResolver(org.keycloak.adapters.saml.SamlConfigResolver) AuthenticationMechanismFactory(io.undertow.security.api.AuthenticationMechanismFactory) DeploymentBuilder(org.keycloak.adapters.saml.config.parsers.DeploymentBuilder)

Example 22 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class StaxParserUtilTest method testXMLBombAttack.

@Test
public void testXMLBombAttack() throws XMLStreamException {
    String xml = "<?xml version=\"1.0\"?>" + "<!DOCTYPE lolz [" + " <!ENTITY lol \"lol\">" + " <!ELEMENT lolz (#PCDATA)>" + " <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">" + " <!ENTITY lol2 \"&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;\">" + " <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">" + " <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\">" + " <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\">" + " <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\">" + " <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\">" + " <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\">" + " <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">" + "]>" + "<lolz>&lol9;</lolz>";
    XMLEventReader reader = StaxParserUtil.getXMLEventReader(IOUtils.toInputStream(xml, Charset.defaultCharset()));
    // <?xml version="1.0"?>
    reader.nextEvent();
    // <!DOCTYPE lolz [ ........ ]>
    reader.nextEvent();
    try {
        StaxParserUtil.getDOMElement(reader);
    } catch (ParsingException exception) {
        // DTD should be disabled for SAML Parser, therefore this should fail with following error message
        assertThat("", exception.getMessage(), containsString("The entity \"lol9\" was referenced, but not declared"));
    }
}
Also used : ParsingException(org.keycloak.saml.common.exceptions.ParsingException) XMLEventReader(javax.xml.stream.XMLEventReader) Test(org.junit.Test)

Example 23 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class SAMLDataMarshaller method deserialize.

@Override
public <T> T deserialize(String serialized, Class<T> clazz) {
    if (clazz.getName().startsWith("org.keycloak.dom.saml")) {
        String xmlString = serialized;
        try {
            if (clazz.equals(ResponseType.class) || clazz.equals(AssertionType.class) || clazz.equals(AuthnStatementType.class) || clazz.equals(ArtifactResponseType.class)) {
                byte[] bytes = xmlString.getBytes(GeneralConstants.SAML_CHARSET);
                InputStream is = new ByteArrayInputStream(bytes);
                Object respType = SAMLParser.getInstance().parse(is);
                return clazz.cast(respType);
            } else {
                throw new IllegalArgumentException("Don't know how to deserialize object of type " + clazz.getName());
            }
        } catch (ParsingException pe) {
            throw new RuntimeException(pe);
        }
    } else {
        return super.deserialize(serialized, clazz);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) ArtifactResponseType(org.keycloak.dom.saml.v2.protocol.ArtifactResponseType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) ArtifactResponseType(org.keycloak.dom.saml.v2.protocol.ArtifactResponseType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType)

Example 24 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class SamlSPFacade method getSamlAuthnRequest.

/*
    * https://idp.ssocircle.com/sso/toolbox/samlEncode.jsp
    *
    * returns (https instead of http in case ssl is required)
    * 
    * <samlp:AuthnRequest 
    *     xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" 
    *     xmlns="urn:oasis:names:tc:SAML:2.0:assertion" 
    *     AssertionConsumerServiceURL="http://localhost:8280/employee/" 
    *     Destination="http://localhost:8180/auth/realms/demo/protocol/saml" 
    *     ForceAuthn="false" 
    *     ID="ID_4d8e5ce2-7206-472b-a897-2d837090c005" 
    *     IsPassive="false" 
    *     IssueInstant="2015-03-06T22:22:17.854Z" 
    *     ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" 
    *     Version="2.0"> 
    *         <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">saml-employee</saml:Issuer> 
    *         <samlp:NameIDPolicy AllowCreate="true" Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"/> 
    * </samlp:AuthnRequest> 
    */
private URI getSamlAuthnRequest(HttpServletRequest req) {
    try {
        BaseSAML2BindingBuilder binding = new BaseSAML2BindingBuilder();
        SAML2Request samlReq = new SAML2Request();
        String appServerUrl = ServletTestUtils.getUrlBase() + "/employee/";
        String authServerUrl = ServletTestUtils.getAuthServerUrlBase() + "/auth/realms/demo/protocol/saml";
        AuthnRequestType loginReq;
        loginReq = samlReq.createAuthnRequestType(UUID.randomUUID().toString(), appServerUrl, authServerUrl, "http://localhost:8280/employee/");
        loginReq.getNameIDPolicy().setFormat(JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.getUri());
        return binding.redirectBinding(SAML2Request.convert(loginReq)).requestURI(authServerUrl);
    } catch (IOException | ConfigurationException | ParsingException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) BaseSAML2BindingBuilder(org.keycloak.saml.BaseSAML2BindingBuilder) IOException(java.io.IOException) SAML2Request(org.keycloak.saml.processing.api.saml.v2.request.SAML2Request) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Example 25 with ParsingException

use of org.keycloak.saml.common.exceptions.ParsingException in project keycloak by keycloak.

the class TransformerUtil method transform.

public static void transform(JAXBContext context, JAXBElement<?> jaxb, Result result) throws ParsingException {
    try {
        Transformer transformer = getTransformer();
        JAXBSource jaxbSource = new JAXBSource(context, jaxb);
        transformer.transform(jaxbSource, result);
    } catch (Exception e) {
        throw logger.parserError(e);
    }
}
Also used : Transformer(javax.xml.transform.Transformer) JAXBSource(javax.xml.bind.util.JAXBSource) TransformerException(javax.xml.transform.TransformerException) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException)

Aggregations

ParsingException (org.keycloak.saml.common.exceptions.ParsingException)31 ConfigurationException (org.keycloak.saml.common.exceptions.ConfigurationException)14 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)14 InputStream (java.io.InputStream)11 Document (org.w3c.dom.Document)10 IOException (java.io.IOException)9 ByteArrayInputStream (java.io.ByteArrayInputStream)7 DeploymentBuilder (org.keycloak.adapters.saml.config.parsers.DeploymentBuilder)7 ResourceLoader (org.keycloak.adapters.saml.config.parsers.ResourceLoader)7 FileNotFoundException (java.io.FileNotFoundException)6 SamlDeployment (org.keycloak.adapters.saml.SamlDeployment)6 FileInputStream (java.io.FileInputStream)5 AuthnRequestType (org.keycloak.dom.saml.v2.protocol.AuthnRequestType)5 Test (org.junit.Test)4 DefaultSamlDeployment (org.keycloak.adapters.saml.DefaultSamlDeployment)4 SamlDeploymentContext (org.keycloak.adapters.saml.SamlDeploymentContext)4 SAML2Request (org.keycloak.saml.processing.api.saml.v2.request.SAML2Request)4 Element (org.w3c.dom.Element)4 HashMap (java.util.HashMap)3 ServletException (javax.servlet.ServletException)3