Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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