Blame SOURCES/rh1991003-enable_fips_keys_import.patch

97e098
diff --git openjdk.orig/src/java.base/share/classes/java/security/Security.java openjdk/src/java.base/share/classes/java/security/Security.java
97e098
index 53f32d12cc..28ab184617 100644
97e098
--- openjdk.orig/src/java.base/share/classes/java/security/Security.java
97e098
+++ openjdk/src/java.base/share/classes/java/security/Security.java
97e098
@@ -82,6 +82,10 @@ public final class Security {
97e098
                 public boolean isSystemFipsEnabled() {
97e098
                     return SystemConfigurator.isSystemFipsEnabled();
97e098
                 }
97e098
+                @Override
97e098
+                public boolean isPlainKeySupportEnabled() {
97e098
+                    return SystemConfigurator.isPlainKeySupportEnabled();
97e098
+                }
97e098
             });
97e098
 
97e098
         // doPrivileged here because there are multiple
97e098
diff --git openjdk.orig/src/java.base/share/classes/java/security/SystemConfigurator.java openjdk/src/java.base/share/classes/java/security/SystemConfigurator.java
97e098
index 5565acb7c6..874c6221eb 100644
97e098
--- openjdk.orig/src/java.base/share/classes/java/security/SystemConfigurator.java
97e098
+++ openjdk/src/java.base/share/classes/java/security/SystemConfigurator.java
97e098
@@ -55,6 +55,7 @@ final class SystemConfigurator {
97e098
             CRYPTO_POLICIES_BASE_DIR + "/back-ends/java.config";
97e098
 
97e098
     private static boolean systemFipsEnabled = false;
97e098
+    private static boolean plainKeySupportEnabled = false;
97e098
 
97e098
     private static final String SYSTEMCONF_NATIVE_LIB = "systemconf";
97e098
 
97e098
@@ -149,6 +150,16 @@ final class SystemConfigurator {
97e098
                 }
97e098
                 loadedProps = true;
97e098
                 systemFipsEnabled = true;
97e098
+                String plainKeySupport = System.getProperty("com.redhat.fips.plainKeySupport",
97e098
+                                                            "true");
97e098
+                plainKeySupportEnabled = !"false".equals(plainKeySupport);
97e098
+                if (sdebug != null) {
97e098
+                    if (plainKeySupportEnabled) {
97e098
+                        sdebug.println("FIPS support enabled with plain key support");
97e098
+                    } else {
97e098
+                        sdebug.println("FIPS support enabled without plain key support");
97e098
+                    }
97e098
+                }
97e098
             }
