Search in sources :

Example 21 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class AuthCryptoProvider method generateKeySignature.

private JSONObject generateKeySignature(Algorithm algorithm, Long expirationTime, int keyLength) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, OperatorCreationException, CertificateException, KeyStoreException, IOException {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm.getParamName());
    if (signatureAlgorithm == null) {
        algorithm = Algorithm.ES384;
        signatureAlgorithm = SignatureAlgorithm.ES384;
    }
    KeyPairGenerator keyGen = null;
    final AlgorithmFamily algorithmFamily = algorithm.getFamily();
    switch(algorithmFamily) {
        case RSA:
            {
                keyGen = KeyPairGenerator.getInstance(algorithmFamily.toString(), "BC");
                keyGen.initialize(keyLength, new SecureRandom());
                break;
            }
        case EC:
            {
                ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
                keyGen = KeyPairGenerator.getInstance(algorithmFamily.toString(), "BC");
                keyGen.initialize(eccgen, new SecureRandom());
                break;
            }
        case ED:
            {
                EdDSAParameterSpec edSpec = new EdDSAParameterSpec(signatureAlgorithm.getCurve().getAlias());
                keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getName(), "BC");
                keyGen.initialize(edSpec, new SecureRandom());
                break;
            }
        default:
            {
                throw new IllegalStateException("The provided signature algorithm parameter is not supported: algorithmFamily = " + algorithmFamily);
            }
    }
    return getJson(algorithm, keyGen, signatureAlgorithm.getAlgorithm(), expirationTime);
}
Also used : EdDSAParameterSpec(org.bouncycastle.jcajce.spec.EdDSAParameterSpec) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) SecureRandom(java.security.SecureRandom) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) KeyPairGenerator(java.security.KeyPairGenerator) AlgorithmFamily(io.jans.as.model.crypto.signature.AlgorithmFamily)

Example 22 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class ClientAssertion method load.

private boolean load(AppConfiguration appConfiguration, AbstractCryptoProvider cryptoProvider, String clientId, io.jans.as.model.token.ClientAssertionType clientAssertionType, String encodedAssertion) throws Exception {
    boolean result;
    if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
        if (StringUtils.isNotBlank(encodedAssertion)) {
            jwt = Jwt.parse(encodedAssertion);
            // TODO: Store jti this value to check for duplicates
            // Validate clientId
            String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
            String subject = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER);
            List<String> audience = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUDIENCE);
            Date expirationTime = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
            // SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
            if ((clientId == null && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && issuer.equals(subject)) || (StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && clientId.equals(issuer) && issuer.equals(subject))) {
                // Validate audience
                String tokenUrl = appConfiguration.getTokenEndpoint();
                String parUrl = StringUtils.isNotBlank(appConfiguration.getParEndpoint()) ? appConfiguration.getParEndpoint() : "";
                String cibaAuthUrl = appConfiguration.getBackchannelAuthenticationEndpoint();
                if (audience != null && (audience.contains(appConfiguration.getIssuer()) || audience.contains(tokenUrl) || audience.contains(parUrl) || audience.contains(cibaAuthUrl))) {
                    // Validate expiration
                    if (expirationTime.after(new Date())) {
                        ClientService clientService = CdiUtil.bean(ClientService.class);
                        Client client = clientService.getClient(subject);
                        // Validate client
                        if (client != null) {
                            JwtType jwtType = JwtType.fromString(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
                            AuthenticationMethod authenticationMethod = client.getAuthenticationMethod();
                            SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getSignatureAlgorithm();
                            if (jwtType == null && signatureAlgorithm != null) {
                                jwtType = signatureAlgorithm.getJwtType();
                            }
                            if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily()) || AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily()))))) {
                                if (client.getTokenEndpointAuthSigningAlg() == null || SignatureAlgorithm.fromString(client.getTokenEndpointAuthSigningAlg()).equals(signatureAlgorithm)) {
                                    clientSecret = clientService.decryptSecret(client.getClientSecret());
                                    // Validate the crypto segment
                                    String keyId = jwt.getHeader().getKeyId();
                                    JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
                                    String sharedSecret = clientService.decryptSecret(client.getClientSecret());
                                    boolean validSignature = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId, jwks, sharedSecret, signatureAlgorithm);
                                    if (validSignature) {
                                        result = true;
                                    } else {
                                        throw new InvalidJwtException("Invalid cryptographic segment");
                                    }
                                } else {
                                    throw new InvalidJwtException("Invalid signing algorithm");
                                }
                            } else {
                                throw new InvalidJwtException("Invalid authentication method");
                            }
                        } else {
                            throw new InvalidJwtException("Invalid client");
                        }
                    } else {
                        throw new InvalidJwtException("JWT has expired");
                    }
                } else {
                    throw new InvalidJwtException("Invalid audience: " + audience);
                }
            } else {
                throw new InvalidJwtException("Invalid clientId");
            }
        } else {
            throw new InvalidJwtException("The Client Assertion is null or empty");
        }
    } else {
        throw new InvalidJwtException("Invalid Client Assertion Type");
    }
    return result;
}
Also used : InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) JSONObject(org.json.JSONObject) ClientService(io.jans.as.server.service.ClientService) JwtType(io.jans.as.model.jwt.JwtType) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) Client(io.jans.as.common.model.registration.Client) Date(java.util.Date)

