Blame SOURCES/fips-11u-9087e80d0ab.patch

89362c
diff --git a/make/autoconf/libraries.m4 b/make/autoconf/libraries.m4
89362c
index a73c0f38181..80710886ed8 100644
89362c
--- a/make/autoconf/libraries.m4
89362c
+++ b/make/autoconf/libraries.m4
89362c
@@ -101,6 +101,7 @@ AC_DEFUN_ONCE([LIB_SETUP_LIBRARIES],
89362c
   LIB_SETUP_LIBFFI
89362c
   LIB_SETUP_BUNDLED_LIBS
89362c
   LIB_SETUP_MISC_LIBS
89362c
+  LIB_SETUP_SYSCONF_LIBS
89362c
   LIB_SETUP_SOLARIS_STLPORT
89362c
   LIB_TESTS_SETUP_GRAALUNIT
89362c
 
89362c
@@ -223,3 +224,62 @@ AC_DEFUN_ONCE([LIB_SETUP_SOLARIS_STLPORT],
89362c
   fi
89362c
 ])
89362c
 
89362c
+################################################################################
89362c
+# Setup system configuration libraries
89362c
+################################################################################
89362c
+AC_DEFUN_ONCE([LIB_SETUP_SYSCONF_LIBS],
89362c
+[
89362c
+  ###############################################################################
89362c
+  #
89362c
+  # Check for the NSS library
89362c
+  #
89362c
+
89362c
+  AC_MSG_CHECKING([whether to use the system NSS library with the System Configurator (libsysconf)])
89362c
+
89362c
+  # default is not available
89362c
+  DEFAULT_SYSCONF_NSS=no
89362c
+
89362c
+  AC_ARG_ENABLE([sysconf-nss], [AS_HELP_STRING([--enable-sysconf-nss],
89362c
+     [build the System Configurator (libsysconf) using the system NSS library if available @<:@disabled@:>@])],
89362c
+  [
89362c
+    case "${enableval}" in
89362c
+      yes)
89362c
+        sysconf_nss=yes
89362c
+        ;;
89362c
+      *)
89362c
+        sysconf_nss=no
89362c
+        ;;
89362c
+    esac
89362c
+  ],
89362c
+  [
89362c
+    sysconf_nss=${DEFAULT_SYSCONF_NSS}
89362c
+  ])
89362c
+  AC_MSG_RESULT([$sysconf_nss])
89362c
+
89362c
+  USE_SYSCONF_NSS=false
89362c
+  if test "x${sysconf_nss}" = "xyes"; then
89362c
+      PKG_CHECK_MODULES(NSS, nss >= 3.53, [NSS_FOUND=yes], [NSS_FOUND=no])
89362c
+      if test "x${NSS_FOUND}" = "xyes"; then
89362c
+         AC_MSG_CHECKING([for system FIPS support in NSS])
89362c
+         saved_libs="${LIBS}"
89362c
+         saved_cflags="${CFLAGS}"
89362c
+         CFLAGS="${CFLAGS} ${NSS_CFLAGS}"
89362c
+         LIBS="${LIBS} ${NSS_LIBS}"
89362c
+         AC_LANG_PUSH([C])
89362c
+         AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <nss3/pk11pub.h>]],
89362c
+                                         [[SECMOD_GetSystemFIPSEnabled()]])],
89362c
+                        [AC_MSG_RESULT([yes])],
89362c
+                        [AC_MSG_RESULT([no])
89362c
+                        AC_MSG_ERROR([System NSS FIPS detection unavailable])])
89362c
+         AC_LANG_POP([C])
89362c
+         CFLAGS="${saved_cflags}"
89362c
+         LIBS="${saved_libs}"
89362c
+         USE_SYSCONF_NSS=true
89362c
+      else
89362c
+         dnl NSS 3.53 is the one that introduces the SECMOD_GetSystemFIPSEnabled API
89362c
+         dnl in nss3/pk11pub.h.
89362c
+         AC_MSG_ERROR([--enable-sysconf-nss specified, but NSS 3.53 or above not found.])
89362c
+      fi
89362c
+  fi
89362c
+  AC_SUBST(USE_SYSCONF_NSS)
89362c
+])
89362c
diff --git a/make/autoconf/spec.gmk.in b/make/autoconf/spec.gmk.in
89362c
index 0ae23b93167..a242acc1234 100644
89362c
--- a/make/autoconf/spec.gmk.in
89362c
+++ b/make/autoconf/spec.gmk.in
89362c
@@ -826,6 +826,10 @@ INSTALL_SYSCONFDIR=@sysconfdir@
89362c
 # Libraries
89362c
 #
89362c
 
89362c
+USE_SYSCONF_NSS:=@USE_SYSCONF_NSS@
89362c
+NSS_LIBS:=@NSS_LIBS@
89362c
+NSS_CFLAGS:=@NSS_CFLAGS@
89362c
+
89362c
 USE_EXTERNAL_LCMS:=@USE_EXTERNAL_LCMS@
89362c
 LCMS_CFLAGS:=@LCMS_CFLAGS@
89362c
 LCMS_LIBS:=@LCMS_LIBS@
89362c
diff --git a/make/lib/Lib-java.base.gmk b/make/lib/Lib-java.base.gmk
89362c
index a529768f39e..daf9c947172 100644
89362c
--- a/make/lib/Lib-java.base.gmk
89362c
+++ b/make/lib/Lib-java.base.gmk
89362c
@@ -178,6 +178,31 @@ ifeq ($(OPENJDK_TARGET_OS_TYPE), unix)
89362c
   endif
89362c
 endif
89362c
 
89362c
+################################################################################
89362c
+# Create the systemconf library
89362c
+
89362c
+LIBSYSTEMCONF_CFLAGS :=
89362c
+LIBSYSTEMCONF_CXXFLAGS :=
89362c
+
89362c
+ifeq ($(USE_SYSCONF_NSS), true)
89362c
+  LIBSYSTEMCONF_CFLAGS += $(NSS_CFLAGS) -DSYSCONF_NSS
89362c
+  LIBSYSTEMCONF_CXXFLAGS += $(NSS_CFLAGS) -DSYSCONF_NSS
89362c
+endif
89362c
+
89362c
+ifeq ($(OPENJDK_BUILD_OS), linux)
89362c
+  $(eval $(call SetupJdkLibrary, BUILD_LIBSYSTEMCONF, \
89362c
+      NAME := systemconf, \
89362c
+      OPTIMIZATION := LOW, \
89362c
+      CFLAGS := $(CFLAGS_JDKLIB) $(LIBSYSTEMCONF_CFLAGS), \
89362c
+      CXXFLAGS := $(CXXFLAGS_JDKLIB) $(LIBSYSTEMCONF_CXXFLAGS), \
89362c
+      LDFLAGS := $(LDFLAGS_JDKLIB) \
89362c
+          $(call SET_SHARED_LIBRARY_ORIGIN), \
89362c
+      LIBS_unix := $(LIBDL) $(NSS_LIBS), \
89362c
+  ))
89362c
+
89362c
+  TARGETS += $(BUILD_LIBSYSTEMCONF)
89362c
+endif
89362c
+
89362c
 ################################################################################
89362c
 # Create the symbols file for static builds.
89362c
 
89362c
diff --git a/make/nb_native/nbproject/configurations.xml b/make/nb_native/nbproject/configurations.xml
89362c
index fb07d54c1f0..c5813e2b7aa 100644
89362c
--- a/make/nb_native/nbproject/configurations.xml
89362c
+++ b/make/nb_native/nbproject/configurations.xml
89362c
@@ -2950,6 +2950,9 @@
89362c
                   <in>LinuxWatchService.c</in>
89362c
                 </df>
89362c
               </df>
89362c
+              <df name="libsystemconf">
89362c
+                <in>systemconf.c</in>
89362c
+              </df>
89362c
             </df>
89362c
           </df>
89362c
           <df name="macosx">
89362c
@@ -29301,6 +29304,11 @@
89362c
             tool="0"
89362c
             flavor2="0">
89362c
       </item>
89362c
+      
89362c
+            ex="false"
89362c
+            tool="0"
89362c
+            flavor2="0">
89362c
+      </item>
89362c
       
89362c
             ex="false"
89362c
             tool="3"
89362c
diff --git a/make/scripts/compare_exceptions.sh.incl b/make/scripts/compare_exceptions.sh.incl
89362c
index 6327040964d..6b3780123b6 100644
89362c
--- a/make/scripts/compare_exceptions.sh.incl
89362c
+++ b/make/scripts/compare_exceptions.sh.incl
89362c
@@ -179,6 +179,7 @@ if [ "$OPENJDK_TARGET_OS" = "solaris" ] && [ "$OPENJDK_TARGET_CPU" = "x86_64" ];
89362c
       ./lib/libsplashscreen.so
89362c
       ./lib/libsunec.so
89362c
       ./lib/libsunwjdga.so
89362c
+      ./lib/libsystemconf.so
89362c
       ./lib/libunpack.so
89362c
       ./lib/libverify.so
89362c
       ./lib/libzip.so
89362c
@@ -289,6 +290,7 @@ if [ "$OPENJDK_TARGET_OS" = "solaris" ] && [ "$OPENJDK_TARGET_CPU" = "sparcv9" ]
89362c
       ./lib/libsplashscreen.so
89362c
       ./lib/libsunec.so
89362c
       ./lib/libsunwjdga.so
89362c
+      ./lib/libsystemconf.so
89362c
       ./lib/libunpack.so
89362c
       ./lib/libverify.so
89362c
       ./lib/libzip.so
