Search in sources :

Example 1 with PowerAuthEncryptionException

use of io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException in project powerauth-restful-integration by lime-company.

the class PowerAuthEncryptionProvider method getEciesDecryptorParameters.

@Override
@Nonnull
public PowerAuthEciesDecryptorParameters getEciesDecryptorParameters(@Nullable String activationId, @Nonnull String applicationKey, @Nonnull String ephemeralPublicKey) throws PowerAuthEncryptionException {
    try {
        GetEciesDecryptorRequest eciesDecryptorRequest = new GetEciesDecryptorRequest();
        eciesDecryptorRequest.setActivationId(activationId);
        eciesDecryptorRequest.setApplicationKey(applicationKey);
        eciesDecryptorRequest.setEphemeralPublicKey(ephemeralPublicKey);
        GetEciesDecryptorResponse eciesDecryptorResponse = powerAuthClient.getEciesDecryptor(eciesDecryptorRequest);
        return new PowerAuthEciesDecryptorParameters(eciesDecryptorResponse.getSecretKey(), eciesDecryptorResponse.getSharedInfo2());
    } catch (Exception ex) {
        logger.warn("Get ECIES decryptor call failed, error: {}", ex.getMessage());
        logger.debug(ex.getMessage(), ex);
        throw new PowerAuthEncryptionException();
    }
}
Also used : PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) GetEciesDecryptorRequest(com.wultra.security.powerauth.client.v3.GetEciesDecryptorRequest) GetEciesDecryptorResponse(com.wultra.security.powerauth.client.v3.GetEciesDecryptorResponse) PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) PowerAuthEciesDecryptorParameters(io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesDecryptorParameters) Nonnull(javax.annotation.Nonnull)

Example 2 with PowerAuthEncryptionException

use of io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException in project powerauth-restful-integration by lime-company.

the class PowerAuthEncryptionProviderBase method extractEciesEncryptionContext.

/**
 * Extract context required for ECIES encryption from either encryption or signature HTTP header.
 *
 * @param request HTTP servlet request.
 * @return Context for ECIES encryption.
 * @throws PowerAuthEncryptionException Thrown when HTTP header with ECIES data is invalid.
 */
private EciesEncryptionContext extractEciesEncryptionContext(HttpServletRequest request) throws PowerAuthEncryptionException {
    final String encryptionHttpHeader = request.getHeader(PowerAuthEncryptionHttpHeader.HEADER_NAME);
    final String signatureHttpHeader = request.getHeader(PowerAuthSignatureHttpHeader.HEADER_NAME);
    // Check that at least one PowerAuth HTTP header with parameters for ECIES is present
    if (encryptionHttpHeader == null && signatureHttpHeader == null) {
        logger.warn("Neither signature nor encryption HTTP header is present");
        throw new PowerAuthEncryptionException();
    }
    // In case the PowerAuth signature HTTP header is present, use it for ECIES
    if (signatureHttpHeader != null) {
        // Parse signature HTTP header
        final PowerAuthSignatureHttpHeader header = new PowerAuthSignatureHttpHeader().fromValue(signatureHttpHeader);
        // Validate the signature HTTP header
        try {
            PowerAuthSignatureHttpHeaderValidator.validate(header);
        } catch (InvalidPowerAuthHttpHeaderException ex) {
            logger.warn("Signature HTTP header validation failed, error: {}", ex.getMessage());
            logger.debug(ex.getMessage(), ex);
            throw new PowerAuthEncryptionException();
        }
        // Construct encryption parameters object
        final String applicationKey = header.getApplicationKey();
        final String activationId = header.getActivationId();
        final String version = header.getVersion();
        return new EciesEncryptionContext(applicationKey, activationId, version, header);
    } else {
        // Parse encryption HTTP header
        final PowerAuthEncryptionHttpHeader header = new PowerAuthEncryptionHttpHeader().fromValue(encryptionHttpHeader);
        // Validate the encryption HTTP header
        try {
            PowerAuthEncryptionHttpHeaderValidator.validate(header);
        } catch (InvalidPowerAuthHttpHeaderException ex) {
            logger.warn("Encryption validation failed, error: {}", ex.getMessage());
            logger.debug(ex.getMessage(), ex);
            throw new PowerAuthEncryptionException();
        }
        // Construct encryption parameters object
        final String applicationKey = header.getApplicationKey();
        final String activationId = header.getActivationId();
        final String version = header.getVersion();
        return new EciesEncryptionContext(applicationKey, activationId, version, header);
    }
}
Also used : PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) InvalidPowerAuthHttpHeaderException(io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException) PowerAuthSignatureHttpHeader(io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader) PowerAuthEncryptionHttpHeader(io.getlime.security.powerauth.http.PowerAuthEncryptionHttpHeader) EciesEncryptionContext(io.getlime.security.powerauth.rest.api.spring.encryption.EciesEncryptionContext)