97e098
         } catch (Exception e) {
97e098
             if (sdebug != null) {
97e098
@@ -176,6 +187,19 @@ final class SystemConfigurator {
97e098
         return systemFipsEnabled;
97e098
     }
97e098
 
97e098
+    /**
97e098
+     * Returns {@code true} if system FIPS alignment is enabled
97e098
+     * and plain key support is allowed.  Plain key support is
97e098
+     * enabled by default but can be disabled with
97e098
+     * {@code -Dcom.redhat.fips.plainKeySupport=false}.
97e098
+     *
97e098
+     * @return a boolean indicating whether plain key support
97e098
+     *         should be enabled.
97e098
+     */
97e098
+    static boolean isPlainKeySupportEnabled() {
97e098
+        return plainKeySupportEnabled;
97e098
+    }
97e098
+
97e098
     /*
97e098
      * OpenJDK FIPS mode will be enabled only if the com.redhat.fips
97e098
      * system property is true (default) and the system is in FIPS mode.
97e098
diff --git openjdk.orig/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java openjdk/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java
97e098
index d8caa5640c..21bc6d0b59 100644
97e098
--- openjdk.orig/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java
97e098
+++ openjdk/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java
97e098
@@ -27,4 +27,5 @@ package jdk.internal.misc;
97e098
 
97e098
 public interface JavaSecuritySystemConfiguratorAccess {
97e098
     boolean isSystemFipsEnabled();
97e098
+    boolean isPlainKeySupportEnabled();
97e098
 }
97e098
diff --git openjdk.orig/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java openjdk/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
97e098
index ffee2c1603..ff3d5e0e4a 100644
97e098
--- openjdk.orig/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
97e098
+++ openjdk/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
97e098
@@ -33,8 +33,13 @@ import java.security.KeyStore.*;
97e098
 
97e098
 import javax.net.ssl.*;
97e098
 
97e098
+import jdk.internal.misc.SharedSecrets;
97e098
+
97e098
 abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
97e098
 
97e098
+    private static final boolean plainKeySupportEnabled = SharedSecrets
97e098
+            .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled();
97e098
+
97e098
     X509ExtendedKeyManager keyManager;
97e098
     boolean isInitialized;
97e098
 
97e098
@@ -62,7 +67,8 @@ abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
97e098
                 KeyStoreException, NoSuchAlgorithmException,
97e098
                 UnrecoverableKeyException {
97e098
             if ((ks != null) && SunJSSE.isFIPS()) {
97e098
-                if (ks.getProvider() != SunJSSE.cryptoProvider) {
97e098
+                if (ks.getProvider() != SunJSSE.cryptoProvider &&
97e098
+                        !plainKeySupportEnabled) {
97e098
                     throw new KeyStoreException("FIPS mode: KeyStore must be "
97e098
                         + "from provider " + SunJSSE.cryptoProvider.getName());
97e098
                 }
97e098
@@ -91,8 +97,8 @@ abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
97e098
                 keyManager = new X509KeyManagerImpl(
97e098
                         Collections.<Builder>emptyList());
97e098
             } else {
97e098
-                if (SunJSSE.isFIPS() &&
97e098
-                        (ks.getProvider() != SunJSSE.cryptoProvider)) {
97e098
+                if (SunJSSE.isFIPS() && (ks.getProvider() != SunJSSE.cryptoProvider)
97e098
+                        && !plainKeySupportEnabled) {
97e098
                     throw new KeyStoreException(
97e098
                         "FIPS mode: KeyStore must be " +
97e098
                         "from provider " + SunJSSE.cryptoProvider.getName());
97e098
diff --git openjdk.orig/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java openjdk/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java
97e098
new file mode 100644
97e098
index 0000000000..b848a1fd78
97e098
--- /dev/null
97e098
+++ openjdk/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java
97e098
@@ -0,0 +1,290 @@
97e098
+/*
97e098
+ * Copyright (c) 2021, Red Hat, Inc.
97e098
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
97e098
+ *
97e098
+ * This code is free software; you can redistribute it and/or modify it
97e098
+ * under the terms of the GNU General Public License version 2 only, as
97e098
+ * published by the Free Software Foundation.  Oracle designates this
97e098
+ * particular file as subject to the "Classpath" exception as provided
97e098
+ * by Oracle in the LICENSE file that accompanied this code.
97e098
+ *
97e098
+ * This code is distributed in the hope that it will be useful, but WITHOUT
97e098
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
97e098
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
97e098
+ * version 2 for more details (a copy is included in the LICENSE file that
97e098
+ * accompanied this code).
97e098
+ *
97e098
+ * You should have received a copy of the GNU General Public License version
97e098
+ * 2 along with this work; if not, write to the Free Software Foundation,
97e098
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
97e098
+ *
97e098
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
97e098
+ * or visit www.oracle.com if you need additional information or have any
97e098
+ * questions.
97e098
+ */
97e098
+
97e098
+package sun.security.pkcs11;
97e098
+
97e098
+import java.math.BigInteger;
97e098
+import java.security.KeyFactory;
97e098
+import java.security.Provider;
97e098
+import java.security.Security;
97e098
+import java.util.HashMap;
97e098
+import java.util.Map;
97e098
+import java.util.concurrent.locks.ReentrantLock;
97e098
+
97e098
+import javax.crypto.Cipher;
97e098
+import javax.crypto.spec.DHPrivateKeySpec;
97e098
+import javax.crypto.spec.IvParameterSpec;
97e098
+
97e098
+import sun.security.jca.JCAUtil;
97e098
+import sun.security.pkcs11.TemplateManager;
97e098
+import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;
97e098
+import sun.security.pkcs11.wrapper.CK_MECHANISM;
97e098
+import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
97e098
+import sun.security.pkcs11.wrapper.PKCS11Exception;
97e098
+import sun.security.rsa.RSAUtil.KeyType;
97e098
+import sun.security.util.Debug;
97e098
+import sun.security.util.ECUtil;
97e098
+
97e098
+final class FIPSKeyImporter {
97e098
+
97e098
+    private static final Debug debug =
97e098
+            Debug.getInstance("sunpkcs11");
97e098
+
97e098
+    private static P11Key importerKey = null;
97e098
+    private static final ReentrantLock importerKeyLock = new ReentrantLock();
97e098
+    private static CK_MECHANISM importerKeyMechanism = null;
97e098
+    private static Cipher importerCipher = null;
97e098
+
97e098
+    private static Provider sunECProvider = null;
97e098
+    private static final ReentrantLock sunECProviderLock = new ReentrantLock();
97e098
+
97e098
+    private static KeyFactory DHKF = null;
97e098
+    private static final ReentrantLock DHKFLock = new ReentrantLock();
97e098
+
97e098
+    static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attributes)
97e098
+            throws PKCS11Exception {
97e098
+        long keyID = -1;
97e098
+        Token token = sunPKCS11.getToken();
97e098
+        if (debug != null) {
97e098
+            debug.println("Private or Secret key will be imported in" +
97e098
+                    " system FIPS mode.");
97e098
+        }
97e098
+        if (importerKey == null) {
97e098
+            importerKeyLock.lock();
97e098
+            try {
97e098
+                if (importerKey == null) {
97e098
+                    if (importerKeyMechanism == null) {
97e098
+                        // Importer Key creation has not been tried yet. Try it.
97e098
+                        createImporterKey(token);
97e098
+                    }
97e098
+                    if (importerKey == null || importerCipher == null) {
97e098
+                        if (debug != null) {
97e098
+                            debug.println("Importer Key could not be" +
97e098
+                                    " generated.");
97e098
+                        }
97e098
+                        throw new PKCS11Exception(CKR_GENERAL_ERROR);
97e098
+                    }
97e098
+                    if (debug != null) {
97e098
+                        debug.println("Importer Key successfully" +
97e098
+                                " generated.");
97e098
+                    }
97e098
+                }
97e098
+            } finally {
97e098
+                importerKeyLock.unlock();
97e098
+            }
97e098
+        }
97e098
+        long importerKeyID = importerKey.getKeyID();
97e098
+        try {
97e098
+            byte[] keyBytes = null;
97e098
+            byte[] encKeyBytes = null;
97e098
+            long keyClass = 0L;
97e098
+            long keyType = 0L;
97e098
+            Map<Long, CK_ATTRIBUTE> attrsMap = new HashMap<>();
97e098
+            for (CK_ATTRIBUTE attr : attributes) {
97e098
+                if (attr.type == CKA_CLASS) {
97e098
+                    keyClass = attr.getLong();
97e098
+                } else if (attr.type == CKA_KEY_TYPE) {
97e098
+                    keyType = attr.getLong();
97e098
+                }
97e098
+                attrsMap.put(attr.type, attr);
97e098
+            }
97e098
+            BigInteger v = null;
97e098
+            if (keyClass == CKO_PRIVATE_KEY) {
97e098
+                if (keyType == CKK_RSA) {
97e098
+                    if (debug != null) {
97e098
+                        debug.println("Importing an RSA private key...");
97e098
+                    }
97e098
+                    keyBytes = sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(
97e098
+                            KeyType.RSA,
97e098
+                            null,
97e098
+                            ((v = attrsMap.get(CKA_MODULUS).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_PUBLIC_EXPONENT).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_PRIVATE_EXPONENT).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_PRIME_1).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_PRIME_2).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_EXPONENT_1).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_EXPONENT_2).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_COEFFICIENT).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO
97e098
+                            ).getEncoded();
97e098
+                } else if (keyType == CKK_DSA) {
97e098
+                    if (debug != null) {
97e098
+                        debug.println("Importing a DSA private key...");
97e098
+                    }
97e098
+                    keyBytes = new sun.security.provider.DSAPrivateKey(
97e098
+                            ((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_PRIME).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_SUBPRIME).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_BASE).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO
97e098
+                            ).getEncoded();
97e098
+                    if (token.config.getNssNetscapeDbWorkaround() &&
97e098
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
97e098
+                        attrsMap.put(CKA_NETSCAPE_DB,
97e098
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
97e098
+                    }
97e098
+                } else if (keyType == CKK_EC) {
97e098
+                    if (debug != null) {
97e098
+                        debug.println("Importing an EC private key...");
97e098
+                    }
97e098
+                    if (sunECProvider == null) {
97e098
+                        sunECProviderLock.lock();
97e098
+                        try {
97e098
+                            if (sunECProvider == null) {
97e098
+                                sunECProvider = Security.getProvider("SunEC");
97e098
+                            }
97e098
+                        } finally {
97e098
+                            sunECProviderLock.unlock();
97e098
+                        }
97e098
+                    }
97e098
+                    keyBytes = ECUtil.generateECPrivateKey(
97e098
+                            ((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ECUtil.getECParameterSpec(sunECProvider,
97e098
+                                    attrsMap.get(CKA_EC_PARAMS).getByteArray()))
97e098
+                            .getEncoded();
97e098
+                    if (token.config.getNssNetscapeDbWorkaround() &&
97e098
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
97e098
+                        attrsMap.put(CKA_NETSCAPE_DB,
97e098
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
97e098
+                    }
97e098
+                } else if (keyType == CKK_DH) {
97e098
+                    if (debug != null) {
97e098
+                        debug.println("Importing a Diffie-Hellman private key...");
97e098
+                    }
97e098
+                    if (DHKF == null) {
97e098
+                        DHKFLock.lock();
97e098
+                        try {
97e098
+                            if (DHKF == null) {
97e098
+                                DHKF = KeyFactory.getInstance(
97e098
+                                        "DH", P11Util.getSunJceProvider());
97e098
+                            }
97e098
+                        } finally {
97e098
+                            DHKFLock.unlock();
97e098
+                        }
97e098
+                    }
97e098
+                    DHPrivateKeySpec spec = new DHPrivateKeySpec
97e098
+                            (((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_PRIME).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO,
97e098
+                            ((v = attrsMap.get(CKA_BASE).getBigInteger()) != null)
97e098
+                                    ? v : BigInteger.ZERO);
97e098
+                    keyBytes = DHKF.generatePrivate(spec).getEncoded();
97e098
+                    if (token.config.getNssNetscapeDbWorkaround() &&
97e098
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
97e098
+                        attrsMap.put(CKA_NETSCAPE_DB,
97e098
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
97e098
+                    }
97e098
+                } else {
97e098
+                    if (debug != null) {
97e098
+                        debug.println("Unrecognized private key type.");
97e098
+                    }
97e098
+                    throw new PKCS11Exception(CKR_GENERAL_ERROR);
97e098
+                }
97e098
+            } else if (keyClass == CKO_SECRET_KEY) {
97e098
+                if (debug != null) {
97e098
+                    debug.println("Importing a secret key...");
97e098
+                }
97e098
+                keyBytes = attrsMap.get(CKA_VALUE).getByteArray();
97e098
+            }
97e098
+            if (keyBytes == null || keyBytes.length == 0) {
97e098
+                if (debug != null) {
97e098
+                    debug.println("Private or secret key plain bytes could" +
97e098
+                            " not be obtained. Import failed.");
97e098
+                }
97e098
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
97e098
+            }
97e098
+            importerCipher.init(Cipher.ENCRYPT_MODE, importerKey,
97e098
+                    new IvParameterSpec((byte[])importerKeyMechanism.pParameter),
97e098
+                    null);
97e098
+            attributes = new CK_ATTRIBUTE[attrsMap.size()];
97e098
+            attrsMap.values().toArray(attributes);
97e098
+            encKeyBytes = importerCipher.doFinal(keyBytes);
97e098
+            attributes = token.getAttributes(TemplateManager.O_IMPORT,
97e098
+                    keyClass, keyType, attributes);
97e098
+            keyID = token.p11.C_UnwrapKey(hSession,
97e098
+                    importerKeyMechanism, importerKeyID, encKeyBytes, attributes);
97e098
+            if (debug != null) {
97e098
+                debug.println("Imported key ID: " + keyID);
97e098
+            }
97e098
+        } catch (Throwable t) {
97e098
+            throw new PKCS11Exception(CKR_GENERAL_ERROR);
97e098
+        } finally {
97e098
+            importerKey.releaseKeyID();
97e098
+        }
97e098
+        return Long.valueOf(keyID);
97e098
+    }
97e098
+
97e098
+    private static void createImporterKey(Token token) {
97e098
+        if (debug != null) {
97e098
+            debug.println("Generating Importer Key...");
97e098
+        }
97e098
+        byte[] iv = new byte[16];
97e098
+        JCAUtil.getSecureRandom().nextBytes(iv);
97e098
+        importerKeyMechanism = new CK_MECHANISM(CKM_AES_CBC_PAD, iv);
97e098
+        try {
97e098
+            CK_ATTRIBUTE[] attributes = token.getAttributes(TemplateManager.O_GENERATE,
97e098
+                            CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] {
97e098
+                                    new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
97e098
+                                    new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3)});
97e098
+            Session s = null;
97e098
+            try {
97e098
+                s = token.getObjSession();
97e098
+                long keyID = token.p11.C_GenerateKey(
97e098
+                        s.id(), new CK_MECHANISM(CKM_AES_KEY_GEN),
97e098
+                        attributes);
97e098
+                if (debug != null) {
97e098
+                    debug.println("Importer Key ID: " + keyID);
97e098
+                }
97e098
+                importerKey = (P11Key)P11Key.secretKey(s, keyID, "AES",
97e098
+                        256 >> 3, null);
97e098
+            } catch (PKCS11Exception e) {
97e098
+                // best effort
97e098
+            } finally {
97e098
+                token.releaseSession(s);
97e098
+            }
97e098
+            if (importerKey != null) {
97e098
+                importerCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
97e098
+            }
97e098
+        } catch (Throwable t) {
97e098
+            // best effort
97e098
+            importerKey = null;
97e098
+            importerCipher = null;
97e098
+            // importerKeyMechanism value is kept initialized to indicate that
97e098
+            // Importer Key creation has been tried and failed.
97e098
+        }
97e098
+    }
97e098
+}
97e098
diff --git openjdk.orig/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java openjdk/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java
97e098
index 1eca1f8f0a..72674a7330 100644
97e098
--- openjdk.orig/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java
97e098
+++ openjdk/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java
97e098
@@ -26,6 +26,9 @@
97e098
 package sun.security.pkcs11;