89362c
diff --git a/src/java.base/linux/native/libsystemconf/systemconf.c b/src/java.base/linux/native/libsystemconf/systemconf.c
89362c
new file mode 100644
89362c
index 00000000000..8dcb7d9073f
89362c
--- /dev/null
89362c
+++ b/src/java.base/linux/native/libsystemconf/systemconf.c
89362c
@@ -0,0 +1,224 @@
89362c
+/*
89362c
+ * Copyright (c) 2021, Red Hat, Inc.
89362c
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
89362c
+ *
89362c
+ * This code is free software; you can redistribute it and/or modify it
89362c
+ * under the terms of the GNU General Public License version 2 only, as
89362c
+ * published by the Free Software Foundation.  Oracle designates this
89362c
+ * particular file as subject to the "Classpath" exception as provided
89362c
+ * by Oracle in the LICENSE file that accompanied this code.
89362c
+ *
89362c
+ * This code is distributed in the hope that it will be useful, but WITHOUT
89362c
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
89362c
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
89362c
+ * version 2 for more details (a copy is included in the LICENSE file that
89362c
+ * accompanied this code).
89362c
+ *
89362c
+ * You should have received a copy of the GNU General Public License version
89362c
+ * 2 along with this work; if not, write to the Free Software Foundation,
89362c
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
89362c
+ *
89362c
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
89362c
+ * or visit www.oracle.com if you need additional information or have any
89362c
+ * questions.
89362c
+ */
89362c
+
89362c
+#include <jni.h>
89362c
+#include <jni_util.h>
89362c
+#include "jvm_md.h"
89362c
+#include <stdio.h>
89362c
+
89362c
+#ifdef SYSCONF_NSS
89362c
+#include <nss3/pk11pub.h>
89362c
+#else
89362c
+#include <dlfcn.h>
89362c
+#endif //SYSCONF_NSS
89362c
+
89362c
+#include "java_security_SystemConfigurator.h"
89362c
+
89362c
+#define MSG_MAX_SIZE 256
89362c
+#define FIPS_ENABLED_PATH "/proc/sys/crypto/fips_enabled"
89362c
+
89362c
+typedef int (SECMOD_GET_SYSTEM_FIPS_ENABLED_TYPE)(void);
89362c
+
89362c
+static SECMOD_GET_SYSTEM_FIPS_ENABLED_TYPE *getSystemFIPSEnabled;
89362c
+static jmethodID debugPrintlnMethodID = NULL;
89362c
+static jobject debugObj = NULL;
89362c
+
89362c
+static void dbgPrint(JNIEnv *env, const char* msg)
89362c
+{
89362c
+    jstring jMsg;
89362c
+    if (debugObj != NULL) {
89362c
+        jMsg = (*env)->NewStringUTF(env, msg);
89362c
+        CHECK_NULL(jMsg);
89362c
+        (*env)->CallVoidMethod(env, debugObj, debugPrintlnMethodID, jMsg);
89362c
+    }
89362c
+}
89362c
+
89362c
+static void throwIOException(JNIEnv *env, const char *msg)
89362c
+{
89362c
+    jclass cls = (*env)->FindClass(env, "java/io/IOException");
89362c
+    if (cls != 0)
89362c
+        (*env)->ThrowNew(env, cls, msg);
89362c
+}
89362c
+
89362c
+static void handle_msg(JNIEnv *env, const char* msg, int msg_bytes)
89362c
+{
89362c
+  if (msg_bytes > 0 && msg_bytes < MSG_MAX_SIZE) {
89362c
+    dbgPrint(env, msg);
89362c
+  } else {
89362c
+    dbgPrint(env, "systemconf: cannot render message");
89362c
+  }
89362c
+}
89362c
+
89362c
+// Only used when NSS is not linked at build time
89362c
+#ifndef SYSCONF_NSS
89362c
+
89362c
+static void *nss_handle;
89362c
+
89362c
+static jboolean loadNSS(JNIEnv *env)
89362c
+{
89362c
+  char msg[MSG_MAX_SIZE];
89362c
+  int msg_bytes;
89362c
+  const char* errmsg;
89362c
+
89362c
+  nss_handle = dlopen(JNI_LIB_NAME("nss3"), RTLD_LAZY);
89362c
+  if (nss_handle == NULL) {
89362c
+    errmsg = dlerror();
89362c
+    msg_bytes = snprintf(msg, MSG_MAX_SIZE, "loadNSS: dlopen: %s\n",
89362c
+                         errmsg);
89362c
+    handle_msg(env, msg, msg_bytes);
89362c
+    return JNI_FALSE;
89362c
+  }
89362c
+  dlerror(); /* Clear errors */
89362c
+  getSystemFIPSEnabled = (SECMOD_GET_SYSTEM_FIPS_ENABLED_TYPE*)dlsym(nss_handle, "SECMOD_GetSystemFIPSEnabled");
89362c
+  if ((errmsg = dlerror()) != NULL) {
89362c
+    msg_bytes = snprintf(msg, MSG_MAX_SIZE, "loadNSS: dlsym: %s\n",
89362c
+                         errmsg);
89362c
+    handle_msg(env, msg, msg_bytes);
89362c
+    return JNI_FALSE;
89362c
+  }
89362c
+  return JNI_TRUE;
89362c
+}
89362c
+
89362c
+static void closeNSS(JNIEnv *env)
89362c
+{
89362c
+  char msg[MSG_MAX_SIZE];
89362c
+  int msg_bytes;
89362c
+  const char* errmsg;
89362c
+
89362c
+  if (dlclose(nss_handle) != 0) {
89362c
+    errmsg = dlerror();
89362c
+    msg_bytes = snprintf(msg, MSG_MAX_SIZE, "closeNSS: dlclose: %s\n",
89362c
+                         errmsg);
89362c
+    handle_msg(env, msg, msg_bytes);
89362c
+  }
89362c
+}
89362c
+
89362c
+#endif
89362c
+
89362c
+/*
89362c
+ * Class:     java_security_SystemConfigurator
89362c
+ * Method:    JNI_OnLoad
89362c
+ */
89362c
+JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *vm, void *reserved)
89362c
+{
89362c
+    JNIEnv *env;
89362c
+    jclass sysConfCls, debugCls;
89362c
+    jfieldID sdebugFld;
89362c
+
89362c
+    if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_2) != JNI_OK) {
89362c
+        return JNI_EVERSION; /* JNI version not supported */
89362c
+    }
89362c
+
89362c
+    sysConfCls = (*env)->FindClass(env,"java/security/SystemConfigurator");
89362c
+    if (sysConfCls == NULL) {
89362c
+        printf("libsystemconf: SystemConfigurator class not found\n");
89362c
+        return JNI_ERR;
89362c
+    }
89362c
+    sdebugFld = (*env)->GetStaticFieldID(env, sysConfCls,
89362c
+            "sdebug", "Lsun/security/util/Debug;");
89362c
+    if (sdebugFld == NULL) {
89362c
+        printf("libsystemconf: SystemConfigurator::sdebug field not found\n");
89362c
+        return JNI_ERR;
89362c
+    }
89362c
+    debugObj = (*env)->GetStaticObjectField(env, sysConfCls, sdebugFld);
89362c
+    if (debugObj != NULL) {
89362c
+        debugCls = (*env)->FindClass(env,"sun/security/util/Debug");
89362c
+        if (debugCls == NULL) {
89362c
+            printf("libsystemconf: Debug class not found\n");
89362c
+            return JNI_ERR;
89362c
+        }
89362c
+        debugPrintlnMethodID = (*env)->GetMethodID(env, debugCls,
89362c
+                "println", "(Ljava/lang/String;)V");
89362c
+        if (debugPrintlnMethodID == NULL) {
89362c
+            printf("libsystemconf: Debug::println(String) method not found\n");
89362c
+            return JNI_ERR;
89362c
+        }
89362c
+        debugObj = (*env)->NewGlobalRef(env, debugObj);
89362c
+    }
89362c
+
89362c
+#ifdef SYSCONF_NSS
89362c
+    getSystemFIPSEnabled = *SECMOD_GetSystemFIPSEnabled;
89362c
+#else
89362c
+    if (loadNSS(env) == JNI_FALSE) {
89362c
+      dbgPrint(env, "libsystemconf: Failed to load NSS library.");
89362c
+    }
89362c
+#endif
89362c
+
89362c
+    return (*env)->GetVersion(env);
89362c
+}
89362c
+
89362c
+/*
89362c
+ * Class:     java_security_SystemConfigurator
89362c
+ * Method:    JNI_OnUnload
89362c
+ */
89362c
+JNIEXPORT void JNICALL DEF_JNI_OnUnload(JavaVM *vm, void *reserved)
89362c
+{
89362c
+    JNIEnv *env;
89362c
+
89362c
+    if (debugObj != NULL) {
89362c
+        if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_2) != JNI_OK) {
89362c
+            return; /* Should not happen */
89362c
+        }
89362c
+#ifndef SYSCONF_NSS
89362c
+        closeNSS(env);
89362c
+#endif
89362c
+        (*env)->DeleteGlobalRef(env, debugObj);
89362c
+    }
89362c
+}
89362c
+
89362c
+JNIEXPORT jboolean JNICALL Java_java_security_SystemConfigurator_getSystemFIPSEnabled
89362c
+  (JNIEnv *env, jclass cls)
89362c
+{
89362c
+    int fips_enabled;
89362c
+    char msg[MSG_MAX_SIZE];
89362c
+    int msg_bytes;
89362c
+
89362c
+    if (getSystemFIPSEnabled != NULL) {
89362c
+      dbgPrint(env, "getSystemFIPSEnabled: calling SECMOD_GetSystemFIPSEnabled");
89362c
+      fips_enabled = (*getSystemFIPSEnabled)();
89362c
+      msg_bytes = snprintf(msg, MSG_MAX_SIZE, "getSystemFIPSEnabled:"   \
89362c
+                           " SECMOD_GetSystemFIPSEnabled returned 0x%x", fips_enabled);
89362c
+      handle_msg(env, msg, msg_bytes);
89362c
+      return (fips_enabled == 1 ? JNI_TRUE : JNI_FALSE);
89362c
+    } else {
89362c
+      FILE *fe;
89362c
+
89362c
+      dbgPrint(env, "getSystemFIPSEnabled: reading " FIPS_ENABLED_PATH);
89362c
+      if ((fe = fopen(FIPS_ENABLED_PATH, "r")) == NULL) {
89362c
+        throwIOException(env, "Cannot open " FIPS_ENABLED_PATH);
89362c
+        return JNI_FALSE;
89362c
+      }
89362c
+      fips_enabled = fgetc(fe);
89362c
+      fclose(fe);
89362c
+      if (fips_enabled == EOF) {
89362c
+        throwIOException(env, "Cannot read " FIPS_ENABLED_PATH);
89362c
+        return JNI_FALSE;
89362c
+      }
89362c
+      msg_bytes = snprintf(msg, MSG_MAX_SIZE, "getSystemFIPSEnabled:"   \
89362c
+                           " read character is '%c'", fips_enabled);
89362c
+      handle_msg(env, msg, msg_bytes);
89362c
+      return (fips_enabled == '1' ? JNI_TRUE : JNI_FALSE);
89362c
+    }
89362c
+}
89362c
diff --git a/src/java.base/share/classes/java/security/Security.java b/src/java.base/share/classes/java/security/Security.java
89362c
index b36510a376b..ad5182e1e7c 100644
89362c
--- a/src/java.base/share/classes/java/security/Security.java
89362c
+++ b/src/java.base/share/classes/java/security/Security.java
89362c
@@ -32,6 +32,7 @@ import java.net.URL;
89362c
 
