Search in sources :

Example 1 with AliasServiceException

use of org.apache.knox.gateway.services.security.AliasServiceException in project knox by apache.

the class Pac4jDispatcherFilter method init.

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // JWT service
    final ServletContext context = filterConfig.getServletContext();
    CryptoService cryptoService = null;
    String clusterName = null;
    if (context != null) {
        GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
        clusterName = (String) context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
        if (services != null) {
            keystoreService = (KeystoreService) services.getService(GatewayServices.KEYSTORE_SERVICE);
            cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
            aliasService = (AliasService) services.getService(GatewayServices.ALIAS_SERVICE);
            masterService = (MasterService) services.getService("MasterService");
        }
    }
    // crypto service, alias service and cluster name are mandatory
    if (cryptoService == null || aliasService == null || clusterName == null) {
        log.cryptoServiceAndAliasServiceAndClusterNameRequired();
        throw new ServletException("The crypto service, alias service and cluster name are required.");
    }
    try {
        aliasService.getPasswordFromAliasForCluster(clusterName, KnoxSessionStore.PAC4J_PASSWORD, true);
    } catch (AliasServiceException e) {
        log.unableToGenerateAPasswordForEncryption(e);
        throw new ServletException("Unable to generate a password for encryption.");
    }
    // url to SSO authentication provider
    String pac4jCallbackUrl = filterConfig.getInitParameter(PAC4J_CALLBACK_URL);
    if (pac4jCallbackUrl == null) {
        log.ssoAuthenticationProviderUrlRequired();
        throw new ServletException("Required pac4j callback URL is missing.");
    }
    // add the callback parameter to know it's a callback
    pac4jCallbackUrl = CommonHelper.addParameter(pac4jCallbackUrl, PAC4J_CALLBACK_PARAMETER, "true");
    final Config config;
    final String clientName;
    // client name from servlet parameter (mandatory)
    final String clientNameParameter = filterConfig.getInitParameter("clientName");
    if (clientNameParameter == null) {
        log.clientNameParameterRequired();
        throw new ServletException("Required pac4j clientName parameter is missing.");
    }
    if (TEST_BASIC_AUTH.equalsIgnoreCase(clientNameParameter)) {
        // test configuration
        final IndirectBasicAuthClient indirectBasicAuthClient = new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator());
        indirectBasicAuthClient.setRealmName("Knox TEST");
        config = new Config(pac4jCallbackUrl, indirectBasicAuthClient);
        clientName = "IndirectBasicAuthClient";
    } else {
        // get clients from the init parameters
        final Map<String, String> properties = new HashMap<>();
        final Enumeration<String> names = filterConfig.getInitParameterNames();
        addDefaultConfig(clientNameParameter, properties);
        while (names.hasMoreElements()) {
            final String key = names.nextElement();
            properties.put(key, filterConfig.getInitParameter(key));
        }
        final PropertiesConfigFactory propertiesConfigFactory = new PropertiesConfigFactory(pac4jCallbackUrl, properties);
        config = propertiesConfigFactory.build();
        final List<Client> clients = config.getClients().getClients();
        if (clients == null || clients.size() == 0) {
            log.atLeastOnePac4jClientMustBeDefined();
            throw new ServletException("At least one pac4j client must be defined.");
        }
        if (CommonHelper.isBlank(clientNameParameter)) {
            clientName = clients.get(0).getName();
        } else {
            clientName = clientNameParameter;
        }
    }
    callbackFilter = new CallbackFilter();
    callbackFilter.init(filterConfig);
    callbackFilter.setConfigOnly(config);
    securityFilter = new SecurityFilter();
    securityFilter.setClients(clientName);
    securityFilter.setConfigOnly(config);
    final String domainSuffix = filterConfig.getInitParameter(PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM);
    final String sessionStoreVar = filterConfig.getInitParameter(PAC4J_SESSION_STORE);
    SessionStore sessionStore;
    if (!StringUtils.isBlank(sessionStoreVar) && J2ESessionStore.class.getName().contains(sessionStoreVar)) {
        sessionStore = new J2ESessionStore();
    } else {
        sessionStore = new KnoxSessionStore(cryptoService, clusterName, domainSuffix);
    }
    config.setSessionStore(sessionStore);
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) J2ESessionStore(org.pac4j.core.context.session.J2ESessionStore) KnoxSessionStore(org.apache.knox.gateway.pac4j.session.KnoxSessionStore) HashMap(java.util.HashMap) Config(org.pac4j.core.config.Config) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) KnoxSessionStore(org.apache.knox.gateway.pac4j.session.KnoxSessionStore) SessionStore(org.pac4j.core.context.session.SessionStore) J2ESessionStore(org.pac4j.core.context.session.J2ESessionStore) CryptoService(org.apache.knox.gateway.services.security.CryptoService) PropertiesConfigFactory(org.pac4j.config.client.PropertiesConfigFactory) SecurityFilter(org.pac4j.j2e.filter.SecurityFilter) CallbackFilter(org.pac4j.j2e.filter.CallbackFilter) Client(org.pac4j.core.client.Client) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) SimpleTestUsernamePasswordAuthenticator(org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator)

