Search in sources :

Example 1 with ParsingException

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

the class AbstractSamlAuthenticator method initializeKeycloak.

@SuppressWarnings("UseSpecificCatch")
public void initializeKeycloak() {
    ServletContext theServletContext = null;
    ContextHandler.Context currentContext = ContextHandler.getCurrentContext();
    if (currentContext != null) {
        String contextPath = currentContext.getContextPath();
        if ("".equals(contextPath)) {
            // This could be the case in osgi environment when deploying apps through pax whiteboard extension.
            theServletContext = currentContext;
        } else {
            theServletContext = currentContext.getContext(contextPath);
        }
    }
    // Jetty 9.1.x servlet context will be null :(
    if (configResolver == null && theServletContext != null) {
        String configResolverClass = theServletContext.getInitParameter("keycloak.config.resolver");
        if (configResolverClass != null) {
            try {
                configResolver = (SamlConfigResolver) ContextHandler.getCurrentContext().getClassLoader().loadClass(configResolverClass).newInstance();
                log.infov("Using {0} to resolve Keycloak configuration on a per-request basis.", configResolverClass);
            } catch (Exception ex) {
                log.infov("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", new Object[] { configResolverClass, ex.getMessage() });
            }
        }
    }
    if (configResolver != null) {
    // deploymentContext = new AdapterDeploymentContext(configResolver);
    } else if (theServletContext != null) {
        InputStream configInputStream = getConfigInputStream(theServletContext);
        if (configInputStream != null) {
            final ServletContext servletContext = theServletContext;
            SamlDeployment deployment = null;
            try {
                deployment = new DeploymentBuilder().build(configInputStream, new ResourceLoader() {

                    @Override
                    public InputStream getResourceAsStream(String resource) {
                        return servletContext.getResourceAsStream(resource);
                    }
                });
            } catch (ParsingException e) {
                throw new RuntimeException(e);
            }
            deploymentContext = new SamlDeploymentContext(deployment);
        }
    }
    if (theServletContext != null)
        theServletContext.setAttribute(SamlDeploymentContext.class.getName(), deploymentContext);
}
Also used : ResourceLoader(org.keycloak.adapters.saml.config.parsers.ResourceLoader) SamlDeploymentContext(org.keycloak.adapters.saml.SamlDeploymentContext) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SamlDeployment(org.keycloak.adapters.saml.SamlDeployment) ServletException(javax.servlet.ServletException) FileNotFoundException(java.io.FileNotFoundException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) ServletContext(javax.servlet.ServletContext) DeploymentBuilder(org.keycloak.adapters.saml.config.parsers.DeploymentBuilder)

Example 2 with ParsingException

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

the class DeploymentBuilder method build.