89362c
 import jdk.internal.event.EventHelper;
89362c
 import jdk.internal.event.SecurityPropertyModificationEvent;
89362c
+import jdk.internal.misc.JavaSecuritySystemConfiguratorAccess;
89362c
 import jdk.internal.misc.SharedSecrets;
89362c
 import jdk.internal.util.StaticProperty;
89362c
 import sun.security.util.Debug;
89362c
@@ -47,12 +48,20 @@ import sun.security.jca.*;
89362c
  * implementation-specific location, which is typically the properties file
89362c
  * {@code conf/security/java.security} in the Java installation directory.
89362c
  *
89362c
+ * 

Additional default values of security properties are read from a

89362c
+ * system-specific location, if available.

89362c
+ *
89362c
  * @author Benjamin Renaud
89362c
  * @since 1.1
89362c
  */
89362c
 
89362c
 public final class Security {
89362c
 
89362c
+    private static final String SYS_PROP_SWITCH =
89362c
+        "java.security.disableSystemPropertiesFile";
89362c
+    private static final String SEC_PROP_SWITCH =
89362c
+        "security.useSystemPropertiesFile";
89362c
+
89362c
     /* Are we debugging? -- for developers */
89362c
     private static final Debug sdebug =
89362c
                         Debug.getInstance("properties");
89362c
@@ -67,6 +76,19 @@ public final class Security {
89362c
     }
89362c
 
89362c
     static {
89362c
+        // Initialise here as used by code with system properties disabled
89362c
+        SharedSecrets.setJavaSecuritySystemConfiguratorAccess(
89362c
+            new JavaSecuritySystemConfiguratorAccess() {
89362c
+                @Override
89362c
+                public boolean isSystemFipsEnabled() {
89362c
+                    return SystemConfigurator.isSystemFipsEnabled();
89362c
+                }
89362c
+                @Override
89362c
+                public boolean isPlainKeySupportEnabled() {
89362c
+                    return SystemConfigurator.isPlainKeySupportEnabled();
89362c
+                }
89362c
+            });
89362c
+
89362c
         // doPrivileged here because there are multiple
89362c
         // things in initialize that might require privs.
89362c
         // (the FileInputStream call and the File.exists call,
89362c
@@ -83,6 +105,7 @@ public final class Security {
89362c
         props = new Properties();
89362c
         boolean loadedProps = false;
89362c
         boolean overrideAll = false;
89362c
+        boolean systemSecPropsEnabled = false;
89362c
 
89362c
         // first load the system properties file
89362c
         // to determine the value of security.overridePropertiesFile
89362c
@@ -98,6 +121,7 @@ public final class Security {
89362c
                 if (sdebug != null) {
89362c
                     sdebug.println("reading security properties file: " +
89362c
                                 propFile);
89362c
+                    sdebug.println(props.toString());
89362c
                 }
89362c
             } catch (IOException e) {
89362c
                 if (sdebug != null) {
89362c
@@ -192,6 +216,61 @@ public final class Security {
89362c
             }
89362c
         }
89362c
 
89362c
+        boolean sysUseProps = Boolean.valueOf(System.getProperty(SYS_PROP_SWITCH, "false"));
89362c
+        boolean secUseProps = Boolean.valueOf(props.getProperty(SEC_PROP_SWITCH));
89362c
+        if (sdebug != null) {
89362c
+            sdebug.println(SYS_PROP_SWITCH + "=" + sysUseProps);
89362c
+            sdebug.println(SEC_PROP_SWITCH + "=" + secUseProps);
89362c
+        }
89362c
+        if (!sysUseProps && secUseProps) {
89362c
+            systemSecPropsEnabled = SystemConfigurator.configureSysProps(props);
89362c
+            if (!systemSecPropsEnabled) {
89362c
+                if (sdebug != null) {
89362c
+                    sdebug.println("WARNING: System security properties could not be loaded.");
89362c
+                }
89362c
+            }
89362c
+        } else {
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("System security property support disabled by user.");
89362c
+            }
89362c
+        }
89362c
+
89362c
+        // FIPS support depends on the contents of java.security so
89362c
+        // ensure it has loaded first
89362c
+        if (loadedProps && systemSecPropsEnabled) {
89362c
+            boolean shouldEnable;
89362c
+            String sysProp = System.getProperty("com.redhat.fips");
89362c
+            if (sysProp == null) {
89362c
+                shouldEnable = true;
89362c
+                if (sdebug != null) {
89362c
+                    sdebug.println("com.redhat.fips unset, using default value of true");
89362c
+                }
89362c
+            } else {
89362c
+                shouldEnable = Boolean.valueOf(sysProp);
89362c
+                if (sdebug != null) {
89362c
+                    sdebug.println("com.redhat.fips set, using its value " + shouldEnable);
89362c
+                }
89362c
+            }
89362c
+            if (shouldEnable) {
89362c
+                boolean fipsEnabled = SystemConfigurator.configureFIPS(props);
89362c
+                if (sdebug != null) {
89362c
+                    if (fipsEnabled) {
89362c
+                        sdebug.println("FIPS mode support configured and enabled.");
89362c
+                    } else {
89362c
+                        sdebug.println("FIPS mode support disabled.");
89362c
+                    }
89362c
+                }
89362c
+            } else {
89362c
+                if (sdebug != null ) {
89362c
+                    sdebug.println("FIPS mode support disabled by user.");
89362c
+                }
89362c
+            }
89362c
+        } else {
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("WARNING: FIPS mode support can not be enabled without " +
89362c
+                               "system security properties being enabled.");
89362c
+            }
89362c
+        }
89362c
     }
89362c
 
89362c
     /*
89362c
diff --git a/src/java.base/share/classes/java/security/SystemConfigurator.java b/src/java.base/share/classes/java/security/SystemConfigurator.java
89362c
new file mode 100644
89362c
index 00000000000..90f6dd2ebc0
89362c
--- /dev/null
89362c
+++ b/src/java.base/share/classes/java/security/SystemConfigurator.java
89362c
@@ -0,0 +1,248 @@
89362c
+/*
89362c
+ * Copyright (c) 2019, 2021, Red Hat, Inc.
89362c
+ *
89362c
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
89362c
+ *
89362c
+ * This code is free software; you can redistribute it and/or modify it
89362c
+ * under the terms of the GNU General Public License version 2 only, as
89362c
+ * published by the Free Software Foundation.  Oracle designates this
89362c
+ * particular file as subject to the "Classpath" exception as provided
89362c
+ * by Oracle in the LICENSE file that accompanied this code.
89362c
+ *
89362c
+ * This code is distributed in the hope that it will be useful, but WITHOUT
89362c
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
89362c
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
89362c
+ * version 2 for more details (a copy is included in the LICENSE file that
89362c
+ * accompanied this code).
89362c
+ *
89362c
+ * You should have received a copy of the GNU General Public License version
89362c
+ * 2 along with this work; if not, write to the Free Software Foundation,
89362c
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
89362c
+ *
89362c
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
89362c
+ * or visit www.oracle.com if you need additional information or have any
89362c
+ * questions.
89362c
+ */
89362c
+
89362c
+package java.security;
89362c
+
89362c
+import java.io.BufferedInputStream;
89362c
+import java.io.FileInputStream;
89362c
+import java.io.IOException;
89362c
+
89362c
+import java.util.Iterator;
89362c
+import java.util.Map.Entry;
89362c
+import java.util.Properties;
89362c
+
89362c
+import sun.security.util.Debug;
89362c
+
89362c
+/**
89362c
+ * Internal class to align OpenJDK with global crypto-policies.
89362c
+ * Called from java.security.Security class initialization,
89362c
+ * during startup.
89362c
+ *
89362c
+ */
89362c
+
89362c
+final class SystemConfigurator {
89362c
+
89362c
+    private static final Debug sdebug =
89362c
+            Debug.getInstance("properties");
89362c
+
89362c
+    private static final String CRYPTO_POLICIES_BASE_DIR =
89362c
+            "/etc/crypto-policies";
89362c
+
89362c
+    private static final String CRYPTO_POLICIES_JAVA_CONFIG =
89362c
+            CRYPTO_POLICIES_BASE_DIR + "/back-ends/java.config";
89362c
+
89362c
+    private static boolean systemFipsEnabled = false;
89362c
+    private static boolean plainKeySupportEnabled = false;
89362c
+
89362c
+    private static final String SYSTEMCONF_NATIVE_LIB = "systemconf";
89362c
+
89362c
+    private static native boolean getSystemFIPSEnabled()
89362c
+            throws IOException;
89362c
+
89362c
+    static {
89362c
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
89362c
+            public Void run() {
89362c
+                System.loadLibrary(SYSTEMCONF_NATIVE_LIB);
89362c
+                return null;
89362c
+            }
89362c
+        });
89362c
+    }
89362c
+
89362c
+    /*
89362c
+     * Invoked when java.security.Security class is initialized, if
89362c
+     * java.security.disableSystemPropertiesFile property is not set and
89362c
+     * security.useSystemPropertiesFile is true.
89362c
+     */
89362c
+    static boolean configureSysProps(Properties props) {
89362c
+        boolean systemSecPropsLoaded = false;
89362c
+
89362c
+        try (BufferedInputStream bis =
89362c
+                new BufferedInputStream(
89362c
+                        new FileInputStream(CRYPTO_POLICIES_JAVA_CONFIG))) {
89362c
+            props.load(bis);
89362c
+            systemSecPropsLoaded = true;
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("reading system security properties file " +
89362c
+                        CRYPTO_POLICIES_JAVA_CONFIG);
89362c
+                sdebug.println(props.toString());
89362c
+            }
89362c
+        } catch (IOException e) {
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("unable to load security properties from " +
89362c
+                        CRYPTO_POLICIES_JAVA_CONFIG);
89362c
+                e.printStackTrace();
89362c
+            }
89362c
+        }
89362c
+        return systemSecPropsLoaded;
89362c
+    }
89362c
+
89362c
+    /*
89362c
+     * Invoked at the end of java.security.Security initialisation
89362c
+     * if java.security properties have been loaded
89362c
+     */
89362c
+    static boolean configureFIPS(Properties props) {
89362c
+        boolean loadedProps = false;
89362c
+
89362c
+        try {
89362c
+            if (enableFips()) {
89362c
+                if (sdebug != null) { sdebug.println("FIPS mode detected"); }
89362c
+                // Remove all security providers
89362c
+                Iterator<Entry<Object, Object>> i = props.entrySet().iterator();
89362c
+                while (i.hasNext()) {
89362c
+                    Entry<Object, Object> e = i.next();
89362c
+                    if (((String) e.getKey()).startsWith("security.provider")) {
89362c
+                        if (sdebug != null) { sdebug.println("Removing provider: " + e); }
89362c
+                        i.remove();
89362c
+                    }
89362c
+                }
89362c
+                // Add FIPS security providers
89362c
+                String fipsProviderValue = null;
89362c
+                for (int n = 1;
89362c
+                     (fipsProviderValue = (String) props.get("fips.provider." + n)) != null; n++) {
89362c
+                    String fipsProviderKey = "security.provider." + n;
89362c
+                    if (sdebug != null) {
89362c
+                        sdebug.println("Adding provider " + n + ": " +
89362c
+                                fipsProviderKey + "=" + fipsProviderValue);
89362c
+                    }
89362c
+                    props.put(fipsProviderKey, fipsProviderValue);
89362c
+                }
89362c
+                // Add other security properties
89362c
+                String keystoreTypeValue = (String) props.get("fips.keystore.type");
89362c
+                if (keystoreTypeValue != null) {
89362c
+                    String nonFipsKeystoreType = props.getProperty("keystore.type");
89362c
+                    props.put("keystore.type", keystoreTypeValue);
89362c
+                    if (keystoreTypeValue.equals("PKCS11")) {
89362c
+                        // If keystore.type is PKCS11, javax.net.ssl.keyStore
89362c
+                        // must be "NONE". See JDK-8238264.
89362c
+                        System.setProperty("javax.net.ssl.keyStore", "NONE");
89362c
+                    }
89362c
+                    if (System.getProperty("javax.net.ssl.trustStoreType") == null) {
89362c
+                        // If no trustStoreType has been set, use the
89362c
+                        // previous keystore.type under FIPS mode. In
89362c
+                        // a default configuration, the Trust Store will
89362c
+                        // be 'cacerts' (JKS type).
89362c
+                        System.setProperty("javax.net.ssl.trustStoreType",
89362c
+                                nonFipsKeystoreType);
89362c
+                    }
89362c
+                    if (sdebug != null) {
89362c
+                        sdebug.println("FIPS mode default keystore.type = " +
89362c
+                                keystoreTypeValue);
89362c
+                        sdebug.println("FIPS mode javax.net.ssl.keyStore = " +
89362c
+                                System.getProperty("javax.net.ssl.keyStore", ""));
89362c
+                        sdebug.println("FIPS mode javax.net.ssl.trustStoreType = " +
89362c
+                                System.getProperty("javax.net.ssl.trustStoreType", ""));
89362c
+                    }
89362c
+                }
89362c
+                loadedProps = true;
89362c
+                systemFipsEnabled = true;
89362c
+                String plainKeySupport = System.getProperty("com.redhat.fips.plainKeySupport",
89362c
+                                                            "true");
89362c
+                plainKeySupportEnabled = !"false".equals(plainKeySupport);
89362c
+                if (sdebug != null) {
89362c
+                    if (plainKeySupportEnabled) {
89362c
+                        sdebug.println("FIPS support enabled with plain key support");
89362c
+                    } else {
89362c
+                        sdebug.println("FIPS support enabled without plain key support");
89362c
+                    }
89362c
+                }
89362c
+            } else {
89362c
+                if (sdebug != null) { sdebug.println("FIPS mode not detected"); }
89362c
+            }
89362c
+        } catch (Exception e) {
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("unable to load FIPS configuration");
89362c
+                e.printStackTrace();
89362c
+            }
89362c
+        }
89362c
+        return loadedProps;
89362c
+    }
89362c
+
89362c
+    /**
89362c
+     * Returns whether or not global system FIPS alignment is enabled.
89362c
+     *
89362c
+     * Value is always 'false' before java.security.Security class is
89362c
+     * initialized.
89362c
+     *
89362c
+     * Call from out of this package through SharedSecrets:
89362c
+     *   SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
89362c
+     *           .isSystemFipsEnabled();
89362c
+     *
89362c
+     * @return  a boolean value indicating whether or not global
89362c
+     *          system FIPS alignment is enabled.
89362c
+     */
89362c
+    static boolean isSystemFipsEnabled() {
89362c
+        return systemFipsEnabled;
89362c
+    }
89362c
+
89362c
+    /**
89362c
+     * Returns {@code true} if system FIPS alignment is enabled
89362c
+     * and plain key support is allowed.  Plain key support is
89362c
+     * enabled by default but can be disabled with
89362c
+     * {@code -Dcom.redhat.fips.plainKeySupport=false}.
89362c
+     *
89362c
+     * @return a boolean indicating whether plain key support
89362c
+     *         should be enabled.
89362c
+     */
89362c
+    static boolean isPlainKeySupportEnabled() {
89362c
+        return plainKeySupportEnabled;
89362c
+    }
89362c
+
89362c
+    /**
89362c
+     * Determines whether FIPS mode should be enabled.
89362c
+     *
89362c
+     * OpenJDK FIPS mode will be enabled only if the system is in
89362c
+     * FIPS mode.
89362c
+     *
89362c
+     * Calls to this method only occur if the system property
89362c
+     * com.redhat.fips is not set to false.
89362c
+     *
89362c
+     * There are 2 possible ways in which OpenJDK detects that the system
89362c
+     * is in FIPS mode: 1) if the NSS SECMOD_GetSystemFIPSEnabled API is
89362c
+     * available at OpenJDK's built-time, it is called; 2) otherwise, the
89362c
+     * /proc/sys/crypto/fips_enabled file is read.
89362c
+     *
89362c
+     * @return true if the system is in FIPS mode
89362c
+     */
89362c
+    private static boolean enableFips() throws Exception {
89362c
+        if (sdebug != null) {
89362c
+            sdebug.println("Calling getSystemFIPSEnabled (libsystemconf)...");
89362c
+        }
89362c
+        try {
89362c
+            boolean fipsEnabled = getSystemFIPSEnabled();
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("Call to getSystemFIPSEnabled (libsystemconf) returned: "
89362c
+                               + fipsEnabled);
89362c
+            }
89362c
+            return fipsEnabled;
89362c
+        } catch (IOException e) {
89362c
+            if (sdebug != null) {
89362c
+                sdebug.println("Call to getSystemFIPSEnabled (libsystemconf) failed:");
89362c
+                sdebug.println(e.getMessage());
89362c
+            }
89362c
+            throw e;
89362c
+        }
89362c
+    }
89362c
+}
89362c
diff --git a/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java b/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java
89362c
new file mode 100644
89362c
index 00000000000..21bc6d0b591
89362c
--- /dev/null
89362c
+++ b/src/java.base/share/classes/jdk/internal/misc/JavaSecuritySystemConfiguratorAccess.java
89362c
@@ -0,0 +1,31 @@
89362c
+/*
89362c
+ * Copyright (c) 2020, Red Hat, Inc.
89362c
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
89362c
+ *
89362c
+ * This code is free software; you can redistribute it and/or modify it
89362c
+ * under the terms of the GNU General Public License version 2 only, as
89362c
+ * published by the Free Software Foundation.  Oracle designates this
89362c
+ * particular file as subject to the "Classpath" exception as provided
89362c
+ * by Oracle in the LICENSE file that accompanied this code.
89362c
+ *
89362c
+ * This code is distributed in the hope that it will be useful, but WITHOUT
89362c
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
89362c
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
89362c
+ * version 2 for more details (a copy is included in the LICENSE file that
89362c
+ * accompanied this code).
89362c
+ *
89362c
+ * You should have received a copy of the GNU General Public License version
89362c
+ * 2 along with this work; if not, write to the Free Software Foundation,
89362c
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
89362c
+ *
89362c
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
89362c
+ * or visit www.oracle.com if you need additional information or have any
89362c
+ * questions.
89362c
+ */
89362c
+
89362c
+package jdk.internal.misc;
89362c
+
89362c
+public interface JavaSecuritySystemConfiguratorAccess {
89362c
+    boolean isSystemFipsEnabled();
89362c
+    boolean isPlainKeySupportEnabled();
89362c
+}
89362c
diff --git a/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java b/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java
89362c
index 688ec9f0915..8489b940c43 100644
89362c
--- a/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java
89362c
+++ b/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java
89362c
@@ -36,6 +36,7 @@ import java.io.FilePermission;
89362c
 import java.io.ObjectInputStream;
