Search in sources :

Example 1 with JWTokenAttributes

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

the class JWTAccessTokenAssertionFilter method getAccessToken.

private String getAccessToken(final String principalName, String serviceName, long expires) {
    String accessToken = null;
    Principal p = new Principal() {

        @Override
        public String getName() {
            return principalName;
        }
    };
    JWT token;
    try {
        final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder().setPrincipal(p).setAudiences(serviceName).setAlgorithm(signatureAlgorithm).setExpires(expires).build();
        token = authority.issueToken(jwtAttributes);
        // Coverity CID 1327961
        if (token != null) {
            accessToken = token.toString();
        }
    } catch (TokenServiceException e) {
        log.unableToIssueToken(e);
    }
    return accessToken;
}
Also used : JWT(org.apache.knox.gateway.services.security.token.impl.JWT) JWTokenAttributes(org.apache.knox.gateway.services.security.token.JWTokenAttributes) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) JWTokenAttributesBuilder(org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder)

Example 2 with JWTokenAttributes

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

the class DefaultTokenAuthorityServiceTest method testTokenCreationCustomSigningKey.

@Test
public void testTokenCreationCustomSigningKey() throws Exception {
    /*
     Generated testSigningKeyName.jks with the following commands:
     cd gateway-server/src/test/resources/keystores/
     keytool -genkey -alias testSigningKeyAlias -keyalg RSA -keystore testSigningKeyName.jks \
         -storepass testSigningKeyPassphrase -keypass testSigningKeyPassphrase -keysize 2048 \
         -dname 'CN=testSigningKey,OU=example,O=Apache,L=US,ST=CA,C=US' -noprompt
     */
    String customSigningKeyName = "testSigningKeyName";
    String customSigningKeyAlias = "testSigningKeyAlias";
    String customSigningKeyPassphrase = "testSigningKeyPassphrase";
    Principal principal = EasyMock.createNiceMock(Principal.class);
    EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
    GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
    String basedir = System.getProperty("basedir");
    if (basedir == null) {
        basedir = new File(".").getCanonicalPath();
    }
    EasyMock.expect(config.getGatewaySecurityDir()).andReturn(basedir + "/target/test-classes").anyTimes();
    EasyMock.expect(config.getGatewayKeystoreDir()).andReturn(basedir + "/target/test-classes/keystores").anyTimes();
    EasyMock.expect(config.getSigningKeystoreName()).andReturn("server-keystore.jks").anyTimes();
    EasyMock.expect(config.getSigningKeystorePath()).andReturn(basedir + "/target/test-classes/keystores/server-keystore.jks").anyTimes();
    EasyMock.expect(config.getSigningKeystorePasswordAlias()).andReturn(GatewayConfig.DEFAULT_SIGNING_KEYSTORE_PASSWORD_ALIAS).anyTimes();
    EasyMock.expect(config.getSigningKeyPassphraseAlias()).andReturn(GatewayConfig.DEFAULT_SIGNING_KEY_PASSPHRASE_ALIAS).anyTimes();
    EasyMock.expect(config.getSigningKeystoreType()).andReturn("jks").anyTimes();
    EasyMock.expect(config.getSigningKeyAlias()).andReturn("server").anyTimes();
    EasyMock.expect(config.getCredentialStoreType()).andReturn(GatewayConfig.DEFAULT_CREDENTIAL_STORE_TYPE).anyTimes();
    EasyMock.expect(config.getCredentialStoreAlgorithm()).andReturn(GatewayConfig.DEFAULT_CREDENTIAL_STORE_ALG).anyTimes();
    MasterService ms = EasyMock.createNiceMock(MasterService.class);
    AliasService as = EasyMock.createNiceMock(AliasService.class);
    EasyMock.expect(as.getSigningKeyPassphrase()).andReturn("horton".toCharArray()).anyTimes();
    EasyMock.replay(principal, config, ms, as);
    DefaultKeystoreService ks = new DefaultKeystoreService();
    ks.setMasterService(ms);
    ks.init(config, new HashMap<>());
    DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
    ta.setAliasService(as);
    ta.setKeystoreService(ks);
    ta.init(config, new HashMap<>());
    ta.start();
    final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder().setPrincipal(principal).setAudiences(Collections.emptyList()).setAlgorithm("RS256").setExpires(-1).setSigningKeystoreName(customSigningKeyName).setSigningKeystoreAlias(customSigningKeyAlias).setSigningKeystorePassphrase(customSigningKeyPassphrase.toCharArray()).build();
    JWT token = ta.issueToken(jwtAttributes);
    assertEquals("KNOXSSO", token.getIssuer());
    assertEquals("john.doe@example.com", token.getSubject());
    RSAPublicKey customPublicKey = (RSAPublicKey) ks.getSigningKeystore(customSigningKeyName).getCertificate(customSigningKeyAlias).getPublicKey();
    assertFalse(ta.verifyToken(token));
    assertTrue(ta.verifyToken(token, customPublicKey));
}
Also used : AliasService(org.apache.knox.gateway.services.security.AliasService) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) MasterService(org.apache.knox.gateway.services.security.MasterService) DefaultKeystoreService(org.apache.knox.gateway.services.security.impl.DefaultKeystoreService) RSAPublicKey(java.security.interfaces.RSAPublicKey) JWTokenAttributes(org.apache.knox.gateway.services.security.token.JWTokenAttributes) File(java.io.File) Principal(java.security.Principal) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) JWTokenAttributesBuilder(org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder) Test(org.junit.Test)