Example 2 with AliasServiceException

use of org.apache.knox.gateway.services.security.AliasServiceException in project knox by apache.

the class RESTInvoker method invoke.

JSONObject invoke(String url, String username, String passwordAlias) {
    JSONObject result = null;
    CloseableHttpResponse response = null;
    try {
        HttpGet request = new HttpGet(url);
        // If no configured username, then use default username alias
        String password = null;
        if (username == null) {
            if (aliasService != null) {
                try {
                    char[] defaultUser = aliasService.getPasswordFromAliasForGateway(DEFAULT_USER_ALIAS);
                    if (defaultUser != null) {
                        username = new String(defaultUser);
                    }
                } catch (AliasServiceException e) {
                    log.aliasServiceUserError(DEFAULT_USER_ALIAS, e.getLocalizedMessage());
                }
            }
            // If username is still null
            if (username == null) {
                log.aliasServiceUserNotFound();
                throw new ConfigurationException("No username is configured for Ambari service discovery.");
            }
        }
        if (aliasService != null) {
            // If no password alias is configured, then try the default alias
            if (passwordAlias == null) {
                passwordAlias = DEFAULT_PWD_ALIAS;
            }
            try {
                char[] pwd = aliasService.getPasswordFromAliasForGateway(passwordAlias);
                if (pwd != null) {
                    password = new String(pwd);
                }
            } catch (AliasServiceException e) {
                log.aliasServicePasswordError(passwordAlias, e.getLocalizedMessage());
            }
        }
        // If the password could not be determined
        if (password == null) {
            log.aliasServicePasswordNotFound();
            throw new ConfigurationException("No password is configured for Ambari service discovery.");
        }
        // Add an auth header if credentials are available
        String encodedCreds = org.apache.commons.codec.binary.Base64.encodeBase64String((username + ":" + password).getBytes());
        request.addHeader(new BasicHeader("Authorization", "Basic " + encodedCreds));
        // Ambari CSRF protection
        request.addHeader("X-Requested-By", "Knox");
        response = httpClient.execute(request);
        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = (JSONObject) JSONValue.parse((EntityUtils.toString(entity)));
                log.debugJSON(result.toJSONString());
            } else {
                log.noJSON(url);
            }
        } else {
            log.unexpectedRestResponseStatusCode(url, response.getStatusLine().getStatusCode());
        }
    } catch (ConnectTimeoutException e) {
        log.restInvocationTimedOut(url, e);
    } catch (IOException e) {
        log.restInvocationError(url, e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
            // Ignore
            }
        }
    }
    return result;
}
Also used : JSONObject(net.minidev.json.JSONObject) HttpEntity(org.apache.http.HttpEntity) ConfigurationException(org.apache.knox.gateway.config.ConfigurationException) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) IOException(java.io.IOException) BasicHeader(org.apache.http.message.BasicHeader) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 3 with AliasServiceException

use of org.apache.knox.gateway.services.security.AliasServiceException in project knox by apache.

the class DefaultAliasService method getPasswordFromAliasForCluster.

/* (non-Javadoc)
   * @see org.apache.knox.gateway.services.security.impl.AliasService#getAliasForCluster(java.lang.String, java.lang.String, boolean)
   */