89362c
 import java.io.RandomAccessFile;
89362c
 import java.security.ProtectionDomain;
89362c
+import java.security.Security;
89362c
 import java.security.Signature;
89362c
 
89362c
 /** A repository of "shared secrets", which are a mechanism for
89362c
@@ -76,6 +77,7 @@ public class SharedSecrets {
89362c
     private static JavaIORandomAccessFileAccess javaIORandomAccessFileAccess;
89362c
     private static JavaSecuritySignatureAccess javaSecuritySignatureAccess;
89362c
     private static JavaxCryptoSealedObjectAccess javaxCryptoSealedObjectAccess;
89362c
+    private static JavaSecuritySystemConfiguratorAccess javaSecuritySystemConfiguratorAccess;
89362c
 
89362c
     public static JavaUtilJarAccess javaUtilJarAccess() {
89362c
         if (javaUtilJarAccess == null) {
89362c
@@ -361,4 +363,15 @@ public class SharedSecrets {
89362c
         }
89362c
         return javaxCryptoSealedObjectAccess;
89362c
     }
89362c
+
89362c
+    public static void setJavaSecuritySystemConfiguratorAccess(JavaSecuritySystemConfiguratorAccess jssca) {
89362c
+        javaSecuritySystemConfiguratorAccess = jssca;
89362c
+    }
89362c
+
89362c
+    public static JavaSecuritySystemConfiguratorAccess getJavaSecuritySystemConfiguratorAccess() {
89362c
+        if (javaSecuritySystemConfiguratorAccess == null) {
89362c
+            unsafe.ensureClassInitialized(Security.class);
89362c
+        }
89362c
+        return javaSecuritySystemConfiguratorAccess;
89362c
+    }
89362c
 }
89362c
diff --git a/src/java.base/share/classes/module-info.java b/src/java.base/share/classes/module-info.java
89362c
index 5460efcf8c5..f08dc2fafc5 100644
89362c
--- a/src/java.base/share/classes/module-info.java
89362c
+++ b/src/java.base/share/classes/module-info.java
89362c
@@ -182,6 +182,7 @@ module java.base {
89362c
         java.security.jgss,
89362c
         java.sql,
89362c
         java.xml,
89362c
+        jdk.crypto.cryptoki,
89362c
         jdk.jartool,
89362c
         jdk.attach,
89362c
         jdk.charsets,
89362c
diff --git a/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java b/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
89362c
index ffee2c1603b..ff3d5e0e4ab 100644
89362c
--- a/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
89362c
+++ b/src/java.base/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
89362c
@@ -33,8 +33,13 @@ import java.security.KeyStore.*;
89362c
 
89362c
 import javax.net.ssl.*;
89362c
 
89362c
+import jdk.internal.misc.SharedSecrets;
89362c
+
89362c
 abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
89362c
 
89362c
+    private static final boolean plainKeySupportEnabled = SharedSecrets
89362c
+            .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled();
89362c
+
89362c
     X509ExtendedKeyManager keyManager;
89362c
     boolean isInitialized;
89362c
 
89362c
@@ -62,7 +67,8 @@ abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
89362c
                 KeyStoreException, NoSuchAlgorithmException,
89362c
                 UnrecoverableKeyException {
89362c
             if ((ks != null) && SunJSSE.isFIPS()) {
89362c
-                if (ks.getProvider() != SunJSSE.cryptoProvider) {
89362c
+                if (ks.getProvider() != SunJSSE.cryptoProvider &&
89362c
+                        !plainKeySupportEnabled) {
89362c
                     throw new KeyStoreException("FIPS mode: KeyStore must be "
89362c
                         + "from provider " + SunJSSE.cryptoProvider.getName());
89362c
                 }
89362c
@@ -91,8 +97,8 @@ abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
89362c
                 keyManager = new X509KeyManagerImpl(
89362c
                         Collections.<Builder>emptyList());
89362c
             } else {
89362c
-                if (SunJSSE.isFIPS() &&
89362c
-                        (ks.getProvider() != SunJSSE.cryptoProvider)) {
89362c
+                if (SunJSSE.isFIPS() && (ks.getProvider() != SunJSSE.cryptoProvider)
89362c
+                        && !plainKeySupportEnabled) {
89362c
                     throw new KeyStoreException(
89362c
                         "FIPS mode: KeyStore must be " +
89362c
                         "from provider " + SunJSSE.cryptoProvider.getName());
89362c
diff --git a/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java b/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java
89362c
index de7da5c3379..5c3813dda7b 100644
89362c
--- a/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java
89362c
+++ b/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java
89362c
@@ -31,6 +31,7 @@ import java.security.*;
89362c
 import java.security.cert.*;
89362c
 import java.util.*;
89362c
 import javax.net.ssl.*;
89362c
+import jdk.internal.misc.SharedSecrets;
89362c
 import sun.security.action.GetPropertyAction;
89362c
 import sun.security.provider.certpath.AlgorithmChecker;
89362c
 import sun.security.validator.Validator;
89362c
@@ -542,20 +543,38 @@ public abstract class SSLContextImpl extends SSLContextSpi {
89362c
 
89362c
         static {
89362c
             if (SunJSSE.isFIPS()) {
89362c
-                supportedProtocols = Arrays.asList(
89362c
-                    ProtocolVersion.TLS13,
89362c
-                    ProtocolVersion.TLS12,
89362c
-                    ProtocolVersion.TLS11,
89362c
-                    ProtocolVersion.TLS10
89362c
-                );
89362c
+                if (SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
89362c
+                        .isSystemFipsEnabled()) {
89362c
+                    // RH1860986: TLSv1.3 key derivation not supported with
89362c
+                    // the Security Providers available in system FIPS mode.
89362c
+                    supportedProtocols = Arrays.asList(
89362c
+                        ProtocolVersion.TLS12,
89362c
+                        ProtocolVersion.TLS11,
89362c
+                        ProtocolVersion.TLS10
89362c
+                    );
89362c
 
89362c
-                serverDefaultProtocols = getAvailableProtocols(
89362c
-                        new ProtocolVersion[] {
89362c
-                    ProtocolVersion.TLS13,
89362c
-                    ProtocolVersion.TLS12,
89362c
-                    ProtocolVersion.TLS11,
89362c
-                    ProtocolVersion.TLS10
89362c
-                });
89362c
+                    serverDefaultProtocols = getAvailableProtocols(
89362c
+                            new ProtocolVersion[] {
89362c
+                        ProtocolVersion.TLS12,
89362c
+                        ProtocolVersion.TLS11,
89362c
+                        ProtocolVersion.TLS10
89362c
+                    });
89362c
+                } else {
89362c
+                    supportedProtocols = Arrays.asList(
89362c
+                        ProtocolVersion.TLS13,
89362c
+                        ProtocolVersion.TLS12,
89362c
+                        ProtocolVersion.TLS11,
89362c
+                        ProtocolVersion.TLS10
89362c
+                    );
89362c
+
89362c
+                    serverDefaultProtocols = getAvailableProtocols(
89362c
+                            new ProtocolVersion[] {
89362c
+                        ProtocolVersion.TLS13,
89362c
+                        ProtocolVersion.TLS12,
89362c
+                        ProtocolVersion.TLS11,
89362c
+                        ProtocolVersion.TLS10
89362c
+                    });
89362c
+                }
89362c
             } else {
89362c
                 supportedProtocols = Arrays.asList(
89362c
                     ProtocolVersion.TLS13,
89362c
@@ -620,6 +639,16 @@ public abstract class SSLContextImpl extends SSLContextSpi {
89362c
 
89362c
         static ProtocolVersion[] getSupportedProtocols() {
89362c
             if (SunJSSE.isFIPS()) {
89362c
+                if (SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
89362c
+                        .isSystemFipsEnabled()) {
89362c
+                    // RH1860986: TLSv1.3 key derivation not supported with
89362c
+                    // the Security Providers available in system FIPS mode.
89362c
+                    return new ProtocolVersion[] {
89362c
+                            ProtocolVersion.TLS12,
89362c
+                            ProtocolVersion.TLS11,
89362c
+                            ProtocolVersion.TLS10
89362c
+                    };
89362c
+                }
89362c
                 return new ProtocolVersion[] {
89362c
                         ProtocolVersion.TLS13,
89362c
                         ProtocolVersion.TLS12,
89362c
@@ -949,6 +978,16 @@ public abstract class SSLContextImpl extends SSLContextSpi {
89362c
 
89362c
         static ProtocolVersion[] getProtocols() {
89362c
             if (SunJSSE.isFIPS()) {
89362c
+                if (SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
89362c
+                        .isSystemFipsEnabled()) {
89362c
+                    // RH1860986: TLSv1.3 key derivation not supported with
89362c
+                    // the Security Providers available in system FIPS mode.
89362c
+                    return new ProtocolVersion[] {
89362c
+                            ProtocolVersion.TLS12,
89362c
+                            ProtocolVersion.TLS11,
89362c
+                            ProtocolVersion.TLS10
89362c
+                    };
89362c
+                }
89362c
                 return new ProtocolVersion[]{
89362c
                         ProtocolVersion.TLS13,
89362c
                         ProtocolVersion.TLS12,
89362c
diff --git a/src/java.base/share/classes/sun/security/ssl/SunJSSE.java b/src/java.base/share/classes/sun/security/ssl/SunJSSE.java
89362c
index c50ba93ecfc..de2a91a478c 100644
89362c
--- a/src/java.base/share/classes/sun/security/ssl/SunJSSE.java
89362c
+++ b/src/java.base/share/classes/sun/security/ssl/SunJSSE.java
89362c
@@ -27,6 +27,8 @@ package sun.security.ssl;
89362c
 
89362c
 import java.security.*;
89362c
 import java.util.*;
89362c
+
89362c
+import jdk.internal.misc.SharedSecrets;
89362c
 import sun.security.rsa.SunRsaSignEntries;
89362c
 import static sun.security.util.SecurityConstants.PROVIDER_VER;
89362c
 import static sun.security.provider.SunEntries.createAliases;
89362c
@@ -195,8 +197,13 @@ public abstract class SunJSSE extends java.security.Provider {
89362c
             "sun.security.ssl.SSLContextImpl$TLS11Context", null, null);
89362c
         ps("SSLContext", "TLSv1.2",
89362c
             "sun.security.ssl.SSLContextImpl$TLS12Context", null, null);
89362c
-        ps("SSLContext", "TLSv1.3",
89362c
-            "sun.security.ssl.SSLContextImpl$TLS13Context", null, null);
89362c
+        if (!SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
89362c
+                .isSystemFipsEnabled()) {
89362c
+            // RH1860986: TLSv1.3 key derivation not supported with
89362c
+            // the Security Providers available in system FIPS mode.
89362c
+            ps("SSLContext", "TLSv1.3",
89362c
+                "sun.security.ssl.SSLContextImpl$TLS13Context", null, null);
89362c
+        }
89362c
         ps("SSLContext", "TLS",
89362c
             "sun.security.ssl.SSLContextImpl$TLSContext",
89362c
             (isfips? null : createAliases("SSL")), null);
89362c
diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security
89362c
index 097517926d1..474fe6f401f 100644
89362c
--- a/src/java.base/share/conf/security/java.security
89362c
+++ b/src/java.base/share/conf/security/java.security
89362c
@@ -85,6 +85,14 @@ security.provider.tbd=Apple
89362c
 security.provider.tbd=SunPKCS11
89362c
 #endif
89362c
 
89362c
+#
89362c
+# Security providers used when FIPS mode support is active
89362c
+#
89362c
+fips.provider.1=SunPKCS11 ${java.home}/conf/security/nss.fips.cfg
89362c
+fips.provider.2=SUN
89362c
+fips.provider.3=SunEC
89362c
+fips.provider.4=com.sun.net.ssl.internal.ssl.Provider SunPKCS11-NSS-FIPS
89362c
+
89362c
 #
89362c
 # A list of preferred providers for specific algorithms. These providers will
89362c
 # be searched for matching algorithms before the list of registered providers.
89362c
@@ -298,6 +306,11 @@ policy.ignoreIdentityScope=false
89362c
 #
89362c
 keystore.type=pkcs12
89362c
 
89362c
+#
89362c
+# Default keystore type used when global crypto-policies are set to FIPS.
89362c
+#
89362c
+fips.keystore.type=PKCS11
89362c
+
89362c
 #
89362c
 # Controls compatibility mode for JKS and PKCS12 keystore types.
89362c
 #
89362c
@@ -335,6 +348,13 @@ package.definition=sun.misc.,\
89362c
 #
89362c
 security.overridePropertiesFile=true
89362c
 
89362c
+#
89362c
+# Determines whether this properties file will be appended to
89362c
+# using the system properties file stored at
89362c
+# /etc/crypto-policies/back-ends/java.config
89362c
+#
89362c
+security.useSystemPropertiesFile=false
89362c
+
89362c
 #
89362c
 # Determines the default key and trust manager factory algorithms for
89362c
 # the javax.net.ssl package.
89362c
diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java
89362c
new file mode 100644
89362c
index 00000000000..b848a1fd783
89362c
--- /dev/null
89362c
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/FIPSKeyImporter.java
89362c
@@ -0,0 +1,290 @@
89362c
+/*
89362c
+ * Copyright (c) 2021, Red Hat, Inc.
89362c
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
89362c
+ *
89362c
+ * This code is free software; you can redistribute it and/or modify it
89362c
+ * under the terms of the GNU General Public License version 2 only, as
89362c
+ * published by the Free Software Foundation.  Oracle designates this
89362c
+ * particular file as subject to the "Classpath" exception as provided
89362c
+ * by Oracle in the LICENSE file that accompanied this code.
89362c
+ *
89362c
+ * This code is distributed in the hope that it will be useful, but WITHOUT
89362c
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
89362c
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
89362c
+ * version 2 for more details (a copy is included in the LICENSE file that
89362c
+ * accompanied this code).
89362c
+ *
89362c
+ * You should have received a copy of the GNU General Public License version
89362c
+ * 2 along with this work; if not, write to the Free Software Foundation,
89362c
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
89362c
+ *
89362c
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
89362c
+ * or visit www.oracle.com if you need additional information or have any
89362c
+ * questions.
89362c
+ */
89362c
+
89362c
+package sun.security.pkcs11;
89362c
+
89362c
+import java.math.BigInteger;
89362c
+import java.security.KeyFactory;
89362c
+import java.security.Provider;
89362c
+import java.security.Security;
89362c
+import java.util.HashMap;
89362c
+import java.util.Map;
89362c
+import java.util.concurrent.locks.ReentrantLock;
89362c
+
89362c
+import javax.crypto.Cipher;
89362c
+import javax.crypto.spec.DHPrivateKeySpec;
89362c
+import javax.crypto.spec.IvParameterSpec;
89362c
+
89362c
+import sun.security.jca.JCAUtil;
89362c
+import sun.security.pkcs11.TemplateManager;
89362c
+import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;
89362c
+import sun.security.pkcs11.wrapper.CK_MECHANISM;
89362c
+import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
89362c
+import sun.security.pkcs11.wrapper.PKCS11Exception;
89362c
+import sun.security.rsa.RSAUtil.KeyType;
89362c
+import sun.security.util.Debug;
89362c
+import sun.security.util.ECUtil;
89362c
+
89362c
+final class FIPSKeyImporter {
89362c
+
89362c
+    private static final Debug debug =
89362c
+            Debug.getInstance("sunpkcs11");
89362c
+
89362c
+    private static P11Key importerKey = null;
89362c
+    private static final ReentrantLock importerKeyLock = new ReentrantLock();
89362c
+    private static CK_MECHANISM importerKeyMechanism = null;
89362c
+    private static Cipher importerCipher = null;
89362c
+
89362c
+    private static Provider sunECProvider = null;
89362c
+    private static final ReentrantLock sunECProviderLock = new ReentrantLock();
89362c
+
89362c
+    private static KeyFactory DHKF = null;
89362c
+    private static final ReentrantLock DHKFLock = new ReentrantLock();
89362c
+
89362c
+    static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attributes)
89362c
+            throws PKCS11Exception {
89362c
+        long keyID = -1;
89362c
+        Token token = sunPKCS11.getToken();
89362c
+        if (debug != null) {
89362c
+            debug.println("Private or Secret key will be imported in" +
89362c
+                    " system FIPS mode.");
89362c
+        }
89362c
+        if (importerKey == null) {
89362c
+            importerKeyLock.lock();
89362c
+            try {
89362c
+                if (importerKey == null) {
89362c
+                    if (importerKeyMechanism == null) {
89362c
+                        // Importer Key creation has not been tried yet. Try it.
89362c
+                        createImporterKey(token);
89362c
+                    }
89362c
+                    if (importerKey == null || importerCipher == null) {
89362c
+                        if (debug != null) {
89362c
+                            debug.println("Importer Key could not be" +
89362c
+                                    " generated.");
89362c
+                        }
89362c
+                        throw new PKCS11Exception(CKR_GENERAL_ERROR);
89362c
+                    }
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Importer Key successfully" +
89362c
+                                " generated.");
89362c
+                    }
89362c
+                }
89362c
+            } finally {
89362c
+                importerKeyLock.unlock();
89362c
+            }
89362c
+        }
89362c
+        long importerKeyID = importerKey.getKeyID();
89362c
+        try {
89362c
+            byte[] keyBytes = null;
89362c
+            byte[] encKeyBytes = null;
89362c
+            long keyClass = 0L;
89362c
+            long keyType = 0L;
89362c
+            Map<Long, CK_ATTRIBUTE> attrsMap = new HashMap<>();
89362c
+            for (CK_ATTRIBUTE attr : attributes) {
89362c
+                if (attr.type == CKA_CLASS) {
89362c
+                    keyClass = attr.getLong();
89362c
+                } else if (attr.type == CKA_KEY_TYPE) {
89362c
+                    keyType = attr.getLong();
89362c
+                }
89362c
+                attrsMap.put(attr.type, attr);
89362c
+            }
89362c
+            BigInteger v = null;
89362c
+            if (keyClass == CKO_PRIVATE_KEY) {
89362c
+                if (keyType == CKK_RSA) {
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Importing an RSA private key...");
89362c
+                    }
89362c
+                    keyBytes = sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(
89362c
+                            KeyType.RSA,
89362c
+                            null,
89362c
+                            ((v = attrsMap.get(CKA_MODULUS).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_PUBLIC_EXPONENT).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_PRIVATE_EXPONENT).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_PRIME_1).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_PRIME_2).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_EXPONENT_1).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_EXPONENT_2).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_COEFFICIENT).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO
89362c
+                            ).getEncoded();
89362c
+                } else if (keyType == CKK_DSA) {
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Importing a DSA private key...");
89362c
+                    }
89362c
+                    keyBytes = new sun.security.provider.DSAPrivateKey(
89362c
+                            ((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_PRIME).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_SUBPRIME).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_BASE).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO
89362c
+                            ).getEncoded();
89362c
+                    if (token.config.getNssNetscapeDbWorkaround() &&
89362c
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
89362c
+                        attrsMap.put(CKA_NETSCAPE_DB,
89362c
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
89362c
+                    }
89362c
+                } else if (keyType == CKK_EC) {
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Importing an EC private key...");
89362c
+                    }
89362c
+                    if (sunECProvider == null) {
89362c
+                        sunECProviderLock.lock();
89362c
+                        try {
89362c
+                            if (sunECProvider == null) {
89362c
+                                sunECProvider = Security.getProvider("SunEC");
89362c
+                            }
89362c
+                        } finally {
89362c
+                            sunECProviderLock.unlock();
89362c
+                        }
89362c
+                    }
89362c
+                    keyBytes = ECUtil.generateECPrivateKey(
89362c
+                            ((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ECUtil.getECParameterSpec(sunECProvider,
89362c
+                                    attrsMap.get(CKA_EC_PARAMS).getByteArray()))
89362c
+                            .getEncoded();
89362c
+                    if (token.config.getNssNetscapeDbWorkaround() &&
89362c
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
89362c
+                        attrsMap.put(CKA_NETSCAPE_DB,
89362c
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
89362c
+                    }
89362c
+                } else if (keyType == CKK_DH) {
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Importing a Diffie-Hellman private key...");
89362c
+                    }
89362c
+                    if (DHKF == null) {
89362c
+                        DHKFLock.lock();
89362c
+                        try {
89362c
+                            if (DHKF == null) {
89362c
+                                DHKF = KeyFactory.getInstance(
89362c
+                                        "DH", P11Util.getSunJceProvider());
89362c
+                            }
89362c
+                        } finally {
89362c
+                            DHKFLock.unlock();
89362c
+                        }
89362c
+                    }
89362c
+                    DHPrivateKeySpec spec = new DHPrivateKeySpec
89362c
+                            (((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_PRIME).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO,
89362c
+                            ((v = attrsMap.get(CKA_BASE).getBigInteger()) != null)
89362c
+                                    ? v : BigInteger.ZERO);
89362c
+                    keyBytes = DHKF.generatePrivate(spec).getEncoded();
89362c
+                    if (token.config.getNssNetscapeDbWorkaround() &&
89362c
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
89362c
+                        attrsMap.put(CKA_NETSCAPE_DB,
89362c
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
89362c
+                    }
89362c
+                } else {
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Unrecognized private key type.");
89362c
+                    }
89362c
+                    throw new PKCS11Exception(CKR_GENERAL_ERROR);
89362c
+                }
89362c
+            } else if (keyClass == CKO_SECRET_KEY) {
89362c
+                if (debug != null) {
89362c
+                    debug.println("Importing a secret key...");
89362c
+                }
89362c
+                keyBytes = attrsMap.get(CKA_VALUE).getByteArray();
89362c
+            }
89362c
+            if (keyBytes == null || keyBytes.length == 0) {
89362c
+                if (debug != null) {
89362c
+                    debug.println("Private or secret key plain bytes could" +
89362c
+                            " not be obtained. Import failed.");
89362c
+                }
89362c
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
89362c
+            }
89362c
+            importerCipher.init(Cipher.ENCRYPT_MODE, importerKey,
89362c
+                    new IvParameterSpec((byte[])importerKeyMechanism.pParameter),
89362c
+                    null);
89362c
+            attributes = new CK_ATTRIBUTE[attrsMap.size()];
89362c
+            attrsMap.values().toArray(attributes);
89362c
+            encKeyBytes = importerCipher.doFinal(keyBytes);
89362c
+            attributes = token.getAttributes(TemplateManager.O_IMPORT,
89362c
+                    keyClass, keyType, attributes);
89362c
+            keyID = token.p11.C_UnwrapKey(hSession,
89362c
+                    importerKeyMechanism, importerKeyID, encKeyBytes, attributes);
89362c
+            if (debug != null) {
89362c
+                debug.println("Imported key ID: " + keyID);
89362c
+            }
89362c
+        } catch (Throwable t) {
89362c
+            throw new PKCS11Exception(CKR_GENERAL_ERROR);
89362c
+        } finally {
89362c
+            importerKey.releaseKeyID();
89362c
+        }
89362c
+        return Long.valueOf(keyID);
89362c
+    }
89362c
+
89362c
+    private static void createImporterKey(Token token) {
89362c
+        if (debug != null) {
89362c
+            debug.println("Generating Importer Key...");
89362c
+        }
89362c
+        byte[] iv = new byte[16];
89362c
+        JCAUtil.getSecureRandom().nextBytes(iv);
89362c
+        importerKeyMechanism = new CK_MECHANISM(CKM_AES_CBC_PAD, iv);
89362c
+        try {
89362c
+            CK_ATTRIBUTE[] attributes = token.getAttributes(TemplateManager.O_GENERATE,
89362c
+                            CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] {
89362c
+                                    new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
89362c
+                                    new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3)});
89362c
+            Session s = null;
89362c
+            try {
89362c
+                s = token.getObjSession();
89362c
+                long keyID = token.p11.C_GenerateKey(
89362c
+                        s.id(), new CK_MECHANISM(CKM_AES_KEY_GEN),
89362c
+                        attributes);
89362c
+                if (debug != null) {
89362c
+                    debug.println("Importer Key ID: " + keyID);
89362c
+                }
89362c
+                importerKey = (P11Key)P11Key.secretKey(s, keyID, "AES",
89362c
+                        256 >> 3, null);
89362c
+            } catch (PKCS11Exception e) {
89362c
+                // best effort
89362c
+            } finally {
89362c
+                token.releaseSession(s);
89362c
+            }
89362c
+            if (importerKey != null) {
89362c
+                importerCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
89362c
+            }
89362c
+        } catch (Throwable t) {
89362c
+            // best effort
89362c
+            importerKey = null;
89362c
+            importerCipher = null;
89362c
+            // importerKeyMechanism value is kept initialized to indicate that
89362c
+            // Importer Key creation has been tried and failed.
89362c
+        }
89362c
+    }
89362c
+}
89362c
diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java
89362c
index 099caac605f..977e5332bd1 100644
89362c
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java
89362c
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java
89362c
@@ -26,6 +26,9 @@
89362c
 package sun.security.pkcs11;
