65e86d
diff --git a/common/autoconf/configure.ac b/common/autoconf/configure.ac
65e86d
index 151e5a109f8..a8761b500e0 100644
65e86d
--- a/common/autoconf/configure.ac
65e86d
+++ b/common/autoconf/configure.ac
65e86d
@@ -212,6 +212,7 @@ LIB_SETUP_FREETYPE
65e86d
 LIB_SETUP_ALSA
65e86d
 LIB_SETUP_FONTCONFIG
65e86d
 LIB_SETUP_MISC_LIBS
65e86d
+LIB_SETUP_SYSCONF_LIBS
65e86d
 LIB_SETUP_STATIC_LINK_LIBSTDCPP
65e86d
 LIB_SETUP_ON_WINDOWS
65e86d
 
65e86d
diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh
65e86d
index 71fabf4dbb3..17f4f50673d 100644
65e86d
--- a/common/autoconf/generated-configure.sh
65e86d
+++ b/common/autoconf/generated-configure.sh
65e86d
@@ -651,6 +651,9 @@ LLVM_CONFIG
65e86d
 LIBFFI_LIBS
65e86d
 LIBFFI_CFLAGS
65e86d
 STATIC_CXX_SETTING
65e86d
+USE_SYSCONF_NSS
65e86d
+NSS_LIBS
65e86d
+NSS_CFLAGS
65e86d
 LIBDL
65e86d
 LIBM
65e86d
 LIBZIP_CAN_USE_MMAP
65e86d
@@ -1111,6 +1114,7 @@ with_fontconfig
65e86d
 with_fontconfig_include
65e86d
 with_giflib
65e86d
 with_zlib
65e86d
+enable_sysconf_nss
65e86d
 with_stdc__lib
65e86d
 with_msvcr_dll
65e86d
 with_msvcp_dll
65e86d
@@ -1218,6 +1222,8 @@ FREETYPE_CFLAGS
65e86d
 FREETYPE_LIBS
65e86d
 ALSA_CFLAGS
65e86d
 ALSA_LIBS
65e86d
+NSS_CFLAGS
65e86d
+NSS_LIBS
65e86d
 LIBFFI_CFLAGS
65e86d
 LIBFFI_LIBS
65e86d
 CCACHE'
65e86d
@@ -1871,6 +1877,8 @@ Optional Features:
65e86d
                           disable bundling of the freetype library with the
65e86d
                           build result [enabled on Windows or when using
65e86d
                           --with-freetype, disabled otherwise]
65e86d
+  --enable-sysconf-nss    build the System Configurator (libsysconf) using the
65e86d
+                          system NSS library if available [disabled]
65e86d
   --enable-sjavac         use sjavac to do fast incremental compiles
65e86d
                           [disabled]
65e86d
   --disable-precompiled-headers
65e86d
@@ -2115,6 +2123,8 @@ Some influential environment variables:
65e86d
               linker flags for FREETYPE, overriding pkg-config
65e86d
   ALSA_CFLAGS C compiler flags for ALSA, overriding pkg-config
65e86d
   ALSA_LIBS   linker flags for ALSA, overriding pkg-config
65e86d
+  NSS_CFLAGS  C compiler flags for NSS, overriding pkg-config
65e86d
+  NSS_LIBS    linker flags for NSS, overriding pkg-config
65e86d
   LIBFFI_CFLAGS
65e86d
               C compiler flags for LIBFFI, overriding pkg-config
65e86d
   LIBFFI_LIBS linker flags for LIBFFI, overriding pkg-config
65e86d
@@ -2879,6 +2889,52 @@ $as_echo "$ac_res" >&6; }
65e86d
   eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
65e86d
 
65e86d
 } # ac_fn_c_check_header_compile
65e86d
+
65e86d
+# ac_fn_c_try_link LINENO
65e86d
+# -----------------------
65e86d
+# Try to link conftest.$ac_ext, and return whether this succeeded.
65e86d
+ac_fn_c_try_link ()
65e86d
+{
65e86d
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
65e86d
+  rm -f conftest.$ac_objext conftest$ac_exeext
65e86d
+  if { { ac_try="$ac_link"
65e86d
+case "(($ac_try" in
65e86d
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
65e86d
+  *) ac_try_echo=$ac_try;;
65e86d
+esac
65e86d
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
65e86d
+$as_echo "$ac_try_echo"; } >&5
65e86d
+  (eval "$ac_link") 2>conftest.err
65e86d
+  ac_status=$?
65e86d
+  if test -s conftest.err; then
65e86d
+    grep -v '^ *+' conftest.err >conftest.er1
65e86d
+    cat conftest.er1 >&5
65e86d
+    mv -f conftest.er1 conftest.err
65e86d
+  fi
65e86d
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
65e86d
+  test $ac_status = 0; } && {
65e86d
+	 test -z "$ac_c_werror_flag" ||
65e86d
+	 test ! -s conftest.err
65e86d
+       } && test -s conftest$ac_exeext && {
65e86d
+	 test "$cross_compiling" = yes ||
65e86d
+	 test -x conftest$ac_exeext
65e86d
+       }; then :
65e86d
+  ac_retval=0
65e86d
+else
65e86d
+  $as_echo "$as_me: failed program was:" >&5
65e86d
+sed 's/^/| /' conftest.$ac_ext >&5
65e86d
+
65e86d
+	ac_retval=1
65e86d
+fi
65e86d
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
65e86d
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
65e86d
+  # interfere with the next link command; also delete a directory that is
65e86d
+  # left behind by Apple's compiler.  We do this before executing the actions.
65e86d
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
65e86d
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
65e86d
+  as_fn_set_status $ac_retval
65e86d
+
65e86d
+} # ac_fn_c_try_link
65e86d
 cat >config.log <<_ACEOF
65e86d
 This file contains any messages produced by compilers while
65e86d
 running configure, to aid debugging if configure makes a mistake.
65e86d
@@ -4049,6 +4105,11 @@ fi
65e86d
 
65e86d
 
65e86d
 
65e86d
+################################################################################
65e86d
+# Setup system configuration libraries
65e86d
+################################################################################
65e86d
+
65e86d
+
65e86d
 #
65e86d
 # Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
65e86d
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
65e86d
@@ -49304,6 +49365,157 @@ fi
65e86d
   LIBS="$save_LIBS"
65e86d
 
65e86d
 
