001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.jaas;
018    
019    import java.io.IOException;
020    import java.security.Principal;
021    import java.text.MessageFormat;
022    import java.util.*;
023    
024    import javax.naming.*;
025    import javax.naming.directory.Attribute;
026    import javax.naming.directory.Attributes;
027    import javax.naming.directory.DirContext;
028    import javax.naming.directory.InitialDirContext;
029    import javax.naming.directory.SearchControls;
030    import javax.naming.directory.SearchResult;
031    import javax.security.auth.Subject;
032    import javax.security.auth.callback.Callback;
033    import javax.security.auth.callback.CallbackHandler;
034    import javax.security.auth.callback.NameCallback;
035    import javax.security.auth.callback.PasswordCallback;
036    import javax.security.auth.callback.UnsupportedCallbackException;
037    import javax.security.auth.login.FailedLoginException;
038    import javax.security.auth.login.LoginException;
039    import javax.security.auth.spi.LoginModule;
040    
041    import org.slf4j.Logger;
042    import org.slf4j.LoggerFactory;
043    
044    /**
045     * @version $Rev: $ $Date: $
046     */
047    public class LDAPLoginModule implements LoginModule {
048    
049        private static final String INITIAL_CONTEXT_FACTORY = "initialContextFactory";
050        private static final String CONNECTION_URL = "connectionURL";
051        private static final String CONNECTION_USERNAME = "connectionUsername";
052        private static final String CONNECTION_PASSWORD = "connectionPassword";
053        private static final String CONNECTION_PROTOCOL = "connectionProtocol";
054        private static final String AUTHENTICATION = "authentication";
055        private static final String USER_BASE = "userBase";
056        private static final String USER_SEARCH_MATCHING = "userSearchMatching";
057        private static final String USER_SEARCH_SUBTREE = "userSearchSubtree";
058        private static final String ROLE_BASE = "roleBase";
059        private static final String ROLE_NAME = "roleName";
060        private static final String ROLE_SEARCH_MATCHING = "roleSearchMatching";
061        private static final String ROLE_SEARCH_SUBTREE = "roleSearchSubtree";
062        private static final String USER_ROLE_NAME = "userRoleName";
063        private static final String EXPAND_ROLES = "expandRoles";
064        private static final String EXPAND_ROLES_MATCHING = "expandRolesMatching";
065    
066        private static Logger log = LoggerFactory.getLogger(LDAPLoginModule.class);
067    
068        protected DirContext context;
069    
070        private Subject subject;
071        private CallbackHandler handler;  
072        private LDAPLoginProperty [] config;
073        private String username;
074        private Set<GroupPrincipal> groups = new HashSet<GroupPrincipal>();
075    
076        @Override
077        public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
078            this.subject = subject;
079            this.handler = callbackHandler;
080            
081            config = new LDAPLoginProperty [] {
082                            new LDAPLoginProperty (INITIAL_CONTEXT_FACTORY, (String)options.get(INITIAL_CONTEXT_FACTORY)),
083                            new LDAPLoginProperty (CONNECTION_URL, (String)options.get(CONNECTION_URL)),
084                            new LDAPLoginProperty (CONNECTION_USERNAME, (String)options.get(CONNECTION_USERNAME)),
085                            new LDAPLoginProperty (CONNECTION_PASSWORD, (String)options.get(CONNECTION_PASSWORD)),
086                            new LDAPLoginProperty (CONNECTION_PROTOCOL, (String)options.get(CONNECTION_PROTOCOL)),
087                            new LDAPLoginProperty (AUTHENTICATION, (String)options.get(AUTHENTICATION)),
088                            new LDAPLoginProperty (USER_BASE, (String)options.get(USER_BASE)),
089                            new LDAPLoginProperty (USER_SEARCH_MATCHING, (String)options.get(USER_SEARCH_MATCHING)),
090                            new LDAPLoginProperty (USER_SEARCH_SUBTREE, (String)options.get(USER_SEARCH_SUBTREE)),
091                            new LDAPLoginProperty (ROLE_BASE, (String)options.get(ROLE_BASE)),
092                            new LDAPLoginProperty (ROLE_NAME, (String)options.get(ROLE_NAME)),
093                            new LDAPLoginProperty (ROLE_SEARCH_MATCHING, (String)options.get(ROLE_SEARCH_MATCHING)),
094                            new LDAPLoginProperty (ROLE_SEARCH_SUBTREE, (String)options.get(ROLE_SEARCH_SUBTREE)),
095                            new LDAPLoginProperty (USER_ROLE_NAME, (String)options.get(USER_ROLE_NAME)),
096                    new LDAPLoginProperty (EXPAND_ROLES, (String) options.get(EXPAND_ROLES)),
097                    new LDAPLoginProperty (EXPAND_ROLES_MATCHING, (String) options.get(EXPAND_ROLES_MATCHING)),
098    
099            };
100        }
101    
102        @Override
103        public boolean login() throws LoginException {
104    
105            Callback[] callbacks = new Callback[2];
106    
107            callbacks[0] = new NameCallback("User name");
108            callbacks[1] = new PasswordCallback("Password", false);
109            try {
110                handler.handle(callbacks);
111            } catch (IOException ioe) {
112                throw (LoginException)new LoginException().initCause(ioe);
113            } catch (UnsupportedCallbackException uce) {
114                throw (LoginException)new LoginException().initCause(uce);
115            }
116            
117            String password;
118            
119            username = ((NameCallback)callbacks[0]).getName();
120            if (username == null)
121                    return false;
122                    
123            if (((PasswordCallback)callbacks[1]).getPassword() != null)
124                    password = new String(((PasswordCallback)callbacks[1]).getPassword());
125            else
126                    password="";
127    
128            // authenticate will throw LoginException
129            // in case of failed authentication
130            authenticate(username, password);
131            return true;
132        }
133    
134        @Override
135        public boolean logout() throws LoginException {
136            username = null;
137            return true;
138        }
139    
140        @Override
141        public boolean commit() throws LoginException {
142            Set<Principal> principals = subject.getPrincipals();
143            principals.add(new UserPrincipal(username));
144            for (GroupPrincipal gp : groups) {
145                principals.add(gp);
146            }
147            return true;
148        }
149    
150        @Override
151        public boolean abort() throws LoginException {
152            username = null;
153            return true;
154        }
155    
156        protected void close(DirContext context) {
157            try {
158                context.close();
159            } catch (Exception e) {
160                log.error(e.toString());
161            }
162        }
163    
164        protected boolean authenticate(String username, String password) throws LoginException {
165    
166            MessageFormat userSearchMatchingFormat;
167            boolean userSearchSubtreeBool;
168            
169            DirContext context = null;
170    
171            if (log.isDebugEnabled()) {
172                log.debug("Create the LDAP initial context.");
173            }
174            try {
175                context = open();
176            } catch (NamingException ne) {
177                FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
178                ex.initCause(ne);
179                throw ex;
180            }
181            
182            if (!isLoginPropertySet(USER_SEARCH_MATCHING))
183                    return false;
184    
185            userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
186            userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();
187    
188            try {
189    
190                String filter = userSearchMatchingFormat.format(new String[] {
191                    username
192                });
193                SearchControls constraints = new SearchControls();
194                if (userSearchSubtreeBool) {
195                    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
196                } else {
197                    constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
198                }
199    
200                // setup attributes
201                List<String> list = new ArrayList<String>();
202                if (isLoginPropertySet(USER_ROLE_NAME)) {
203                    list.add(getLDAPPropertyValue(USER_ROLE_NAME));
204                }
205                String[] attribs = new String[list.size()];
206                list.toArray(attribs);
207                constraints.setReturningAttributes(attribs);
208    
209                if (log.isDebugEnabled()) {
210                    log.debug("Get the user DN.");
211                    log.debug("Looking for the user in LDAP with ");
212                    log.debug("  base DN: " + getLDAPPropertyValue(USER_BASE));
213                    log.debug("  filter: " + filter);
214                }
215    
216                NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(USER_BASE), filter, constraints);
217    
218                if (results == null || !results.hasMore()) {
219                    log.warn("User " + username + " not found in LDAP.");
220                    throw new FailedLoginException("User " + username + " not found in LDAP.");
221                }
222    
223                SearchResult result = results.next();
224    
225                if (results.hasMore()) {
226                    // ignore for now
227                }
228                NameParser parser = context.getNameParser("");
229                Name contextName = parser.parse(context.getNameInNamespace());
230                Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE));
231                Name entryName = parser.parse(result.getName());
232                Name name = contextName.addAll(baseName);
233                name = name.addAll(entryName);
234                String dn = name.toString();
235    
236                Attributes attrs = result.getAttributes();
237                if (attrs == null) {
238                    throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
239                }
240                List<String> roles = null;
241                if (isLoginPropertySet(USER_ROLE_NAME)) {
242                    roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles);
243                }
244    
245                // check the credentials by binding to server
246                if (bindUser(context, dn, password)) {
247                    // if authenticated add more roles
248                    roles = getRoles(context, dn, username, roles);
249                    if (log.isDebugEnabled()) {
250                        log.debug("Roles " + roles + " for user " + username);
251                    }
252                    for (int i = 0; i < roles.size(); i++) {
253                        groups.add(new GroupPrincipal(roles.get(i)));
254                    }
255                } else {
256                    throw new FailedLoginException("Password does not match for user: " + username);
257                }
258            } catch (CommunicationException e) {
259                FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
260                ex.initCause(e);
261                throw ex;
262            } catch (NamingException e) {
263                if (context != null) {
264                    close(context);
265                }
266                FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
267                ex.initCause(e);
268                throw ex;
269            }
270    
271            return true;
272        }
273    
274        protected List<String> getRoles(DirContext context, String dn, String username, List<String> currentRoles) throws NamingException {
275            List<String> list = currentRoles;
276            MessageFormat roleSearchMatchingFormat;
277            boolean roleSearchSubtreeBool;
278            boolean expandRolesBool;
279            roleSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(ROLE_SEARCH_MATCHING));
280            roleSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(ROLE_SEARCH_SUBTREE)).booleanValue();
281            expandRolesBool = Boolean.valueOf(getLDAPPropertyValue(EXPAND_ROLES)).booleanValue();
282            
283            if (list == null) {
284                list = new ArrayList<String>();
285            }
286            if (!isLoginPropertySet(ROLE_NAME)) {
287                return list;
288            }
289            String filter = roleSearchMatchingFormat.format(new String[] {
290                doRFC2254Encoding(dn), username
291            });
292    
293            SearchControls constraints = new SearchControls();
294            if (roleSearchSubtreeBool) {
295                constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
296            } else {
297                constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
298            }
299            if (log.isDebugEnabled()) {
300                log.debug("Get user roles.");
301                log.debug("Looking for the user roles in LDAP with ");
302                log.debug("  base DN: " + getLDAPPropertyValue(ROLE_BASE));
303                log.debug("  filter: " + filter);
304            }
305            HashSet<String> haveSeenNames = new HashSet<String>();
306            Queue<String> pendingNameExpansion = new LinkedList<String>();
307            NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints);
308            while (results.hasMore()) {
309                SearchResult result = results.next();
310                Attributes attrs = result.getAttributes();
311                if (expandRolesBool) {
312                    haveSeenNames.add(result.getNameInNamespace());
313                    pendingNameExpansion.add(result.getNameInNamespace());
314                }
315                if (attrs == null) {
316                    continue;
317                }
318                list = addAttributeValues(getLDAPPropertyValue(ROLE_NAME), attrs, list);
319            }
320            if (expandRolesBool) {
321                MessageFormat expandRolesMatchingFormat = new MessageFormat(getLDAPPropertyValue(EXPAND_ROLES_MATCHING));
322                while (!pendingNameExpansion.isEmpty()) {
323                    String name = pendingNameExpansion.remove();
324                    filter = expandRolesMatchingFormat.format(new String[]{name});
325                    results = context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints);
326                    while (results.hasMore()) {
327                        SearchResult result = results.next();
328                        name = result.getNameInNamespace();
329                        if (!haveSeenNames.contains(name)) {
330                            Attributes attrs = result.getAttributes();
331                            list = addAttributeValues(getLDAPPropertyValue(ROLE_NAME), attrs, list);
332                            haveSeenNames.add(name);
333                            pendingNameExpansion.add(name);
334                        }
335                    }
336                }
337            }
338            return list;
339        }
340    
341        protected String doRFC2254Encoding(String inputString) {
342            StringBuffer buf = new StringBuffer(inputString.length());
343            for (int i = 0; i < inputString.length(); i++) {
344                char c = inputString.charAt(i);
345                switch (c) {
346                case '\\':
347                    buf.append("\\5c");
348                    break;
349                case '*':
350                    buf.append("\\2a");
351                    break;
352                case '(':
353                    buf.append("\\28");
354                    break;
355                case ')':
356                    buf.append("\\29");
357                    break;
358                case '\0':
359                    buf.append("\\00");
360                    break;
361                default:
362                    buf.append(c);
363                    break;
364                }
365            }
366            return buf.toString();
367        }
368    
369        protected boolean bindUser(DirContext context, String dn, String password) throws NamingException {
370            boolean isValid = false;
371    
372            if (log.isDebugEnabled()) {
373                log.debug("Binding the user.");
374            }
375            context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn);
376            context.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
377            try {
378                context.getAttributes("", null);
379                isValid = true;
380                if (log.isDebugEnabled()) {
381                    log.debug("User " + dn + " successfully bound.");
382                }
383            } catch (AuthenticationException e) {
384                isValid = false;
385                if (log.isDebugEnabled()) {
386                    log.debug("Authentication failed for dn=" + dn);
387                }
388            }
389    
390            if (isLoginPropertySet(CONNECTION_USERNAME)) {
391                context.addToEnvironment(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
392            } else {
393                context.removeFromEnvironment(Context.SECURITY_PRINCIPAL);
394            }
395            if (isLoginPropertySet(CONNECTION_PASSWORD)) {
396                context.addToEnvironment(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
397            } else {
398                context.removeFromEnvironment(Context.SECURITY_CREDENTIALS);
399            }
400    
401            return isValid;
402        }
403    
404        private List<String> addAttributeValues(String attrId, Attributes attrs, List<String> values) throws NamingException {
405    
406            if (attrId == null || attrs == null) {
407                return values;
408            }
409            if (values == null) {
410                values = new ArrayList<String>();
411            }
412            Attribute attr = attrs.get(attrId);
413            if (attr == null) {
414                return values;
415            }
416            NamingEnumeration<?> e = attr.getAll();
417            while (e.hasMore()) {
418                String value = (String)e.next();
419                values.add(value);
420            }
421            return values;
422        }
423    
424        protected DirContext open() throws NamingException {
425            try {
426                Hashtable<String, String> env = new Hashtable<String, String>();
427                env.put(Context.INITIAL_CONTEXT_FACTORY, getLDAPPropertyValue(INITIAL_CONTEXT_FACTORY));
428                if (isLoginPropertySet(CONNECTION_USERNAME)) {
429                    env.put(Context.SECURITY_PRINCIPAL, getLDAPPropertyValue(CONNECTION_USERNAME));
430                }
431                if (isLoginPropertySet(CONNECTION_PASSWORD)) {
432                    env.put(Context.SECURITY_CREDENTIALS, getLDAPPropertyValue(CONNECTION_PASSWORD));
433                }
434                env.put(Context.SECURITY_PROTOCOL, getLDAPPropertyValue(CONNECTION_PROTOCOL));
435                env.put(Context.PROVIDER_URL, getLDAPPropertyValue(CONNECTION_URL));
436                env.put(Context.SECURITY_AUTHENTICATION, getLDAPPropertyValue(AUTHENTICATION));
437                context = new InitialDirContext(env);
438    
439            } catch (NamingException e) {
440                log.error(e.toString());
441                throw e;
442            }
443            return context;
444        }
445        
446        private String getLDAPPropertyValue (String propertyName){
447            for (int i=0; i < config.length; i++ )
448                    if (config[i].getPropertyName() == propertyName)
449                            return config[i].getPropertyValue();
450            return null;
451        }
452        
453        private boolean isLoginPropertySet(String propertyName) {
454            for (int i=0; i < config.length; i++ ) {
455                    if (config[i].getPropertyName() == propertyName && config[i].getPropertyValue() != null)
456                                    return true;
457            }
458            return false;
459        }
460    
461    }