@Override
public char[] getPasswordFromAliasForCluster(String clusterName, String alias, boolean generate) throws AliasServiceException {
    char[] credential = null;
    try {
        credential = keystoreService.getCredentialForCluster(clusterName, alias);
        if (credential == null) {
            if (generate) {
                generateAliasForCluster(clusterName, alias);
                credential = keystoreService.getCredentialForCluster(clusterName, alias);
            }
        }
    } catch (KeystoreServiceException e) {
        LOG.failedToGetCredentialForCluster(clusterName, e);
        throw new AliasServiceException(e);
    }
    return credential;
}
Also used : AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException)

Example 4 with AliasServiceException

use of org.apache.knox.gateway.services.security.AliasServiceException in project knox by apache.

the class DefaultAliasService method generateAliasForCluster.

@Override
public void generateAliasForCluster(String clusterName, String alias) throws AliasServiceException {
    try {
        keystoreService.getCredentialStoreForCluster(clusterName);
    } catch (KeystoreServiceException e) {
        LOG.failedToGenerateAliasForCluster(clusterName, e);
        throw new AliasServiceException(e);
    }
    String passwordString = generatePassword(16);
    addAliasForCluster(clusterName, alias, passwordString);
}
Also used : AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException)

Example 5 with AliasServiceException

use of org.apache.knox.gateway.services.security.AliasServiceException in project knox by apache.

the class JettySSLService method logAndValidateCertificate.

private void logAndValidateCertificate() throws ServiceLifecycleException {
    // let's log the hostname (CN) and cert expiry from the gateway's public cert to aid in SSL debugging
    Certificate cert;
    try {
        cert = as.getCertificateForGateway("gateway-identity");
    } catch (AliasServiceException e) {
        throw new ServiceLifecycleException("Cannot Retreive Gateway SSL Certificate. Server will not start.", e);
    }
    if (cert != null) {
        if (cert instanceof X509Certificate) {
            X500Principal x500Principal = ((X509Certificate) cert).getSubjectX500Principal();
            X500PrincipalParser parser = new X500PrincipalParser(x500Principal);
            log.certificateHostNameForGateway(parser.getCN());
            Date notBefore = ((X509Certificate) cert).getNotBefore();
            Date notAfter = ((X509Certificate) cert).getNotAfter();
            log.certificateValidityPeriod(notBefore, notAfter);
            // let's not even start if the current date is not within the validity period for the SSL cert
            try {
                ((X509Certificate) cert).checkValidity();
            } catch (CertificateExpiredException e) {
                throw new ServiceLifecycleException("Gateway SSL Certificate is Expired. Server will not start.", e);
            } catch (CertificateNotYetValidException e) {
                throw new ServiceLifecycleException("Gateway SSL Certificate is not yet valid. Server will not start.", e);
            }
        } else {
            throw new ServiceLifecycleException("Public certificate for the gateway cannot be found with the alias gateway-identity. Plase check the identity certificate alias.");
        }
    } else {
        throw new ServiceLifecycleException("Public certificate for the gateway is not of the expected type of X509Certificate. Something is wrong with the gateway keystore.");
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) X500PrincipalParser(org.apache.knox.gateway.util.X500PrincipalParser) CertificateExpiredException(java.security.cert.CertificateExpiredException) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) ServiceLifecycleException(org.apache.knox.gateway.services.ServiceLifecycleException) X500Principal(javax.security.auth.x500.X500Principal) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

AliasServiceException (org.apache.knox.gateway.services.security.AliasServiceException)15 KeystoreServiceException (org.apache.knox.gateway.services.security.KeystoreServiceException)6 GatewayServices (org.apache.knox.gateway.services.GatewayServices)5 AliasService (org.apache.knox.gateway.services.security.AliasService)4 ServiceLifecycleException (org.apache.knox.gateway.services.ServiceLifecycleException)3 IOException (java.io.IOException)2 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)2 HashMap (java.util.HashMap)2 JWSSigner (com.nimbusds.jose.JWSSigner)1 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 InvalidKeyException (java.security.InvalidKeyException)1 KeyStore (java.security.KeyStore)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 PrivateKey (java.security.PrivateKey)1 Signature (java.security.Signature)1 SignatureException (java.security.SignatureException)1 Certificate (java.security.cert.Certificate)1 CertificateExpiredException (java.security.cert.CertificateExpiredException)1 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)1