5016517: Replace plaintext passwords by hashed passwords for out-of-the-box JMX Agent
Reviewed-by: rriggs, dfuchs, mchung
This commit is contained in:
parent
800d7ffc3e
commit
46f665881f
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2004, 2017, 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
|
||||
@ -22,22 +22,17 @@
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
package com.sun.jmx.remote.security;
|
||||
|
||||
import com.sun.jmx.mbeanserver.GetPropertyAction;
|
||||
import com.sun.jmx.mbeanserver.Util;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FilePermission;
|
||||
import java.io.IOException;
|
||||
import java.security.AccessControlException;
|
||||
import java.security.AccessController;
|
||||
import java.util.Arrays;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.security.auth.*;
|
||||
import javax.security.auth.callback.*;
|
||||
@ -59,10 +54,7 @@ import com.sun.jmx.remote.util.EnvHelp;
|
||||
* the access control file for JMX remote management or in a Java security
|
||||
* policy.
|
||||
*
|
||||
* <p> The password file comprises a list of key-value pairs as specified in
|
||||
* {@link Properties}. The key represents a user's name and the value is its
|
||||
* associated cleartext password. By default, the following password file is
|
||||
* used:
|
||||
* By default, the following password file is used:
|
||||
* <pre>
|
||||
* ${java.home}/conf/management/jmxremote.password
|
||||
* </pre>
|
||||
@ -105,6 +97,11 @@ import com.sun.jmx.remote.util.EnvHelp;
|
||||
* <dd> if <code>true</code>, this module clears the username and password
|
||||
* stored in the module's shared state after both phases of authentication
|
||||
* (login and commit) have completed.</dd>
|
||||
*
|
||||
* <dt> <code>hashPasswords</code> </dt>
|
||||
* <dd> if <code>true</code>, this module replaces each clear text password
|
||||
* with its hash, if present. </dd>
|
||||
*
|
||||
* </dl>
|
||||
*/
|
||||
public class FileLoginModule implements LoginModule {
|
||||
@ -135,6 +132,7 @@ public class FileLoginModule implements LoginModule {
|
||||
private boolean tryFirstPass = false;
|
||||
private boolean storePass = false;
|
||||
private boolean clearPass = false;
|
||||
private boolean hashPasswords = false;
|
||||
|
||||
// Authentication status
|
||||
private boolean succeeded = false;
|
||||
@ -154,7 +152,7 @@ public class FileLoginModule implements LoginModule {
|
||||
private String passwordFileDisplayName;
|
||||
private boolean userSuppliedPasswordFile;
|
||||
private boolean hasJavaHomePermission;
|
||||
private Properties userCredentials;
|
||||
private HashedPasswordManager hashPwdMgr;
|
||||
|
||||
/**
|
||||
* Initialize this <code>LoginModule</code>.
|
||||
@ -186,6 +184,8 @@ public class FileLoginModule implements LoginModule {
|
||||
"true".equalsIgnoreCase((String)options.get("storePass"));
|
||||
clearPass =
|
||||
"true".equalsIgnoreCase((String)options.get("clearPass"));
|
||||
hashPasswords
|
||||
= "true".equalsIgnoreCase((String) options.get("hashPasswords"));
|
||||
|
||||
passwordFile = (String)options.get("passwordFile");
|
||||
passwordFileDisplayName = passwordFile;
|
||||
@ -221,17 +221,28 @@ public class FileLoginModule implements LoginModule {
|
||||
public boolean login() throws LoginException {
|
||||
|
||||
try {
|
||||
loadPasswordFile();
|
||||
synchronized (this) {
|
||||
if (hashPwdMgr == null) {
|
||||
hashPwdMgr = new HashedPasswordManager(passwordFile, hashPasswords);
|
||||
}
|
||||
}
|
||||
hashPwdMgr.loadPasswords();
|
||||
} catch (IOException ioe) {
|
||||
LoginException le = new LoginException(
|
||||
"Error: unable to load the password file: " +
|
||||
passwordFileDisplayName);
|
||||
throw EnvHelp.initCause(le, ioe);
|
||||
}
|
||||
|
||||
if (userCredentials == null) {
|
||||
throw new LoginException
|
||||
("Error: unable to locate the users' credentials.");
|
||||
} catch (SecurityException e) {
|
||||
if (userSuppliedPasswordFile || hasJavaHomePermission) {
|
||||
throw e;
|
||||
} else {
|
||||
final FilePermission fp
|
||||
= new FilePermission(passwordFileDisplayName, "read");
|
||||
AccessControlException ace = new AccessControlException(
|
||||
"access denied " + fp.toString());
|
||||
ace.initCause(e);
|
||||
throw ace;
|
||||
}
|
||||
}
|
||||
|
||||
if (logger.debugOn()) {
|
||||
@ -437,12 +448,7 @@ public class FileLoginModule implements LoginModule {
|
||||
// get the username and password
|
||||
getUsernamePassword(usePasswdFromSharedState);
|
||||
|
||||
String localPassword;
|
||||
|
||||
// userCredentials is initialized in login()
|
||||
if (((localPassword = userCredentials.getProperty(username)) == null) ||
|
||||
(! localPassword.equals(new String(password)))) {
|
||||
|
||||
if (!hashPwdMgr.authenticate(username, password)) {
|
||||
// username not found or passwords do not match
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("login", "Invalid username or password");
|
||||
@ -468,38 +474,6 @@ public class FileLoginModule implements LoginModule {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Read the password file.
|
||||
*/
|
||||
private void loadPasswordFile() throws IOException {
|
||||
FileInputStream fis;
|
||||
try {
|
||||
fis = new FileInputStream(passwordFile);
|
||||
} catch (SecurityException e) {
|
||||
if (userSuppliedPasswordFile || hasJavaHomePermission) {
|
||||
throw e;
|
||||
} else {
|
||||
final FilePermission fp =
|
||||
new FilePermission(passwordFileDisplayName, "read");
|
||||
AccessControlException ace = new AccessControlException(
|
||||
"access denied " + fp.toString());
|
||||
ace.setStackTrace(e.getStackTrace());
|
||||
throw ace;
|
||||
}
|
||||
}
|
||||
try {
|
||||
final BufferedInputStream bis = new BufferedInputStream(fis);
|
||||
try {
|
||||
userCredentials = new Properties();
|
||||
userCredentials.load(bis);
|
||||
} finally {
|
||||
bis.close();
|
||||
}
|
||||
} finally {
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the username and password.
|
||||
* This method does not return any value.
|
||||
|
@ -0,0 +1,333 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
package com.sun.jmx.remote.security;
|
||||
|
||||
import com.sun.jmx.remote.util.ClassLogger;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.CharBuffer;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* HashedPasswordManager loads passwords from the password file and optionally
|
||||
* hashes them.
|
||||
* <p>
|
||||
* <p>
|
||||
* This class accepts Unicode UTF-8 encoded file
|
||||
* <p>
|
||||
* <p>
|
||||
* Each entry in the password file contains a username followed by a password.
|
||||
* Password can be in clear text or as a hash. Hashed passwords must follow the
|
||||
* below format. hashedPassword = base64_encoded_64_byte_salt W
|
||||
* base64_encoded_hash W hash_algorithm where, W = spaces,
|
||||
* base64_encoded_64_byte_salt = 64 byte random salt, base64_encoded_hash =
|
||||
* hash_algorithm(password + salt), hash_algorithm = Algorithm string as
|
||||
* specified in
|
||||
* <a href="{@docRoot}/../specs/security/standard-names.html#messagedigest-algorithms">
|
||||
* </a>
|
||||
* hash_algorithm is an optional field. If not specified, SHA3-512 will be
|
||||
* assumed.
|
||||
* <p>
|
||||
* <p>
|
||||
* If passwords are in clear, they will be over-written by their hash if hashing
|
||||
* is requested by setting com.sun.management.jmxremote.password.toHashes
|
||||
* property to true in the management.properties file and if the password file
|
||||
* is writable and if the system security policy allows writing into the
|
||||
* password file, if a security manager is configured
|
||||
* <p>
|
||||
* <p>
|
||||
* In order to change the password for a role, replace the hashed password entry
|
||||
* with a new clear text password or a new hashed password. If the new password
|
||||
* is in clear, it will be replaced with its hash when a new login attempt is
|
||||
* made.
|
||||
* <p>
|
||||
* <p>
|
||||
* A given role should have at most one entry in this file. If a role has no
|
||||
* entry, it has no access. If multiple entries are found for the same role
|
||||
* name, then the last one will be used.
|
||||
* <p>
|
||||
* <p>
|
||||
* <p>
|
||||
* A user generated hashed password file can also be used instead of a
|
||||
* clear-text password file. If generated by the user, hashed passwords must
|
||||
* follow the format specified above.
|
||||
*/
|
||||
final public class HashedPasswordManager {
|
||||
|
||||
private static final class UserCredentials {
|
||||
|
||||
private final String userName;
|
||||
private final String hashAlgorithm;
|
||||
private final String b64Salt;
|
||||
private final String b64Hash;
|
||||
|
||||
public UserCredentials(String userName, String hashAlgorithm, String b64Salt, String b64Hash) {
|
||||
this.userName = userName;
|
||||
this.hashAlgorithm = hashAlgorithm;
|
||||
this.b64Salt = b64Salt;
|
||||
this.b64Hash = b64Hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return userName + " " + b64Salt + " " + b64Hash + " " + hashAlgorithm;
|
||||
}
|
||||
}
|
||||
|
||||
private static final String DefaultHashAlgorithm = "SHA3-512";
|
||||
private static final int DefaultSaltLength = 64;
|
||||
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final Map<String, UserCredentials> userCredentialsMap = new HashMap<>();
|
||||
private final String passwordFile;
|
||||
private final boolean shouldHashPasswords;
|
||||
private boolean isLogged = false;
|
||||
|
||||
private static final ClassLogger logger
|
||||
= new ClassLogger("javax.management.remote.misc",
|
||||
"HashedPasswordManager");
|
||||
|
||||
/**
|
||||
* Creates a new password manager for the input password file
|
||||
*
|
||||
* @param filename UTF-8 encoded input file to read passwords from
|
||||
* @param shouldHashPasswords Request for clear passwords to be hashed
|
||||
*/
|
||||
public HashedPasswordManager(String filename, boolean shouldHashPasswords) {
|
||||
this.passwordFile = filename;
|
||||
this.shouldHashPasswords = shouldHashPasswords;
|
||||
}
|
||||
|
||||
private String[] getHash(String algorithm, String password) {
|
||||
try {
|
||||
byte[] salt = new byte[DefaultSaltLength];
|
||||
random.nextBytes(salt);
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
digest.reset();
|
||||
digest.update(salt);
|
||||
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
|
||||
String saltStr = Base64.getEncoder().encodeToString(salt);
|
||||
String hashStr = Base64.getEncoder().encodeToString(hash);
|
||||
|
||||
return new String[]{saltStr, hashStr};
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("getHash", "Invalid algorithm : " + algorithm);
|
||||
}
|
||||
// We should never reach here as default Hash Algorithm
|
||||
// must be always present
|
||||
return new String[]{"", ""};
|
||||
}
|
||||
}
|
||||
|
||||
private String[] readPasswordFile() throws IOException {
|
||||
synchronized (HashedPasswordManager.class) {
|
||||
byte[] data;
|
||||
File f = new File(passwordFile);
|
||||
try (FileInputStream fin = new FileInputStream(f);
|
||||
FileLock lock = fin.getChannel().lock(0L, Long.MAX_VALUE, true)) {
|
||||
data = new byte[(int) f.length()];
|
||||
int read = fin.read(data);
|
||||
if (read != data.length) {
|
||||
throw new IOException("Failed to read data from the password file");
|
||||
}
|
||||
lock.release();
|
||||
}
|
||||
String str = new String(data, StandardCharsets.UTF_8);
|
||||
return str.split("\\r?\\n");
|
||||
}
|
||||
}
|
||||
|
||||
private void writePasswordFile(String input) throws IOException {
|
||||
synchronized (HashedPasswordManager.class) {
|
||||
try (FileOutputStream fout = new FileOutputStream(passwordFile);
|
||||
OutputStreamWriter out = new OutputStreamWriter(fout, StandardCharsets.UTF_8);
|
||||
FileLock lock = fout.getChannel().lock()) {
|
||||
out.write(input);
|
||||
lock.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate the supplied credentials against the one present in the file
|
||||
*
|
||||
* @param userName Input username
|
||||
* @param inputPassword Input password
|
||||
* @return true if authentication succeeds, false otherwise
|
||||
*/
|
||||
public synchronized boolean authenticate(String userName, char[] inputPassword) {
|
||||
if (userCredentialsMap.containsKey(userName)) {
|
||||
try {
|
||||
UserCredentials us = userCredentialsMap.get(userName);
|
||||
byte[] salt = Base64.getDecoder().decode(us.b64Salt);
|
||||
byte[] targetHash = Base64.getDecoder().decode(us.b64Hash);
|
||||
MessageDigest digest = MessageDigest.getInstance(us.hashAlgorithm);
|
||||
digest.reset();
|
||||
digest.update(salt);
|
||||
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(CharBuffer.wrap(inputPassword));
|
||||
byte[] passwordBytes = new byte[byteBuffer.limit()];
|
||||
byteBuffer.get(passwordBytes);
|
||||
byte[] hash = digest.digest(passwordBytes);
|
||||
return Arrays.equals(hash, targetHash);
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("authenticate", "Unrecognized hash algorithm : "
|
||||
+ userCredentialsMap.get(userName).hashAlgorithm
|
||||
+ " - for user : " + userName);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("authenticate", "Unknown user : " + userName);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load passwords from the password file.
|
||||
* <p>
|
||||
* <p>
|
||||
* This method should be called for every login attempt to load new/changed
|
||||
* credentials, if any.
|
||||
* <p>
|
||||
* <p>
|
||||
* If hashing is requested, clear passwords will be over-written with their
|
||||
* SHA3-512 hash
|
||||
*
|
||||
* @throws IOException If unable to access the file
|
||||
* @throws SecurityException If read/write file permissions are not granted
|
||||
*/
|
||||
public synchronized void loadPasswords()
|
||||
throws IOException, SecurityException {
|
||||
|
||||
SecurityManager security = System.getSecurityManager();
|
||||
if (security != null) {
|
||||
security.checkRead(passwordFile);
|
||||
}
|
||||
|
||||
AtomicBoolean hasClearPasswords = new AtomicBoolean(false);
|
||||
StringBuilder sbuf = new StringBuilder();
|
||||
final String header = "# The passwords in this file are hashed.\n"
|
||||
+ "# In order to change the password for a role, replace the hashed "
|
||||
+ "password entry\n"
|
||||
+ "# with a clear text password or a new hashed password. "
|
||||
+ "If the new password is in clear,\n# it will be replaced with its "
|
||||
+ "hash when a new login attempt is made.\n\n";
|
||||
|
||||
userCredentialsMap.clear();
|
||||
Arrays.stream(readPasswordFile()).forEach(line -> {
|
||||
if (line.trim().startsWith("#")) { // Ignore comments
|
||||
sbuf.append(line).append("\n");
|
||||
return;
|
||||
}
|
||||
String[] tokens = line.split("\\s+");
|
||||
switch (tokens.length) {
|
||||
case 2: {
|
||||
// Password is in clear
|
||||
String[] b64str = getHash(DefaultHashAlgorithm, tokens[1]);
|
||||
UserCredentials us = new UserCredentials(tokens[0], DefaultHashAlgorithm, b64str[0], b64str[1]);
|
||||
sbuf.append(us.userName).append(" ").append(us.b64Salt).
|
||||
append(" ").append(us.b64Hash).append(" ").
|
||||
append(us.hashAlgorithm).append("\n");
|
||||
if (userCredentialsMap.get(tokens[0]) != null) {
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("loadPasswords", "Ignoring entry for role : " + tokens[0]);
|
||||
}
|
||||
}
|
||||
userCredentialsMap.put(tokens[0], us);
|
||||
hasClearPasswords.set(true);
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("loadPasswords",
|
||||
"Found atleast one clear password");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 3:
|
||||
case 4: {
|
||||
// Passwords are hashed
|
||||
UserCredentials us = new UserCredentials(tokens[0], (tokens.length == 4 ? tokens[3] : DefaultHashAlgorithm),
|
||||
tokens[1], tokens[2]);
|
||||
sbuf.append(line).append("\n");
|
||||
if (userCredentialsMap.get(tokens[0]) != null) {
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("loadPasswords", "Ignoring entry for role : " + tokens[0]);
|
||||
}
|
||||
}
|
||||
userCredentialsMap.put(tokens[0], us);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
sbuf.append(line).append("\n");
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
if (!shouldHashPasswords && hasClearPasswords.get()) {
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("loadPasswords",
|
||||
"Passwords in " + passwordFile + " are in clear but are requested "
|
||||
+ "not to be hashed !!!");
|
||||
}
|
||||
}
|
||||
|
||||
// Check if header needs to be inserted
|
||||
if (sbuf.indexOf("# The passwords in this file are hashed") != 0) {
|
||||
sbuf.insert(0, header);
|
||||
}
|
||||
|
||||
// Even if we are unable to write hashed passwords to password file,
|
||||
// passwords will be hashed in memory so that jvm heap dump should not
|
||||
// give away clear passwords
|
||||
if (shouldHashPasswords && hasClearPasswords.get()) {
|
||||
if (new File(passwordFile).canWrite()) {
|
||||
writePasswordFile(sbuf.toString());
|
||||
if (logger.debugOn()) {
|
||||
logger.debug("loadPasswords",
|
||||
"Wrote hashed passwords to file : " + passwordFile);
|
||||
}
|
||||
} else if (logger.debugOn() && !isLogged) {
|
||||
isLogged = true;
|
||||
logger.debug("loadPasswords",
|
||||
"Passwords in " + passwordFile + " are in clear and password file is read-only. "
|
||||
+ "Passwords cannot be hashed !!!!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2004, 2008, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2004, 2017, 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
|
||||
@ -34,8 +34,6 @@ import java.security.PrivilegedExceptionAction;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import javax.management.remote.JMXPrincipal;
|
||||
import javax.management.remote.JMXAuthenticator;
|
||||
import javax.security.auth.AuthPermission;
|
||||
import javax.security.auth.Subject;
|
||||
@ -91,10 +89,12 @@ public final class JMXPluggableAuthenticator implements JMXAuthenticator {
|
||||
|
||||
String loginConfigName = null;
|
||||
String passwordFile = null;
|
||||
String hashPasswords = null;
|
||||
|
||||
if (env != null) {
|
||||
loginConfigName = (String) env.get(LOGIN_CONFIG_PROP);
|
||||
passwordFile = (String) env.get(PASSWORD_FILE_PROP);
|
||||
hashPasswords = (String) env.get(HASH_PASSWORDS);
|
||||
}
|
||||
|
||||
try {
|
||||
@ -114,6 +114,7 @@ public final class JMXPluggableAuthenticator implements JMXAuthenticator {
|
||||
}
|
||||
|
||||
final String pf = passwordFile;
|
||||
final String hashPass = hashPasswords;
|
||||
try {
|
||||
loginContext = AccessController.doPrivileged(
|
||||
new PrivilegedExceptionAction<LoginContext>() {
|
||||
@ -122,7 +123,7 @@ public final class JMXPluggableAuthenticator implements JMXAuthenticator {
|
||||
LOGIN_CONFIG_NAME,
|
||||
null,
|
||||
new JMXCallbackHandler(),
|
||||
new FileLoginConfig(pf));
|
||||
new FileLoginConfig(pf, hashPass));
|
||||
}
|
||||
});
|
||||
} catch (PrivilegedActionException pae) {
|
||||
@ -250,6 +251,8 @@ public final class JMXPluggableAuthenticator implements JMXAuthenticator {
|
||||
private static final String LOGIN_CONFIG_NAME = "JMXPluggableAuthenticator";
|
||||
private static final String PASSWORD_FILE_PROP =
|
||||
"jmx.remote.x.password.file";
|
||||
private static final String HASH_PASSWORDS =
|
||||
"jmx.remote.x.password.toHashes";
|
||||
private static final ClassLogger logger =
|
||||
new ClassLogger("javax.management.remote.misc", LOGIN_CONFIG_NAME);
|
||||
|
||||
@ -303,19 +306,22 @@ private static class FileLoginConfig extends Configuration {
|
||||
|
||||
// The option that identifies the password file to use
|
||||
private static final String PASSWORD_FILE_OPTION = "passwordFile";
|
||||
private static final String HASH_PASSWORDS = "hashPasswords";
|
||||
|
||||
/**
|
||||
* Creates an instance of <code>FileLoginConfig</code>
|
||||
*
|
||||
* @param passwordFile A filepath that identifies the password file to use.
|
||||
* If null then the default password file is used.
|
||||
* @param hashPasswords Flag to indicate if the password file needs to be hashed
|
||||
*/
|
||||
public FileLoginConfig(String passwordFile) {
|
||||
public FileLoginConfig(String passwordFile, String hashPasswords) {
|
||||
|
||||
Map<String, String> options;
|
||||
if (passwordFile != null) {
|
||||
options = new HashMap<String, String>(1);
|
||||
options.put(PASSWORD_FILE_OPTION, passwordFile);
|
||||
options.put(HASH_PASSWORDS, hashPasswords);
|
||||
} else {
|
||||
options = Collections.emptyMap();
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2003, 2017, 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
|
||||
@ -70,10 +70,8 @@ import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.rmi.ssl.SslRMIClientSocketFactory;
|
||||
import javax.rmi.ssl.SslRMIServerSocketFactory;
|
||||
import javax.security.auth.Subject;
|
||||
|
||||
import com.sun.jmx.remote.internal.rmi.RMIExporter;
|
||||
import com.sun.jmx.remote.security.JMXPluggableAuthenticator;
|
||||
|
||||
import jdk.internal.agent.Agent;
|
||||
import jdk.internal.agent.AgentConfigurationError;
|
||||
import static jdk.internal.agent.AgentConfigurationError.*;
|
||||
@ -102,6 +100,7 @@ public final class ConnectorBootstrap {
|
||||
public static final String USE_REGISTRY_SSL = "false";
|
||||
public static final String USE_AUTHENTICATION = "true";
|
||||
public static final String PASSWORD_FILE_NAME = "jmxremote.password";
|
||||
public static final String HASH_PASSWORDS = "true";
|
||||
public static final String ACCESS_FILE_NAME = "jmxremote.access";
|
||||
public static final String SSL_NEED_CLIENT_AUTH = "false";
|
||||
}
|
||||
@ -129,6 +128,8 @@ public final class ConnectorBootstrap {
|
||||
"com.sun.management.jmxremote.authenticate";
|
||||
public static final String PASSWORD_FILE_NAME =
|
||||
"com.sun.management.jmxremote.password.file";
|
||||
public static final String HASH_PASSWORDS
|
||||
= "com.sun.management.jmxremote.password.toHashes";
|
||||
public static final String ACCESS_FILE_NAME =
|
||||
"com.sun.management.jmxremote.access.file";
|
||||
public static final String LOGIN_CONFIG_NAME =
|
||||
@ -412,6 +413,7 @@ public final class ConnectorBootstrap {
|
||||
|
||||
String loginConfigName = null;
|
||||
String passwordFileName = null;
|
||||
boolean shouldHashPasswords = true;
|
||||
String accessFileName = null;
|
||||
|
||||
// Initialize settings when authentication is active
|
||||
@ -426,6 +428,11 @@ public final class ConnectorBootstrap {
|
||||
passwordFileName =
|
||||
props.getProperty(PropertyNames.PASSWORD_FILE_NAME,
|
||||
getDefaultFileName(DefaultValues.PASSWORD_FILE_NAME));
|
||||
String hashPasswords
|
||||
= props.getProperty(PropertyNames.HASH_PASSWORDS,
|
||||
DefaultValues.HASH_PASSWORDS);
|
||||
shouldHashPasswords = Boolean.parseBoolean(hashPasswords);
|
||||
|
||||
checkPasswordFile(passwordFileName);
|
||||
}
|
||||
|
||||
@ -474,7 +481,7 @@ public final class ConnectorBootstrap {
|
||||
sslConfigFileName, enabledCipherSuitesList,
|
||||
enabledProtocolsList, sslNeedClientAuth,
|
||||
useAuthentication, loginConfigName,
|
||||
passwordFileName, accessFileName, bindAddress, jmxRmiFilter);
|
||||
passwordFileName, shouldHashPasswords, accessFileName, bindAddress, jmxRmiFilter);
|
||||
cs = data.jmxConnectorServer;
|
||||
url = data.jmxRemoteURL;
|
||||
config("startRemoteConnectorServer",
|
||||
@ -569,6 +576,10 @@ public final class ConnectorBootstrap {
|
||||
throw new AgentConfigurationError(PASSWORD_FILE_NOT_READABLE, passwordFileName);
|
||||
}
|
||||
|
||||
if(!file.canWrite() && PropertyNames.HASH_PASSWORDS.equalsIgnoreCase("true")) {
|
||||
logger.log(Level.WARNING, "");
|
||||
}
|
||||
|
||||
FileSystem fs = FileSystem.open();
|
||||
try {
|
||||
if (fs.supportsFileSecurity(file)) {
|
||||
@ -729,6 +740,7 @@ public final class ConnectorBootstrap {
|
||||
boolean useAuthentication,
|
||||
String loginConfigName,
|
||||
String passwordFileName,
|
||||
boolean shouldHashPasswords,
|
||||
String accessFileName,
|
||||
String bindAddress,
|
||||
String jmxRmiFilter)
|
||||
@ -761,6 +773,9 @@ public final class ConnectorBootstrap {
|
||||
if (passwordFileName != null) {
|
||||
env.put("jmx.remote.x.password.file", passwordFileName);
|
||||
}
|
||||
if (shouldHashPasswords) {
|
||||
env.put("jmx.remote.x.password.toHashes", "true");
|
||||
}
|
||||
|
||||
env.put("jmx.remote.x.access.file", accessFileName);
|
||||
|
||||
|
@ -3,11 +3,12 @@
|
||||
#
|
||||
# o Copy this template to jmxremote.password
|
||||
# o Set the user/password entries in jmxremote.password
|
||||
# o Change the permission of jmxremote.password to read-only
|
||||
# by the owner.
|
||||
# o Change the permission of jmxremote.password to be accessible
|
||||
# only by the owner.
|
||||
# o The jmxremote.passwords file will be re-written by the server
|
||||
# to replace all plain text passwords with hashed passwords when
|
||||
# the file is read by the server.
|
||||
#
|
||||
# See below for the location of jmxremote.password file.
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
##############################################################
|
||||
# Password File for Remote JMX Monitoring
|
||||
@ -24,41 +25,91 @@
|
||||
# the management config file $JRE/conf/management/management.properties
|
||||
# or by specifying a system property (See that file for details).
|
||||
|
||||
|
||||
##############################################################
|
||||
# File permissions of the jmxremote.password file
|
||||
# File format of the jmxremote.password file
|
||||
##############################################################
|
||||
# Since there are cleartext passwords stored in this file,
|
||||
# this file must be readable by ONLY the owner,
|
||||
# otherwise the program will exit with an error.
|
||||
#
|
||||
# The file format for password and access files is syntactically the same
|
||||
# as the Properties file format. The syntax is described in the Javadoc
|
||||
# for java.util.Properties.load.
|
||||
# Typical password file has multiple lines, where each line is blank,
|
||||
# The file contains multiple lines where each line is blank,
|
||||
# a comment (like this one), or a password entry.
|
||||
#
|
||||
# password entry follows the below syntax
|
||||
# role_name W [clearPassword|hashedPassword]
|
||||
#
|
||||
# A password entry consists of a role name and an associated
|
||||
# password. The role name is any string that does not itself contain
|
||||
# spaces or tabs. The password is again any string that does not
|
||||
# contain spaces or tabs. Note that passwords appear in the clear in
|
||||
# this file, so it is a good idea not to use valuable passwords.
|
||||
# role_name is any string that does not itself contain spaces or tabs.
|
||||
# W = spaces or tabs
|
||||
#
|
||||
# Passwords can be specified via clear text or via a hash. Clear text password
|
||||
# is any string that does not contain spaces or tabs. Hashed passwords must
|
||||
# follow the below format.
|
||||
# hashedPassword = base64_encoded_64_byte_salt W base64_encoded_hash W hash_algorithm
|
||||
# where,
|
||||
# base64_encoded_64_byte_salt = 64 byte random salt
|
||||
# base64_encoded_hash = Hash_algorithm(password + salt)
|
||||
# W = spaces or tabs
|
||||
# hash_algorithm = Algorithm string specified using the format below
|
||||
# https://docs.oracle.com/javase/9/docs/specs/security/standard-names.html#messagedigest-algorithms
|
||||
# This is an optional field. If not specified, SHA3-512 will be assumed.
|
||||
#
|
||||
# If passwords are in clear, they will be overwritten by their hash if all of
|
||||
# the below criteria are met.
|
||||
# * com.sun.management.jmxremote.password.toHashes property is set to true in
|
||||
# management.properties file
|
||||
# * the password file is writable
|
||||
# * the system security policy allows writing into the password file, if a
|
||||
# security manager is configured
|
||||
#
|
||||
# In order to change the password for a role, replace the hashed password entry
|
||||
# with a new clear text password or a new hashed password. If the new password
|
||||
# is in clear, it will be replaced with its hash when a new login attempt is made.
|
||||
#
|
||||
# A given role should have at most one entry in this file. If a role
|
||||
# has no entry, it has no access.
|
||||
# If multiple entries are found for the same role name, then the last one
|
||||
# is used.
|
||||
#
|
||||
# In a typical installation, this file can be read by anybody on the
|
||||
# A user generated hashed password file can also be used instead of clear-text
|
||||
# password file. If generated by the user, hashed passwords must follow the
|
||||
# format specified above.
|
||||
#
|
||||
# Caution: It is recommended not to edit the password file while the
|
||||
# agent is running, as edits could be lost if a client connection triggers the
|
||||
# hashing of the password file at the same time that the file is externally modified.
|
||||
# The integrity of the file is guaranteed, but any external edits made to the
|
||||
# file during the short period between the time that the agent reads the file
|
||||
# and the time that it writes it back might get lost
|
||||
|
||||
##############################################################
|
||||
# File permissions of the jmxremote.password file
|
||||
##############################################################
|
||||
# This file must be made accessible by ONLY the owner,
|
||||
# otherwise the program will exit with an error.
|
||||
#
|
||||
# In a typical installation, this file can be accessed by anybody on the
|
||||
# local machine, and possibly by people on other machines.
|
||||
# For # security, you should either restrict the access to this file,
|
||||
# For security, you should either restrict the access to this file except for owner,
|
||||
# or specify another, less accessible file in the management config file
|
||||
# as described above.
|
||||
#
|
||||
# Following are two commented-out entries. The "measureRole" role has
|
||||
# password "QED". The "controlRole" role has password "R&D".
|
||||
# In order to prevent inadverent edits to the password file in the
|
||||
# production environment, it is recommended to deploy a read-only
|
||||
# hashed password file. The hashed entries for clear passwords can be generated
|
||||
# in advance by running the JMX agent.
|
||||
#
|
||||
# monitorRole QED
|
||||
# controlRole R&D
|
||||
|
||||
##############################################################
|
||||
# Sample of the jmxremote.password file
|
||||
##############################################################
|
||||
# Following are two commented-out entries. The "monitorRole" role has
|
||||
# password "QED". The "controlRole" role has password "R&D". This is an example
|
||||
# of specifying passwords in the clear
|
||||
#
|
||||
# monitorRole QED
|
||||
# controlRole R&D
|
||||
#
|
||||
# Once a login attempt is made, passwords will be hashed and the file will have
|
||||
# below entries with clear passwords overwritten by their respective
|
||||
# SHA3-512 hash
|
||||
#
|
||||
# monitorRole trilby APzBTt34rV2l+OMbuvbnOQ4si8UZmfRCVbIY1+fAofV5CkQzXS/FDMGteQQk/R3q1wtt104qImzJEA7gCwl6dw== 4EeTdSJ7X6Imu0Mb+dWqIns7a7QPIBoM3NB/XlpMQSPSicE7PnlALVWn2pBY3Q3pGDHyAb32Hd8GUToQbUhAjA== SHA3-512
|
||||
# controlRole roHEJSbRqSSTII4Z4+NOCV2OJaZVQ/dw153Fy2u4ILDP9XiZ426GwzCzc3RtpoqNMwqYIcfdd74xWXSMrWtGaA== w9qDsekgKn0WOVJycDyU0kLBa081zbStcCjUAVEqlfon5Sgx7XHtaodbmzpLegA1jT7Ag36T0zHaEWRHJe2fdA== SHA3-512
|
||||
#
|
@ -300,6 +300,17 @@
|
||||
# For a non-default password file location use the following line
|
||||
# com.sun.management.jmxremote.password.file=filepath
|
||||
|
||||
#
|
||||
# ################# Hash passwords in password file ##############
|
||||
# com.sun.management.jmxremote.password.toHashes = true|false
|
||||
# Default for this property is true.
|
||||
# Specifies if passwords in the password file should be hashed or not.
|
||||
# If this property is true, and if the password file is writable, and if the
|
||||
# system security policy allows writing into the password file,
|
||||
# all the clear passwords in the password file will be replaced by
|
||||
# their SHA3-512 hash when the file is read by the server
|
||||
#
|
||||
|
||||
#
|
||||
# ################ RMI Access file location #####################
|
||||
#
|
||||
|
514
test/jdk/javax/management/security/HashedPasswordFileTest.java
Normal file
514
test/jdk/javax/management/security/HashedPasswordFileTest.java
Normal file
@ -0,0 +1,514 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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 5016517
|
||||
* @summary Test Hashed passwords
|
||||
* @library /test/lib
|
||||
* @modules java.management
|
||||
* @build HashedPasswordFileTest
|
||||
* @run testng/othervm HashedPasswordFileTest
|
||||
*
|
||||
*/
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.net.MalformedURLException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.*;
|
||||
import javax.management.MBeanServer;
|
||||
import javax.management.remote.JMXConnector;
|
||||
import javax.management.remote.JMXConnectorFactory;
|
||||
import javax.management.remote.JMXConnectorServer;
|
||||
import javax.management.remote.JMXConnectorServerFactory;
|
||||
import javax.management.remote.JMXServiceURL;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.Test;
|
||||
import org.testng.annotations.AfterClass;
|
||||
|
||||
import jdk.test.lib.Utils;
|
||||
import jdk.test.lib.process.ProcessTools;
|
||||
|
||||
@Test
|
||||
public class HashedPasswordFileTest {
|
||||
|
||||
private final String[] randomWords = {"accost", "savoie", "bogart", "merest",
|
||||
"azuela", "hoodie", "bursal", "lingua", "wincey", "trilby", "egesta",
|
||||
"wester", "gilgai", "weinek", "ochone", "sanest", "gainst", "defang",
|
||||
"ranket", "mayhem", "tagger", "timber", "eggcup", "mhren", "colloq",
|
||||
"dreamy", "hattie", "rootle", "bloody", "helyne", "beater", "cosine",
|
||||
"enmity", "outbox", "issuer", "lumina", "dekker", "vetoed", "dennis",
|
||||
"strove", "gurnet", "talkie", "bennie", "behove", "coates", "shiloh",
|
||||
"yemeni", "boleyn", "coaxal", "irne"};
|
||||
|
||||
private final String[] hashAlgs = {
|
||||
"MD2",
|
||||
"MD5",
|
||||
"SHA-1",
|
||||
"SHA-224",
|
||||
"SHA-256",
|
||||
"SHA-384",
|
||||
"SHA-512/224",
|
||||
"SHA-512/256",
|
||||
"SHA3-224",
|
||||
"SHA3-256",
|
||||
"SHA3-384",
|
||||
"SHA3-512"
|
||||
};
|
||||
|
||||
private final Random rnd = new Random();
|
||||
private final Random random = Utils.getRandomInstance();
|
||||
|
||||
private JMXConnectorServer cs;
|
||||
|
||||
private String randomWord() {
|
||||
int idx = rnd.nextInt(randomWords.length);
|
||||
return randomWords[idx];
|
||||
}
|
||||
|
||||
private String[] getHash(String algorithm, String password) {
|
||||
try {
|
||||
byte[] salt = new byte[64];
|
||||
random.nextBytes(salt);
|
||||
|
||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
digest.reset();
|
||||
digest.update(salt);
|
||||
byte[] hash = digest.digest(password.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
String saltStr = Base64.getEncoder().encodeToString(salt);
|
||||
String hashStr = Base64.getEncoder().encodeToString(hash);
|
||||
|
||||
return new String[]{saltStr, hashStr};
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new RuntimeException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private String getPasswordFilePath() {
|
||||
String testDir = System.getProperty("test.src");
|
||||
String testFileName = "jmxremote.password";
|
||||
return testDir + File.separator + testFileName;
|
||||
}
|
||||
|
||||
private File createNewPasswordFile() throws IOException {
|
||||
File file = new File(getPasswordFilePath());
|
||||
if (file.exists()) {
|
||||
file.delete();
|
||||
}
|
||||
file.createNewFile();
|
||||
return file;
|
||||
}
|
||||
|
||||
private Map<String, String> generateClearTextPasswordFile() throws IOException {
|
||||
File file = createNewPasswordFile();
|
||||
Map<String, String> props = new HashMap<>();
|
||||
BufferedWriter br;
|
||||
try (FileWriter fw = new FileWriter(file)) {
|
||||
br = new BufferedWriter(fw);
|
||||
int numentries = rnd.nextInt(5) + 3;
|
||||
for (int i = 0; i < numentries; i++) {
|
||||
String username = randomWord();
|
||||
String password = randomWord();
|
||||
props.put(username, password);
|
||||
br.write(username + " " + password + "\n");
|
||||
}
|
||||
br.flush();
|
||||
}
|
||||
br.close();
|
||||
return props;
|
||||
}
|
||||
|
||||
private boolean isPasswordFileHashed() throws IOException {
|
||||
BufferedReader br;
|
||||
boolean result;
|
||||
try (FileReader fr = new FileReader(getPasswordFilePath())) {
|
||||
br = new BufferedReader(fr);
|
||||
result = br.lines().anyMatch(line -> {
|
||||
if (line.startsWith("#")) {
|
||||
return false;
|
||||
}
|
||||
String[] tokens = line.split("\\s+");
|
||||
return tokens.length == 3 || tokens.length == 4;
|
||||
});
|
||||
}
|
||||
br.close();
|
||||
return result;
|
||||
}
|
||||
|
||||
private Map<String, String> generateHashedPasswordFile() throws IOException {
|
||||
File file = createNewPasswordFile();
|
||||
Map<String, String> props = new HashMap<>();
|
||||
BufferedWriter br;
|
||||
try (FileWriter fw = new FileWriter(file)) {
|
||||
br = new BufferedWriter(fw);
|
||||
int numentries = rnd.nextInt(5) + 3;
|
||||
for (int i = 0; i < numentries; i++) {
|
||||
String username = randomWord();
|
||||
String password = randomWord();
|
||||
String alg = hashAlgs[rnd.nextInt(hashAlgs.length)];
|
||||
String[] b64str = getHash(alg, password);
|
||||
br.write(username + " " + b64str[0] + " " + b64str[1] + " " + alg + "\n");
|
||||
props.put(username, password);
|
||||
}
|
||||
br.flush();
|
||||
}
|
||||
br.close();
|
||||
return props;
|
||||
}
|
||||
|
||||
private JMXServiceURL createServerSide(boolean useHash)
|
||||
throws IOException {
|
||||
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
|
||||
JMXServiceURL url = new JMXServiceURL("rmi", null, 0);
|
||||
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.x.password.file", getPasswordFilePath());
|
||||
env.put("jmx.remote.x.password.toHashes", useHash ? "true" : "false");
|
||||
cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
|
||||
cs.start();
|
||||
return cs.getAddress();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testClearTextPasswordFile() throws IOException {
|
||||
Boolean[] bvals = new Boolean[]{true, false};
|
||||
for (boolean bval : bvals) {
|
||||
try {
|
||||
Map<String, String> credentials = generateClearTextPasswordFile();
|
||||
JMXServiceURL serverUrl = createServerSide(bval);
|
||||
for (Map.Entry<String, String> entry : credentials.entrySet()) {
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.credentials",
|
||||
new String[]{entry.getKey(), entry.getValue()});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(serverUrl, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
}
|
||||
Assert.assertEquals(isPasswordFileHashed(), bval);
|
||||
} finally {
|
||||
cs.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testReadOnlyPasswordFile() throws IOException {
|
||||
Boolean[] bvals = new Boolean[]{true, false};
|
||||
for (boolean bval : bvals) {
|
||||
try {
|
||||
Map<String, String> credentials = generateClearTextPasswordFile();
|
||||
File file = new File(getPasswordFilePath());
|
||||
file.setReadOnly();
|
||||
JMXServiceURL serverUrl = createServerSide(bval);
|
||||
for (Map.Entry<String, String> entry : credentials.entrySet()) {
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.credentials",
|
||||
new String[]{entry.getKey(), entry.getValue()});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(serverUrl, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
}
|
||||
Assert.assertEquals(isPasswordFileHashed(), false);
|
||||
} finally {
|
||||
cs.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashedPasswordFile() throws IOException {
|
||||
Boolean[] bvals = new Boolean[]{true, false};
|
||||
for (boolean bval : bvals) {
|
||||
try {
|
||||
Map<String, String> credentials = generateHashedPasswordFile();
|
||||
JMXServiceURL serverUrl = createServerSide(bval);
|
||||
Assert.assertEquals(isPasswordFileHashed(), true);
|
||||
for (Map.Entry<String, String> entry : credentials.entrySet()) {
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.credentials",
|
||||
new String[]{entry.getKey(), entry.getValue()});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(serverUrl, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
cs.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class SimpleJMXClient implements Callable {
|
||||
private final JMXServiceURL url;
|
||||
private final Map<String, String> credentials;
|
||||
|
||||
public SimpleJMXClient(JMXServiceURL url, Map<String, String> credentials) {
|
||||
this.url = url;
|
||||
this.credentials = credentials;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object call() throws Exception {
|
||||
for (Map.Entry<String, String> entry : credentials.entrySet()) {
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.credentials",
|
||||
new String[]{entry.getKey(), entry.getValue()});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(url, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleClients() throws Throwable {
|
||||
Map<String, String> credentials = generateClearTextPasswordFile();
|
||||
JMXServiceURL serverUrl = createServerSide(true);
|
||||
Assert.assertEquals(isPasswordFileHashed(), false);
|
||||
// create random number of clients
|
||||
int numClients = rnd.nextInt(20) + 10;
|
||||
List<Future> futures = new ArrayList<>();
|
||||
ExecutorService executor = Executors.newFixedThreadPool(numClients);
|
||||
for (int i = 0; i < numClients; i++) {
|
||||
Future future = executor.submit(new SimpleJMXClient(serverUrl, credentials));
|
||||
futures.add(future);
|
||||
}
|
||||
try {
|
||||
for (Future future : futures) {
|
||||
future.get();
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException ex) {
|
||||
throw ex.getCause();
|
||||
} finally {
|
||||
executor.shutdown();
|
||||
}
|
||||
|
||||
Assert.assertEquals(isPasswordFileHashed(), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPasswordChange() throws IOException {
|
||||
try {
|
||||
Map<String, String> credentials = generateClearTextPasswordFile();
|
||||
JMXServiceURL serverUrl = createServerSide(true);
|
||||
Assert.assertEquals(isPasswordFileHashed(), false);
|
||||
|
||||
for (Map.Entry<String, String> entry : credentials.entrySet()) {
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.credentials",
|
||||
new String[]{entry.getKey(), entry.getValue()});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(serverUrl, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
}
|
||||
Assert.assertEquals(isPasswordFileHashed(), true);
|
||||
|
||||
// Read the file back. Add new entries. Change passwords for few
|
||||
BufferedReader br = new BufferedReader(new FileReader(getPasswordFilePath()));
|
||||
String line;
|
||||
StringBuilder sbuild = new StringBuilder();
|
||||
while ((line = br.readLine()) != null) {
|
||||
if (line.trim().startsWith("#")) {
|
||||
sbuild.append(line).append("\n");
|
||||
continue;
|
||||
}
|
||||
String[] tokens = line.split("\\s+");
|
||||
// Change password for random entries
|
||||
if ((tokens.length == 4 || tokens.length == 3) && rnd.nextBoolean()) {
|
||||
String password = randomWord();
|
||||
credentials.put(tokens[0], password);
|
||||
sbuild.append(tokens[0]).append(" ").append(password).append("\n");
|
||||
} else {
|
||||
sbuild.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Add new entries in clear
|
||||
int newentries = rnd.nextInt(2) + 3;
|
||||
for (int i = 0; i < newentries; i++) {
|
||||
String username = randomWord();
|
||||
String password = randomWord();
|
||||
credentials.put(username, password);
|
||||
sbuild.append(username).append(" ").append(password).append("\n");
|
||||
}
|
||||
|
||||
// Add new entries as a hash
|
||||
int numentries = rnd.nextInt(2) + 3;
|
||||
for (int i = 0; i < numentries; i++) {
|
||||
String username = randomWord();
|
||||
String password = randomWord();
|
||||
String alg = hashAlgs[rnd.nextInt(hashAlgs.length)];
|
||||
String[] b64str = getHash(alg, password);
|
||||
credentials.put(username, password);
|
||||
sbuild.append(username).append(" ").append(b64str[0])
|
||||
.append(" ").append(b64str[1]).append(" ")
|
||||
.append(alg).append("\n");
|
||||
}
|
||||
|
||||
try (BufferedWriter bw = new BufferedWriter(new FileWriter(getPasswordFilePath()))) {
|
||||
bw.write(sbuild.toString());
|
||||
}
|
||||
|
||||
for (Map.Entry<String, String> entry : credentials.entrySet()) {
|
||||
HashMap<String, Object> env = new HashMap<>();
|
||||
env.put("jmx.remote.credentials",
|
||||
new String[]{entry.getKey(), entry.getValue()});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(serverUrl, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
cs.stop();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultAgent() throws Exception {
|
||||
List<String> pbArgs = new ArrayList<>();
|
||||
int port = Utils.getFreePort();
|
||||
generateClearTextPasswordFile();
|
||||
|
||||
// This will run only on a POSIX compliant system
|
||||
if (!FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure only owner is able to read/write the file or else
|
||||
// default agent will fail to start
|
||||
File file = new File(getPasswordFilePath());
|
||||
Set<PosixFilePermission> perms = new HashSet<>();
|
||||
perms.add(PosixFilePermission.OWNER_READ);
|
||||
perms.add(PosixFilePermission.OWNER_WRITE);
|
||||
Files.setPosixFilePermissions(file.toPath(), perms);
|
||||
|
||||
pbArgs.add("-cp");
|
||||
pbArgs.add(System.getProperty("test.class.path"));
|
||||
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.port=" + port);
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.authenticate=true");
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.password.file=" + file.getAbsolutePath());
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.ssl=false");
|
||||
pbArgs.add(TestApp.class.getSimpleName());
|
||||
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
|
||||
pbArgs.toArray(new String[0]));
|
||||
Process process = ProcessTools.startProcess(
|
||||
TestApp.class.getSimpleName(),
|
||||
pb);
|
||||
|
||||
if (process.waitFor() != 0) {
|
||||
throw new RuntimeException("Test Failed : Error starting default agent");
|
||||
}
|
||||
Assert.assertEquals(isPasswordFileHashed(), true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDefaultAgentNoHash() throws Exception {
|
||||
List<String> pbArgs = new ArrayList<>();
|
||||
int port = Utils.getFreePort();
|
||||
generateClearTextPasswordFile();
|
||||
|
||||
// This will run only on a POSIX compliant system
|
||||
if (!FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure only owner is able to read/write the file or else
|
||||
// default agent will fail to start
|
||||
File file = new File(getPasswordFilePath());
|
||||
Set<PosixFilePermission> perms = new HashSet<>();
|
||||
perms.add(PosixFilePermission.OWNER_READ);
|
||||
perms.add(PosixFilePermission.OWNER_WRITE);
|
||||
Files.setPosixFilePermissions(file.toPath(), perms);
|
||||
|
||||
pbArgs.add("-cp");
|
||||
pbArgs.add(System.getProperty("test.class.path"));
|
||||
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.port=" + port);
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.authenticate=true");
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.password.file=" + file.getAbsolutePath());
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.password.toHashes=false");
|
||||
pbArgs.add("-Dcom.sun.management.jmxremote.ssl=false");
|
||||
pbArgs.add(TestApp.class.getSimpleName());
|
||||
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
|
||||
pbArgs.toArray(new String[0]));
|
||||
Process process = ProcessTools.startProcess(
|
||||
TestApp.class.getSimpleName(),
|
||||
pb);
|
||||
|
||||
if (process.waitFor() != 0) {
|
||||
throw new RuntimeException("Test Failed : Error starting default agent");
|
||||
}
|
||||
Assert.assertEquals(isPasswordFileHashed(), false);
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public void cleanUp() {
|
||||
File file = new File(getPasswordFilePath());
|
||||
if (file.exists()) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TestApp {
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
try {
|
||||
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:"
|
||||
+ System.getProperty("com.sun.management.jmxremote.port") + "/jmxrmi");
|
||||
Map<String, Object> env = new HashMap<>(1);
|
||||
// any dummy credentials will do. We just have to trigger password hashing
|
||||
env.put("jmx.remote.credentials", new String[]{"a", "a"});
|
||||
try (JMXConnector cc = JMXConnectorFactory.connect(url, env)) {
|
||||
cc.getMBeanServerConnection();
|
||||
}
|
||||
} catch (SecurityException ex) {
|
||||
// Catch authentication failure here
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user