Blame SOURCES/fips-11u-b34fb09a5c.patch

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

Additional default values of security properties are read from a

6cb6a7
+ * system-specific location, if available.

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