Example 3 with JWTokenAttributes

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

the class TokenResource method getAuthenticationToken.

private Response getAuthenticationToken() {
    if (clientCertRequired) {
        X509Certificate cert = extractCertificate(request);
        if (cert != null) {
            if (!allowedDNs.contains(cert.getSubjectDN().getName().replaceAll("\\s+", ""))) {
                return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - untrusted client cert.\" }").build();
            }
        } else {
            return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - client cert required.\" }").build();
        }
    }
    GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
    JWTokenAuthority ts = services.getService(ServiceType.TOKEN_SERVICE);
    Principal p = request.getUserPrincipal();
    long expires = getExpiry();
    if (endpointPublicCert == null) {
        // acquire PEM for gateway identity of this gateway instance
        KeystoreService ks = services.getService(ServiceType.KEYSTORE_SERVICE);
        if (ks != null) {
            try {
                Certificate cert = ks.getCertificateForGateway();
                byte[] bytes = cert.getEncoded();
                endpointPublicCert = Base64.encodeBase64String(bytes);
            } catch (KeyStoreException | KeystoreServiceException | CertificateEncodingException e) {
                // assuming that certs will be properly provisioned across all clients
                log.unableToAcquireCertForEndpointClients(e);
            }
        }
    }
    String jku = null;
    /* remove .../token and replace it with ..../jwks.json */
    final int idx = request.getRequestURL().lastIndexOf("/");
    if (idx > 1) {
        jku = request.getRequestURL().substring(0, idx) + JWKSResource.JWKS_PATH;
    }
    if (tokenStateService != null) {
        if (tokenLimitPerUser != -1) {
            // if -1 => unlimited tokens for all users
            if (tokenStateService.getTokens(p.getName()).size() >= tokenLimitPerUser) {
                log.tokenLimitExceeded(p.getName());
                return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - token limit exceeded.\" }").build();
            }
        }
    }
    try {
        final boolean managedToken = tokenStateService != null;
        JWT token;
        JWTokenAttributes jwtAttributes;
        final JWTokenAttributesBuilder jwtAttributesBuilder = new JWTokenAttributesBuilder();
        jwtAttributesBuilder.setPrincipal(p).setAlgorithm(signatureAlgorithm).setExpires(expires).setManaged(managedToken).setJku(jku).setType(tokenType);
        if (!targetAudiences.isEmpty()) {
            jwtAttributesBuilder.setAudiences(targetAudiences);
        }
        jwtAttributes = jwtAttributesBuilder.build();
        token = ts.issueToken(jwtAttributes);
        if (token != null) {
            String accessToken = token.toString();
            String tokenId = TokenUtils.getTokenId(token);
            log.issuedToken(getTopologyName(), Tokens.getTokenDisplayText(accessToken), Tokens.getTokenIDDisplayText(tokenId));
            final HashMap<String, Object> map = new HashMap<>();
            map.put(ACCESS_TOKEN, accessToken);
            map.put(TOKEN_ID, tokenId);
            map.put(MANAGED_TOKEN, String.valueOf(managedToken));
            map.put(TOKEN_TYPE, BEARER);
            map.put(EXPIRES_IN, expires);
            if (tokenTargetUrl != null) {
                map.put(TARGET_URL, tokenTargetUrl);
            }
            if (tokenClientDataMap != null) {
                map.putAll(tokenClientDataMap);
            }
            if (endpointPublicCert != null) {
                map.put(ENDPOINT_PUBLIC_CERT, endpointPublicCert);
            }
            final String passcode = UUID.randomUUID().toString();
            map.put(PASSCODE, generatePasscodeField(tokenId, passcode));
            String jsonResponse = JsonUtils.renderAsJsonString(map);
            // Optional token store service persistence
            if (tokenStateService != null) {
                final long issueTime = System.currentTimeMillis();
                tokenStateService.addToken(tokenId, issueTime, expires, maxTokenLifetime.orElse(tokenStateService.getDefaultMaxLifetimeDuration()));
                final String comment = request.getParameter(COMMENT);
                final TokenMetadata tokenMetadata = new TokenMetadata(p.getName(), StringUtils.isBlank(comment) ? null : comment);
                tokenMetadata.setPasscode(tokenMAC.hash(tokenId, issueTime, p.getName(), passcode));
                tokenStateService.addMetadata(tokenId, tokenMetadata);
                log.storedToken(getTopologyName(), Tokens.getTokenDisplayText(accessToken), Tokens.getTokenIDDisplayText(tokenId));
            }
            return Response.ok().entity(jsonResponse).build();
        } else {
            return Response.serverError().build();
        }
    } catch (TokenServiceException e) {
        log.unableToIssueToken(e);
    }
    return Response.ok().entity("{ \"Unable to acquire token.\" }").build();
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) HashMap(java.util.HashMap) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyStoreException(java.security.KeyStoreException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) TokenMetadata(org.apache.knox.gateway.services.security.token.TokenMetadata) X509Certificate(java.security.cert.X509Certificate) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) JWTokenAttributes(org.apache.knox.gateway.services.security.token.JWTokenAttributes) KeystoreService(org.apache.knox.gateway.services.security.KeystoreService) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) JWTokenAttributesBuilder(org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder)