Example 23 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class RegisterRestWebServiceImpl method validateSoftwareStatement.

private JSONObject validateSoftwareStatement(HttpServletRequest httpServletRequest, JSONObject requestObject) {
    if (!requestObject.has(SOFTWARE_STATEMENT.toString())) {
        return null;
    }
    try {
        Jwt softwareStatement = Jwt.parseOrThrow(requestObject.getString(SOFTWARE_STATEMENT.toString()));
        final SignatureAlgorithm signatureAlgorithm = softwareStatement.getHeader().getSignatureAlgorithm();
        final SoftwareStatementValidationType validationType = SoftwareStatementValidationType.fromString(appConfiguration.getSoftwareStatementValidationType());
        if (validationType == SoftwareStatementValidationType.NONE) {
            log.trace("software_statement validation was skipped due to `softwareStatementValidationType` configuration property set to none. (Not recommended.)");
            return softwareStatement.getClaims().toJsonObject();
        }
        if (validationType == SoftwareStatementValidationType.SCRIPT) {
            if (!externalDynamicClientRegistrationService.isEnabled()) {
                log.error("Server is mis-configured. softwareStatementValidationType=script but there is no any Dynamic Client Registration script enabled.");
                return null;
            }
            if (AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) {
                final String hmacSecret = externalDynamicClientRegistrationService.getSoftwareStatementHmacSecret(httpServletRequest, requestObject, softwareStatement);
                if (StringUtils.isBlank(hmacSecret)) {
                    log.error("No hmacSecret provided in Dynamic Client Registration script (method getSoftwareStatementHmacSecret didn't return actual secret). ");
                    throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, "");
                }
                if (!cryptoProvider.verifySignature(softwareStatement.getSigningInput(), softwareStatement.getEncodedSignature(), null, null, hmacSecret, signatureAlgorithm)) {
                    throw new InvalidJwtException("Invalid signature in the software statement");
                }
                return softwareStatement.getClaims().toJsonObject();
            }
            final JSONObject softwareStatementJwks = externalDynamicClientRegistrationService.getSoftwareStatementJwks(httpServletRequest, requestObject, softwareStatement);
            if (softwareStatementJwks == null) {
                log.error("No jwks provided in Dynamic Client Registration script (method getSoftwareStatementJwks didn't return actual jwks). ");
                throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, "");
            }
            if (!cryptoProvider.verifySignature(softwareStatement.getSigningInput(), softwareStatement.getEncodedSignature(), softwareStatement.getHeader().getKeyId(), softwareStatementJwks, null, signatureAlgorithm)) {
                throw new InvalidJwtException("Invalid signature in the software statement");
            }
            return softwareStatement.getClaims().toJsonObject();
        }
        if ((validationType == SoftwareStatementValidationType.JWKS_URI || validationType == SoftwareStatementValidationType.JWKS) && StringUtils.isBlank(appConfiguration.getSoftwareStatementValidationClaimName())) {
            log.error("softwareStatementValidationClaimName configuration property is not specified. Please specify claim name from software_statement which points to jwks (or jwks_uri).");
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, "Failed to validate software statement");
        }
        String jwksUriClaim = null;
        if (validationType == SoftwareStatementValidationType.JWKS_URI) {
            jwksUriClaim = softwareStatement.getClaims().getClaimAsString(appConfiguration.getSoftwareStatementValidationClaimName());
        }
        String jwksClaim = null;
        if (validationType == SoftwareStatementValidationType.JWKS) {
            jwksClaim = softwareStatement.getClaims().getClaimAsString(appConfiguration.getSoftwareStatementValidationClaimName());
        }
        if (StringUtils.isBlank(jwksUriClaim) && StringUtils.isBlank(jwksClaim)) {
            final String msg = String.format("software_statement does not contain `%s` claim and thus is considered as invalid.", appConfiguration.getSoftwareStatementValidationClaimName());
            log.error(msg);
            throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, msg);
        }
        JSONObject jwks = Strings.isNullOrEmpty(jwksUriClaim) ? new JSONObject(jwksClaim) : JwtUtil.getJSONWebKeys(jwksUriClaim);
        boolean validSignature = cryptoProvider.verifySignature(softwareStatement.getSigningInput(), softwareStatement.getEncodedSignature(), softwareStatement.getHeader().getKeyId(), jwks, null, signatureAlgorithm);
        if (!validSignature) {
            throw new InvalidJwtException("Invalid cryptographic segment in the software statement");
        }
        return softwareStatement.getClaims().toJsonObject();
    } catch (Exception e) {
        final String msg = "Invalid software_statement.";
        log.error(msg, e);
        throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_SOFTWARE_STATEMENT, msg);
    }
}
Also used : InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) JSONObject(org.json.JSONObject) Jwt(io.jans.as.model.jwt.Jwt) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) JSONException(org.json.JSONException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 24 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class AuthorizeService method createJarmRedirectUri.

private String createJarmRedirectUri(RedirectUri redirectUri, Client client, final SessionId session) {
    String jarmRedirectUri = redirectUri.toString();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(client.getAttributes().getAuthorizationSignedResponseAlg());
    redirectUri.setSignatureAlgorithm(signatureAlgorithm);
    redirectUri.addResponseParameter("error", "access_denied");
    redirectUri.addResponseParameter("error_description", "User Denied the Access");
    redirectUri.setIssuer(appConfiguration.getIssuer());
    redirectUri.setAudience(client.getClientId());
    redirectUri.setCryptoProvider(cryptoProvider);
    String keyId = null;
    try {
        String clientSecret = clientService.decryptSecret(client.getClientSecret());
        redirectUri.setSharedSecret(clientSecret);
        keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(webKeysConfiguration, Algorithm.fromString(signatureAlgorithm.getName()), Use.SIGNATURE);
    } catch (CryptoProviderException e) {
        log.error(e.getMessage(), e);
    } catch (StringEncrypter.EncryptionException e) {
        log.error(e.getMessage(), e);
    }
    redirectUri.setKeyId(keyId);
    String jarmQueryString = redirectUri.getQueryString();
    log.info("The JARM Query Response:" + jarmQueryString);
    jarmRedirectUri = jarmRedirectUri + jarmQueryString;
    return jarmRedirectUri;
}
Also used : SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) StringEncrypter(io.jans.util.security.StringEncrypter) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException)

