Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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