Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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