8292067: Convert test/sun/management/jmxremote/bootstrap shell tests to java version

Reviewed-by: lmesnik
This commit is contained in:
Bill Huang 2022-09-02 18:10:56 +00:00 committed by Leonid Mesnik
parent 83a34086bc
commit 3993a1f9ea
9 changed files with 909 additions and 1046 deletions

View File

@ -1,33 +0,0 @@
#
# Copyright (c) 2003, 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.
#
# Execute the test.
# No need to compile (now done by JTReg tags in calling file)
#
echo ${TESTJAVA}/bin/java ${TESTVMOPTS} -Dtest.src=${TESTCLASSES} \
-classpath ${TESTCLASSPATH} $* || exit 20
${TESTJAVA}/bin/java ${TESTVMOPTS} -Dtest.src=${TESTCLASSES} \
-classpath ${TESTCLASSPATH} $* || exit 20
exit 0

View File

@ -1,131 +0,0 @@
#
# Copyright (c) 2003, 2020, 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.
#
#
# Utility Shell Script for generating .properties files or .password files
# or .access files from a list of input .in files.
#
# Source in this GeneratePropertyPassword.sh and call the function
# generatePropertyPasswordFiles.
# Call restoreFilePermissions to restore file permissions after the test completes
#
OS=`uname -s`
UMASK=`umask`
case $OS in
CYGWIN_NT*)
OS="Windows_NT"
if [ -z "$SystemRoot" ] ; then
SystemRoot=`cygpath $SYSTEMROOT`
fi
esac
case $OS in
Linux | Darwin | AIX )
PATHSEP=":"
FILESEP="/"
DFILESEP=$FILESEP
TMP_FILE=${TESTCLASSES}${FILESEP}${TESTCLASS}.sed.tmpfile
cat <<EOF > ${TMP_FILE}
s^@TEST-SRC@/^${TESTCLASSES}${DFILESEP}^g
EOF
;;
Windows_95 | Windows_98 | Windows_NT | Windows_ME | CYGWIN*)
PATHSEP=";"
FILESEP="\\"
DFILESEP=$FILESEP$FILESEP
TMP_FILE=${TESTCLASSES}${FILESEP}${TESTCLASS}.sed.tmpfile
cat <<EOF > ${TMP_FILE}0
s^@TEST-SRC@/^${TESTCLASSES}${DFILESEP}^g
EOF
# Need to put double backslash in the .properties files
cat ${TMP_FILE}0 | sed -e 's^\\\\^ZZZZ^g' | \
sed -e 's^\\^ZZZZ^g' | \
sed -e 's^ZZZZ^\\\\\\\\^g' > ${TMP_FILE}
if [ "$OS" = "Windows_NT" ]; then
USER=`id -u -n`
CACLS="$SystemRoot/system32/cacls.exe"
REVOKEALL="$TESTNATIVEPATH/revokeall.exe"
if [ ! -x "$REVOKEALL" ] ; then
echo "$REVOKEALL doesn't exist or is not executable"
exit 1
fi
fi
;;
*)
echo "Unrecognized system! $OS"
exit 1
;;
esac
generatePropertyPasswordFiles()
{
for f in $@
do
echo processing $f
suffix=`basename $f .in`
f2="${TESTCLASSES}${FILESEP}${suffix}"
if [ -f "$f2" ] ; then
rm -f $f2 || echo WARNING: $f2 already exits - unable to remove old copy
fi
echo creating $f2
sed -f $TMP_FILE $f > $f2
if [ "$OS" = "Windows_NT" ]; then
chown $USER $f2
# Grant this user full access
echo Y|$CACLS $f2 \/E \/G $USER:F
# Revoke everyone else
$REVOKEALL $f2
# Display ACLs
$CACLS $f2
else
chmod 600 $f2
fi
done
}
restoreFilePermissions()
{
for f in $@
do
suffix=`basename $f .in`
f2="${TESTCLASSES}${FILESEP}${suffix}"
if [ "$OS" = "Windows_NT" ]; then
# Grant everyone full control
$CACLS $f2 \/E \/G Everyone:F
else
chmod 777 $f2
fi
done
}

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -20,29 +20,57 @@
* or visit www.oracle.com if you need additional information or have any * or visit www.oracle.com if you need additional information or have any
* questions. * questions.
*/ */
import sun.management.jmxremote.ConnectorBootstrap; import sun.management.jmxremote.ConnectorBootstrap;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.net.BindException; import java.net.BindException;
import java.nio.file.Path;
import java.rmi.server.ExportException; import java.rmi.server.ExportException;
import java.util.Properties;
import java.util.Iterator;
import java.util.Set;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Enumeration;
import javax.management.remote.*;
import javax.management.*;
import jdk.internal.agent.AgentConfigurationError; import jdk.internal.agent.AgentConfigurationError;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXServiceURL;
import java.security.Security; import java.security.Security;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/*
* @test
* @bug 6528083
* @key intermittent
* @summary Test RMI Bootstrap
*
* @library /test/lib
*
* @run main/timeout=300 RmiBootstrapTest .*_test.*.in
* */
/*
* @test
* @bug 6528083
* @key intermittent
* @summary Test RMI Bootstrap
*
* @library /test/lib
*
* @run main/timeout=300 RmiBootstrapTest .*_ssltest.*.in
* */
/** /**
* <p>This class implements unit test for RMI Bootstrap. * <p>This class implements unit test for RMI Bootstrap.
@ -56,7 +84,7 @@ import java.security.Security;
* <p>The rmi port number can be specified with the "rmi.port" system property. * <p>The rmi port number can be specified with the "rmi.port" system property.
* If not, this test will use the first available port</p> * If not, this test will use the first available port</p>
* *
* <p>When called with some argument, the main() will interprete its args to * <p>When called with some argument, the main() will interpret its args to
* be Java M&M configuration file names. The filenames are expected to end * be Java M&M configuration file names. The filenames are expected to end
* with ok.properties or ko.properties - and are interpreted as above.</p> * with ok.properties or ko.properties - and are interpreted as above.</p>
* *
@ -68,160 +96,57 @@ import java.security.Security;
* *
* <p>Debug traces are logged in "sun.management.test"</p> * <p>Debug traces are logged in "sun.management.test"</p>
**/ **/
public class RmiBootstrapTest { public class RmiBootstrapTest extends RmiTestBase {
static TestLogger log = new TestLogger("RmiBootstrapTest");
// the number of consecutive ports to test for availability // the number of consecutive ports to test for availability
private static int MAX_GET_FREE_PORT_TRIES = 10; private static int MAX_GET_FREE_PORT_TRIES = 10;
static TestLogger log =
new TestLogger("RmiBootstrapTest");
/**
* Default values for RMI configuration properties.
**/
public static interface DefaultValues {
public static final String PORT="0";
public static final String CONFIG_FILE_NAME="management.properties";
public static final String USE_SSL="true";
public static final String USE_AUTHENTICATION="true";
public static final String PASSWORD_FILE_NAME="jmxremote.password";
public static final String ACCESS_FILE_NAME="jmxremote.access";
public static final String KEYSTORE="keystore";
public static final String KEYSTORE_PASSWD="password";
public static final String TRUSTSTORE="truststore";
public static final String TRUSTSTORE_PASSWD="trustword";
public static final String SSL_NEED_CLIENT_AUTH="false";
}
/**
* Names of RMI configuration properties.
**/
public static interface PropertyNames {
public static final String PORT=
"com.sun.management.jmxremote.port";
public static final String CONFIG_FILE_NAME=
"com.sun.management.config.file";
public static final String USE_SSL=
"com.sun.management.jmxremote.ssl";
public static final String USE_AUTHENTICATION=
"com.sun.management.jmxremote.authenticate";
public static final String PASSWORD_FILE_NAME=
"com.sun.management.jmxremote.password.file";
public static final String ACCESS_FILE_NAME=
"com.sun.management.jmxremote.access.file";
public static final String INSTRUMENT_ALL=
"com.sun.management.instrumentall";
public static final String CREDENTIALS =
"jmx.remote.credentials";
public static final String KEYSTORE=
"javax.net.ssl.keyStore";
public static final String KEYSTORE_PASSWD=
"javax.net.ssl.keyStorePassword";
public static final String TRUSTSTORE=
"javax.net.ssl.trustStore";
public static final String TRUSTSTORE_PASSWD=
"javax.net.ssl.trustStorePassword";
public static final String SSL_ENABLED_CIPHER_SUITES =
"com.sun.management.jmxremote.ssl.enabled.cipher.suites";
public static final String SSL_ENABLED_PROTOCOLS =
"com.sun.management.jmxremote.ssl.enabled.protocols";
public static final String SSL_NEED_CLIENT_AUTH =
"com.sun.management.jmxremote.ssl.need.client.auth";
public static final String SSL_CLIENT_ENABLED_CIPHER_SUITES =
"javax.rmi.ssl.client.enabledCipherSuites";
}
/**
* A filter to find all filenames who match <prefix>*<suffix>.
* Note that <prefix> and <suffix> can overlap.
**/
private static class ConfigFilenameFilter implements FilenameFilter {
final String suffix;
final String prefix;
ConfigFilenameFilter(String prefix, String suffix) {
this.suffix=suffix;
this.prefix=prefix;
}
public boolean accept(File dir, String name) {
return (name.startsWith(prefix) && name.endsWith(suffix));
}
}
/**
* Get all "management*ok.properties" files in the directory
* indicated by the "test.src" management property.
**/
private static File[] findConfigurationFilesOk() {
final String testSrc = System.getProperty("test.src");
final File dir = new File(testSrc);
final FilenameFilter filter =
new ConfigFilenameFilter("management_test","ok.properties");
return dir.listFiles(filter);
}
/**
* Get all "management*ko.properties" files in the directory
* indicated by the "test.src" management property.
**/
private static File[] findConfigurationFilesKo() {
final String testSrc = System.getProperty("test.src");
final File dir = new File(testSrc);
final FilenameFilter filter =
new ConfigFilenameFilter("management_test","ko.properties");
return dir.listFiles(filter);
}
/** /**
* List all MBeans and their attributes. Used to test communication * List all MBeans and their attributes. Used to test communication
* with the Java M&M MBean Server. * with the Java M&M MBean Server.
*
* @return the number of queried MBeans. * @return the number of queried MBeans.
*/ */
public static int listMBeans(MBeanServerConnection server) public static int listMBeans(MBeanServerConnection server) throws IOException {
throws IOException {
return listMBeans(server, null, null); return listMBeans(server, null, null);
} }
/** /**
* List all matching MBeans and their attributes. * List all matching MBeans and their attributes.
* Used to test communication with the Java M&M MBean Server. * Used to test communication with the Java M&M MBean Server.
*
* @return the number of matching MBeans. * @return the number of matching MBeans.
*/ */
public static int listMBeans(MBeanServerConnection server, public static int listMBeans(MBeanServerConnection server, ObjectName pattern, QueryExp query)
ObjectName pattern, QueryExp query)
throws IOException { throws IOException {
final Set names = server.queryNames(pattern,query); final Set<ObjectName> names = server.queryNames(pattern, query);
for (final Iterator i=names.iterator(); i.hasNext(); ) { for (ObjectName name : names) {
ObjectName name = (ObjectName)i.next();
log.trace("listMBeans", "Got MBean: " + name); log.trace("listMBeans", "Got MBean: " + name);
try { try {
MBeanInfo info = MBeanInfo info = server.getMBeanInfo(name);
server.getMBeanInfo((ObjectName)name);
MBeanAttributeInfo[] attrs = info.getAttributes(); MBeanAttributeInfo[] attrs = info.getAttributes();
if (attrs == null) continue; if (attrs == null) {
continue;
}
for (int j = 0; j < attrs.length; j++) { for (int j = 0; j < attrs.length; j++) {
if (attrs[j].isReadable()) { if (attrs[j].isReadable()) {
try { try {
Object o = Object o = server.getAttribute(name, attrs[j].getName());
server.getAttribute(name,attrs[j].getName()); if (log.isDebugOn()) {
if (log.isDebugOn()) log.debug("listMBeans", "\t\t" + attrs[j].getName() + " = " + o);
log.debug("listMBeans","\t\t" + }
attrs[j].getName() +
" = "+o);
} catch (Exception x) { } catch (Exception x) {
log.trace("listMBeans","JmxClient failed to get " + log.trace("listMBeans", "JmxClient failed to get " + attrs[j].getName() + ": " + x);
attrs[j].getName() + ": " + x); final IOException io = new IOException("JmxClient failed to get " + attrs[j].getName());
final IOException io =
new IOException("JmxClient failed to get " +
attrs[j].getName());
io.initCause(x); io.initCause(x);
throw io; throw io;
} }
} }
} }
} catch (Exception x) { } catch (Exception x) {
log.trace("listMBeans", log.trace("listMBeans", "JmxClient failed to get MBeanInfo: " + x);
"JmxClient failed to get MBeanInfo: " + x); final IOException io = new IOException("JmxClient failed to get MBeanInfo: " + x);
final IOException io =
new IOException("JmxClient failed to get MBeanInfo: "+x);
io.initCause(x); io.initCause(x);
throw io; throw io;
} }
@ -230,34 +155,38 @@ public class RmiBootstrapTest {
} }
/** /**
* Compute the full path name for a default file. * Calls run(args[]).
* @param basename basename (with extension) of the default file. * exit(1) if the test fails.
* @return ${JRE}/conf/management/${basename}
**/ **/
private static String getDefaultFileName(String basename) { public static void main(String args[]) throws Exception {
final String fileSeparator = File.separator; if (args.length == 0) {
final StringBuffer defaultFileName = throw new IllegalArgumentException("Argument is required for this" + " test");
new StringBuffer(System.getProperty("java.home")).
append(fileSeparator).append("conf").append(fileSeparator).
append("management").append(fileSeparator).
append(basename);
return defaultFileName.toString();
} }
/** final List<Path> credentialFiles = prepareTestFiles(args[0]);
* Compute the full path name for a default file.
* @param basename basename (with extension) of the default file. Security.setProperty("jdk.tls.disabledAlgorithms", "");
* @return ${JRE}/conf/management/${basename}
**/ try {
private static String getDefaultStoreName(String basename) { MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
final String fileSeparator = File.separator; } catch (NumberFormatException ex) {
final StringBuffer defaultFileName =
new StringBuffer(System.getProperty("test.src")).
append(fileSeparator).append("ssl").append(fileSeparator).
append(basename);
return defaultFileName.toString();
} }
RmiBootstrapTest manager = new RmiBootstrapTest();
try {
manager.run(args);
} catch (RuntimeException r) {
System.out.println("Test Failed: " + r.getMessage());
System.exit(1);
} catch (Throwable t) {
System.out.println("Test Failed: " + t);
t.printStackTrace();
System.exit(2);
}
System.out.println("**** Test RmiBootstrap Passed ****");
grantFilesAccess(credentialFiles, AccessControl.EVERYONE);
}
/** /**
* Parses the password file to read the credentials. * Parses the password file to read the credentials.
@ -266,14 +195,17 @@ public class RmiBootstrapTest {
* If the password file does not exists, return an empty list. * If the password file does not exists, return an empty list.
* (File not found = empty file). * (File not found = empty file).
**/ **/
private ArrayList readCredentials(String passwordFileName) private ArrayList readCredentials(String passwordFileName) throws IOException {
throws IOException {
final Properties pws = new Properties(); final Properties pws = new Properties();
final ArrayList result = new ArrayList(); final ArrayList result = new ArrayList();
final File f = new File(passwordFileName); final File f = new File(passwordFileName);
if (!f.exists()) return result; if (!f.exists()) {
FileInputStream fin = new FileInputStream(passwordFileName); return result;
try {pws.load(fin);}finally{fin.close();} }
try (FileInputStream fin = new FileInputStream(passwordFileName)){
pws.load(fin);
} catch (IOException e) {
}
for (Enumeration en = pws.propertyNames(); en.hasMoreElements(); ) { for (Enumeration en = pws.propertyNames(); en.hasMoreElements(); ) {
final String[] cred = new String[2]; final String[] cred = new String[2];
cred[0] = (String) en.nextElement(); cred[0] = (String) en.nextElement();
@ -283,35 +215,40 @@ public class RmiBootstrapTest {
return result; return result;
} }
/** /**
* Connect with the given url, using all given credentials in turn. * Connect with the given url, using all given credentials in turn.
* A null entry in the useCredentials arrays indicate a connection * A null entry in the useCredentials arrays indicate a connection
* where no credentials are used. * where no credentials are used.
*
* @param url JMXServiceURL of the server. * @param url JMXServiceURL of the server.
* @param useCredentials An array of credentials (a credential * @param useCredentials An array of credentials (a credential
* is a two String array, so this is an array of arrays * is a two String array, so this is an array of
* arrays
* of strings: * of strings:
* useCredentials[i][0]=subject * useCredentials[i][0]=subject
* useCredentials[i][1]=password * useCredentials[i][1]=password
* if useCredentials[i] == null means no credentials. * if useCredentials[i] == null means no credentials.
* @param expectConnectOk true if connection is expected to succeed * @param expectConnectOk true if connection is expected to succeed
* Note: if expectConnectOk=false and the test fails to connect * Note: if expectConnectOk=false and the test
* the number of failure is not incremented. Conversely, * fails to connect
* if expectConnectOk=false and the test does not fail to * the number of failure is not incremented.
* Conversely,
* if expectConnectOk=false and the test does not
* fail to
* connect the number of failure is incremented. * connect the number of failure is incremented.
* @param expectReadOk true if communication (listMBeans) is expected * @param expectReadOk true if communication (listMBeans) is expected
* to succeed. * to succeed.
* Note: if expectReadOk=false and the test fails to read MBeans * Note: if expectReadOk=false and the test fails
* the number of failure is not incremented. Conversely, * to read MBeans
* if expectReadOk=false and the test does not fail to * the number of failure is not incremented.
* Conversely,
* if expectReadOk=false and the test does not
* fail to
* read MBeans the number of failure is incremented. * read MBeans the number of failure is incremented.
* @return number of failure. * @return number of failure.
**/ **/
public int connectAndRead(JMXServiceURL url, public int connectAndRead(JMXServiceURL url, Object[] useCredentials,
Object[] useCredentials, boolean expectConnectOk, boolean expectReadOk)
boolean expectConnectOk,
boolean expectReadOk)
throws IOException { throws IOException {
int errorCount = 0; int errorCount = 0;
@ -333,88 +270,73 @@ public class RmiBootstrapTest {
c = JMXConnectorFactory.connect(url, m); c = JMXConnectorFactory.connect(url, m);
} catch (IOException x) { } catch (IOException x) {
if (expectConnectOk) { if (expectConnectOk) {
final String err = "Connection failed for " + crinfo + final String err = "Connection failed for " + crinfo + ": " + x;
": " + x;
System.out.println(err); System.out.println(err);
log.trace("testCommunication", err); log.trace("testCommunication", err);
log.debug("testCommunication", x); log.debug("testCommunication", x);
errorCount++; errorCount++;
continue; continue;
} else { } else {
System.out.println("Connection failed as expected for " + System.out.println("Connection failed as expected for " + crinfo + ": " + x);
crinfo + ": " + x);
continue; continue;
} }
} catch (RuntimeException x) { } catch (RuntimeException x) {
if (expectConnectOk) { if (expectConnectOk) {
final String err = "Connection failed for " + crinfo + final String err = "Connection failed for " + crinfo + ": " + x;
": " + x;
System.out.println(err); System.out.println(err);
log.trace("testCommunication", err); log.trace("testCommunication", err);
log.debug("testCommunication", x); log.debug("testCommunication", x);
errorCount++; errorCount++;
continue; continue;
} else { } else {
System.out.println("Connection failed as expected for " + System.out.println("Connection failed as expected for " + crinfo + ": " + x);
crinfo + ": " + x);
continue; continue;
} }
} }
try { try {
MBeanServerConnection conn = MBeanServerConnection conn = c.getMBeanServerConnection();
c.getMBeanServerConnection();
if (log.isDebugOn()) { if (log.isDebugOn()) {
log.debug("testCommunication", "Connection is:" + conn); log.debug("testCommunication", "Connection is:" + conn);
log.debug("testCommunication","Server domain is: " + log.debug("testCommunication", "Server domain is: " + conn.getDefaultDomain());
conn.getDefaultDomain());
} }
final ObjectName pattern = final ObjectName pattern = new ObjectName("java.lang:type=Memory,*");
new ObjectName("java.lang:type=Memory,*");
final int count = listMBeans(conn, pattern, null); final int count = listMBeans(conn, pattern, null);
if (count == 0) if (count == 0) {
throw new Exception("Expected at least one matching "+ throw new Exception("Expected at least one matching " + "MBean for " + pattern);
"MBean for "+pattern); }
if (expectReadOk) { if (expectReadOk) {
System.out.println("Communication succeeded " + System.out.println("Communication succeeded " + "as expected for " + crinfo + ": found " + count +
"as expected for "+ ((count < 2) ? "MBean" : "MBeans"));
crinfo + ": found " + count
+ ((count<2)?"MBean":"MBeans"));
} else { } else {
final String err = "Expected failure didn't occur for " + final String err = "Expected failure didn't occur for " + crinfo;
crinfo;
System.out.println(err); System.out.println(err);
errorCount++; errorCount++;
} }
} catch (IOException x) { } catch (IOException x) {
final String err = "Communication failed with " + crinfo + ": " + x;
if (expectReadOk) { if (expectReadOk) {
final String err = "Communication failed with " + crinfo +
": " + x;
System.out.println(err); System.out.println(err);
log.trace("testCommunication", err); log.trace("testCommunication", err);
log.debug("testCommunication", x); log.debug("testCommunication", x);
errorCount++; errorCount++;
continue; continue;
} else { } else {
System.out.println("Communication failed as expected for "+ System.out.println("Communication failed as expected for " + crinfo + ": " + x);
crinfo + ": " + x);
continue; continue;
} }
} catch (RuntimeException x) { } catch (RuntimeException x) {
if (expectReadOk) { if (expectReadOk) {
final String err = "Communication failed with " + crinfo + final String err = "Communication failed with " + crinfo + ": " + x;
": " + x;
System.out.println(err); System.out.println(err);
log.trace("testCommunication", err); log.trace("testCommunication", err);
log.debug("testCommunication", x); log.debug("testCommunication", x);
errorCount++; errorCount++;
continue; continue;
} else { } else {
System.out.println("Communication failed as expected for "+ System.out.println("Communication failed as expected for " + crinfo + ": " + x);
crinfo + ": " + x);
} }
} catch (Exception x) { } catch (Exception x) {
final String err = "Failed to read MBeans with " + crinfo + final String err = "Failed to read MBeans with " + crinfo + ": " + x;
": " + x;
System.out.println(err); System.out.println(err);
log.trace("testCommunication", err); log.trace("testCommunication", err);
log.debug("testCommunication", x); log.debug("testCommunication", x);
@ -427,42 +349,28 @@ public class RmiBootstrapTest {
return errorCount; return errorCount;
} }
private void setSslProperties(String clientEnabledCipherSuites) { private void setSslProperties(String clientEnabledCipherSuites) {
final String defaultKeyStore = final String defaultKeyStore = defaultStoreNamePrefix + DefaultValues.KEYSTORE;
getDefaultStoreName(DefaultValues.KEYSTORE); final String defaultTrustStore = defaultStoreNamePrefix + DefaultValues.TRUSTSTORE;
final String defaultTrustStore =
getDefaultStoreName(DefaultValues.TRUSTSTORE);
final String keyStore = final String keyStore = System.getProperty(PropertyNames.KEYSTORE, defaultKeyStore);
System.getProperty(PropertyNames.KEYSTORE, defaultKeyStore);
System.setProperty(PropertyNames.KEYSTORE, keyStore); System.setProperty(PropertyNames.KEYSTORE, keyStore);
log.trace("setSslProperties", PropertyNames.KEYSTORE + "=" + keyStore); log.trace("setSslProperties", PropertyNames.KEYSTORE + "=" + keyStore);
final String password = final String password = System.getProperty(PropertyNames.KEYSTORE_PASSWD, DefaultValues.KEYSTORE_PASSWD);
System.getProperty(PropertyNames.KEYSTORE_PASSWD,
DefaultValues.KEYSTORE_PASSWD);
System.setProperty(PropertyNames.KEYSTORE_PASSWD, password); System.setProperty(PropertyNames.KEYSTORE_PASSWD, password);
log.trace("setSslProperties", log.trace("setSslProperties", PropertyNames.KEYSTORE_PASSWD + "=" + password);
PropertyNames.KEYSTORE_PASSWD+"="+password);
final String trustStore = final String trustStore = System.getProperty(PropertyNames.TRUSTSTORE, defaultTrustStore);
System.getProperty(PropertyNames.TRUSTSTORE,
defaultTrustStore);
System.setProperty(PropertyNames.TRUSTSTORE, trustStore); System.setProperty(PropertyNames.TRUSTSTORE, trustStore);
log.trace("setSslProperties", log.trace("setSslProperties", PropertyNames.TRUSTSTORE + "=" + trustStore);
PropertyNames.TRUSTSTORE+"="+trustStore);
final String trustword = final String trustword = System.getProperty(PropertyNames.TRUSTSTORE_PASSWD, DefaultValues.TRUSTSTORE_PASSWD);
System.getProperty(PropertyNames.TRUSTSTORE_PASSWD,
DefaultValues.TRUSTSTORE_PASSWD);
System.setProperty(PropertyNames.TRUSTSTORE_PASSWD, trustword); System.setProperty(PropertyNames.TRUSTSTORE_PASSWD, trustword);
log.trace("setSslProperties", log.trace("setSslProperties", PropertyNames.TRUSTSTORE_PASSWD + "=" + trustword);
PropertyNames.TRUSTSTORE_PASSWD+"="+trustword);
if (clientEnabledCipherSuites != null) { if (clientEnabledCipherSuites != null) {
System.setProperty("javax.rmi.ssl.client.enabledCipherSuites", System.setProperty("javax.rmi.ssl.client.enabledCipherSuites", clientEnabledCipherSuites);
clientEnabledCipherSuites);
} else { } else {
System.clearProperty("javax.rmi.ssl.client.enabledCipherSuites"); System.clearProperty("javax.rmi.ssl.client.enabledCipherSuites");
} }
@ -470,57 +378,44 @@ public class RmiBootstrapTest {
private void checkSslConfiguration() { private void checkSslConfiguration() {
try { try {
final String defaultConf = final String defaultConf = defaultFileNamePrefix + DefaultValues.CONFIG_FILE_NAME;
getDefaultFileName(DefaultValues.CONFIG_FILE_NAME); final String confname = System.getProperty(PropertyNames.CONFIG_FILE_NAME, defaultConf);
final String confname =
System.getProperty(PropertyNames.CONFIG_FILE_NAME,defaultConf);
final Properties props = new Properties(); final Properties props = new Properties();
final File conf = new File(confname); final File conf = new File(confname);
if (conf.exists()) { if (conf.exists()) {
FileInputStream fin = new FileInputStream(conf); FileInputStream fin = new FileInputStream(conf);
try {props.load(fin);} finally {fin.close();} try {
props.load(fin);
} finally {
fin.close();
}
} }
// Do we use SSL? // Do we use SSL?
final String useSslStr = final String useSslStr = props.getProperty(PropertyNames.USE_SSL, DefaultValues.USE_SSL);
props.getProperty(PropertyNames.USE_SSL, final boolean useSsl = Boolean.valueOf(useSslStr).booleanValue();
DefaultValues.USE_SSL);
final boolean useSsl =
Boolean.valueOf(useSslStr).booleanValue();
log.debug("checkSslConfiguration", log.debug("checkSslConfiguration", PropertyNames.USE_SSL + "=" + useSsl + ": setting SSL");
PropertyNames.USE_SSL+"="+useSsl+
": setting SSL");
// Do we use SSL client authentication? // Do we use SSL client authentication?
final String useSslClientAuthStr = final String useSslClientAuthStr =
props.getProperty(PropertyNames.SSL_NEED_CLIENT_AUTH, props.getProperty(PropertyNames.SSL_NEED_CLIENT_AUTH, DefaultValues.SSL_NEED_CLIENT_AUTH);
DefaultValues.SSL_NEED_CLIENT_AUTH); final boolean useSslClientAuth = Boolean.valueOf(useSslClientAuthStr).booleanValue();
final boolean useSslClientAuth =
Boolean.valueOf(useSslClientAuthStr).booleanValue();
log.debug("checkSslConfiguration", log.debug("checkSslConfiguration", PropertyNames.SSL_NEED_CLIENT_AUTH + "=" + useSslClientAuth);
PropertyNames.SSL_NEED_CLIENT_AUTH+"="+useSslClientAuth);
// Do we use customized SSL cipher suites? // Do we use customized SSL cipher suites?
final String sslCipherSuites = final String sslCipherSuites = props.getProperty(PropertyNames.SSL_ENABLED_CIPHER_SUITES);
props.getProperty(PropertyNames.SSL_ENABLED_CIPHER_SUITES);
log.debug("checkSslConfiguration", log.debug("checkSslConfiguration", PropertyNames.SSL_ENABLED_CIPHER_SUITES + "=" + sslCipherSuites);
PropertyNames.SSL_ENABLED_CIPHER_SUITES + "=" +
sslCipherSuites);
// Do we use customized SSL protocols? // Do we use customized SSL protocols?
final String sslProtocols = final String sslProtocols = props.getProperty(PropertyNames.SSL_ENABLED_PROTOCOLS);
props.getProperty(PropertyNames.SSL_ENABLED_PROTOCOLS);
log.debug("checkSslConfiguration", log.debug("checkSslConfiguration", PropertyNames.SSL_ENABLED_PROTOCOLS + "=" + sslProtocols);
PropertyNames.SSL_ENABLED_PROTOCOLS + "=" +
sslProtocols);
if (useSsl) { if (useSsl) {
setSslProperties(props.getProperty( setSslProperties(props.getProperty(PropertyNames.SSL_CLIENT_ENABLED_CIPHER_SUITES));
PropertyNames.SSL_CLIENT_ENABLED_CIPHER_SUITES));
} }
} catch (Exception x) { } catch (Exception x) {
System.out.println("Failed to setup SSL configuration: " + x); System.out.println("Failed to setup SSL configuration: " + x);
@ -535,44 +430,40 @@ public class RmiBootstrapTest {
* Loads the password file to find out wich credentials to use. * Loads the password file to find out wich credentials to use.
* Also checks that unregistered user/passwords are not allowed to * Also checks that unregistered user/passwords are not allowed to
* connect when a password file is used. * connect when a password file is used.
* * <p>
* This method calls connectAndRead(). * This method calls connectAndRead().
**/ **/
public void testCommunication(JMXServiceURL url) public void testCommunication(JMXServiceURL url) throws IOException {
throws IOException {
final String defaultConf = final String defaultConf = defaultFileNamePrefix + DefaultValues.CONFIG_FILE_NAME;
getDefaultFileName(DefaultValues.CONFIG_FILE_NAME); final String confname = System.getProperty(PropertyNames.CONFIG_FILE_NAME, defaultConf);
final String confname =
System.getProperty(PropertyNames.CONFIG_FILE_NAME,defaultConf);
final Properties props = new Properties(); final Properties props = new Properties();
final File conf = new File(confname); final File conf = new File(confname);
if (conf.exists()) { if (conf.exists()) {
FileInputStream fin = new FileInputStream(conf); FileInputStream fin = new FileInputStream(conf);
try {props.load(fin);} finally {fin.close();} try {
props.load(fin);
} finally {
fin.close();
}
} }
// Do we use authentication? // Do we use authentication?
final String useAuthenticationStr = final String useAuthenticationStr =
props.getProperty(PropertyNames.USE_AUTHENTICATION, props.getProperty(PropertyNames.USE_AUTHENTICATION, DefaultValues.USE_AUTHENTICATION);
DefaultValues.USE_AUTHENTICATION); final boolean useAuthentication = Boolean.valueOf(useAuthenticationStr).booleanValue();
final boolean useAuthentication =
Boolean.valueOf(useAuthenticationStr).booleanValue();
// Get Password File // Get Password File
final String defaultPasswordFileName = Utils.convertPath( final String defaultPasswordFileName =
getDefaultFileName(DefaultValues.PASSWORD_FILE_NAME)); Utils.convertPath(defaultFileNamePrefix + DefaultValues.PASSWORD_FILE_NAME);
final String passwordFileName = Utils.convertPath( final String passwordFileName =
props.getProperty(PropertyNames.PASSWORD_FILE_NAME, Utils.convertPath(props.getProperty(PropertyNames.PASSWORD_FILE_NAME, defaultPasswordFileName));
defaultPasswordFileName));
// Get Access File // Get Access File
final String defaultAccessFileName = Utils.convertPath( final String defaultAccessFileName = Utils.convertPath(defaultFileNamePrefix + DefaultValues.ACCESS_FILE_NAME);
getDefaultFileName(DefaultValues.ACCESS_FILE_NAME)); final String accessFileName =
final String accessFileName = Utils.convertPath( Utils.convertPath(props.getProperty(PropertyNames.ACCESS_FILE_NAME, defaultAccessFileName));
props.getProperty(PropertyNames.ACCESS_FILE_NAME,
defaultAccessFileName));
if (useAuthentication) { if (useAuthentication) {
System.out.println("PasswordFileName: " + passwordFileName); System.out.println("PasswordFileName: " + passwordFileName);
@ -583,9 +474,14 @@ public class RmiBootstrapTest {
final Object[] noCredentials = {null}; final Object[] noCredentials = {null};
if (useAuthentication) { if (useAuthentication) {
final ArrayList l = readCredentials(passwordFileName); final ArrayList l = readCredentials(passwordFileName);
if (l.size() == 0) allCredentials = null; if (l.size() == 0) {
else allCredentials = l.toArray(); allCredentials = null;
} else allCredentials = noCredentials; } else {
allCredentials = l.toArray();
}
} else {
allCredentials = noCredentials;
}
int errorCount = 0; int errorCount = 0;
if (allCredentials != null) { if (allCredentials != null) {
@ -597,11 +493,7 @@ public class RmiBootstrapTest {
// Tests that no one is allowed // Tests that no one is allowed
// connect & read // connect & read
// //
final String[][] someCredentials = { final String[][] someCredentials = {null, {"modify", "R&D"}, {"measure", "QED"}};
null,
{ "modify", "R&D" },
{ "measure", "QED" }
};
errorCount += connectAndRead(url, someCredentials, false, false); errorCount += connectAndRead(url, someCredentials, false, false);
} }
@ -609,26 +501,22 @@ public class RmiBootstrapTest {
// Tests that the registered user/passwords are not allowed to // Tests that the registered user/passwords are not allowed to
// connect & read // connect & read
// //
final String[][] badCredentials = { final String[][] badCredentials = {{"bad.user", "R&D"}, {"measure", "bad.password"}};
{ "bad.user", "R&D" },
{ "measure", "bad.password" }
};
errorCount += connectAndRead(url, badCredentials, false, false); errorCount += connectAndRead(url, badCredentials, false, false);
} }
if (errorCount > 0) { if (errorCount > 0) {
final String err = "Test " + confname + " failed with " + final String err = "Test " + confname + " failed with " + errorCount + " error(s)";
errorCount + " error(s)";
log.debug("testCommunication", err); log.debug("testCommunication", err);
throw new RuntimeException(err); throw new RuntimeException(err);
} }
} }
/** /**
* Test the configuration indicated by `file'. * Test the configuration indicated by `file'.
* Sets the appropriate System properties for config file and * Sets the appropriate System properties for config file and
* port and then calls ConnectorBootstrap.initialize(). * port and then calls ConnectorBootstrap.initialize().
* eventually cleans up by calling ConnectorBootstrap.terminate(). * eventually cleans up by calling ConnectorBootstrap.terminate().
*
* @return null if the test succeeds, an error message otherwise. * @return null if the test succeeds, an error message otherwise.
**/ **/
private String testConfiguration(File file) throws IOException, InterruptedException { private String testConfiguration(File file) throws IOException, InterruptedException {
@ -640,8 +528,7 @@ public class RmiBootstrapTest {
try { try {
path = (file == null) ? null : file.getCanonicalPath(); path = (file == null) ? null : file.getCanonicalPath();
} catch (IOException x) { } catch (IOException x) {
final String err = "Failed to test configuration " + file + final String err = "Failed to test configuration " + file + ": " + x;
": " + x;
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
log.debug("testConfiguration", x); log.debug("testConfiguration", x);
return err; return err;
@ -649,21 +536,20 @@ public class RmiBootstrapTest {
final String config = (path == null) ? "Default config file" : path; final String config = (path == null) ? "Default config file" : path;
System.out.println("***"); System.out.println("***");
System.out.println("*** Testing configuration (port=" + port + "): " System.out.println("*** Testing configuration (port=" + port + "): " + path);
+ path);
System.out.println("***"); System.out.println("***");
System.setProperty("com.sun.management.jmxremote.port", System.setProperty("com.sun.management.jmxremote.port", Integer.toString(port));
Integer.toString(port)); if (path != null) {
if (path != null)
System.setProperty("com.sun.management.config.file", path); System.setProperty("com.sun.management.config.file", path);
else } else {
System.getProperties().remove("com.sun.management.config.file"); System.getProperties().remove("com.sun.management.config.file");
}
log.trace("testConfiguration", "com.sun.management.jmxremote.port=" + port); log.trace("testConfiguration", "com.sun.management.jmxremote.port=" + port);
if (path != null && log.isDebugOn()) if (path != null && log.isDebugOn()) {
log.trace("testConfiguration", log.trace("testConfiguration", "com.sun.management.config.file=" + path);
"com.sun.management.config.file="+path); }
checkSslConfiguration(); checkSslConfiguration();
@ -676,10 +562,9 @@ public class RmiBootstrapTest {
throw (BindException) x.getCause().getCause(); throw (BindException) x.getCause().getCause();
} }
} }
final String err = "Failed to initialize connector:" + final String err =
"\n\tcom.sun.management.jmxremote.port=" + port + "Failed to initialize connector:" + "\n\tcom.sun.management.jmxremote.port=" + port +
((path!=null)?"\n\tcom.sun.management.config.file="+path: ((path != null) ? "\n\tcom.sun.management.config.file=" + path : "\n\t" + config) +
"\n\t"+config) +
"\n\tError is: " + x; "\n\tError is: " + x;
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
log.debug("testConfiguration", x); log.debug("testConfiguration", x);
@ -690,22 +575,18 @@ public class RmiBootstrapTest {
} }
try { try {
JMXServiceURL url = JMXServiceURL url = new JMXServiceURL("rmi", null, 0, "/jndi/rmi://localhost:" + port + "/jmxrmi");
new JMXServiceURL("rmi",null,0,"/jndi/rmi://localhost:"+
port+"/jmxrmi");
try { try {
testCommunication(url); testCommunication(url);
} catch (Exception x) { } catch (Exception x) {
final String err = "Failed to connect to agent {url="+url+ final String err = "Failed to connect to agent {url=" + url + "}: " + x;
"}: " + x;
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
log.debug("testConfiguration", x); log.debug("testConfiguration", x);
return err; return err;
} }
} catch (Exception x) { } catch (Exception x) {
final String err = "Failed to test configuration "+config+ final String err = "Failed to test configuration " + config + ": " + x;
": "+x;
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
log.debug("testConfiguration", x); log.debug("testConfiguration", x);
return err; return err;
@ -730,17 +611,15 @@ public class RmiBootstrapTest {
/** /**
* Test a configuration file which should make the bootstrap fail. * Test a configuration file which should make the bootstrap fail.
* The test is assumed to have succeeded if the bootstrap fails. * The test is assumed to have succeeded if the bootstrap fails.
*
* @return null if the test succeeds, an error message otherwise. * @return null if the test succeeds, an error message otherwise.
**/ **/
private String testConfigurationKo(File conf) throws InterruptedException, IOException { private String testConfigurationKo(File conf) throws InterruptedException, IOException {
String errStr = null; String errStr = testConfiguration(conf);
errStr = testConfiguration(conf);
if (errStr == null) { if (errStr == null) {
return "Configuration " + return "Configuration " + conf + " should have failed!";
conf + " should have failed!";
} }
System.out.println("Configuration " + System.out.println("Configuration " + conf + " failed as expected");
conf + " failed as expected");
log.debug("runko", "Error was: " + errStr); log.debug("runko", "Error was: " + errStr);
return null; return null;
} }
@ -750,6 +629,7 @@ public class RmiBootstrapTest {
* should succeed or fail depending on the file name: * should succeed or fail depending on the file name:
* *ok.properties: bootstrap should succeed. * *ok.properties: bootstrap should succeed.
* *ko.properties: bootstrap or connection should fail. * *ko.properties: bootstrap or connection should fail.
*
* @return null if the test succeeds, an error message otherwise. * @return null if the test succeeds, an error message otherwise.
**/ **/
private String testConfigurationFile(String fileName) throws InterruptedException, IOException { private String testConfigurationFile(String fileName) throws InterruptedException, IOException {
@ -763,19 +643,20 @@ public class RmiBootstrapTest {
if (fileName.endsWith("ko.properties")) { if (fileName.endsWith("ko.properties")) {
return testConfigurationKo(file); return testConfigurationKo(file);
} }
return fileName + return fileName + ": test file suffix must be one of [ko|ok].properties";
": test file suffix must be one of [ko|ok].properties";
} }
/** /**
* Find all *ko.property files and test them. * Find all *ko.property files and test them.
* (see findConfigurationFilesKo() and testConfigurationKo()) * (see findConfigurationFilesKo() and testConfigurationKo())
*
* @throws RuntimeException if the test fails. * @throws RuntimeException if the test fails.
**/ **/
public void runko() throws InterruptedException, IOException { public void runko(boolean useSsl) throws InterruptedException, IOException {
final File[] conf = findConfigurationFilesKo(); final File[] conf = RmiTestBase.findConfigurationFilesKo(useSsl);
if ((conf == null)||(conf.length == 0)) if ((conf == null) || (conf.length == 0)) {
throw new RuntimeException("No configuration found"); throw new RuntimeException("No configuration found");
}
String errStr; String errStr;
for (int i = 0; i < conf.length; i++) { for (int i = 0; i < conf.length; i++) {
@ -790,12 +671,14 @@ public class RmiBootstrapTest {
/** /**
* Find all *ok.property files and test them. * Find all *ok.property files and test them.
* (see findConfigurationFilesOk() and testConfiguration()) * (see findConfigurationFilesOk() and testConfiguration())
*
* @throws RuntimeException if the test fails. * @throws RuntimeException if the test fails.
**/ **/
public void runok() throws InterruptedException, IOException { public void runok(boolean useSsl) throws InterruptedException, IOException {
final File[] conf = findConfigurationFilesOk(); final File[] conf = RmiTestBase.findConfigurationFilesOk(useSsl);
if ((conf == null)||(conf.length == 0)) if ((conf == null) || (conf.length == 0)) {
throw new RuntimeException("No configuration found"); throw new RuntimeException("No configuration found");
}
String errStr = null; String errStr = null;
for (int i = 0; i < conf.length; i++) { for (int i = 0; i < conf.length; i++) {
@ -820,11 +703,12 @@ public class RmiBootstrapTest {
* Finds all configuration files (*ok.properties and *ko.properties) * Finds all configuration files (*ok.properties and *ko.properties)
* and tests them. * and tests them.
* (see runko() and runok()). * (see runko() and runok()).
*
* @throws RuntimeException if the test fails. * @throws RuntimeException if the test fails.
**/ **/
public void run() throws InterruptedException, IOException { public void run(boolean useSsl) throws InterruptedException, IOException {
runok(); runok(useSsl);
runko(); runko(useSsl);
} }
/** /**
@ -834,44 +718,19 @@ public class RmiBootstrapTest {
* Otherwise, the configuration files will be automatically determined * Otherwise, the configuration files will be automatically determined
* by looking at all *.properties files located in the directory * by looking at all *.properties files located in the directory
* indicated by the System property "test.src". * indicated by the System property "test.src".
*
* @throws RuntimeException if the test fails. * @throws RuntimeException if the test fails.
**/ **/
public void run(String args[]) throws InterruptedException, IOException { public void run(String[] args) throws InterruptedException, IOException {
if (args.length == 0) { if (args.length == 1) {
run() ; return; run(args[0].contains("ssl"));
} } else {
for (int i=0; i<args.length; i++) { for (int i = 1; i < args.length; i++) {
final String errStr = testConfigurationFile(args[i]); final String errStr = testConfigurationFile(args[i]);
if (errStr != null) { if (errStr != null) {
throw new RuntimeException(errStr); throw new RuntimeException(errStr);
} }
} }
} }
/**
* Calls run(args[]).
* exit(1) if the test fails.
**/
public static void main(String args[]) throws Exception {
Security.setProperty("jdk.tls.disabledAlgorithms", "");
try {
MAX_GET_FREE_PORT_TRIES = Integer.parseInt(System.getProperty("test.getfreeport.max.tries", "10"));
} catch (NumberFormatException ex) {
} }
RmiBootstrapTest manager = new RmiBootstrapTest();
try {
manager.run(args);
} catch (RuntimeException r) {
System.out.println("Test Failed: "+ r.getMessage());
System.exit(1);
} catch (Throwable t) {
System.out.println("Test Failed: "+ t);
t.printStackTrace();
System.exit(2);
}
System.out.println("**** Test RmiBootstrap Passed ****");
}
} }

View File

@ -1,66 +0,0 @@
#
# Copyright (c) 2003, 2018, 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 6528083
# @key intermittent
# @summary Test RMI Bootstrap
#
# @library /test/lib
#
# @build TestLogger Utils RmiBootstrapTest
# @run shell/timeout=300 RmiBootstrapTest.sh
# Define the Java class test name
TESTCLASS="RmiBootstrapTest"
export TESTCLASS
# Source in utility shell script to generate and remove .properties and .acl files
. ${TESTSRC}/GeneratePropertyPassword.sh
generatePropertyPasswordFiles `ls ${TESTSRC}/*_test*.in`
rm -rf ${TESTCLASSES}/ssl
mkdir -p ${TESTCLASSES}/ssl
cp -rf ${TESTSRC}/ssl/*store ${TESTCLASSES}/ssl
chmod -R 777 ${TESTCLASSES}/ssl
DEBUGOPTIONS=""
export DEBUGOPTIONS
EXTRAOPTIONS="--add-exports jdk.management.agent/jdk.internal.agent=ALL-UNNAMED \
--add-exports jdk.management.agent/sun.management.jmxremote=ALL-UNNAMED"
export EXTRAOPTIONS
# Call the common generic test
#
# No need to since bug 4267864 is now fixed.
#
echo -------------------------------------------------------------
echo Launching test for `basename $0 .sh`
echo -------------------------------------------------------------
sh ${TESTSRC}/../RunTest.sh ${DEBUGOPTIONS} ${EXTRAOPTIONS} ${TESTCLASS}
result=$?
restoreFilePermissions `ls ${TESTSRC}/*_test*.in`
exit $result

View File

@ -1,64 +0,0 @@
#
# Copyright (c) 2003, 2018, 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 6528083
# @summary Test RMI Bootstrap with SSL
#
# @library /test/lib
#
# @build TestLogger Utils RmiBootstrapTest
# @run shell/timeout=300 RmiSslBootstrapTest.sh
# Define the Java class test name
TESTCLASS="RmiBootstrapTest"
export TESTCLASS
# Source in utility shell script to generate and remove .properties and .acl files
. ${TESTSRC}/GeneratePropertyPassword.sh
generatePropertyPasswordFiles `ls ${TESTSRC}/*_ssltest*.in`
rm -rf ${TESTCLASSES}/ssl
mkdir -p ${TESTCLASSES}/ssl
cp -rf ${TESTSRC}/ssl/*store ${TESTCLASSES}/ssl
chmod -R 777 ${TESTCLASSES}/ssl
DEBUGOPTIONS=""
export DEBUGOPTIONS
EXTRAOPTIONS="--add-exports jdk.management.agent/jdk.internal.agent=ALL-UNNAMED \
--add-exports jdk.management.agent/sun.management.jmxremote=ALL-UNNAMED"
export EXTRAOPTIONS
# Call the common generic test
#
echo -------------------------------------------------------------
echo Launching test for `basename $0 .sh`
echo -------------------------------------------------------------
sh ${TESTSRC}/../RunTest.sh ${DEBUGOPTIONS} ${EXTRAOPTIONS} ${TESTCLASS} \
${TESTCLASSES}/management_ssltest*.properties
result=$?
restoreFilePermissions `ls ${TESTSRC}/*_ssltest*.in`
exit $result

View File

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* *
* This code is free software; you can redistribute it and/or modify it * This code is free software; you can redistribute it and/or modify it
@ -20,31 +20,37 @@
* or visit www.oracle.com if you need additional information or have any * or visit www.oracle.com if you need additional information or have any
* questions. * questions.
*/ */
import sun.management.jmxremote.ConnectorBootstrap; import sun.management.jmxremote.ConnectorBootstrap;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Path;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.KeyStore; import java.security.KeyStore;
import java.util.Properties;
import java.util.Iterator;
import java.util.Set;
import java.util.Arrays; import java.util.Arrays;
import java.util.ArrayList; import java.util.List;
import java.util.HashMap; import java.util.Properties;
import java.util.Map;
import java.util.Enumeration;
import javax.management.remote.*;
import javax.management.*;
import jdk.internal.agent.AgentConfigurationError; import jdk.internal.agent.AgentConfigurationError;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
/*
* @test
* @bug 4932854
* @key intermittent
* @summary Test RMI Bootstrap with SSL and no keystore.
*
* @library /test/lib
*
* @run main/timeout=300 RmiSslNoKeyStoreTest .*_ssltest.*.in
* */
/** /**
* <p>This class implements unit test for RMI Bootstrap. * <p>This class implements unit test for RMI Bootstrap.
* When called with no arguments main() looks in the directory indicated * When called with no arguments main() looks in the directory indicated
@ -69,124 +75,48 @@ import jdk.internal.agent.AgentConfigurationError;
* *
* <p>Debug traces are logged in "sun.management.test"</p> * <p>Debug traces are logged in "sun.management.test"</p>
**/ **/
public class RmiSslNoKeyStoreTest { public class RmiSslNoKeyStoreTest extends RmiTestBase {
static TestLogger log =
new TestLogger("RmiSslNoKeyStoreTest");
static TestLogger log = new TestLogger("RmiSslNoKeyStoreTest");
/** /**
* When launching several registries, we increment the port number * When launching several registries, we increment the port number
* to avoid falling into "port number already in use" problems. * to avoid falling into "port number already in use" problems.
**/ **/
static int testPort = 0; static int testPort = 0;
final String DEFAULT_KEY_STORE = defaultStoreNamePrefix + DefaultValues.KEYSTORE;
/** final String KEY_STORE = System.getProperty(PropertyNames.KEYSTORE, DEFAULT_KEY_STORE);
* Default values for RMI configuration properties.
**/
public static interface DefaultValues {
public static final String PORT="0";
public static final String CONFIG_FILE_NAME="management.properties";
public static final String USE_SSL="true";
public static final String USE_AUTHENTICATION="true";
public static final String PASSWORD_FILE_NAME="jmxremote.password";
public static final String ACCESS_FILE_NAME="jmxremote.access";
public static final String KEYSTORE="keystore";
public static final String KEYSTORE_PASSWD="password";
public static final String TRUSTSTORE="truststore";
public static final String TRUSTSTORE_PASSWD="trustword";
}
/**
* Names of RMI configuration properties.
**/
public static interface PropertyNames {
public static final String PORT="com.sun.management.jmxremote.port";
public static final String CONFIG_FILE_NAME=
"com.sun.management.config.file";
public static final String USE_SSL="com.sun.management.jmxremote.ssl";
public static final String USE_AUTHENTICATION=
"com.sun.management.jmxremote.authenticate";
public static final String PASSWORD_FILE_NAME=
"com.sun.management.jmxremote.password.file";
public static final String ACCESS_FILE_NAME=
"com.sun.management.jmxremote.access.file";
public static final String INSTRUMENT_ALL=
"com.sun.management.instrumentall";
public static final String CREDENTIALS =
"jmx.remote.credentials";
public static final String KEYSTORE="javax.net.ssl.keyStore";
public static final String KEYSTORE_PASSWD=
"javax.net.ssl.keyStorePassword";
public static final String KEYSTORE_TYPE="javax.net.ssl.keyStoreType";
public static final String TRUSTSTORE="javax.net.ssl.trustStore";
public static final String TRUSTSTORE_PASSWD=
"javax.net.ssl.trustStorePassword";
}
/**
* Compute the full path name for a default file.
* @param basename basename (with extension) of the default file.
* @return ${JRE}/conf/management/${basename}
**/
private static String getDefaultFileName(String basename) {
final String fileSeparator = File.separator;
final StringBuffer defaultFileName =
new StringBuffer(System.getProperty("java.home")).
append(fileSeparator).append("conf").append(fileSeparator).
append("management").append(fileSeparator).
append(basename);
return defaultFileName.toString();
}
/**
* Compute the full path name for a default file.
* @param basename basename (with extension) of the default file.
* @return ${JRE}/conf/management/${basename}
**/
private static String getDefaultStoreName(String basename) {
final String fileSeparator = File.separator;
final StringBuffer defaultFileName =
new StringBuffer(System.getProperty("test.src")).
append(fileSeparator).append("ssl").append(fileSeparator).
append(basename);
return defaultFileName.toString();
}
private static void checkKeystore(Properties props) private static void checkKeystore(Properties props)
throws IOException, GeneralSecurityException { throws IOException, GeneralSecurityException {
if (log.isDebugOn()) if (log.isDebugOn()) {
log.debug("checkKeystore", "Checking Keystore configuration"); log.debug("checkKeystore", "Checking Keystore configuration");
}
final String keyStore = final String keyStore = System.getProperty(PropertyNames.KEYSTORE);
System.getProperty(PropertyNames.KEYSTORE); if (keyStore == null) {
if (keyStore == null) throw new IllegalArgumentException("System property " + PropertyNames.KEYSTORE + " not specified");
throw new IllegalArgumentException("System property " + }
PropertyNames.KEYSTORE +
" not specified");
final String keyStorePass = final String keyStorePass = System.getProperty(PropertyNames.KEYSTORE_PASSWD);
System.getProperty(PropertyNames.KEYSTORE_PASSWD);
if (keyStorePass == null) { if (keyStorePass == null) {
// We don't have the password, we can only check whether the // We don't have the password, we can only check whether the
// file exists... // file exists...
// //
final File ksf = new File(keyStore); final File ksf = new File(keyStore);
if (! ksf.canRead()) if (!ksf.canRead()) {
throw new IOException(keyStore + ": not readable"); throw new IOException(keyStore + ": not readable");
}
if (log.isDebugOn()) if (log.isDebugOn()) {
log.debug("checkSSL", "No password."); log.debug("checkSSL", "No password.");
throw new IllegalArgumentException("System property " + }
PropertyNames.KEYSTORE_PASSWD + throw new IllegalArgumentException("System property " + PropertyNames.KEYSTORE_PASSWD + " not specified");
" not specified");
} }
// Now we're going to load the keyStore - just to check it's // Now we're going to load the keyStore - just to check it's
// correct. // correct.
// //
final String keyStoreType = final String keyStoreType = System.getProperty(PropertyNames.KEYSTORE_TYPE, KeyStore.getDefaultType());
System.getProperty(PropertyNames.KEYSTORE_TYPE,
KeyStore.getDefaultType());
final KeyStore ks = KeyStore.getInstance(keyStoreType); final KeyStore ks = KeyStore.getInstance(keyStoreType);
final FileInputStream fin = new FileInputStream(keyStore); final FileInputStream fin = new FileInputStream(keyStore);
final char keypassword[] = keyStorePass.toCharArray(); final char keypassword[] = keyStorePass.toCharArray();
@ -198,34 +128,60 @@ public class RmiSslNoKeyStoreTest {
fin.close(); fin.close();
} }
if (log.isDebugOn()) if (log.isDebugOn()) {
log.debug("checkSSL", "SSL configuration successfully checked"); log.debug("checkSSL", "SSL configuration successfully checked");
} }
}
/**
* Calls run(args[]).
* exit(1) if the test fails.
**/
public static void main(String args[]) throws Exception {
if (args.length == 0) {
throw new IllegalArgumentException("Argument is required for this" + " test");
}
final List<Path> credentialFiles = prepareTestFiles(args[0]);
RmiSslNoKeyStoreTest manager = new RmiSslNoKeyStoreTest();
try {
manager.run(args);
} catch (RuntimeException r) {
System.err.println("Test Failed: " + r.getMessage());
System.exit(1);
} catch (Throwable t) {
System.err.println("Test Failed: " + t);
t.printStackTrace();
System.exit(2);
}
System.out.println("**** Test RmiSslNoKeyStoreTest Passed ****");
grantFilesAccess(credentialFiles, AccessControl.EVERYONE);
}
private void checkSslConfiguration() throws Exception { private void checkSslConfiguration() throws Exception {
final String defaultConf = final String defaultConf = defaultFileNamePrefix + DefaultValues.CONFIG_FILE_NAME;
getDefaultFileName(DefaultValues.CONFIG_FILE_NAME); final String confname = System.getProperty(PropertyNames.CONFIG_FILE_NAME, defaultConf);
final String confname =
System.getProperty(PropertyNames.CONFIG_FILE_NAME,defaultConf);
final Properties props = new Properties(); final Properties props = new Properties();
final File conf = new File(confname); final File conf = new File(confname);
if (conf.exists()) { if (conf.exists()) {
FileInputStream fin = new FileInputStream(conf); FileInputStream fin = new FileInputStream(conf);
try {props.load(fin);} finally {fin.close();} try {
props.load(fin);
} finally {
fin.close();
}
} }
// Do we use SSL? // Do we use SSL?
final String useSslStr = final String useSslStr = props.getProperty(PropertyNames.USE_SSL, DefaultValues.USE_SSL);
props.getProperty(PropertyNames.USE_SSL, final boolean useSsl = Boolean.valueOf(useSslStr).booleanValue();
DefaultValues.USE_SSL);
final boolean useSsl =
Boolean.valueOf(useSslStr).booleanValue();
log.debug("checkSslConfiguration", PropertyNames.USE_SSL + "=" + useSsl); log.debug("checkSslConfiguration", PropertyNames.USE_SSL + "=" + useSsl);
if (useSsl == false) { if (useSsl == false) {
final String msg = final String msg = PropertyNames.USE_SSL + "=" + useSsl + ", can't run test";
PropertyNames.USE_SSL+"="+useSsl+", can't run test";
throw new IllegalArgumentException(msg); throw new IllegalArgumentException(msg);
} }
@ -246,6 +202,7 @@ public class RmiSslNoKeyStoreTest {
* Sets the appropriate System properties for config file and * Sets the appropriate System properties for config file and
* port and then calls ConnectorBootstrap.initialize(). * port and then calls ConnectorBootstrap.initialize().
* eventually cleans up by calling ConnectorBootstrap.terminate(). * eventually cleans up by calling ConnectorBootstrap.terminate().
*
* @return null if the test succeeds, an error message otherwise. * @return null if the test succeeds, an error message otherwise.
**/ **/
private String testConfiguration(File file, int port) { private String testConfiguration(File file, int port) {
@ -255,22 +212,20 @@ public class RmiSslNoKeyStoreTest {
try { try {
System.out.println("***"); System.out.println("***");
System.out.println("*** Testing configuration (port="+ System.out.println("*** Testing configuration (port=" + port + "): " + path);
port + "): "+ path);
System.out.println("***"); System.out.println("***");
System.setProperty("com.sun.management.jmxremote.port", System.setProperty("com.sun.management.jmxremote.port", Integer.toString(port));
Integer.toString(port)); if (path != null) {
if (path != null)
System.setProperty("com.sun.management.config.file", path); System.setProperty("com.sun.management.config.file", path);
else } else {
System.getProperties(). System.getProperties().remove("com.sun.management.config.file");
remove("com.sun.management.config.file"); }
log.trace("testConfiguration", "com.sun.management.jmxremote.port=" + port); log.trace("testConfiguration", "com.sun.management.jmxremote.port=" + port);
if (path != null && log.isDebugOn()) if (path != null && log.isDebugOn()) {
log.trace("testConfiguration", log.trace("testConfiguration", "com.sun.management.config.file=" + path);
"com.sun.management.config.file="+path); }
checkSslConfiguration(); checkSslConfiguration();
@ -278,10 +233,8 @@ public class RmiSslNoKeyStoreTest {
try { try {
cs = ConnectorBootstrap.initialize(); cs = ConnectorBootstrap.initialize();
} catch (AgentConfigurationError x) { } catch (AgentConfigurationError x) {
final String err = "Failed to initialize connector:" + final String err = "Failed to initialize connector:" + "\n\tcom.sun.management.jmxremote.port=" + port +
"\n\tcom.sun.management.jmxremote.port=" + port + ((path != null) ? "\n\tcom.sun.management.config.file=" + path : "\n\t" + config) +
((path!=null)?"\n\tcom.sun.management.config.file="+path:
"\n\t"+config) +
"\n\tError is: " + x; "\n\tError is: " + x;
log.trace("testConfiguration", "Expected failure: " + err); log.trace("testConfiguration", "Expected failure: " + err);
@ -293,14 +246,11 @@ public class RmiSslNoKeyStoreTest {
return x.toString(); return x.toString();
} }
try { try {
JMXConnector cc = JMXConnector cc = JMXConnectorFactory.connect(cs.getAddress(), null);
JMXConnectorFactory.connect(cs.getAddress(), null);
cc.close(); cc.close();
} catch (IOException x) { } catch (IOException x) {
final String err = "Failed to initialize connector:" + final String err = "Failed to initialize connector:" + "\n\tcom.sun.management.jmxremote.port=" + port +
"\n\tcom.sun.management.jmxremote.port=" + port + ((path != null) ? "\n\tcom.sun.management.config.file=" + path : "\n\t" + config) +
((path!=null)?"\n\tcom.sun.management.config.file="+path:
"\n\t"+config) +
"\n\tError is: " + x; "\n\tError is: " + x;
log.trace("testConfiguration", "Expected failure: " + err); log.trace("testConfiguration", "Expected failure: " + err);
@ -318,17 +268,13 @@ public class RmiSslNoKeyStoreTest {
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
log.debug("testConfiguration", x); log.debug("testConfiguration", x);
} }
final String err = "Bootstrap should have failed:" + final String err = "Bootstrap should have failed:" + "\n\tcom.sun.management.jmxremote.port=" + port +
"\n\tcom.sun.management.jmxremote.port=" + port + ((path != null) ? "\n\tcom.sun.management.config.file=" + path : "\n\t" + config);
((path!=null)?"\n\tcom.sun.management.config.file="+path:
"\n\t"+config);
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
return err; return err;
} catch (Exception x) { } catch (Exception x) {
final String err = "Failed to test bootstrap for:" + final String err = "Failed to test bootstrap for:" + "\n\tcom.sun.management.jmxremote.port=" + port +
"\n\tcom.sun.management.jmxremote.port=" + port + ((path != null) ? "\n\tcom.sun.management.config.file=" + path : "\n\t" + config) +
((path!=null)?"\n\tcom.sun.management.config.file="+path:
"\n\t"+config)+
"\n\tError is: " + x; "\n\tError is: " + x;
log.trace("testConfiguration", err); log.trace("testConfiguration", err);
@ -342,6 +288,7 @@ public class RmiSslNoKeyStoreTest {
* should succeed or fail depending on the file name: * should succeed or fail depending on the file name:
* *ok.properties: bootstrap should succeed. * *ok.properties: bootstrap should succeed.
* *ko.properties: bootstrap or connection should fail. * *ko.properties: bootstrap or connection should fail.
*
* @return null if the test succeeds, an error message otherwise. * @return null if the test succeeds, an error message otherwise.
**/ **/
private String testConfigurationFile(String fileName) { private String testConfigurationFile(String fileName) {
@ -352,25 +299,11 @@ public class RmiSslNoKeyStoreTest {
return testConfiguration(file, port + testPort++); return testConfiguration(file, port + testPort++);
} }
/** /**
* Tests the specified configuration files. * Test a configuration file.
* If args[] is not empty, each element in args[] is expected to be
* a filename ending either by ok.properties or ko.properties.
* Otherwise, the configuration files will be automatically determined
* by looking at all *.properties files located in the directory
* indicated by the System property "test.src".
* @throws RuntimeException if the test fails.
**/ **/
public void run(String args[]) { private void runConfigurationFile(String fileName) {
final String defaultKeyStore = String errStr = testConfigurationFile(fileName);
getDefaultStoreName(DefaultValues.KEYSTORE);
final String keyStore =
System.getProperty(PropertyNames.KEYSTORE, defaultKeyStore);
for (int i=0; i<args.length; i++) {
String errStr =testConfigurationFile(args[i]);
if (errStr != null) { if (errStr != null) {
throw new RuntimeException(errStr); throw new RuntimeException(errStr);
} }
@ -382,10 +315,10 @@ public class RmiSslNoKeyStoreTest {
// Specify the keystore, but don't specify the // Specify the keystore, but don't specify the
// password. // password.
// //
System.setProperty(PropertyNames.KEYSTORE,keyStore); System.setProperty(PropertyNames.KEYSTORE, KEY_STORE);
log.trace("run",PropertyNames.KEYSTORE+"="+keyStore); log.trace("run", PropertyNames.KEYSTORE + "=" + KEY_STORE);
errStr =testConfigurationFile(args[i]); errStr = testConfigurationFile(fileName);
if (errStr != null) { if (errStr != null) {
throw new RuntimeException(errStr); throw new RuntimeException(errStr);
} }
@ -394,25 +327,41 @@ public class RmiSslNoKeyStoreTest {
} }
} }
} }
/**
* Finds all configuration files (*ok.properties and *ko.properties)
* and tests them.
*
* @throws RuntimeException if the test fails.
**/
public void run(boolean useSsl) throws IOException {
final File[] conf = findAllConfigurationFiles(useSsl);
if ((conf == null) || (conf.length == 0)) {
throw new RuntimeException("No configuration found");
}
for (int i = 0; i < conf.length; i++) {
runConfigurationFile(conf[i].toPath().toString());
}
} }
/** /**
* Calls run(args[]). * Tests the specified configuration files.
* exit(1) if the test fails. * If args[] is not empty, each element in args[] is expected to be
* a filename ending either by ok.properties or ko.properties.
* Otherwise, the configuration files will be automatically determined
* by looking at all *.properties files located in the directory
* indicated by the System property "test.src".
*
* @throws RuntimeException if the test fails.
**/ **/
public static void main(String args[]) { public void run(String args[]) throws IOException {
RmiSslNoKeyStoreTest manager = new RmiSslNoKeyStoreTest(); if (args.length == 1) {
try { run(args[0].contains("ssl"));
manager.run(args); } else {
} catch (RuntimeException r) { for (int i = 1; i < args.length; i++) {
System.err.println("Test Failed: "+ r.getMessage()); runConfigurationFile(args[i]);
System.exit(1); }
} catch (Throwable t) {
System.err.println("Test Failed: "+ t);
t.printStackTrace();
System.exit(2);
} }
System.out.println("**** Test RmiSslNoKeyStoreTest Passed ****");
} }
} }

View File

@ -1,62 +0,0 @@
#
# Copyright (c) 2003, 2015, 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
# @summary Test RMI Bootstrap with SSL and no keystore.
# @bug 4932854
#
# @build TestLogger RmiSslNoKeyStoreTest
# @run shell/timeout=300 RmiSslNoKeyStoreTest.sh
# Define the Java class test name
TESTCLASS="RmiSslNoKeyStoreTest"
export TESTCLASS
# Source in utility shell script to generate and remove .properties and .acl files
. ${TESTSRC}/GeneratePropertyPassword.sh
generatePropertyPasswordFiles `ls ${TESTSRC}/*_ssltest*.in`
rm -rf ${TESTCLASSES}/ssl
mkdir -p ${TESTCLASSES}/ssl
cp -rf ${TESTSRC}/ssl/*store ${TESTCLASSES}/ssl
chmod -R 777 ${TESTCLASSES}/ssl
DEBUGOPTIONS=""
export DEBUGOPTIONS
EXTRAOPTIONS="--add-exports jdk.management.agent/jdk.internal.agent=ALL-UNNAMED \
--add-exports jdk.management.agent/sun.management.jmxremote=ALL-UNNAMED"
export EXTRAOPTIONS
# Call the common generic test
#
echo -------------------------------------------------------------
echo Launching test for `basename $0 .sh`
echo -------------------------------------------------------------
sh ${TESTSRC}/../RunTest.sh ${DEBUGOPTIONS} ${EXTRAOPTIONS} ${TESTCLASS} \
${TESTCLASSES}/management_ssltest*.properties
result=$?
restoreFilePermissions `ls ${TESTSRC}/*_ssltest*.in`
exit $result

View File

@ -0,0 +1,265 @@
/*
* Copyright (c) 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
* 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.
*/
/*
* @library /test/lib
* */
import jdk.test.lib.Platform;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryType;
import java.nio.file.attribute.AclFileAttributeView;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class RmiTestBase {
static final String SEP = System.getProperty("file.separator");
static final String SRC = System.getProperty("test.src");
static final String DEST = System.getProperty("test.classes");
static final String SRC_SSL = SRC + SEP + "ssl";
static final String DEST_SSL = DEST + SEP + "ssl";
static final String TEST_SRC = "@TEST-SRC@";
static final String defaultFileNamePrefix =
System.getProperty("java" + ".home") + SEP + "conf" + SEP + "management" + SEP;
static final String defaultStoreNamePrefix = SRC + SEP + "ssl" + SEP;
/**
* A filter to find all filenames who match <prefix>*<suffix>.
* Note that <prefix> and <suffix> can overlap.
**/
static class FilenameFilterFactory {
static FilenameFilter prefixSuffix(final String p, final String s) {
return (dir, name) -> name.startsWith(p) && name.endsWith(s);
}
}
enum AccessControl {
OWNER,
EVERYONE,
}
/**
* Default values for RMI configuration properties.
**/
public interface DefaultValues {
String PORT = "0";
String CONFIG_FILE_NAME = "management.properties";
String USE_SSL = "true";
String USE_AUTHENTICATION = "true";
String PASSWORD_FILE_NAME = "jmxremote.password";
String ACCESS_FILE_NAME = "jmxremote.access";
String KEYSTORE = "keystore";
String KEYSTORE_PASSWD = "password";
String TRUSTSTORE = "truststore";
String TRUSTSTORE_PASSWD = "trustword";
String SSL_NEED_CLIENT_AUTH = "false";
}
/**
* Names of RMI configuration properties.
**/
public interface PropertyNames {
String PORT = "com.sun.management.jmxremote.port";
String CONFIG_FILE_NAME = "com.sun.management.config.file";
String USE_SSL = "com.sun.management.jmxremote.ssl";
String USE_AUTHENTICATION = "com.sun.management.jmxremote.authenticate";
String PASSWORD_FILE_NAME = "com.sun.management.jmxremote.password.file";
String ACCESS_FILE_NAME = "com.sun.management.jmxremote.access.file";
String INSTRUMENT_ALL = "com.sun.management.instrumentall";
String CREDENTIALS = "jmx.remote.credentials";
String KEYSTORE = "javax.net.ssl.keyStore";
String KEYSTORE_PASSWD = "javax.net.ssl.keyStorePassword";
String KEYSTORE_TYPE = "javax.net.ssl.keyStoreType";
String TRUSTSTORE = "javax.net.ssl.trustStore";
String TRUSTSTORE_PASSWD = "javax.net.ssl.trustStorePassword";
String SSL_ENABLED_CIPHER_SUITES = "com.sun.management.jmxremote.ssl.enabled.cipher.suites";
String SSL_ENABLED_PROTOCOLS = "com.sun.management.jmxremote.ssl.enabled.protocols";
String SSL_NEED_CLIENT_AUTH = "com.sun.management.jmxremote.ssl.need.client.auth";
String SSL_CLIENT_ENABLED_CIPHER_SUITES = "javax.rmi.ssl.client.enabledCipherSuites";
}
/**
* Copy test artifacts to test folder.
*
* @param filenamePattern the filename pattern to look for
* @return files who match the filename pattern
* @throws IOException if error occurs
*/
static List<Path> prepareTestFiles(String filenamePattern) throws IOException {
copySsl();
List<Path> files = Utils.findFiles(Paths.get(SRC), (dir, name) -> name.matches(filenamePattern));
final Function<String, String> removeSuffix = (s) -> s.substring(0, s.lastIndexOf("."));
List<Path> propertyFiles =
Utils.copyFiles(files, Paths.get(DEST), removeSuffix, StandardCopyOption.REPLACE_EXISTING);
// replace @TEST-SRC@ with the path of the current test folder
if (Platform.isWindows()) {
// On Windows, also replace forward slash or single backslash to double backslashes
Utils.replaceFilesString(propertyFiles,
(s) -> s.replace(TEST_SRC, DEST).replaceAll("[/\\\\]", "\\\\\\\\"));
} else {
Utils.replaceFilesString(propertyFiles, (s) -> s.replace(TEST_SRC, DEST));
}
grantFilesAccess(propertyFiles, AccessControl.OWNER);
return Collections.unmodifiableList(files);
}
/**
* Grant file access.
*
* @param file file to grant access
* @param access user access or full access
* @throws IOException if error occurs
*/
static void grantAccess(Path file, AccessControl access) throws IOException {
Set<String> attr = file.getFileSystem().supportedFileAttributeViews();
if (attr.contains("posix")) {
String perms = access == AccessControl.OWNER ? "rw-------" : "rwxrwxrwx";
Files.setPosixFilePermissions(file, PosixFilePermissions.fromString(perms));
} else if (attr.contains("acl")) {
AclFileAttributeView view = Files.getFileAttributeView(file, AclFileAttributeView.class);
List<AclEntry> acl = new ArrayList<>();
for (AclEntry thisEntry : view.getAcl()) {
if (access == AccessControl.OWNER) {
if (thisEntry.principal().getName().equals(view.getOwner().getName())) {
acl.add(Utils.allowAccess(thisEntry));
} else if (thisEntry.type() == AclEntryType.ALLOW) {
acl.add(Utils.revokeAccess(thisEntry));
} else {
acl.add(thisEntry);
}
} else {
if (!thisEntry.principal().getName().contains("NULL SID")
&& thisEntry.type() != AclEntryType.ALLOW) {
acl.add(Utils.allowAccess(thisEntry));
} else {
acl.add(thisEntry);
}
}
}
view.setAcl(acl);
} else {
throw new RuntimeException("Unsupported file attributes: " + attr);
}
}
/**
* Grant files' access.
*
* @param files files to grant access
* @param access user access or full access
* @throws IOException if error occurs
*/
static void grantFilesAccess(List<Path> files, AccessControl access) throws IOException {
for (Path thisFile : files) {
grantAccess(thisFile, access);
}
}
/**
* Copy SSL files to test folder.
*
* @throws IOException
*/
static void copySsl() throws IOException {
Path sslSource = Paths.get(SRC_SSL);
Path sslTarget = Paths.get(DEST_SSL);
List<Path> files = Arrays.stream(sslSource.toFile().listFiles()).map(File::toPath).collect(Collectors.toList());
Utils.copyFiles(files, sslTarget, StandardCopyOption.REPLACE_EXISTING);
for (Path file : files) {
grantAccess(sslTarget.resolve(file.getFileName()), AccessControl.EVERYONE);
}
}
/**
* Get all "management*ok.properties" files in the directory
* indicated by the "test.src" management property.
*
* @param useSsl boolean that indicates if test uses SSL
* @return configuration files
**/
static File[] findConfigurationFilesOk(boolean useSsl) {
String prefix = useSsl ? "management_ssltest" : "management_test";
return findAllConfigurationFiles(prefix, "ok.properties");
}
/**
* Get all "management*ko.properties" files in the directory
* indicated by the "test.src" management property.
*
* @param useSsl boolean that indicates if test uses SSL
* @return configuration files
**/
static File[] findConfigurationFilesKo(boolean useSsl) {
String prefix = useSsl ? "management_ssltest" : "management_test";
return findAllConfigurationFiles(prefix, "ko.properties");
}
/**
* Get all "management*.properties" files in the directory
* indicated by the "test.src" management property.
*
* @param useSsl boolean that indicates if test uses SSL
* @return configuration files
**/
static File[] findAllConfigurationFiles(boolean useSsl) {
String prefix = useSsl ? "management_ssltest" : "management_test";
return findAllConfigurationFiles(prefix, "properties");
}
/**
* Get all "management*.properties" files in the directory
* indicated by the "test.src" management property.
*
* @param prefix filename prefix
* @param suffix filename suffix
* @return configuration files
**/
static File[] findAllConfigurationFiles(String prefix, String suffix) {
final File dir = new File(DEST);
final FilenameFilter filter = FilenameFilterFactory.prefixSuffix(prefix, suffix);
return dir.listFiles(filter);
}
}

View File

@ -21,6 +21,15 @@
* questions. * questions.
*/ */
import java.io.*;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.*;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/** /**
* Utility class. * Utility class.
*/ */
@ -46,4 +55,141 @@ public class Utils {
String newPath = new String(cs); String newPath = new String(cs);
return newPath; return newPath;
} }
/**
* Return file directories that satisfy the specified filter.
*
* @param searchDirectory the base directory to search
* @param filter a filename filter
* @return file directories
*/
public static List<Path> findFiles(Path searchDirectory,
FilenameFilter filter) {
return Arrays.stream(searchDirectory.toFile().listFiles(filter))
.map(f -> f.toPath())
.collect(Collectors.toList());
}
/**
* Copy files to the target path.
*
* @param source the paths to the files to copy
* @param target the path to the target files
* @param filenameMapper mapper function applied to filenames
* @param options options specifying how the copy should be done
* @return the paths to the target files
* @throws IOException if error occurs
*/
public static List<Path> copyFiles(List<Path> source, Path target,
Function<String, String> filenameMapper,
CopyOption... options) throws IOException {
List<Path> result = new ArrayList<>();
if (!target.toFile().exists()) {
Files.createDirectory(target);
}
for (Path file : source) {
if (!file.toFile().exists()) {
continue;
}
String baseName = file.getFileName().toString();
Path targetFile = target.resolve(filenameMapper.apply(baseName));
Files.copy(file, targetFile, options);
result.add(targetFile);
}
return result;
}
/**
* Copy files to the target path.
*
* @param source the paths to the files to copy
* @param target the path to the target files
* @param options options specifying how the copy should be done
* @return the paths to the target files
* @throws IOException if error occurs
*/
public static List<Path> copyFiles(List<Path> source, Path target,
CopyOption... options) throws IOException {
return copyFiles(source, target, (s) -> s, options);
}
/**
* Return an ACL entry that revokes owner access.
*
* @param acl original ACL entry to build from
* @return an ACL entry that revokes all access
*/
public static AclEntry revokeAccess(AclEntry acl) {
return buildAclEntry(acl, AclEntryType.DENY);
}
/**
* Return an ACL entry that allow owner access.
* @param acl original ACL entry to build from
* @return an ACL entry that allows all access
*/
public static AclEntry allowAccess(AclEntry acl) {
return buildAclEntry(acl, AclEntryType.ALLOW);
}
/**
* Build an ACL entry with a given ACL entry type.
*
* @param acl original ACL entry to build from
* @return an ACL entry with a given ACL entry type
*/
public static AclEntry buildAclEntry(AclEntry acl, AclEntryType type) {
return AclEntry.newBuilder()
.setType(type)
.setPrincipal(acl.principal())
.setPermissions(acl.permissions())
.build();
}
/**
* Replace file string by applying the given mapper function.
*
* @param source the file to read
* @param contentMapper the mapper function applied to file's content
* @throws IOException if an I/O error occurs
*/
public static void replaceFileString(Path source,
Function<String, String> contentMapper) throws IOException {
StringBuilder sb = new StringBuilder();
String lineSep = System.getProperty("line.separator");
try (BufferedReader reader =
new BufferedReader(new FileReader(source.toFile()))) {
String line;
// read all and replace all at once??
while ((line = reader.readLine()) != null) {
sb.append(contentMapper.apply(line))
.append(lineSep);
}
}
try (FileWriter writer = new FileWriter(source.toFile())) {
writer.write(sb.toString());
}
}
/**
* Replace files' string by applying the given mapper function.
*
* @param source the file to read
* @param contentMapper the mapper function applied to files' content
* @throws IOException if an I/O error occurs
*/
public static void replaceFilesString(List<Path> source,
Function<String, String> contentMapper) throws IOException {
for (Path file : source) {
replaceFileString(file, contentMapper);
}
}
} }