Blame SOURCES/fips-8u-6d1aade0648.patch

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

Additional default values of security properties are read from a

66549d
+ * system-specific location, if available.

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