use of java.security.ProviderException in project zaproxy by zaproxy.
the class OptionsCertificatePanel method addPkcs11ButtonActionPerformed.
//GEN-LAST:event_showActiveCertificateButtonActionPerformed
private void addPkcs11ButtonActionPerformed(java.awt.event.ActionEvent evt) {
//GEN-FIRST:event_addPkcs11ButtonActionPerformed
String name = null;
try {
final int indexSelectedDriver = driverComboBox.getSelectedIndex();
name = driverConfig.getNames().get(indexSelectedDriver);
if (name.equals("")) {
return;
}
String library = driverConfig.getPaths().get(indexSelectedDriver);
if (library.equals("")) {
return;
}
int slot = driverConfig.getSlots().get(indexSelectedDriver).intValue();
if (slot < 0) {
return;
}
int slotListIndex = driverConfig.getSlotIndexes().get(indexSelectedDriver).intValue();
if (slotListIndex < 0) {
return;
}
String kspass = new String(pkcs11PasswordField.getPassword());
if (kspass.equals("")) {
kspass = null;
}
PCKS11ConfigurationBuilder confBuilder = PKCS11Configuration.builder();
confBuilder.setName(name).setLibrary(library);
if (usePkcs11ExperimentalSliSupportCheckBox.isSelected()) {
confBuilder.setSlotListIndex(slotListIndex);
} else {
confBuilder.setSlotId(slot);
}
int ksIndex = contextManager.initPKCS11(confBuilder.build(), kspass);
if (ksIndex == -1) {
logger.error("The required PKCS#11 provider is not available (" + SSLContextManager.SUN_PKCS11_CANONICAL_CLASS_NAME + " or " + SSLContextManager.IBM_PKCS11_CONONICAL_CLASS_NAME + ").");
showErrorMessageSunPkcs11ProviderNotAvailable();
return;
}
// The PCKS11 driver/smartcard was initialized properly: reset login attempts
login_attempts = 0;
keyStoreListModel.insertElementAt(contextManager.getKeyStoreDescription(ksIndex), ksIndex);
// Issue 182
retry = true;
certificatejTabbedPane.setSelectedIndex(0);
selectFirstAliasOfKeyStore(ksIndex);
driverComboBox.setSelectedIndex(-1);
pkcs11PasswordField.setText("");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ProviderException) {
if ("Error parsing configuration".equals(e.getCause().getMessage())) {
// There was a problem with the configuration provided:
// - Missing library.
// - Malformed configuration.
// - ...
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from " + name, e.getCause());
} else if ("Initialization failed".equals(e.getCause().getMessage())) {
// conflicts with other software (eg. Firefox), that is accessing it too.
if (retry) {
// Try two times only
retry = false;
addPkcs11ButtonActionPerformed(evt);
} else {
JOptionPane.showMessageDialog(null, new String[] { Constant.messages.getString("options.cert.error"), Constant.messages.getString("options.cert.error.pkcs11") }, Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
// Error message changed to explain that user should try to add it again...
retry = true;
logger.warn("Couldn't add key from " + name, e);
}
} else {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from " + name, e);
}
} else {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.error("Couldn't add key from " + name, e);
}
} catch (java.io.IOException e) {
if (e.getMessage().equals("load failed") && e.getCause().getClass().getName().equals("javax.security.auth.login.FailedLoginException")) {
// Exception due to a failed login attempt: BAD PIN or password
login_attempts++;
String attempts = " (" + login_attempts + "/" + MAX_LOGIN_ATTEMPTS + ") ";
if (login_attempts == (MAX_LOGIN_ATTEMPTS - 1)) {
// Last attempt before blocking the smartcard
JOptionPane.showMessageDialog(null, new String[] { Constant.messages.getString("options.cert.error"), Constant.messages.getString("options.cert.error.wrongpassword"), Constant.messages.getString("options.cert.error.wrongpasswordlast"), attempts }, Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password" + attempts + ": " + name + " *LAST TRY BEFORE BLOCKING*");
} else {
JOptionPane.showMessageDialog(null, new String[] { Constant.messages.getString("options.cert.error"), Constant.messages.getString("options.cert.error.wrongpassword"), attempts }, Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password" + attempts + ": " + name);
}
} else {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from " + name, e);
}
} catch (KeyStoreException e) {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.warn("Couldn't add key from " + name, e);
} catch (Exception e) {
showGenericErrorMessagePkcs11CouldNotBeAdded();
logger.error("Couldn't add key from " + name, e);
}
}
use of java.security.ProviderException in project android_frameworks_base by DirtyUnicorns.
the class AndroidKeyStoreSignatureSpiBase method ensureKeystoreOperationInitialized.
private void ensureKeystoreOperationInitialized() throws InvalidKeyException {
if (mMessageStreamer != null) {
return;
}
if (mCachedException != null) {
return;
}
if (mKey == null) {
throw new IllegalStateException("Not initialized");
}
KeymasterArguments keymasterInputArgs = new KeymasterArguments();
addAlgorithmSpecificParametersToBegin(keymasterInputArgs);
OperationResult opResult = mKeyStore.begin(mKey.getAlias(), mSigning ? KeymasterDefs.KM_PURPOSE_SIGN : KeymasterDefs.KM_PURPOSE_VERIFY, // permit aborting this operation if keystore runs out of resources
true, keymasterInputArgs, // no additional entropy for begin -- only finish might need some
null, mKey.getUid());
if (opResult == null) {
throw new KeyStoreConnectException();
}
// Store operation token and handle regardless of the error code returned by KeyStore to
// ensure that the operation gets aborted immediately if the code below throws an exception.
mOperationToken = opResult.token;
mOperationHandle = opResult.operationHandle;
// If necessary, throw an exception due to KeyStore operation having failed.
InvalidKeyException e = KeyStoreCryptoOperationUtils.getInvalidKeyExceptionForInit(mKeyStore, mKey, opResult.resultCode);
if (e != null) {
throw e;
}
if (mOperationToken == null) {
throw new ProviderException("Keystore returned null operation token");
}
if (mOperationHandle == 0) {
throw new ProviderException("Keystore returned invalid operation handle");
}
mMessageStreamer = createMainDataStreamer(mKeyStore, opResult.token);
}
use of java.security.ProviderException in project android_frameworks_base by DirtyUnicorns.
the class AndroidKeyStoreUnauthenticatedAESCipherSpi method loadAlgorithmSpecificParametersFromBeginResult.
@Override
protected final void loadAlgorithmSpecificParametersFromBeginResult(@NonNull KeymasterArguments keymasterArgs) {
mIvHasBeenUsed = true;
// NOTE: Keymaster doesn't always return an IV, even if it's used.
byte[] returnedIv = keymasterArgs.getBytes(KeymasterDefs.KM_TAG_NONCE, null);
if ((returnedIv != null) && (returnedIv.length == 0)) {
returnedIv = null;
}
if (mIvRequired) {
if (mIv == null) {
mIv = returnedIv;
} else if ((returnedIv != null) && (!Arrays.equals(returnedIv, mIv))) {
throw new ProviderException("IV in use differs from provided IV");
}
} else {
if (returnedIv != null) {
throw new ProviderException("IV in use despite IV not being used by this transformation");
}
}
}
use of java.security.ProviderException in project android_frameworks_base by DirtyUnicorns.
the class KeyStoreCryptoOperationChunkedStreamer method flush.
public byte[] flush() throws KeyStoreException {
if (mBufferedLength <= 0) {
return EmptyArray.BYTE;
}
// Keep invoking the update operation with remaining buffered data until either all of the
// buffered data is consumed or until update fails to consume anything.
ByteArrayOutputStream bufferedOutput = null;
while (mBufferedLength > 0) {
byte[] chunk = ArrayUtils.subarray(mBuffered, mBufferedOffset, mBufferedLength);
OperationResult opResult = mKeyStoreStream.update(chunk);
if (opResult == null) {
throw new KeyStoreConnectException();
} else if (opResult.resultCode != KeyStore.NO_ERROR) {
throw KeyStore.getKeyStoreException(opResult.resultCode);
}
if (opResult.inputConsumed <= 0) {
// Nothing was consumed. Break out of the loop to avoid an infinite loop.
break;
}
if (opResult.inputConsumed >= chunk.length) {
// All of the input was consumed
mBuffered = EmptyArray.BYTE;
mBufferedOffset = 0;
mBufferedLength = 0;
} else {
// Some of the input was not consumed
mBuffered = chunk;
mBufferedOffset = opResult.inputConsumed;
mBufferedLength = chunk.length - opResult.inputConsumed;
}
if (opResult.inputConsumed > chunk.length) {
throw new KeyStoreException(KeymasterDefs.KM_ERROR_UNKNOWN_ERROR, "Keystore consumed more input than provided. Provided: " + chunk.length + ", consumed: " + opResult.inputConsumed);
}
if ((opResult.output != null) && (opResult.output.length > 0)) {
// Some output was produced by this update operation
if (bufferedOutput == null) {
// No output buffered yet.
if (mBufferedLength == 0) {
// No more output will be produced by this flush operation
mProducedOutputSizeBytes += opResult.output.length;
return opResult.output;
} else {
// More output might be produced by this flush operation -- buffer output.
bufferedOutput = new ByteArrayOutputStream();
}
}
// Buffer the output from this update operation
try {
bufferedOutput.write(opResult.output);
} catch (IOException e) {
throw new ProviderException("Failed to buffer output", e);
}
}
}
if (mBufferedLength > 0) {
throw new KeyStoreException(KeymasterDefs.KM_ERROR_INVALID_INPUT_LENGTH, "Keystore failed to consume last " + ((mBufferedLength != 1) ? (mBufferedLength + " bytes") : "byte") + " of input");
}
byte[] result = (bufferedOutput != null) ? bufferedOutput.toByteArray() : EmptyArray.BYTE;
mProducedOutputSizeBytes += result.length;
return result;
}
use of java.security.ProviderException in project android_frameworks_base by DirtyUnicorns.
the class KeymasterUtils method addUserAuthArgs.
/**
* Adds keymaster arguments to express the key's authorization policy supported by user
* authentication.
*
* @param userAuthenticationRequired whether user authentication is required to authorize the
* use of the key.
* @param userAuthenticationValidityDurationSeconds duration of time (seconds) for which user
* authentication is valid as authorization for using the key or {@code -1} if every
* use of the key needs authorization.
*
* @throws IllegalStateException if user authentication is required but the system is in a wrong
* state (e.g., secure lock screen not set up) for generating or importing keys that
* require user authentication.
*/
public static void addUserAuthArgs(KeymasterArguments args, boolean userAuthenticationRequired, int userAuthenticationValidityDurationSeconds, boolean userAuthenticationValidWhileOnBody, boolean invalidatedByBiometricEnrollment) {
if (!userAuthenticationRequired) {
args.addBoolean(KeymasterDefs.KM_TAG_NO_AUTH_REQUIRED);
return;
}
if (userAuthenticationValidityDurationSeconds == -1) {
// Every use of this key needs to be authorized by the user. This currently means
// fingerprint-only auth.
FingerprintManager fingerprintManager = KeyStore.getApplicationContext().getSystemService(FingerprintManager.class);
// TODO: Restore USE_FINGERPRINT permission check in
// FingerprintManager.getAuthenticatorId once the ID is no longer needed here.
long fingerprintOnlySid = (fingerprintManager != null) ? fingerprintManager.getAuthenticatorId() : 0;
if (fingerprintOnlySid == 0) {
throw new IllegalStateException("At least one fingerprint must be enrolled to create keys requiring user" + " authentication for every use");
}
long sid;
if (invalidatedByBiometricEnrollment) {
// The fingerprint-only SID will change on fingerprint enrollment or removal of all,
// enrolled fingerprints, invalidating the key.
sid = fingerprintOnlySid;
} else {
// The root SID will *not* change on fingerprint enrollment, or removal of all
// enrolled fingerprints, allowing the key to remain valid.
sid = getRootSid();
}
args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID, KeymasterArguments.toUint64(sid));
args.addEnum(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, KeymasterDefs.HW_AUTH_FINGERPRINT);
if (userAuthenticationValidWhileOnBody) {
throw new ProviderException("Key validity extension while device is on-body is not " + "supported for keys requiring fingerprint authentication");
}
} else {
// The key is authorized for use for the specified amount of time after the user has
// authenticated. Whatever unlocks the secure lock screen should authorize this key.
long rootSid = getRootSid();
args.addUnsignedLong(KeymasterDefs.KM_TAG_USER_SECURE_ID, KeymasterArguments.toUint64(rootSid));
args.addEnum(KeymasterDefs.KM_TAG_USER_AUTH_TYPE, KeymasterDefs.HW_AUTH_PASSWORD | KeymasterDefs.HW_AUTH_FINGERPRINT);
args.addUnsignedInt(KeymasterDefs.KM_TAG_AUTH_TIMEOUT, userAuthenticationValidityDurationSeconds);
if (userAuthenticationValidWhileOnBody) {
args.addBoolean(KeymasterDefs.KM_TAG_ALLOW_WHILE_ON_BODY);
}
}
}
Aggregations