Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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