Example 4 with JWTokenAttributes

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

the class WebSSOResource method getAuthenticationToken.

private Response getAuthenticationToken(int statusCode) {
    GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
    boolean removeOriginalUrlCookie = true;
    List<Cookie> originalUrlCookies = CookieUtils.getCookiesForName(request, ORIGINAL_URL_COOKIE_NAME);
    String original;
    if (originalUrlCookies.isEmpty()) {
        // in the case where there are no SAML redirects done before here
        // we need to get it from the request parameters
        removeOriginalUrlCookie = false;
        original = getOriginalUrlFromQueryParams();
        if (original.isEmpty()) {
            LOGGER.originalURLNotFound();
            throw new WebApplicationException("Original URL not found in the request.", Response.Status.BAD_REQUEST);
        }
        boolean validRedirect = true;
        // If there is no whitelist, then everything is valid.
        if (whitelist != null) {
            String decodedOriginal = null;
            try {
                decodedOriginal = URLDecoder.decode(original, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
            // 
            }
            validRedirect = RegExUtils.checkWhitelist(whitelist, (decodedOriginal != null ? decodedOriginal : original));
        }
        if (!validRedirect) {
            LOGGER.whiteListMatchFail(Log4jAuditor.maskTokenFromURL(original), whitelist);
            throw new WebApplicationException("Original URL not valid according to the configured whitelist.", Response.Status.BAD_REQUEST);
        }
    } else {
        // There should only be one original url cookie for the given path
        original = originalUrlCookies.get(0).getValue();
    }
    AliasService as = services.getService(ServiceType.ALIAS_SERVICE);
    JWTokenAuthority tokenAuthority = services.getService(ServiceType.TOKEN_SERVICE);
    Principal p = request.getUserPrincipal();
    try {
        String signingKeystoreName = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_NAME);
        String signingKeystoreAlias = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_ALIAS);
        String signingKeystorePassphraseAlias = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_PASSPHRASE_ALIAS);
        char[] signingKeystorePassphrase = null;
        if (signingKeystorePassphraseAlias != null) {
            signingKeystorePassphrase = as.getPasswordFromAliasForCluster(clusterName, signingKeystorePassphraseAlias);
        }
        final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder().setPrincipal(p).setAudiences(targetAudiences).setAlgorithm(signatureAlgorithm).setExpires(getExpiry()).setSigningKeystoreName(signingKeystoreName).setSigningKeystoreAlias(signingKeystoreAlias).setSigningKeystorePassphrase(signingKeystorePassphrase).build();
        JWT token = tokenAuthority.issueToken(jwtAttributes);
        // Coverity CID 1327959
        if (token != null) {
            addJWTHadoopCookie(original, token);
        }
        if (removeOriginalUrlCookie) {
            removeOriginalUrlCookie(response);
        }
        LOGGER.aboutToRedirectToOriginal(Log4jAuditor.maskTokenFromURL(original));
        response.setStatus(statusCode);
        response.setHeader("Location", original);
        try {
            response.getOutputStream().close();
        } catch (IOException e) {
            LOGGER.unableToCloseOutputStream(e.getMessage(), Arrays.toString(e.getStackTrace()));
        }
    } catch (TokenServiceException | AliasServiceException e) {
        LOGGER.unableToIssueToken(e);
    }
    URI location = null;
    try {
        location = new URI(original);
    } catch (URISyntaxException urise) {
    // todo log return error response
    }
    if (!enableSession) {
        // invalidate the session to avoid autologin
        // Coverity CID 1352857
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
    }
    return Response.seeOther(location).entity("{ \"redirectTo\" : " + original + " }").build();
}
Also used : Cookie(javax.servlet.http.Cookie) GatewayServices(org.apache.knox.gateway.services.GatewayServices) AliasService(org.apache.knox.gateway.services.security.AliasService) WebApplicationException(javax.ws.rs.WebApplicationException) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) HttpSession(javax.servlet.http.HttpSession) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) JWTokenAttributes(org.apache.knox.gateway.services.security.token.JWTokenAttributes) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) JWTokenAttributesBuilder(org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder)

Aggregations

Principal (java.security.Principal)4 JWTokenAttributes (org.apache.knox.gateway.services.security.token.JWTokenAttributes)4 JWTokenAttributesBuilder (org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder)4 JWT (org.apache.knox.gateway.services.security.token.impl.JWT)4 TokenServiceException (org.apache.knox.gateway.services.security.token.TokenServiceException)3 GatewayServices (org.apache.knox.gateway.services.GatewayServices)2 AliasService (org.apache.knox.gateway.services.security.AliasService)2 JWTokenAuthority (org.apache.knox.gateway.services.security.token.JWTokenAuthority)2 File (java.io.File)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 KeyStoreException (java.security.KeyStoreException)1 Certificate (java.security.cert.Certificate)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 X509Certificate (java.security.cert.X509Certificate)1 RSAPublicKey (java.security.interfaces.RSAPublicKey)1 HashMap (java.util.HashMap)1 Cookie (javax.servlet.http.Cookie)1