Blame SOURCES/fips-8u-8e8bbf0ff74.patch

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

Additional default values of security properties are read from a

221ce3
+ * system-specific location, if available.

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