Search in sources :

Example 1 with SignatureAlgorithm

use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class OxAuthCryptoProvider method getSignatureAlgorithm.

public SignatureAlgorithm getSignatureAlgorithm(String alias) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    Certificate[] chain = keyStore.getCertificateChain(alias);
    if ((chain == null) || chain.length == 0) {
        return null;
    }
    X509Certificate cert = (X509Certificate) chain[0];
    String sighAlgName = cert.getSigAlgName();
    for (SignatureAlgorithm sa : SignatureAlgorithm.values()) {
        if (sighAlgName.equalsIgnoreCase(sa.getAlgorithm())) {
            return sa;
        }
    }
    return null;
}
Also used : SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 2 with SignatureAlgorithm

use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class AbstractCryptoProvider method getPublicKey.

public PublicKey getPublicKey(String alias, JSONObject jwks) throws Exception {
    java.security.PublicKey publicKey = null;
    JSONArray webKeys = jwks.getJSONArray(JSON_WEB_KEY_SET);
    for (int i = 0; i < webKeys.length(); i++) {
        JSONObject key = webKeys.getJSONObject(i);
        if (alias.equals(key.getString(KEY_ID))) {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(key.getString(ALGORITHM));
            if (signatureAlgorithm != null) {
                if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.RSA)) {
                    publicKey = new RSAPublicKeyImpl(new BigInteger(1, Base64Util.base64urldecode(key.getString(MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(EXPONENT))));
                } else if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.EC)) {
                    AlgorithmParameters parameters = AlgorithmParameters.getInstance(SignatureAlgorithmFamily.EC);
                    parameters.init(new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()));
                    ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
                    publicKey = KeyFactory.getInstance(SignatureAlgorithmFamily.EC).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(Y)))), ecParameters));
                }
            }
        }
    }
    return publicKey;
}
Also used : RSAPublicKeyImpl(sun.security.rsa.RSAPublicKeyImpl) JSONArray(org.codehaus.jettison.json.JSONArray) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) PublicKey(java.security.PublicKey) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) ECPoint(java.security.spec.ECPoint) ECPoint(java.security.spec.ECPoint) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) JSONObject(org.codehaus.jettison.json.JSONObject) ECParameterSpec(java.security.spec.ECParameterSpec) BigInteger(java.math.BigInteger) AlgorithmParameters(java.security.AlgorithmParameters)

Example 3 with SignatureAlgorithm

use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class UserInfoRestWebServiceImpl method requestUserInfo.

public Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
    if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) {
        accessToken = authorization.substring(7);
    }
    log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
    Response.ResponseBuilder builder = Response.ok();
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
    try {
        if (!UserInfoParamsValidator.validateParams(accessToken)) {
            builder = Response.status(400);
            builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_REQUEST));
        } else {
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
            if (authorizationGrant == null) {
                builder = Response.status(400);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_TOKEN));
            } else if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
                builder = Response.status(403);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
            } else if (!authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
                builder = Response.status(403);
                builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
                oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
            } else {
                oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
                CacheControl cacheControl = new CacheControl();
                cacheControl.setPrivate(true);
                cacheControl.setNoTransform(false);
                cacheControl.setNoStore(true);
                builder.cacheControl(cacheControl);
                builder.header("Pragma", "no-cache");
                User currentUser = authorizationGrant.getUser();
                try {
                    currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
                } catch (EntryPersistenceException ex) {
                    log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
                }
                if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
                    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
                    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
                    builder.type("application/jwt");
                    builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
                } else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
                    SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
                    builder.type("application/jwt");
                    builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
                } else {
                    builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
                    builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
                }
            }
        }
    } catch (StringEncrypter.EncryptionException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidJwtException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (SignatureException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    } catch (Exception e) {
        // 500
        builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) OAuth2AuditLog(org.xdi.oxauth.model.audit.OAuth2AuditLog) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) SignatureException(java.security.SignatureException) InvalidClaimException(org.xdi.oxauth.model.exception.InvalidClaimException) StringEncrypter(org.xdi.util.security.StringEncrypter) InvalidJwtException(org.xdi.oxauth.model.exception.InvalidJwtException) SignatureException(java.security.SignatureException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvalidClaimException(org.xdi.oxauth.model.exception.InvalidClaimException) EntryPersistenceException(org.gluu.site.ldap.persistence.exception.EntryPersistenceException) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) BlockEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.BlockEncryptionAlgorithm) JsonWebResponse(org.xdi.oxauth.model.token.JsonWebResponse) Response(javax.ws.rs.core.Response) KeyEncryptionAlgorithm(org.xdi.oxauth.model.crypto.encryption.KeyEncryptionAlgorithm) CacheControl(javax.ws.rs.core.CacheControl)