Example 3 with PowerAuthEncryptionException

use of io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException in project powerauth-restful-integration by lime-company.

the class PowerAuthEncryptionProviderBase method decryptRequest.

/**
 * Decrypt HTTP request body and construct object with ECIES data. Use the requestType parameter to specify
 * the type of decrypted object.
 *
 * @param request HTTP request.
 * @param requestType Class of request object.
 * @param eciesScope ECIES scope.
 * @return Object with ECIES data.
 * @throws PowerAuthEncryptionException In case request decryption fails.
 */
@Nonnull
public PowerAuthEciesEncryption decryptRequest(@Nonnull HttpServletRequest request, @Nonnull Type requestType, @Nonnull EciesScope eciesScope) throws PowerAuthEncryptionException {
    // Only POST HTTP method is supported for ECIES
    if (!"POST".equals(request.getMethod())) {
        logger.warn("Invalid HTTP method: {}", request.getMethod());
        throw new PowerAuthEncryptionException();
    }
    // Resolve either signature or encryption HTTP header for ECIES
    final EciesEncryptionContext encryptionContext = extractEciesEncryptionContext(request);
    // Construct ECIES encryption object from HTTP header
    final PowerAuthEciesEncryption eciesEncryption = new PowerAuthEciesEncryption(encryptionContext);
    // Save ECIES scope in context
    eciesEncryption.getContext().setEciesScope(eciesScope);
    try {
        // Parse ECIES cryptogram from request body
        final PowerAuthRequestBody requestBody = ((PowerAuthRequestBody) request.getAttribute(PowerAuthRequestObjects.REQUEST_BODY));
        if (requestBody == null) {
            logger.warn("The X-PowerAuth-Request-Body request attribute is missing. Register the PowerAuthRequestFilter to fix this error.");
            throw new PowerAuthEncryptionException();
        }
        final byte[] requestBodyBytes = requestBody.getRequestBytes();
        if (requestBodyBytes == null || requestBodyBytes.length == 0) {
            logger.warn("Invalid HTTP request");
            throw new PowerAuthEncryptionException();
        }
        final EciesEncryptedRequest eciesRequest = objectMapper.readValue(requestBodyBytes, EciesEncryptedRequest.class);
        if (eciesRequest == null) {
            logger.warn("Invalid ECIES request data");
            throw new PowerAuthEncryptionException();
        }
        // Prepare ephemeral public key
        final String ephemeralPublicKey = eciesRequest.getEphemeralPublicKey();
        final String encryptedData = eciesRequest.getEncryptedData();
        final String mac = eciesRequest.getMac();
        final String nonce = eciesRequest.getNonce();
        // Verify ECIES request data. Nonce is required for protocol 3.1+
        if (ephemeralPublicKey == null || encryptedData == null || mac == null) {
            logger.warn("Invalid ECIES request data");
            throw new PowerAuthEncryptionException();
        }
        if (nonce == null && !"3.0".equals(encryptionContext.getVersion())) {
            logger.warn("Missing nonce in ECIES request data");
            throw new PowerAuthEncryptionException();
        }
        final byte[] ephemeralPublicKeyBytes = BaseEncoding.base64().decode(ephemeralPublicKey);
        final byte[] encryptedDataBytes = BaseEncoding.base64().decode(encryptedData);
        final byte[] macBytes = BaseEncoding.base64().decode(mac);
        final byte[] nonceBytes = nonce != null ? BaseEncoding.base64().decode(nonce) : null;
        final String applicationKey = eciesEncryption.getContext().getApplicationKey();
        final PowerAuthEciesDecryptorParameters decryptorParameters;
        // Obtain ECIES decryptor parameters from PowerAuth server
        switch(eciesScope) {
            case ACTIVATION_SCOPE:
                final String activationId = eciesEncryption.getContext().getActivationId();
                if (activationId == null) {
                    logger.warn("Activation ID is required in ECIES activation scope");
                    throw new PowerAuthEncryptionException();
                }
                decryptorParameters = getEciesDecryptorParameters(activationId, applicationKey, ephemeralPublicKey);
                break;
            case APPLICATION_SCOPE:
                decryptorParameters = getEciesDecryptorParameters(null, applicationKey, ephemeralPublicKey);
                break;
            default:
                logger.warn("Unsupported ECIES scope: {}", eciesScope);
                throw new PowerAuthEncryptionException();
        }
        // Prepare envelope key and sharedInfo2 parameter for decryptor
        final byte[] secretKey = BaseEncoding.base64().decode(decryptorParameters.getSecretKey());
        final EciesEnvelopeKey envelopeKey = new EciesEnvelopeKey(secretKey, ephemeralPublicKeyBytes);
        final byte[] sharedInfo2 = BaseEncoding.base64().decode(decryptorParameters.getSharedInfo2());
        // Construct decryptor and set it to the request for later encryption of response
        final EciesDecryptor eciesDecryptor = eciesFactory.getEciesDecryptor(envelopeKey, sharedInfo2);
        eciesEncryption.setEciesDecryptor(eciesDecryptor);
        // Decrypt request data
        final EciesCryptogram cryptogram = new EciesCryptogram(ephemeralPublicKeyBytes, macBytes, encryptedDataBytes, nonceBytes);
        final byte[] decryptedData = eciesDecryptor.decryptRequest(cryptogram);
        eciesEncryption.setEncryptedRequest(encryptedDataBytes);
        eciesEncryption.setDecryptedRequest(decryptedData);
        // Set the request object only in case when request data is sent
        if (decryptedData.length != 0) {
            eciesEncryption.setRequestObject(deserializeRequestData(decryptedData, requestType));
        }
        // Set encryption object in HTTP servlet request
        request.setAttribute(PowerAuthRequestObjects.ENCRYPTION_OBJECT, eciesEncryption);
    } catch (Exception ex) {
        logger.debug("Request decryption failed, error: " + ex.getMessage(), ex);
        throw new PowerAuthEncryptionException();
    }
    return eciesEncryption;
}
Also used : EciesCryptogram(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesCryptogram) PowerAuthEciesEncryption(io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesEncryption) PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) EciesEncryptedRequest(io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest) PowerAuthRequestBody(io.getlime.security.powerauth.rest.api.spring.model.PowerAuthRequestBody) EciesEnvelopeKey(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesEnvelopeKey) EciesDecryptor(io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor) PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) InvalidPowerAuthHttpHeaderException(io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) EciesEncryptionContext(io.getlime.security.powerauth.rest.api.spring.encryption.EciesEncryptionContext) PowerAuthEciesDecryptorParameters(io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesDecryptorParameters) Nonnull(javax.annotation.Nonnull)