public SamlDeployment build(InputStream xml, ResourceLoader resourceLoader) throws ParsingException {
    DefaultSamlDeployment deployment = new DefaultSamlDeployment();
    DefaultSamlDeployment.DefaultIDP defaultIDP = new DefaultSamlDeployment.DefaultIDP();
    DefaultSamlDeployment.DefaultSingleSignOnService sso = new DefaultSamlDeployment.DefaultSingleSignOnService();
    DefaultSamlDeployment.DefaultSingleLogoutService slo = new DefaultSamlDeployment.DefaultSingleLogoutService();
    defaultIDP.setSingleSignOnService(sso);
    defaultIDP.setSingleLogoutService(slo);
    KeycloakSamlAdapter adapter = (KeycloakSamlAdapter) KeycloakSamlAdapterParser.getInstance().parse(xml);
    SP sp = adapter.getSps().get(0);
    deployment.setConfigured(true);
    deployment.setEntityID(sp.getEntityID());
    try {
        URI.create(sp.getEntityID());
    } catch (IllegalArgumentException ex) {
        log.warnf("Entity ID is not an URI, assertion that restricts audience will fail. Update Entity ID to be URI.", sp.getEntityID());
    }
    deployment.setForceAuthentication(sp.isForceAuthentication());
    deployment.setIsPassive(sp.isIsPassive());
    deployment.setNameIDPolicyFormat(sp.getNameIDPolicyFormat());
    deployment.setLogoutPage(sp.getLogoutPage());
    IDP idp = sp.getIdp();
    deployment.setSignatureCanonicalizationMethod(idp.getSignatureCanonicalizationMethod());
    deployment.setAutodetectBearerOnly(sp.isAutodetectBearerOnly());
    deployment.setKeepDOMAssertion(sp.isKeepDOMAssertion());
    deployment.setSignatureAlgorithm(SignatureAlgorithm.RSA_SHA256);
    if (idp.getSignatureAlgorithm() != null) {
        deployment.setSignatureAlgorithm(SignatureAlgorithm.valueOf(idp.getSignatureAlgorithm()));
    }
    if (sp.getPrincipalNameMapping() != null) {
        SamlDeployment.PrincipalNamePolicy policy = SamlDeployment.PrincipalNamePolicy.valueOf(sp.getPrincipalNameMapping().getPolicy());
        deployment.setPrincipalNamePolicy(policy);
        deployment.setPrincipalAttributeName(sp.getPrincipalNameMapping().getAttributeName());
    }
    deployment.setRoleAttributeNames(sp.getRoleAttributes());
    if (sp.getRoleAttributes() == null) {
        Set<String> roles = new HashSet<>();
        roles.add("Role");
        deployment.setRoleAttributeNames(roles);
    }
    if (sp.getSslPolicy() != null) {
        SslRequired ssl = SslRequired.valueOf(sp.getSslPolicy());
        deployment.setSslRequired(ssl);
    }
    if (sp.getKeys() != null) {
        for (Key key : sp.getKeys()) {
            if (key.isSigning()) {
                PrivateKey privateKey = null;
                PublicKey publicKey = null;
                if (key.getKeystore() != null) {
                    KeyStore keyStore = loadKeystore(resourceLoader, key);
                    Certificate cert = null;
                    try {
                        log.debugf("Try to load key [%s]", key.getKeystore().getCertificateAlias());
                        cert = keyStore.getCertificate(key.getKeystore().getCertificateAlias());
                        if (cert == null) {
                            log.errorf("Key alias %s is not found into keystore", key.getKeystore().getCertificateAlias());
                        }
                        privateKey = (PrivateKey) keyStore.getKey(key.getKeystore().getPrivateKeyAlias(), key.getKeystore().getPrivateKeyPassword().toCharArray());
                        publicKey = cert.getPublicKey();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    if (key.getPrivateKeyPem() == null) {
                        throw new RuntimeException("SP signing key must have a PrivateKey defined");
                    }
                    try {
                        privateKey = PemUtils.decodePrivateKey(key.getPrivateKeyPem().trim());
                        if (key.getPublicKeyPem() == null && key.getCertificatePem() == null) {
                            throw new RuntimeException("Sp signing key must have a PublicKey or Certificate defined");
                        }
                        publicKey = getPublicKeyFromPem(key);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
                KeyPair keyPair = new KeyPair(publicKey, privateKey);
                deployment.setSigningKeyPair(keyPair);
            }
            if (key.isEncryption()) {
                if (key.getKeystore() != null) {
                    KeyStore keyStore = loadKeystore(resourceLoader, key);
                    try {
                        PrivateKey privateKey = (PrivateKey) keyStore.getKey(key.getKeystore().getPrivateKeyAlias(), key.getKeystore().getPrivateKeyPassword().toCharArray());
                        deployment.setDecryptionKey(privateKey);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    if (key.getPrivateKeyPem() == null) {
                        throw new RuntimeException("SP signing key must have a PrivateKey defined");
                    }
                    try {
                        PrivateKey privateKey = PemUtils.decodePrivateKey(key.getPrivateKeyPem().trim());
                        deployment.setDecryptionKey(privateKey);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
    deployment.setIdp(defaultIDP);
    defaultIDP.setEntityID(idp.getEntityID());
    sso.setRequestBinding(SamlDeployment.Binding.parseBinding(idp.getSingleSignOnService().getRequestBinding()));
    sso.setRequestBindingUrl(idp.getSingleSignOnService().getBindingUrl());
    if (idp.getSingleSignOnService().getResponseBinding() != null) {
        sso.setResponseBinding(SamlDeployment.Binding.parseBinding(idp.getSingleSignOnService().getResponseBinding()));
    }
    if (idp.getAllowedClockSkew() != null) {
        defaultIDP.setAllowedClockSkew(convertClockSkewInMillis(idp.getAllowedClockSkew(), idp.getAllowedClockSkewUnit()));
    }
    if (idp.getSingleSignOnService().getAssertionConsumerServiceUrl() != null) {
        if (!idp.getSingleSignOnService().getAssertionConsumerServiceUrl().endsWith("/saml")) {
            throw new RuntimeException("AssertionConsumerServiceUrl must end with \"/saml\".");
        }
        sso.setAssertionConsumerServiceUrl(URI.create(idp.getSingleSignOnService().getAssertionConsumerServiceUrl()));
    }
    sso.setSignRequest(idp.getSingleSignOnService().isSignRequest());
    sso.setValidateResponseSignature(idp.getSingleSignOnService().isValidateResponseSignature());
    sso.setValidateAssertionSignature(idp.getSingleSignOnService().isValidateAssertionSignature());
    slo.setSignRequest(idp.getSingleLogoutService().isSignRequest());
    slo.setSignResponse(idp.getSingleLogoutService().isSignResponse());
    slo.setValidateResponseSignature(idp.getSingleLogoutService().isValidateResponseSignature());
    slo.setValidateRequestSignature(idp.getSingleLogoutService().isValidateRequestSignature());
    slo.setRequestBinding(SamlDeployment.Binding.parseBinding(idp.getSingleLogoutService().getRequestBinding()));
    slo.setResponseBinding(SamlDeployment.Binding.parseBinding(idp.getSingleLogoutService().getResponseBinding()));
    if (slo.getRequestBinding() == SamlDeployment.Binding.POST) {
        slo.setRequestBindingUrl(idp.getSingleLogoutService().getPostBindingUrl());
    } else {
        slo.setRequestBindingUrl(idp.getSingleLogoutService().getRedirectBindingUrl());
    }
    if (slo.getResponseBinding() == SamlDeployment.Binding.POST) {
        slo.setResponseBindingUrl(idp.getSingleLogoutService().getPostBindingUrl());
    } else {
        slo.setResponseBindingUrl(idp.getSingleLogoutService().getRedirectBindingUrl());
    }
    if (idp.getKeys() != null) {
        for (Key key : idp.getKeys()) {
            if (key.isSigning()) {
                processSigningKey(defaultIDP, key, resourceLoader);
            }
        }
    }
    defaultIDP.setMetadataUrl(idp.getMetadataUrl());
    defaultIDP.setClient(new HttpClientBuilder().build(idp.getHttpClientConfig()));
    defaultIDP.refreshKeyLocatorConfiguration();
    // set the role mappings provider.
    deployment.setRoleMappingsProvider(RoleMappingsProviderUtils.bootstrapRoleMappingsProvider(deployment, resourceLoader, sp.getRoleMappingsProviderConfig()));
    return deployment;
}
Also used : PrivateKey(java.security.PrivateKey) SslRequired(org.keycloak.common.enums.SslRequired) DefaultSamlDeployment(org.keycloak.adapters.saml.DefaultSamlDeployment) HttpClientBuilder(org.keycloak.adapters.cloned.HttpClientBuilder) IDP(org.keycloak.adapters.saml.config.IDP) SP(org.keycloak.adapters.saml.config.SP) HashSet(java.util.HashSet) KeyPair(java.security.KeyPair) PublicKey(java.security.PublicKey) DefaultSamlDeployment(org.keycloak.adapters.saml.DefaultSamlDeployment) SamlDeployment(org.keycloak.adapters.saml.SamlDeployment) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) CertificateException(java.security.cert.CertificateException) FileNotFoundException(java.io.FileNotFoundException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) KeycloakSamlAdapter(org.keycloak.adapters.saml.config.KeycloakSamlAdapter) Key(org.keycloak.adapters.saml.config.Key) PublicKey(java.security.PublicKey) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 3 with ParsingException

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

the class SamlDescriptorIDPKeysExtractor method parse.

public MultivaluedHashMap<String, KeyInfo> parse(InputStream stream) throws ParsingException {
    MultivaluedHashMap<String, KeyInfo> res = new MultivaluedHashMap<>();
    try {
        DocumentBuilder builder = DocumentUtil.getDocumentBuilder();
        Document doc = builder.parse(stream);
        XPathExpression expr = xpath.compile("//m:EntityDescriptor/m:IDPSSODescriptor/m:KeyDescriptor");
        NodeList keyDescriptors = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < keyDescriptors.getLength(); i++) {
            Node keyDescriptor = keyDescriptors.item(i);
            Element keyDescriptorEl = (Element) keyDescriptor;
            KeyInfo ki = processKeyDescriptor(keyDescriptorEl);
            if (ki != null) {
                String use = keyDescriptorEl.getAttribute(JBossSAMLConstants.USE.get());
                res.add(use, ki);
            }
        }
    } catch (SAXException | IOException | ParserConfigurationException | MarshalException | XPathExpressionException e) {
        throw new ParsingException("Error parsing SAML descriptor", e);
    }
    return res;
}
Also used : XPathExpression(javax.xml.xpath.XPathExpression) MarshalException(javax.xml.crypto.MarshalException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 4 with ParsingException

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

the class AbstractSamlAuthenticatorValve method keycloakInit.

@SuppressWarnings("UseSpecificCatch")
public void keycloakInit() {
    // 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
    String configResolverClass = context.getServletContext().getInitParameter("keycloak.config.resolver");
    if (configResolverClass != null) {
        try {
            SamlConfigResolver configResolver = (SamlConfigResolver) context.getLoader().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.errorv("The specified resolver {0} could NOT be loaded. Keycloak is unconfigured and will deny all requests. Reason: {1}", configResolverClass, ex.getMessage());
            deploymentContext = new SamlDeploymentContext(new DefaultSamlDeployment());
        }
    } else {
        InputStream is = getConfigInputStream(context);
        final SamlDeployment deployment;
        if (is == null) {
            log.error("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 context.getServletContext().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.");
    }
    context.getServletContext().setAttribute(SamlDeploymentContext.class.getName(), deploymentContext);
    addTokenStoreUpdaters();
}
Also used : ResourceLoader(org.keycloak.adapters.saml.config.parsers.ResourceLoader) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) DeploymentBuilder(org.keycloak.adapters.saml.config.parsers.DeploymentBuilder)

Example 5 with ParsingException

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

the class SamlProtocol method frontchannelLogout.

@Override
public Response frontchannelLogout(UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
    ClientModel client = clientSession.getClient();
    SamlClient samlClient = new SamlClient(client);
    try {
        boolean postBinding = isLogoutPostBindingForClient(clientSession);
        String bindingUri = getLogoutServiceUrl(session, client, postBinding ? SAML_POST_BINDING : SAML_REDIRECT_BINDING, false);
        if (bindingUri == null) {
            logger.warnf("Failed to logout client %s, skipping this client.  Please configure the logout service url in the admin console for your client applications.", client.getClientId());
            return null;
        }
        NodeGenerator[] extensions = new NodeGenerator[] {};
        if (!postBinding) {
            if (samlClient.requiresRealmSignature() && samlClient.addExtensionsElementWithKeyInfo()) {
                KeyManager.ActiveRsaKey keys = session.keys().getActiveRsaKey(realm);
                String keyName = samlClient.getXmlSigKeyInfoKeyNameTransformer().getKeyName(keys.getKid(), keys.getCertificate());
                extensions = new NodeGenerator[] { new KeycloakKeySamlExtensionGenerator(keyName) };
            }
        }
        LogoutRequestType logoutRequest = createLogoutRequest(bindingUri, clientSession, client, extensions);
        JaxrsSAML2BindingBuilder binding = createBindingBuilder(samlClient, "true".equals(clientSession.getNote(JBossSAMLURIConstants.SAML_HTTP_ARTIFACT_BINDING.get())));
        // If this session uses artifact binding, send an artifact instead of the LogoutRequest
        if ("true".equals(clientSession.getNote(JBossSAMLURIConstants.SAML_HTTP_ARTIFACT_BINDING.get())) && useArtifactForLogout(client)) {
            clientSession.setAction(CommonClientSessionModel.Action.LOGGING_OUT.name());
            return buildArtifactAuthenticatedResponse(clientSession, bindingUri, logoutRequest, binding);
        }
        Document samlDocument = SAML2Request.convert(logoutRequest);
        if (postBinding) {
            // This is POST binding, hence KeyID is included in dsig:KeyInfo/dsig:KeyName, no need to add <samlp:Extensions> element
            return binding.postBinding(samlDocument).request(bindingUri);
        } else {
            logger.debug("frontchannel redirect binding");
            return binding.redirectBinding(samlDocument).request(bindingUri);
        }
    } catch (ConfigurationException | ProcessingException | IOException | ParsingException e) {
        throw new RuntimeException(e);
    }
}
Also used : LogoutRequestType(org.keycloak.dom.saml.v2.protocol.LogoutRequestType) IOException(java.io.IOException) KeycloakKeySamlExtensionGenerator(org.keycloak.saml.processing.core.util.KeycloakKeySamlExtensionGenerator) Document(org.w3c.dom.Document) ClientModel(org.keycloak.models.ClientModel) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) KeyManager(org.keycloak.models.KeyManager) NodeGenerator(org.keycloak.saml.SamlProtocolExtensionsAwareBuilder.NodeGenerator) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

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