Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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