Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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