65e86d
+  ###############################################################################
65e86d
+  #
65e86d
+  # Check for the NSS library
65e86d
+  #
65e86d
+
65e86d
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to use the system NSS library with the System Configurator (libsysconf)" >&5
65e86d
+$as_echo_n "checking whether to use the system NSS library with the System Configurator (libsysconf)... " >&6; }
65e86d
+
65e86d
+  # default is not available
65e86d
+  DEFAULT_SYSCONF_NSS=no
65e86d
+
65e86d
+  # Check whether --enable-sysconf-nss was given.
65e86d
+if test "${enable_sysconf_nss+set}" = set; then :
65e86d
+  enableval=$enable_sysconf_nss;
65e86d
+    case "${enableval}" in
65e86d
+      yes)
65e86d
+        sysconf_nss=yes
65e86d
+        ;;
65e86d
+      *)
65e86d
+        sysconf_nss=no
65e86d
+        ;;
65e86d
+    esac
65e86d
+
65e86d
+else
65e86d
+
65e86d
+    sysconf_nss=${DEFAULT_SYSCONF_NSS}
65e86d
+
65e86d
+fi
65e86d
+
65e86d
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $sysconf_nss" >&5
65e86d
+$as_echo "$sysconf_nss" >&6; }
65e86d
+
65e86d
+  USE_SYSCONF_NSS=false
65e86d
+  if test "x${sysconf_nss}" = "xyes"; then
65e86d
+
65e86d
+pkg_failed=no
65e86d
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for NSS" >&5
65e86d
+$as_echo_n "checking for NSS... " >&6; }
65e86d
+
65e86d
+if test -n "$NSS_CFLAGS"; then
65e86d
+    pkg_cv_NSS_CFLAGS="$NSS_CFLAGS"
65e86d
+ elif test -n "$PKG_CONFIG"; then
65e86d
+    if test -n "$PKG_CONFIG" && \
65e86d
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"nss >= 3.53\""; } >&5
65e86d
+  ($PKG_CONFIG --exists --print-errors "nss >= 3.53") 2>&5
65e86d
+  ac_status=$?
65e86d
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
65e86d
+  test $ac_status = 0; }; then
65e86d
+  pkg_cv_NSS_CFLAGS=`$PKG_CONFIG --cflags "nss >= 3.53" 2>/dev/null`
65e86d
+else
65e86d
+  pkg_failed=yes
65e86d
+fi
65e86d
+ else
65e86d
+    pkg_failed=untried
65e86d
+fi
65e86d
+if test -n "$NSS_LIBS"; then
65e86d
+    pkg_cv_NSS_LIBS="$NSS_LIBS"
65e86d
+ elif test -n "$PKG_CONFIG"; then
65e86d
+    if test -n "$PKG_CONFIG" && \
65e86d
+    { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"nss >= 3.53\""; } >&5
65e86d
+  ($PKG_CONFIG --exists --print-errors "nss >= 3.53") 2>&5
65e86d
+  ac_status=$?
65e86d
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
65e86d
+  test $ac_status = 0; }; then
65e86d
+  pkg_cv_NSS_LIBS=`$PKG_CONFIG --libs "nss >= 3.53" 2>/dev/null`
65e86d
+else
65e86d
+  pkg_failed=yes
65e86d
+fi
65e86d
+ else
65e86d
+    pkg_failed=untried
65e86d
+fi
65e86d
+
65e86d
+
65e86d
+
65e86d
+if test $pkg_failed = yes; then
65e86d
+
65e86d
+if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
65e86d
+        _pkg_short_errors_supported=yes
65e86d
+else
65e86d
+        _pkg_short_errors_supported=no
65e86d
+fi
65e86d
+        if test $_pkg_short_errors_supported = yes; then
65e86d
+	        NSS_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors "nss >= 3.53" 2>&1`
65e86d
+        else
65e86d
+	        NSS_PKG_ERRORS=`$PKG_CONFIG --print-errors "nss >= 3.53" 2>&1`
65e86d
+        fi
65e86d
+	# Put the nasty error message in config.log where it belongs
65e86d
+	echo "$NSS_PKG_ERRORS" >&5
65e86d
+
65e86d
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
65e86d
+$as_echo "no" >&6; }
65e86d
+                NSS_FOUND=no
65e86d
+elif test $pkg_failed = untried; then
65e86d
+	NSS_FOUND=no
65e86d
+else
65e86d
+	NSS_CFLAGS=$pkg_cv_NSS_CFLAGS
65e86d
+	NSS_LIBS=$pkg_cv_NSS_LIBS
65e86d
+        { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
65e86d
+$as_echo "yes" >&6; }
65e86d
+	NSS_FOUND=yes
65e86d
+fi
65e86d
+      if test "x${NSS_FOUND}" = "xyes"; then
65e86d
+         { $as_echo "$as_me:${as_lineno-$LINENO}: checking for system FIPS support in NSS" >&5
65e86d
+$as_echo_n "checking for system FIPS support in NSS... " >&6; }
65e86d
+         saved_libs="${LIBS}"
65e86d
+         saved_cflags="${CFLAGS}"
65e86d
+         CFLAGS="${CFLAGS} ${NSS_CFLAGS}"
65e86d
+         LIBS="${LIBS} ${NSS_LIBS}"
65e86d
+         ac_ext=c
65e86d
+ac_cpp='$CPP $CPPFLAGS'
65e86d
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
65e86d
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
65e86d
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
65e86d
+
65e86d
+         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
65e86d
+/* end confdefs.h.  */
65e86d
+#include <nss3/pk11pub.h>
65e86d
+int
65e86d
+main ()
65e86d
+{
65e86d
+SECMOD_GetSystemFIPSEnabled()
65e86d
+  ;
65e86d
+  return 0;
65e86d
+}
65e86d
+_ACEOF
65e86d
+if ac_fn_c_try_link "$LINENO"; then :
65e86d
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
65e86d
+$as_echo "yes" >&6; }
65e86d
+else
65e86d
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
65e86d
+$as_echo "no" >&6; }
65e86d
+                        as_fn_error $? "System NSS FIPS detection unavailable" "$LINENO" 5
65e86d
+fi
65e86d
+rm -f core conftest.err conftest.$ac_objext \
65e86d
+    conftest$ac_exeext conftest.$ac_ext
65e86d
+         ac_ext=cpp
65e86d
+ac_cpp='$CXXCPP $CPPFLAGS'
65e86d
+ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
65e86d
+ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
65e86d
+ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
65e86d
+
65e86d
+         CFLAGS="${saved_cflags}"
65e86d
+         LIBS="${saved_libs}"
65e86d
+         USE_SYSCONF_NSS=true
65e86d
+      else
65e86d
+                           as_fn_error $? "--enable-sysconf-nss specified, but NSS 3.53 or above not found." "$LINENO" 5
65e86d
+      fi
65e86d
+  fi
65e86d
+
65e86d
+
65e86d
+
65e86d
   ###############################################################################
65e86d
   #
65e86d
   # statically link libstdc++ before C++ ABI is stablized on Linux unless
65e86d
diff --git a/common/autoconf/libraries.m4 b/common/autoconf/libraries.m4
65e86d
index 6efae578ea9..0080846255b 100644
65e86d
--- a/common/autoconf/libraries.m4
65e86d
+++ b/common/autoconf/libraries.m4
65e86d
@@ -1067,3 +1067,63 @@ AC_DEFUN_ONCE([LIB_SETUP_ON_WINDOWS],
65e86d
     BASIC_DEPRECATED_ARG_WITH([dxsdk-include])
65e86d
   fi
65e86d
 ])
65e86d
+
65e86d
+################################################################################
65e86d
+# Setup system configuration libraries
65e86d
+################################################################################
65e86d
+AC_DEFUN_ONCE([LIB_SETUP_SYSCONF_LIBS],
65e86d
+[
65e86d
+  ###############################################################################
65e86d
+  #
65e86d
+  # Check for the NSS library
65e86d
+  #
65e86d
+
65e86d
+  AC_MSG_CHECKING([whether to use the system NSS library with the System Configurator (libsysconf)])
65e86d
+
65e86d
+  # default is not available
65e86d
+  DEFAULT_SYSCONF_NSS=no
65e86d
+
65e86d
+  AC_ARG_ENABLE([sysconf-nss], [AS_HELP_STRING([--enable-sysconf-nss],
65e86d
+     [build the System Configurator (libsysconf) using the system NSS library if available @<:@disabled@:>@])],
65e86d
+  [
65e86d
+    case "${enableval}" in
65e86d
+      yes)
65e86d
+        sysconf_nss=yes
65e86d
+        ;;
65e86d
+      *)
65e86d
+        sysconf_nss=no
65e86d
+        ;;
65e86d
+    esac
65e86d
+  ],
65e86d
+  [
65e86d
+    sysconf_nss=${DEFAULT_SYSCONF_NSS}
65e86d
+  ])
65e86d
+  AC_MSG_RESULT([$sysconf_nss])
65e86d
+
65e86d
+  USE_SYSCONF_NSS=false
65e86d
+  if test "x${sysconf_nss}" = "xyes"; then
65e86d
+      PKG_CHECK_MODULES(NSS, nss >= 3.53, [NSS_FOUND=yes], [NSS_FOUND=no])
65e86d
+      if test "x${NSS_FOUND}" = "xyes"; then
65e86d
+         AC_MSG_CHECKING([for system FIPS support in NSS])
65e86d
+         saved_libs="${LIBS}"
65e86d
+         saved_cflags="${CFLAGS}"
65e86d
+         CFLAGS="${CFLAGS} ${NSS_CFLAGS}"
65e86d
+         LIBS="${LIBS} ${NSS_LIBS}"
65e86d
+         AC_LANG_PUSH([C])
65e86d
+         AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <nss3/pk11pub.h>]],
65e86d
+                                         [[SECMOD_GetSystemFIPSEnabled()]])],
65e86d
+                        [AC_MSG_RESULT([yes])],
65e86d
+                        [AC_MSG_RESULT([no])
65e86d
+                        AC_MSG_ERROR([System NSS FIPS detection unavailable])])
65e86d
+         AC_LANG_POP([C])
65e86d
+         CFLAGS="${saved_cflags}"
65e86d
+         LIBS="${saved_libs}"
65e86d
+         USE_SYSCONF_NSS=true
65e86d
+      else
65e86d
+         dnl NSS 3.53 is the one that introduces the SECMOD_GetSystemFIPSEnabled API
65e86d
+         dnl in nss3/pk11pub.h.
65e86d
+         AC_MSG_ERROR([--enable-sysconf-nss specified, but NSS 3.53 or above not found.])
65e86d
+      fi
65e86d
+  fi
65e86d
+  AC_SUBST(USE_SYSCONF_NSS)
65e86d
+])
65e86d
diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in
65e86d
index 506cf617087..7241593b1a4 100644
65e86d
--- a/common/autoconf/spec.gmk.in
65e86d
+++ b/common/autoconf/spec.gmk.in
65e86d
@@ -312,6 +312,10 @@ CUPS_CFLAGS:=@CUPS_CFLAGS@
65e86d
 ALSA_LIBS:=@ALSA_LIBS@
65e86d
 ALSA_CFLAGS:=@ALSA_CFLAGS@
65e86d
 
65e86d
+USE_SYSCONF_NSS:=@USE_SYSCONF_NSS@
65e86d
+NSS_LIBS:=@NSS_LIBS@
65e86d
+NSS_CFLAGS:=@NSS_CFLAGS@
65e86d
+
65e86d
 PACKAGE_PATH=@PACKAGE_PATH@
65e86d
 
65e86d
 # Source file for cacerts
65e86d
diff --git a/common/bin/compare_exceptions.sh.incl b/common/bin/compare_exceptions.sh.incl
65e86d
index 3b79a526f56..d2a0e39b206 100644
65e86d
--- a/common/bin/compare_exceptions.sh.incl
65e86d
+++ b/common/bin/compare_exceptions.sh.incl
65e86d
@@ -280,6 +280,7 @@ ACCEPTED_SMALL_SIZE_DIFF="
65e86d
 ./jre/lib/i386/libsplashscreen.so
65e86d
 ./jre/lib/i386/libsunec.so
65e86d
 ./jre/lib/i386/libsunwjdga.so
65e86d
+./jre/lib/i386/libsystemconf.so
65e86d
 ./jre/lib/i386/libt2k.so
65e86d
 ./jre/lib/i386/libunpack.so
65e86d
 ./jre/lib/i386/libverify.so
65e86d
@@ -433,6 +434,7 @@ ACCEPTED_SMALL_SIZE_DIFF="
65e86d
 ./jre/lib/amd64/libsplashscreen.so
65e86d
 ./jre/lib/amd64/libsunec.so
65e86d
 ./jre/lib/amd64/libsunwjdga.so
65e86d
+//jre/lib/amd64/libsystemconf.so
65e86d
 ./jre/lib/amd64/libt2k.so
65e86d
 ./jre/lib/amd64/libunpack.so
65e86d
 ./jre/lib/amd64/libverify.so
65e86d
@@ -587,6 +589,7 @@ ACCEPTED_SMALL_SIZE_DIFF="
65e86d
 ./jre/lib/sparc/libsplashscreen.so
65e86d
 ./jre/lib/sparc/libsunec.so
65e86d
 ./jre/lib/sparc/libsunwjdga.so
65e86d
+./jre/lib/sparc/libsystemconf.so
65e86d
 ./jre/lib/sparc/libt2k.so
65e86d
 ./jre/lib/sparc/libunpack.so
65e86d
 ./jre/lib/sparc/libverify.so
65e86d
@@ -741,6 +744,7 @@ ACCEPTED_SMALL_SIZE_DIFF="
65e86d
 ./jre/lib/sparcv9/libsplashscreen.so
65e86d
 ./jre/lib/sparcv9/libsunec.so
65e86d
 ./jre/lib/sparcv9/libsunwjdga.so
65e86d
+./jre/lib/sparcv9/libsystemconf.so
65e86d
 ./jre/lib/sparcv9/libt2k.so
65e86d
 ./jre/lib/sparcv9/libunpack.so
65e86d
 ./jre/lib/sparcv9/libverify.so
65e86d
diff --git a/common/nb_native/nbproject/configurations.xml b/common/nb_native/nbproject/configurations.xml
65e86d
index d2beed0b93a..3b6aef98d9a 100644
65e86d
--- a/common/nb_native/nbproject/configurations.xml
65e86d
+++ b/common/nb_native/nbproject/configurations.xml
65e86d
@@ -53,6 +53,9 @@
65e86d
                   <in>jvmtiEnterTrace.cpp</in>
65e86d
                 </df>
65e86d
               </df>
65e86d
+              <df name="libsystemconf">
65e86d
+                <in>systemconf.c</in>
65e86d
+              </df>
65e86d
             </df>
65e86d
           </df>
65e86d
           <df name="jdk">
65e86d
@@ -12772,6 +12775,11 @@
65e86d
             tool="0"
65e86d
             flavor2="0">
65e86d
       </item>
65e86d
+      
65e86d
+            ex="false"
65e86d
+            tool="0"
65e86d
+            flavor2="0">
65e86d
+      </item>
65e86d
       
65e86d
             ex="false"
65e86d
             tool="0"
65e86d
diff --git a/jdk/make/lib/SecurityLibraries.gmk b/jdk/make/lib/SecurityLibraries.gmk
65e86d
index b0b85d80448..47a41d7518d 100644
65e86d
--- a/jdk/make/lib/SecurityLibraries.gmk
65e86d
+++ b/jdk/make/lib/SecurityLibraries.gmk
65e86d
@@ -289,3 +289,34 @@ ifeq ($(OPENJDK_TARGET_OS), solaris)
65e86d
 
65e86d
   endif
65e86d
 endif
65e86d
+
65e86d
+################################################################################
65e86d
+# Create the systemconf library
65e86d
+
65e86d
+LIBSYSTEMCONF_CFLAGS :=
65e86d
+LIBSYSTEMCONF_CXXFLAGS :=
65e86d
+
65e86d
+ifeq ($(USE_SYSCONF_NSS), true)
65e86d
+  LIBSYSTEMCONF_CFLAGS += $(NSS_CFLAGS) -DSYSCONF_NSS
65e86d
+  LIBSYSTEMCONF_CXXFLAGS += $(NSS_CFLAGS) -DSYSCONF_NSS
65e86d
+endif
65e86d
+
65e86d
+ifeq ($(OPENJDK_BUILD_OS), linux)
65e86d
+  $(eval $(call SetupNativeCompilation,BUILD_LIBSYSTEMCONF, \
65e86d
+      LIBRARY := systemconf, \
65e86d
+      OUTPUT_DIR := $(INSTALL_LIBRARIES_HERE), \
65e86d
+      SRC := $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/native/java/security, \
65e86d
+      LANG := C, \
65e86d
+      OPTIMIZATION := LOW, \
65e86d
+      CFLAGS := $(CFLAGS_JDKLIB) $(LIBSYSTEMCONF_CFLAGS), \
65e86d
+      CXXFLAGS := $(CXXFLAGS_JDKLIB) $(LIBSYSTEMCONF_CXXFLAGS), \
65e86d
+      MAPFILE := $(JDK_TOPDIR)/make/mapfiles/libsystemconf/mapfile-vers, \
65e86d
+      LDFLAGS := $(LDFLAGS_JDKLIB) \
65e86d
+          $(call SET_SHARED_LIBRARY_ORIGIN), \
65e86d
+      LDFLAGS_SUFFIX := $(LIBDL) $(NSS_LIBS), \
65e86d
+      OBJECT_DIR := $(JDK_OUTPUTDIR)/objs/libsystemconf, \
65e86d
+      DEBUG_SYMBOLS := $(DEBUG_ALL_BINARIES)))
65e86d
+
65e86d
+  BUILD_LIBRARIES += $(BUILD_LIBSYSTEMCONF)
65e86d
+endif
65e86d
+
65e86d
diff --git a/jdk/make/mapfiles/libsystemconf/mapfile-vers b/jdk/make/mapfiles/libsystemconf/mapfile-vers
65e86d
new file mode 100644
65e86d
index 00000000000..a65ceb3b78c
65e86d
--- /dev/null
65e86d
+++ b/jdk/make/mapfiles/libsystemconf/mapfile-vers
65e86d
@@ -0,0 +1,35 @@
65e86d
+#
65e86d
+# Copyright (c) 2021, Red Hat, Inc.
65e86d
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
65e86d
+#
65e86d
+# This code is free software; you can redistribute it and/or modify it
65e86d
+# under the terms of the GNU General Public License version 2 only, as
65e86d
+# published by the Free Software Foundation.  Oracle designates this
65e86d
+# particular file as subject to the "Classpath" exception as provided
65e86d
+# by Oracle in the LICENSE file that accompanied this code.
65e86d
+#
65e86d
+# This code is distributed in the hope that it will be useful, but WITHOUT
65e86d
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
65e86d
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
65e86d
+# version 2 for more details (a copy is included in the LICENSE file that
65e86d
+# accompanied this code).
65e86d
+#
65e86d
+# You should have received a copy of the GNU General Public License version
65e86d
+# 2 along with this work; if not, write to the Free Software Foundation,
65e86d
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
65e86d
+#
65e86d
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
65e86d
+# or visit www.oracle.com if you need additional information or have any
65e86d
+# questions.
65e86d
+#
65e86d
+
65e86d
+# Define public interface.
65e86d
+
65e86d
+SUNWprivate_1.1 {
65e86d
+	global:
65e86d
+		DEF_JNI_OnLoad;
65e86d
+		DEF_JNI_OnUnLoad;
65e86d
+		Java_java_security_SystemConfigurator_getSystemFIPSEnabled;
65e86d
+	local:
65e86d
+		*;
65e86d
+};
65e86d
diff --git a/jdk/src/share/classes/java/security/Security.java b/jdk/src/share/classes/java/security/Security.java
65e86d
index 0db09da7061..813b907db3e 100644
65e86d
--- a/jdk/src/share/classes/java/security/Security.java
65e86d
+++ b/jdk/src/share/classes/java/security/Security.java
65e86d
@@ -30,6 +30,8 @@ import java.util.*;
65e86d
 import java.util.concurrent.ConcurrentHashMap;
65e86d
 import java.io.*;
65e86d
 import java.net.URL;
65e86d
+import sun.misc.SharedSecrets;
65e86d
+import sun.misc.JavaSecuritySystemConfiguratorAccess;
65e86d
 import sun.security.util.Debug;
65e86d
 import sun.security.util.PropertyExpander;
65e86d
 
65e86d
@@ -43,11 +45,19 @@ import sun.security.jca.*;
65e86d
  * implementation-specific location, which is typically the properties file
65e86d
  * {@code lib/security/java.security} in the Java installation directory.
65e86d
  *
65e86d
+ * 

Additional default values of security properties are read from a

65e86d
+ * system-specific location, if available.

65e86d
+ *
65e86d
  * @author Benjamin Renaud
65e86d
  */
65e86d
 
65e86d
 public final class Security {
65e86d
 
65e86d
+    private static final String SYS_PROP_SWITCH =
65e86d
+        "java.security.disableSystemPropertiesFile";
65e86d
+    private static final String SEC_PROP_SWITCH =
65e86d
+        "security.useSystemPropertiesFile";
65e86d
+
65e86d
     /* Are we debugging? -- for developers */
65e86d
     private static final Debug sdebug =
65e86d
                         Debug.getInstance("properties");
65e86d
@@ -62,6 +72,19 @@ public final class Security {
65e86d
     }
65e86d
 
65e86d
     static {
65e86d
+        // Initialise here as used by code with system properties disabled
65e86d
+        SharedSecrets.setJavaSecuritySystemConfiguratorAccess(
65e86d
+            new JavaSecuritySystemConfiguratorAccess() {
65e86d
+                @Override
65e86d
+                public boolean isSystemFipsEnabled() {
65e86d
+                    return SystemConfigurator.isSystemFipsEnabled();
65e86d
+                }
65e86d
+                @Override
65e86d
+                public boolean isPlainKeySupportEnabled() {
65e86d
+                    return SystemConfigurator.isPlainKeySupportEnabled();
65e86d
+                }
65e86d
+            });
65e86d
+
65e86d
         // doPrivileged here because there are multiple
65e86d
         // things in initialize that might require privs.
65e86d
         // (the FileInputStream call and the File.exists call,
65e86d
@@ -78,6 +101,7 @@ public final class Security {
65e86d
         props = new Properties();
65e86d
         boolean loadedProps = false;
65e86d
         boolean overrideAll = false;
65e86d
+        boolean systemSecPropsEnabled = false;
65e86d
 
65e86d
         // first load the system properties file
65e86d
         // to determine the value of security.overridePropertiesFile
65e86d
@@ -93,6 +117,7 @@ public final class Security {
65e86d
                 if (sdebug != null) {
65e86d
                     sdebug.println("reading security properties file: " +
65e86d
                                 propFile);
65e86d
+                    sdebug.println(props.toString());
65e86d
                 }
65e86d
             } catch (IOException e) {
65e86d
                 if (sdebug != null) {
65e86d
@@ -187,6 +212,61 @@ public final class Security {
65e86d
             }
65e86d
         }
65e86d
 
65e86d
+        boolean sysUseProps = Boolean.valueOf(System.getProperty(SYS_PROP_SWITCH, "false"));
65e86d
+        boolean secUseProps = Boolean.valueOf(props.getProperty(SEC_PROP_SWITCH));
65e86d
+        if (sdebug != null) {
65e86d
+            sdebug.println(SYS_PROP_SWITCH + "=" + sysUseProps);
65e86d
+            sdebug.println(SEC_PROP_SWITCH + "=" + secUseProps);
65e86d
+        }
65e86d
+        if (!sysUseProps && secUseProps) {
65e86d
+            systemSecPropsEnabled = SystemConfigurator.configureSysProps(props);
65e86d
+            if (!systemSecPropsEnabled) {
65e86d
+                if (sdebug != null) {
65e86d
+                    sdebug.println("WARNING: System security properties could not be loaded.");
65e86d
+                }
65e86d
+            }
65e86d
+        } else {
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("System security property support disabled by user.");
65e86d
+            }
65e86d
+        }
65e86d
+
65e86d
+        // FIPS support depends on the contents of java.security so
65e86d
+        // ensure it has loaded first
65e86d
+        if (loadedProps && systemSecPropsEnabled) {
65e86d
+            boolean shouldEnable;
65e86d
+            String sysProp = System.getProperty("com.redhat.fips");
65e86d
+            if (sysProp == null) {
65e86d
+                shouldEnable = true;
65e86d
+                if (sdebug != null) {
65e86d
+                    sdebug.println("com.redhat.fips unset, using default value of true");
65e86d
+                }
65e86d
+            } else {
65e86d
+                shouldEnable = Boolean.valueOf(sysProp);
65e86d
+                if (sdebug != null) {
65e86d
+                    sdebug.println("com.redhat.fips set, using its value " + shouldEnable);
65e86d
+                }
65e86d
+             }
65e86d
+            if (shouldEnable) {
65e86d
+                boolean fipsEnabled = SystemConfigurator.configureFIPS(props);
65e86d
+                if (sdebug != null) {
65e86d
+                    if (fipsEnabled) {
65e86d
+                        sdebug.println("FIPS mode support configured and enabled.");
65e86d
+                    } else {
65e86d
+                        sdebug.println("FIPS mode support disabled.");
65e86d
+                    }
65e86d
+                }
65e86d
+            } else {
65e86d
+                if (sdebug != null ) {
65e86d
+                    sdebug.println("FIPS mode support disabled by user.");
65e86d
+                }
65e86d
+            }
65e86d
+        } else {
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("WARNING: FIPS mode support can not be enabled without " +
65e86d
+                               "system security properties being enabled.");
65e86d
+            }
65e86d
+        }
65e86d
     }
65e86d
 
65e86d
     /*
65e86d
diff --git a/jdk/src/share/classes/java/security/SystemConfigurator.java b/jdk/src/share/classes/java/security/SystemConfigurator.java
65e86d
new file mode 100644
65e86d
index 00000000000..a24a0445db2
65e86d
--- /dev/null
65e86d
+++ b/jdk/src/share/classes/java/security/SystemConfigurator.java
65e86d
@@ -0,0 +1,248 @@
65e86d
+/*
65e86d
+ * Copyright (c) 2019, 2021, Red Hat, Inc.
65e86d
+ *
65e86d
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
65e86d
+ *
65e86d
+ * This code is free software; you can redistribute it and/or modify it
65e86d
+ * under the terms of the GNU General Public License version 2 only, as
65e86d
+ * published by the Free Software Foundation.  Oracle designates this
65e86d
+ * particular file as subject to the "Classpath" exception as provided
65e86d
+ * by Oracle in the LICENSE file that accompanied this code.
65e86d
+ *
65e86d
+ * This code is distributed in the hope that it will be useful, but WITHOUT
65e86d
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
65e86d
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
65e86d
+ * version 2 for more details (a copy is included in the LICENSE file that
65e86d
+ * accompanied this code).
65e86d
+ *
65e86d
+ * You should have received a copy of the GNU General Public License version
65e86d
+ * 2 along with this work; if not, write to the Free Software Foundation,
65e86d
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
65e86d
+ *
65e86d
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
65e86d
+ * or visit www.oracle.com if you need additional information or have any
65e86d
+ * questions.
65e86d
+ */
65e86d
+
65e86d
+package java.security;
65e86d
+
65e86d
+import java.io.BufferedInputStream;
65e86d
+import java.io.FileInputStream;
65e86d
+import java.io.IOException;
65e86d
+
65e86d
+import java.util.Iterator;
65e86d
+import java.util.Map.Entry;
65e86d
+import java.util.Properties;
65e86d
+
65e86d
+import sun.security.util.Debug;
65e86d
+
65e86d
+/**
65e86d
+ * Internal class to align OpenJDK with global crypto-policies.
65e86d
+ * Called from java.security.Security class initialization,
65e86d
+ * during startup.
65e86d
+ *
65e86d
+ */
65e86d
+
65e86d
+final class SystemConfigurator {
65e86d
+
65e86d
+    private static final Debug sdebug =
65e86d
+            Debug.getInstance("properties");
65e86d
+
65e86d
+    private static final String CRYPTO_POLICIES_BASE_DIR =
65e86d
+            "/etc/crypto-policies";
65e86d
+
65e86d
+    private static final String CRYPTO_POLICIES_JAVA_CONFIG =
65e86d
+            CRYPTO_POLICIES_BASE_DIR + "/back-ends/java.config";
65e86d
+
65e86d
+    private static boolean systemFipsEnabled = false;
65e86d
+    private static boolean plainKeySupportEnabled = false;
65e86d
+
65e86d
+    private static final String SYSTEMCONF_NATIVE_LIB = "systemconf";
65e86d
+
65e86d
+    private static native boolean getSystemFIPSEnabled()
65e86d
+            throws IOException;
65e86d
+
65e86d
+    static {
65e86d
+        AccessController.doPrivileged(new PrivilegedAction<Void>() {
65e86d
+            public Void run() {
65e86d
+                System.loadLibrary(SYSTEMCONF_NATIVE_LIB);
65e86d
+                return null;
65e86d
+            }
65e86d
+        });
65e86d
+    }
65e86d
+
65e86d
+    /*
65e86d
+     * Invoked when java.security.Security class is initialized, if
65e86d
+     * java.security.disableSystemPropertiesFile property is not set and
65e86d
+     * security.useSystemPropertiesFile is true.
65e86d
+     */
65e86d
+    static boolean configureSysProps(Properties props) {
65e86d
+        boolean systemSecPropsLoaded = false;
65e86d
+
65e86d
+        try (BufferedInputStream bis =
65e86d
+                new BufferedInputStream(
65e86d
+                        new FileInputStream(CRYPTO_POLICIES_JAVA_CONFIG))) {
65e86d
+            props.load(bis);
65e86d
+            systemSecPropsLoaded = true;
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("reading system security properties file " +
65e86d
+                        CRYPTO_POLICIES_JAVA_CONFIG);
65e86d
+                sdebug.println(props.toString());
65e86d
+            }
65e86d
+        } catch (IOException e) {
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("unable to load security properties from " +
65e86d
+                        CRYPTO_POLICIES_JAVA_CONFIG);
65e86d
+                e.printStackTrace();
65e86d
+            }
65e86d
+        }
65e86d
+        return systemSecPropsLoaded;
65e86d
+    }
65e86d
+
65e86d
+    /*
65e86d
+     * Invoked at the end of java.security.Security initialisation
65e86d
+     * if java.security properties have been loaded
65e86d
+     */
65e86d
+    static boolean configureFIPS(Properties props) {
65e86d
+        boolean loadedProps = false;
65e86d
+
65e86d
+        try {
65e86d
+            if (enableFips()) {
65e86d
+                if (sdebug != null) { sdebug.println("FIPS mode detected"); }
65e86d
+                // Remove all security providers
65e86d
+                Iterator<Entry<Object, Object>> i = props.entrySet().iterator();
65e86d
+                while (i.hasNext()) {
65e86d
+                    Entry<Object, Object> e = i.next();
65e86d
+                    if (((String) e.getKey()).startsWith("security.provider")) {
65e86d
+                        if (sdebug != null) { sdebug.println("Removing provider: " + e); }
65e86d
+                        i.remove();
65e86d
+                    }
65e86d
+                }
65e86d
+                // Add FIPS security providers
65e86d
+                String fipsProviderValue = null;
65e86d
+                for (int n = 1;
65e86d
+                     (fipsProviderValue = (String) props.get("fips.provider." + n)) != null; n++) {
65e86d
+                    String fipsProviderKey = "security.provider." + n;
65e86d
+                    if (sdebug != null) {
65e86d
+                        sdebug.println("Adding provider " + n + ": " +
65e86d
+                                fipsProviderKey + "=" + fipsProviderValue);
65e86d
+                    }
65e86d
+                    props.put(fipsProviderKey, fipsProviderValue);
65e86d
+                }
65e86d
+                // Add other security properties
65e86d
+                String keystoreTypeValue = (String) props.get("fips.keystore.type");
65e86d
+                if (keystoreTypeValue != null) {
65e86d
+                    String nonFipsKeystoreType = props.getProperty("keystore.type");
65e86d
+                    props.put("keystore.type", keystoreTypeValue);
65e86d
+                    if (keystoreTypeValue.equals("PKCS11")) {
65e86d
+                        // If keystore.type is PKCS11, javax.net.ssl.keyStore
65e86d
+                        // must be "NONE". See JDK-8238264.
65e86d
+                        System.setProperty("javax.net.ssl.keyStore", "NONE");
65e86d
+                    }
65e86d
+                    if (System.getProperty("javax.net.ssl.trustStoreType") == null) {
65e86d
+                        // If no trustStoreType has been set, use the
65e86d
+                        // previous keystore.type under FIPS mode. In
65e86d
+                        // a default configuration, the Trust Store will
65e86d
+                        // be 'cacerts' (JKS type).
65e86d
+                        System.setProperty("javax.net.ssl.trustStoreType",
65e86d
+                                nonFipsKeystoreType);
65e86d
+                    }
65e86d
+                    if (sdebug != null) {
65e86d
+                        sdebug.println("FIPS mode default keystore.type = " +
65e86d
+                                keystoreTypeValue);
65e86d
+                        sdebug.println("FIPS mode javax.net.ssl.keyStore = " +
65e86d
+                                System.getProperty("javax.net.ssl.keyStore", ""));
65e86d
+                        sdebug.println("FIPS mode javax.net.ssl.trustStoreType = " +
65e86d
+                                System.getProperty("javax.net.ssl.trustStoreType", ""));
65e86d
+                    }
65e86d
+                }
65e86d
+                loadedProps = true;
65e86d
+                systemFipsEnabled = true;
65e86d
+                String plainKeySupport = System.getProperty("com.redhat.fips.plainKeySupport",
65e86d
+                                                            "true");
65e86d
+                plainKeySupportEnabled = !"false".equals(plainKeySupport);
65e86d
+                if (sdebug != null) {
65e86d
+                    if (plainKeySupportEnabled) {
65e86d
+                        sdebug.println("FIPS support enabled with plain key support");
65e86d
+                    } else {
65e86d
+                        sdebug.println("FIPS support enabled without plain key support");
65e86d
+                    }
65e86d
+                }
65e86d
+            } else {
65e86d
+                if (sdebug != null) { sdebug.println("FIPS mode not detected"); }
65e86d
+            }
65e86d
+        } catch (Exception e) {
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("unable to load FIPS configuration");
65e86d
+                e.printStackTrace();
65e86d
+            }
65e86d
+        }
65e86d
+        return loadedProps;
65e86d
+    }
65e86d
+
65e86d
+    /**
65e86d
+     * Returns whether or not global system FIPS alignment is enabled.
65e86d
+     *
65e86d
+     * Value is always 'false' before java.security.Security class is
65e86d
+     * initialized.
65e86d
+     *
65e86d
+     * Call from out of this package through SharedSecrets:
65e86d
+     *   SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
65e86d
+     *           .isSystemFipsEnabled();
65e86d
+     *
65e86d
+     * @return  a boolean value indicating whether or not global
65e86d
+     *          system FIPS alignment is enabled.
65e86d
+     */
65e86d
+    static boolean isSystemFipsEnabled() {
65e86d
+        return systemFipsEnabled;
65e86d
+    }
65e86d
+
65e86d
+    /**
65e86d
+     * Returns {@code true} if system FIPS alignment is enabled
65e86d
+     * and plain key support is allowed.  Plain key support is
65e86d
+     * enabled by default but can be disabled with
65e86d
+     * {@code -Dcom.redhat.fips.plainKeySupport=false}.
65e86d
+     *
65e86d
+     * @return a boolean indicating whether plain key support
65e86d
+     *         should be enabled.
65e86d
+     */
65e86d
+    static boolean isPlainKeySupportEnabled() {
65e86d
+        return plainKeySupportEnabled;
65e86d
+    }
65e86d
+
65e86d
+    /**
65e86d
+     * Determines whether FIPS mode should be enabled.
65e86d
+     *
65e86d
+     * OpenJDK FIPS mode will be enabled only if the system is in
65e86d
+     * FIPS mode.
65e86d
+     *
65e86d
+     * Calls to this method only occur if the system property
65e86d
+     * com.redhat.fips is not set to false.
65e86d
+     *
65e86d
+     * There are 2 possible ways in which OpenJDK detects that the system
65e86d
+     * is in FIPS mode: 1) if the NSS SECMOD_GetSystemFIPSEnabled API is
65e86d
+     * available at OpenJDK's built-time, it is called; 2) otherwise, the
65e86d
+     * /proc/sys/crypto/fips_enabled file is read.
65e86d
+     *
65e86d
+     * @return true if the system is in FIPS mode
65e86d
+     */
65e86d
+    private static boolean enableFips() throws IOException {
65e86d
+        if (sdebug != null) {
65e86d
+            sdebug.println("Calling getSystemFIPSEnabled (libsystemconf)...");
65e86d
+        }
65e86d
+        try {
65e86d
+            boolean fipsEnabled = getSystemFIPSEnabled();
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("Call to getSystemFIPSEnabled (libsystemconf) returned: "
65e86d
+                               + fipsEnabled);
65e86d
+            }
65e86d
+            return fipsEnabled;
65e86d
+        } catch (IOException e) {
65e86d
+            if (sdebug != null) {
65e86d
+                sdebug.println("Call to getSystemFIPSEnabled (libsystemconf) failed:");
65e86d
+                sdebug.println(e.getMessage());
65e86d
+            }
65e86d
+            throw e;
65e86d
+        }
65e86d
+    }
65e86d
+}
65e86d
diff --git a/jdk/src/share/classes/sun/misc/JavaSecuritySystemConfiguratorAccess.java b/jdk/src/share/classes/sun/misc/JavaSecuritySystemConfiguratorAccess.java
65e86d
new file mode 100644
65e86d
index 00000000000..5c30a8b29c7
65e86d
--- /dev/null
65e86d
+++ b/jdk/src/share/classes/sun/misc/JavaSecuritySystemConfiguratorAccess.java
65e86d
@@ -0,0 +1,31 @@
65e86d
+/*
65e86d
+ * Copyright (c) 2020, Red Hat, Inc.
65e86d
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
65e86d
+ *
65e86d
+ * This code is free software; you can redistribute it and/or modify it
65e86d
+ * under the terms of the GNU General Public License version 2 only, as
65e86d
+ * published by the Free Software Foundation.  Oracle designates this
65e86d
+ * particular file as subject to the "Classpath" exception as provided
65e86d
+ * by Oracle in the LICENSE file that accompanied this code.
65e86d
+ *
65e86d
+ * This code is distributed in the hope that it will be useful, but WITHOUT
65e86d
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
65e86d
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
65e86d
+ * version 2 for more details (a copy is included in the LICENSE file that
65e86d
+ * accompanied this code).
65e86d
+ *
65e86d
+ * You should have received a copy of the GNU General Public License version
65e86d
+ * 2 along with this work; if not, write to the Free Software Foundation,
65e86d
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
65e86d
+ *
65e86d
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
65e86d
+ * or visit www.oracle.com if you need additional information or have any
65e86d
+ * questions.
65e86d
+ */
65e86d
+
65e86d
+package sun.misc;
65e86d
+
65e86d
+public interface JavaSecuritySystemConfiguratorAccess {
65e86d
+    boolean isSystemFipsEnabled();
65e86d
+    boolean isPlainKeySupportEnabled();
65e86d
+}
65e86d
diff --git a/jdk/src/share/classes/sun/misc/SharedSecrets.java b/jdk/src/share/classes/sun/misc/SharedSecrets.java
65e86d
index f065a2c685d..0dafe6f59cf 100644
65e86d
--- a/jdk/src/share/classes/sun/misc/SharedSecrets.java
65e86d
+++ b/jdk/src/share/classes/sun/misc/SharedSecrets.java
65e86d
@@ -31,6 +31,7 @@ import java.io.Console;
65e86d
 import java.io.FileDescriptor;
65e86d
 import java.io.ObjectInputStream;
65e86d
 import java.security.ProtectionDomain;
65e86d
+import java.security.Security;
65e86d
 import java.security.Signature;
65e86d
 
65e86d
 import java.security.AccessController;
65e86d
@@ -63,6 +64,7 @@ public class SharedSecrets {
65e86d
     private static JavaObjectInputStreamReadString javaObjectInputStreamReadString;
65e86d
     private static JavaObjectInputStreamAccess javaObjectInputStreamAccess;
65e86d
     private static JavaSecuritySignatureAccess javaSecuritySignatureAccess;
65e86d
+    private static JavaSecuritySystemConfiguratorAccess javaSecuritySystemConfiguratorAccess;
65e86d
 
65e86d
     public static JavaUtilJarAccess javaUtilJarAccess() {
65e86d
         if (javaUtilJarAccess == null) {
65e86d
@@ -248,4 +250,15 @@ public class SharedSecrets {
65e86d
         }
65e86d
         return javaxCryptoSealedObjectAccess;
65e86d
     }
65e86d
+
65e86d
+    public static void setJavaSecuritySystemConfiguratorAccess(JavaSecuritySystemConfiguratorAccess jssca) {
65e86d
+        javaSecuritySystemConfiguratorAccess = jssca;
65e86d
+    }
65e86d
+
65e86d
+    public static JavaSecuritySystemConfiguratorAccess getJavaSecuritySystemConfiguratorAccess() {
65e86d
+        if (javaSecuritySystemConfiguratorAccess == null) {
65e86d
+            unsafe.ensureClassInitialized(Security.class);
65e86d
+        }
65e86d
+        return javaSecuritySystemConfiguratorAccess;
65e86d
+    }
65e86d
 }
65e86d
diff --git a/jdk/src/share/classes/sun/security/pkcs11/FIPSKeyImporter.java b/jdk/src/share/classes/sun/security/pkcs11/FIPSKeyImporter.java
65e86d
new file mode 100644
65e86d
index 00000000000..14d19450390
65e86d
--- /dev/null
65e86d
+++ b/jdk/src/share/classes/sun/security/pkcs11/FIPSKeyImporter.java
65e86d
@@ -0,0 +1,290 @@
65e86d
+/*
65e86d
+ * Copyright (c) 2021, Red Hat, Inc.
65e86d
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
65e86d
+ *
65e86d
+ * This code is free software; you can redistribute it and/or modify it
65e86d
+ * under the terms of the GNU General Public License version 2 only, as
65e86d
+ * published by the Free Software Foundation.  Oracle designates this
65e86d
+ * particular file as subject to the "Classpath" exception as provided
65e86d
+ * by Oracle in the LICENSE file that accompanied this code.
65e86d
+ *
65e86d
+ * This code is distributed in the hope that it will be useful, but WITHOUT
65e86d
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
65e86d
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
65e86d
+ * version 2 for more details (a copy is included in the LICENSE file that
65e86d
+ * accompanied this code).
65e86d
+ *
65e86d
+ * You should have received a copy of the GNU General Public License version
65e86d
+ * 2 along with this work; if not, write to the Free Software Foundation,
65e86d
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
65e86d
+ *
65e86d
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
65e86d
+ * or visit www.oracle.com if you need additional information or have any
65e86d
+ * questions.
65e86d
+ */
65e86d
+
65e86d
+package sun.security.pkcs11;
65e86d
+
65e86d
+import java.math.BigInteger;
65e86d
+import java.security.KeyFactory;
65e86d
+import java.security.Provider;
65e86d
+import java.security.Security;
65e86d
+import java.util.HashMap;
65e86d
+import java.util.Map;
65e86d
+import java.util.concurrent.locks.ReentrantLock;
65e86d
+
65e86d
+import javax.crypto.Cipher;
65e86d
+import javax.crypto.spec.DHPrivateKeySpec;
65e86d
+import javax.crypto.spec.IvParameterSpec;
65e86d
+
65e86d
+import sun.security.jca.JCAUtil;
65e86d
+import sun.security.pkcs11.TemplateManager;
65e86d
+import sun.security.pkcs11.wrapper.CK_ATTRIBUTE;
65e86d
+import sun.security.pkcs11.wrapper.CK_MECHANISM;
65e86d
+import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
65e86d
+import sun.security.pkcs11.wrapper.PKCS11Exception;
65e86d
+import sun.security.rsa.RSAUtil.KeyType;
65e86d
+import sun.security.util.Debug;
65e86d
+import sun.security.util.ECUtil;
65e86d
+
65e86d
+final class FIPSKeyImporter {
65e86d
+
65e86d
+    private static final Debug debug =
65e86d
+            Debug.getInstance("sunpkcs11");
65e86d
+
65e86d
+    private static P11Key importerKey = null;
65e86d
+    private static final ReentrantLock importerKeyLock = new ReentrantLock();
65e86d
+    private static CK_MECHANISM importerKeyMechanism = null;
65e86d
+    private static Cipher importerCipher = null;
65e86d
+
65e86d
+    private static Provider sunECProvider = null;
65e86d
+    private static final ReentrantLock sunECProviderLock = new ReentrantLock();
65e86d
+
65e86d
+    private static KeyFactory DHKF = null;
65e86d
+    private static final ReentrantLock DHKFLock = new ReentrantLock();
65e86d
+
65e86d
+    static Long importKey(SunPKCS11 sunPKCS11, long hSession, CK_ATTRIBUTE[] attributes)
65e86d
+            throws PKCS11Exception {
65e86d
+        long keyID = -1;
65e86d
+        Token token = sunPKCS11.getToken();
65e86d
+        if (debug != null) {
65e86d
+            debug.println("Private or Secret key will be imported in" +
65e86d
+                    " system FIPS mode.");
65e86d
+        }
65e86d
+        if (importerKey == null) {
65e86d
+            importerKeyLock.lock();
65e86d
+            try {
65e86d
+                if (importerKey == null) {
65e86d
+                    if (importerKeyMechanism == null) {
65e86d
+                        // Importer Key creation has not been tried yet. Try it.
65e86d
+                        createImporterKey(token);
65e86d
+                    }
65e86d
+                    if (importerKey == null || importerCipher == null) {
65e86d
+                        if (debug != null) {
65e86d
+                            debug.println("Importer Key could not be" +
65e86d
+                                    " generated.");
65e86d
+                        }
65e86d
+                        throw new PKCS11Exception(CKR_GENERAL_ERROR);
65e86d
+                    }
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Importer Key successfully" +
65e86d
+                                " generated.");
65e86d
+                    }
65e86d
+                }
65e86d
+            } finally {
65e86d
+                importerKeyLock.unlock();
65e86d
+            }
65e86d
+        }
65e86d
+        long importerKeyID = importerKey.getKeyID();
65e86d
+        try {
65e86d
+            byte[] keyBytes = null;
65e86d
+            byte[] encKeyBytes = null;
65e86d
+            long keyClass = 0L;
65e86d
+            long keyType = 0L;
65e86d
+            Map<Long, CK_ATTRIBUTE> attrsMap = new HashMap<>();
65e86d
+            for (CK_ATTRIBUTE attr : attributes) {
65e86d
+                if (attr.type == CKA_CLASS) {
65e86d
+                    keyClass = attr.getLong();
65e86d
+                } else if (attr.type == CKA_KEY_TYPE) {
65e86d
+                    keyType = attr.getLong();
65e86d
+                }
65e86d
+                attrsMap.put(attr.type, attr);
65e86d
+            }
65e86d
+            BigInteger v = null;
65e86d
+            if (keyClass == CKO_PRIVATE_KEY) {
65e86d
+                if (keyType == CKK_RSA) {
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Importing an RSA private key...");
65e86d
+                    }
65e86d
+                    keyBytes = sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(
65e86d
+                            KeyType.RSA,
65e86d
+                            null,
65e86d
+                            ((v = attrsMap.get(CKA_MODULUS).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_PUBLIC_EXPONENT).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_PRIVATE_EXPONENT).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_PRIME_1).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_PRIME_2).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_EXPONENT_1).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_EXPONENT_2).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_COEFFICIENT).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO
65e86d
+                            ).getEncoded();
65e86d
+                } else if (keyType == CKK_DSA) {
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Importing a DSA private key...");
65e86d
+                    }
65e86d
+                    keyBytes = new sun.security.provider.DSAPrivateKey(
65e86d
+                            ((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_PRIME).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_SUBPRIME).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_BASE).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO
65e86d
+                            ).getEncoded();
65e86d
+                    if (token.config.getNssNetscapeDbWorkaround() &&
65e86d
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
65e86d
+                        attrsMap.put(CKA_NETSCAPE_DB,
65e86d
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
65e86d
+                    }
65e86d
+                } else if (keyType == CKK_EC) {
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Importing an EC private key...");
65e86d
+                    }
65e86d
+                    if (sunECProvider == null) {
65e86d
+                        sunECProviderLock.lock();
65e86d
+                        try {
65e86d
+                            if (sunECProvider == null) {
65e86d
+                                sunECProvider = Security.getProvider("SunEC");
65e86d
+                            }
65e86d
+                        } finally {
65e86d
+                            sunECProviderLock.unlock();
65e86d
+                        }
65e86d
+                    }
65e86d
+                    keyBytes = P11ECUtil.generateECPrivateKey(
65e86d
+                            ((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ECUtil.getECParameterSpec(sunECProvider,
65e86d
+                                    attrsMap.get(CKA_EC_PARAMS).getByteArray()))
65e86d
+                            .getEncoded();
65e86d
+                    if (token.config.getNssNetscapeDbWorkaround() &&
65e86d
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
65e86d
+                        attrsMap.put(CKA_NETSCAPE_DB,
65e86d
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
65e86d
+                    }
65e86d
+                } else if (keyType == CKK_DH) {
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Importing a Diffie-Hellman private key...");
65e86d
+                    }
65e86d
+                    if (DHKF == null) {
65e86d
+                        DHKFLock.lock();
65e86d
+                        try {
65e86d
+                            if (DHKF == null) {
65e86d
+                                DHKF = KeyFactory.getInstance(
65e86d
+                                        "DH", P11Util.getSunJceProvider());
65e86d
+                            }
65e86d
+                        } finally {
65e86d
+                            DHKFLock.unlock();
65e86d
+                        }
65e86d
+                    }
65e86d
+                    DHPrivateKeySpec spec = new DHPrivateKeySpec
65e86d
+                            (((v = attrsMap.get(CKA_VALUE).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_PRIME).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO,
65e86d
+                            ((v = attrsMap.get(CKA_BASE).getBigInteger()) != null)
65e86d
+                                    ? v : BigInteger.ZERO);
65e86d
+                    keyBytes = DHKF.generatePrivate(spec).getEncoded();
65e86d
+                    if (token.config.getNssNetscapeDbWorkaround() &&
65e86d
+                            attrsMap.get(CKA_NETSCAPE_DB) == null) {
65e86d
+                        attrsMap.put(CKA_NETSCAPE_DB,
65e86d
+                                new CK_ATTRIBUTE(CKA_NETSCAPE_DB, BigInteger.ZERO));
65e86d
+                    }
65e86d
+                } else {
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Unrecognized private key type.");
65e86d
+                    }
65e86d
+                    throw new PKCS11Exception(CKR_GENERAL_ERROR);
65e86d
+                }
65e86d
+            } else if (keyClass == CKO_SECRET_KEY) {
65e86d
+                if (debug != null) {
65e86d
+                    debug.println("Importing a secret key...");
65e86d
+                }
65e86d
+                keyBytes = attrsMap.get(CKA_VALUE).getByteArray();
65e86d
+            }
65e86d
+            if (keyBytes == null || keyBytes.length == 0) {
65e86d
+                if (debug != null) {
65e86d
+                    debug.println("Private or secret key plain bytes could" +
65e86d
+                            " not be obtained. Import failed.");
65e86d
+                }
65e86d
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
65e86d
+            }
65e86d
+            importerCipher.init(Cipher.ENCRYPT_MODE, importerKey,
65e86d
+                    new IvParameterSpec((byte[])importerKeyMechanism.pParameter),
65e86d
+                    null);
65e86d
+            attributes = new CK_ATTRIBUTE[attrsMap.size()];
65e86d
+            attrsMap.values().toArray(attributes);
65e86d
+            encKeyBytes = importerCipher.doFinal(keyBytes);
65e86d
+            attributes = token.getAttributes(TemplateManager.O_IMPORT,
65e86d
+                    keyClass, keyType, attributes);
65e86d
+            keyID = token.p11.C_UnwrapKey(hSession,
65e86d
+                    importerKeyMechanism, importerKeyID, encKeyBytes, attributes);
65e86d
+            if (debug != null) {
65e86d
+                debug.println("Imported key ID: " + keyID);
65e86d
+            }
65e86d
+        } catch (Throwable t) {
65e86d
+            throw new PKCS11Exception(CKR_GENERAL_ERROR);
65e86d
+        } finally {
65e86d
+            importerKey.releaseKeyID();
65e86d
+        }
65e86d
+        return Long.valueOf(keyID);
65e86d
+    }
65e86d
+
65e86d
+    private static void createImporterKey(Token token) {
65e86d
+        if (debug != null) {
65e86d
+            debug.println("Generating Importer Key...");
65e86d
+        }
65e86d
+        byte[] iv = new byte[16];
65e86d
+        JCAUtil.getSecureRandom().nextBytes(iv);
65e86d
+        importerKeyMechanism = new CK_MECHANISM(CKM_AES_CBC_PAD, iv);
65e86d
+        try {
65e86d
+            CK_ATTRIBUTE[] attributes = token.getAttributes(TemplateManager.O_GENERATE,
65e86d
+                            CKO_SECRET_KEY, CKK_AES, new CK_ATTRIBUTE[] {
65e86d
+                                    new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY),
65e86d
+                                    new CK_ATTRIBUTE(CKA_VALUE_LEN, 256 >> 3)});
65e86d
+            Session s = null;
65e86d
+            try {
65e86d
+                s = token.getObjSession();
65e86d
+                long keyID = token.p11.C_GenerateKey(
65e86d
+                        s.id(), new CK_MECHANISM(CKM_AES_KEY_GEN),
65e86d
+                        attributes);
65e86d
+                if (debug != null) {
65e86d
+                    debug.println("Importer Key ID: " + keyID);
65e86d
+                }
65e86d
+                importerKey = (P11Key)P11Key.secretKey(s, keyID, "AES",
65e86d
+                        256 >> 3, null);
65e86d
+            } catch (PKCS11Exception e) {
65e86d
+                // best effort
65e86d
+            } finally {
65e86d
+                token.releaseSession(s);
65e86d
+            }
65e86d
+            if (importerKey != null) {
65e86d
+                importerCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
65e86d
+            }
65e86d
+        } catch (Throwable t) {
65e86d
+            // best effort
65e86d
+            importerKey = null;
65e86d
+            importerCipher = null;
65e86d
+            // importerKeyMechanism value is kept initialized to indicate that
65e86d
+            // Importer Key creation has been tried and failed.
65e86d
+        }
65e86d
+    }
65e86d
+}
65e86d
diff --git a/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java b/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java
65e86d
index fedcd7743ef..f9d70863bd1 100644
65e86d
--- a/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java
65e86d
+++ b/jdk/src/share/classes/sun/security/pkcs11/SunPKCS11.java
65e86d
@@ -26,6 +26,9 @@
65e86d
 package sun.security.pkcs11;
65e86d
 
65e86d
 import java.io.*;
65e86d
+import java.lang.invoke.MethodHandle;
65e86d
+import java.lang.invoke.MethodHandles;
65e86d
+import java.lang.invoke.MethodType;
65e86d
 import java.util.*;
65e86d
 
65e86d
 import java.security.*;
65e86d
@@ -42,6 +45,8 @@ import javax.security.auth.callback.ConfirmationCallback;
65e86d
 import javax.security.auth.callback.PasswordCallback;
65e86d
 import javax.security.auth.callback.TextOutputCallback;
65e86d
 
65e86d
+import sun.misc.SharedSecrets;
65e86d
+
65e86d
 import sun.security.util.Debug;
65e86d
 import sun.security.util.ResourcesMgr;
65e86d
 
65e86d
@@ -58,6 +63,29 @@ import static sun.security.pkcs11.wrapper.PKCS11Constants.*;
65e86d
  */
65e86d
 public final class SunPKCS11 extends AuthProvider {
65e86d
 
65e86d
+    private static final boolean systemFipsEnabled = SharedSecrets
65e86d
+            .getJavaSecuritySystemConfiguratorAccess().isSystemFipsEnabled();
65e86d
+
65e86d
+    private static final boolean plainKeySupportEnabled = SharedSecrets
65e86d
+            .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled();
65e86d
+
65e86d
+    private static final MethodHandle fipsImportKey;
65e86d
+    static {
65e86d
+        MethodHandle fipsImportKeyTmp = null;
65e86d
+        if (plainKeySupportEnabled) {
65e86d
+            try {
65e86d
+                fipsImportKeyTmp = MethodHandles.lookup().findStatic(
65e86d
+                        FIPSKeyImporter.class, "importKey",
65e86d
+                        MethodType.methodType(Long.class, SunPKCS11.class,
65e86d
+                        long.class, CK_ATTRIBUTE[].class));
65e86d
+            } catch (Throwable t) {
65e86d
+                throw new SecurityException("FIPS key importer initialization" +
65e86d
+                        " failed", t);
65e86d
+            }
65e86d
+        }
65e86d
+        fipsImportKey = fipsImportKeyTmp;
65e86d
+    }
65e86d
+
65e86d
     private static final long serialVersionUID = -1354835039035306505L;
65e86d
 
65e86d
     static final Debug debug = Debug.getInstance("sunpkcs11");
65e86d
@@ -309,10 +337,15 @@ public final class SunPKCS11 extends AuthProvider {
65e86d
             // request multithreaded access first
65e86d
             initArgs.flags = CKF_OS_LOCKING_OK;
65e86d
             PKCS11 tmpPKCS11;
65e86d
+            MethodHandle fipsKeyImporter = null;
65e86d
+            if (plainKeySupportEnabled) {
65e86d
+                fipsKeyImporter = MethodHandles.insertArguments(
65e86d
+                        fipsImportKey, 0, this);
65e86d
+            }
65e86d
             try {
65e86d
                 tmpPKCS11 = PKCS11.getInstance(
65e86d
                     library, functionList, initArgs,
65e86d
-                    config.getOmitInitialize());
65e86d
+                    config.getOmitInitialize(), fipsKeyImporter);
65e86d
             } catch (PKCS11Exception e) {
65e86d
                 if (debug != null) {
65e86d
                     debug.println("Multi-threaded initialization failed: " + e);
65e86d
@@ -328,7 +361,7 @@ public final class SunPKCS11 extends AuthProvider {
65e86d
                     initArgs.flags = 0;
65e86d
                 }
65e86d
                 tmpPKCS11 = PKCS11.getInstance(library,
65e86d
-                    functionList, initArgs, config.getOmitInitialize());
65e86d
+                    functionList, initArgs, config.getOmitInitialize(), fipsKeyImporter);
65e86d
             }
65e86d
             p11 = tmpPKCS11;
65e86d
 
65e86d
@@ -368,6 +401,24 @@ public final class SunPKCS11 extends AuthProvider {
65e86d
             if (nssModule != null) {
65e86d
                 nssModule.setProvider(this);
65e86d
             }
65e86d
+            if (systemFipsEnabled) {
65e86d
+                // The NSS Software Token in FIPS 140-2 mode requires a user
65e86d
+                // login for most operations. See sftk_fipsCheck. The NSS DB
65e86d
+                // (/etc/pki/nssdb) PIN is empty.
65e86d
+                Session session = null;
65e86d
+                try {
65e86d
+                    session = token.getOpSession();
65e86d
+                    p11.C_Login(session.id(), CKU_USER, new char[] {});
65e86d
+                } catch (PKCS11Exception p11e) {
65e86d
+                    if (debug != null) {
65e86d
+                        debug.println("Error during token login: " +
65e86d
+                                p11e.getMessage());
65e86d
+                    }
65e86d
+                    throw p11e;
65e86d
+                } finally {
65e86d
+                    token.releaseSession(session);
65e86d
+                }
65e86d
+            }
65e86d
         } catch (Exception e) {
65e86d
             if (config.getHandleStartupErrors() == Config.ERR_IGNORE_ALL) {
65e86d
                 throw new UnsupportedOperationException
65e86d
diff --git a/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11.java b/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
65e86d
index 2e42d1d9fb0..1b7eed1c656 100644
65e86d
--- a/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
65e86d
+++ b/jdk/src/share/classes/sun/security/pkcs11/wrapper/PKCS11.java
65e86d
@@ -49,6 +49,7 @@ package sun.security.pkcs11.wrapper;
65e86d
 
65e86d
 import java.io.File;
65e86d
 import java.io.IOException;
65e86d
+import java.lang.invoke.MethodHandle;
65e86d
 import java.util.*;
65e86d
 
65e86d
 import java.security.AccessController;
65e86d
@@ -145,18 +146,41 @@ public class PKCS11 {
65e86d
         this.pkcs11ModulePath = pkcs11ModulePath;
65e86d
     }
65e86d
 
65e86d
+    /*
65e86d
+     * Compatibility wrapper to allow this method to work as before
65e86d
+     * when FIPS mode support is not active.
65e86d
+     */
65e86d
+    public static synchronized PKCS11 getInstance(String pkcs11ModulePath,
65e86d
+           String functionList, CK_C_INITIALIZE_ARGS pInitArgs,
65e86d
+           boolean omitInitialize) throws IOException, PKCS11Exception {
65e86d
+        return getInstance(pkcs11ModulePath, functionList,
65e86d
+                           pInitArgs, omitInitialize, null);
65e86d
+    }
65e86d
+
65e86d
     public static synchronized PKCS11 getInstance(String pkcs11ModulePath,
65e86d
             String functionList, CK_C_INITIALIZE_ARGS pInitArgs,
65e86d
-            boolean omitInitialize) throws IOException, PKCS11Exception {
65e86d
+            boolean omitInitialize, MethodHandle fipsKeyImporter)
65e86d
+                    throws IOException, PKCS11Exception {
65e86d
         // we may only call C_Initialize once per native .so/.dll
65e86d
         // so keep a cache using the (non-canonicalized!) path
65e86d
         PKCS11 pkcs11 = moduleMap.get(pkcs11ModulePath);
65e86d
         if (pkcs11 == null) {
65e86d
+            boolean nssFipsMode = fipsKeyImporter != null;
65e86d
             if ((pInitArgs != null)
65e86d
                     && ((pInitArgs.flags & CKF_OS_LOCKING_OK) != 0)) {
65e86d
-                pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
65e86d
+                if (nssFipsMode) {
65e86d
+                    pkcs11 = new FIPSPKCS11(pkcs11ModulePath, functionList,
65e86d
+                            fipsKeyImporter);
65e86d
+                } else {
65e86d
+                    pkcs11 = new PKCS11(pkcs11ModulePath, functionList);
65e86d
+                }
65e86d
             } else {
65e86d
-                pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
65e86d
+                if (nssFipsMode) {
65e86d
+                    pkcs11 = new SynchronizedFIPSPKCS11(pkcs11ModulePath,
65e86d
+                            functionList, fipsKeyImporter);
65e86d
+                } else {
65e86d
+                    pkcs11 = new SynchronizedPKCS11(pkcs11ModulePath, functionList);
65e86d
+                }
65e86d
             }
65e86d
             if (omitInitialize == false) {
65e86d
                 try {
65e86d
@@ -1905,4 +1929,69 @@ static class SynchronizedPKCS11 extends PKCS11 {
65e86d
         super.C_GenerateRandom(hSession, randomData);
65e86d
     }
65e86d
 }
65e86d
+
65e86d
+// PKCS11 subclass that allows using plain private or secret keys in
65e86d
+// FIPS-configured NSS Software Tokens. Only used when System FIPS
65e86d
+// is enabled.
65e86d
+static class FIPSPKCS11 extends PKCS11 {
65e86d
+    private MethodHandle fipsKeyImporter;
65e86d
+    FIPSPKCS11(String pkcs11ModulePath, String functionListName,
65e86d
+            MethodHandle fipsKeyImporter) throws IOException {
65e86d
+        super(pkcs11ModulePath, functionListName);
65e86d
+        this.fipsKeyImporter = fipsKeyImporter;
65e86d
+    }
65e86d
+
65e86d
+    public synchronized long C_CreateObject(long hSession,
65e86d
+            CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
65e86d
+        // Creating sensitive key objects from plain key material in a
65e86d
+        // FIPS-configured NSS Software Token is not allowed. We apply
65e86d
+        // a key-unwrapping scheme to achieve so.
65e86d
+        if (FIPSPKCS11Helper.isSensitiveObject(pTemplate)) {
65e86d
+            try {
65e86d
+                return ((Long)fipsKeyImporter.invoke(hSession, pTemplate))
65e86d
+                        .longValue();
65e86d
+            } catch (Throwable t) {
65e86d
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
65e86d
+            }
65e86d
+        }
65e86d
+        return super.C_CreateObject(hSession, pTemplate);
65e86d
+    }
65e86d
+}
65e86d
+
65e86d
+// FIPSPKCS11 synchronized counterpart.
65e86d
+static class SynchronizedFIPSPKCS11 extends SynchronizedPKCS11 {
65e86d
+    private MethodHandle fipsKeyImporter;
65e86d
+    SynchronizedFIPSPKCS11(String pkcs11ModulePath, String functionListName,
65e86d
+            MethodHandle fipsKeyImporter) throws IOException {
65e86d
+        super(pkcs11ModulePath, functionListName);
65e86d
+        this.fipsKeyImporter = fipsKeyImporter;
65e86d
+    }
65e86d
+
65e86d
+    public synchronized long C_CreateObject(long hSession,
65e86d
+            CK_ATTRIBUTE[] pTemplate) throws PKCS11Exception {
65e86d
+        // See FIPSPKCS11::C_CreateObject.
65e86d
+        if (FIPSPKCS11Helper.isSensitiveObject(pTemplate)) {
65e86d
+            try {
65e86d
+                return ((Long)fipsKeyImporter.invoke(hSession, pTemplate))
65e86d
+                        .longValue();
65e86d
+            } catch (Throwable t) {
65e86d
+                throw new PKCS11Exception(CKR_GENERAL_ERROR);
65e86d
+            }
65e86d
+        }
65e86d
+        return super.C_CreateObject(hSession, pTemplate);
65e86d
+    }
65e86d
+}
65e86d
+
65e86d
+private static class FIPSPKCS11Helper {
65e86d
+    static boolean isSensitiveObject(CK_ATTRIBUTE[] pTemplate) {
65e86d
+        for (CK_ATTRIBUTE attr : pTemplate) {
65e86d
+            if (attr.type == CKA_CLASS &&
65e86d
+                    (attr.getLong() == CKO_PRIVATE_KEY ||
65e86d
+                    attr.getLong() == CKO_SECRET_KEY)) {
65e86d
+                return true;
65e86d
+            }
65e86d
+        }
65e86d
+        return false;
65e86d
+    }
65e86d
+}
65e86d
 }
65e86d
diff --git a/jdk/src/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java b/jdk/src/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
65e86d
index ffee2c1603b..98119479823 100644
65e86d
--- a/jdk/src/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
65e86d
+++ b/jdk/src/share/classes/sun/security/ssl/KeyManagerFactoryImpl.java
65e86d
@@ -33,8 +33,13 @@ import java.security.KeyStore.*;
65e86d
 
65e86d
 import javax.net.ssl.*;
65e86d
 
65e86d
+import sun.misc.SharedSecrets;
65e86d
+
65e86d
 abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
65e86d
 
65e86d
+    private static final boolean plainKeySupportEnabled = SharedSecrets
65e86d
+            .getJavaSecuritySystemConfiguratorAccess().isPlainKeySupportEnabled();
65e86d
+
65e86d
     X509ExtendedKeyManager keyManager;
65e86d
     boolean isInitialized;
65e86d
 
65e86d
@@ -62,7 +67,8 @@ abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
65e86d
                 KeyStoreException, NoSuchAlgorithmException,
65e86d
                 UnrecoverableKeyException {
65e86d
             if ((ks != null) && SunJSSE.isFIPS()) {
65e86d
-                if (ks.getProvider() != SunJSSE.cryptoProvider) {
65e86d
+                if (ks.getProvider() != SunJSSE.cryptoProvider &&
65e86d
+                        !plainKeySupportEnabled) {
65e86d
                     throw new KeyStoreException("FIPS mode: KeyStore must be "
65e86d
                         + "from provider " + SunJSSE.cryptoProvider.getName());
65e86d
                 }
65e86d
@@ -91,8 +97,8 @@ abstract class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
65e86d
                 keyManager = new X509KeyManagerImpl(
65e86d
                         Collections.<Builder>emptyList());
65e86d
             } else {
65e86d
-                if (SunJSSE.isFIPS() &&
65e86d
-                        (ks.getProvider() != SunJSSE.cryptoProvider)) {
65e86d
+                if (SunJSSE.isFIPS() && (ks.getProvider() != SunJSSE.cryptoProvider)
65e86d
+                        && !plainKeySupportEnabled) {
65e86d
                     throw new KeyStoreException(
65e86d
                         "FIPS mode: KeyStore must be " +
65e86d
                         "from provider " + SunJSSE.cryptoProvider.getName());
65e86d
diff --git a/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java b/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
65e86d
index 820e10164fc..6fe2c29389f 100644
65e86d
--- a/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
65e86d
+++ b/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
65e86d
@@ -31,6 +31,7 @@ import java.security.*;
65e86d
 import java.security.cert.*;
65e86d
 import java.util.*;
65e86d
 import javax.net.ssl.*;
65e86d
+import sun.misc.SharedSecrets;
65e86d
 import sun.security.action.GetPropertyAction;
65e86d
 import sun.security.provider.certpath.AlgorithmChecker;
65e86d
 import sun.security.validator.Validator;
65e86d
@@ -539,20 +540,38 @@ public abstract class SSLContextImpl extends SSLContextSpi {
65e86d
 
65e86d
         static {
65e86d
             if (SunJSSE.isFIPS()) {
65e86d
-                supportedProtocols = Arrays.asList(
65e86d
-                    ProtocolVersion.TLS13,
65e86d
-                    ProtocolVersion.TLS12,
65e86d
-                    ProtocolVersion.TLS11,
65e86d
-                    ProtocolVersion.TLS10
65e86d
-                );
65e86d
+                if (SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
65e86d
+                        .isSystemFipsEnabled()) {
65e86d
+                    // RH1860986: TLSv1.3 key derivation not supported with
65e86d
+                    // the Security Providers available in system FIPS mode.
65e86d
+                    supportedProtocols = Arrays.asList(
65e86d
+                        ProtocolVersion.TLS12,
65e86d
+                        ProtocolVersion.TLS11,
65e86d
+                        ProtocolVersion.TLS10
65e86d
+                    );
65e86d
 
65e86d
-                serverDefaultProtocols = getAvailableProtocols(
65e86d
-                        new ProtocolVersion[] {
65e86d
-                    ProtocolVersion.TLS13,
65e86d
-                    ProtocolVersion.TLS12,
65e86d
-                    ProtocolVersion.TLS11,
65e86d
-                    ProtocolVersion.TLS10
65e86d
-                });
65e86d
+                    serverDefaultProtocols = getAvailableProtocols(
65e86d
+                            new ProtocolVersion[] {
65e86d
+                        ProtocolVersion.TLS12,
65e86d
+                        ProtocolVersion.TLS11,
65e86d
+                        ProtocolVersion.TLS10
65e86d
+                    });
65e86d
+                } else {
65e86d
+                    supportedProtocols = Arrays.asList(
65e86d
+                        ProtocolVersion.TLS13,
65e86d
+                        ProtocolVersion.TLS12,
65e86d
+                        ProtocolVersion.TLS11,
65e86d
+                        ProtocolVersion.TLS10
65e86d
+                    );
65e86d
+
65e86d
+                    serverDefaultProtocols = getAvailableProtocols(
65e86d
+                            new ProtocolVersion[] {
65e86d
+                        ProtocolVersion.TLS13,
65e86d
+                        ProtocolVersion.TLS12,
65e86d
+                        ProtocolVersion.TLS11,
65e86d
+                        ProtocolVersion.TLS10
65e86d
+                    });
65e86d
+                }
65e86d
             } else {
65e86d
                 supportedProtocols = Arrays.asList(
65e86d
                     ProtocolVersion.TLS13,
65e86d
@@ -612,6 +631,16 @@ public abstract class SSLContextImpl extends SSLContextSpi {
65e86d
 
65e86d
         static ProtocolVersion[] getSupportedProtocols() {
65e86d
             if (SunJSSE.isFIPS()) {
65e86d
+                if (SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
65e86d
+                        .isSystemFipsEnabled()) {
65e86d
+                    // RH1860986: TLSv1.3 key derivation not supported with
65e86d
+                    // the Security Providers available in system FIPS mode.
65e86d
+                    return new ProtocolVersion[] {
65e86d
+                            ProtocolVersion.TLS12,
65e86d
+                            ProtocolVersion.TLS11,
65e86d
+                            ProtocolVersion.TLS10
65e86d
+                    };
65e86d
+                }
65e86d
                 return new ProtocolVersion[] {
65e86d
                         ProtocolVersion.TLS13,
65e86d
                         ProtocolVersion.TLS12,
65e86d
@@ -939,6 +968,16 @@ public abstract class SSLContextImpl extends SSLContextSpi {
65e86d
 
65e86d
         static ProtocolVersion[] getProtocols() {
65e86d
             if (SunJSSE.isFIPS()) {
65e86d
+                if (SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
65e86d
+                        .isSystemFipsEnabled()) {
65e86d
+                    // RH1860986: TLSv1.3 key derivation not supported with
65e86d
+                    // the Security Providers available in system FIPS mode.
65e86d
+                    return new ProtocolVersion[] {
65e86d
+                            ProtocolVersion.TLS12,
65e86d
+                            ProtocolVersion.TLS11,
65e86d
+                            ProtocolVersion.TLS10
65e86d
+                    };
65e86d
+                }
65e86d
                 return new ProtocolVersion[]{
65e86d
                         ProtocolVersion.TLS13,
65e86d
                         ProtocolVersion.TLS12,
65e86d
diff --git a/jdk/src/share/classes/sun/security/ssl/SunJSSE.java b/jdk/src/share/classes/sun/security/ssl/SunJSSE.java
65e86d
index 2845dc37938..52337a7b6cf 100644
65e86d
--- a/jdk/src/share/classes/sun/security/ssl/SunJSSE.java
65e86d
+++ b/jdk/src/share/classes/sun/security/ssl/SunJSSE.java
65e86d
@@ -30,6 +30,8 @@ import static sun.security.util.SecurityConstants.PROVIDER_VER;
65e86d
 
65e86d
 import java.security.*;
65e86d
 
65e86d
+import sun.misc.SharedSecrets;
65e86d
+
65e86d
 /**
65e86d
  * The JSSE provider.
65e86d
  *
65e86d
@@ -215,8 +217,13 @@ public abstract class SunJSSE extends java.security.Provider {
65e86d
             "sun.security.ssl.SSLContextImpl$TLS11Context");
65e86d
         put("SSLContext.TLSv1.2",
65e86d
             "sun.security.ssl.SSLContextImpl$TLS12Context");
65e86d
-        put("SSLContext.TLSv1.3",
65e86d
-            "sun.security.ssl.SSLContextImpl$TLS13Context");
65e86d
+        if (!SharedSecrets.getJavaSecuritySystemConfiguratorAccess()
65e86d
+                .isSystemFipsEnabled()) {
65e86d
+            // RH1860986: TLSv1.3 key derivation not supported with
65e86d
+            // the Security Providers available in system FIPS mode.
65e86d
+            put("SSLContext.TLSv1.3",
65e86d
+                "sun.security.ssl.SSLContextImpl$TLS13Context");
65e86d
+        }
65e86d
         put("SSLContext.TLS",
65e86d
             "sun.security.ssl.SSLContextImpl$TLSContext");
65e86d
         if (isfips == false) {
65e86d
diff --git a/jdk/src/share/lib/security/java.security-aix b/jdk/src/share/lib/security/java.security-aix
65e86d
index 7a93d4e6b59..681a24b905d 100644
65e86d
--- a/jdk/src/share/lib/security/java.security-aix
65e86d
+++ b/jdk/src/share/lib/security/java.security-aix
65e86d
@@ -287,6 +287,13 @@ package.definition=sun.,\
65e86d
 #
65e86d
 security.overridePropertiesFile=true
65e86d
 
65e86d
+#
65e86d
+# Determines whether this properties file will be appended to
65e86d
+# using the system properties file stored at
65e86d
+# /etc/crypto-policies/back-ends/java.config
65e86d
+#
65e86d
+security.useSystemPropertiesFile=false
65e86d
+
65e86d
 #
65e86d
 # Determines the default key and trust manager factory algorithms for
65e86d
 # the javax.net.ssl package.
65e86d
diff --git a/jdk/src/share/lib/security/java.security-linux b/jdk/src/share/lib/security/java.security-linux
65e86d
index 145a84f94cf..789c19a8cba 100644
65e86d
--- a/jdk/src/share/lib/security/java.security-linux
65e86d
+++ b/jdk/src/share/lib/security/java.security-linux
65e86d
@@ -75,6 +75,14 @@ security.provider.7=com.sun.security.sasl.Provider
65e86d
 security.provider.8=org.jcp.xml.dsig.internal.dom.XMLDSigRI
65e86d
 security.provider.9=sun.security.smartcardio.SunPCSC
65e86d
 
65e86d
+#
65e86d
+# Security providers used when FIPS mode support is active
65e86d
+#
65e86d
+fips.provider.1=sun.security.pkcs11.SunPKCS11 ${java.home}/lib/security/nss.fips.cfg
65e86d
+fips.provider.2=sun.security.provider.Sun
65e86d
+fips.provider.3=sun.security.ec.SunEC
65e86d
+fips.provider.4=com.sun.net.ssl.internal.ssl.Provider SunPKCS11-NSS-FIPS
65e86d
+
65e86d
 #
65e86d
 # Sun Provider SecureRandom seed source.
65e86d
 #
65e86d
@@ -170,6 +178,11 @@ policy.ignoreIdentityScope=false
65e86d
 #
65e86d
 keystore.type=jks
65e86d
 
65e86d
+#
65e86d
+# Default keystore type used when global crypto-policies are set to FIPS.
65e86d
+#
65e86d
+fips.keystore.type=PKCS11
65e86d
+
65e86d
 #
65e86d
 # Controls compatibility mode for the JKS keystore type.
65e86d
 #
65e86d
@@ -287,6 +300,13 @@ package.definition=sun.,\
65e86d
 #
65e86d
 security.overridePropertiesFile=true
65e86d
 
65e86d
+#
65e86d
+# Determines whether this properties file will be appended to
65e86d
+# using the system properties file stored at
65e86d
+# /etc/crypto-policies/back-ends/java.config
65e86d
+#
65e86d
+security.useSystemPropertiesFile=false
65e86d
+
65e86d
 #
65e86d
 # Determines the default key and trust manager factory algorithms for
65e86d
 # the javax.net.ssl package.
65e86d
diff --git a/jdk/src/share/lib/security/java.security-macosx b/jdk/src/share/lib/security/java.security-macosx
65e86d
index 35fa140d7a5..d4da666af3b 100644
65e86d
--- a/jdk/src/share/lib/security/java.security-macosx
65e86d
+++ b/jdk/src/share/lib/security/java.security-macosx
65e86d
@@ -290,6 +290,13 @@ package.definition=sun.,\
65e86d
 #
65e86d
 security.overridePropertiesFile=true
65e86d
 
65e86d
+#
65e86d
+# Determines whether this properties file will be appended to
65e86d
+# using the system properties file stored at
65e86d
+# /etc/crypto-policies/back-ends/java.config
65e86d
+#
65e86d
+security.useSystemPropertiesFile=false
65e86d
+
65e86d
 #
65e86d
 # Determines the default key and trust manager factory algorithms for
65e86d
 # the javax.net.ssl package.
65e86d
diff --git a/jdk/src/share/lib/security/java.security-solaris b/jdk/src/share/lib/security/java.security-solaris
65e86d
index f79ba37ddb9..300132384a1 100644
65e86d
--- a/jdk/src/share/lib/security/java.security-solaris
65e86d
+++ b/jdk/src/share/lib/security/java.security-solaris
65e86d
@@ -288,6 +288,13 @@ package.definition=sun.,\
65e86d
 #
65e86d
 security.overridePropertiesFile=true
65e86d
 
65e86d
+#
65e86d
+# Determines whether this properties file will be appended to
65e86d
+# using the system properties file stored at
65e86d
+# /etc/crypto-policies/back-ends/java.config
65e86d
+#
65e86d
+security.useSystemPropertiesFile=false
65e86d
+
65e86d
 #
65e86d
 # Determines the default key and trust manager factory algorithms for
65e86d
 # the javax.net.ssl package.
65e86d
diff --git a/jdk/src/share/lib/security/java.security-windows b/jdk/src/share/lib/security/java.security-windows
65e86d
index d70503ce95f..64db5a5cd1e 100644
65e86d
--- a/jdk/src/share/lib/security/java.security-windows
65e86d
+++ b/jdk/src/share/lib/security/java.security-windows
65e86d
@@ -290,6 +290,13 @@ package.definition=sun.,\
65e86d
 #
65e86d
 security.overridePropertiesFile=true
65e86d
 
65e86d
+#
65e86d
+# Determines whether this properties file will be appended to
65e86d
+# using the system properties file stored at
65e86d
+# /etc/crypto-policies/back-ends/java.config
65e86d
+#
65e86d
+security.useSystemPropertiesFile=false
65e86d
+
65e86d
 #
65e86d
 # Determines the default key and trust manager factory algorithms for
65e86d
 # the javax.net.ssl package.
65e86d
diff --git a/jdk/src/solaris/native/java/security/systemconf.c b/jdk/src/solaris/native/java/security/systemconf.c
65e86d
new file mode 100644
65e86d
index 00000000000..8dcb7d9073f
65e86d
--- /dev/null
65e86d
+++ b/jdk/src/solaris/native/java/security/systemconf.c
65e86d
@@ -0,0 +1,224 @@
65e86d
+/*
65e86d
+ * Copyright (c) 2021, Red Hat, Inc.
65e86d
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
65e86d
+ *
65e86d
+ * This code is free software; you can redistribute it and/or modify it
65e86d
+ * under the terms of the GNU General Public License version 2 only, as
65e86d
+ * published by the Free Software Foundation.  Oracle designates this
65e86d
+ * particular file as subject to the "Classpath" exception as provided
65e86d
+ * by Oracle in the LICENSE file that accompanied this code.
65e86d
+ *
65e86d
+ * This code is distributed in the hope that it will be useful, but WITHOUT
65e86d
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
65e86d
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
65e86d
+ * version 2 for more details (a copy is included in the LICENSE file that
65e86d
+ * accompanied this code).
65e86d
+ *
65e86d
+ * You should have received a copy of the GNU General Public License version
65e86d
+ * 2 along with this work; if not, write to the Free Software Foundation,
65e86d
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
65e86d
+ *
65e86d
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
65e86d
+ * or visit www.oracle.com if you need additional information or have any
65e86d
+ * questions.
65e86d
+ */
65e86d
+
65e86d
+#include <jni.h>
65e86d
+#include <jni_util.h>
65e86d
+#include "jvm_md.h"
65e86d
+#include <stdio.h>
65e86d
+
65e86d
+#ifdef SYSCONF_NSS
65e86d
+#include <nss3/pk11pub.h>
65e86d
+#else
65e86d
+#include <dlfcn.h>
65e86d
+#endif //SYSCONF_NSS
65e86d
+
65e86d
+#include "java_security_SystemConfigurator.h"
65e86d
+
65e86d
+#define MSG_MAX_SIZE 256
65e86d
+#define FIPS_ENABLED_PATH "/proc/sys/crypto/fips_enabled"
65e86d
+
65e86d
+typedef int (SECMOD_GET_SYSTEM_FIPS_ENABLED_TYPE)(void);
65e86d
+
65e86d
+static SECMOD_GET_SYSTEM_FIPS_ENABLED_TYPE *getSystemFIPSEnabled;
65e86d
+static jmethodID debugPrintlnMethodID = NULL;
65e86d
+static jobject debugObj = NULL;
65e86d
+
65e86d
+static void dbgPrint(JNIEnv *env, const char* msg)
65e86d
+{
65e86d
+    jstring jMsg;
65e86d
+    if (debugObj != NULL) {
65e86d
+        jMsg = (*env)->NewStringUTF(env, msg);
65e86d
+        CHECK_NULL(jMsg);
65e86d
+        (*env)->CallVoidMethod(env, debugObj, debugPrintlnMethodID, jMsg);
65e86d
+    }
65e86d
+}
65e86d
+
65e86d
+static void throwIOException(JNIEnv *env, const char *msg)
65e86d
+{
65e86d
+    jclass cls = (*env)->FindClass(env, "java/io/IOException");
65e86d
+    if (cls != 0)
65e86d
+        (*env)->ThrowNew(env, cls, msg);
65e86d
+}
65e86d
+
65e86d
+static void handle_msg(JNIEnv *env, const char* msg, int msg_bytes)
65e86d
+{
65e86d
+  if (msg_bytes > 0 && msg_bytes < MSG_MAX_SIZE) {
65e86d
+    dbgPrint(env, msg);
65e86d
+  } else {
65e86d
+    dbgPrint(env, "systemconf: cannot render message");
65e86d
+  }
65e86d
+}
65e86d
+
65e86d
+// Only used when NSS is not linked at build time
65e86d
+#ifndef SYSCONF_NSS
65e86d
+
65e86d
+static void *nss_handle;
65e86d
+
65e86d
+static jboolean loadNSS(JNIEnv *env)
65e86d
+{
65e86d
+  char msg[MSG_MAX_SIZE];
65e86d
+  int msg_bytes;
65e86d
+  const char* errmsg;
65e86d
+
65e86d
+  nss_handle = dlopen(JNI_LIB_NAME("nss3"), RTLD_LAZY);
65e86d
+  if (nss_handle == NULL) {
65e86d
+    errmsg = dlerror();
65e86d
+    msg_bytes = snprintf(msg, MSG_MAX_SIZE, "loadNSS: dlopen: %s\n",
65e86d
+                         errmsg);
65e86d
+    handle_msg(env, msg, msg_bytes);
65e86d
+    return JNI_FALSE;
65e86d
+  }
65e86d
+  dlerror(); /* Clear errors */
65e86d
+  getSystemFIPSEnabled = (SECMOD_GET_SYSTEM_FIPS_ENABLED_TYPE*)dlsym(nss_handle, "SECMOD_GetSystemFIPSEnabled");
65e86d
+  if ((errmsg = dlerror()) != NULL) {
65e86d
+    msg_bytes = snprintf(msg, MSG_MAX_SIZE, "loadNSS: dlsym: %s\n",
65e86d
+                         errmsg);
65e86d
+    handle_msg(env, msg, msg_bytes);
65e86d
+    return JNI_FALSE;
65e86d
+  }
65e86d
+  return JNI_TRUE;
65e86d
+}
65e86d
+
65e86d
+static void closeNSS(JNIEnv *env)
65e86d
+{
65e86d
+  char msg[MSG_MAX_SIZE];
65e86d
+  int msg_bytes;
65e86d
+  const char* errmsg;
65e86d
+
65e86d
+  if (dlclose(nss_handle) != 0) {
65e86d
+    errmsg = dlerror();
65e86d
+    msg_bytes = snprintf(msg, MSG_MAX_SIZE, "closeNSS: dlclose: %s\n",
65e86d
+                         errmsg);
65e86d
+    handle_msg(env, msg, msg_bytes);
65e86d
+  }
65e86d
+}
65e86d
+
65e86d
+#endif
65e86d
+
65e86d
+/*
65e86d
+ * Class:     java_security_SystemConfigurator
65e86d
+ * Method:    JNI_OnLoad
65e86d
+ */
65e86d
+JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *vm, void *reserved)
65e86d
+{
65e86d
+    JNIEnv *env;
65e86d
+    jclass sysConfCls, debugCls;
65e86d
+    jfieldID sdebugFld;
65e86d
+
65e86d
+    if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_2) != JNI_OK) {
65e86d
+        return JNI_EVERSION; /* JNI version not supported */
65e86d
+    }
65e86d
+
65e86d
+    sysConfCls = (*env)->FindClass(env,"java/security/SystemConfigurator");
65e86d
+    if (sysConfCls == NULL) {
65e86d
+        printf("libsystemconf: SystemConfigurator class not found\n");
65e86d
+        return JNI_ERR;
65e86d
+    }
65e86d
+    sdebugFld = (*env)->GetStaticFieldID(env, sysConfCls,
65e86d
+            "sdebug", "Lsun/security/util/Debug;");
65e86d
+    if (sdebugFld == NULL) {
65e86d
+        printf("libsystemconf: SystemConfigurator::sdebug field not found\n");
65e86d
+        return JNI_ERR;
65e86d
+    }
65e86d
+    debugObj = (*env)->GetStaticObjectField(env, sysConfCls, sdebugFld);
65e86d
+    if (debugObj != NULL) {
65e86d
+        debugCls = (*env)->FindClass(env,"sun/security/util/Debug");
65e86d
+        if (debugCls == NULL) {
65e86d
+            printf("libsystemconf: Debug class not found\n");
65e86d
+            return JNI_ERR;
65e86d
+        }
65e86d
+        debugPrintlnMethodID = (*env)->GetMethodID(env, debugCls,
65e86d
+                "println", "(Ljava/lang/String;)V");
65e86d
+        if (debugPrintlnMethodID == NULL) {
65e86d
+            printf("libsystemconf: Debug::println(String) method not found\n");
65e86d
+            return JNI_ERR;
65e86d
+        }
65e86d
+        debugObj = (*env)->NewGlobalRef(env, debugObj);
65e86d
+    }
65e86d
+
65e86d
+#ifdef SYSCONF_NSS
65e86d
+    getSystemFIPSEnabled = *SECMOD_GetSystemFIPSEnabled;
65e86d
+#else
65e86d
+    if (loadNSS(env) == JNI_FALSE) {
65e86d
+      dbgPrint(env, "libsystemconf: Failed to load NSS library.");
65e86d
+    }
65e86d
+#endif
65e86d
+
65e86d
+    return (*env)->GetVersion(env);
65e86d
+}
65e86d
+
65e86d
+/*
65e86d
+ * Class:     java_security_SystemConfigurator
65e86d
+ * Method:    JNI_OnUnload
65e86d
+ */
65e86d
+JNIEXPORT void JNICALL DEF_JNI_OnUnload(JavaVM *vm, void *reserved)
65e86d
+{
65e86d
+    JNIEnv *env;
65e86d
+
65e86d
+    if (debugObj != NULL) {
65e86d
+        if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_2) != JNI_OK) {
65e86d
+            return; /* Should not happen */
65e86d
+        }
65e86d
+#ifndef SYSCONF_NSS
65e86d
+        closeNSS(env);
65e86d
+#endif
65e86d
+        (*env)->DeleteGlobalRef(env, debugObj);
65e86d
+    }
65e86d
+}
65e86d
+
65e86d
+JNIEXPORT jboolean JNICALL Java_java_security_SystemConfigurator_getSystemFIPSEnabled
65e86d
+  (JNIEnv *env, jclass cls)
65e86d
+{
65e86d
+    int fips_enabled;
65e86d
+    char msg[MSG_MAX_SIZE];
65e86d
+    int msg_bytes;
65e86d
+
65e86d
+    if (getSystemFIPSEnabled != NULL) {
65e86d
+      dbgPrint(env, "getSystemFIPSEnabled: calling SECMOD_GetSystemFIPSEnabled");
65e86d
+      fips_enabled = (*getSystemFIPSEnabled)();
65e86d
+      msg_bytes = snprintf(msg, MSG_MAX_SIZE, "getSystemFIPSEnabled:"   \
65e86d
+                           " SECMOD_GetSystemFIPSEnabled returned 0x%x", fips_enabled);
65e86d
+      handle_msg(env, msg, msg_bytes);
65e86d
+      return (fips_enabled == 1 ? JNI_TRUE : JNI_FALSE);
65e86d
+    } else {
65e86d
+      FILE *fe;
65e86d
+
65e86d
+      dbgPrint(env, "getSystemFIPSEnabled: reading " FIPS_ENABLED_PATH);
65e86d
+      if ((fe = fopen(FIPS_ENABLED_PATH, "r")) == NULL) {
65e86d
+        throwIOException(env, "Cannot open " FIPS_ENABLED_PATH);
65e86d
+        return JNI_FALSE;
65e86d
+      }
65e86d
+      fips_enabled = fgetc(fe);
65e86d
+      fclose(fe);
65e86d
+      if (fips_enabled == EOF) {
65e86d
+        throwIOException(env, "Cannot read " FIPS_ENABLED_PATH);
65e86d
+        return JNI_FALSE;
65e86d
+      }
65e86d
+      msg_bytes = snprintf(msg, MSG_MAX_SIZE, "getSystemFIPSEnabled:"   \
65e86d
+                           " read character is '%c'", fips_enabled);
65e86d
+      handle_msg(env, msg, msg_bytes);
65e86d
+      return (fips_enabled == '1' ? JNI_TRUE : JNI_FALSE);
65e86d
+    }
65e86d
+}