diff --git a/closed/custom/modules/java.base/Copy.gmk b/closed/custom/modules/java.base/Copy.gmk index a20152e2304..872f8856ee0 100644 --- a/closed/custom/modules/java.base/Copy.gmk +++ b/closed/custom/modules/java.base/Copy.gmk @@ -243,9 +243,9 @@ ifneq ($(OPENSSL_BUNDLE_LIB_PATH), ) endif # OPENJ9_ENABLE_JITSERVER endif # OPENSSL_BUNDLE_LIB_PATH ################################################################################ -# Copy the nss.fips.cfg only on x86 linux +# Copy the nss.fips.cfg only on x86/p/z linux -ifeq ($(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU_ARCH), linux-x86) +ifneq ($(filter linux-x86_64 linux-ppc64le linux-s390x, $(OPENJDK_TARGET_OS)-$(OPENJDK_TARGET_CPU)), ) NSS_FIPS_CFG_SRC := $(TOPDIR)/closed/src/java.base/share/conf/security/nss.fips.cfg NSS_FIPS_CFG_DST := $(CONF_DST_DIR)/security/nss.fips.cfg diff --git a/closed/openjdk-tag.gmk b/closed/openjdk-tag.gmk index e7e3b7a2535..ceacb0a9cb1 100644 --- a/closed/openjdk-tag.gmk +++ b/closed/openjdk-tag.gmk @@ -1 +1 @@ -OPENJDK_TAG := jdk-17.0.10+4 +OPENJDK_TAG := jdk-17.0.10+5 diff --git a/closed/src/java.base/share/classes/openj9/internal/security/RestrictedSecurity.java b/closed/src/java.base/share/classes/openj9/internal/security/RestrictedSecurity.java index 9bacf62f094..db60a3f2adc 100644 --- a/closed/src/java.base/share/classes/openj9/internal/security/RestrictedSecurity.java +++ b/closed/src/java.base/share/classes/openj9/internal/security/RestrictedSecurity.java @@ -32,12 +32,16 @@ import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import sun.security.util.Debug; @@ -50,41 +54,104 @@ public final class RestrictedSecurity { // Restricted security mode enable check, only supported on Linux x64. private static final boolean userEnabledFIPS; - private static final boolean userEnabledSecurity; - private static final boolean isSecuritySupported; + private static boolean isFIPSSupported; + private static boolean isFIPSEnabled; + + private static final boolean isNSSSupported; + private static final boolean isOpenJCEPlusSupported; + + private static final boolean userSetProfile; private static final boolean shouldEnableSecurity; - private static final String userSecuritySetting; + private static String selectedProfile; + private static String profileID; private static boolean securityEnabled; - private static int userSecurityNum; - private static boolean userSecurityTrace; - private static boolean userSecurityAudit; - private static boolean userSecurityHelp; + private static String userSecurityID; private static RestrictedSecurityProperties restricts; - private static final List supportPlatforms = List.of("amd64"); + private static final Map> supportedPlatformsNSS = new HashMap<>(); + private static final Map> supportedPlatformsOpenJCEPlus = new HashMap<>(); static { + supportedPlatformsNSS.put("Arch", List.of("amd64", "ppc64le", "s390x")); + supportedPlatformsNSS.put("OS", List.of("Linux")); + + supportedPlatformsOpenJCEPlus.put("Arch", List.of("amd64", "ppc64")); + supportedPlatformsOpenJCEPlus.put("OS", List.of("Linux", "AIX", "Windows")); + @SuppressWarnings("removal") String[] props = AccessController.doPrivileged( new PrivilegedAction<>() { @Override public String[] run() { return new String[] { System.getProperty("semeru.fips"), - System.getProperty("semeru.restrictedsecurity"), + System.getProperty("semeru.customprofile"), System.getProperty("os.name"), System.getProperty("os.arch") }; } }); + + boolean isOsSupported, isArchSupported; + // Check whether the NSS FIPS solution is supported. + isOsSupported = false; + for (String os: supportedPlatformsNSS.get("OS")) { + if (props[2].contains(os)) { + isOsSupported = true; + } + } + isArchSupported = false; + for (String arch: supportedPlatformsNSS.get("Arch")) { + if (props[3].contains(arch)) { + isArchSupported = true; + } + } + isNSSSupported = isOsSupported && isArchSupported; + + // Check whether the OpenJCEPlus FIPS solution is supported. + isOsSupported = false; + for (String os: supportedPlatformsOpenJCEPlus.get("OS")) { + if (props[2].contains(os)) { + isOsSupported = true; + } + } + isArchSupported = false; + for (String arch: supportedPlatformsOpenJCEPlus.get("Arch")) { + if (props[3].contains(arch)) { + isArchSupported = true; + } + } + isOpenJCEPlusSupported = isOsSupported && isArchSupported; + + // Check the default solution to see if FIPS is supported. + isFIPSSupported = isNSSSupported; + userEnabledFIPS = Boolean.parseBoolean(props[0]); - // If semeru.fips is true, then ignore semeru.restrictedsecurity, use userSecurityNum 1. - userSecuritySetting = userEnabledFIPS ? "1" : props[1]; - userEnabledSecurity = !isNullOrBlank(userSecuritySetting); - isSecuritySupported = "Linux".equalsIgnoreCase(props[2]) - && supportPlatforms.contains(props[3]); - shouldEnableSecurity = (userEnabledFIPS || userEnabledSecurity) && isSecuritySupported; + + if (userEnabledFIPS) { + if (isFIPSSupported) { + // Set to default profile for the default FIPS solution. + selectedProfile = "NSS.140-2"; + } + } + + // If user has specified a profile, use that + if (props[1] != null) { + selectedProfile = props[1]; + userSetProfile = true; + } else { + userSetProfile = false; + } + + // Check if FIPS is supported on this platform without explicitly setting a profile. + if (userEnabledFIPS && !isFIPSSupported && !userSetProfile) { + printStackTraceAndExit("FIPS mode is not supported on this platform by default.\n" + + " Use the semeru.customprofile system property to use an available FIPS-compliant profile.\n" + + " Note: Not all platforms support FIPS at the moment."); + } + + shouldEnableSecurity = (userEnabledFIPS && isFIPSSupported) || userSetProfile; } private RestrictedSecurity() { @@ -95,8 +162,9 @@ private RestrictedSecurity() { * Check if restricted security mode is enabled. * * Restricted security mode is enabled when, on supported platforms, - * the semeru.restrictedsecurity system property is set or the system - * property semeru.fips is true. + * the semeru.customprofile system property is used to set a + * specific security profile or the semeru.fips system property is + * set to true. * * @return true if restricted security mode is enabled */ @@ -139,13 +207,16 @@ public static String getRandomAlgorithm() { /** * Check if the FIPS mode is enabled. * - * FIPS mode will be enabled when the semeru.fips system property is true, - * or semeru.restrictedsecurity system property is set by using FIPS policy. + * FIPS mode will be enabled when the semeru.fips system property is + * true, and the RestrictedSecurity mode has been successfully initialized. * * @return true if FIPS is enabled */ public static boolean isFIPSEnabled() { - return securityEnabled && (userSecurityNum == 1); + if (securityEnabled) { + return isFIPSEnabled; + } + return false; } /** @@ -198,6 +269,104 @@ public static boolean isProviderAllowed(Class providerClazz) { return true; } + /** + * Figure out the full profile ID. + * + * Use the default or user selected profile and attempt to find + * an appropriate entry in the java.security properties. + * + * If a profile cannot be found, or multiple defaults are discovered + * for a single profile, an appropriate message is printed and the + * system exits. + * + * @param props the java.security properties + */ + private static void getProfileID(Properties props) { + String potentialProfileID = "RestrictedSecurity." + selectedProfile; + + if (selectedProfile.indexOf(".") != -1) { + /* The default profile is used, or the user specified the + * full . + */ + if (debug != null) { + debug.println("Profile specified using full name (i.e., ): " + + selectedProfile); + } + for (Object keyObject : props.keySet()) { + if (keyObject instanceof String key) { + if (key.startsWith(potentialProfileID)) { + profileID = potentialProfileID; + return; + } + } + } + printStackTraceAndExit(selectedProfile + " is not present in the java.security file."); + } else { + /* The user specified the only the without + * indicating the part. + */ + if (debug != null) { + debug.println("Profile specified without version (i.e., ): " + + selectedProfile); + } + String defaultMatch = null; + for (Object keyObject : props.keySet()) { + if (keyObject instanceof String key) { + if (key.startsWith(potentialProfileID) && key.endsWith(".desc.default")) { + // Check if property is set to true. + if (Boolean.parseBoolean(props.getProperty(key))) { + // Check if multiple defaults exist and act accordingly. + if (defaultMatch == null) { + defaultMatch = key.split("\\.desc")[0]; + } else { + printStackTraceAndExit("Multiple default RestrictedSecurity" + + " profiles for " + selectedProfile); + } + } + } + } + } + if (defaultMatch == null) { + printStackTraceAndExit("No default RestrictedSecurity profile was found for " + + selectedProfile); + } else { + profileID = defaultMatch; + } + } + } + + private static void checkIfKnownProfileSupported() { + if (profileID.contains("NSS") && !isNSSSupported) { + printStackTraceAndExit("NSS RestrictedSecurity profiles are not supported" + + " on this platform."); + } + + if (profileID.contains("OpenJCEPlus") && !isOpenJCEPlusSupported) { + printStackTraceAndExit("OpenJCEPlus RestrictedSecurity profiles are not supported" + + " on this platform."); + } + + if (debug != null) { + debug.println("RestrictedSecurity profile " + profileID + + " is supported on this platform."); + } + } + + private static void checkFIPSCompatibility(Properties props) { + boolean isFIPSProfile = Boolean.parseBoolean(props.getProperty(profileID + ".desc.fips")); + if (isFIPSProfile) { + if (debug != null) { + debug.println("RestrictedSecurity profile " + profileID + + " is specified as FIPS compliant."); + } + isFIPSEnabled = true; + } else { + printStackTraceAndExit("RestrictedSecurity profile " + profileID + + " is not specified as FIPS compliant, but the semeru.fips" + + " system property is set to true."); + } + } + /** * Remove the security providers and only add restricted security providers. * @@ -210,23 +379,22 @@ public static boolean configure(Properties props) { printStackTraceAndExit("Restricted security mode is already initialized, it can't be initialized twice."); } - // Check if restricted security is supported on this platform. - if ((userEnabledFIPS || userEnabledSecurity) && !isSecuritySupported) { - printStackTraceAndExit("Restricted security mode is not supported on this platform."); - } - try { if (shouldEnableSecurity) { if (debug != null) { - debug.println("Restricted security mode detected, loading..."); + debug.println("Restricted security mode is being enabled..."); } - // Read and set user restricted security settings. - initUserSetting(); + getProfileID(props); + checkIfKnownProfileSupported(); + + // If user enabled FIPS, check whether chosen profile is applicable. + if (userEnabledFIPS) { + checkFIPSCompatibility(props); + } // Initialize restricted security properties from java.security file. - restricts = new RestrictedSecurityProperties(userSecurityNum, - props, userSecurityTrace, userSecurityAudit, userSecurityHelp); + restricts = new RestrictedSecurityProperties(profileID, props); // Restricted security properties checks. restrictsCheck(); @@ -249,11 +417,6 @@ public static boolean configure(Properties props) { // Add restricted security Properties. setProperties(props); - // Print out the Trace info. - if (userSecurityTrace) { - restricts.listTrace(); - } - if (debug != null) { debug.println("Restricted security mode loaded."); debug.println("Restricted security mode properties: " + props.toString()); @@ -270,46 +433,6 @@ public static boolean configure(Properties props) { return securityEnabled; } - /** - * Load user restricted security settings from system property. - */ - private static void initUserSetting() { - if (debug != null) { - debug.println("Loading user restricted security settings."); - } - - String[] inputs = userSecuritySetting.split(","); - - // For input ",," - if (inputs.length == 0) { - printStackTraceAndExit("User restricted security setting " + userSecuritySetting + " incorrect."); - } - - for (String input : inputs) { - String in = input.trim(); - if (in.equalsIgnoreCase("audit")) { - userSecurityAudit = true; - } else if (in.equalsIgnoreCase("help")) { - userSecurityHelp = true; - } else if (in.equalsIgnoreCase("trace")) { - userSecurityTrace = true; - } else { - try { - userSecurityNum = Integer.parseInt(in); - } catch (NumberFormatException e) { - printStackTraceAndExit("User restricted security setting " + userSecuritySetting + " incorrect."); - } - } - } - - if (debug != null) { - debug.println("Loaded user restricted security settings, with userSecurityNum: " + userSecurityNum - + " userSecurityTrace: " + userSecurityTrace - + " userSecurityAudit: " + userSecurityAudit - + " userSecurityHelp: " + userSecurityHelp); - } - } - /** * Add restricted security providers. * @@ -450,6 +573,8 @@ private static void printStackTraceAndExit(String message) { private static final class RestrictedSecurityProperties { private String descName; + private boolean descIsDefault; + private boolean descIsFIPS; private String descNumber; private String descPolicy; private String descSunsetDate; @@ -475,35 +600,25 @@ private static final class RestrictedSecurityProperties { // The map is keyed by provider name. private final Map providerConstraints; - private final int userSecurityNum; - private final boolean userSecurityTrace; - private final boolean userSecurityAudit; - private final boolean userSecurityHelp; - - private final String propsPrefix; + private final String profileID; // The java.security properties. private final Properties securityProps; /** * - * @param num the restricted security setting number + * @param id the restricted security custom profile ID * @param props the java.security properties * @param trace the user security trace * @param audit the user security audit * @param help the user security help */ - private RestrictedSecurityProperties(int num, Properties props, boolean trace, boolean audit, boolean help) { + private RestrictedSecurityProperties(String id, Properties props) { Objects.requireNonNull(props); - userSecurityNum = num; - userSecurityTrace = trace; - userSecurityAudit = audit; - userSecurityHelp = help; + profileID = id; securityProps = props; - propsPrefix = "RestrictedSecurity" + userSecurityNum; - providers = new ArrayList<>(); providersSimpleName = new ArrayList<>(); providerConstraints = new HashMap<>(); @@ -521,43 +636,28 @@ private void init() { } try { - // Print out the Help and Audit info. - if (userSecurityHelp || userSecurityAudit || userSecurityTrace) { - if (userSecurityHelp) { - printHelp(); - } - if (userSecurityAudit) { - listAudit(); - } - if (userSecurityNum == 0) { - if (userSecurityTrace) { - printStackTraceAndExit( - "Unable to list the trace info without specify the security policy number."); - } else { - if (debug != null) { - debug.println("Print out the info and exit."); - } - System.exit(0); - } - } - } - // Load restricted security providers from java.security properties. initProviders(); // Load restricted security properties from java.security properties. initProperties(); // Load restricted security provider constraints from java.security properties. initConstraints(); - - if (debug != null) { - debug.println("Initialized restricted security mode."); - } } catch (Exception e) { if (debug != null) { debug.println("Unable to initialize restricted security mode."); } printStackTraceAndExit(e); } + + if (debug != null) { + debug.println("Initialization of restricted security mode completed."); + + // Print all available restricted security profiles. + listAvailableProfiles(); + + // Print information of utilized security profile. + listUsedProfile(); + } } /** @@ -565,12 +665,12 @@ private void init() { */ private void initProviders() { if (debug != null) { - debug.println("Loading restricted security providers."); + debug.println("\tLoading providers of restricted security profile."); } for (int pNum = 1;; ++pNum) { String providerInfo = securityProps - .getProperty(propsPrefix + ".jce.provider." + pNum); + .getProperty(profileID + ".jce.provider." + pNum); if ((providerInfo == null) || providerInfo.trim().isEmpty()) { break; @@ -593,17 +693,15 @@ private void initProviders() { providerName = (pos < 0) ? providerName : providerName.substring(pos + 1, providerName.length()); // Provider without arguments and package names. providersSimpleName.add(pNum - 1, providerName); - - if (debug != null) { - debug.println( - "Loaded restricted security provider: " + providers.get(pNum - 1) - + " with simple name: " + providerName); - } } if (providers.isEmpty()) { printStackTraceAndExit( - "Restricted security mode provider list empty, or no such restricted security policy in java.security file."); + "No providers are specified as part of the Restricted Security profile."); + } + + if (debug != null) { + debug.println("\tProviders of restricted security profile successfully loaded."); } } @@ -612,38 +710,40 @@ private void initProviders() { */ private void initProperties() { if (debug != null) { - debug.println("Loading restricted security properties."); + debug.println("\tLoading properties of restricted security profile."); } - descName = parseProperty(securityProps.getProperty(propsPrefix + ".desc.name")); - descNumber = parseProperty(securityProps.getProperty(propsPrefix + ".desc.number")); - descPolicy = parseProperty(securityProps.getProperty(propsPrefix + ".desc.policy")); - descSunsetDate = parseProperty(securityProps.getProperty(propsPrefix + ".desc.sunsetDate")); + descName = parseProperty(securityProps.getProperty(profileID + ".desc.name")); + descIsDefault = Boolean.parseBoolean(parseProperty(securityProps.getProperty(profileID + ".desc.default"))); + descIsFIPS = Boolean.parseBoolean(parseProperty(securityProps.getProperty(profileID + ".desc.fips"))); + descNumber = parseProperty(securityProps.getProperty(profileID + ".desc.number")); + descPolicy = parseProperty(securityProps.getProperty(profileID + ".desc.policy")); + descSunsetDate = parseProperty(securityProps.getProperty(profileID + ".desc.sunsetDate")); jdkTlsDisabledNamedCurves = parseProperty( - securityProps.getProperty(propsPrefix + ".tls.disabledNamedCurves")); + securityProps.getProperty(profileID + ".tls.disabledNamedCurves")); jdkTlsDisabledAlgorithms = parseProperty( - securityProps.getProperty(propsPrefix + ".tls.disabledAlgorithms")); + securityProps.getProperty(profileID + ".tls.disabledAlgorithms")); jdkTlsDphemeralDHKeySize = parseProperty( - securityProps.getProperty(propsPrefix + ".tls.ephemeralDHKeySize")); + securityProps.getProperty(profileID + ".tls.ephemeralDHKeySize")); jdkTlsLegacyAlgorithms = parseProperty( - securityProps.getProperty(propsPrefix + ".tls.legacyAlgorithms")); + securityProps.getProperty(profileID + ".tls.legacyAlgorithms")); jdkCertpathDisabledAlgorithms = parseProperty( - securityProps.getProperty(propsPrefix + ".jce.certpath.disabledAlgorithms")); + securityProps.getProperty(profileID + ".jce.certpath.disabledAlgorithms")); jdkSecurityLegacyAlgorithm = parseProperty( - securityProps.getProperty(propsPrefix + ".jce.legacyAlgorithms")); + securityProps.getProperty(profileID + ".jce.legacyAlgorithms")); keyStoreType = parseProperty( - securityProps.getProperty(propsPrefix + ".keystore.type")); + securityProps.getProperty(profileID + ".keystore.type")); keyStore = parseProperty( - securityProps.getProperty(propsPrefix + ".javax.net.ssl.keyStore")); + securityProps.getProperty(profileID + ".javax.net.ssl.keyStore")); jdkSecureRandomProvider = parseProperty( - securityProps.getProperty(propsPrefix + ".securerandom.provider")); + securityProps.getProperty(profileID + ".securerandom.provider")); jdkSecureRandomAlgorithm = parseProperty( - securityProps.getProperty(propsPrefix + ".securerandom.algorithm")); + securityProps.getProperty(profileID + ".securerandom.algorithm")); if (debug != null) { - debug.println("Loaded restricted security properties."); + debug.println("\tProperties of restricted security profile successfully loaded."); } } @@ -655,19 +755,23 @@ private void initProperties() { * {Policy, JavaPolicy, *}, {CertPathValidator, *, *}]. */ private void initConstraints() { + if (debug != null) { + debug.println("\tLoading constraints of restricted security profile."); + } + for (int pNum = 1; pNum <= providersSimpleName.size(); pNum++) { String providerName = providersSimpleName.get(pNum - 1); String providerInfo = securityProps - .getProperty(propsPrefix + ".jce.provider." + pNum); + .getProperty(profileID + ".jce.provider." + pNum); if (debug != null) { - debug.println("Loading constraints for security provider: " + providerName); + debug.println("\t\tLoading constraints for security provider: " + providerName); } // Check if the provider has constraints. if (providerInfo.indexOf('[') < 0) { if (debug != null) { - debug.println("No constraints for security provider: " + providerName); + debug.println("\t\t\tNo constraints for security provider: " + providerName); } providerConstraints.put(providerName, new Constraint[0]); continue; @@ -723,22 +827,26 @@ private void initConstraints() { Constraint constraint = new Constraint(inType, inAlgorithm, inAttributes); if (debug != null) { - debug.println("Loading constraints for security provider: " + providerName - + " with constraints type: " + inType - + " algorithm: " + inAlgorithm - + " attributes: " + inAttributes); + debug.println("\t\t\tConstraint specified for security provider: " + providerName); + debug.println("\t\t\t\twith type: " + inType); + debug.println("\t\t\t\tfor algorithm: " + inAlgorithm); + debug.println("\t\t\t\twith attributes: " + inAttributes); } constraints[cNum] = constraint; cNum++; } providerConstraints.put(providerName, constraints); if (debug != null) { - debug.println("Loaded constraints for security provider: " + providerName); + debug.println("\t\tSuccessfully loaded constraints for security provider: " + providerName); } } else { printStackTraceAndExit("Constraint format is incorrect: " + providerInfo); } } + + if (debug != null) { + debug.println("\tAll constraints of restricted security profile successfully loaded."); + } } /** @@ -881,103 +989,104 @@ boolean isRestrictedProviderAllowed(String providerName) { } /** - * List audit info if userSecurityAudit is true, default as false. + * List audit info of all available RestrictedSecurity profiles. */ - private void listAudit() { + private void listAvailableProfiles() { System.out.println(); - System.out.println("Restricted Security Audit Info:"); - System.out.println("==============================="); - - for (int num = 1;; ++num) { - String desc = securityProps.getProperty("RestrictedSecurity" + num + ".desc.name"); - if ((desc == null) || desc.trim().isEmpty()) { - break; + System.out.println("Restricted Security Available Profiles' Info:"); + System.out.println("============================================="); + + Set availableProfiles = new HashSet<>(); + Pattern profileNamePattern = Pattern.compile("^(RestrictedSecurity\\.\\S+)\\.desc\\.name"); + for(Object securityFileObject : securityProps.keySet()) { + if (securityFileObject instanceof String key) { + Matcher profileMatcher = profileNamePattern.matcher(key); + if (profileMatcher.matches()) { + availableProfiles.add(profileMatcher.group(1)); + } } - System.out.println("RestrictedSecurity" + num + ".desc.name: " - + securityProps.getProperty("RestrictedSecurity" + num + ".desc.name")); - System.out.println("RestrictedSecurity" + num + ".desc.number: " - + parseProperty(securityProps.getProperty("RestrictedSecurity" + num + ".desc.number"))); - System.out.println("RestrictedSecurity" + num + ".desc.policy: " - + parseProperty(securityProps.getProperty("RestrictedSecurity" + num + ".desc.policy"))); - System.out.println("RestrictedSecurity" + num + ".desc.sunsetDate: " - + parseProperty(securityProps.getProperty("RestrictedSecurity" + num + ".desc.sunsetDate"))); - System.out.println(); + } + System.out.println("The available Restricted Security profiles:\n"); + + for (String availableProfile : availableProfiles) { + printProfile(availableProfile); } } /** - * List trace info if userSecurityTrace is true, default as false. + * List the RestrictedSecurity profile currently used. */ - void listTrace() { + private void listUsedProfile() { System.out.println(); - System.out.println("Restricted Security Trace Info:"); - System.out.println("==============================="); - System.out.println(propsPrefix + ".desc.name: " + descName); - System.out.println(propsPrefix + ".desc.number: " + descNumber); - System.out.println(propsPrefix + ".desc.policy: " + descPolicy); - System.out.println(propsPrefix + ".desc.sunsetDate: " + descSunsetDate); + System.out.println("Utilized Restricted Security Profile Info:"); + System.out.println("=========================================="); + System.out.println("The Restricted Security profile used is: " + profileID); System.out.println(); + printProfile(profileID); + } - // List restrictions. - System.out.println(propsPrefix + ".tls.disabledNamedCurves: " - + parseProperty(securityProps.getProperty("jdk.tls.disabledNamedCurves"))); - System.out.println(propsPrefix + ".tls.disabledAlgorithms: " - + parseProperty(securityProps.getProperty("jdk.tls.disabledAlgorithms"))); - System.out.println(propsPrefix + ".tls.ephemeralDHKeySize: " - + parseProperty(securityProps.getProperty("jdk.tls.ephemeralDHKeySize"))); - System.out.println(propsPrefix + ".tls.legacyAlgorithms: " - + parseProperty(securityProps.getProperty("jdk.tls.legacyAlgorithms"))); - System.out.println(propsPrefix + ".jce.certpath.disabledAlgorithms: " - + parseProperty(securityProps.getProperty("jdk.certpath.disabledAlgorithms"))); - System.out.println(propsPrefix + ".jce.legacyAlgorithms: " - + parseProperty(securityProps.getProperty("jdk.security.legacyAlgorithm"))); + private void printProfile(String profileToPrint) { + System.out.println(profileToPrint + " Profile Info:"); + System.out.println("=========================================="); + printProperty(profileToPrint + ".desc.name: ", + securityProps.getProperty(profileToPrint + ".desc.name")); + printProperty(profileToPrint + ".desc.default: ", + securityProps.getProperty(profileToPrint + ".desc.default")); + printProperty(profileToPrint + ".desc.fips: ", + securityProps.getProperty(profileToPrint + ".desc.fips")); + printProperty(profileToPrint + ".desc.number: ", + parseProperty(securityProps.getProperty(profileToPrint + ".desc.number"))); + printProperty(profileToPrint + ".desc.policy: ", + parseProperty(securityProps.getProperty(profileToPrint + ".desc.policy"))); + printProperty(profileToPrint + ".desc.sunsetDate: ", + parseProperty(securityProps.getProperty(profileToPrint + ".desc.sunsetDate"))); System.out.println(); - System.out.println(propsPrefix + ".keystore.type: " - + parseProperty(securityProps.getProperty("keystore.type"))); - System.out.println(propsPrefix + ".javax.net.ssl.keyStore: " - + keyStore); - System.out.println(propsPrefix + ".securerandom.provider: " - + jdkSecureRandomProvider); - System.out.println(propsPrefix + ".securerandom.algorithm: " - + jdkSecureRandomAlgorithm); - // List providers. - System.out.println(); - for (int pNum = 1; pNum <= providers.size(); pNum++) { - System.out.println(propsPrefix + ".jce.provider." + pNum + ": " - + providers.get(pNum - 1)); - } + System.out.println(profileToPrint + " Profile Providers:"); + System.out.println("==============================================="); + for (int pNum = 1;; ++pNum) { + String providerInfo = securityProps + .getProperty(profileToPrint + ".jce.provider." + pNum); + if ((providerInfo == null) || providerInfo.trim().isEmpty()) { + break; + } + printProperty(profileToPrint + ".jce.provider." + pNum + ": ", providerInfo); + } System.out.println(); - } - /** - * Print help info if userSecurityHelp is ture, default as false. - */ - private void printHelp() { + // List profile restrictions. + System.out.println(profileToPrint + " Profile Restrictions:"); + System.out.println("=================================================="); + printProperty(profileToPrint + ".tls.disabledNamedCurves: ", + parseProperty(securityProps.getProperty(profileToPrint + ".tls.disabledNamedCurves"))); + printProperty(profileToPrint + ".tls.disabledAlgorithms: ", + parseProperty(securityProps.getProperty(profileToPrint + ".tls.disabledAlgorithms"))); + printProperty(profileToPrint + ".tls.ephemeralDHKeySize: ", + parseProperty(securityProps.getProperty(profileToPrint + ".tls.ephemeralDHKeySize"))); + printProperty(profileToPrint + ".tls.legacyAlgorithms: ", + parseProperty(securityProps.getProperty(profileToPrint + ".tls.legacyAlgorithms"))); + printProperty(profileToPrint + ".jce.certpath.disabledAlgorithms: ", + parseProperty(securityProps.getProperty(profileToPrint + ".jce.certpath.disabledAlgorithms"))); + printProperty(profileToPrint + ".jce.legacyAlgorithms: ", + parseProperty(securityProps.getProperty(profileToPrint + ".jce.legacyAlgorithms"))); System.out.println(); - System.out.println("Restricted Security Mode Usage:"); - System.out.println("==============================="); - - System.out.println( - "-Dsemeru.restrictedsecurity= This flag will select the settings for the user " + - "specified restricted security policy."); - System.out.println( - "-Dsemeru.restrictedsecurity=audit This flag will list the name and number of all " + - "configured restricted security policies."); - System.out.println( - "-Dsemeru.restrictedsecurity=trace This flag will list all properties relevant to " + - "restricted security mode, including the existing default properties and " + - "restricted security properties."); - System.out.println("-Dsemeru.restrictedsecurity=help This flag will print help message."); + printProperty(profileToPrint + ".keystore.type: ", + parseProperty(securityProps.getProperty(profileToPrint + ".keystore.type"))); + printProperty(profileToPrint + ".javax.net.ssl.keyStore: ", + parseProperty(securityProps.getProperty(profileToPrint + ".javax.net.ssl.keyStore"))); + printProperty(profileToPrint + ".securerandom.provider: ", + parseProperty(securityProps.getProperty(profileToPrint + ".securerandom.provider"))); + printProperty(profileToPrint + ".securerandom.algorithm: ", + parseProperty(securityProps.getProperty(profileToPrint + ".securerandom.algorithm"))); System.out.println(); - System.out.println("e.g."); - System.out.println(" -Dsemeru.restrictedsecurity=1,trace,audit,help"); - System.out.println(" -Dsemeru.restrictedsecurity=help"); + } - System.out.println(); + private void printProperty(String name, String value) { + String valueToPrint = (value.isEmpty()) ? "NOT AVAILABLE" : value; + System.out.println(name + valueToPrint); } /** diff --git a/make/data/cacerts/emsigneccrootcag3 b/make/data/cacerts/emsigneccrootcag3 new file mode 100644 index 00000000000..a286f81c2f4 --- /dev/null +++ b/make/data/cacerts/emsigneccrootcag3 @@ -0,0 +1,22 @@ +Owner: CN=emSign ECC Root CA - G3, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Issuer: CN=emSign ECC Root CA - G3, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Serial number: 3cf607a968700eda8b84 +Valid from: Sun Feb 18 18:30:00 GMT 2018 until: Wed Feb 18 18:30:00 GMT 2043 +Signature algorithm name: SHA384withECDSA +Subject Public Key Algorithm: 384-bit EC (secp384r1) key +Version: 3 +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG +EwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo +bm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw +djAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0 +WXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS +fvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB +zhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq +hkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB +CUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD ++JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- diff --git a/make/data/cacerts/emsignrootcag1 b/make/data/cacerts/emsignrootcag1 new file mode 100644 index 00000000000..6b06f6689bc --- /dev/null +++ b/make/data/cacerts/emsignrootcag1 @@ -0,0 +1,29 @@ +Owner: CN=emSign Root CA - G1, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Issuer: CN=emSign Root CA - G1, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Serial number: 31f5e4620c6c58edd6d8 +Valid from: Sun Feb 18 18:30:00 GMT 2018 until: Wed Feb 18 18:30:00 GMT 2043 +Signature algorithm name: SHA256withRSA +Subject Public Key Algorithm: 2048-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD +VQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU +ZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH +MTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO +MRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv +Z2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz +f2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO +8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq +d7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM +tTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt +Od9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB +o0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD +AgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x +PaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM +wiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d +GNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH +6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby +RQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- diff --git a/make/data/cacerts/emsignrootcag2 b/make/data/cacerts/emsignrootcag2 new file mode 100644 index 00000000000..e4e4ddda65a --- /dev/null +++ b/make/data/cacerts/emsignrootcag2 @@ -0,0 +1,39 @@ +Owner: CN=emSign Root CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Issuer: CN=emSign Root CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN +Serial number: 864dbf0fe35ed77d8ed8 +Valid from: Sun Feb 18 18:30:00 GMT 2018 until: Wed Feb 18 18:30:00 GMT 2043 +Signature algorithm name: SHA384withRSA +Subject Public Key Algorithm: 4096-bit RSA key +Version: 3 +-----BEGIN CERTIFICATE----- +MIIFlTCCA32gAwIBAgILAIZNvw/jXtd9jtgwDQYJKoZIhvcNAQEMBQAwZzELMAkG +A1UEBhMCSU4xEzARBgNVBAsTCmVtU2lnbiBQS0kxJTAjBgNVBAoTHGVNdWRocmEg +VGVjaG5vbG9naWVzIExpbWl0ZWQxHDAaBgNVBAMTE2VtU2lnbiBSb290IENBIC0g +RzIwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBnMQswCQYDVQQGEwJJ +TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s +b2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBHMjCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMNwGIWW2kHfHK+sXTNwxF07K+IV +ySTuyFM2r1v002wUfcdT+zs5OM5QbMYFFnedXQI6gCFLsjKrcaej48Zt37OyEb3i +aPs7CsP4kAyTwzKH9aZe6gXYHrJq40/ZVMNcQVI2PcIp40B/SAN2gUZ+ZaUtIOvV +jEx26/ebNaXRIsthlkOG/caB+QRwDw1tl7338Zlv0M2oTBUy4B3e7dGP5pgXH71M +jqHPCoNo+xv9f0NTBT+hUDa8h8wUtcGQq9CDeJTpjWcD2bP2AMdVG6oVpMAUeUzo +cCyglvtFdUMjggxBbw4qhau1HXPG8Ot9hwL7ZMi8tkTzrvUIxxb8G9LF/7kKeCE7 +tGZaVzDTnXuifl3msR4ErHsQ4P7lVu2AIjIAhrAXoedDidb7pMcf7TABdrYUT1Jo +G/AiK+J9jO6GTjeADD4LMDSBZhHMuBK/PJ/g0kGBt+/C1L+/HURzQhJkMlRnM6Rv +XoCtfKopSlns5trZmTi971Wjbn88QXP61lGpBCUPwCjs7rpOYvSUJtI+lcbF+37q +kIqOXYkVT3cupDSpw+H89kFtj5GKY+Xny4LxY+3IvDIRiyd6ky1DPj713DI0yqve +EpsIr3A0PdwuyUI7CS1jg0NnGFT6Xxyr0xB+VDt83FJYW8v16k2pbaQ4kVxA3aXd +X9dZYyVR1S59KM75AgMBAAGjQjBAMB0GA1UdDgQWBBTt7E1FYRgo57MjKBEcTaUn +DV7s9DAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B +AQwFAAOCAgEACFC/ilQg8KTCVBxFJW/sazomkS0kNYbEIZg4B3obqwsJ7SX98z8Z +gfzBpz0nYClwwJjWbFN1R2zY8pCEot6/dgmA8Vbq0GxhwPM5YN/SZquNyRIxO3cU +dlAcwf+vSezdVCf9wOzvSAF3q0a5ljvbdbNJNpfScQVp7UUd5sBsZk8jXO1KQ/go +/Vf/GDPnrIFmxpAIGE3sgnO8lAv9FzUaAeuv7HWe47xN9J7+bQzF93yHuIXACPTL +pQHhg2zMv5C7BAbuDHfbj1Cu294Z832yhSfBcziWGskOvl3es2EcHytbS9c9P+0z +Mpka7zGC1FHrvLb/FoduH86TeZt0QjZ6pcplNzoaxDnDvzTJ6CC2Eny+qH/APFCu +VUv5/wjwF+HPm8Pup2ARj9cEp92+0qcerfHacNq5hMeGZdbA/dzdUR/5z5zXdxAk +nl8mcfGb0eMNSTXQmmB/i4AecNnr72uYjzlaXUGYN7Nrb6XouG0pnh0/BBtWWp0U +ShIPpWEAqs7RJBj6+1ZUYXZ4ObrCw962DxhN2p19Hxw9LtuUUcLqqTPrFXYvwO4t +ouj7KJnAkaTUfXGdEaFVtFig1EA30WzJY2X1vAQ7hVnniCjgaXAGqjsU6sklNM9n +xDx5rFCCCEtj9Kh8UHjGK2QqgP5kwgttjOApQMaCoezMfK4KD7WpOXU= +-----END CERTIFICATE----- diff --git a/make/jdk/src/classes/build/tools/makejavasecurity/MakeJavaSecurity.java b/make/jdk/src/classes/build/tools/makejavasecurity/MakeJavaSecurity.java index 963db0b593e..bb796be4335 100644 --- a/make/jdk/src/classes/build/tools/makejavasecurity/MakeJavaSecurity.java +++ b/make/jdk/src/classes/build/tools/makejavasecurity/MakeJavaSecurity.java @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2023, 2023 All Rights Reserved + * =========================================================================== + */ + package build.tools.makejavasecurity; import java.io.*; @@ -91,7 +97,8 @@ public static void main(String[] args) throws Exception { } // Filter out platform-unrelated ones. We only support - // #ifdef, #ifndef, #else, and #endif. Nesting not supported (yet). + // #ifdef, #ifndef, #else, #endif and #if defined A || B. + // Other Nesting not supported (yet). int mode = 0; // 0: out of block, 1: in match, 2: in non-match Iterator iter = lines.iterator(); while (iter.hasNext()) { @@ -113,6 +120,18 @@ public static void main(String[] args) throws Exception { mode = line.endsWith(args[2]) ? 2 : 1; } iter.remove(); + } else if (line.startsWith("#if defined ")) { + for (String l : line.split("\\|\\|")) { + if (l.indexOf('-') > 0) { + mode = l.trim().endsWith(args[2] + "-" + args[3]) ? 1 : 2; + } else { + mode = l.trim().endsWith(args[2]) ? 1 : 2; + } + if (mode == 1) { + break; + } + } + iter.remove(); } else if (line.startsWith("#else")) { if (mode == 0) { throw new IllegalStateException("#else not in #if block"); diff --git a/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java b/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java index 9353c515367..39f68ac953b 100644 --- a/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java +++ b/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java @@ -2553,7 +2553,7 @@ private static String toString(Set mods, String what) { private static int modsHashCode(Iterable> enums) { int h = 0; for (Enum e : enums) { - h += e.name().hashCode(); + h = h * 43 + Objects.hashCode(e.name()); } return h; } diff --git a/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java b/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java index c35e95b661b..af9cd69575f 100644 --- a/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/SessionTicketExtension.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -403,11 +403,13 @@ public byte[] produce(ConnectionContext context, chc.statelessResumption = true; // If resumption is not in progress, return an empty value - if (!chc.isResumption || chc.resumingSession == null) { + if (!chc.isResumption || chc.resumingSession == null + || chc.resumingSession.getPskIdentity() == null + || chc.resumingSession.getProtocolVersion().useTLS13PlusSpec()) { if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.fine("Stateless resumption supported"); } - return new SessionTicketSpec().getEncoded(); + return new byte[0]; } if (chc.localSupportedSignAlgs == null) { diff --git a/src/java.base/share/conf/security/java.security b/src/java.base/share/conf/security/java.security index 7fe0e69659b..f54c125eea7 100644 --- a/src/java.base/share/conf/security/java.security +++ b/src/java.base/share/conf/security/java.security @@ -82,17 +82,19 @@ security.provider.tbd=Apple #endif security.provider.tbd=SunPKCS11 -#ifdef linux-x86 +#if defined linux-x86 || defined linux-ppc || defined linux-s390 # # Java Restricted Security Mode # -RestrictedSecurity1.desc.name = Red Hat Enterprise Linux 8 NSS Cryptographic Module FIPS 140-2 -RestrictedSecurity1.desc.number = Certificate #4413 -RestrictedSecurity1.desc.policy = https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/4413 -RestrictedSecurity1.desc.sunsetDate = 2026-09-21 +RestrictedSecurity.NSS.140-2.desc.name = Red Hat Enterprise Linux 8 NSS Cryptographic Module FIPS 140-2 +RestrictedSecurity.NSS.140-2.desc.default = true +RestrictedSecurity.NSS.140-2.desc.fips = true +RestrictedSecurity.NSS.140-2.desc.number = Certificate #4413 +RestrictedSecurity.NSS.140-2.desc.policy = https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/4413 +RestrictedSecurity.NSS.140-2.desc.sunsetDate = 2026-09-21 -RestrictedSecurity1.tls.disabledNamedCurves = -RestrictedSecurity1.tls.disabledAlgorithms = \ +RestrictedSecurity.NSS.140-2.tls.disabledNamedCurves = +RestrictedSecurity.NSS.140-2.tls.disabledAlgorithms = \ SSLv3, \ TLS_AES_128_GCM_SHA256, \ TLS_AES_256_GCM_SHA384, \ @@ -123,29 +125,29 @@ RestrictedSecurity1.tls.disabledAlgorithms = \ TLSv1.1, \ X25519, \ X448 -RestrictedSecurity1.tls.ephemeralDHKeySize = -RestrictedSecurity1.tls.legacyAlgorithms = +RestrictedSecurity.NSS.140-2.tls.ephemeralDHKeySize = +RestrictedSecurity.NSS.140-2.tls.legacyAlgorithms = -RestrictedSecurity1.jce.certpath.disabledAlgorithms = -RestrictedSecurity1.jce.legacyAlgorithms = -RestrictedSecurity1.jce.provider.1 = SunPKCS11 ${java.home}/conf/security/nss.fips.cfg -RestrictedSecurity1.jce.provider.2 = SUN [{CertificateFactory, X.509, ImplementedIn=Software}, \ +RestrictedSecurity.NSS.140-2.jce.certpath.disabledAlgorithms = +RestrictedSecurity.NSS.140-2.jce.legacyAlgorithms = +RestrictedSecurity.NSS.140-2.jce.provider.1 = SunPKCS11 ${java.home}/conf/security/nss.fips.cfg +RestrictedSecurity.NSS.140-2.jce.provider.2 = SUN [{CertificateFactory, X.509, ImplementedIn=Software}, \ {CertStore, Collection, ImplementedIn=Software}, \ {CertStore, com.sun.security.IndexedCollection, ImplementedIn=Software}, \ {Policy, JavaPolicy, *}, {Configuration, JavaLoginConfig, *}, \ {CertPathBuilder, PKIX, ValidationAlgorithm=RFC5280:ImplementedIn=Software}, \ {CertPathValidator, PKIX, ValidationAlgorithm=RFC5280:ImplementedIn=Software}, \ {KeyStore, PKCS12, *}] -RestrictedSecurity1.jce.provider.3 = SunEC [{KeyFactory, EC, ImplementedIn=Software: \ +RestrictedSecurity.NSS.140-2.jce.provider.3 = SunEC [{KeyFactory, EC, ImplementedIn=Software: \ SupportedKeyClasses=java.security.interfaces.ECPublicKey|java.security.interfaces.ECPrivateKey: \ KeySize=256}, {AlgorithmParameters, EC, *}] -RestrictedSecurity1.jce.provider.4 = SunJSSE +RestrictedSecurity.NSS.140-2.jce.provider.4 = SunJSSE -RestrictedSecurity1.keystore.type = PKCS11 -RestrictedSecurity1.javax.net.ssl.keyStore = NONE +RestrictedSecurity.NSS.140-2.keystore.type = PKCS11 +RestrictedSecurity.NSS.140-2.javax.net.ssl.keyStore = NONE -RestrictedSecurity1.securerandom.provider = SunPKCS11-NSS-FIPS -RestrictedSecurity1.securerandom.algorithm = PKCS11 +RestrictedSecurity.NSS.140-2.securerandom.provider = SunPKCS11-NSS-FIPS +RestrictedSecurity.NSS.140-2.securerandom.algorithm = PKCS11 #endif # diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java index f8819d1f0c9..2ba4b6171c3 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Key.java @@ -126,7 +126,7 @@ abstract class P11Key implements Key, Length { } P11Key(String type, Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { + int keyLength, CK_ATTRIBUTE[] attrs) { this.type = type; this.token = session.token; this.algorithm = algorithm; @@ -134,15 +134,15 @@ abstract class P11Key implements Key, Length { boolean tokenObject = false; boolean sensitive = false; boolean extractable = true; - int n = (attributes == null) ? 0 : attributes.length; - for (int i = 0; i < n; i++) { - CK_ATTRIBUTE attr = attributes[i]; - if (attr.type == CKA_TOKEN) { - tokenObject = attr.getBoolean(); - } else if (attr.type == CKA_SENSITIVE) { - sensitive = attr.getBoolean(); - } else if (attr.type == CKA_EXTRACTABLE) { - extractable = attr.getBoolean(); + if (attrs != null) { + for (CK_ATTRIBUTE attr : attrs) { + if (attr.type == CKA_TOKEN) { + tokenObject = attr.getBoolean(); + } else if (attr.type == CKA_SENSITIVE) { + sensitive = attr.getBoolean(); + } else if (attr.type == CKA_EXTRACTABLE) { + extractable = attr.getBoolean(); + } } } this.tokenObject = tokenObject; @@ -259,7 +259,7 @@ protected Object writeReplace() throws ObjectStreamException { public String toString() { token.ensureValid(); String s1 = token.provider.getName() + " " + algorithm + " " + type - + " key, " + keyLength + " bits"; + + " key, " + keyLength + " bits "; s1 += (tokenObject ? "token" : "session") + " object"; if (isPublic()) { s1 += ")"; @@ -290,19 +290,31 @@ boolean isSecret() { return type == SECRET; } - void fetchAttributes(CK_ATTRIBUTE[] attributes) { + CK_ATTRIBUTE[] fetchAttributes(CK_ATTRIBUTE[] attrs) { + Objects.requireNonNull(attrs, "attrs must be non-null"); Session tempSession = null; long keyID = this.getKeyID(); try { tempSession = token.getOpSession(); token.p11.C_GetAttributeValue(tempSession.id(), keyID, - attributes); + attrs); } catch (PKCS11Exception e) { throw new ProviderException(e); } finally { this.releaseKeyID(); token.releaseSession(tempSession); } + return attrs; + } + + // convenience method which returns the attribute values as BigInteger[] + BigInteger[] fetchAttributesAsInts(CK_ATTRIBUTE[] attrs) { + attrs = fetchAttributes(attrs); + BigInteger[] res = new BigInteger[attrs.length]; + for (int i = 0; i < attrs.length; i++) { + res[i] = attrs[i].getBigInteger(); + } + return res; } private static final CK_ATTRIBUTE[] A0 = new CK_ATTRIBUTE[0]; @@ -341,21 +353,21 @@ private static CK_ATTRIBUTE[] getAttributes(Session session, long keyID, } static SecretKey secretKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - attributes = getAttributes(session, keyID, attributes, new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_TOKEN), - new CK_ATTRIBUTE(CKA_SENSITIVE), - new CK_ATTRIBUTE(CKA_EXTRACTABLE), + int keyLength, CK_ATTRIBUTE[] attrs) { + attrs = getAttributes(session, keyID, attrs, new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_TOKEN), + new CK_ATTRIBUTE(CKA_SENSITIVE), + new CK_ATTRIBUTE(CKA_EXTRACTABLE), }); if ((SunPKCS11.mysunpkcs11 != null) && !SunPKCS11.isExportWrapKey.get() && ("AES".equals(algorithm) || "TripleDES".equals(algorithm)) ) { - if (attributes[0].getBoolean() || attributes[1].getBoolean() || (attributes[2].getBoolean() == false)) { + if (attrs[0].getBoolean() || attrs[1].getBoolean() || (attrs[2].getBoolean() == false)) { try { - byte[] key = SunPKCS11.mysunpkcs11.exportKey(session.id(), attributes, keyID); + byte[] key = SunPKCS11.mysunpkcs11.exportKey(session.id(), attrs, keyID); SecretKey secretKey = new SecretKeySpec(key, algorithm); - return new P11SecretKeyFIPS(session, keyID, algorithm, keyLength, attributes, secretKey); + return new P11SecretKeyFIPS(session, keyID, algorithm, keyLength, attrs, secretKey); } catch (PKCS11Exception e) { // Attempt failed, create a P11SecretKey object. if (debug != null) { @@ -365,38 +377,37 @@ static SecretKey secretKey(Session session, long keyID, String algorithm, } } - return new P11SecretKey(session, keyID, algorithm, keyLength, - attributes); + return new P11SecretKey(session, keyID, algorithm, keyLength, attrs); } - static SecretKey masterSecretKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes, int major, int minor) { - attributes = getAttributes(session, keyID, attributes, new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_TOKEN), - new CK_ATTRIBUTE(CKA_SENSITIVE), - new CK_ATTRIBUTE(CKA_EXTRACTABLE), + static SecretKey masterSecretKey(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs, + int major, int minor) { + attrs = getAttributes(session, keyID, attrs, new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_TOKEN), + new CK_ATTRIBUTE(CKA_SENSITIVE), + new CK_ATTRIBUTE(CKA_EXTRACTABLE), }); - return new P11TlsMasterSecretKey( - session, keyID, algorithm, keyLength, attributes, major, - minor); + return new P11TlsMasterSecretKey(session, keyID, algorithm, keyLength, + attrs, major, minor); } // we assume that all components of public keys are always accessible static PublicKey publicKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { + int keyLength, CK_ATTRIBUTE[] attrs) { switch (algorithm) { case "RSA": return new P11RSAPublicKey(session, keyID, algorithm, - keyLength, attributes); + keyLength, attrs); case "DSA": return new P11DSAPublicKey(session, keyID, algorithm, - keyLength, attributes); + keyLength, attrs); case "DH": return new P11DHPublicKey(session, keyID, algorithm, - keyLength, attributes); + keyLength, attrs); case "EC": return new P11ECPublicKey(session, keyID, algorithm, - keyLength, attributes); + keyLength, attrs); default: throw new ProviderException ("Unknown public key algorithm " + algorithm); @@ -404,24 +415,24 @@ static PublicKey publicKey(Session session, long keyID, String algorithm, } static PrivateKey privateKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - attributes = getAttributes(session, keyID, attributes, new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_TOKEN), - new CK_ATTRIBUTE(CKA_SENSITIVE), - new CK_ATTRIBUTE(CKA_EXTRACTABLE), + int keyLength, CK_ATTRIBUTE[] attrs) { + attrs = getAttributes(session, keyID, attrs, new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_TOKEN), + new CK_ATTRIBUTE(CKA_SENSITIVE), + new CK_ATTRIBUTE(CKA_EXTRACTABLE), }); - boolean keySensitive = (attributes[0].getBoolean() || - attributes[1].getBoolean() || !attributes[2].getBoolean()); + boolean keySensitive = (attrs[0].getBoolean() || + attrs[1].getBoolean() || !attrs[2].getBoolean()); if (keySensitive && (SunPKCS11.mysunpkcs11 != null) && "RSA".equals(algorithm)) { try { - byte[] key = SunPKCS11.mysunpkcs11.exportKey(session.id(), attributes, keyID); + byte[] key = SunPKCS11.mysunpkcs11.exportKey(session.id(), attrs, keyID); RSAPrivateKey rsaPrivKey = RSAPrivateCrtKeyImpl.newKey(KeyType.RSA, "PKCS#8", key); if (rsaPrivKey instanceof RSAPrivateCrtKeyImpl privImpl) { - return new P11RSAPrivateKeyFIPS(session, keyID, algorithm, keyLength, attributes, privImpl); + return new P11RSAPrivateKeyFIPS(session, keyID, algorithm, keyLength, attrs, privImpl); } else { - return new P11RSAPrivateNonCRTKeyFIPS(session, keyID, algorithm, keyLength, attributes, rsaPrivKey); + return new P11RSAPrivateNonCRTKeyFIPS(session, keyID, algorithm, keyLength, attrs, rsaPrivKey); } } catch (PKCS11Exception | InvalidKeyException e) { // Attempt failed, create a P11PrivateKey object. @@ -433,9 +444,9 @@ static PrivateKey privateKey(Session session, long keyID, String algorithm, if (keySensitive && (SunPKCS11.mysunpkcs11 != null) && "EC".equals(algorithm)) { try { - byte[] key = SunPKCS11.mysunpkcs11.exportKey(session.id(), attributes, keyID); + byte[] key = SunPKCS11.mysunpkcs11.exportKey(session.id(), attrs, keyID); ECPrivateKey ecPrivKey = ECUtil.decodePKCS8ECPrivateKey(key); - return new P11ECPrivateKeyFIPS(session, keyID, algorithm, keyLength, attributes, ecPrivKey); + return new P11ECPrivateKeyFIPS(session, keyID, algorithm, keyLength, attrs, ecPrivKey); } catch (PKCS11Exception | InvalidKeySpecException e) { // Attempt failed, create a P11PrivateKey object. if (debug != null) { @@ -444,67 +455,35 @@ static PrivateKey privateKey(Session session, long keyID, String algorithm, } } - if (attributes[1].getBoolean() || (attributes[2].getBoolean() == false)) { - return new P11PrivateKey - (session, keyID, algorithm, keyLength, attributes); - } else { - switch (algorithm) { - case "RSA": - // In order to decide if this is RSA CRT key, we first query - // and see if all extra CRT attributes are available. - CK_ATTRIBUTE[] attrs2 = new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_PUBLIC_EXPONENT), - new CK_ATTRIBUTE(CKA_PRIME_1), - new CK_ATTRIBUTE(CKA_PRIME_2), - new CK_ATTRIBUTE(CKA_EXPONENT_1), - new CK_ATTRIBUTE(CKA_EXPONENT_2), - new CK_ATTRIBUTE(CKA_COEFFICIENT), - }; - boolean crtKey; - try { - session.token.p11.C_GetAttributeValue - (session.id(), keyID, attrs2); - crtKey = ((attrs2[0].pValue instanceof byte[]) && - (attrs2[1].pValue instanceof byte[]) && - (attrs2[2].pValue instanceof byte[]) && - (attrs2[3].pValue instanceof byte[]) && - (attrs2[4].pValue instanceof byte[]) && - (attrs2[5].pValue instanceof byte[])) ; - } catch (PKCS11Exception e) { - // ignore, assume not available - crtKey = false; - } - if (crtKey) { - return new P11RSAPrivateKey(session, keyID, algorithm, - keyLength, attributes, attrs2); - } else { - return new P11RSAPrivateNonCRTKey(session, keyID, - algorithm, keyLength, attributes); - } - case "DSA": - return new P11DSAPrivateKey(session, keyID, algorithm, - keyLength, attributes); - case "DH": - return new P11DHPrivateKey(session, keyID, algorithm, - keyLength, attributes); - case "EC": - return new P11ECPrivateKey(session, keyID, algorithm, - keyLength, attributes); - default: - throw new ProviderException - ("Unknown private key algorithm " + algorithm); - } + switch (algorithm) { + case "RSA": + return P11RSAPrivateKeyInternal.of(session, keyID, algorithm, + keyLength, attrs, keySensitive); + case "DSA": + return P11DSAPrivateKeyInternal.of(session, keyID, algorithm, + keyLength, attrs, keySensitive); + case "DH": + return P11DHPrivateKeyInternal.of(session, keyID, algorithm, + keyLength, attrs, keySensitive); + case "EC": + return P11ECPrivateKeyInternal.of(session, keyID, algorithm, + keyLength, attrs, keySensitive); + default: + throw new ProviderException + ("Unknown private key algorithm " + algorithm); } } - // class for sensitive and unextractable private keys - private static final class P11PrivateKey extends P11Key - implements PrivateKey { + // base class for all PKCS11 private keys + private static abstract class P11PrivateKey extends P11Key implements + PrivateKey { private static final long serialVersionUID = -2138581185214187615L; + protected byte[] encoded; // guard by synchronized + P11PrivateKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PRIVATE, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(PRIVATE, session, keyID, algorithm, keyLength, attrs); } // XXX temporary encoding for serialization purposes public String getFormat() { @@ -542,11 +521,14 @@ byte[] getEncodedInternal() { private static class P11SecretKey extends P11Key implements SecretKey { private static final long serialVersionUID = -7828241727014329084L; - private volatile byte[] encoded; + + private volatile byte[] encoded; // guard by double-checked locking + P11SecretKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(SECRET, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(SECRET, session, keyID, algorithm, keyLength, attrs); } + public String getFormat() { token.ensureValid(); if (sensitive || !extractable || (isNSS && tokenObject)) { @@ -555,32 +537,21 @@ public String getFormat() { return "RAW"; } } + byte[] getEncodedInternal() { token.ensureValid(); if (getFormat() == null) { return null; } + byte[] b = encoded; if (b == null) { synchronized (this) { b = encoded; if (b == null) { - Session tempSession = null; - long keyID = this.getKeyID(); - try { - tempSession = token.getOpSession(); - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { + b = fetchAttributes(new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_VALUE), - }; - token.p11.C_GetAttributeValue - (tempSession.id(), keyID, attributes); - b = attributes[0].getByteArray(); - } catch (PKCS11Exception e) { - throw new ProviderException(e); - } finally { - this.releaseKeyID(); - token.releaseSession(tempSession); - } + })[0].getByteArray(); encoded = b; } } @@ -589,6 +560,19 @@ byte[] getEncodedInternal() { } } + // base class for all PKCS11 public keys + private static abstract class P11PublicKey extends P11Key implements + PublicKey { + private static final long serialVersionUID = 1L; + + protected byte[] encoded; // guard by synchronized + + P11PublicKey(Session session, long keyID, String algorithm, + int keyLength, CK_ATTRIBUTE[] attrs) { + super(PUBLIC, session, keyID, algorithm, keyLength, attrs); + } + } + @SuppressWarnings("deprecation") private static class P11TlsMasterSecretKey extends P11SecretKey implements TlsMasterSecret { @@ -596,8 +580,8 @@ private static class P11TlsMasterSecretKey extends P11SecretKey private final int majorVersion, minorVersion; P11TlsMasterSecretKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes, int major, int minor) { - super(session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs, int major, int minor) { + super(session, keyID, algorithm, keyLength, attrs); this.majorVersion = major; this.minorVersion = minor; } @@ -674,17 +658,92 @@ public BigInteger getCrtCoefficient() { } } + // impl class for sensitive/unextractable RSA private keys + static class P11RSAPrivateKeyInternal extends P11PrivateKey { + private static final long serialVersionUID = -2138581185214187615L; + + static P11RSAPrivateKeyInternal of(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs, + boolean keySensitive) { + if (keySensitive) { + return new P11RSAPrivateKeyInternal(session, keyID, algorithm, + keyLength, attrs); + } else { + CK_ATTRIBUTE[] rsaAttrs = new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_MODULUS), + new CK_ATTRIBUTE(CKA_PRIVATE_EXPONENT), + new CK_ATTRIBUTE(CKA_PUBLIC_EXPONENT), + new CK_ATTRIBUTE(CKA_PRIME_1), + new CK_ATTRIBUTE(CKA_PRIME_2), + new CK_ATTRIBUTE(CKA_EXPONENT_1), + new CK_ATTRIBUTE(CKA_EXPONENT_2), + new CK_ATTRIBUTE(CKA_COEFFICIENT), + }; + boolean isCRT = true; + Session tempSession = null; + try { + tempSession = session.token.getOpSession(); + session.token.p11.C_GetAttributeValue(tempSession.id(), + keyID, rsaAttrs); + for (CK_ATTRIBUTE attr : rsaAttrs) { + isCRT &= (attr.pValue instanceof byte[]); + if (!isCRT) break; + } + } catch (PKCS11Exception e) { + // ignore, assume not available + isCRT = false; + } finally { + session.token.releaseSession(tempSession); + } + BigInteger n = rsaAttrs[0].getBigInteger(); + BigInteger d = rsaAttrs[1].getBigInteger(); + if (isCRT) { + return new P11RSAPrivateKey(session, keyID, algorithm, + keyLength, attrs, n, d, + Arrays.copyOfRange(rsaAttrs, 2, rsaAttrs.length)); + } else { + return new P11RSAPrivateNonCRTKey(session, keyID, + algorithm, keyLength, attrs, n, d); + } + } + } + + protected transient BigInteger n; + + private P11RSAPrivateKeyInternal(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); + } + + private synchronized void fetchValues() { + token.ensureValid(); + if (n != null) return; + + n = fetchAttributesAsInts(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_MODULUS) + })[0]; + } + + public BigInteger getModulus() { + fetchValues(); + return n; + } + } + // RSA CRT private key - private static final class P11RSAPrivateKey extends P11Key - implements RSAPrivateCrtKey { + private static final class P11RSAPrivateKey extends P11RSAPrivateKeyInternal + implements RSAPrivateCrtKey { private static final long serialVersionUID = 9215872438913515220L; - private BigInteger n, e, d, p, q, pe, qe, coeff; - private byte[] encoded; - P11RSAPrivateKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attrs, CK_ATTRIBUTE[] crtAttrs) { - super(PRIVATE, session, keyID, algorithm, keyLength, attrs); + private transient BigInteger e, d, p, q, pe, qe, coeff; + + private P11RSAPrivateKey(Session session, long keyID, String algorithm, + int keyLength, CK_ATTRIBUTE[] attrs, BigInteger n, BigInteger d, + CK_ATTRIBUTE[] crtAttrs) { + super(session, keyID, algorithm, keyLength, attrs); + this.n = n; + this.d = d; for (CK_ATTRIBUTE a : crtAttrs) { if (a.type == CKA_PUBLIC_EXPONENT) { e = a.getBigInteger(); @@ -701,28 +760,15 @@ private static final class P11RSAPrivateKey extends P11Key } } } - private synchronized void fetchValues() { - token.ensureValid(); - if (n != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_MODULUS), - new CK_ATTRIBUTE(CKA_PRIVATE_EXPONENT), - }; - fetchAttributes(attributes); - n = attributes[0].getBigInteger(); - d = attributes[1].getBigInteger(); - } public String getFormat() { token.ensureValid(); return "PKCS#8"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { - fetchValues(); try { Key newKey = RSAPrivateCrtKeyImpl.newKey (KeyType.RSA, null, n, e, d, p, q, pe, qe, coeff); @@ -733,15 +779,15 @@ synchronized byte[] getEncodedInternal() { } return encoded; } + + @Override public BigInteger getModulus() { - fetchValues(); return n; } public BigInteger getPublicExponent() { return e; } public BigInteger getPrivateExponent() { - fetchValues(); return d; } public BigInteger getPrimeP() { @@ -796,37 +842,28 @@ public BigInteger getPrivateExponent() { } // RSA non-CRT private key - private static final class P11RSAPrivateNonCRTKey extends P11Key - implements RSAPrivateKey { + private static final class P11RSAPrivateNonCRTKey extends + P11RSAPrivateKeyInternal implements RSAPrivateKey { private static final long serialVersionUID = 1137764983777411481L; - private BigInteger n, d; - private byte[] encoded; + private transient BigInteger d; + P11RSAPrivateNonCRTKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PRIVATE, session, keyID, algorithm, keyLength, attributes); - } - private synchronized void fetchValues() { - token.ensureValid(); - if (n != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_MODULUS), - new CK_ATTRIBUTE(CKA_PRIVATE_EXPONENT), - }; - fetchAttributes(attributes); - n = attributes[0].getBigInteger(); - d = attributes[1].getBigInteger(); + int keyLength, CK_ATTRIBUTE[] attrs, BigInteger n, + BigInteger d) { + super(session, keyID, algorithm, keyLength, attrs); + this.n = n; + this.d = d; } + public String getFormat() { token.ensureValid(); return "PKCS#8"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { - fetchValues(); try { // XXX make constructor in SunRsaSign provider public // and call it directly @@ -840,42 +877,43 @@ synchronized byte[] getEncodedInternal() { } return encoded; } + + @Override public BigInteger getModulus() { - fetchValues(); return n; } public BigInteger getPrivateExponent() { - fetchValues(); return d; } } - private static final class P11RSAPublicKey extends P11Key + private static final class P11RSAPublicKey extends P11PublicKey implements RSAPublicKey { private static final long serialVersionUID = -826726289023854455L; - private BigInteger n, e; - private byte[] encoded; + private transient BigInteger n, e; + P11RSAPublicKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PUBLIC, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (n != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { + if (n != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_MODULUS), - new CK_ATTRIBUTE(CKA_PUBLIC_EXPONENT), - }; - fetchAttributes(attributes); - n = attributes[0].getBigInteger(); - e = attributes[1].getBigInteger(); + new CK_ATTRIBUTE(CKA_PUBLIC_EXPONENT) + }); + n = res[0]; + e = res[1]; } + public String getFormat() { token.ensureValid(); return "X.509"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { @@ -889,6 +927,7 @@ synchronized byte[] getEncodedInternal() { } return encoded; } + public BigInteger getModulus() { fetchValues(); return n; @@ -904,40 +943,37 @@ public String toString() { } } - private static final class P11DSAPublicKey extends P11Key + private static final class P11DSAPublicKey extends P11PublicKey implements DSAPublicKey { private static final long serialVersionUID = 5989753793316396637L; - private BigInteger y; - private DSAParams params; - private byte[] encoded; + private transient BigInteger y; + private transient DSAParams params; + P11DSAPublicKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PUBLIC, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (y != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { + if (y != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_VALUE), new CK_ATTRIBUTE(CKA_PRIME), new CK_ATTRIBUTE(CKA_SUBPRIME), - new CK_ATTRIBUTE(CKA_BASE), - }; - fetchAttributes(attributes); - y = attributes[0].getBigInteger(); - params = new DSAParameterSpec( - attributes[1].getBigInteger(), - attributes[2].getBigInteger(), - attributes[3].getBigInteger() - ); + new CK_ATTRIBUTE(CKA_BASE) + }); + y = res[0]; + params = new DSAParameterSpec(res[1], res[2], res[3]); } + public String getFormat() { token.ensureValid(); return "X.509"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { @@ -967,40 +1003,76 @@ public String toString() { } } - private static final class P11DSAPrivateKey extends P11Key - implements DSAPrivateKey { + static class P11DSAPrivateKeyInternal extends P11PrivateKey { + private static final long serialVersionUID = 3119629997181999389L; + + protected transient DSAParams params; + + static P11DSAPrivateKeyInternal of(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs, + boolean keySensitive) { + if (keySensitive) { + return new P11DSAPrivateKeyInternal(session, keyID, algorithm, + keyLength, attrs); + } else { + return new P11DSAPrivateKey(session, keyID, algorithm, + keyLength, attrs); + } + } + + private P11DSAPrivateKeyInternal(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); + } + + private synchronized void fetchValues() { + token.ensureValid(); + if (params != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_PRIME), + new CK_ATTRIBUTE(CKA_SUBPRIME), + new CK_ATTRIBUTE(CKA_BASE), + }); + params = new DSAParameterSpec(res[0], res[1], res[2]); + } + + protected DSAParams getParams() { + fetchValues(); + return params; + } + } + + private static final class P11DSAPrivateKey extends P11DSAPrivateKeyInternal + implements DSAPrivateKey { private static final long serialVersionUID = 3119629997181999389L; - private BigInteger x; - private DSAParams params; - private byte[] encoded; + private transient BigInteger x; // params inside P11DSAPrivateKeyInternal + P11DSAPrivateKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PRIVATE, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (x != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_VALUE), - new CK_ATTRIBUTE(CKA_PRIME), - new CK_ATTRIBUTE(CKA_SUBPRIME), - new CK_ATTRIBUTE(CKA_BASE), - }; - fetchAttributes(attributes); - x = attributes[0].getBigInteger(); - params = new DSAParameterSpec( - attributes[1].getBigInteger(), - attributes[2].getBigInteger(), - attributes[3].getBigInteger() - ); + if (x != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_VALUE), + new CK_ATTRIBUTE(CKA_PRIME), + new CK_ATTRIBUTE(CKA_SUBPRIME), + new CK_ATTRIBUTE(CKA_BASE), + }); + x = res[0]; + params = new DSAParameterSpec(res[1], res[2], res[3]); } + public String getFormat() { token.ensureValid(); return "PKCS#8"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { @@ -1011,48 +1083,87 @@ synchronized byte[] getEncodedInternal() { } return encoded; } + public BigInteger getX() { fetchValues(); return x; } + + @Override public DSAParams getParams() { fetchValues(); return params; } } - private static final class P11DHPrivateKey extends P11Key + static class P11DHPrivateKeyInternal extends P11PrivateKey { + private static final long serialVersionUID = 1L; + + protected transient DHParameterSpec params; + + static P11DHPrivateKeyInternal of(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs, + boolean keySensitive) { + if (keySensitive) { + return new P11DHPrivateKeyInternal(session, keyID, algorithm, + keyLength, attrs); + } else { + return new P11DHPrivateKey(session, keyID, algorithm, + keyLength, attrs); + } + } + + private P11DHPrivateKeyInternal(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); + } + + private synchronized void fetchValues() { + token.ensureValid(); + if (params != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_PRIME), + new CK_ATTRIBUTE(CKA_BASE), + }); + params = new DHParameterSpec(res[0], res[1]); + } + + public DHParameterSpec getParams() { + fetchValues(); + return params; + } + } + + private static final class P11DHPrivateKey extends P11DHPrivateKeyInternal implements DHPrivateKey { private static final long serialVersionUID = -1698576167364928838L; - private BigInteger x; - private DHParameterSpec params; - private byte[] encoded; + private transient BigInteger x; // params in P11DHPrivateKeyInternal + P11DHPrivateKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PRIVATE, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (x != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_VALUE), - new CK_ATTRIBUTE(CKA_PRIME), - new CK_ATTRIBUTE(CKA_BASE), - }; - fetchAttributes(attributes); - x = attributes[0].getBigInteger(); - params = new DHParameterSpec( - attributes[1].getBigInteger(), - attributes[2].getBigInteger() - ); + if (x != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_VALUE), + new CK_ATTRIBUTE(CKA_PRIME), + new CK_ATTRIBUTE(CKA_BASE), + }); + x = res[0]; + params = new DHParameterSpec(res[1], res[2]); } + public String getFormat() { token.ensureValid(); return "PKCS#8"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { @@ -1079,10 +1190,10 @@ public DHParameterSpec getParams() { return params; } public int hashCode() { + fetchValues(); if (!token.isValid()) { return 0; } - fetchValues(); return Objects.hash(x, params.getP(), params.getG()); } public boolean equals(Object obj) { @@ -1103,38 +1214,36 @@ public boolean equals(Object obj) { } } - private static final class P11DHPublicKey extends P11Key + private static final class P11DHPublicKey extends P11PublicKey implements DHPublicKey { static final long serialVersionUID = -598383872153843657L; - private BigInteger y; - private DHParameterSpec params; - private byte[] encoded; + private transient BigInteger y; + private transient DHParameterSpec params; + P11DHPublicKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PUBLIC, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (y != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { - new CK_ATTRIBUTE(CKA_VALUE), - new CK_ATTRIBUTE(CKA_PRIME), - new CK_ATTRIBUTE(CKA_BASE), - }; - fetchAttributes(attributes); - y = attributes[0].getBigInteger(); - params = new DHParameterSpec( - attributes[1].getBigInteger(), - attributes[2].getBigInteger() - ); + if (y != null) return; + + BigInteger[] res = fetchAttributesAsInts(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_VALUE), + new CK_ATTRIBUTE(CKA_PRIME), + new CK_ATTRIBUTE(CKA_BASE), + }); + y = res[0]; + params = new DHParameterSpec(res[1], res[2]); } + public String getFormat() { token.ensureValid(); return "X.509"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { @@ -1223,44 +1332,88 @@ public ECParameterSpec getParams() { } } - private static final class P11ECPrivateKey extends P11Key + static class P11ECPrivateKeyInternal extends P11PrivateKey { + + private static final long serialVersionUID = 1L; + + protected transient ECParameterSpec params; + + static P11ECPrivateKeyInternal of(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs, + boolean keySensitive) { + if (keySensitive) { + return new P11ECPrivateKeyInternal(session, keyID, algorithm, + keyLength, attrs); + } else { + return new P11ECPrivateKey(session, keyID, algorithm, + keyLength, attrs); + } + } + + private P11ECPrivateKeyInternal(Session session, long keyID, + String algorithm, int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); + } + + private synchronized void fetchValues() { + token.ensureValid(); + if (params != null) return; + + try { + byte[] paramBytes = fetchAttributes(new CK_ATTRIBUTE[] { + new CK_ATTRIBUTE(CKA_EC_PARAMS) + })[0].getByteArray(); + + params = P11ECKeyFactory.decodeParameters(paramBytes); + } catch (Exception e) { + throw new RuntimeException("Could not parse key values", e); + } + } + + protected ECParameterSpec getParams() { + fetchValues(); + return params; + } + } + + private static final class P11ECPrivateKey extends P11ECPrivateKeyInternal implements ECPrivateKey { private static final long serialVersionUID = -7786054399510515515L; - private BigInteger s; - private ECParameterSpec params; - private byte[] encoded; + private transient BigInteger s; // params in P11ECPrivateKeyInternal + P11ECPrivateKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PRIVATE, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (s != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { + if (s != null) return; + + CK_ATTRIBUTE[] attrs = fetchAttributes(new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_VALUE), - new CK_ATTRIBUTE(CKA_EC_PARAMS, params), - }; - fetchAttributes(attributes); - s = attributes[0].getBigInteger(); + new CK_ATTRIBUTE(CKA_EC_PARAMS), + }); + + s = attrs[0].getBigInteger(); try { params = P11ECKeyFactory.decodeParameters - (attributes[1].getByteArray()); + (attrs[1].getByteArray()); } catch (Exception e) { throw new RuntimeException("Could not parse key values", e); } } + public String getFormat() { token.ensureValid(); return "PKCS#8"; } + synchronized byte[] getEncodedInternal() { - token.ensureValid(); if (encoded == null) { - fetchValues(); try { + fetchValues(); Key key = ECUtil.generateECPrivateKey(s, params); encoded = key.getEncoded(); } catch (InvalidKeySpecException e) { @@ -1269,42 +1422,43 @@ synchronized byte[] getEncodedInternal() { } return encoded; } + public BigInteger getS() { fetchValues(); return s; } + public ECParameterSpec getParams() { fetchValues(); return params; } } - private static final class P11ECPublicKey extends P11Key + private static final class P11ECPublicKey extends P11PublicKey implements ECPublicKey { private static final long serialVersionUID = -6371481375154806089L; - private ECPoint w; - private ECParameterSpec params; - private byte[] encoded; + private transient ECPoint w; + private transient ECParameterSpec params; + P11ECPublicKey(Session session, long keyID, String algorithm, - int keyLength, CK_ATTRIBUTE[] attributes) { - super(PUBLIC, session, keyID, algorithm, keyLength, attributes); + int keyLength, CK_ATTRIBUTE[] attrs) { + super(session, keyID, algorithm, keyLength, attrs); } + private synchronized void fetchValues() { token.ensureValid(); - if (w != null) { - return; - } - CK_ATTRIBUTE[] attributes = new CK_ATTRIBUTE[] { + if (w != null) return; + + CK_ATTRIBUTE[] attrs = fetchAttributes(new CK_ATTRIBUTE[] { new CK_ATTRIBUTE(CKA_EC_POINT), new CK_ATTRIBUTE(CKA_EC_PARAMS), - }; - fetchAttributes(attributes); + }); try { params = P11ECKeyFactory.decodeParameters - (attributes[1].getByteArray()); - byte[] ecKey = attributes[0].getByteArray(); + (attrs[1].getByteArray()); + byte[] ecKey = attrs[0].getByteArray(); // Check whether the X9.63 encoding of an EC point is wrapped // in an ASN.1 OCTET STRING @@ -1326,10 +1480,12 @@ private synchronized void fetchValues() { throw new RuntimeException("Could not parse key values", e); } } + public String getFormat() { token.ensureValid(); return "X.509"; } + synchronized byte[] getEncodedInternal() { token.ensureValid(); if (encoded == null) { @@ -1628,3 +1784,4 @@ void dispose() { this.clear(); } } + diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Signature.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Signature.java index ae6c852b3c2..606ad16dd9a 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Signature.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/P11Signature.java @@ -124,6 +124,9 @@ final class P11Signature extends SignatureSpi { // key instance used, if init*() was called private P11Key p11Key; + // signature length expected or 0 for unknown + private int sigLen; + // message digest, if we do the digesting ourselves private final MessageDigest md; @@ -300,7 +303,7 @@ private void cancelOperation() { try { if (mode == M_SIGN) { if (type == T_UPDATE) { - token.p11.C_SignFinal(session.id(), 0); + token.p11.C_SignFinal(session.id(), sigLen); } else { byte[] digest; if (type == T_DIGEST) { @@ -311,12 +314,7 @@ private void cancelOperation() { token.p11.C_Sign(session.id(), digest); } } else { // M_VERIFY - byte[] signature; - if (mechanism == CKM_DSA) { - signature = new byte[64]; // assume N = 256 - } else { - signature = new byte[(p11Key.length() + 7) >> 3]; - } + byte[] signature = new byte[sigLen]; if (type == T_UPDATE) { token.p11.C_VerifyFinal(session.id(), signature); } else { @@ -388,6 +386,15 @@ private void initialize() { md.reset(); } } + sigLen = 0; + if ("DSA".equals(p11Key.getAlgorithm())) { + if (p11Key instanceof P11Key.P11DSAPrivateKeyInternal) { + sigLen = ((P11Key.P11DSAPrivateKeyInternal)p11Key).getParams() + .getQ().bitLength() >> 2; + } else if (p11Key instanceof DSAKey) { + sigLen = ((DSAKey)p11Key).getParams().getQ().bitLength() >> 2; + } + } initialized = true; } @@ -641,7 +648,7 @@ protected byte[] engineSign() throws SignatureException { try { byte[] signature; if (type == T_UPDATE) { - signature = token.p11.C_SignFinal(session.id(), 0); + signature = token.p11.C_SignFinal(session.id(), sigLen); } else { byte[] digest; if (type == T_DIGEST) { @@ -708,7 +715,7 @@ protected boolean engineVerify(byte[] signature) throws SignatureException { try { if (!p1363Format) { if (keyAlgorithm.equals("DSA")) { - signature = asn1ToDSA(signature); + signature = asn1ToDSA(signature, sigLen); } else if (keyAlgorithm.equals("EC")) { signature = asn1ToECDSA(signature); } @@ -832,7 +839,8 @@ private static byte[] dsaToASN1(byte[] signature) { } } - private static byte[] asn1ToDSA(byte[] sig) throws SignatureException { + private static byte[] asn1ToDSA(byte[] sig, int sigLen) + throws SignatureException { try { // Enforce strict DER checking for signatures DerInputStream in = new DerInputStream(sig, 0, sig.length, false); @@ -847,8 +855,8 @@ private static byte[] asn1ToDSA(byte[] sig) throws SignatureException { BigInteger r = values[0].getPositiveBigInteger(); BigInteger s = values[1].getPositiveBigInteger(); - byte[] br = toByteArray(r, 20); - byte[] bs = toByteArray(s, 20); + byte[] br = toByteArray(r, sigLen/2); + byte[] bs = toByteArray(s, sigLen/2); if ((br == null) || (bs == null)) { throw new SignatureException("Out of range value for R or S"); } @@ -945,3 +953,4 @@ protected AlgorithmParameters engineGetParameters() { return null; } } + diff --git a/test/hotspot/jtreg/compiler/locks/TestUnlockOSR.java b/test/hotspot/jtreg/compiler/locks/TestUnlockOSR.java new file mode 100644 index 00000000000..f2133b49658 --- /dev/null +++ b/test/hotspot/jtreg/compiler/locks/TestUnlockOSR.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2023 SAP SE. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +/* + * @test + * @bug 8316746 + * @summary During OSR, locks get transferred from interpreter frame. + * Check that unlocking 2 such locks works in the OSR compiled nmethod. + * Some platforms verify that the unlocking happens in the corrent order. + * + * @run main/othervm -Xbatch TestUnlockOSR + */ + +public class TestUnlockOSR { + static void test_method(Object a, Object b, int limit) { + synchronized(a) { // allocate space for monitors + synchronized(b) { + } + } // free space to test allocation in reused space + synchronized(a) { // reuse the space + synchronized(b) { + for (int i = 0; i < limit; i++) {} + } + } + } + + public static void main(String[] args) { + Object a = new TestUnlockOSR(), + b = new TestUnlockOSR(); + // avoid uncommon trap before last unlocks + for (int i = 0; i < 100; i++) { test_method(a, b, 0); } + // trigger OSR + test_method(a, b, 100000); + } +} diff --git a/test/hotspot/jtreg/gc/stress/TestStressRSetCoarsening.java b/test/hotspot/jtreg/gc/stress/TestStressRSetCoarsening.java index b8916416902..22077376236 100644 --- a/test/hotspot/jtreg/gc/stress/TestStressRSetCoarsening.java +++ b/test/hotspot/jtreg/gc/stress/TestStressRSetCoarsening.java @@ -27,13 +27,12 @@ import jdk.test.whitebox.WhiteBox; /* - * @test TestStressRSetCoarsening.java + * @test * @key stress * @bug 8146984 8147087 * @requires vm.gc.G1 * @requires os.maxMemory > 3G * @requires vm.opt.MaxGCPauseMillis == "null" - * * @summary Stress G1 Remembered Set by creating a lot of cross region links * @modules java.base/jdk.internal.misc * @library /test/lib @@ -42,27 +41,82 @@ * @run main/othervm/timeout=300 * -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UseG1GC -Xlog:gc* -XX:MaxGCPauseMillis=1000 - * -Xmx500m -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 1 0 300 + * -Xmx500m -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 1 0 300 + */ + +/* + * @test + * @requires vm.gc.G1 + * @requires os.maxMemory > 3G + * @requires vm.opt.MaxGCPauseMillis == "null" + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run main/othervm/timeout=300 * -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UseG1GC -Xlog:gc* -XX:MaxGCPauseMillis=1000 - * -Xmx500m -XX:G1HeapRegionSize=8m gc.stress.TestStressRSetCoarsening 1 10 300 + * -Xmx500m -XX:G1HeapRegionSize=8m gc.stress.TestStressRSetCoarsening 1 10 300 + */ + +/* + * @test + * @requires vm.gc.G1 + * @requires os.maxMemory > 3G + * @requires vm.opt.MaxGCPauseMillis == "null" + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run main/othervm/timeout=300 * -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UseG1GC -Xlog:gc* -XX:MaxGCPauseMillis=1000 * -Xmx500m -XX:G1HeapRegionSize=32m gc.stress.TestStressRSetCoarsening 42 10 300 + */ + +/* + * @test + * @requires vm.gc.G1 + * @requires os.maxMemory > 3G + * @requires vm.opt.MaxGCPauseMillis == "null" + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run main/othervm/timeout=300 * -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UseG1GC -Xlog:gc* -XX:MaxGCPauseMillis=1000 - * -Xmx500m -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 2 0 300 + * -Xmx500m -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 2 0 300 + */ + +/* + * @test + * @requires vm.gc.G1 + * @requires os.maxMemory > 3G + * @requires vm.opt.MaxGCPauseMillis == "null" + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run main/othervm/timeout=1800 * -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UseG1GC -Xlog:gc* -XX:MaxGCPauseMillis=1000 - * -Xmx1G -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 500 0 1800 + * -Xmx1G -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 500 0 1800 + */ + +/* + * @test + * @requires vm.gc.G1 + * @requires os.maxMemory > 3G + * @requires vm.opt.MaxGCPauseMillis == "null" + * @modules java.base/jdk.internal.misc + * @library /test/lib + * @build jdk.test.whitebox.WhiteBox + * @run driver jdk.test.lib.helpers.ClassFileInstaller jdk.test.whitebox.WhiteBox * @run main/othervm/timeout=1800 * -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI * -XX:+UseG1GC -Xlog:gc* -XX:MaxGCPauseMillis=1000 - * -Xmx1G -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 10 10 1800 + * -Xmx1G -XX:G1HeapRegionSize=1m gc.stress.TestStressRSetCoarsening 10 10 1800 */ /** @@ -95,7 +149,7 @@ public static void main(String... args) throws InterruptedException { } int objectsPerRegion = Integer.parseInt(args[0]); // 1 means humongous int regsToRefresh = Integer.parseInt(args[1]); // 0 means no regions to refresh at the end of cycle - int timeout = Integer.parseInt(args[2]); // in seconds, test should stop working eariler + int timeout = Integer.parseInt(args[2]); // in seconds, test should stop working earlier new TestStressRSetCoarsening(objectsPerRegion, regsToRefresh, timeout).go(); } diff --git a/test/hotspot/jtreg/runtime/os/HugePageConfiguration.java b/test/hotspot/jtreg/runtime/os/HugePageConfiguration.java index a0590b7739d..f475af4c2de 100644 --- a/test/hotspot/jtreg/runtime/os/HugePageConfiguration.java +++ b/test/hotspot/jtreg/runtime/os/HugePageConfiguration.java @@ -30,17 +30,46 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +// This class allows us to parse system hugepage config from +// - a) the Operating System (the truth) +// - b) the JVM log (-Xlog:pagesize) +// This is used e.g. in TestHugePageDetection to determine if the JVM detects the correct settings from the OS. class HugePageConfiguration { - Set _staticHugePageSizes; - long _staticDefaultHugePageSize; + public static class StaticHugePageConfig implements Comparable { + public long pageSize = -1; + public long nr_hugepages = -1; + public long nr_overcommit_hugepages = -1; - enum THPMode {always, never, madvise, unknown} + @Override + public int hashCode() { + return Objects.hash(pageSize); + } + + @Override + public String toString() { + return "StaticHugePageConfig{" + + "pageSize=" + pageSize + + ", nr_hugepages=" + nr_hugepages + + ", nr_overcommit_hugepages=" + nr_overcommit_hugepages + + '}'; + } + + @Override + public int compareTo(StaticHugePageConfig o) { + return (int) (pageSize - o.pageSize); + } + } + + Set _staticHugePageConfigurations; + long _staticDefaultHugePageSize = -1; + + enum THPMode {always, never, madvise} THPMode _thpMode; long _thpPageSize; - public Set getStaticHugePageSizes() { - return _staticHugePageSizes; + public Set getStaticHugePageConfigurations() { + return _staticHugePageConfigurations; } public long getStaticDefaultHugePageSize() { @@ -55,8 +84,18 @@ public long getThpPageSize() { return _thpPageSize; } - public HugePageConfiguration(Set _staticHugePageSizes, long _staticDefaultHugePageSize, THPMode _thpMode, long _thpPageSize) { - this._staticHugePageSizes = _staticHugePageSizes; + // Returns true if the THP support is enabled + public boolean supportsTHP() { + return _thpMode == THPMode.always || _thpMode == THPMode.madvise; + } + + // Returns true if static huge pages are supported (whether or not we have configured the pools) + public boolean supportsStaticHugePages() { + return _staticDefaultHugePageSize > 0 && _staticHugePageConfigurations.size() > 0; + } + + public HugePageConfiguration(Set _staticHugePageConfigurations, long _staticDefaultHugePageSize, THPMode _thpMode, long _thpPageSize) { + this._staticHugePageConfigurations = _staticHugePageConfigurations; this._staticDefaultHugePageSize = _staticDefaultHugePageSize; this._thpMode = _thpMode; this._thpPageSize = _thpPageSize; @@ -65,7 +104,7 @@ public HugePageConfiguration(Set _staticHugePageSizes, long _staticDefault @Override public String toString() { return "Configuration{" + - "_staticHugePageSizes=" + _staticHugePageSizes + + "_staticHugePageConfigurations=" + _staticHugePageConfigurations + ", _staticDefaultHugePageSize=" + _staticDefaultHugePageSize + ", _thpMode=" + _thpMode + ", _thpPageSize=" + _thpPageSize + @@ -77,12 +116,8 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HugePageConfiguration that = (HugePageConfiguration) o; - return _staticDefaultHugePageSize == that._staticDefaultHugePageSize && _thpPageSize == that._thpPageSize && Objects.equals(_staticHugePageSizes, that._staticHugePageSizes) && _thpMode == that._thpMode; - } - - @Override - public int hashCode() { - return Objects.hash(_staticHugePageSizes, _staticDefaultHugePageSize, _thpMode, _thpPageSize); + return _staticDefaultHugePageSize == that._staticDefaultHugePageSize && _thpPageSize == that._thpPageSize && + Objects.equals(_staticHugePageConfigurations, that._staticHugePageConfigurations) && _thpMode == that._thpMode; } private static long readDefaultHugePageSizeFromOS() { @@ -102,25 +137,36 @@ private static long readDefaultHugePageSizeFromOS() { return 0; } - private static Set readSupportedHugePagesFromOS() { - TreeSet pagesizes = new TreeSet<>(); + private static Set readSupportedHugePagesFromOS() throws IOException { + TreeSet hugePageConfigs = new TreeSet<>(); Pattern pat = Pattern.compile("hugepages-(\\d+)kB"); File[] subdirs = new File("/sys/kernel/mm/hugepages").listFiles(); if (subdirs != null) { - for (File f : subdirs) { - String name = f.getName(); + for (File subdir : subdirs) { + String name = subdir.getName(); Matcher mat = pat.matcher(name); if (mat.matches()) { - long pagesize = Long.parseLong(mat.group(1)) * 1024; - pagesizes.add(pagesize); + StaticHugePageConfig config = new StaticHugePageConfig(); + config.pageSize = Long.parseLong(mat.group(1)) * 1024; + try (FileReader fr = new FileReader(subdir.getAbsolutePath() + "/nr_hugepages"); + BufferedReader reader = new BufferedReader(fr)) { + String s = reader.readLine(); + config.nr_hugepages = Long.parseLong(s); + } + try (FileReader fr = new FileReader(subdir.getAbsolutePath() + "/nr_overcommit_hugepages"); + BufferedReader reader = new BufferedReader(fr)) { + String s = reader.readLine(); + config.nr_overcommit_hugepages = Long.parseLong(s); + } + hugePageConfigs.add(config); } } } - return pagesizes; + return hugePageConfigs; } private static THPMode readTHPModeFromOS() { - THPMode mode = THPMode.unknown; + THPMode mode = THPMode.never; String file = "/sys/kernel/mm/transparent_hugepage/enabled"; try (FileReader fr = new FileReader(file); BufferedReader reader = new BufferedReader(fr)) { @@ -136,7 +182,8 @@ private static THPMode readTHPModeFromOS() { } } catch (IOException e) { System.out.println("Failed to read " + file); - mode = THPMode.unknown; + // Happens when the kernel is not built to support THPs. + mode = THPMode.never; } return mode; } @@ -148,19 +195,19 @@ private static long readTHPPageSizeFromOS() { BufferedReader reader = new BufferedReader(fr)) { String s = reader.readLine(); pagesize = Long.parseLong(s); - } catch (IOException | NumberFormatException e) { /* ignored */ } + } catch (IOException | NumberFormatException e) { } // ignored return pagesize; } // Fill object with info read from proc file system - public static HugePageConfiguration readFromOS() { + public static HugePageConfiguration readFromOS() throws IOException { return new HugePageConfiguration(readSupportedHugePagesFromOS(), readDefaultHugePageSizeFromOS(), readTHPModeFromOS(), readTHPPageSizeFromOS()); } - private static long parseSIUnit(String num, String unit) { + public static long parseSIUnit(String num, String unit) { long n = Long.parseLong(num); return switch (unit) { case "K" -> n * 1024; @@ -180,7 +227,7 @@ public static HugePageConfiguration readFromJVMLog(OutputAnalyzer output) { // [0.001s][info][pagesize] Transparent hugepage (THP) support: // [0.001s][info][pagesize] THP mode: madvise // [0.001s][info][pagesize] THP pagesize: 2M - TreeSet hugepages = new TreeSet<>(); + TreeSet staticHugePageConfigs = new TreeSet<>(); long defaultHugepageSize = 0; THPMode thpMode = THPMode.never; long thpPageSize = 0; @@ -192,7 +239,9 @@ public static HugePageConfiguration readFromJVMLog(OutputAnalyzer output) { for (String s : lines) { Matcher mat = patternHugepageSize.matcher(s); if (mat.matches()) { - hugepages.add(parseSIUnit(mat.group(1), mat.group(2))); + StaticHugePageConfig config = new StaticHugePageConfig(); + config.pageSize = parseSIUnit(mat.group(1), mat.group(2)); + staticHugePageConfigs.add(config); continue; } if (defaultHugepageSize == 0) { @@ -215,7 +264,7 @@ public static HugePageConfiguration readFromJVMLog(OutputAnalyzer output) { } } - return new HugePageConfiguration(hugepages, defaultHugepageSize, thpMode, thpPageSize); + return new HugePageConfiguration(staticHugePageConfigs, defaultHugepageSize, thpMode, thpPageSize); } } diff --git a/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java b/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java new file mode 100644 index 00000000000..e93309c0b00 --- /dev/null +++ b/test/hotspot/jtreg/runtime/os/TestHugePageDecisionsAtVMStartup.java @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, Red Hat Inc. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test id=Default + * @summary Test JVM large page setup (default options) + * @library /test/lib + * @requires os.family == "linux" + * @modules java.base/jdk.internal.misc + * java.management + * @run driver TestHugePageDecisionsAtVMStartup + */ + +/* + * @test id=LP_enabled + * @summary Test JVM large page setup (+LP) + * @library /test/lib + * @requires os.family == "linux" + * @modules java.base/jdk.internal.misc + * java.management + * @run driver TestHugePageDecisionsAtVMStartup -XX:+UseLargePages + */ + +/* + * @test id=THP_enabled + * @summary Test JVM large page setup (+THP) + * @library /test/lib + * @requires os.family == "linux" + * @modules java.base/jdk.internal.misc + * java.management + * @run driver TestHugePageDecisionsAtVMStartup -XX:+UseTransparentHugePages + */ + +import jdk.test.lib.process.OutputAnalyzer; +import jdk.test.lib.process.ProcessTools; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +public class TestHugePageDecisionsAtVMStartup { + + // End user warnings, printing with Xlog:pagesize at warning level, should be unconditional + static final String warningNoTHP = "[warning][pagesize] UseTransparentHugePages disabled, transparent huge pages are not supported by the operating system."; + static final String warningNoLP = "[warning][pagesize] UseLargePages disabled, no large pages configured and available on the system."; + + static final String buildSizeString(long l) { + String units[] = { "K", "M", "G" }; + long factor = 1024 * 1024 * 1024; + for (int i = 2; i >= 0; i--) { + if (l >= factor) { + return Long.toString(l / factor) + units[i]; + } + factor /= 1024; + } + return Long.toString(l) + "B"; + } + + static void testOutput(boolean useLP, boolean useTHP, OutputAnalyzer out, HugePageConfiguration configuration) { + + // Note: If something goes wrong, the JVM warns but continues, so we should never see an exit value != 0 + out.shouldHaveExitValue(0); + + // Static hugepages: + // Let X = the default hugepage size of the system (the one in /proc/meminfo). + // The JVM will cycle through page sizes, starting at X, down to the smallest hugepage size. + // + // Example 1: a system with 1GB and 2MB pages, the default hugepage size is 1GB (can only be done + // via kernel parameter). the JVM should first attempt to use 1GB pages, failing that should try 2MB, failing + // that give up and disable -UseLargePages. + // + // Example 1: same system, but the default hugepage size is 2MB. The JVM should not attempt to use 1GB pages. + // + // This picture gets more complex with -XX:LargePageSizeInBytes, which overrides the default + // large page size; but we ignore this for now (feel free to extend the test to cover LBSiB too). + + boolean haveUsableStaticHugePages = false; + if (configuration.supportsStaticHugePages()) { + long defaultLargePageSize = configuration.getStaticDefaultHugePageSize(); + Set configs = configuration.getStaticHugePageConfigurations(); + for (HugePageConfiguration.StaticHugePageConfig config: configs) { + if (config.pageSize <= defaultLargePageSize) { + if (config.nr_hugepages > 0 || config.nr_overcommit_hugepages > 0) { + haveUsableStaticHugePages = true; break; + } + } + } + } + + if (useTHP && !useLP) { + useLP = true; // its implicit + } + + if (!useLP) { + out.shouldContain("[info][pagesize] Large page support disabled"); + } else if (useLP && !useTHP && + (!configuration.supportsStaticHugePages() || !haveUsableStaticHugePages)) { + out.shouldContain(warningNoLP); + } else if (useLP && useTHP && !configuration.supportsTHP()) { + out.shouldContain(warningNoTHP); + } else if (useLP && !useTHP && + configuration.supportsStaticHugePages() && haveUsableStaticHugePages) { + out.shouldContain("[info][pagesize] Using the default large page size: " + buildSizeString(configuration.getStaticDefaultHugePageSize())); + out.shouldContain("[info][pagesize] UseLargePages=1, UseTransparentHugePages=0"); + out.shouldContain("[info][pagesize] Large page support enabled"); + } else if (useLP && useTHP && configuration.supportsTHP()) { + String thpPageSizeString = buildSizeString(configuration.getThpPageSize()); + // We expect to see exactly two "Usable page sizes" : the system page size and the THP page size. The system + // page size differs, but its always in KB). + out.shouldContain("[info][pagesize] UseLargePages=1, UseTransparentHugePages=1"); + out.shouldMatch(".*\\[info]\\[pagesize] Large page support enabled. Usable page sizes: \\d+[kK], " + thpPageSizeString + ". Default large page size: " + thpPageSizeString + ".*"); + } + } + + public static void main(String[] extraOptions) throws Exception { + List allOptions = new ArrayList(); + if (extraOptions != null) { + allOptions.addAll(Arrays.asList(extraOptions)); + } + allOptions.add("-Xmx128m"); + allOptions.add("-Xlog:pagesize"); + allOptions.add("-version"); + + boolean useLP = allOptions.contains("-XX:+UseLargePages"); + boolean useTHP = allOptions.contains("-XX:+UseTransparentHugePages"); + System.out.println("useLP: " + useLP + " useTHP: " + useTHP); + + ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(allOptions.toArray(new String[0])); + OutputAnalyzer output = new OutputAnalyzer(pb.start()); + output.reportDiagnosticSummary(); + HugePageConfiguration configuration = HugePageConfiguration.readFromOS(); + System.out.println("configuration read from OS:" + configuration); + + testOutput(useLP, useTHP, output, configuration); + } +} diff --git a/test/jdk/java/lang/module/ModuleDescriptorHashCodeTest.java b/test/jdk/java/lang/module/ModuleDescriptorHashCodeTest.java new file mode 100644 index 00000000000..78b124d8701 --- /dev/null +++ b/test/jdk/java/lang/module/ModuleDescriptorHashCodeTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.module.ModuleDescriptor; +import java.util.Set; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotSame; + +/** + * @test + * @bug 8275509 + * @run testng ModuleDescriptorHashCodeTest + * @run testng/othervm -Xshare:off ModuleDescriptorHashCodeTest + * @summary Tests the ModuleDescriptor.hashCode() for boot layer modules + */ +public class ModuleDescriptorHashCodeTest { + + /** + * Verifies that the ModuleDescriptor.hashCode() returned by a boot layer module is + * the same as that returned by a ModuleDescriptor constructed from the ModuleDescriptor.Builder + * for the same module. + */ + @Test + public void testBootModuleDescriptor() throws Exception { + Set bootModules = ModuleLayer.boot().modules(); + for (Module bootModule : bootModules) { + System.out.println("Testing module descriptor of boot module " + bootModule); + ModuleDescriptor bootMD = bootModule.getDescriptor(); + ModuleDescriptor mdFromBuilder = fromModuleInfoClass(bootModule); + // verify that this object is indeed a different object instance than the boot module descriptor + // to prevent any artificial passing of the test + assertNotSame(mdFromBuilder, bootMD, "ModuleDescriptor loaded from boot layer and " + + "one created from module-info.class unexpectedly returned the same instance"); + assertEquals(mdFromBuilder.hashCode(), bootMD.hashCode(), + "Unexpected ModuleDescriptor.hashCode() for " + mdFromBuilder); + assertEquals(mdFromBuilder.compareTo(bootMD), 0, + "Unexpected ModuleDescriptor.compareTo() for " + mdFromBuilder); + } + } + + // Returns a ModuleDescriptor parsed out of the module-info.class of the passed Module + private static ModuleDescriptor fromModuleInfoClass(Module module) throws IOException { + try (InputStream moduleInfo = module.getResourceAsStream("module-info.class")) { + if (moduleInfo == null) { + throw new RuntimeException("Could not locate module-info.class in " + module); + } + // internally calls ModuleDescriptor.Builder + return ModuleDescriptor.read(moduleInfo); + } + } +} diff --git a/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java b/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java index fbb62441e1c..3e70af733fb 100644 --- a/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java +++ b/test/jdk/javax/net/ssl/SSLSession/ResumeTLS13withSNI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ /* * @test - * @bug 8211806 8277881 + * @bug 8211806 8277881 8277307 * @summary TLS 1.3 handshake server name indication is missing on a session resume * @run main/othervm ResumeTLS13withSNI */ @@ -102,7 +102,7 @@ public static void main(String args[]) throws Exception { SSLParameters cliSSLParams = clientEngine.getSSLParameters(); cliSSLParams.setServerNames(List.of(SNI_NAME)); clientEngine.setSSLParameters(cliSSLParams); - clientEngine.setEnabledProtocols(new String[] { "TLSv1.3" }); + clientEngine.setEnabledProtocols(new String[] { "TLSv1.2", "TLSv1.3" }); SSLEngine serverEngine = makeEngine(sslCtx, kmf, tmf, false); SSLParameters servSSLParams = serverEngine.getSSLParameters(); @@ -114,7 +114,7 @@ public static void main(String args[]) throws Exception { // Create a new client-side engine which can initiate TLS session // resumption SSLEngine newCliEngine = makeEngine(sslCtx, kmf, tmf, true); - newCliEngine.setEnabledProtocols(new String[] { "TLSv1.3" }); + newCliEngine.setEnabledProtocols(new String[] { "TLSv1.2", "TLSv1.3" }); ByteBuffer resCliHello = getResumptionClientHello(newCliEngine); dumpBuffer("Resumed ClientHello Data", resCliHello); @@ -394,6 +394,16 @@ private static void checkResumedClientHelloSNI(ByteBuffer resCliHello) System.err.println("* Found pre_shared_key Extension"); resCliHello.position(resCliHello.position() + extLen); break; + case 35: // session_ticket + // This is a TLS1.2 extension; should be empty since we're + // negotiating TLS1.3. See JDK-8277307 + System.err.format("* Found session_ticket extension " + + "(%d bytes)\n", extLen); + if (extLen != 0) { + throw new Exception("Unexpected session_ticket content"); + } + resCliHello.position(resCliHello.position() + extLen); + break; default: System.err.format("* Found extension %d (%d bytes)\n", extType, extLen); diff --git a/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java b/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java index 62157256422..b5bb698e458 100644 --- a/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java +++ b/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java @@ -431,6 +431,26 @@ * @run main/othervm -Djava.security.debug=certpath CAInterop teliarootcav2 CRL */ +/* + * @test id=emsignrootcag1 + * @bug 8319187 + * @summary Interoperability tests with eMudhra Root CA G1 + * @library /test/lib + * @build jtreg.SkippedException ValidatePathWithURL CAInterop + * @run main/othervm -Djava.security.debug=certpath,ocsp CAInterop emsignrootcag1 OCSP + * @run main/othervm -Djava.security.debug=certpath CAInterop emsignrootcag1 CRL + */ + +/* + * @test id=emsigneccrootcag3 + * @bug 8319187 + * @summary Interoperability tests with eMudhra ECC Root CA G3 + * @library /test/lib + * @build jtreg.SkippedException ValidatePathWithURL CAInterop + * @run main/othervm -Djava.security.debug=certpath,ocsp CAInterop emsigneccrootcag3 OCSP + * @run main/othervm -Djava.security.debug=certpath CAInterop emsigneccrootcag3 CRL + */ + /** * Collection of certificate validation tests for interoperability with external CAs */ @@ -586,6 +606,13 @@ private CATestURLs getTestURLs(String alias) { new CATestURLs("https://juolukka.cover.telia.fi:10600", "https://juolukka.cover.telia.fi:10601"); + case "emsignrootcag1" -> + new CATestURLs("https://testovg1.emsign.com/RootOVG1.html", + "https://testovg1r.emsign.com/RootOVG1MR.html"); + case "emsigneccrootcag3" -> + new CATestURLs("https://testovg3.emsign.com/RootOVG3.html", + "https://testovg3r.emsign.com/RootOVG3MR.html"); + default -> throw new RuntimeException("No test setup found for: " + alias); }; } diff --git a/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java b/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java new file mode 100644 index 00000000000..8f5df9cce75 --- /dev/null +++ b/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/EmSignRootG2CA.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8319187 + * @summary Interoperability tests with eMudhra emSign Root CA G2 CS root + * @build ValidatePathWithParams + * @run main/othervm -Djava.security.debug=certpath EmSignRootG2CA OCSP + * @run main/othervm -Djava.security.debug=certpath EmSignRootG2CA CRL + */ + +public class EmSignRootG2CA { + + // Owner: CN=emSign CS CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Issuer: CN=emSign Root CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Serial number: c084e666596139a1fa9b + // Valid from: Sun Feb 18 10:30:00 PST 2018 until: Fri Feb 18 10:30:00 PST 2033 + private static final String INT = "-----BEGIN CERTIFICATE-----\n" + + "MIIGeDCCBGCgAwIBAgILAMCE5mZZYTmh+pswDQYJKoZIhvcNAQEMBQAwZzELMAkG\n" + + "A1UEBhMCSU4xEzARBgNVBAsTCmVtU2lnbiBQS0kxJTAjBgNVBAoTHGVNdWRocmEg\n" + + "VGVjaG5vbG9naWVzIExpbWl0ZWQxHDAaBgNVBAMTE2VtU2lnbiBSb290IENBIC0g\n" + + "RzIwHhcNMTgwMjE4MTgzMDAwWhcNMzMwMjE4MTgzMDAwWjBlMQswCQYDVQQGEwJJ\n" + + "TjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s\n" + + "b2dpZXMgTGltaXRlZDEaMBgGA1UEAxMRZW1TaWduIENTIENBIC0gRzIwggIiMA0G\n" + + "CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDYYkv6Q9an5RylOJ6rkTAHT0cAwfYg\n" + + "ZsFKk/Hz/4VwWYsmzf+Z7M8i3CK3mnUcqgw0AIzrVLUwxiKAaL0qca+SbXwOk/7p\n" + + "Y/zwwLdg0OhHVGeeU3OTvkbsBpiLS08i7ids9FGrte6m1kqk+QSOY2F5AESxA4+F\n" + + "AKXGtzIImQd15m67C88AzzFsvszAAxSvVTqs4hb8BcRnUCzlAp7gMJSwwrrgTiEv\n" + + "6Ap6cFVT+n1oj6370sd5KBiRelLoqZtQx4njoNJkJlM30ftPNMGnqPLCloQ6koP/\n" + + "dAdpmwWB+F0/5d5UVmVPC3R/F8w7aX3fdSC8+M2E/ZXPVIYkEquLT7K2yXhRl3hn\n" + + "xwG6qqGp6TjvKvhiyac8qieu9YNG1R+PVFqejOFMohV2g0Z5MfwaruhUCNwHHeZs\n" + + "Dv/MVYMiHcV+5qU+MMzcKngb3RCmq0jzCb+MESomEMiAieCC15W7YC/LpgDHO0jY\n" + + "vV4AdLquUHfsOnhT2KD7mEg2PnL7JOwoQSFtuJYmM/coh+Y6CIoV3x+aV1bO7FDF\n" + + "ap33u36lE639oQj0tTqW3n1WcyNxhD0lwGlYIAjG8XnhRjtl6/MVVrGuyPWpB4TH\n" + + "u8CgNT0roENuq13RnHbBz2rLnndenHiMbxCyElGJBpZfXiF1H25KHUzvyzxt++L+\n" + + "hSfprX9BSXLpGQIDAQABo4IBJTCCASEwHwYDVR0jBBgwFoAU7exNRWEYKOezIygR\n" + + "HE2lJw1e7PQwHQYDVR0OBBYEFBWGyrZ0lhdIWDSCLM3S4XWer0S3MA4GA1UdDwEB\n" + + "/wQEAwIBBjATBgNVHSUEDDAKBggrBgEFBQcDAzA9BgNVHSAENjA0MDIGBFUdIAAw\n" + + "KjAoBggrBgEFBQcCARYcaHR0cDovL3JlcG9zaXRvcnkuZW1zaWduLmNvbTASBgNV\n" + + "HRMBAf8ECDAGAQH/AgEAMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcwAYYWaHR0\n" + + "cDovL29jc3AuZW1zaWduLmNvbTAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js\n" + + "LmVtc2lnbi5jb20/Um9vdENBRzIuY3JsMA0GCSqGSIb3DQEBDAUAA4ICAQCDkogs\n" + + "d5Tv1zwsQdk15btzYK/oI1tEwvN6IpIM9rSqIrje8XnXKjHHmbHX6emHIR31bxuK\n" + + "7mY77XjrJMWp+71udC/DgDy4tfZTXIzEekI0XQfcui1UPC08Ysl0taQKTANwsAOV\n" + + "VSi7boSGqLet0qSmeKVyQ5/blbwx1NhjyLTyi66rVYf7fYdPV55X5TKUJdKDgiRI\n" + + "BomNVRcrrnHZtS8+t9CXxSXR35VAu2ube44Tl+dQHIWz9XwLxtYFwIPSEdqPpoAu\n" + + "5XEVo7evwMHQoY/MQj6Ywbw6tYh6bHu6C/qrp4oSyYXbz2ZWlHkz1oEXvefi7a9Z\n" + + "6mKnnaY3UYHq5AI+k6ojazVFbSTenb/TO/Z247gdhG7Wssshd6pgyqcTEa+FZz+F\n" + + "5ZZdoiIl8UJsTCPPg0xP9Ab0WE3BjCCqTPt+Czbd3cgBxiBS7KTQs/DnQRFuPCjC\n" + + "khbDtHsCN4aUoLM9OOw94/ZcoU0G5cg9mSvONBxUv9W7SIpJreXXMPXixcBKULoJ\n" + + "focui3s0yzGqTA9tSzQ4nmA9aXBCAAxrABlY/hk10ImeBa1SPjocRb/vuCaGp74T\n" + + "n8oADP42XudDnp8wlOKWxFJulhNi960Rev+5vZOPF/LGfS78GI6yzBjR49VJGhOP\n" + + "EJK8NSNmK3FNblQfOyFM7VE0uOGHOUwpMGVM2A==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=test, OU=test, O=test, L=test, ST=test, C=IN + // Issuer: CN=emSign CS CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Serial number: 7c9ade672c0ad1b6 + // Valid from: Wed Aug 30 05:39:25 PDT 2023 until: Sat Aug 30 05:39:25 PDT 2025 + private static final String VALID = "-----BEGIN CERTIFICATE-----\n" + + "MIIGNjCCBB6gAwIBAgIIfJreZywK0bYwDQYJKoZIhvcNAQEMBQAwZTELMAkGA1UE\n" + + "BhMCSU4xEzARBgNVBAsTCmVtU2lnbiBQS0kxJTAjBgNVBAoTHGVNdWRocmEgVGVj\n" + + "aG5vbG9naWVzIExpbWl0ZWQxGjAYBgNVBAMTEWVtU2lnbiBDUyBDQSAtIEcyMB4X\n" + + "DTIzMDgzMDEyMzkyNVoXDTI1MDgzMDEyMzkyNVowWDELMAkGA1UEBhMCSU4xDTAL\n" + + "BgNVBAgTBHRlc3QxDTALBgNVBAcTBHRlc3QxDTALBgNVBAoMBHRlc3QxDTALBgNV\n" + + "BAsTBHRlc3QxDTALBgNVBAMTBHRlc3QwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAw\n" + + "ggGKAoIBgQC04pOiSFbl7Bd4wFYXzzyukKh+EmwIq8xRGQDkuYH+C6Zao36VAV+k\n" + + "xGw7lmM3rf4YUcArgZYHfrxgPJNBbGrCi/YnEPYQTNwSrBAePUx1tt13LVBxHfNu\n" + + "cQQT+kqE7064WsYfmfr/uzJZemqVH7lG82DN23+8E/235AIh3lz/pn7T9ByLj7TV\n" + + "zWP40oT0UfQXQvWUpFevPONu/RksRP+NiKV3ji6/wYpvrfodzkrGxw2DPfOh4Iam\n" + + "j6bBH2rkTMToH853plsQGr2ji8OndePfvDdk+5c33Jz1knCNPZSlYQIIp8scyz4z\n" + + "jaUGdoC140FjEA1SMA2WzpRJoE7xjAidLv7jiV596/bTwrIM+IZhzBc8SKRmkdZ6\n" + + "lYjPYJHPqRosRtfxcQne3pY6F4s1aOUtuGJaQS/AJkkykZoOx27plWM5SjtmlrL+\n" + + "7g2/ihWT9CEagYuo44tqk9Tmp3P37+ADAmiXxP0zUxYIv77DSabdArrZ+AB5XUol\n" + + "V8sxE1V6h0UCAwEAAaOCAXUwggFxMB8GA1UdIwQYMBaAFBWGyrZ0lhdIWDSCLM3S\n" + + "4XWer0S3MB0GA1UdDgQWBBQ2k0TE2p46sYwI5M/a1XJ8M5Oc8DAOBgNVHQ8BAf8E\n" + + "BAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwMwNwYDVR0fBDAwLjAsoCqgKIYmaHR0\n" + + "cDovL2NybC5lbXNpZ24uY29tP2VtU2lnbkNTQ0FHMi5jcmwwTgYDVR0gBEcwRTA5\n" + + "BgsrBgEEAYOOIQEAATAqMCgGCCsGAQUFBwIBFhxodHRwOi8vcmVwb3NpdG9yeS5l\n" + + "bVNpZ24uY29tMAgGBmeBDAEEATBzBggrBgEFBQcBAQRnMGUwIgYIKwYBBQUHMAGG\n" + + "Fmh0dHA6Ly9vY3NwLmVtU2lnbi5jb20wPwYIKwYBBQUHMAKGM2h0dHA6Ly9yZXBv\n" + + "c2l0b3J5LmVtc2lnbi5jb20vY2VydHMvZW1TaWduQ1NDQUcyLmNydDAMBgNVHRMB\n" + + "Af8EAjAAMA0GCSqGSIb3DQEBDAUAA4ICAQBKLa7j8fNpcnWNv7NegrMKTRy7gycI\n" + + "qrMK848wISX6jl2wg6b275sWQHzQRxA6rbB76bF2HXLFcpITJPaz+vjetYOVQd4v\n" + + "l8iZN52OpN6Pwrheiz7JhdLiHisN+2NKMmF899bH7w1l2Sr/FQl5vqk41gwwWMen\n" + + "99Waf4Bp6p3lvBArK2BbabTs8+16xvmkHEK3d3l3Bu6qTEbQRgUI5XsVXmXXn8Pg\n" + + "IANliTEsbsN9CMWrJ56ciEujU7w2L+IBfvKhl10N1AQNHwpQzwfFyz2BUbACN75o\n" + + "feIUBarM3ssNzpnt7idgkCTwWVrdEL1NHyW967aEMWyVwaRrtkjFOW/0xuSr2rEI\n" + + "jBpPj5RPdP6ZEaqnmg5PIgSrJ8FBjx6JmvVgZH/XEl5MZ7PsvJFfIMun6RxXtGn7\n" + + "QP0+ipkRrI6USNFS84H53Q0WJhQWZUgd3cdm37wpFGvxOVEskIgJNW9SbOgiT9sB\n" + + "zTIy3ceOK2onmUkDM2Q2+Hbc7A4BmNIlW4fpYXvZlM7IXSl9U3Voks92Hi45azgz\n" + + "StWZv9+Ronmmp+b7JKCe7MZXIBHfj0JhAVNJiYTZ9BqkY2VRvuQPVUdKxske9fQ6\n" + + "ciFJ5a6RDOhce6pFloaQu39ci2XCY1N4mIR3vFzpmBNkttlEXviK07XNTv9cnQt6\n" + + "3CW5aMAsfTbmOw==\n" + + "-----END CERTIFICATE-----"; + + // Owner: CN=test, OU=test, O=test, L=test, ST=test, C=IN + // Issuer: CN=emSign CS CA - G2, O=eMudhra Technologies Limited, OU=emSign PKI, C=IN + // Serial number: cf02dedd03d2f509 + // Valid from: Thu Oct 05 22:38:51 PDT 2023 until: Sun Oct 05 22:38:51 PDT 2025 + private static final String REVOKED = "-----BEGIN CERTIFICATE-----\n" + + "MIIGNzCCBB+gAwIBAgIJAM8C3t0D0vUJMA0GCSqGSIb3DQEBDAUAMGUxCzAJBgNV\n" + + "BAYTAklOMRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRl\n" + + "Y2hub2xvZ2llcyBMaW1pdGVkMRowGAYDVQQDExFlbVNpZ24gQ1MgQ0EgLSBHMjAe\n" + + "Fw0yMzEwMDYwNTM4NTFaFw0yNTEwMDYwNTM4NTFaMFgxCzAJBgNVBAYTAklOMQ0w\n" + + "CwYDVQQIEwR0ZXN0MQ0wCwYDVQQHEwR0ZXN0MQ0wCwYDVQQKDAR0ZXN0MQ0wCwYD\n" + + "VQQLEwR0ZXN0MQ0wCwYDVQQDEwR0ZXN0MIIBojANBgkqhkiG9w0BAQEFAAOCAY8A\n" + + "MIIBigKCAYEAmUSghjvjUvVgYguH2PMLwW4TwtYsNDpAuGPqux53lI9v9S5u4oAv\n" + + "m1Sa3MW7CeEnhHNAIFu/AKvNXSfkvnJpTozWstZMjd93DcNacteBG0fBKTkIq+5k\n" + + "A8qIBiXWk8NORlbjV5bXnoW2pO7wbrALDK3FGf2JAQjuYWXE1mlVk0+SJewUSN+F\n" + + "XTl63V3tcaqjxhoViY8/dCWc7pNTPgQ/f+Rmnm1bpE0hxVPpQ29+60lyoNtKiOWj\n" + + "InKRKBV8jYkR/xI13bKWguaxZnswpf2MrophQTvO9ivPHADWhZlNYYjYYEMl4tbi\n" + + "rG2EquJ7g8Jdo+aL3BggLv5gFkpfoEcaveNuUWy7ggUl7MNhvgDdWdoi6VY7R8Fi\n" + + "F52+JqPByGpHkZKi0wPa3BaI7guGGyCn3TMe66kNTMS4ADxHktqQlpNSaYYl/84G\n" + + "lnr2WxQt/W+sXoorlKc/Kh0ubbm6eDzPE8kkIDV2uIxUEgSL7SJQ95yf5XgRihoH\n" + + "KoBA45iR5vCtAgMBAAGjggF1MIIBcTAfBgNVHSMEGDAWgBQVhsq2dJYXSFg0gizN\n" + + "0uF1nq9EtzAdBgNVHQ4EFgQUDs5dk74eElzdEKdxIlkzISoWSFkwDgYDVR0PAQH/\n" + + "BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMDcGA1UdHwQwMC4wLKAqoCiGJmh0\n" + + "dHA6Ly9jcmwuZW1zaWduLmNvbT9lbVNpZ25DU0NBRzIuY3JsME4GA1UdIARHMEUw\n" + + "OQYLKwYBBAGDjiEBAAEwKjAoBggrBgEFBQcCARYcaHR0cDovL3JlcG9zaXRvcnku\n" + + "ZW1TaWduLmNvbTAIBgZngQwBBAEwcwYIKwYBBQUHAQEEZzBlMCIGCCsGAQUFBzAB\n" + + "hhZodHRwOi8vb2NzcC5lbVNpZ24uY29tMD8GCCsGAQUFBzAChjNodHRwOi8vcmVw\n" + + "b3NpdG9yeS5lbXNpZ24uY29tL2NlcnRzL2VtU2lnbkNTQ0FHMi5jcnQwDAYDVR0T\n" + + "AQH/BAIwADANBgkqhkiG9w0BAQwFAAOCAgEAGa2XSoRkoIkHHHGXrdzTBCf/+KgK\n" + + "FlHhqlBOk5rwLDX1sfNlmsaz10I69phE90Ac8Coa/xCrBaFrTYqRvmkY9gU19jkn\n" + + "FdVcwQEHNku7Ro/Z/mbyi+aTBzHMTy0Vl4HqVnQInjV891n64SerUuAB7wNVOOho\n" + + "GoBfpf6lzDzzuEmetFokHYv1tWGQqPF/dHLARQraUlQpWjsnOx0QcZ5cM79REONE\n" + + "y6uzXT2vaatT3ns8Mtx8zooq+t8pnZlXJqlrwNTcnPad9gSsVu6vfsnWhLhz0VLG\n" + + "sYPXcWIssLbBQW3v5z0l1Isj7vy2UFfbn8AmZ0PanPo3v3C2sk19DK+Zlc9xBAXc\n" + + "KKwc4m8le6QkP/EB2wUA7ey5Cf29hjNDJpZznquEaWl9aKbBRdJDKsK88IBJjzK0\n" + + "Gbpw9fYJ3txuGA7Q27gyaZAeGAIrFvOtRY0XFbr20qSh2GBBYN57+lBPh4UKqgy8\n" + + "Z2Kk/2jK9k+nm41JYCmwVZHg3Va9RRfW8FkeE95gAUFPDWjeV+GvcimCbcB3DwaZ\n" + + "9fy1qfV4xsduhC3ei6f7Ask8LbAEWaEIXmgK10YbIfhzomCyCzlA+E+gwkq/bmkv\n" + + "B8hh27KWA6IRt7URI51MZlh0e8fULyXlOZcoJA/IPX9RdePa2RHFuPSypBHjoN7z\n" + + "6bCML1XZ2xnHIAg=\n" + + "-----END CERTIFICATE-----"; + + public static void main(String[] args) throws Exception { + + ValidatePathWithParams pathValidator = new ValidatePathWithParams(null); + + if (args.length >= 1 && "CRL".equalsIgnoreCase(args[0])) { + pathValidator.enableCRLCheck(); + } else { + // OCSP check by default + pathValidator.enableOCSPCheck(); + } + + // Validate valid + pathValidator.validate(new String[]{VALID, INT}, + ValidatePathWithParams.Status.GOOD, null, System.out); + + // Validate Revoked + pathValidator.validate(new String[]{REVOKED, INT}, + ValidatePathWithParams.Status.REVOKED, + "Thu Oct 05 22:51:36 PDT 2023", System.out); + } +} diff --git a/test/jdk/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java b/test/jdk/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java index 2c494a58c92..f41347f7fd2 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/RmiBootstrapTest.java @@ -58,7 +58,7 @@ * * @library /test/lib * - * @run main/timeout=300 RmiBootstrapTest .*_test.*.in + * @run main/othervm/timeout=300 RmiBootstrapTest .*_test.*.in * */ /* @@ -69,7 +69,7 @@ * * @library /test/lib * - * @run main/timeout=300 RmiBootstrapTest .*_ssltest.*.in + * @run main/othervm/timeout=300 RmiBootstrapTest .*_ssltest.*.in * */ /** diff --git a/test/jdk/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java b/test/jdk/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java index 41b303399cc..78ccaa86c5f 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java @@ -48,7 +48,7 @@ * * @library /test/lib * - * @run main/timeout=300 RmiSslNoKeyStoreTest .*_ssltest.*.in + * @run main/othervm/timeout=300 RmiSslNoKeyStoreTest .*_ssltest.*.in * */ /** diff --git a/test/jdk/sun/management/jmxremote/bootstrap/RmiTestBase.java b/test/jdk/sun/management/jmxremote/bootstrap/RmiTestBase.java index 0fb2996f913..2d6dbbbbe0f 100644 --- a/test/jdk/sun/management/jmxremote/bootstrap/RmiTestBase.java +++ b/test/jdk/sun/management/jmxremote/bootstrap/RmiTestBase.java @@ -141,7 +141,7 @@ static List prepareTestFiles(String filenamePattern) throws IOException { grantFilesAccess(propertyFiles, AccessControl.OWNER); - return Collections.unmodifiableList(files); + return Collections.unmodifiableList(propertyFiles); } /** diff --git a/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java b/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java index 53a98159116..80e5931b2b2 100644 --- a/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java +++ b/test/jdk/sun/security/lib/cacerts/VerifyCACerts.java @@ -28,7 +28,7 @@ * 8209452 8209506 8210432 8195793 8216577 8222089 8222133 8222137 8222136 * 8223499 8225392 8232019 8234245 8233223 8225068 8225069 8243321 8243320 * 8243559 8225072 8258630 8259312 8256421 8225081 8225082 8225083 8245654 - * 8305975 8304760 8307134 8295894 8314960 8317373 8317374 8318759 + * 8305975 8304760 8307134 8295894 8314960 8317373 8317374 8318759 8319187 * @summary Check root CA entries in cacerts file */ import java.io.ByteArrayInputStream; @@ -47,12 +47,13 @@ public class VerifyCACerts { + File.separator + "security" + File.separator + "cacerts"; // The numbers of certs now. - private static final int COUNT = 103; + private static final int COUNT = 106; // SHA-256 of cacerts, can be generated with // shasum -a 256 cacerts | sed -e 's/../&:/g' | tr '[:lower:]' '[:upper:]' | cut -c1-95 private static final String CHECKSUM - = "A6:73:50:DD:6B:49:E6:F0:E7:E7:7B:F9:F9:11:9F:83:2D:FD:95:97:69:03:54:54:9C:B7:DF:46:A4:05:7A:15"; + = "61:5F:6D:C5:9C:A3:8A:65:3F:CB:F9:F5:26:04:23:F4:53:A6:8C:B3:8B:2B:0A:F0:66:7D:9E:67:B9:4D:AC:B7"; + // Hex formatter to upper case with ":" delimiter private static final HexFormat HEX = HexFormat.ofDelimiter(":").withUpperCase(); @@ -266,6 +267,12 @@ public class VerifyCACerts { "D4:8D:3D:23:EE:DB:50:A4:59:E5:51:97:60:1C:27:77:4B:9D:7B:18:C9:4D:5A:05:95:11:A1:02:50:B9:31:68"); put("teliarootcav2 [jdk]", "24:2B:69:74:2F:CB:1E:5B:2A:BF:98:89:8B:94:57:21:87:54:4E:5B:4D:99:11:78:65:73:62:1F:6A:74:B8:2C"); + put("emsignrootcag1 [jdk]", + "40:F6:AF:03:46:A9:9A:A1:CD:1D:55:5A:4E:9C:CE:62:C7:F9:63:46:03:EE:40:66:15:83:3D:C8:C8:D0:03:67"); + put("emsigneccrootcag3 [jdk]", + "86:A1:EC:BA:08:9C:4A:8D:3B:BE:27:34:C6:12:BA:34:1D:81:3E:04:3C:F9:E8:A8:62:CD:5C:57:A3:6B:BE:6B"); + put("emsignrootcag2 [jdk]", + "1A:A0:C2:70:9E:83:1B:D6:E3:B5:12:9A:00:BA:41:F7:EE:EF:02:08:72:F1:E6:50:4B:F0:F6:C3:F2:4F:3A:F3"); } }; diff --git a/test/jdk/sun/security/pkcs11/Signature/LargeDSAKey.java b/test/jdk/sun/security/pkcs11/Signature/LargeDSAKey.java new file mode 100644 index 00000000000..a45a5ca47f5 --- /dev/null +++ b/test/jdk/sun/security/pkcs11/Signature/LargeDSAKey.java @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2021, Red Hat, Inc. + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.AlgorithmParameterGenerator; +import java.security.AlgorithmParameters; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.spec.DSAGenParameterSpec; +import java.security.spec.DSAParameterSpec; + +/* + * @test + * @bug 8271566 + * @library /test/lib .. + * @modules jdk.crypto.cryptoki + * @run main/othervm/timeout=30 LargeDSAKey + */ + +public final class LargeDSAKey extends PKCS11Test { + + private static final boolean enableDebug = false; + + private static final String knownText = + "Known text known text known text"; + + @Override + public void main(Provider p) throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA", p); + AlgorithmParameterGenerator dsaParGen = + AlgorithmParameterGenerator.getInstance("DSA"); + DSAGenParameterSpec dsaParGenSpec = + new DSAGenParameterSpec(2048, 256); + dsaParGen.init(dsaParGenSpec, new SecureRandom()); + AlgorithmParameters params = dsaParGen.generateParameters(); + DSAParameterSpec dsaParams = + params.getParameterSpec(DSAParameterSpec.class); + kpg.initialize(dsaParams); + KeyPair kp = kpg.generateKeyPair(); + doTestSignature(kp, p); + } + + private static void doTestSignature(KeyPair kp, Provider p) + throws Exception { + byte[] knownTextSig = null; + Signature s = Signature.getInstance("SHA1withDSA", p); + PrivateKey privKey = kp.getPrivate(); + PublicKey pubKey = kp.getPublic(); + if (enableDebug) { + System.out.println("Signature algorithm: " + s.getAlgorithm()); + System.out.println("Signature Provider: " + s.getProvider()); + System.out.println("Private key for signature: " + privKey); + System.out.println("Public key for signature: " + pubKey); + } + s.initSign(privKey); + s.update(knownText.getBytes()); + knownTextSig = s.sign(); + s.initVerify(pubKey); + s.update(knownText.getBytes()); + if (s.verify(knownTextSig) == false) { + throw new Exception("Could not verify signature"); + } + if (enableDebug) { + System.out.println("Signature verified"); + } + } + + public static void main(String[] args) throws Throwable { + main(new LargeDSAKey()); + System.out.println("TEST PASS - OK"); + } + +}