Example 4 with SignatureAlgorithm

use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class JwtSigner method newJwtSigner.

public static JwtSigner newJwtSigner(AppConfiguration appConfiguration, JSONWebKeySet webKeys, Client client) throws Exception {
    Preconditions.checkNotNull(client);
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getIdTokenSignedResponseAlg() != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getIdTokenSignedResponseAlg());
    }
    ClientService clientService = CdiUtil.bean(ClientService.class);
    return new JwtSigner(appConfiguration, webKeys, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
}
Also used : ClientService(org.xdi.oxauth.service.ClientService) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm)

Example 5 with SignatureAlgorithm

use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.

the class ClientAssertion method load.

private boolean load(AppConfiguration appConfiguration, String clientId, 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();
                if (audience != null && audience.contains(tokenUrl)) {
                    // 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().getAlgorithm();
                            if (jwtType == null && signatureAlgorithm != null) {
                                jwtType = signatureAlgorithm.getJwtType();
                            }
                            if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && signatureAlgorithm.getFamily().equals("HMAC")) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (signatureAlgorithm.getFamily().equals("RSA") || signatureAlgorithm.getFamily().equals("EC"))))) {
                                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());
                                AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
                                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 authentication method");
                            }
                        } else {
                            throw new InvalidJwtException("Invalid client");
                        }
                    } else {
                        throw new InvalidJwtException("JWT has expired");
                    }
                } else {
                    throw new InvalidJwtException("Invalid audience: " + audience + ", tokenUrl: " + tokenUrl);
                }
            } 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(org.xdi.oxauth.model.exception.InvalidJwtException) JSONObject(org.codehaus.jettison.json.JSONObject) ClientService(org.xdi.oxauth.service.ClientService) JwtType(org.xdi.oxauth.model.jwt.JwtType) SignatureAlgorithm(org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm) AbstractCryptoProvider(org.xdi.oxauth.model.crypto.AbstractCryptoProvider) AuthenticationMethod(org.xdi.oxauth.model.common.AuthenticationMethod) Client(org.xdi.oxauth.model.registration.Client) Date(java.util.Date)

Aggregations

SignatureAlgorithm (org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm)5 JSONObject (org.codehaus.jettison.json.JSONObject)2 InvalidJwtException (org.xdi.oxauth.model.exception.InvalidJwtException)2 ClientService (org.xdi.oxauth.service.ClientService)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 BigInteger (java.math.BigInteger)1 AlgorithmParameters (java.security.AlgorithmParameters)1 PublicKey (java.security.PublicKey)1 SignatureException (java.security.SignatureException)1 Certificate (java.security.cert.Certificate)1 X509Certificate (java.security.cert.X509Certificate)1 ECGenParameterSpec (java.security.spec.ECGenParameterSpec)1 ECParameterSpec (java.security.spec.ECParameterSpec)1 ECPoint (java.security.spec.ECPoint)1 ECPublicKeySpec (java.security.spec.ECPublicKeySpec)1 Date (java.util.Date)1 CacheControl (javax.ws.rs.core.CacheControl)1 Response (javax.ws.rs.core.Response)1 JSONArray (org.codehaus.jettison.json.JSONArray)1 EntryPersistenceException (org.gluu.site.ldap.persistence.exception.EntryPersistenceException)1