You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@activemq.apache.org by cl...@apache.org on 2017/09/05 20:35:21 UTC
[1/3] activemq-artemis git commit: This closes #1508
Repository: activemq-artemis
Updated Branches:
refs/heads/master cc35b2361 -> ea9b12bbc
This closes #1508
Project: http://git-wip-us.apache.org/repos/asf/activemq-artemis/repo
Commit: http://git-wip-us.apache.org/repos/asf/activemq-artemis/commit/ea9b12bb
Tree: http://git-wip-us.apache.org/repos/asf/activemq-artemis/tree/ea9b12bb
Diff: http://git-wip-us.apache.org/repos/asf/activemq-artemis/diff/ea9b12bb
Branch: refs/heads/master
Commit: ea9b12bbc8f20863873fb501383c12446521462b
Parents: cc35b23 5db68a4
Author: Clebert Suconic <cl...@apache.org>
Authored: Tue Sep 5 16:35:14 2017 -0400
Committer: Clebert Suconic <cl...@apache.org>
Committed: Tue Sep 5 16:35:14 2017 -0400
----------------------------------------------------------------------
.../spi/core/security/jaas/LDAPLoginModule.java | 205 +++++++---
.../integration/amqp/JMSSaslGssapiTest.java | 14 +-
.../amqp/SaslKrb5LDAPSecurityTest.java | 401 +++++++++++++++++++
.../resources/SaslKrb5LDAPSecurityTest.ldif | 61 +++
.../src/test/resources/login.config | 32 ++
5 files changed, 652 insertions(+), 61 deletions(-)
----------------------------------------------------------------------
[3/3] activemq-artemis git commit: ARTEMIS-1373 - allow LDAP login
module apply role mapping to existing user principals in the subject
Posted by cl...@apache.org.
ARTEMIS-1373 - allow LDAP login module apply role mapping to existing user principals in the subject
Project: http://git-wip-us.apache.org/repos/asf/activemq-artemis/repo
Commit: http://git-wip-us.apache.org/repos/asf/activemq-artemis/commit/ab7dc69b
Tree: http://git-wip-us.apache.org/repos/asf/activemq-artemis/tree/ab7dc69b
Diff: http://git-wip-us.apache.org/repos/asf/activemq-artemis/diff/ab7dc69b
Branch: refs/heads/master
Commit: ab7dc69b5dc9f4b144320fa0fad3823d556fa562
Parents: cc35b23
Author: gtully <ga...@gmail.com>
Authored: Fri Sep 1 15:40:33 2017 +0100
Committer: Clebert Suconic <cl...@apache.org>
Committed: Tue Sep 5 16:35:14 2017 -0400
----------------------------------------------------------------------
.../spi/core/security/jaas/LDAPLoginModule.java | 105 ++++--
.../integration/amqp/JMSSaslGssapiTest.java | 14 +-
.../amqp/SaslKrb5LDAPSecurityTest.java | 354 +++++++++++++++++++
.../resources/SaslKrb5LDAPSecurityTest.ldif | 74 ++++
.../src/test/resources/login.config | 23 ++
5 files changed, 528 insertions(+), 42 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/ab7dc69b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
----------------------------------------------------------------------
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
index 48fc3b9..3ce0e17 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
@@ -83,6 +83,7 @@ public class LDAPLoginModule implements LoginModule {
private LDAPLoginProperty[] config;
private String username;
private final Set<RolePrincipal> groups = new HashSet<>();
+ private boolean userAuthenticated = false;
@Override
public void initialize(Subject subject,
@@ -122,6 +123,7 @@ public class LDAPLoginModule implements LoginModule {
// authenticate will throw LoginException
// in case of failed authentication
authenticate(username, password);
+ userAuthenticated = true;
return true;
}
@@ -134,7 +136,24 @@ public class LDAPLoginModule implements LoginModule {
@Override
public boolean commit() throws LoginException {
Set<Principal> principals = subject.getPrincipals();
- principals.add(new UserPrincipal(username));
+ if (userAuthenticated) {
+ principals.add(new UserPrincipal(username));
+ } else {
+ // assign roles to any other UserPrincipal
+ Set<UserPrincipal> authenticatedUsers = subject.getPrincipals(UserPrincipal.class);
+ for (UserPrincipal authenticatedUser : authenticatedUsers) {
+ List<String> roles = new ArrayList<>();
+ try {
+ String dn = resolveDN(username, roles);
+ resolveRolesForDN(context, dn, username, 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 +179,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;
@@ -175,7 +233,7 @@ public class LDAPLoginModule implements LoginModule {
}
if (!isLoginPropertySet(USER_SEARCH_MATCHING))
- return false;
+ return dn;
userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();
@@ -218,7 +276,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 +314,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 +329,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,11 +343,8 @@ 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)});
@@ -335,7 +373,7 @@ 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));
@@ -348,14 +386,13 @@ public class LDAPLoginModule implements LoginModule {
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,26 +458,22 @@ 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 {
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/ab7dc69b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSSaslGssapiTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSSaslGssapiTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSSaslGssapiTest.java
index 17d70a5..2a47e1f 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSSaslGssapiTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/JMSSaslGssapiTest.java
@@ -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
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/ab7dc69b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
new file mode 100644
index 0000000..4908eb0
--- /dev/null
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
@@ -0,0 +1,354 @@
+/*
+ * 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 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.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.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.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.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)})
+@CreateKdcServer(searchBaseDn = "dc=example,dc=com", 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");
+
+ 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 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();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/ab7dc69b/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif b/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
new file mode 100644
index 0000000..ace1a6c
--- /dev/null
+++ b/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
@@ -0,0 +1,74 @@
+## ---------------------------------------------------------------------------
+## 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,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
+
+dn: uid=ldap,ou=users,dc=example,dc=com
+objectClass: top
+objectClass: person
+objectClass: inetOrgPerson
+objectClass: krb5principal
+objectClass: krb5kdcentry
+cn: LDAP
+sn: Service
+uid: ldap
+userPassword: secret
+krb5PrincipalName: ldap/localhost@EXAMPLE.COM
+krb5KeyVersionNumber: 0
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/ab7dc69b/tests/integration-tests/src/test/resources/login.config
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/resources/login.config b/tests/integration-tests/src/test/resources/login.config
index a834627..8793d34 100644
--- a/tests/integration-tests/src/test/resources/login.config
+++ b/tests/integration-tests/src/test/resources/login.config
@@ -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"
+ connectionUsername="uid=admin,ou=system"
+ connectionPassword=secret
+ connectionProtocol=s
+ authentication=simple
+ userBase="dc=example,dc=com"
+ userSearchMatching="(krb5PrincipalName={0})"
+ userSearchSubtree=true
+ roleBase="ou=system"
+ roleName=cn
+ roleSearchMatching="(member={0})"
+ roleSearchSubtree=false
+ ;
+};
+
core-tls-krb5-server {
com.sun.security.auth.module.Krb5LoginModule required
isInitiator=false
[2/3] activemq-artemis git commit: ARTEMIS-1372 - alow auth to ldap
via kerberos
Posted by cl...@apache.org.
ARTEMIS-1372 - alow auth to ldap via kerberos
Project: http://git-wip-us.apache.org/repos/asf/activemq-artemis/repo
Commit: http://git-wip-us.apache.org/repos/asf/activemq-artemis/commit/5db68a45
Tree: http://git-wip-us.apache.org/repos/asf/activemq-artemis/tree/5db68a45
Diff: http://git-wip-us.apache.org/repos/asf/activemq-artemis/diff/5db68a45
Branch: refs/heads/master
Commit: 5db68a451b6e61524b1cc1b9e6764f0ff416f245
Parents: ab7dc69
Author: gtully <ga...@gmail.com>
Authored: Mon Sep 4 14:33:30 2017 +0100
Committer: Clebert Suconic <cl...@apache.org>
Committed: Tue Sep 5 16:35:14 2017 -0400
----------------------------------------------------------------------
.../spi/core/security/jaas/LDAPLoginModule.java | 128 ++++++++++++++-----
.../amqp/SaslKrb5LDAPSecurityTest.java | 57 ++++++++-
.../resources/SaslKrb5LDAPSecurityTest.ldif | 15 +--
.../src/test/resources/login.config | 17 ++-
4 files changed, 161 insertions(+), 56 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/5db68a45/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
----------------------------------------------------------------------
diff --git a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
index 3ce0e17..65dc5ad 100644
--- a/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
+++ b/artemis-server/src/main/java/org/apache/activemq/artemis/spi/core/security/jaas/LDAPLoginModule.java
@@ -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;
@@ -84,6 +89,8 @@ public class LDAPLoginModule implements LoginModule {
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,
@@ -93,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_S
EARCH_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_S
EARCH_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");
@@ -135,25 +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();
if (userAuthenticated) {
principals.add(new UserPrincipal(username));
- } else {
- // assign roles to any other UserPrincipal
- Set<UserPrincipal> authenticatedUsers = subject.getPrincipals(UserPrincipal.class);
- for (UserPrincipal authenticatedUser : authenticatedUsers) {
- List<String> roles = new ArrayList<>();
- try {
- String dn = resolveDN(username, roles);
- resolveRolesForDN(context, dn, username, roles);
- } catch (NamingException e) {
- closeContext();
- FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
- ex.initCause(e);
- throw ex;
- }
+ }
+
+ // 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);
}
@@ -226,7 +241,7 @@ 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;
@@ -264,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.");
@@ -346,7 +369,7 @@ public class LDAPLoginModule implements LoginModule {
if (!isLoginPropertySet(ROLE_NAME)) {
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) {
@@ -362,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();
@@ -379,8 +411,15 @@ public class LDAPLoginModule implements LoginModule {
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();
@@ -476,26 +515,49 @@ public class LDAPLoginModule implements LoginModule {
}
}
- 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));
+ env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
+ env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
+ env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
+
+ 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 {
- throw new NamingException("Empty username is not allowed");
+
+ 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");
+ }
}
- 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();
}
- 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);
} catch (NamingException e) {
closeContext();
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/5db68a45/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
index 4908eb0..4ede6c6 100644
--- a/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
+++ b/tests/integration-tests/src/test/java/org/apache/activemq/artemis/tests/integration/amqp/SaslKrb5LDAPSecurityTest.java
@@ -26,6 +26,8 @@ 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;
@@ -36,6 +38,8 @@ 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;
@@ -58,6 +62,7 @@ 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;
@@ -70,6 +75,7 @@ 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;
@@ -82,6 +88,7 @@ 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;
@@ -98,15 +105,18 @@ import org.slf4j.LoggerFactory;
import static org.apache.activemq.artemis.tests.util.ActiveMQTestBase.NETTY_ACCEPTOR_FACTORY;
-@RunWith(FrameworkRunner.class)
-@CreateDS(name = "Example",
+@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)})
-@CreateKdcServer(searchBaseDn = "dc=example,dc=com", transports = {@CreateTransport(protocol = "TCP", port = 0)})
+@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 {
@@ -165,7 +175,7 @@ public class SaslKrb5LDAPSecurityTest extends AbstractLdapTestUnit {
// hard coded match, default_keytab_name in minikdc-krb5.conf template
File userKeyTab = new File("target/test.krb5.keytab");
- createPrincipal(userKeyTab, "client", "amqp/localhost");
+ createPrincipal(userKeyTab, "client", "amqp/localhost", "ldap/localhost");
if (debug) {
dumpLdapContents();
@@ -310,6 +320,43 @@ public class SaslKrb5LDAPSecurityTest extends AbstractLdapTestUnit {
}
@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<>();
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/5db68a45/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif b/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
index ace1a6c..195c167 100644
--- a/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
+++ b/tests/integration-tests/src/test/resources/SaslKrb5LDAPSecurityTest.ldif
@@ -29,7 +29,7 @@ objectClass: top
dn: cn=admins,ou=system
cn: admins
member: uid=first,ou=system
-member: uid=client,dc=example,dc=com
+member: uid=client,ou=users,dc=example,dc=com
objectClass: groupOfNames
objectClass: top
@@ -59,16 +59,3 @@ uid: krbtgt
userPassword: secret
krb5PrincipalName: krbtgt/EXAMPLE.COM@EXAMPLE.COM
krb5KeyVersionNumber: 0
-
-dn: uid=ldap,ou=users,dc=example,dc=com
-objectClass: top
-objectClass: person
-objectClass: inetOrgPerson
-objectClass: krb5principal
-objectClass: krb5kdcentry
-cn: LDAP
-sn: Service
-uid: ldap
-userPassword: secret
-krb5PrincipalName: ldap/localhost@EXAMPLE.COM
-krb5KeyVersionNumber: 0
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/activemq-artemis/blob/5db68a45/tests/integration-tests/src/test/resources/login.config
----------------------------------------------------------------------
diff --git a/tests/integration-tests/src/test/resources/login.config b/tests/integration-tests/src/test/resources/login.config
index 8793d34..f8e48ba 100644
--- a/tests/integration-tests/src/test/resources/login.config
+++ b/tests/integration-tests/src/test/resources/login.config
@@ -158,13 +158,13 @@ Krb5PlusLdap {
debug=true
initialContextFactory=com.sun.jndi.ldap.LdapCtxFactory
connectionURL="ldap://localhost:1024"
- connectionUsername="uid=admin,ou=system"
- connectionPassword=secret
+ authentication=GSSAPI
+ loginConfigScope=broker-sasl-gssapi
connectionProtocol=s
- authentication=simple
- userBase="dc=example,dc=com"
+ userBase="ou=users,dc=example,dc=com"
userSearchMatching="(krb5PrincipalName={0})"
userSearchSubtree=true
+ authenticateUser=false
roleBase="ou=system"
roleName=cn
roleSearchMatching="(member={0})"
@@ -196,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;