Example 4 with PowerAuthEncryptionException

use of io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException in project powerauth-restful-integration by lime-company.

the class PowerAuthAnnotationInterceptor method preHandle.

@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
    // requests before the actual requests.
    if (handler instanceof HandlerMethod) {
        final HandlerMethod handlerMethod = (HandlerMethod) handler;
        // Obtain annotations
        PowerAuth powerAuthSignatureAnnotation = handlerMethod.getMethodAnnotation(PowerAuth.class);
        PowerAuthToken powerAuthTokenAnnotation = handlerMethod.getMethodAnnotation(PowerAuthToken.class);
        PowerAuthEncryption powerAuthEncryptionAnnotation = handlerMethod.getMethodAnnotation(PowerAuthEncryption.class);
        // Check that either signature or token annotation is active
        if (powerAuthSignatureAnnotation != null && powerAuthTokenAnnotation != null) {
            logger.warn("You cannot use both @PowerAuth and @PowerAuthToken on same handler method. We are removing both.");
            powerAuthSignatureAnnotation = null;
            powerAuthTokenAnnotation = null;
        }
        // sign-then-encrypt sequence in case both authorization and encryption are used.
        if (powerAuthEncryptionAnnotation != null) {
            final Type requestType = resolveGenericParameterTypeForEcies(handlerMethod);
            try {
                encryptionProvider.decryptRequest(request, requestType, powerAuthEncryptionAnnotation.scope());
            // Encryption object is saved in HTTP servlet request by encryption provider, so that it is available for Spring
            } catch (PowerAuthEncryptionException ex) {
                logger.warn("Decryption failed, error: {}", ex.getMessage());
                logger.debug("Error details", ex);
            }
        }
        // Resolve @PowerAuth annotation
        if (powerAuthSignatureAnnotation != null) {
            try {
                final String resourceId = expandResourceId(powerAuthSignatureAnnotation.resourceId(), request, handlerMethod);
                final String header = request.getHeader(PowerAuthSignatureHttpHeader.HEADER_NAME);
                final List<PowerAuthSignatureTypes> signatureTypes = Arrays.asList(powerAuthSignatureAnnotation.signatureType());
                final PowerAuthApiAuthentication authentication = authenticationProvider.validateRequestSignatureWithActivationDetails(request, resourceId, header, signatureTypes);
                request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, authentication);
            } catch (PowerAuthAuthenticationException ex) {
                logger.warn("Invalid request signature, authentication object was removed");
                request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, null);
            }
        }
        // Resolve @PowerAuthToken annotation
        if (powerAuthTokenAnnotation != null) {
            try {
                final String header = request.getHeader(PowerAuthTokenHttpHeader.HEADER_NAME);
                final List<PowerAuthSignatureTypes> signatureTypes = Arrays.asList(powerAuthTokenAnnotation.signatureType());
                final PowerAuthApiAuthentication authentication = authenticationProvider.validateTokenWithActivationDetails(header, signatureTypes);
                request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, authentication);
            } catch (PowerAuthAuthenticationException ex) {
                logger.warn("Invalid token, authentication object was removed");
                request.setAttribute(PowerAuthRequestObjects.AUTHENTICATION_OBJECT, null);
            }
        }
    }
    return true;
}
Also used : Type(java.lang.reflect.Type) PowerAuth(io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuth) PowerAuthToken(io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuthToken) PowerAuthEncryptionException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException) PowerAuthEncryption(io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuthEncryption) PowerAuthAuthenticationException(io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthAuthenticationException) PowerAuthSignatureTypes(io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes) PowerAuthApiAuthentication(io.getlime.security.powerauth.rest.api.spring.authentication.PowerAuthApiAuthentication) HandlerMethod(org.springframework.web.method.HandlerMethod)

