Search in sources :

Example 16 with KeystoreServiceException

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

the class DefaultTokenAuthorityService method issueToken.

@Override
public JWT issueToken(Principal p, List<String> audiences, String algorithm, long expires) throws TokenServiceException {
    String[] claimArray = new String[4];
    claimArray[0] = "KNOXSSO";
    claimArray[1] = p.getName();
    claimArray[2] = null;
    if (expires == -1) {
        claimArray[3] = null;
    } else {
        claimArray[3] = String.valueOf(expires);
    }
    JWT token = null;
    if (SUPPORTED_SIG_ALGS.contains(algorithm)) {
        token = new JWTToken(algorithm, claimArray, audiences);
        RSAPrivateKey key;
        char[] passphrase = null;
        try {
            passphrase = getSigningKeyPassphrase();
        } catch (AliasServiceException e) {
            throw new TokenServiceException(e);
        }
        try {
            key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
            JWSSigner signer = new RSASSASigner(key);
            token.sign(signer);
        } catch (KeystoreServiceException e) {
            throw new TokenServiceException(e);
        }
    } else {
        throw new TokenServiceException("Cannot issue token - Unsupported algorithm");
    }
    return token;
}
Also used : JWT(org.apache.knox.gateway.services.security.token.impl.JWT) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWSSigner(com.nimbusds.jose.JWSSigner) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException)

Example 17 with KeystoreServiceException

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

the class DefaultTokenAuthorityService method init.

@Override
public void init(GatewayConfig config, Map<String, String> options) throws ServiceLifecycleException {
    if (as == null || ks == null) {
        throw new ServiceLifecycleException("Alias or Keystore service is not set");
    }
    signingKeyAlias = config.getSigningKeyAlias();
    @SuppressWarnings("unused") RSAPrivateKey key;
    char[] passphrase = null;
    try {
        passphrase = as.getPasswordFromAliasForGateway(SIGNING_KEY_PASSPHRASE);
        if (passphrase != null) {
            key = (RSAPrivateKey) ks.getSigningKey(getSigningKeyAlias(), passphrase);
            if (key == null) {
                throw new ServiceLifecycleException("Provisioned passphrase cannot be used to acquire signing key.");
            }
        }
    } catch (AliasServiceException e) {
        throw new ServiceLifecycleException("Provisioned signing key passphrase cannot be acquired.", e);
    } catch (KeystoreServiceException e) {
        throw new ServiceLifecycleException("Provisioned signing key passphrase cannot be acquired.", e);
    }
}
Also used : AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) ServiceLifecycleException(org.apache.knox.gateway.services.ServiceLifecycleException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 18 with KeystoreServiceException

use of org.apache.knox.gateway.services.security.KeystoreServiceException 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 19 with KeystoreServiceException

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

the class DefaultKeystoreService method createKeyStore.

// Package private for unit test access
// We need this to be synchronized to prevent multiple threads from using at once
synchronized KeyStore createKeyStore(Path keystoreFilePath, String keystoreType, char[] password) throws KeystoreServiceException {
    // Ensure the parent directory exists...
    // This is symlink safe.
    Path parentPath = keystoreFilePath.getParent();
    if (parentPath != null && !Files.isDirectory(parentPath)) {
        try {
            // This will attempt to create all missing directories.  No failures will occur if the
            // directories already exist.
            Files.createDirectories(parentPath);
        } catch (IOException e) {
            LOG.failedToCreateKeystore(keystoreFilePath.toString(), keystoreType, e);
            throw new KeystoreServiceException(e);
        }
    }
    try {
        KeyStore ks = KeyStore.getInstance(keystoreType);
        ks.load(null, null);
        writeKeyStoreToFile(ks, keystoreFilePath, password);
        return ks;
    } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) {
        LOG.failedToCreateKeystore(keystoreFilePath.toString(), keystoreType, e);
        throw new KeystoreServiceException(e);
    }
}
Also used : Path(java.nio.file.Path) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) KeyStore(java.security.KeyStore)

Example 20 with KeystoreServiceException

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

the class DefaultCryptoService method verify.

@Override
public boolean verify(String algorithm, String signed, byte[] signature) {
    boolean verified = false;
    try {
        Signature sig = Signature.getInstance(algorithm);
        sig.initVerify(keystoreService.getCertificateForGateway().getPublicKey());
        sig.update(signed.getBytes(StandardCharsets.UTF_8));
        verified = sig.verify(signature);
    } catch (SignatureException | KeystoreServiceException | InvalidKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        LOG.failedToVerifySignature(e);
    }
    LOG.signatureVerified(verified);
    return verified;
}
Also used : Signature(java.security.Signature) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) InvalidKeyException(java.security.InvalidKeyException)

Aggregations

KeystoreServiceException (org.apache.knox.gateway.services.security.KeystoreServiceException)25 KeyStoreException (java.security.KeyStoreException)14 KeyStore (java.security.KeyStore)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 AliasServiceException (org.apache.knox.gateway.services.security.AliasServiceException)7 IOException (java.io.IOException)6 TokenServiceException (org.apache.knox.gateway.services.security.token.TokenServiceException)5 File (java.io.File)4 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)4 RSAPublicKey (java.security.interfaces.RSAPublicKey)4 PublicKey (java.security.PublicKey)3 X509Certificate (java.security.cert.X509Certificate)3 ServiceLifecycleException (org.apache.knox.gateway.services.ServiceLifecycleException)3 JOSEException (com.nimbusds.jose.JOSEException)2 JWSSigner (com.nimbusds.jose.JWSSigner)2 JWSVerifier (com.nimbusds.jose.JWSVerifier)2 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)2 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)2 GeneralSecurityException (java.security.GeneralSecurityException)2 InvalidKeyException (java.security.InvalidKeyException)2