97e098
 
97e098
 import java.io.*;
97e098
+import java.lang.invoke.MethodHandle;
97e098
+import java.lang.invoke.MethodHandles;
97e098
+import java.lang.invoke.MethodType;
97e098
 import java.util.*;
97e098
 
97e098
 import java.security.*;
97e098
@@ -64,6 +67,26 @@ public final class SunPKCS11 extends AuthProvider {
97e098
     private static final boolean systemFipsEnabled = SharedSecrets
97e098
             .getJavaSecuritySystemConfiguratorAccess().isSystemFipsEnabled();
97e098
 
97e098
+    private static final boolean plainKeySupportEnabled = SharedSecrets
97e098
+            .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled();
97e098
+
97e098
+    private static final MethodHandle fipsImportKey;
97e098
+    static {
97e098
+        MethodHandle fipsImportKeyTmp = null;
97e098
+        if (plainKeySupportEnabled) {
97e098
+            try {
97e098
+                fipsImportKeyTmp = MethodHandles.lookup().findStatic(
97e098
+                        FIPSKeyImporter.class, "importKey",
97e098
+                        MethodType.methodType(Long.class, SunPKCS11.class,
97e098
+                        long.class, CK_ATTRIBUTE[].class));
97e098
+            } catch (Throwable t) {
97e098
+                throw new SecurityException("FIPS key importer initialization" +
97e098
+                        " failed", t);
97e098
+            }
97e098
+        }
97e098
+        fipsImportKey = fipsImportKeyTmp;
97e098
+    }
97e098
+
97e098
     private static final long serialVersionUID = -1354835039035306505L;
97e098
 
97e098
     static final Debug debug = Debug.getInstance("sunpkcs11");
97e098
@@ -319,10 +342,15 @@ public final class SunPKCS11 extends AuthProvider {
97e098
             // request multithreaded access first
97e098
             initArgs.flags = CKF_OS_LOCKING_OK;
97e098
             PKCS11 tmpPKCS11;
97e098
+            MethodHandle fipsKeyImporter = null;
97e098
+            if (plainKeySupportEnabled) {
97e098
+                fipsKeyImporter = MethodHandles.insertArguments(
97e098
+                        fipsImportKey, 0, this);
97e098
+            }
97e098
             try {
97e098
                 tmpPKCS11 = PKCS11.getInstance(
97e098
                     library, functionList, initArgs,
97e098
-                    config.getOmitInitialize());
97e098
+                    config.getOmitInitialize(), fipsKeyImporter);
97e098
             } catch (PKCS11Exception e) {
97e098
                 if (debug != null) {
97e098
                     debug.println("Multi-threaded initialization failed: " + e);
97e098
@@ -338,7 +366,7 @@ public final class SunPKCS11 extends AuthProvider {
97e098
                     initArgs.flags = 0;
97e098
                 }
97e098
                 tmpPKCS11 = PKCS11.getInstance(library,
97e098
-                    functionList, initArgs, config.getOmitInitialize());
97e098
+                    functionList, initArgs, config.getOmitInitialize(), fipsKeyImporter);
97e098
             }
97e098
             p11 = tmpPKCS11;
97e098
 
97e098
diff --git openjdk.orig/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java openjdk/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
97e098
index 04a369f453..8d2081abaa 100644
97e098
--- openjdk.orig/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
97e098
+++ openjdk/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
97e098
@@ -49,6 +49,7 @@ package sun.security.pkcs11.wrapper;
97e098
 
97e098
 import java.io.File;
97e098
 import java.io.IOException;
97e098
+import java.lang.invoke.MethodHandle;
97e098
 import java.util.*;
97e098
 
97e098
 import java.security.AccessController;
97e098
@@ -150,16 +151,28 @@ public class PKCS11 {
97e098
 
97e098
     public static synchronized PKCS11 getInstance(String pkcs11ModulePath,
97e098
             String functionList, CK_C_INITIALIZE_ARGS pInitArgs,
97e098
-            boolean omitInitialize) throws IOException, PKCS11Exception {
97e098
+            boolean omitInitialize, MethodHandle fipsKeyImporter)
97e098
+                    throws IOException, PKCS11Exception {
97e098
         // we may only call C_Initialize once per native .so/.dll
97e098
         // so keep a cache using the (non-canonicalized!) path
97e098
         PKCS11 pkcs11 = moduleMap.get(pkcs11ModulePath);
97e098
         if (pkcs11 == null) {
97e098
+            boolean nssFipsMode = fipsKeyImporter != null;
97e098
             if ((pInitArgs != null)
97e098
                     && ((pInitArgs.flags & CKF_OS_LOCKING_OK) != 0)) {
97e098
-                pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
97e098
+                if (nssFipsMode) {
97e098
+                    pkcs11 = new FIPSPKCS11(pkcs11ModulePath, functionList,
97e098
+                            fipsKeyImporter);
97e098
+                } else {
97e098
+                    pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
97e098
+                }
97e098
             } else {
97e098
-                pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
97e098
+                if (nssFipsMode) {
97e098
+                    pkcs11 = new SynchronizedFIPSPKCS11(pkcs11ModulePath,
97e098
+                            functionList, fipsKeyImporter);
97e098
+                } else {
97e098
+                    pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
97e098
+                }
97e098
             }
97e098
             if (omitInitialize == false) {
97e098
                 try {
97e098
@@ -1909,4 +1922,69 @@ static class SynchronizedPKCS11 extends PKCS11 {
97e098
         super.C_GenerateRandom(hSession, randomData);
97e098
     }
97e098
 }
97e098
+
97e098
+// PKCS11 subclass that allows using plain private or secret keys in
97e098
+// FIPS-configured NSS Software Tokens. Only used when System FIPS
97e098
+// is enabled.
97e098
+static class FIPSPKCS11 extends PKCS11 {
97e098
+    private MethodHandle fipsKeyImporter;
97e098
+    FIPSPKCS11(String pkcs11ModulePath, String functionListName,
97e098
+            MethodHandle fipsKeyImporter) throws IOException {
97e098
+        super(pkcs11ModulePath, functionListName);
97e098
+        this.fipsKeyImporter = fipsKeyImporter;
97e098
+    }
97e098
+
97e098
+    public synchronized long C_CreateObject(long hSession,
97e098
+            CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
97e098
+        // Creating sensitive key objects from plain key material in a
97e098
+        // FIPS-configured NSS Software Token is not allowed. We apply
97e098
+        // a key-unwrapping scheme to achieve so.
97e098
+        if (FIPSPKCS11Helper.isSensitiveObject(pTemplate)) {
97e098
+            try {
97e098
+                return ((Long)fipsKeyImporter.invoke(hSession, pTemplate))
97e098
+                        .longValue();
97e098
+            } catch (Throwable t) {
97e098
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
97e098
+            }
97e098
+        }
97e098
+        return super.C_CreateObject(hSession, pTemplate);
97e098
+    }
97e098
+}
97e098
+
97e098
+// FIPSPKCS11 synchronized counterpart.
97e098
+static class SynchronizedFIPSPKCS11 extends SynchronizedPKCS11 {
97e098
+    private MethodHandle fipsKeyImporter;
97e098
+    SynchronizedFIPSPKCS11(String pkcs11ModulePath, String functionListName,
97e098
+            MethodHandle fipsKeyImporter) throws IOException {
97e098
+        super(pkcs11ModulePath, functionListName);
97e098
+        this.fipsKeyImporter = fipsKeyImporter;
97e098
+    }
97e098
+
97e098
+    public synchronized long C_CreateObject(long hSession,
97e098
+            CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
97e098
+        // See FIPSPKCS11::C_CreateObject.
97e098
+        if (FIPSPKCS11Helper.isSensitiveObject(pTemplate)) {
97e098
+            try {
97e098
+                return ((Long)fipsKeyImporter.invoke(hSession, pTemplate))
97e098
+                        .longValue();
97e098
+            } catch (Throwable t) {
97e098
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
97e098
+            }
97e098
+        }
97e098
+        return super.C_CreateObject(hSession, pTemplate);
97e098
+    }
97e098
+}
97e098
+
97e098
+private static class FIPSPKCS11Helper {
97e098
+    static boolean isSensitiveObject(CK_ATTRIBUTE[] pTemplate) {
97e098
+        for (CK_ATTRIBUTE attr : pTemplate) {
97e098
+            if (attr.type == CKA_CLASS &&
97e098
+                    (attr.getLong() == CKO_PRIVATE_KEY ||
97e098
+                    attr.getLong() == CKO_SECRET_KEY)) {
97e098
+                return true;
97e098
+            }
97e098
+        }
97e098
+        return false;
97e098
+    }
97e098
+}
97e098
 }