Path: blob/master/test/jdk/javax/management/security/SecurityTest.java
41149 views
/*1* Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 805886526* @summary Checks various secure ways of connecting from remote jmx client27* @author Olivier Lagneau28* @modules java.management.rmi29* @library /test/lib30* @compile MBS_Light.java ServerDelegate.java TestSampleLoginModule.java31* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dusername=SQE_username -Dpassword=SQE_password SecurityTest -server -mapType x.password.file -client -mapType credentials32* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dusername=UNKNOWN_username -Dpassword=SQE_password SecurityTest -server -mapType x.password.file -client -mapType credentials -expectedThrowable java.lang.SecurityException33* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dusername=SQE_username -Dpassword=WRONG_password SecurityTest -server -mapType x.password.file -client -mapType credentials -expectedThrowable java.lang.SecurityException34* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dsusername=TestJMXAuthenticatorUsername -Dspassword=TestJMXAuthenticatorPassword -Dusername=TestJMXAuthenticatorUsername -Dpassword=TestJMXAuthenticatorPassword SecurityTest -server -mapType x.authenticator -client -mapType credentials35* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dsusername=TestJMXAuthenticatorUsername -Dspassword=TestJMXAuthenticatorPassword -Dusername=AnotherTestJMXAuthenticatorUsername -Dpassword=TestJMXAuthenticatorPassword SecurityTest -server -mapType x.authenticator -client -mapType credentials -expectedThrowable java.lang.SecurityException36* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dlogin.config.file=${test.src}/login.config -Dpassword.file=password.properties -Dusername=usernameFileLoginModule -Dpassword=passwordFileLoginModule SecurityTest -server -mapType x.login.config.PasswordFileAuthentication -client -mapType credentials37* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dlogin.config.file=${test.src}/login.config.UNKNOWN -Dpassword.file=password.properties -Dusername=usernameFileLoginModule -Dpassword=passwordFileLoginModule SecurityTest -server -mapType x.login.config.PasswordFileAuthentication -client -mapType credentialss -expectedThrowable java.lang.SecurityException38* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dlogin.config.file=${test.src}/login.config -Dpassword.file=password.properties -Dusername=usernameFileLoginModule -Dpassword=passwordFileLoginModule SecurityTest -server -mapType x.login.config.UnknownAuthentication -client -mapType credentials -expectedThrowable java.lang.SecurityException39* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dlogin.config.file=${test.src}/login.config -Dsusername=usernameSampleLoginModule -Dspassword=passwordSampleLoginModule -Dpassword.file=password.properties -Dusername=usernameSampleLoginModule -Dpassword=passwordSampleLoginModule SecurityTest -server -mapType x.login.config.SampleLoginModule -client -mapType credentials40* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Dlogin.config.file=${test.src}/login.config -Dsusername=usernameSampleLoginModule -Dspassword=passwordSampleLoginModule -Dpassword.file=password.properties -Dusername=AnotherUsernameSampleLoginModule -Dpassword=passwordSampleLoginModule SecurityTest -server -mapType x.login.config.SampleLoginModule -client -mapType credentials -expectedThrowable java.lang.SecurityException41* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop42* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword WRONG_password -expectedThrowable java.io.IOException43* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.server.socket.factory.ssl -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException44* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException45* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl -keystore keystoreAgent -keystorepassword glopglop -client -expectedThrowable java.io.IOException46* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.need.client.authentication -keystore keystoreAgent -keystorepassword glopglop -truststore truststoreAgent -truststorepassword glopglop -client -keystore keystoreClient -keystorepassword glopglop -truststore truststoreClient -truststorepassword glopglop47* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.need.client.authentication -keystore keystoreAgent -keystorepassword glopglop -truststore truststoreAgent -truststorepassword glopglop -client -keystore keystoreClient -keystorepassword WRONG_password -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException48* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.need.client.authentication -keystore keystoreAgent -keystorepassword glopglop -truststore truststoreAgent -truststorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException49* @run main/othervm/timeout=300 -DDEBUG_STANDARD SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.need.client.authentication -keystore keystoreAgent -keystorepassword glopglop -client -keystore keystoreClient -keystorepassword glopglop -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException50* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Djavax.rmi.ssl.client.enabledCipherSuites=SSL_RSA_WITH_RC4_128_MD5 SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.enabled.cipher.suites.md5 -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop51* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Djavax.rmi.ssl.client.enabledCipherSuites=SSL_RSA_WITH_RC4_128_SHA SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.enabled.cipher.suites.md5 -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException52* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Djavax.rmi.ssl.client.enabledCipherSuites=SSL_RSA_WITH_RC4_128_MD5 SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.enabled.cipher.suites.sha -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException53* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Djavax.rmi.ssl.client.enabledProtocols=SSLv3 SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.enabled.protocols.sslv3 -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop54* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Djavax.rmi.ssl.client.enabledProtocols=TLSv1 SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.enabled.protocols.sslv3 -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException55* @run main/othervm/timeout=300 -DDEBUG_STANDARD -Djavax.rmi.ssl.client.enabledProtocols=SSLv3 SecurityTest -server -mapType rmi.client.socket.factory.ssl;rmi.server.socket.factory.ssl.enabled.protocols.tlsv1 -keystore keystoreAgent -keystorepassword glopglop -client -truststore truststoreClient -truststorepassword glopglop -expectedThrowable java.io.IOException56*/5758import java.io.File;59import java.util.Map ;60import java.util.HashMap ;61import java.util.List;62import java.util.ArrayList;63import java.util.Arrays;6465import javax.management.MBeanServer;66import javax.management.MBeanServerFactory ;67import javax.management.MBeanServerConnection;68import javax.management.remote.JMXConnector;69import javax.management.remote.JMXConnectorFactory;70import javax.management.remote.JMXConnectorServer;71import javax.management.remote.JMXConnectorServerFactory;72import javax.management.remote.JMXServiceURL;7374import javax.management.Attribute ;75import javax.management.ObjectName ;7677import javax.rmi.ssl.SslRMIClientSocketFactory;78import javax.rmi.ssl.SslRMIServerSocketFactory;7980import java.security.Security;8182import jdk.test.lib.JDKToolFinder;83import jdk.test.lib.process.ProcessTools;8485public class SecurityTest {8687static final String SERVER_CLASS_NAME = "SecurityTest";88static final String CLIENT_CLASS_NAME = "SecurityTest$ClientSide";89static final String CLIENT_CLASS_MAIN = CLIENT_CLASS_NAME;9091static final String USERNAME_PROPERTY = "username";92static final String PASSWORD_PROPERTY = "password";9394static final String SERVER_DELEGATE_MBEAN_NAME =95"defaultDomain:class=ServerDelegate";9697static final String RMI_SERVER_SOCKET_FACTORY_SSL = "rmi.server.socket.factory.ssl";98static final String RMI_CLIENT_SOCKET_FACTORY_SSL = "rmi.client.socket.factory.ssl";99static final String KEYSTORE_PROPNAME = "javax.net.ssl.keyStore";100static final String KEYSTORE_PWD_PROPNAME = "javax.net.ssl.keyStorePassword";101static final String TRUSTSTORE_PROPNAME = "javax.net.ssl.trustStore";102static final String TRUSTSTORE_PWD_PROPNAME = "javax.net.ssl.trustStorePassword";103104static final String RMI_SSL_CLIENT_ENABLEDCIPHERSUITES =105"javax.rmi.ssl.client.enabledCipherSuites";106static final String RMI_SSL_CLIENT_ENABLEDPROTOCOLS =107"javax.rmi.ssl.client.enabledProtocols";108109private JMXConnectorServer cs;110111// Construct and set keyStore properties from given map112static void setKeyStoreProperties(Map<String, Object> map) {113114String keyStore = (String) map.get("-keystore");115keyStore = buildSourcePath(keyStore);116System.setProperty(KEYSTORE_PROPNAME, keyStore);117System.out.println("keyStore location = \"" + keyStore + "\"");118119String password = (String) map.get("-keystorepassword");120System.setProperty(KEYSTORE_PWD_PROPNAME, password);121System.out.println("keyStore password = " + password);122123}124125// Construct and set trustStore properties from given map126static void setTrustStoreProperties(Map<String, Object> map) {127128String trustStore = (String) map.get("-truststore");129trustStore = buildSourcePath(trustStore);130System.setProperty(TRUSTSTORE_PROPNAME, trustStore);131System.out.println("trustStore location = \"" + trustStore + "\"");132133String password = (String) map.get("-truststorepassword");134System.setProperty(TRUSTSTORE_PWD_PROPNAME, password);135System.out.println("trustStore password = " + password);136137}138139/*140* First Debug properties and arguments are collect in expected141* map (argName, value) format, then calls original test's run method.142*/143public static void main(String args[]) throws Exception {144145System.out.println("=================================================");146147// Parses parameters148Utils.parseDebugProperties();149150// Supported parameters list format is :151// "MainClass [-server <param-spec> ...] [-client <param-spec> ...]152// with <param-spec> either "-parami valuei" or "-parami"153HashMap<String, Object> serverMap = new HashMap<>() ;154int clientArgsIndex =155Utils.parseServerParameters(args, SERVER_CLASS_NAME, serverMap);156157// Extract and records client params158String[] clientParams = null;159if (clientArgsIndex < args.length) {160int clientParamsSize = args.length - clientArgsIndex;161clientParams = new String[clientParamsSize];162System.arraycopy(args, clientArgsIndex, clientParams, 0, clientParamsSize);163} else {164clientParams = new String[0];165}166167// Run test168SecurityTest test = new SecurityTest();169test.run(serverMap, clientParams);170171}172173// Return full path of filename in the test sopurce directory174private static String buildSourcePath(String filename) {175return System.getProperty("test.src") + File.separator + filename;176}177178/*179* Collects security run params for server side.180*/181private HashMap<String, Object> setServerSecurityEnv(Map<String, Object> map)182throws Exception {183184// Creates Authentication environment from server side params185HashMap<String, Object> env = new HashMap<>();186187// Retrieve and set keystore and truststore config if any188if (map.containsKey("-keystore") &&189map.get("-keystore") != null) {190setKeyStoreProperties(map);191}192System.out.println("Done keystore properties");193194if (map.containsKey("-truststore") &&195map.get("-truststore") != null) {196setTrustStoreProperties(map);197}198System.out.println("Done truststore properties");199200String value = null;201if ((value = (String)map.get("-mapType")) != null) {202203// Case of remote password file with all authorized credentials204if (value.contains("x.password.file")) {205String passwordFileStr = buildSourcePath("password.properties");206env.put("jmx.remote.x.password.file", passwordFileStr);207System.out.println("Added " + passwordFileStr +208" file as jmx.remote.x.password.file");209}210211// Case of dedicated authenticator class : TestJMXAuthenticator212if (value.contains("x.authenticator")) {213env.put("jmx.remote.authenticator", new TestJMXAuthenticator()) ;214System.out.println(215"Added \"jmx.remote.authenticator\" = TestJMXAuthenticator");216}217218// Case of security config file with standard Authentication219if (value.contains("x.login.config.PasswordFileAuthentication")) {220String loginConfig = System.getProperty("login.config.file");221222// Override the default JAAS configuration223System.setProperty("java.security.auth.login.config",224"file:" + loginConfig);225System.out.println("Overrided default JAAS configuration with " +226"\"java.security.auth.login.config\" = \"" + loginConfig + "\"") ;227228env.put("jmx.remote.x.login.config", "PasswordFileAuthentication") ;229System.out.println(230"Added \"jmx.remote.x.login.config\" = " +231"\"PasswordFileAuthentication\"") ;232233// redirects "password.file" property to file in ${test.src}234String passwordFileStr =235buildSourcePath(System.getProperty("password.file"));236System.setProperty("password.file", passwordFileStr);237System.out.println(238"Redirected \"password.file\" property value to = " +239passwordFileStr) ;240}241242// Case of security config file with unexisting athentication config243if (value.contains("x.login.config.UnknownAuthentication")) {244String loginConfig = System.getProperty("login.config.file");245246// Override the default JAAS configuration247System.setProperty("java.security.auth.login.config",248"file:" + loginConfig);249System.out.println("Overrided default JAAS configuration with " +250"\"java.security.auth.login.config\" = \"" + loginConfig + "\"") ;251252env.put("jmx.remote.x.login.config", "UnknownAuthentication") ;253System.out.println(254"Added \"jmx.remote.x.login.config\" = " +255"\"UnknownAuthentication\"") ;256257// redirects "password.file" property to file in ${test.src}258String passwordFileStr =259buildSourcePath(System.getProperty("password.file"));260System.setProperty("password.file", passwordFileStr);261System.out.println(262"Redirected \"password.file\" property value to = " +263passwordFileStr) ;264}265266// Case of security config file with dedicated login module267if (value.contains("x.login.config.SampleLoginModule")) {268String loginConfig = System.getProperty("login.config.file");269270// Override the default JAAS configuration271System.setProperty("java.security.auth.login.config",272"file:" + loginConfig);273System.out.println("Overrided default JAAS configuration with " +274"\"java.security.auth.login.config\" = \"" + loginConfig + "\"") ;275276env.put("jmx.remote.x.login.config", "SampleLoginModule") ;277System.out.println(278"Added \"jmx.remote.x.login.config\" = " +279"\"SampleLoginModule\"") ;280}281282// Simple rmi ssl authentication283if (value.contains(RMI_CLIENT_SOCKET_FACTORY_SSL)) {284env.put("jmx.remote.rmi.client.socket.factory",285new SslRMIClientSocketFactory()) ;286System.out.println(287"Added \"jmx.remote.rmi.client.socket.factory\"" +288" = SslRMIClientSocketFactory") ;289}290291if (value.contains(RMI_SERVER_SOCKET_FACTORY_SSL)) {292if (value.contains(293"rmi.server.socket.factory.ssl.need.client.authentication")) {294// rmi ssl authentication with client authentication295env.put("jmx.remote.rmi.server.socket.factory",296new SslRMIServerSocketFactory(null, null, true)) ;297System.out.println(298"Added \"jmx.remote.rmi.server.socket.factory\"" +299" = SslRMIServerSocketFactory with client authentication") ;300301} else if (value.contains("rmi.server.socket.factory.ssl.enabled.cipher.suites.md5")) {302// Allows all ciphering and protocols for testing purpose303Security.setProperty("jdk.tls.disabledAlgorithms", "");304305env.put("jmx.remote.rmi.server.socket.factory",306new SslRMIServerSocketFactory(307new String[] {"SSL_RSA_WITH_RC4_128_MD5"}, null, false));308System.out.println(309"Added \"jmx.remote.rmi.server.socket.factory\"" +310" = SslRMIServerSocketFactory with SSL_RSA_WITH_RC4_128_MD5 cipher suite");311312} else if (value.contains("rmi.server.socket.factory.ssl.enabled.cipher.suites.sha")) {313// Allows all ciphering and protocols for testing purpose314Security.setProperty("jdk.tls.disabledAlgorithms", "");315316env.put("jmx.remote.rmi.server.socket.factory",317new SslRMIServerSocketFactory(318new String[] { "SSL_RSA_WITH_RC4_128_SHA" }, null, false)) ;319System.out.println(320"Added \"jmx.remote.rmi.server.socket.factory\"" +321" = SslRMIServerSocketFactory with SSL_RSA_WITH_RC4_128_SHA cipher suite") ;322323} else if (value.contains("rmi.server.socket.factory.ssl.enabled.protocols.sslv3")) {324// Allows all ciphering and protocols for testing purpose325Security.setProperty("jdk.tls.disabledAlgorithms", "");326327env.put("jmx.remote.rmi.server.socket.factory",328new SslRMIServerSocketFactory(null, new String[] {"SSLv3"}, false)) ;329System.out.println(330"Added \"jmx.remote.rmi.server.socket.factory\"" +331" = SslRMIServerSocketFactory with SSLv3 protocol") ;332333} else if (value.contains("rmi.server.socket.factory.ssl.enabled.protocols.tlsv1")) {334// Allows all ciphering and protocols for testing purpose335Security.setProperty("jdk.tls.disabledAlgorithms", "");336337env.put("jmx.remote.rmi.server.socket.factory",338new SslRMIServerSocketFactory(null, new String[] {"TLSv1"}, false)) ;339System.out.println(340"Added \"jmx.remote.rmi.server.socket.factory\"" +341" = SslRMIServerSocketFactory with TLSv1 protocol") ;342343} else {344env.put("jmx.remote.rmi.server.socket.factory",345new SslRMIServerSocketFactory());346System.out.println(347"Added \"jmx.remote.rmi.server.socket.factory\"" +348" = SslRMIServerSocketFactory");349}350}351}352353return env;354}355356/*357* Create the MBeansServer side of the test and returns its address358*/359private JMXServiceURL createServerSide(Map<String, Object> serverMap)360throws Exception {361final int NINETY_SECONDS = 90;362363System.out.println("SecurityTest::createServerSide: Start") ;364365// Prepare server side security env366HashMap<String, Object> env = setServerSecurityEnv(serverMap);367368// Create and start mbean server and connector server369MBeanServer mbs = MBeanServerFactory.newMBeanServer();370JMXServiceURL url = new JMXServiceURL("rmi", null, 0);371cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);372cs.start();373374// Waits availibility of connector server375Utils.waitReady(cs, NINETY_SECONDS);376377JMXServiceURL addr = cs.getAddress();378379System.out.println("SecurityTest::createServerSide: Done.") ;380381return addr;382}383384/*385* Creating command-line for running subprocess JVM:386*387* JVM command line is like:388* {test_jdk}/bin/java {defaultopts} -cp {test.class.path} {testopts} main389*390* {defaultopts} are the default java options set by the framework.391*392*/393private List<String> buildCommandLine(String args[]) {394395System.out.println("SecurityTest::buildCommandLine: Start") ;396397List<String> opts = new ArrayList<>();398opts.add(JDKToolFinder.getJDKTool("java"));399opts.addAll(Arrays.asList(jdk.test.lib.Utils.getTestJavaOpts()));400401// We need to forward some properties to the client side402opts.add("-Dtest.src=" + System.getProperty("test.src"));403404String usernameValue = System.getProperty(USERNAME_PROPERTY);405if (usernameValue != null) {406System.out.println("SecurityTest::buildCommandLine: "+407" forward username property to client side");408opts.add("-D" + USERNAME_PROPERTY + "=" + usernameValue);409}410String passwordValue = System.getProperty(PASSWORD_PROPERTY);411if (passwordValue != null) {412System.out.println("SecurityTest::buildCommandLine: "+413" forward password property to client side");414opts.add("-D" + PASSWORD_PROPERTY + "=" + passwordValue);415}416417String enabledCipherSuites =418System.getProperty(RMI_SSL_CLIENT_ENABLEDCIPHERSUITES);419if (enabledCipherSuites != null) {420System.out.println("SecurityTest::buildCommandLine: "+421" forward enabledCipherSuites property to client side");422opts.add("-D" + RMI_SSL_CLIENT_ENABLEDCIPHERSUITES +423"=" + enabledCipherSuites);424}425426String enabledProtocols =427System.getProperty(RMI_SSL_CLIENT_ENABLEDPROTOCOLS);428if (enabledProtocols != null) {429System.out.println("SecurityTest::buildCommandLine: "+430" forward enabledProtocols property to client side");431opts.add("-D" + RMI_SSL_CLIENT_ENABLEDPROTOCOLS +432"=" + enabledProtocols);433}434435opts.add("-cp");436opts.add(System.getProperty("test.class.path", "test.class.path"));437opts.add(CLIENT_CLASS_MAIN);438opts.addAll(Arrays.asList(args));439440System.out.println("SecurityTest::buildCommandLine: Done.") ;441442return opts;443}444445/**446* Runs SecurityTest$ClientSide with the passed options and redirects447* subprocess standard I/O to the current (parent) process. This provides a448* trace of what happens in the subprocess while it is runnning (and before449* it terminates).450*451* @param serviceUrlStr string representing the JMX service Url to connect to.452*/453private int runClientSide(String args[], String serviceUrlStr) throws Exception {454455System.out.println("SecurityTest::runClientSide: Start") ;456457// Building command-line458List<String> opts = buildCommandLine(args);459opts.add("-serviceUrl");460opts.add(serviceUrlStr);461462// Launch separate JVM subprocess463int exitCode = 0;464String[] optsArray = opts.toArray(new String[0]);465ProcessBuilder pb = new ProcessBuilder(optsArray);466Process p = ProcessTools.startProcess("SecurityTest$ClientSide", pb);467468// Handling end of subprocess469try {470exitCode = p.waitFor();471if (exitCode != 0) {472System.out.println(473"Subprocess unexpected exit value of [" + exitCode +474"]. Expected 0.\n");475}476} catch (InterruptedException e) {477System.out.println("Parent process interrupted with exception : \n " + e + " :" );478479// Parent thread unknown state, killing subprocess.480p.destroyForcibly();481482throw new RuntimeException(483"Parent process interrupted with exception : \n " + e + " :" );484485} finally {486if (p.isAlive()) {487p.destroyForcibly();488}489490System.out.println("SecurityTest::runClientSide: Done") ;491492return exitCode;493}494495}496497public void run(Map<String, Object> serverArgs, String clientArgs[]) {498499System.out.println("SecurityTest::run: Start") ;500int errorCount = 0;501502try {503// Initialise the server side504JMXServiceURL urlToUse = createServerSide(serverArgs);505506// Run client side507errorCount = runClientSide(clientArgs, urlToUse.toString());508509if ( errorCount == 0 ) {510System.out.println("SecurityTest::run: Done without any error") ;511} else {512System.out.println(513"SecurityTest::run: Done with " + errorCount + " error(s)");514throw new RuntimeException("errorCount = " + errorCount);515}516517cs.stop();518519} catch(Exception e) {520throw new RuntimeException(e);521}522523}524525private static class ClientSide {526527private JMXConnector cc = null;528private MBeanServerConnection mbsc = null;529530public static void main(String args[]) throws Exception {531532// Parses parameters533Utils.parseDebugProperties();534535// Supported parameters list format is : "MainClass [-client <param-spec> ...]536// with <param-spec> either "-parami valuei" or "-parami"537HashMap<String, Object> clientMap = new HashMap<>() ;538Utils.parseClientParameters(args, CLIENT_CLASS_NAME, clientMap);539540// Run test541ClientSide test = new ClientSide();542test.run(clientMap);543}544545public void run(Map<String, Object> args) {546547System.out.println("ClientSide::run: Start");548int errorCount = 0;549550try {551// Setup client side parameters552HashMap<String, Object> env = new HashMap<>();553554// If needed allows all ciphering and protocols for testing purpose555if (System.getProperty(RMI_SSL_CLIENT_ENABLEDCIPHERSUITES) != null) {556Security.setProperty("jdk.tls.disabledAlgorithms", "");557}558559// If needed allows all ciphering and protocols for testing purpose560if (System.getProperty(RMI_SSL_CLIENT_ENABLEDPROTOCOLS) != null) {561Security.setProperty("jdk.tls.disabledAlgorithms", "");562}563564// Retrieve and set keystore and truststore config if any565if (args.containsKey("-keystore") &&566args.get("-keystore") != null) {567SecurityTest.setKeyStoreProperties(args);568}569if (args.containsKey("-truststore") &&570args.get("-truststore") != null) {571SecurityTest.setTrustStoreProperties(args);572}573574Object value = args.get("-mapType");575if ((value != null) &&576value.equals("credentials")) {577String username = System.getProperty("username");578String password = System.getProperty("password");579Utils.debug(Utils.DEBUG_STANDARD,580"add \"jmx.remote.credentials\" = \"" +581username + "\", \"" + password + "\"");582env.put("jmx.remote.credentials",583new String[] { username , password });584}585586String expectedThrowable = (String) args.get("-expectedThrowable");587588String authCallCountName = "-expectedAuthenticatorCallCount";589int authCallCountValue = 0;590if (args.containsKey(authCallCountName)) {591authCallCountValue =592(new Integer((String) args.get(authCallCountName))).intValue();593}594595try {596// Get a connection to remote mbean server597JMXServiceURL addr = new JMXServiceURL((String)args.get("-serviceUrl"));598cc = JMXConnectorFactory.connect(addr,env);599mbsc = cc.getMBeanServerConnection();600601// In case we should have got an exception602if (expectedThrowable != null) {603System.out.println("ClientSide::run: (ERROR) " +604" Connect did not fail with expected " + expectedThrowable);605errorCount++;606} else {607System.out.println("ClientSide::run: (OK) Connect succeed");608}609} catch (Throwable e) {610Utils.printThrowable(e, true);611if (expectedThrowable != null) {612if (Utils.compareThrowable(e, expectedThrowable)) {613System.out.println("ClientSide::run: (OK) " +614"Connect failed with expected " + expectedThrowable);615} else {616System.out.println("ClientSide::run: (ERROR) Connect failed with " +617e.getClass() + " instead of expected " +618expectedThrowable);619errorCount++;620}621} else {622System.out.println("ClientSide::run: (ERROR) " +623"Connect failed with exception");624errorCount++;625}626}627628// Depending on the client state,629// perform some requests630if (mbsc != null && errorCount == 0) {631// Perform some little JMX requests632System.out.println("ClientSide::run: Start sending requests");633634doRequests();635636// In case authentication has been used we check how it did.637if (authCallCountValue != 0) {638errorCount += checkAuthenticator(mbsc, authCallCountValue);639}640}641} catch (Exception e) {642Utils.printThrowable(e, true);643errorCount++;644} finally {645// Terminate the JMX Client if any646if (cc != null) {647try {648cc.close();649} catch (Exception e) {650Utils.printThrowable(e, true) ;651errorCount++;652}653}654}655656System.out.println("ClientSide::run: Done");657658// Handle result659if (errorCount != 0) {660throw new RuntimeException();661}662}663664private void doRequests() throws Exception {665666// Send some requests to the remote JMX server667ObjectName objName1 =668new ObjectName("TestDomain:class=MBS_Light,rank=1");669String mbeanClass = "MBS_Light";670Exception exception = new Exception("MY TEST EXCEPTION");671Attribute attException = new Attribute("AnException", exception);672Error error = new Error("MY TEST ERROR");673Attribute attError = new Attribute("AnError", error);674String opParamString = "TOTORO";675RjmxMBeanParameter opParam = new RjmxMBeanParameter(opParamString);676Object[] params1 = {opParamString};677String[] sig1 = {"java.lang.String"};678Object[] params2 = {opParam};679String[] sig2 = {"RjmxMBeanParameter"};680681// Create and register the MBean682Utils.debug(Utils.DEBUG_STANDARD,683"ClientSide::doRequests: Create and register the MBean");684mbsc.createMBean(mbeanClass, objName1);685if (!mbsc.isRegistered(objName1)) {686throw new Exception("Unable to register an MBean");687}688689// Set attributes of the MBean690Utils.debug(Utils.DEBUG_STANDARD,691"ClientSide::doRequests: Set attributes of the MBean");692mbsc.setAttribute(objName1, attException);693mbsc.setAttribute(objName1, attError);694695// Get attributes of the MBean696Utils.debug(Utils.DEBUG_STANDARD,697"ClientSide::doRequests: Get attributes of the MBean");698Exception retException =699(Exception) mbsc.getAttribute(objName1,"AnException");700if (!retException.getMessage().equals(exception.getMessage())) {701System.out.println("Expected = " + exception);702System.out.println("Got = " + retException);703throw new Exception("Attribute AnException not as expected");704}705Error retError = (Error) mbsc.getAttribute(objName1, "AnError");706if (!retError.getMessage().equals(error.getMessage())) {707System.out.println("Expected = " + error);708System.out.println("Got = " + retError);709throw new Exception("Attribute AnError not as expected");710}711712// Invoke operations on the MBean713Utils.debug(Utils.DEBUG_STANDARD,714"ClientSide::doRequests: Invoke operations on the MBean");715RjmxMBeanParameter res1 =716(RjmxMBeanParameter) mbsc.invoke(objName1, "operate1", params1, sig1);717if (!res1.equals(opParam)) {718System.out.println("Expected = " + opParam);719System.out.println("Got = " + res1);720throw new Exception("Operation operate1 behaved badly");721}722String res2 =723(String) mbsc.invoke(objName1, "operate2", params2, sig2);724if (!res2.equals(opParamString)) {725System.out.println("Expected = " + opParamString);726System.out.println("Got = " + res2);727throw new Exception("Operation operate2 behaved badly");728}729730// Unregister the MBean731Utils.debug(Utils.DEBUG_STANDARD,732"ClientSide::doRequests: Unregister the MBean");733mbsc.unregisterMBean(objName1);734if (mbsc.isRegistered(objName1)) {735throw new Exception("Unable to unregister an MBean");736}737}738739/**740* Make some check about the instance of TestJMXAuthenticator.741* The authenticator is supposed to have set some properties on742* a ServerDelegate MBean.743* We compare the number of times it has been called with the expected value.744* We also check the Principal that has been given to the authenticator745* was not null.746* That method is of use to authentication with the JSR 262.747* @param mbs748* @param expectedAuthenticatorCallCount749* @return The number of errors encountered.750* @throws java.lang.Exception751*/752protected int checkAuthenticator(MBeanServerConnection mbs,753int expectedAuthenticatorCallCount) throws Exception {754int errorCount = 0;755756// Ensure the authenticator has been called the right number757// of times.758int callCount =759((Integer) mbs.getAttribute(760new ObjectName(SERVER_DELEGATE_MBEAN_NAME),761"TestJMXAuthenticatorCallCount")).intValue();762763if (callCount == expectedAuthenticatorCallCount) {764System.out.println("---- OK Authenticator has been called "765+ expectedAuthenticatorCallCount + " time");766} else {767errorCount++;768System.out.println("---- ERROR Authenticator has been called " + callCount769+ " times in place of " + expectedAuthenticatorCallCount);770}771772// Ensure the provider has been called with773// a non null Principal.774String principalString =775(String) mbs.getAttribute(776new ObjectName(SERVER_DELEGATE_MBEAN_NAME),777"TestJMXAuthenticatorPrincipalString");778779if (principalString == null) {780errorCount++;781System.out.println("---- ERROR Authenticator has been called"782+ " with a null Principal");783} else {784if (principalString.length() > 0) {785System.out.println("---- OK Authenticator has been called"786+ " with the Principal " + principalString);787} else {788errorCount++;789System.out.println("---- ERROR Authenticator has been called"790+ " with an empty Principal");791}792}793794return errorCount;795}796797}798799}800801802