Example 25 with SignatureAlgorithm

use of io.jans.as.model.crypto.signature.SignatureAlgorithm in project jans by JanssenProject.

the class CrossEncryptionTest method nestedJWTProducedByGluu.

@Test
public void nestedJWTProducedByGluu() throws Exception {
    AppConfiguration appConfiguration = new AppConfiguration();
    List<JSONWebKey> keyArrayList = new ArrayList<JSONWebKey>();
    keyArrayList.add(getSenderWebKey());
    JSONWebKeySet keySet = new JSONWebKeySet();
    keySet.setKeys(keyArrayList);
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, keySet, SignatureAlgorithm.RS256, "audience", null, new AbstractCryptoProvider() {

        @Override
        public JSONObject generateKey(Algorithm algorithm, Long expirationTime) throws CryptoProviderException {
            return null;
        }

        @Override
        public JSONObject generateKey(Algorithm algorithm, Long expirationTime, int keyLength) throws CryptoProviderException {
            return null;
        }

        @Override
        public boolean containsKey(String keyId) {
            return false;
        }

        @Override
        public String sign(String signingInput, String keyId, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws CryptoProviderException {
            try {
                RSAPrivateKey privateKey = ((RSAKey) JWK.parse(senderJwkJson)).toRSAPrivateKey();
                Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
                signature.initSign(privateKey);
                signature.update(signingInput.getBytes());
                return Base64Util.base64urlencode(signature.sign());
            } catch (JOSEException | ParseException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {
                throw new CryptoProviderException(e);
            }
        }

        @Override
        public boolean verifySignature(String signingInput, String encodedSignature, String keyId, JSONObject jwks, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws CryptoProviderException {
            return false;
        }

        @Override
        public boolean deleteKey(String keyId) throws CryptoProviderException {
            return false;
        }

        @Override
        public PrivateKey getPrivateKey(String keyId) throws CryptoProviderException {
            throw new UnsupportedOperationException("Method not implemented.");
        }

        @Override
        public PublicKey getPublicKey(String keyId) {
            throw new UnsupportedOperationException("Method not implemented.");
        }
    });
    Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setSubjectIdentifier("testing");
    jwt.getClaims().setIssuer("https:devgluu.saminet.local");
    jwt = jwtSigner.sign();
    RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));
    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.A128GCM;
    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.RSA_OAEP;
    Jwe jwe = new Jwe();
    jwe.getHeader().setType(JwtType.JWT);
    jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
    jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
    jwe.getHeader().setKeyId("1");
    jwe.setSignedJWTPayload(jwt);
    JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
    String jweString = encrypter.encrypt(jwe).toString();
    decryptAndValidateSignatureWithGluu(jweString);
    decryptAndValidateSignatureWithNimbus(jweString);
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) ArrayList(java.util.ArrayList) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) JwtSigner(io.jans.as.server.model.token.JwtSigner) AppConfiguration(io.jans.as.model.configuration.AppConfiguration) Jwe(io.jans.as.model.jwe.Jwe) AbstractCryptoProvider(io.jans.as.model.crypto.AbstractCryptoProvider) PublicKey(java.security.PublicKey) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) Jwt(io.jans.as.model.jwt.Jwt) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException) JSONWebKey(io.jans.as.model.jwk.JSONWebKey) JSONObject(org.json.JSONObject) Signature(java.security.Signature) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) JweEncrypterImpl(io.jans.as.model.jwe.JweEncrypterImpl) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Test(org.testng.annotations.Test)

Aggregations

SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)28 JSONObject (org.json.JSONObject)10 Jwt (io.jans.as.model.jwt.Jwt)8 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)7 HttpException (io.jans.ca.server.HttpException)7 KeyEncryptionAlgorithm (io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm)6 WebApplicationException (javax.ws.rs.WebApplicationException)6 Client (io.jans.as.common.model.registration.Client)5 RSAPublicKey (io.jans.as.model.crypto.signature.RSAPublicKey)5 BlockEncryptionAlgorithm (io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm)4 ECDSAPublicKey (io.jans.as.model.crypto.signature.ECDSAPublicKey)4 Signature (java.security.Signature)4 SignatureException (java.security.SignatureException)4 Date (java.util.Date)4 User (io.jans.as.common.model.common.User)3 AuthenticationMethod (io.jans.as.model.common.AuthenticationMethod)3 CryptoProviderException (io.jans.as.model.exception.CryptoProviderException)3 ECDSASigner (io.jans.as.model.jws.ECDSASigner)3 RegisterRequest (io.jans.as.client.RegisterRequest)2 GrantType (io.jans.as.model.common.GrantType)2