89362c
 
89362c
 import java.io.*;
89362c
+import java.lang.invoke.MethodHandle;
89362c
+import java.lang.invoke.MethodHandles;
89362c
+import java.lang.invoke.MethodType;
89362c
 import java.util.*;
89362c
 
89362c
 import java.security.*;
89362c
@@ -43,6 +46,8 @@ import javax.security.auth.callback.PasswordCallback;
89362c
 import com.sun.crypto.provider.ChaCha20Poly1305Parameters;
89362c
 
89362c
 import jdk.internal.misc.InnocuousThread;
89362c
+import jdk.internal.misc.SharedSecrets;
89362c
+
89362c
 import sun.security.util.Debug;
89362c
 import sun.security.util.ResourcesMgr;
89362c
 import static sun.security.util.SecurityConstants.PROVIDER_VER;
89362c
@@ -60,6 +65,29 @@ import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
89362c
  */
89362c
 public final class SunPKCS11 extends AuthProvider {
89362c
 
89362c
+    private static final boolean systemFipsEnabled = SharedSecrets
89362c
+            .getJavaSecuritySystemConfiguratorAccess().isSystemFipsEnabled();
89362c
+
89362c
+    private static final boolean plainKeySupportEnabled = SharedSecrets
89362c
+            .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled();
89362c
+
89362c
+    private static final MethodHandle fipsImportKey;
89362c
+    static {
89362c
+        MethodHandle fipsImportKeyTmp = null;
89362c
+        if (plainKeySupportEnabled) {
89362c
+            try {
89362c
+                fipsImportKeyTmp = MethodHandles.lookup().findStatic(
89362c
+                        FIPSKeyImporter.class, "importKey",
89362c
+                        MethodType.methodType(Long.class, SunPKCS11.class,
89362c
+                        long.class, CK_ATTRIBUTE[].class));
89362c
+            } catch (Throwable t) {
89362c
+                throw new SecurityException("FIPS key importer initialization" +
89362c
+                        " failed", t);
89362c
+            }
89362c
+        }
89362c
+        fipsImportKey = fipsImportKeyTmp;
89362c
+    }
89362c
+
89362c
     private static final long serialVersionUID = -1354835039035306505L;
89362c
 
89362c
     static final Debug debug = Debug.getInstance("sunpkcs11");
89362c
@@ -317,10 +345,15 @@ public final class SunPKCS11 extends AuthProvider {
89362c
             // request multithreaded access first
89362c
             initArgs.flags = CKF_OS_LOCKING_OK;
89362c
             PKCS11 tmpPKCS11;
89362c
+            MethodHandle fipsKeyImporter = null;
89362c
+            if (plainKeySupportEnabled) {
89362c
+                fipsKeyImporter = MethodHandles.insertArguments(
89362c
+                        fipsImportKey, 0, this);
89362c
+            }
89362c
             try {
89362c
                 tmpPKCS11 = PKCS11.getInstance(
89362c
                     library, functionList, initArgs,
89362c
-                    config.getOmitInitialize());
89362c
+                    config.getOmitInitialize(), fipsKeyImporter);
89362c
             } catch (PKCS11Exception e) {
89362c
                 if (debug != null) {
89362c
                     debug.println("Multi-threaded initialization failed: " + e);
89362c
@@ -336,7 +369,7 @@ public final class SunPKCS11 extends AuthProvider {
89362c
                     initArgs.flags = 0;
89362c
                 }
89362c
                 tmpPKCS11 = PKCS11.getInstance(library,
89362c
-                    functionList, initArgs, config.getOmitInitialize());
89362c
+                    functionList, initArgs, config.getOmitInitialize(), fipsKeyImporter);
89362c
             }
89362c
             p11 = tmpPKCS11;
89362c
 
89362c
@@ -376,6 +409,24 @@ public final class SunPKCS11 extends AuthProvider {
89362c
             if (nssModule != null) {
89362c
                 nssModule.setProvider(this);
89362c
             }
89362c
+            if (systemFipsEnabled) {
89362c
+                // The NSS Software Token in FIPS 140-2 mode requires a user
89362c
+                // login for most operations. See sftk_fipsCheck. The NSS DB
89362c
+                // (/etc/pki/nssdb) PIN is empty.
89362c
+                Session session = null;
89362c
+                try {
89362c
+                    session = token.getOpSession();
89362c
+                    p11.C_Login(session.id(), CKU_USER, new char[] {});
89362c
+                } catch (PKCS11Exception p11e) {
89362c
+                    if (debug != null) {
89362c
+                        debug.println("Error during token login: " +
89362c
+                                p11e.getMessage());
89362c
+                    }
89362c
+                    throw p11e;
89362c
+                } finally {
89362c
+                    token.releaseSession(session);
89362c
+                }
89362c
+            }
89362c
         } catch (Exception e) {
89362c
             if (config.getHandleStartupErrors() == Config.ERR_IGNORE_ALL) {
89362c
                 throw new UnsupportedOperationException
89362c
diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
89362c
index 04a369f453c..f033fe47593 100644
89362c
--- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
89362c
+++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
89362c
@@ -49,6 +49,7 @@ package sun.security.pkcs11.wrapper;
89362c
 
89362c
 import java.io.File;
89362c
 import java.io.IOException;
89362c
+import java.lang.invoke.MethodHandle;
89362c
 import java.util.*;
89362c
 
89362c
 import java.security.AccessController;
89362c
@@ -148,18 +149,41 @@ public class PKCS11 {
89362c
         this.pkcs11ModulePath = pkcs11ModulePath;
89362c
     }
89362c
 
89362c
+    /*
89362c
+     * Compatibility wrapper to allow this method to work as before
89362c
+     * when FIPS mode support is not active.
89362c
+     */
89362c
+    public static synchronized PKCS11 getInstance(String pkcs11ModulePath,
89362c
+           String functionList, CK_C_INITIALIZE_ARGS pInitArgs,
89362c
+           boolean omitInitialize) throws IOException, PKCS11Exception {
89362c
+        return getInstance(pkcs11ModulePath, functionList,
89362c
+                           pInitArgs, omitInitialize, null);
89362c
+    }
89362c
+
89362c
     public static synchronized PKCS11 getInstance(String pkcs11ModulePath,
89362c
             String functionList, CK_C_INITIALIZE_ARGS pInitArgs,
89362c
-            boolean omitInitialize) throws IOException, PKCS11Exception {
89362c
+            boolean omitInitialize, MethodHandle fipsKeyImporter)
89362c
+                    throws IOException, PKCS11Exception {
89362c
         // we may only call C_Initialize once per native .so/.dll
89362c
         // so keep a cache using the (non-canonicalized!) path
89362c
         PKCS11 pkcs11 = moduleMap.get(pkcs11ModulePath);
89362c
         if (pkcs11 == null) {
89362c
+            boolean nssFipsMode = fipsKeyImporter != null;
89362c
             if ((pInitArgs != null)
89362c
                     && ((pInitArgs.flags & CKF_OS_LOCKING_OK) != 0)) {
89362c
-                pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
89362c
+                if (nssFipsMode) {
89362c
+                    pkcs11 = new FIPSPKCS11(pkcs11ModulePath, functionList,
89362c
+                            fipsKeyImporter);
89362c
+                } else {
89362c
+                    pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
89362c
+                }
89362c
             } else {
89362c
-                pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
89362c
+                if (nssFipsMode) {
89362c
+                    pkcs11 = new SynchronizedFIPSPKCS11(pkcs11ModulePath,
89362c
+                            functionList, fipsKeyImporter);
89362c
+                } else {
89362c
+                    pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
89362c
+                }
89362c
             }
89362c
             if (omitInitialize == false) {
89362c
                 try {
89362c
@@ -1909,4 +1933,69 @@ static class SynchronizedPKCS11 extends PKCS11 {
89362c
         super.C_GenerateRandom(hSession, randomData);
89362c
     }
89362c
 }
89362c
+
89362c
+// PKCS11 subclass that allows using plain private or secret keys in
89362c
+// FIPS-configured NSS Software Tokens. Only used when System FIPS
89362c
+// is enabled.
89362c
+static class FIPSPKCS11 extends PKCS11 {
89362c
+    private MethodHandle fipsKeyImporter;
89362c
+    FIPSPKCS11(String pkcs11ModulePath, String functionListName,
89362c
+            MethodHandle fipsKeyImporter) throws IOException {
89362c
+        super(pkcs11ModulePath, functionListName);
89362c
+        this.fipsKeyImporter = fipsKeyImporter;
89362c
+    }
89362c
+
89362c
+    public synchronized long C_CreateObject(long hSession,
89362c
+            CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
89362c
+        // Creating sensitive key objects from plain key material in a
89362c
+        // FIPS-configured NSS Software Token is not allowed. We apply
89362c
+        // a key-unwrapping scheme to achieve so.
89362c
+        if (FIPSPKCS11Helper.isSensitiveObject(pTemplate)) {
89362c
+            try {
89362c
+                return ((Long)fipsKeyImporter.invoke(hSession, pTemplate))
89362c
+                        .longValue();
89362c
+            } catch (Throwable t) {
89362c
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
89362c
+            }
89362c
+        }
89362c
+        return super.C_CreateObject(hSession, pTemplate);
89362c
+    }
89362c
+}
89362c
+
89362c
+// FIPSPKCS11 synchronized counterpart.
89362c
+static class SynchronizedFIPSPKCS11 extends SynchronizedPKCS11 {
89362c
+    private MethodHandle fipsKeyImporter;
89362c
+    SynchronizedFIPSPKCS11(String pkcs11ModulePath, String functionListName,
89362c
+            MethodHandle fipsKeyImporter) throws IOException {
89362c
+        super(pkcs11ModulePath, functionListName);
89362c
+        this.fipsKeyImporter = fipsKeyImporter;
89362c
+    }
89362c
+
89362c
+    public synchronized long C_CreateObject(long hSession,
89362c
+            CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
89362c
+        // See FIPSPKCS11::C_CreateObject.
89362c
+        if (FIPSPKCS11Helper.isSensitiveObject(pTemplate)) {
89362c
+            try {
89362c
+                return ((Long)fipsKeyImporter.invoke(hSession, pTemplate))
89362c
+                        .longValue();
89362c
+            } catch (Throwable t) {
89362c
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
89362c
+            }
89362c
+        }
89362c
+        return super.C_CreateObject(hSession, pTemplate);
89362c
+    }
89362c
+}
89362c
+
89362c
+private static class FIPSPKCS11Helper {
89362c
+    static boolean isSensitiveObject(CK_ATTRIBUTE[] pTemplate) {
89362c
+        for (CK_ATTRIBUTE attr : pTemplate) {
89362c
+            if (attr.type == CKA_CLASS &&
89362c
+                    (attr.getLong() == CKO_PRIVATE_KEY ||
89362c
+                    attr.getLong() == CKO_SECRET_KEY)) {
89362c
+                return true;
89362c
+            }
89362c
+        }
89362c
+        return false;
89362c
+    }
89362c
+}
89362c
 }