Blame SOURCES/rh1991003-enable_fips_keys_import.patch

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