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

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

Additional default values of security properties are read from a

9e62d6
+ * system-specific location, if available.

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