Path: blob/master/test/jdk/sun/management/jmxremote/bootstrap/RmiSslNoKeyStoreTest.java
41153 views
/*1* Copyright (c) 2003, 2004, 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*/22import sun.management.jmxremote.ConnectorBootstrap;2324import java.io.File;25import java.io.FileInputStream;26import java.io.InputStream;27import java.io.FilenameFilter;28import java.io.IOException;2930import java.security.GeneralSecurityException;31import java.security.KeyStore;3233import java.util.Properties;34import java.util.Iterator;35import java.util.Set;36import java.util.Arrays;37import java.util.ArrayList;38import java.util.HashMap;39import java.util.Map;40import java.util.Enumeration;4142import javax.management.remote.*;43import javax.management.*;4445import jdk.internal.agent.AgentConfigurationError;4647/**48* <p>This class implements unit test for RMI Bootstrap.49* When called with no arguments main() looks in the directory indicated50* by the "test.src" system property for files called management*ok.properties51* or management*ko.properties. The *ok.properties files are assumed to be52* valid Java M&M config files for which the bootstrap should succeed.53* The *ko.properties files are assumed to be configurations for which the54* bootstrap & connection test will fail.</p>55*56* <p>The rmi port number can be specified with the "rmi.port" system property.57* If not, this test will use 12424</p>58*59* <p>When called with some argument, the main() will interprete its args to60* be Java M&M configuration file names. The filenames are expected to end61* with ok.properties or ko.properties - and are interpreted as above.</p>62*63* <p>Note that a limitation of the RMI registry (bug 4267864) prevent64* this test from succeeding if more than 1 configuration is used.65* As long as 4267864 isn't fix, this test must be called as many times66* as needed but with a single argument (no arguments, or several arguments67* will fail).</p>68*69* <p>Debug traces are logged in "sun.management.test"</p>70**/71public class RmiSslNoKeyStoreTest {7273static TestLogger log =74new TestLogger("RmiSslNoKeyStoreTest");7576/**77* When launching several registries, we increment the port number78* to avoid falling into "port number already in use" problems.79**/80static int testPort = 0;8182/**83* Default values for RMI configuration properties.84**/85public static interface DefaultValues {86public static final String PORT="0";87public static final String CONFIG_FILE_NAME="management.properties";88public static final String USE_SSL="true";89public static final String USE_AUTHENTICATION="true";90public static final String PASSWORD_FILE_NAME="jmxremote.password";91public static final String ACCESS_FILE_NAME="jmxremote.access";92public static final String KEYSTORE="keystore";93public static final String KEYSTORE_PASSWD="password";94public static final String TRUSTSTORE="truststore";95public static final String TRUSTSTORE_PASSWD="trustword";96}9798/**99* Names of RMI configuration properties.100**/101public static interface PropertyNames {102public static final String PORT="com.sun.management.jmxremote.port";103public static final String CONFIG_FILE_NAME=104"com.sun.management.config.file";105public static final String USE_SSL="com.sun.management.jmxremote.ssl";106public static final String USE_AUTHENTICATION=107"com.sun.management.jmxremote.authenticate";108public static final String PASSWORD_FILE_NAME=109"com.sun.management.jmxremote.password.file";110public static final String ACCESS_FILE_NAME=111"com.sun.management.jmxremote.access.file";112public static final String INSTRUMENT_ALL=113"com.sun.management.instrumentall";114public static final String CREDENTIALS =115"jmx.remote.credentials";116public static final String KEYSTORE="javax.net.ssl.keyStore";117public static final String KEYSTORE_PASSWD=118"javax.net.ssl.keyStorePassword";119public static final String KEYSTORE_TYPE="javax.net.ssl.keyStoreType";120public static final String TRUSTSTORE="javax.net.ssl.trustStore";121public static final String TRUSTSTORE_PASSWD=122"javax.net.ssl.trustStorePassword";123}124125/**126* Compute the full path name for a default file.127* @param basename basename (with extension) of the default file.128* @return ${JRE}/conf/management/${basename}129**/130private static String getDefaultFileName(String basename) {131final String fileSeparator = File.separator;132final StringBuffer defaultFileName =133new StringBuffer(System.getProperty("java.home")).134append(fileSeparator).append("conf").append(fileSeparator).135append("management").append(fileSeparator).136append(basename);137return defaultFileName.toString();138}139140/**141* Compute the full path name for a default file.142* @param basename basename (with extension) of the default file.143* @return ${JRE}/conf/management/${basename}144**/145private static String getDefaultStoreName(String basename) {146final String fileSeparator = File.separator;147final StringBuffer defaultFileName =148new StringBuffer(System.getProperty("test.src")).149append(fileSeparator).append("ssl").append(fileSeparator).150append(basename);151return defaultFileName.toString();152}153154private static void checkKeystore(Properties props)155throws IOException, GeneralSecurityException {156if (log.isDebugOn())157log.debug("checkKeystore","Checking Keystore configuration");158159final String keyStore =160System.getProperty(PropertyNames.KEYSTORE);161if (keyStore == null)162throw new IllegalArgumentException("System property " +163PropertyNames.KEYSTORE +164" not specified");165166final String keyStorePass =167System.getProperty(PropertyNames.KEYSTORE_PASSWD);168if (keyStorePass == null) {169// We don't have the password, we can only check whether the170// file exists...171//172final File ksf = new File(keyStore);173if (! ksf.canRead())174throw new IOException(keyStore + ": not readable");175176if (log.isDebugOn())177log.debug("checkSSL", "No password.");178throw new IllegalArgumentException("System property " +179PropertyNames.KEYSTORE_PASSWD +180" not specified");181}182183// Now we're going to load the keyStore - just to check it's184// correct.185//186final String keyStoreType =187System.getProperty(PropertyNames.KEYSTORE_TYPE,188KeyStore.getDefaultType());189final KeyStore ks = KeyStore.getInstance(keyStoreType);190final FileInputStream fin = new FileInputStream(keyStore);191final char keypassword[] = keyStorePass.toCharArray();192193try {194ks.load(fin,keypassword);195} finally {196Arrays.fill(keypassword,' ');197fin.close();198}199200if (log.isDebugOn())201log.debug("checkSSL","SSL configuration successfully checked");202}203204private void checkSslConfiguration() throws Exception {205final String defaultConf =206getDefaultFileName(DefaultValues.CONFIG_FILE_NAME);207final String confname =208System.getProperty(PropertyNames.CONFIG_FILE_NAME,defaultConf);209210final Properties props = new Properties();211final File conf = new File(confname);212if (conf.exists()) {213FileInputStream fin = new FileInputStream(conf);214try {props.load(fin);} finally {fin.close();}215}216217// Do we use SSL?218final String useSslStr =219props.getProperty(PropertyNames.USE_SSL,220DefaultValues.USE_SSL);221final boolean useSsl =222Boolean.valueOf(useSslStr).booleanValue();223224log.debug("checkSslConfiguration",PropertyNames.USE_SSL+"="+useSsl);225if (useSsl == false) {226final String msg =227PropertyNames.USE_SSL+"="+useSsl+", can't run test";228throw new IllegalArgumentException(msg);229}230231try {232checkKeystore(props);233} catch (Exception x) {234// Ok!235log.debug("checkSslConfiguration","Test configuration OK: " + x);236return;237}238239final String msg = "KeyStore properly configured, can't run test";240throw new IllegalArgumentException(msg);241}242243/**244* Test the configuration indicated by `file'.245* Sets the appropriate System properties for config file and246* port and then calls ConnectorBootstrap.initialize().247* eventually cleans up by calling ConnectorBootstrap.terminate().248* @return null if the test succeeds, an error message otherwise.249**/250private String testConfiguration(File file,int port) {251252final String path = (file==null)?null:file.getAbsolutePath();253final String config = (path==null)?"Default config file":path;254255try {256System.out.println("***");257System.out.println("*** Testing configuration (port="+258port + "): "+ path);259System.out.println("***");260261System.setProperty("com.sun.management.jmxremote.port",262Integer.toString(port));263if (path != null)264System.setProperty("com.sun.management.config.file", path);265else266System.getProperties().267remove("com.sun.management.config.file");268269log.trace("testConfiguration","com.sun.management.jmxremote.port="+port);270if (path != null && log.isDebugOn())271log.trace("testConfiguration",272"com.sun.management.config.file="+path);273274checkSslConfiguration();275276final JMXConnectorServer cs;277try {278cs = ConnectorBootstrap.initialize();279} catch (AgentConfigurationError x) {280final String err = "Failed to initialize connector:" +281"\n\tcom.sun.management.jmxremote.port=" + port +282((path!=null)?"\n\tcom.sun.management.config.file="+path:283"\n\t"+config) +284"\n\tError is: " + x;285286log.trace("testConfiguration","Expected failure: " + err);287log.debug("testConfiguration",x);288System.out.println("Got expected failure: " + x);289return null;290} catch (Exception x) {291log.debug("testConfiguration",x);292return x.toString();293}294try {295JMXConnector cc =296JMXConnectorFactory.connect(cs.getAddress(), null);297cc.close();298} catch (IOException x) {299final String err = "Failed to initialize connector:" +300"\n\tcom.sun.management.jmxremote.port=" + port +301((path!=null)?"\n\tcom.sun.management.config.file="+path:302"\n\t"+config) +303"\n\tError is: " + x;304305log.trace("testConfiguration","Expected failure: " + err);306log.debug("testConfiguration",x);307System.out.println("Got expected failure: " + x);308return null;309} catch (Exception x) {310log.debug("testConfiguration",x);311return x.toString();312}313try {314cs.stop();315} catch (Exception x) {316final String err = "Failed to terminate: "+x;317log.trace("testConfiguration",err);318log.debug("testConfiguration",x);319}320final String err = "Bootstrap should have failed:" +321"\n\tcom.sun.management.jmxremote.port=" + port +322((path!=null)?"\n\tcom.sun.management.config.file="+path:323"\n\t"+config);324log.trace("testConfiguration",err);325return err;326} catch (Exception x) {327final String err = "Failed to test bootstrap for:" +328"\n\tcom.sun.management.jmxremote.port=" + port +329((path!=null)?"\n\tcom.sun.management.config.file="+path:330"\n\t"+config)+331"\n\tError is: " + x;332333log.trace("testConfiguration",err);334log.debug("testConfiguration",x);335return err;336}337}338339/**340* Test a configuration file. Determines whether the bootstrap341* should succeed or fail depending on the file name:342* *ok.properties: bootstrap should succeed.343* *ko.properties: bootstrap or connection should fail.344* @return null if the test succeeds, an error message otherwise.345**/346private String testConfigurationFile(String fileName) {347File file = new File(fileName);348final String portStr = System.getProperty("rmi.port","12424");349final int port = Integer.parseInt(portStr);350351return testConfiguration(file,port+testPort++);352}353354355/**356* Tests the specified configuration files.357* If args[] is not empty, each element in args[] is expected to be358* a filename ending either by ok.properties or ko.properties.359* Otherwise, the configuration files will be automatically determined360* by looking at all *.properties files located in the directory361* indicated by the System property "test.src".362* @throws RuntimeException if the test fails.363**/364public void run(String args[]) {365final String defaultKeyStore =366getDefaultStoreName(DefaultValues.KEYSTORE);367final String keyStore =368System.getProperty(PropertyNames.KEYSTORE, defaultKeyStore);369370for (int i=0; i<args.length; i++) {371372String errStr =testConfigurationFile(args[i]);373if (errStr != null) {374throw new RuntimeException(errStr);375}376377if ((System.getProperty(PropertyNames.KEYSTORE) == null) &&378(System.getProperty(PropertyNames.KEYSTORE_PASSWD) == null)) {379try {380381// Specify the keystore, but don't specify the382// password.383//384System.setProperty(PropertyNames.KEYSTORE,keyStore);385log.trace("run",PropertyNames.KEYSTORE+"="+keyStore);386387errStr =testConfigurationFile(args[i]);388if (errStr != null) {389throw new RuntimeException(errStr);390}391} finally {392System.getProperties().remove(PropertyNames.KEYSTORE);393}394}395}396}397398/**399* Calls run(args[]).400* exit(1) if the test fails.401**/402public static void main(String args[]) {403RmiSslNoKeyStoreTest manager = new RmiSslNoKeyStoreTest();404try {405manager.run(args);406} catch (RuntimeException r) {407System.err.println("Test Failed: "+ r.getMessage());408System.exit(1);409} catch (Throwable t) {410System.err.println("Test Failed: "+ t);411t.printStackTrace();412System.exit(2);413}414System.out.println("**** Test RmiSslNoKeyStoreTest Passed ****");415}416417}418419420