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

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

Additional default values of security properties are read from a

b9c0b6
+ * system-specific location, if available.

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