Aggregations

PowerAuthEncryptionException (io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthEncryptionException)4 InvalidPowerAuthHttpHeaderException (io.getlime.security.powerauth.http.validator.InvalidPowerAuthHttpHeaderException)2 EciesEncryptionContext (io.getlime.security.powerauth.rest.api.spring.encryption.EciesEncryptionContext)2 PowerAuthEciesDecryptorParameters (io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesDecryptorParameters)2 Nonnull (javax.annotation.Nonnull)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 GetEciesDecryptorRequest (com.wultra.security.powerauth.client.v3.GetEciesDecryptorRequest)1 GetEciesDecryptorResponse (com.wultra.security.powerauth.client.v3.GetEciesDecryptorResponse)1 EciesDecryptor (io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesDecryptor)1 EciesEnvelopeKey (io.getlime.security.powerauth.crypto.lib.encryptor.ecies.EciesEnvelopeKey)1 EciesCryptogram (io.getlime.security.powerauth.crypto.lib.encryptor.ecies.model.EciesCryptogram)1 PowerAuthSignatureTypes (io.getlime.security.powerauth.crypto.lib.enums.PowerAuthSignatureTypes)1 PowerAuthEncryptionHttpHeader (io.getlime.security.powerauth.http.PowerAuthEncryptionHttpHeader)1 PowerAuthSignatureHttpHeader (io.getlime.security.powerauth.http.PowerAuthSignatureHttpHeader)1 EciesEncryptedRequest (io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest)1 PowerAuth (io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuth)1 PowerAuthEncryption (io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuthEncryption)1 PowerAuthToken (io.getlime.security.powerauth.rest.api.spring.annotation.PowerAuthToken)1 PowerAuthApiAuthentication (io.getlime.security.powerauth.rest.api.spring.authentication.PowerAuthApiAuthentication)1 PowerAuthEciesEncryption (io.getlime.security.powerauth.rest.api.spring.encryption.PowerAuthEciesEncryption)1