Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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