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

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

Additional default values of security properties are read from a

c69722
+ * system-specific location, if available.

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