This commit is contained in:
Clebert Suconic 2017-09-05 16:35:14 -04:00
commit ea9b12bbc8
5 changed files with 653 additions and 62 deletions

View File

@ -36,12 +36,15 @@ import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
@ -75,6 +78,8 @@ public class LDAPLoginModule implements LoginModule {
private static final String USER_ROLE_NAME = "userRoleName";
private static final String EXPAND_ROLES = "expandRoles";
private static final String EXPAND_ROLES_MATCHING = "expandRolesMatching";
private static final String LOGIN_CONFIG_SCOPE = "loginConfigScope";
private static final String AUTHENTICATE_USER = "authenticateUser";
protected DirContext context;
@ -83,6 +88,9 @@ public class LDAPLoginModule implements LoginModule {
private LDAPLoginProperty[] config;
private String username;
private final Set<RolePrincipal> groups = new HashSet<>();
private boolean userAuthenticated = false;
private boolean authenticateUser = true;
private Subject brokerGssapiIdentity = null;
@Override
public void initialize(Subject subject,
@ -92,12 +100,19 @@ public class LDAPLoginModule implements LoginModule {
this.subject = subject;
this.handler = callbackHandler;
config = new LDAPLoginProperty[]{new LDAPLoginProperty(INITIAL_CONTEXT_FACTORY, (String) options.get(INITIAL_CONTEXT_FACTORY)), new LDAPLoginProperty(CONNECTION_URL, (String) options.get(CONNECTION_URL)), new LDAPLoginProperty(CONNECTION_USERNAME, (String) options.get(CONNECTION_USERNAME)), new LDAPLoginProperty(CONNECTION_PASSWORD, (String) options.get(CONNECTION_PASSWORD)), new LDAPLoginProperty(CONNECTION_PROTOCOL, (String) options.get(CONNECTION_PROTOCOL)), new LDAPLoginProperty(AUTHENTICATION, (String) options.get(AUTHENTICATION)), new LDAPLoginProperty(USER_BASE, (String) options.get(USER_BASE)), new LDAPLoginProperty(USER_SEARCH_MATCHING, (String) options.get(USER_SEARCH_MATCHING)), new LDAPLoginProperty(USER_SEARCH_SUBTREE, (String) options.get(USER_SEARCH_SUBTREE)), new LDAPLoginProperty(ROLE_BASE, (String) options.get(ROLE_BASE)), new LDAPLoginProperty(ROLE_NAME, (String) options.get(ROLE_NAME)), new LDAPLoginProperty(ROLE_SEARCH_MATCHING, (String) options.get(ROLE_SEARCH_MATCHING)), new LDAPLoginProperty(ROLE_SEARCH_SUBTREE, (String) options.get(ROLE_SEARCH_SUBTREE)), new LDAPLoginProperty(USER_ROLE_NAME, (String) options.get(USER_ROLE_NAME)), new LDAPLoginProperty(EXPAND_ROLES, (String) options.get(EXPAND_ROLES)), new LDAPLoginProperty(EXPAND_ROLES_MATCHING, (String) options.get(EXPAND_ROLES_MATCHING))};
config = new LDAPLoginProperty[]{new LDAPLoginProperty(INITIAL_CONTEXT_FACTORY, (String) options.get(INITIAL_CONTEXT_FACTORY)), new LDAPLoginProperty(CONNECTION_URL, (String) options.get(CONNECTION_URL)), new LDAPLoginProperty(CONNECTION_USERNAME, (String) options.get(CONNECTION_USERNAME)), new LDAPLoginProperty(CONNECTION_PASSWORD, (String) options.get(CONNECTION_PASSWORD)), new LDAPLoginProperty(CONNECTION_PROTOCOL, (String) options.get(CONNECTION_PROTOCOL)), new LDAPLoginProperty(AUTHENTICATION, (String) options.get(AUTHENTICATION)), new LDAPLoginProperty(USER_BASE, (String) options.get(USER_BASE)), new LDAPLoginProperty(USER_SEARCH_MATCHING, (String) options.get(USER_SEARCH_MATCHING)), new LDAPLoginProperty(USER_SEARCH_SUBTREE, (String) options.get(USER_SEARCH_SUBTREE)), new LDAPLoginProperty(ROLE_BASE, (String) options.get(ROLE_BASE)), new LDAPLoginProperty(ROLE_NAME, (String) options.get(ROLE_NAME)), new LDAPLoginProperty(ROLE_SEARCH_MATCHING, (String) options.get(ROLE_SEARCH_MATCHING)), new LDAPLoginProperty(ROLE_SEARCH_SUBTREE, (String) options.get(ROLE_SEARCH_SUBTREE)), new LDAPLoginProperty(USER_ROLE_NAME, (String) options.get(USER_ROLE_NAME)), new LDAPLoginProperty(EXPAND_ROLES, (String) options.get(EXPAND_ROLES)), new LDAPLoginProperty(EXPAND_ROLES_MATCHING, (String) options.get(EXPAND_ROLES_MATCHING)), new LDAPLoginProperty(LOGIN_CONFIG_SCOPE, (String) options.get(LOGIN_CONFIG_SCOPE)), new LDAPLoginProperty(AUTHENTICATE_USER, (String) options.get(AUTHENTICATE_USER))};
if (isLoginPropertySet(AUTHENTICATE_USER)) {
authenticateUser = Boolean.valueOf(getLDAPPropertyValue(AUTHENTICATE_USER));
}
}
@Override
public boolean login() throws LoginException {
if (!authenticateUser) {
return false;
}
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("User name");
@ -122,6 +137,7 @@ public class LDAPLoginModule implements LoginModule {
// authenticate will throw LoginException
// in case of failed authentication
authenticate(username, password);
userAuthenticated = true;
return true;
}
@ -133,8 +149,26 @@ public class LDAPLoginModule implements LoginModule {
@Override
public boolean commit() throws LoginException {
Set<UserPrincipal> authenticatedUsers = subject.getPrincipals(UserPrincipal.class);
Set<Principal> principals = subject.getPrincipals();
principals.add(new UserPrincipal(username));
if (userAuthenticated) {
principals.add(new UserPrincipal(username));
}
// assign roles to any other UserPrincipal
for (UserPrincipal authenticatedUser : authenticatedUsers) {
List<String> roles = new ArrayList<>();
try {
String dn = resolveDN(authenticatedUser.getName(), roles);
resolveRolesForDN(context, dn, authenticatedUser.getName(), roles);
} catch (NamingException e) {
closeContext();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
}
}
for (RolePrincipal gp : groups) {
principals.add(gp);
}
@ -160,6 +194,45 @@ public class LDAPLoginModule implements LoginModule {
protected boolean authenticate(String username, String password) throws LoginException {
List<String> roles = new ArrayList<>();
try {
String dn = resolveDN(username, roles);
// check the credentials by binding to server
if (bindUser(context, dn, password)) {
// if authenticated add more roles
resolveRolesForDN(context, dn, username, roles);
} else {
throw new FailedLoginException("Password does not match for user: " + username);
}
} catch (CommunicationException e) {
closeContext();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
} catch (NamingException e) {
closeContext();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
ex.initCause(e);
throw ex;
}
return true;
}
private void resolveRolesForDN(DirContext context, String dn, String username, List<String> roles) throws NamingException {
addRoles(context, dn, username, roles);
if (logger.isDebugEnabled()) {
logger.debug("Roles " + roles + " for user " + username);
}
for (String role : roles) {
groups.add(new RolePrincipal(role));
}
}
private String resolveDN(String username, List<String> roles) throws FailedLoginException {
String dn = null;
MessageFormat userSearchMatchingFormat;
boolean userSearchSubtreeBool;
@ -168,14 +241,14 @@ public class LDAPLoginModule implements LoginModule {
}
try {
openContext();
} catch (NamingException ne) {
} catch (Exception ne) {
FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
ex.initCause(ne);
throw ex;
}
if (!isLoginPropertySet(USER_SEARCH_MATCHING))
return false;
return dn;
userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();
@ -206,7 +279,15 @@ public class LDAPLoginModule implements LoginModule {
logger.debug(" filter: " + filter);
}
NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(USER_BASE), filter, constraints);
NamingEnumeration<SearchResult> results = null;
try {
results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction< NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(USER_BASE), filter, constraints));
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
FailedLoginException ex = new FailedLoginException("Error executing search query to resolve DN");
ex.initCause(cause);
throw ex;
}
if (results == null || !results.hasMore()) {
throw new FailedLoginException("User " + username + " not found in LDAP.");
@ -218,7 +299,6 @@ public class LDAPLoginModule implements LoginModule {
// ignore for now
}
String dn;
if (result.isRelative()) {
logger.debug("LDAP returned a relative name: " + result.getName());
@ -257,23 +337,8 @@ public class LDAPLoginModule implements LoginModule {
if (attrs == null) {
throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
}
List<String> roles = null;
if (isLoginPropertySet(USER_ROLE_NAME)) {
roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles);
}
// check the credentials by binding to server
if (bindUser(context, dn, password)) {
// if authenticated add more roles
roles = getRoles(context, dn, username, roles);
if (logger.isDebugEnabled()) {
logger.debug("Roles " + roles + " for user " + username);
}
for (String role : roles) {
groups.add(new RolePrincipal(role));
}
} else {
throw new FailedLoginException("Password does not match for user: " + username);
addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles);
}
} catch (CommunicationException e) {
closeContext();
@ -287,14 +352,13 @@ public class LDAPLoginModule implements LoginModule {
throw ex;
}
return true;
return dn;
}
protected List<String> getRoles(DirContext context,
protected void addRoles(DirContext context,
String dn,
String username,
List<String> currentRoles) throws NamingException {
List<String> list = currentRoles;
MessageFormat roleSearchMatchingFormat;
boolean roleSearchSubtreeBool;
boolean expandRolesBool;
@ -302,13 +366,10 @@ public class LDAPLoginModule implements LoginModule {
roleSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(ROLE_SEARCH_SUBTREE)).booleanValue();
expandRolesBool = Boolean.valueOf(getLDAPPropertyValue(EXPAND_ROLES)).booleanValue();
if (list == null) {
list = new ArrayList<>();
}
if (!isLoginPropertySet(ROLE_NAME)) {
return list;
return;
}
String filter = roleSearchMatchingFormat.format(new String[]{doRFC2254Encoding(dn), doRFC2254Encoding(username)});
final String filter = roleSearchMatchingFormat.format(new String[]{doRFC2254Encoding(dn), doRFC2254Encoding(username)});
SearchControls constraints = new SearchControls();
if (roleSearchSubtreeBool) {
@ -324,7 +385,16 @@ public class LDAPLoginModule implements LoginModule {
}
HashSet<String> haveSeenNames = new HashSet<>();
Queue<String> pendingNameExpansion = new LinkedList<>();
NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints);
NamingEnumeration<SearchResult> results = null;
try {
results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction< NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints));
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
NamingException ex = new NamingException("Error executing search query to resolve roles");
ex.initCause(cause);
throw ex;
}
while (results.hasMore()) {
SearchResult result = results.next();
Attributes attrs = result.getAttributes();
@ -335,27 +405,33 @@ public class LDAPLoginModule implements LoginModule {
if (attrs == null) {
continue;
}
list = addAttributeValues(getLDAPPropertyValue(ROLE_NAME), attrs, list);
addAttributeValues(getLDAPPropertyValue(ROLE_NAME), attrs, currentRoles);
}
if (expandRolesBool) {
MessageFormat expandRolesMatchingFormat = new MessageFormat(getLDAPPropertyValue(EXPAND_ROLES_MATCHING));
while (!pendingNameExpansion.isEmpty()) {
String name = pendingNameExpansion.remove();
filter = expandRolesMatchingFormat.format(new String[]{name});
results = context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints);
final String expandFilter = expandRolesMatchingFormat.format(new String[]{name});
try {
results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction< NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(ROLE_BASE), expandFilter, constraints));
} catch (PrivilegedActionException e) {
Exception cause = e.getException();
NamingException ex = new NamingException("Error executing search query to expand roles");
ex.initCause(cause);
throw ex;
}
while (results.hasMore()) {
SearchResult result = results.next();
name = result.getNameInNamespace();
if (!haveSeenNames.contains(name)) {
Attributes attrs = result.getAttributes();
list = addAttributeValues(getLDAPPropertyValue(ROLE_NAME), attrs, list);
addAttributeValues(getLDAPPropertyValue(ROLE_NAME), attrs, currentRoles);
haveSeenNames.add(name);
pendingNameExpansion.add(name);
}
}
}
}
return list;
}
protected String doRFC2254Encoding(String inputString) {
@ -421,48 +497,67 @@ public class LDAPLoginModule implements LoginModule {
return isValid;
}
private List<String> addAttributeValues(String attrId,
private void addAttributeValues(String attrId,
Attributes attrs,
List<String> values) throws NamingException {
if (attrId == null || attrs == null) {
return values;
}
if (values == null) {
values = new ArrayList<>();
return;
}
Attribute attr = attrs.get(attrId);
if (attr == null) {
return values;
return;
}
NamingEnumeration<?> e = attr.getAll();
while (e.hasMore()) {
String value = (String) e.next();
values.add(value);
}
return values;
}
protected void openContext() throws NamingException {
protected void openContext() throws Exception {
if (context == null) {
try {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(INITIAL_CONTEXT_FACTORY));
if (isLoginPropertySet(CONNECTION_USERNAME)) {
env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
} else {
throw new NamingException("Empty username is not allowed");
}
if (isLoginPropertySet(CONNECTION_PASSWORD)) {
env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
} else {
throw new NamingException("Empty password is not allowed");
}
env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
context = new InitialDirContext(env);
if ("GSSAPI".equalsIgnoreCase(getLDAPPropertyValue(AUTHENTICATION))) {
final String configScope = isLoginPropertySet(LOGIN_CONFIG_SCOPE) ? getLDAPPropertyValue(LOGIN_CONFIG_SCOPE) : "broker-sasl-gssapi";
try {
LoginContext loginContext = new LoginContext(configScope);
loginContext.login();
brokerGssapiIdentity = loginContext.getSubject();
} catch (LoginException e) {
e.printStackTrace();
FailedLoginException ex = new FailedLoginException("Error contacting LDAP using GSSAPI in JAAS loginConfigScope: " + configScope);
ex.initCause(e);
throw ex;
}
} else {
if (isLoginPropertySet(CONNECTION_USERNAME)) {
env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
} else {
throw new NamingException("Empty username is not allowed");
}
if (isLoginPropertySet(CONNECTION_PASSWORD)) {
env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
} else {
throw new NamingException("Empty password is not allowed");
}
}
try {
context = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction<DirContext>) () -> new InitialDirContext(env));
} catch (PrivilegedActionException e) {
throw e.getException();
}
} catch (NamingException e) {
closeContext();

View File

@ -50,6 +50,7 @@ public class JMSSaslGssapiTest extends JMSClientTestSupport {
}
}
MiniKdc kdc = null;
private final boolean debug = false;
@Before
public void setUpKerberos() throws Exception {
@ -60,13 +61,14 @@ public class JMSSaslGssapiTest extends JMSClientTestSupport {
File userKeyTab = new File("target/test.krb5.keytab");
kdc.createPrincipal(userKeyTab, "client", "amqp/localhost");
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("javax.security.sasl");
logger.setLevel(java.util.logging.Level.FINEST);
logger.addHandler(new java.util.logging.ConsoleHandler());
for (java.util.logging.Handler handler: logger.getHandlers()) {
handler.setLevel(java.util.logging.Level.FINEST);
if (debug) {
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("javax.security.sasl");
logger.setLevel(java.util.logging.Level.FINEST);
logger.addHandler(new java.util.logging.ConsoleHandler());
for (java.util.logging.Handler handler : logger.getHandlers()) {
handler.setLevel(java.util.logging.Level.FINEST);
}
}
}
@After

View File

@ -0,0 +1,401 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.amqp;
import javax.jms.Connection;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants;
import org.apache.activemq.artemis.core.security.Role;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.spi.core.security.ActiveMQJAASSecurityManager;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.RandomUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.filter.PresenceNode;
import org.apache.directory.api.ldap.model.ldif.LdifEntry;
import org.apache.directory.api.ldap.model.ldif.LdifReader;
import org.apache.directory.api.ldap.model.ldif.LdifUtils;
import org.apache.directory.api.ldap.model.message.AliasDerefMode;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.server.annotations.CreateKdcServer;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.annotations.SaslMechanism;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.annotations.ContextEntry;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreateIndex;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.api.filtering.EntryFilteringCursor;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
import org.apache.directory.server.kerberos.shared.crypto.encryption.KerberosKeyFactory;
import org.apache.directory.server.kerberos.shared.keytab.Keytab;
import org.apache.directory.server.kerberos.shared.keytab.KeytabEntry;
import org.apache.directory.server.ldap.handlers.sasl.gssapi.GssapiMechanismHandler;
import org.apache.directory.shared.kerberos.KerberosTime;
import org.apache.directory.shared.kerberos.codec.types.EncryptionType;
import org.apache.directory.shared.kerberos.components.EncryptionKey;
import org.apache.qpid.jms.JmsConnectionFactory;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.activemq.artemis.tests.util.ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY;
@RunWith(FrameworkRunner.class) @CreateDS(name = "Example",
partitions = {@CreatePartition(name = "example", suffix = "dc=example,dc=com",
contextEntry = @ContextEntry(entryLdif = "dn: dc=example,dc=com\n" + "dc: example\n" + "objectClass: top\n" + "objectClass: domain\n\n"),
indexes = {@CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou")})},
additionalInterceptors = { KeyDerivationInterceptor.class })
@CreateLdapServer(transports = {@CreateTransport(protocol = "LDAP", port = 1024)},
saslHost = "localhost",
saslPrincipal = "ldap/localhost@EXAMPLE.COM",
saslMechanisms = {@SaslMechanism(name = SupportedSaslMechanisms.GSSAPI, implClass = GssapiMechanismHandler.class)})
@CreateKdcServer(transports = {@CreateTransport(protocol = "TCP", port = 0)})
@ApplyLdifFiles("SaslKrb5LDAPSecurityTest.ldif")
public class SaslKrb5LDAPSecurityTest extends AbstractLdapTestUnit {
protected static final Logger LOG = LoggerFactory.getLogger(SaslKrb5LDAPSecurityTest.class);
public static final String QUEUE_NAME = "some_queue";
static {
String path = System.getProperty("java.security.auth.login.config");
if (path == null) {
URL resource = SaslKrb5LDAPSecurityTest.class.getClassLoader().getResource("login.config");
if (resource != null) {
path = resource.getFile();
System.setProperty("java.security.auth.login.config", path);
}
}
}
ActiveMQServer server;
public static final String TARGET_TMP = "./target/tmp";
private static final String PRINCIPAL = "uid=admin,ou=system";
private static final String CREDENTIALS = "secret";
private final boolean debug = false;
public SaslKrb5LDAPSecurityTest() {
File parent = new File(TARGET_TMP);
parent.mkdirs();
temporaryFolder = new TemporaryFolder(parent);
}
@Rule
public TemporaryFolder temporaryFolder;
private String testDir;
@Before
public void setUp() throws Exception {
if (debug) {
initLogging();
}
testDir = temporaryFolder.getRoot().getAbsolutePath();
ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager("Krb5PlusLdap");
HashMap<String, Object> params = new HashMap<>();
params.put(TransportConstants.PORT_PROP_NAME, String.valueOf(5672));
params.put(TransportConstants.PROTOCOLS_PROP_NAME, "AMQP");
HashMap<String, Object> amqpParams = new HashMap<>();
amqpParams.put("saslMechanisms", "GSSAPI");
amqpParams.put("saslLoginConfigScope", "amqp-sasl-gssapi");
Configuration configuration = new ConfigurationImpl().setSecurityEnabled(true).addAcceptorConfiguration(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY, params, "netty-amqp", amqpParams)).setJournalDirectory(ActiveMQTestBase.getJournalDir(testDir, 0, false)).setBindingsDirectory(ActiveMQTestBase.getBindingsDir(testDir, 0, false)).setPagingDirectory(ActiveMQTestBase.getPageDir(testDir, 0, false)).setLargeMessagesDirectory(ActiveMQTestBase.getLargeMessagesDir(testDir, 0, false));
server = ActiveMQServers.newActiveMQServer(configuration, ManagementFactory.getPlatformMBeanServer(), securityManager, false);
// hard coded match, default_keytab_name in minikdc-krb5.conf template
File userKeyTab = new File("target/test.krb5.keytab");
createPrincipal(userKeyTab, "client", "amqp/localhost", "ldap/localhost");
if (debug) {
dumpLdapContents();
}
rewriteKerb5Conf();
}
private void rewriteKerb5Conf() throws Exception {
StringBuilder sb = new StringBuilder();
InputStream is2 = this.getClass().getClassLoader().getResourceAsStream("minikdc-krb5.conf");
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(is2, StandardCharsets.UTF_8));
String line = r.readLine();
while (line != null) {
sb.append(line).append("{3}");
line = r.readLine();
}
} finally {
IOUtils.closeQuietly(r);
IOUtils.closeQuietly(is2);
}
InetSocketAddress addr =
(InetSocketAddress)kdcServer.getTransports()[0].getAcceptor().getLocalAddress();
int port = addr.getPort();
File krb5conf = new File(testDir, "krb5.conf").getAbsoluteFile();
FileUtils.writeStringToFile(krb5conf, MessageFormat.format(sb.toString(), getRealm(), "localhost", Integer.toString(port), System.getProperty("line.separator")));
System.setProperty("java.security.krb5.conf", krb5conf.getAbsolutePath());
System.setProperty("sun.security.krb5.debug", "true");
// refresh the config
Class<?> classRef;
if (System.getProperty("java.vendor").contains("IBM")) {
classRef = Class.forName("com.ibm.security.krb5.internal.Config");
} else {
classRef = Class.forName("sun.security.krb5.Config");
}
Method refreshMethod = classRef.getMethod("refresh", new Class[0]);
refreshMethod.invoke(classRef, new Object[0]);
LOG.info("krb5.conf to: {}", krb5conf.getAbsolutePath());
}
private void dumpLdapContents() throws Exception {
EntryFilteringCursor cursor = getService().getAdminSession().search(new Dn("ou=system"), SearchScope.SUBTREE, new PresenceNode("ObjectClass"), AliasDerefMode.DEREF_ALWAYS);
String st = "";
while (cursor.next()) {
Entry entry = cursor.get();
String ss = LdifUtils.convertToLdif(entry);
st += ss + "\n";
}
System.out.println(st);
cursor = getService().getAdminSession().search(new Dn("dc=example,dc=com"), SearchScope.SUBTREE, new PresenceNode("ObjectClass"), AliasDerefMode.DEREF_ALWAYS);
st = "";
while (cursor.next()) {
Entry entry = cursor.get();
String ss = LdifUtils.convertToLdif(entry);
st += ss + "\n";
}
System.out.println(st);
}
private void initLogging() {
java.util.logging.Logger logger = java.util.logging.Logger.getLogger("javax.security.sasl");
logger.setLevel(java.util.logging.Level.FINEST);
logger.addHandler(new java.util.logging.ConsoleHandler());
for (java.util.logging.Handler handler: logger.getHandlers()) {
handler.setLevel(java.util.logging.Level.FINEST);
}
}
public synchronized void createPrincipal(String principal, String password) throws Exception {
String baseDn = getKdcServer().getSearchBaseDn();
String content = "dn: uid=" + principal + "," + baseDn + "\n" + "objectClass: top\n" + "objectClass: person\n" + "objectClass: inetOrgPerson\n" + "objectClass: krb5principal\n" + "objectClass: krb5kdcentry\n" + "cn: " + principal + "\n" + "sn: " + principal + "\n" + "uid: " + principal + "\n" + "userPassword: " + password + "\n" + "krb5PrincipalName: " + principal + "@" + getRealm() + "\n" + "krb5KeyVersionNumber: 0";
for (LdifEntry ldifEntry : new LdifReader(new StringReader(content))) {
service.getAdminSession().add(new DefaultEntry(service.getSchemaManager(), ldifEntry.getEntry()));
}
}
public void createPrincipal(File keytabFile, String... principals) throws Exception {
String generatedPassword = UUID.randomUUID().toString();
Keytab keytab = new Keytab();
List<KeytabEntry> entries = new ArrayList<>();
for (String principal : principals) {
createPrincipal(principal, generatedPassword);
principal = principal + "@" + getRealm();
KerberosTime timestamp = new KerberosTime();
for (Map.Entry<EncryptionType, EncryptionKey> entry : KerberosKeyFactory.getKerberosKeys(principal, generatedPassword).entrySet()) {
EncryptionKey ekey = entry.getValue();
byte keyVersion = (byte) ekey.getKeyVersion();
entries.add(new KeytabEntry(principal, 1L, timestamp, keyVersion, ekey));
}
}
keytab.setEntries(entries);
keytab.write(keytabFile);
}
private String getRealm() {
return getKdcServer().getConfig().getPrimaryRealm();
}
@After
public void tearDown() throws Exception {
server.stop();
}
@Test
public void testRunning() throws Exception {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, PRINCIPAL);
env.put(Context.SECURITY_CREDENTIALS, CREDENTIALS);
DirContext ctx = new InitialDirContext(env);
HashSet<String> set = new HashSet<>();
NamingEnumeration<NameClassPair> list = ctx.list("ou=system");
while (list.hasMore()) {
NameClassPair ncp = list.next();
set.add(ncp.getName());
}
Assert.assertTrue(set.contains("uid=admin"));
Assert.assertTrue(set.contains("ou=users"));
Assert.assertTrue(set.contains("ou=groups"));
Assert.assertTrue(set.contains("ou=configuration"));
Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));
ctx.close();
}
@Test
public void testSaslGssapiLdapAuth() throws Exception {
final Hashtable<String, String> env = new Hashtable<>();
env.put(Context.PROVIDER_URL, "ldap://localhost:1024");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
LoginContext loginContext = new LoginContext("broker-sasl-gssapi");
loginContext.login();
try {
Subject.doAs(loginContext.getSubject(), (PrivilegedExceptionAction<Object>) () -> {
HashSet<String> set = new HashSet<>();
DirContext ctx = new InitialDirContext(env);
NamingEnumeration<NameClassPair> list = ctx.list("ou=system");
while (list.hasMore()) {
NameClassPair ncp = list.next();
set.add(ncp.getName());
}
Assert.assertTrue(set.contains("uid=first"));
Assert.assertTrue(set.contains("cn=users"));
Assert.assertTrue(set.contains("ou=configuration"));
Assert.assertTrue(set.contains("prefNodeName=sysPrefRoot"));
ctx.close();
return null;
});
} catch (PrivilegedActionException e) {
throw e.getException();
}
}
@Test
public void testJAASSecurityManagerAuthorizationPositive() throws Exception {
Set<Role> roles = new HashSet<>();
roles.add(new Role("admins", true, true, true, true, true, true, true, true, true, true));
server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
server.start();
JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory("amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
Connection connection = jmsConnectionFactory.createConnection("client", null);
try {
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Queue queue = session.createQueue(QUEUE_NAME);
// PRODUCE
final String text = RandomUtil.randomString();
try {
MessageProducer producer = session.createProducer(queue);
producer.send(session.createTextMessage(text));
} catch (Exception e) {
e.printStackTrace();
Assert.fail("should not throw exception here");
}
// CONSUME
try {
MessageConsumer consumer = session.createConsumer(queue);
TextMessage m = (TextMessage) consumer.receive(1000);
Assert.assertNotNull(m);
Assert.assertEquals(text, m.getText());
} catch (Exception e) {
Assert.fail("should not throw exception here");
}
} finally {
connection.close();
}
}
}

View File

@ -0,0 +1,61 @@
## ---------------------------------------------------------------------------
## Licensed to the Apache Software Foundation (ASF) under one or more
## contributor license agreements. See the NOTICE file distributed with
## this work for additional information regarding copyright ownership.
## The ASF licenses this file to You under the Apache License, Version 2.0
## (the "License"); you may not use this file except in compliance with
## the License. You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
## ---------------------------------------------------------------------------
dn: uid=first,ou=system
uid: first
userPassword: secret
objectClass: account
objectClass: simpleSecurityObject
objectClass: top
###################
## Define groups ##
###################
dn: cn=admins,ou=system
cn: admins
member: uid=first,ou=system
member: uid=client,ou=users,dc=example,dc=com
objectClass: groupOfNames
objectClass: top
dn: cn=users,ou=system
cn: users
member: cn=admins,ou=system
objectClass: groupOfNames
objectClass: top
#########
### kdc
#########
dn: ou=users,dc=example,dc=com
objectClass: organizationalUnit
objectClass: top
ou: users
dn: uid=krbtgt,ou=users,dc=example,dc=com
objectClass: top
objectClass: person
objectClass: inetOrgPerson
objectClass: krb5principal
objectClass: krb5kdcentry
cn: KDC Service
sn: Service
uid: krbtgt
userPassword: secret
krb5PrincipalName: krbtgt/EXAMPLE.COM@EXAMPLE.COM
krb5KeyVersionNumber: 0

View File

@ -149,6 +149,29 @@ Krb5Plus {
org.apache.activemq.jaas.properties.role="dual-authentication-roles.properties";
};
Krb5PlusLdap {
org.apache.activemq.artemis.spi.core.security.jaas.Krb5LoginModule optional
debug=true;
org.apache.activemq.artemis.spi.core.security.jaas.LDAPLoginModule optional
debug=true
initialContextFactory=com.sun.jndi.ldap.LdapCtxFactory
connectionURL="ldap://localhost:1024"
authentication=GSSAPI
loginConfigScope=broker-sasl-gssapi
connectionProtocol=s
userBase="ou=users,dc=example,dc=com"
userSearchMatching="(krb5PrincipalName={0})"
userSearchSubtree=true
authenticateUser=false
roleBase="ou=system"
roleName=cn
roleSearchMatching="(member={0})"
roleSearchSubtree=false
;
};
core-tls-krb5-server {
com.sun.security.auth.module.Krb5LoginModule required
isInitiator=false
@ -173,6 +196,15 @@ amqp-sasl-gssapi {
debug=true;
};
broker-sasl-gssapi {
com.sun.security.auth.module.Krb5LoginModule required
isInitiator=true
storeKey=true
useKeyTab=true
principal="amqp/localhost"
debug=true;
};
amqp-jms-client {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=true;