diff --git a/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java b/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java index 16c5ad2e227a8..225517ac69b80 100644 --- a/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java +++ b/src/java.base/share/classes/sun/security/rsa/SunRsaSignEntries.java @@ -65,10 +65,13 @@ public SunRsaSignEntries(Provider p) { attrs.put("SupportedKeyClasses", "java.security.interfaces.RSAPublicKey" + "|java.security.interfaces.RSAPrivateKey"); + } - add(p, "KeyFactory", "RSA", - "sun.security.rsa.RSAKeyFactory$Legacy", - getAliases("PKCS1"), null); + add(p, "KeyFactory", "RSA", + "sun.security.rsa.RSAKeyFactory$Legacy", + getAliases("PKCS1"), null); + + if (!systemFipsEnabled) { add(p, "KeyPairGenerator", "RSA", "sun.security.rsa.RSAKeyPairGenerator$Legacy", getAliases("PKCS1"), null); @@ -98,9 +101,12 @@ public SunRsaSignEntries(Provider p) { "sun.security.rsa.RSASignature$SHA3_384withRSA", attrs); addA(p, "Signature", "SHA3-512withRSA", "sun.security.rsa.RSASignature$SHA3_512withRSA", attrs); + } + + addA(p, "KeyFactory", "RSASSA-PSS", + "sun.security.rsa.RSAKeyFactory$PSS", attrs); - addA(p, "KeyFactory", "RSASSA-PSS", - "sun.security.rsa.RSAKeyFactory$PSS", attrs); + if (!systemFipsEnabled) { addA(p, "KeyPairGenerator", "RSASSA-PSS", "sun.security.rsa.RSAKeyPairGenerator$PSS", attrs); addA(p, "Signature", "RSASSA-PSS", diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java index bee3a1e15376e..9bb31555f480d 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java @@ -29,11 +29,15 @@ import java.security.KeyFactory; import java.security.Provider; import java.security.Security; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPrivateKey; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import javax.crypto.Cipher; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.DHPrivateKeySpec; import javax.crypto.spec.IvParameterSpec; @@ -44,6 +48,8 @@ import static sun.security.pkcs11.wrapper.PKCS11Constants.*; import static sun.security.pkcs11.wrapper.PKCS11Exception.*; import sun.security.pkcs11.wrapper.PKCS11Exception; +import sun.security.rsa.RSAPrivateCrtKeyImpl; +import sun.security.rsa.RSAUtil; import sun.security.rsa.RSAUtil.KeyType; import sun.security.util.Debug; import sun.security.util.ECUtil; @@ -53,15 +59,21 @@ final class FIPSKeyImporter { private static final Debug debug = Debug.getInstance("sunpkcs11"); - private static P11Key importerKey = null; + private static volatile P11Key importerKey = null; + private static SecretKeySpec exporterKey = null; + private static volatile P11Key exporterKeyP11 = null; private static final ReentrantLock importerKeyLock = new ReentrantLock(); - private static CK_MECHANISM importerKeyMechanism = null; + // Do not take the exporterKeyLock with the importerKeyLock held. + private static final ReentrantLock exporterKeyLock = new ReentrantLock(); + private static volatile CK_MECHANISM importerKeyMechanism = null; + private static volatile CK_MECHANISM exporterKeyMechanism = null; private static Cipher importerCipher = null; + private static Cipher exporterCipher = null; - private static Provider sunECProvider = null; + private static volatile Provider sunECProvider = null; private static final ReentrantLock sunECProviderLock = new ReentrantLock(); - private static KeyFactory DHKF = null; + private static volatile KeyFactory DHKF = null; private static final ReentrantLock DHKFLock = new ReentrantLock(); static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attributes) @@ -85,7 +97,8 @@ static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attribu debug.println("Importer Key could not be" + " generated."); } - throw new PKCS11Exception(CKR_GENERAL_ERROR); + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " fips key importer"); } if (debug != null) { debug.println("Importer Key successfully" + @@ -213,7 +226,8 @@ static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attribu if (debug != null) { debug.println("Unrecognized private key type."); } - throw new PKCS11Exception(CKR_GENERAL_ERROR); + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " fips key importer"); } } else if (keyClass == CKO_SECRET_KEY) { if (debug != null) { @@ -226,14 +240,19 @@ static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attribu debug.println("Private or secret key plain bytes could" + " not be obtained. Import failed."); } - throw new PKCS11Exception(CKR_GENERAL_ERROR); + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " fips key importer"); } - importerCipher.init(Cipher.ENCRYPT_MODE, importerKey, - new IvParameterSpec((byte[])importerKeyMechanism.pParameter), - null); attributes = new CK_ATTRIBUTE[attrsMap.size()]; attrsMap.values().toArray(attributes); - encKeyBytes = importerCipher.doFinal(keyBytes); + importerKeyLock.lock(); + try { + // No need to reset the cipher object because no multi-part + // operations are performed. + encKeyBytes = importerCipher.doFinal(keyBytes); + } finally { + importerKeyLock.unlock(); + } attributes = token.getAttributes(TemplateManager.O_IMPORT, keyClass, keyType, attributes); keyID = token.p11.C_UnwrapKey(hSession, @@ -242,13 +261,155 @@ static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attribu debug.println("Imported key ID: " + keyID); } } catch (Throwable t) { - throw new PKCS11Exception(CKR_GENERAL_ERROR); + if (t instanceof PKCS11Exception) { + throw (PKCS11Exception)t; + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + t.getMessage()); } finally { importerKey.releaseKeyID(); } return Long.valueOf(keyID); } + static void exportKey(SunPKCS11 sunPKCS11, long hSession, long hObject, + long keyClass, long keyType, Map sensitiveAttrs) + throws PKCS11Exception { + Token token = sunPKCS11.getToken(); + if (debug != null) { + debug.println("Private or Secret key will be exported in" + + " system FIPS mode."); + } + if (exporterKeyP11 == null) { + try { + exporterKeyLock.lock(); + if (exporterKeyP11 == null) { + if (exporterKeyMechanism == null) { + // Exporter Key creation has not been tried yet. Try it. + createExporterKey(token); + } + if (exporterKeyP11 == null || exporterCipher == null) { + if (debug != null) { + debug.println("Exporter Key could not be" + + " generated."); + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " fips key exporter"); + } + if (debug != null) { + debug.println("Exporter Key successfully" + + " generated."); + } + } + } finally { + exporterKeyLock.unlock(); + } + } + long exporterKeyID = exporterKeyP11.getKeyID(); + try { + byte[] wrappedKeyBytes = token.p11.C_WrapKey(hSession, + exporterKeyMechanism, exporterKeyID, hObject); + byte[] plainExportedKey = null; + exporterKeyLock.lock(); + try { + // No need to reset the cipher object because no multi-part + // operations are performed. + plainExportedKey = exporterCipher.doFinal(wrappedKeyBytes); + } finally { + exporterKeyLock.unlock(); + } + if (keyClass == CKO_PRIVATE_KEY) { + exportPrivateKey(sensitiveAttrs, keyType, plainExportedKey); + } else if (keyClass == CKO_SECRET_KEY) { + checkAttrs(sensitiveAttrs, "CKO_SECRET_KEY", CKA_VALUE); + // CKA_VALUE is guaranteed to be present, since sensitiveAttrs' + // size is greater than 0 and no invalid attributes exist + sensitiveAttrs.get(CKA_VALUE).pValue = plainExportedKey; + } else { + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " fips key exporter"); + } + } catch (Throwable t) { + if (t instanceof PKCS11Exception) { + throw (PKCS11Exception)t; + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + t.getMessage()); + } finally { + exporterKeyP11.releaseKeyID(); + } + } + + private static void exportPrivateKey( + Map sensitiveAttrs, long keyType, + byte[] plainExportedKey) throws Throwable { + if (keyType == CKK_RSA) { + checkAttrs(sensitiveAttrs, "CKO_PRIVATE_KEY CKK_RSA", + CKA_PRIVATE_EXPONENT, CKA_PRIME_1, CKA_PRIME_2, + CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT); + RSAPrivateKey rsaPKey = RSAPrivateCrtKeyImpl.newKey( + RSAUtil.KeyType.RSA, "PKCS#8", plainExportedKey + ); + CK_ATTRIBUTE attr; + if ((attr = sensitiveAttrs.get(CKA_PRIVATE_EXPONENT)) != null) { + attr.pValue = rsaPKey.getPrivateExponent().toByteArray(); + } + if (rsaPKey instanceof RSAPrivateCrtKey) { + RSAPrivateCrtKey rsaPCrtKey = (RSAPrivateCrtKey) rsaPKey; + if ((attr = sensitiveAttrs.get(CKA_PRIME_1)) != null) { + attr.pValue = rsaPCrtKey.getPrimeP().toByteArray(); + } + if ((attr = sensitiveAttrs.get(CKA_PRIME_2)) != null) { + attr.pValue = rsaPCrtKey.getPrimeQ().toByteArray(); + } + if ((attr = sensitiveAttrs.get(CKA_EXPONENT_1)) != null) { + attr.pValue = rsaPCrtKey.getPrimeExponentP().toByteArray(); + } + if ((attr = sensitiveAttrs.get(CKA_EXPONENT_2)) != null) { + attr.pValue = rsaPCrtKey.getPrimeExponentQ().toByteArray(); + } + if ((attr = sensitiveAttrs.get(CKA_COEFFICIENT)) != null) { + attr.pValue = rsaPCrtKey.getCrtCoefficient().toByteArray(); + } + } else { + checkAttrs(sensitiveAttrs, "CKO_PRIVATE_KEY CKK_RSA", + CKA_PRIVATE_EXPONENT); + } + } else if (keyType == CKK_DSA) { + checkAttrs(sensitiveAttrs, "CKO_PRIVATE_KEY CKK_DSA", CKA_VALUE); + // CKA_VALUE is guaranteed to be present, since sensitiveAttrs' + // size is greater than 0 and no invalid attributes exist + sensitiveAttrs.get(CKA_VALUE).pValue = + new sun.security.provider.DSAPrivateKey(plainExportedKey) + .getX().toByteArray(); + } else if (keyType == CKK_EC) { + checkAttrs(sensitiveAttrs, "CKO_PRIVATE_KEY CKK_EC", CKA_VALUE); + // CKA_VALUE is guaranteed to be present, since sensitiveAttrs' + // size is greater than 0 and no invalid attributes exist + sensitiveAttrs.get(CKA_VALUE).pValue = + ECUtil.decodePKCS8ECPrivateKey(plainExportedKey) + .getS().toByteArray(); + } else { + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " unsupported CKO_PRIVATE_KEY key type: " + keyType); + } + } + + private static void checkAttrs(Map sensitiveAttrs, + String keyName, long... validAttrs) + throws PKCS11Exception { + int sensitiveAttrsCount = sensitiveAttrs.size(); + if (sensitiveAttrsCount <= validAttrs.length) { + int validAttrsCount = 0; + for (long validAttr : validAttrs) { + if (sensitiveAttrs.containsKey(validAttr)) validAttrsCount++; + } + if (validAttrsCount == sensitiveAttrsCount) return; + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + " invalid attribute types for a " + keyName + " key object"); + } + private static void createImporterKey(Token token) { if (debug != null) { debug.println("Generating Importer Key..."); @@ -279,6 +440,9 @@ private static void createImporterKey(Token token) { } if (importerKey != null) { importerCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + importerCipher.init(Cipher.ENCRYPT_MODE, importerKey, + new IvParameterSpec( + (byte[])importerKeyMechanism.pParameter), null); } } catch (Throwable t) { // best effort @@ -286,6 +450,41 @@ private static void createImporterKey(Token token) { importerCipher = null; // importerKeyMechanism value is kept initialized to indicate that // Importer Key creation has been tried and failed. + if (debug != null) { + debug.println("Error generating the Importer Key"); + } + } + } + + private static void createExporterKey(Token token) { + if (debug != null) { + debug.println("Generating Exporter Key..."); + } + byte[] iv = new byte[16]; + JCAUtil.getSecureRandom().nextBytes(iv); + exporterKeyMechanism = new CK_MECHANISM(CKM_AES_CBC_PAD, iv); + byte[] exporterKeyRaw = new byte[32]; + JCAUtil.getSecureRandom().nextBytes(exporterKeyRaw); + exporterKey = new SecretKeySpec(exporterKeyRaw, "AES"); + try { + SecretKeyFactory skf = SecretKeyFactory.getInstance("AES"); + exporterKeyP11 = (P11Key)(skf.translateKey(exporterKey)); + if (exporterKeyP11 != null) { + exporterCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + exporterCipher.init(Cipher.DECRYPT_MODE, exporterKey, + new IvParameterSpec( + (byte[])exporterKeyMechanism.pParameter), null); + } + } catch (Throwable t) { + // best effort + exporterKey = null; + exporterKeyP11 = null; + exporterCipher = null; + // exporterKeyMechanism value is kept initialized to indicate that + // Exporter Key creation has been tried and failed. + if (debug != null) { + debug.println("Error generating the Exporter Key"); + } } } } diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java index 9b69072280ef8..b403e6d3c6d1e 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java @@ -37,6 +37,8 @@ import javax.crypto.interfaces.*; import javax.crypto.spec.*; +import jdk.internal.access.SharedSecrets; + import sun.security.rsa.RSAUtil.KeyType; import sun.security.rsa.RSAPublicKeyImpl; import sun.security.rsa.RSAPrivateCrtKeyImpl; @@ -69,6 +71,9 @@ */ abstract class P11Key implements Key, Length { + private static final boolean plainKeySupportEnabled = SharedSecrets + .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled(); + private static final long serialVersionUID = -2575874101938349339L; private static final String PUBLIC = "public"; @@ -379,7 +384,8 @@ static PrivateKey privateKey(Session session, long keyID, String algorithm, new CK_ATTRIBUTE(CKA_SENSITIVE), new CK_ATTRIBUTE(CKA_EXTRACTABLE), }); - if (attributes[1].getBoolean() || (attributes[2].getBoolean() == false)) { + if (!plainKeySupportEnabled && (attributes[1].getBoolean() || + (attributes[2].getBoolean() == false))) { return new P11PrivateKey (session, keyID, algorithm, keyLength, attributes); } else { @@ -461,7 +467,8 @@ private static class P11SecretKey extends P11Key implements SecretKey { } public String getFormat() { token.ensureValid(); - if (sensitive || (extractable == false)) { + if (!plainKeySupportEnabled && + (sensitive || (extractable == false))) { return null; } else { return "RAW"; diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java index 42c72b393fdf7..5549cd9ed4e71 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java @@ -73,20 +73,28 @@ public final class SunPKCS11 extends AuthProvider { .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled(); private static final MethodHandle fipsImportKey; + private static final MethodHandle fipsExportKey; static { MethodHandle fipsImportKeyTmp = null; + MethodHandle fipsExportKeyTmp = null; if (plainKeySupportEnabled) { try { fipsImportKeyTmp = MethodHandles.lookup().findStatic( FIPSKeyImporter.class, "importKey", MethodType.methodType(Long.class, SunPKCS11.class, long.class, CK_ATTRIBUTE[].class)); + fipsExportKeyTmp = MethodHandles.lookup().findStatic( + FIPSKeyImporter.class, "exportKey", + MethodType.methodType(void.class, SunPKCS11.class, + long.class, long.class, + long.class, long.class, Map.class)); } catch (Throwable t) { - throw new SecurityException("FIPS key importer initialization" + - " failed", t); + throw new SecurityException("FIPS key importer-exporter" + + " initialization failed", t); } } fipsImportKey = fipsImportKeyTmp; + fipsExportKey = fipsExportKeyTmp; } private static final long serialVersionUID = -1354835039035306505L; @@ -348,14 +356,18 @@ private static T checkNull(T obj) { initArgs.flags = CKF_OS_LOCKING_OK; PKCS11 tmpPKCS11; MethodHandle fipsKeyImporter = null; + MethodHandle fipsKeyExporter = null; if (plainKeySupportEnabled) { fipsKeyImporter = MethodHandles.insertArguments( fipsImportKey, 0, this); + fipsKeyExporter = MethodHandles.insertArguments( + fipsExportKey, 0, this); } try { tmpPKCS11 = PKCS11.getInstance( library, functionList, initArgs, - config.getOmitInitialize(), fipsKeyImporter); + config.getOmitInitialize(), fipsKeyImporter, + fipsKeyExporter); } catch (PKCS11Exception e) { if (debug != null) { debug.println("Multi-threaded initialization failed: " + e); @@ -371,7 +383,8 @@ private static T checkNull(T obj) { initArgs.flags = 0; } tmpPKCS11 = PKCS11.getInstance(library, - functionList, initArgs, config.getOmitInitialize(), fipsKeyImporter); + functionList, initArgs, config.getOmitInitialize(), fipsKeyImporter, + fipsKeyExporter); } p11 = tmpPKCS11; diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java index 4d80145cb91e8..372a50dd58728 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java @@ -50,6 +50,8 @@ import java.io.File; import java.io.IOException; import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.MethodType; import java.util.*; import java.security.AccessController; @@ -153,25 +155,27 @@ public static void loadNative() { public static synchronized PKCS11 getInstance(String pkcs11ModulePath, String functionList, CK_C_INITIALIZE_ARGS pInitArgs, - boolean omitInitialize, MethodHandle fipsKeyImporter) + boolean omitInitialize, MethodHandle fipsKeyImporter, + MethodHandle fipsKeyExporter) throws IOException, PKCS11Exception { // we may only call C_Initialize once per native .so/.dll // so keep a cache using the (non-canonicalized!) path PKCS11 pkcs11 = moduleMap.get(pkcs11ModulePath); if (pkcs11 == null) { - boolean nssFipsMode = fipsKeyImporter != null; + boolean nssFipsMode = fipsKeyImporter != null && + fipsKeyExporter != null; if ((pInitArgs != null) && ((pInitArgs.flags & CKF_OS_LOCKING_OK) != 0)) { if (nssFipsMode) { pkcs11 = new FIPSPKCS11(pkcs11ModulePath, functionList, - fipsKeyImporter); + fipsKeyImporter, fipsKeyExporter); } else { pkcs11 = new PKCS11(pkcs11ModulePath, functionList); } } else { if (nssFipsMode) { pkcs11 = new SynchronizedFIPSPKCS11(pkcs11ModulePath, - functionList, fipsKeyImporter); + functionList, fipsKeyImporter, fipsKeyExporter); } else { pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList); } @@ -1930,13 +1934,29 @@ public synchronized void C_GenerateRandom(long hSession, byte[] randomData) // is enabled. static class FIPSPKCS11 extends PKCS11 { private MethodHandle fipsKeyImporter; + private MethodHandle fipsKeyExporter; + private MethodHandle hC_GetAttributeValue; FIPSPKCS11(String pkcs11ModulePath, String functionListName, - MethodHandle fipsKeyImporter) throws IOException { + MethodHandle fipsKeyImporter, MethodHandle fipsKeyExporter) + throws IOException { super(pkcs11ModulePath, functionListName); this.fipsKeyImporter = fipsKeyImporter; + this.fipsKeyExporter = fipsKeyExporter; + try { + hC_GetAttributeValue = MethodHandles.insertArguments( + MethodHandles.lookup().findSpecial(PKCS11.class, + "C_GetAttributeValue", MethodType.methodType( + void.class, long.class, long.class, + CK_ATTRIBUTE[].class), + FIPSPKCS11.class), 0, this); + } catch (Throwable t) { + throw new RuntimeException( + "sun.security.pkcs11.wrapper.PKCS11" + + "::C_GetAttributeValue method not found.", t); + } } - public synchronized long C_CreateObject(long hSession, + public long C_CreateObject(long hSession, CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception { // Creating sensitive key objects from plain key material in a // FIPS-configured NSS Software Token is not allowed. We apply @@ -1946,20 +1966,46 @@ public synchronized long C_CreateObject(long hSession, return ((Long)fipsKeyImporter.invoke(hSession, pTemplate)) .longValue(); } catch (Throwable t) { - throw new PKCS11Exception(CKR_GENERAL_ERROR); + if (t instanceof PKCS11Exception) { + throw (PKCS11Exception)t; + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + t.getMessage()); } } return super.C_CreateObject(hSession, pTemplate); } + + public void C_GetAttributeValue(long hSession, long hObject, + CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception { + FIPSPKCS11Helper.C_GetAttributeValue(hC_GetAttributeValue, + fipsKeyExporter, hSession, hObject, pTemplate); + } } // FIPSPKCS11 synchronized counterpart. static class SynchronizedFIPSPKCS11 extends SynchronizedPKCS11 { private MethodHandle fipsKeyImporter; + private MethodHandle fipsKeyExporter; + private MethodHandle hC_GetAttributeValue; SynchronizedFIPSPKCS11(String pkcs11ModulePath, String functionListName, - MethodHandle fipsKeyImporter) throws IOException { + MethodHandle fipsKeyImporter, MethodHandle fipsKeyExporter) + throws IOException { super(pkcs11ModulePath, functionListName); this.fipsKeyImporter = fipsKeyImporter; + this.fipsKeyExporter = fipsKeyExporter; + try { + hC_GetAttributeValue = MethodHandles.insertArguments( + MethodHandles.lookup().findSpecial(SynchronizedPKCS11.class, + "C_GetAttributeValue", MethodType.methodType( + void.class, long.class, long.class, + CK_ATTRIBUTE[].class), + SynchronizedFIPSPKCS11.class), 0, this); + } catch (Throwable t) { + throw new RuntimeException( + "sun.security.pkcs11.wrapper.SynchronizedPKCS11" + + "::C_GetAttributeValue method not found.", t); + } } public synchronized long C_CreateObject(long hSession, @@ -1970,11 +2016,21 @@ public synchronized long C_CreateObject(long hSession, return ((Long)fipsKeyImporter.invoke(hSession, pTemplate)) .longValue(); } catch (Throwable t) { - throw new PKCS11Exception(CKR_GENERAL_ERROR); + if (t instanceof PKCS11Exception) { + throw (PKCS11Exception)t; + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + t.getMessage()); } } return super.C_CreateObject(hSession, pTemplate); } + + public synchronized void C_GetAttributeValue(long hSession, long hObject, + CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception { + FIPSPKCS11Helper.C_GetAttributeValue(hC_GetAttributeValue, + fipsKeyExporter, hSession, hObject, pTemplate); + } } private static class FIPSPKCS11Helper { @@ -1988,5 +2044,78 @@ static boolean isSensitiveObject(CK_ATTRIBUTE[] pTemplate) { } return false; } + static void C_GetAttributeValue(MethodHandle hC_GetAttributeValue, + MethodHandle fipsKeyExporter, long hSession, long hObject, + CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception { + Map sensitiveAttrs = new HashMap<>(); + List nonSensitiveAttrs = new LinkedList<>(); + FIPSPKCS11Helper.getAttributesBySensitivity(pTemplate, + sensitiveAttrs, nonSensitiveAttrs); + try { + if (sensitiveAttrs.size() > 0) { + long keyClass = -1L; + long keyType = -1L; + try { + // Secret and private keys have both class and type + // attributes, so we can query them at once. + CK_ATTRIBUTE[] queryAttrs = new CK_ATTRIBUTE[]{ + new CK_ATTRIBUTE(CKA_CLASS), + new CK_ATTRIBUTE(CKA_KEY_TYPE), + }; + hC_GetAttributeValue.invoke(hSession, hObject, queryAttrs); + keyClass = queryAttrs[0].getLong(); + keyType = queryAttrs[1].getLong(); + } catch (PKCS11Exception e) { + // If the query fails, the object is neither a secret nor a + // private key. As this case won't be handled with the FIPS + // Key Exporter, we keep keyClass initialized to -1L. + } + if (keyClass == CKO_SECRET_KEY || keyClass == CKO_PRIVATE_KEY) { + fipsKeyExporter.invoke(hSession, hObject, keyClass, keyType, + sensitiveAttrs); + if (nonSensitiveAttrs.size() > 0) { + CK_ATTRIBUTE[] pNonSensitiveAttrs = + new CK_ATTRIBUTE[nonSensitiveAttrs.size()]; + int i = 0; + for (CK_ATTRIBUTE nonSensAttr : nonSensitiveAttrs) { + pNonSensitiveAttrs[i++] = nonSensAttr; + } + hC_GetAttributeValue.invoke(hSession, hObject, + pNonSensitiveAttrs); + // libj2pkcs11 allocates new CK_ATTRIBUTE objects, so we + // update the reference on the previous CK_ATTRIBUTEs + i = 0; + for (CK_ATTRIBUTE nonSensAttr : nonSensitiveAttrs) { + nonSensAttr.pValue = pNonSensitiveAttrs[i++].pValue; + } + } + return; + } + } + hC_GetAttributeValue.invoke(hSession, hObject, pTemplate); + } catch (Throwable t) { + if (t instanceof PKCS11Exception) { + throw (PKCS11Exception)t; + } + throw new PKCS11Exception(CKR_GENERAL_ERROR, + t.getMessage()); + } + } + private static void getAttributesBySensitivity(CK_ATTRIBUTE[] pTemplate, + Map sensitiveAttrs, + List nonSensitiveAttrs) { + for (CK_ATTRIBUTE attr : pTemplate) { + long type = attr.type; + // Aligned with NSS' sftk_isSensitive in lib/softoken/pkcs11u.c + if (type == CKA_VALUE || type == CKA_PRIVATE_EXPONENT || + type == CKA_PRIME_1 || type == CKA_PRIME_2 || + type == CKA_EXPONENT_1 || type == CKA_EXPONENT_2 || + type == CKA_COEFFICIENT) { + sensitiveAttrs.put(type, attr); + } else { + nonSensitiveAttrs.add(attr); + } + } + } } } diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java index dc5e7eefdd3ef..e2d6d371becc6 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11Exception.java @@ -219,14 +219,6 @@ private static String lookup(long errorCode) { return "0x" + Functions.toFullHexString((int)errorCode); } - /** - * Constructor taking the error code (the CKR_* constants in PKCS#11) with - * no extra info for the error message. - */ - public PKCS11Exception(long errorCode) { - this(errorCode, null); - } - /** * Constructor taking the error code (the CKR_* constants in PKCS#11) and * extra info for error message.