use of io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest 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;
}
use of io.getlime.security.powerauth.rest.api.model.request.v3.EciesEncryptedRequest in project powerauth-restful-integration by lime-company.
the class ActivationService method createActivation.
/**
* Create activation.
*
* @param request Create activation layer 1 request.
* @param eciesContext PowerAuth ECIES encryption context.
* @return Create activation layer 1 response.
* @throws PowerAuthActivationException In case create activation fails.
* @throws PowerAuthRecoveryException In case activation recovery fails.
*/
public ActivationLayer1Response createActivation(ActivationLayer1Request request, EciesEncryptionContext eciesContext) throws PowerAuthActivationException, PowerAuthRecoveryException {
try {
final String applicationKey = eciesContext.getApplicationKey();
final EciesEncryptedRequest activationData = request.getActivationData();
final String ephemeralPublicKey = activationData.getEphemeralPublicKey();
final String encryptedData = activationData.getEncryptedData();
final String mac = activationData.getMac();
final String nonce = activationData.getNonce();
final Map<String, String> identity = request.getIdentityAttributes();
final Map<String, Object> customAttributes = (request.getCustomAttributes() != null) ? request.getCustomAttributes() : new HashMap<>();
// Validate inner encryption
if (nonce == null && !"3.0".equals(eciesContext.getVersion())) {
logger.warn("Missing nonce for protocol version: {}", eciesContext.getVersion());
throw new PowerAuthActivationException();
}
switch(request.getType()) {
// Regular activation which uses "code" identity attribute
case CODE:
{
// Check if identity attributes are present
if (identity == null || identity.isEmpty()) {
logger.warn("Identity attributes are missing for code activation");
throw new PowerAuthActivationException();
}
// Extract data from request and encryption object
final String activationCode = identity.get("code");
if (activationCode == null || activationCode.isEmpty()) {
logger.warn("Activation code is missing");
throw new PowerAuthActivationException();
}
// Call PrepareActivation method on PA server
final PrepareActivationResponse response = powerAuthClient.prepareActivation(activationCode, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce);
// Create context for passing parameters between activation provider calls
final Map<String, Object> context = new LinkedHashMap<>();
Map<String, Object> processedCustomAttributes = customAttributes;
// In case a custom activation provider is enabled, process custom attributes and save any flags
if (activationProvider != null) {
processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context);
List<String> activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context);
if (activationFlags != null && !activationFlags.isEmpty()) {
powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags);
}
}
boolean notifyActivationCommit = false;
if (response.getActivationStatus() == ActivationStatus.ACTIVE) {
// Activation was committed instantly due to presence of Activation OTP.
notifyActivationCommit = true;
} else {
// Otherwise check if activation should be committed instantly and if yes, perform commit.
if (activationProvider != null && activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context)) {
CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null);
notifyActivationCommit = commitResponse.isActivated();
}
}
// Notify activation provider about an activation commit.
if (activationProvider != null && notifyActivationCommit) {
activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.CODE, context);
}
// Prepare and return encrypted response
return prepareEncryptedResponse(response.getEncryptedData(), response.getMac(), processedCustomAttributes);
}
// Custom activation
case CUSTOM:
{
// Check if there is a custom activation provider available, return an error in case it is not available
if (activationProvider == null) {
logger.warn("Activation provider is not available");
throw new PowerAuthActivationException();
}
// Check if identity attributes are present
if (identity == null || identity.isEmpty()) {
logger.warn("Identity attributes are missing for custom activation");
throw new PowerAuthActivationException();
}
// Create context for passing parameters between activation provider calls
final Map<String, Object> context = new LinkedHashMap<>();
// Lookup user ID using a provided identity attributes
final String userId = activationProvider.lookupUserIdForAttributes(identity, context);
// If no user was found or user ID is invalid, return an error
if (userId == null || userId.equals("") || userId.length() > 255) {
logger.warn("Invalid user ID: {}", userId);
throw new PowerAuthActivationException();
}
// Resolve maxFailedCount and activationExpireTimestamp parameters, null value means use value configured on PowerAuth server
final Integer maxFailed = activationProvider.getMaxFailedAttemptCount(identity, customAttributes, userId, ActivationType.CUSTOM, context);
final Long maxFailedCount = maxFailed == null ? null : maxFailed.longValue();
final Long activationValidityPeriod = activationProvider.getValidityPeriodDuringActivation(identity, customAttributes, userId, ActivationType.CUSTOM, context);
Date activationExpireTimestamp = null;
if (activationValidityPeriod != null) {
Instant now = Instant.now();
Instant expiration = now.plusMillis(activationValidityPeriod);
activationExpireTimestamp = Date.from(expiration);
}
// Create activation for a looked up user and application related to the given application key
final CreateActivationResponse response = powerAuthClient.createActivation(userId, activationExpireTimestamp, maxFailedCount, applicationKey, ephemeralPublicKey, encryptedData, mac, nonce);
// Process custom attributes using a custom logic
final Map<String, Object> processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context);
// Save activation flags in case the provider specified any flags
final List<String> activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context);
if (activationFlags != null && !activationFlags.isEmpty()) {
powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags);
}
// Check if activation should be committed instantly and if yes, perform commit
if (activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context)) {
final CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null);
if (commitResponse.isActivated()) {
activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), userId, response.getApplicationId(), ActivationType.CUSTOM, context);
}
}
// Prepare encrypted activation data
final EciesEncryptedResponse encryptedActivationData = new EciesEncryptedResponse(response.getEncryptedData(), response.getMac());
// Prepare the created activation response data
final ActivationLayer1Response responseL1 = new ActivationLayer1Response();
responseL1.setCustomAttributes(processedCustomAttributes);
responseL1.setActivationData(encryptedActivationData);
// Return response
return responseL1;
}
// Activation using recovery code
case RECOVERY:
{
// Check if identity attributes are present
if (identity == null || identity.isEmpty()) {
logger.warn("Identity attributes are missing for activation recovery");
throw new PowerAuthActivationException();
}
// Extract data from request and encryption object
final String recoveryCode = identity.get("recoveryCode");
final String recoveryPuk = identity.get("puk");
if (recoveryCode == null || recoveryCode.isEmpty()) {
logger.warn("Recovery code is missing");
throw new PowerAuthActivationException();
}
if (recoveryPuk == null || recoveryPuk.isEmpty()) {
logger.warn("Recovery PUK is missing");
throw new PowerAuthActivationException();
}
// Create context for passing parameters between activation provider calls
final Map<String, Object> context = new LinkedHashMap<>();
// Resolve maxFailedCount, user ID is not known
Long maxFailedCount = null;
if (activationProvider != null) {
final Integer maxFailed = activationProvider.getMaxFailedAttemptCount(identity, customAttributes, null, ActivationType.RECOVERY, context);
maxFailedCount = maxFailed == null ? null : maxFailed.longValue();
}
// Call RecoveryCodeActivation method on PA server
final RecoveryCodeActivationResponse response = powerAuthClient.createActivationUsingRecoveryCode(recoveryCode, recoveryPuk, applicationKey, maxFailedCount, ephemeralPublicKey, encryptedData, mac, nonce);
Map<String, Object> processedCustomAttributes = customAttributes;
// In case a custom activation provider is enabled, process custom attributes and save any flags
if (activationProvider != null) {
processedCustomAttributes = activationProvider.processCustomActivationAttributes(customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context);
final List<String> activationFlags = activationProvider.getActivationFlags(identity, processedCustomAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context);
if (activationFlags != null && !activationFlags.isEmpty()) {
powerAuthClient.addActivationFlags(response.getActivationId(), activationFlags);
}
}
// Automatically commit activation by default, the optional activation provider can override automatic commit
if (activationProvider == null || activationProvider.shouldAutoCommitActivation(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context)) {
final CommitActivationResponse commitResponse = powerAuthClient.commitActivation(response.getActivationId(), null);
if (activationProvider != null && commitResponse.isActivated()) {
activationProvider.activationWasCommitted(identity, customAttributes, response.getActivationId(), response.getUserId(), response.getApplicationId(), ActivationType.RECOVERY, context);
}
}
// Prepare and return encrypted response
return prepareEncryptedResponse(response.getEncryptedData(), response.getMac(), processedCustomAttributes);
}
default:
logger.warn("Invalid activation request");
throw new PowerAuthInvalidRequestException();
}
} catch (PowerAuthClientException ex) {
if (ex.getPowerAuthError() instanceof PowerAuthErrorRecovery) {
final PowerAuthErrorRecovery errorRecovery = (PowerAuthErrorRecovery) ex.getPowerAuthError();
logger.debug("Invalid recovery code, current PUK index: {}", errorRecovery.getCurrentRecoveryPukIndex());
throw new PowerAuthRecoveryException(ex.getMessage(), "INVALID_RECOVERY_CODE", errorRecovery.getCurrentRecoveryPukIndex());
}
logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage());
logger.debug(ex.getMessage(), ex);
throw new PowerAuthActivationException();
} catch (PowerAuthActivationException ex) {
// Do not swallow PowerAuthActivationException for custom activations.
// See: https://github.com/wultra/powerauth-restful-integration/issues/199
logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage());
throw ex;
} catch (Exception ex) {
logger.warn("Creating PowerAuth activation failed, error: {}", ex.getMessage());
logger.debug(ex.getMessage(), ex);
throw new PowerAuthActivationException();
}
}
Aggregations