View Javadoc

1   // ========================================================================
2   // Copyright (c) 2007-2009 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // All rights reserved. This program and the accompanying materials
5   // are made available under the terms of the Eclipse Public License v1.0
6   // and Apache License v2.0 which accompanies this distribution.
7   // The Eclipse Public License is available at 
8   // http://www.eclipse.org/legal/epl-v10.html
9   // The Apache License v2.0 is available at
10  // http://www.opensource.org/licenses/apache2.0.php
11  // You may elect to redistribute this code under either of these licenses. 
12  // ========================================================================
13  package org.eclipse.jetty.plus.jaas.spi;
14  
15  import java.io.IOException;
16  import java.util.ArrayList;
17  import java.util.Hashtable;
18  import java.util.List;
19  import java.util.Map;
20  import java.util.Properties;
21  
22  import javax.naming.Context;
23  import javax.naming.NamingEnumeration;
24  import javax.naming.NamingException;
25  import javax.naming.directory.Attribute;
26  import javax.naming.directory.Attributes;
27  import javax.naming.directory.DirContext;
28  import javax.naming.directory.InitialDirContext;
29  import javax.naming.directory.SearchControls;
30  import javax.naming.directory.SearchResult;
31  import javax.security.auth.Subject;
32  import javax.security.auth.callback.Callback;
33  import javax.security.auth.callback.CallbackHandler;
34  import javax.security.auth.callback.NameCallback;
35  import javax.security.auth.callback.UnsupportedCallbackException;
36  import javax.security.auth.login.LoginException;
37  
38  import org.eclipse.jetty.util.security.Credential;
39  import org.eclipse.jetty.plus.jaas.callback.ObjectCallback;
40  import org.eclipse.jetty.util.log.Log;
41  import org.eclipse.jetty.util.log.Logger;
42  
43  /**
44   * A LdapLoginModule for use with JAAS setups
45   * <p/>
46   * The jvm should be started with the following parameter:
47   * <br><br>
48   * <code>
49   * -Djava.security.auth.login.config=etc/ldap-loginModule.conf
50   * </code>
51   * <br><br>
52   * and an example of the ldap-loginModule.conf would be:
53   * <br><br>
54   * <pre>
55   * ldaploginmodule {
56   *    org.eclipse.jetty.server.server.plus.jaas.spi.LdapLoginModule required
57   *    debug="true"
58   *    useLdaps="false"
59   *    contextFactory="com.sun.jndi.ldap.LdapCtxFactory"
60   *    hostname="ldap.example.com"
61   *    port="389"
62   *    bindDn="cn=Directory Manager"
63   *    bindPassword="directory"
64   *    authenticationMethod="simple"
65   *    forceBindingLogin="false"
66   *    userBaseDn="ou=people,dc=alcatel"
67   *    userRdnAttribute="uid"
68   *    userIdAttribute="uid"
69   *    userPasswordAttribute="userPassword"
70   *    userObjectClass="inetOrgPerson"
71   *    roleBaseDn="ou=groups,dc=example,dc=com"
72   *    roleNameAttribute="cn"
73   *    roleMemberAttribute="uniqueMember"
74   *    roleObjectClass="groupOfUniqueNames";
75   *    };
76   *  </pre>
77   *
78   * 
79   * 
80   * 
81   */
82  public class LdapLoginModule extends AbstractLoginModule
83  {
84      private static final Logger LOG = Log.getLogger(LdapLoginModule.class);
85  
86      /**
87       * hostname of the ldap server
88       */
89      private String _hostname;
90  
91      /**
92       * port of the ldap server
93       */
94      private int _port;
95  
96      /**
97       * Context.SECURITY_AUTHENTICATION
98       */
99      private String _authenticationMethod;
100 
101     /**
102      * Context.INITIAL_CONTEXT_FACTORY
103      */
104     private String _contextFactory;
105 
106     /**
107      * root DN used to connect to
108      */
109     private String _bindDn;
110 
111     /**
112      * password used to connect to the root ldap context
113      */
114     private String _bindPassword;
115 
116     /**
117      * object class of a user
118      */
119     private String _userObjectClass = "inetOrgPerson";
120 
121     /**
122      * attribute that the principal is located
123      */
124     private String _userRdnAttribute = "uid";
125 
126     /**
127      * attribute that the principal is located
128      */
129     private String _userIdAttribute = "cn";
130 
131     /**
132      * name of the attribute that a users password is stored under
133      * <p/>
134      * NOTE: not always accessible, see force binding login
135      */
136     private String _userPasswordAttribute = "userPassword";
137 
138     /**
139      * base DN where users are to be searched from
140      */
141     private String _userBaseDn;
142 
143     /**
144      * base DN where role membership is to be searched from
145      */
146     private String _roleBaseDn;
147 
148     /**
149      * object class of roles
150      */
151     private String _roleObjectClass = "groupOfUniqueNames";
152 
153     /**
154      * name of the attribute that a username would be under a role class
155      */
156     private String _roleMemberAttribute = "uniqueMember";
157 
158     /**
159      * the name of the attribute that a role would be stored under
160      */
161     private String _roleNameAttribute = "roleName";
162 
163     private boolean _debug;
164 
165     /**
166      * if the getUserInfo can pull a password off of the user then
167      * password comparison is an option for authn, to force binding
168      * login checks, set this to true
169      */
170     private boolean _forceBindingLogin = false;
171     
172     /**
173      * When true changes the protocol to ldaps
174      */
175     private boolean _useLdaps = false;
176 
177     private DirContext _rootContext;
178 
179     /**
180      * get the available information about the user
181      * <p/>
182      * for this LoginModule, the credential can be null which will result in a
183      * binding ldap authentication scenario
184      * <p/>
185      * roles are also an optional concept if required
186      *
187      * @param username
188      * @return the userinfo for the username
189      * @throws Exception
190      */
191     public UserInfo getUserInfo(String username) throws Exception
192     {
193         String pwdCredential = getUserCredentials(username);
194 
195         if (pwdCredential == null)
196         {
197             return null;
198         }
199 
200         pwdCredential = convertCredentialLdapToJetty(pwdCredential);
201         Credential credential = Credential.getCredential(pwdCredential);
202         List<String> roles = getUserRoles(_rootContext, username);
203 
204         return new UserInfo(username, credential, roles);
205     }
206 
207     protected String doRFC2254Encoding(String inputString)
208     {
209         StringBuffer buf = new StringBuffer(inputString.length());
210         for (int i = 0; i < inputString.length(); i++)
211         {
212             char c = inputString.charAt(i);
213             switch (c)
214             {
215                 case '\\':
216                     buf.append("\\5c");
217                     break;
218                 case '*':
219                     buf.append("\\2a");
220                     break;
221                 case '(':
222                     buf.append("\\28");
223                     break;
224                 case ')':
225                     buf.append("\\29");
226                     break;
227                 case '\0':
228                     buf.append("\\00");
229                     break;
230                 default:
231                     buf.append(c);
232                     break;
233             }
234         }
235         return buf.toString();
236     }
237 
238     /**
239      * attempts to get the users credentials from the users context
240      * <p/>
241      * NOTE: this is not an user authenticated operation
242      *
243      * @param username
244      * @return
245      * @throws LoginException
246      */
247     private String getUserCredentials(String username) throws LoginException
248     {
249         String ldapCredential = null;
250 
251         SearchControls ctls = new SearchControls();
252         ctls.setCountLimit(1);
253         ctls.setDerefLinkFlag(true);
254         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
255 
256         String filter = "(&(objectClass={0})({1}={2}))";
257 
258         LOG.debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn);
259 
260         try
261         {
262             Object[] filterArguments = {_userObjectClass, _userIdAttribute, username};
263             NamingEnumeration<SearchResult> results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);
264 
265             LOG.debug("Found user?: " + results.hasMoreElements());
266 
267             if (!results.hasMoreElements())
268             {
269                 throw new LoginException("User not found.");
270             }
271 
272             SearchResult result = findUser(username);
273 
274             Attributes attributes = result.getAttributes();
275 
276             Attribute attribute = attributes.get(_userPasswordAttribute);
277             if (attribute != null)
278             {
279                 try
280                 {
281                     byte[] value = (byte[]) attribute.get();
282 
283                     ldapCredential = new String(value);
284                 }
285                 catch (NamingException e)
286                 {
287                     LOG.debug("no password available under attribute: " + _userPasswordAttribute);
288                 }
289             }
290         }
291         catch (NamingException e)
292         {
293             throw new LoginException("Root context binding failure.");
294         }
295 
296         LOG.debug("user cred is: " + ldapCredential);
297 
298         return ldapCredential;
299     }
300 
301     /**
302      * attempts to get the users roles from the root context
303      * <p/>
304      * NOTE: this is not an user authenticated operation
305      *
306      * @param dirContext
307      * @param username
308      * @return
309      * @throws LoginException
310      */
311     private List<String> getUserRoles(DirContext dirContext, String username) throws LoginException, NamingException
312     {
313         String userDn = _userRdnAttribute + "=" + username + "," + _userBaseDn;
314 
315         return getUserRolesByDn(dirContext, userDn);
316     }
317 
318     private List<String> getUserRolesByDn(DirContext dirContext, String userDn) throws LoginException, NamingException
319     {
320         List<String> roleList = new ArrayList<String>();
321 
322         if (dirContext == null || _roleBaseDn == null || _roleMemberAttribute == null || _roleObjectClass == null)
323         {
324             return roleList;
325         }
326 
327         SearchControls ctls = new SearchControls();
328         ctls.setDerefLinkFlag(true);
329         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
330         ctls.setReturningAttributes(new String[]{_roleNameAttribute});
331 
332         String filter = "(&(objectClass={0})({1}={2}))";
333         Object[] filterArguments = {_roleObjectClass, _roleMemberAttribute, userDn};
334         NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
335 
336         LOG.debug("Found user roles?: " + results.hasMoreElements());
337 
338         while (results.hasMoreElements())
339         {
340             SearchResult result = (SearchResult) results.nextElement();
341 
342             Attributes attributes = result.getAttributes();
343 
344             if (attributes == null)
345             {
346                 continue;
347             }
348 
349             Attribute roleAttribute = attributes.get(_roleNameAttribute);
350 
351             if (roleAttribute == null)
352             {
353                 continue;
354             }
355 
356             NamingEnumeration<?> roles = roleAttribute.getAll();
357             while (roles.hasMore())
358             {
359                 roleList.add(roles.next().toString());
360             }
361         }
362 
363         return roleList;
364     }
365 
366 
367     /**
368      * since ldap uses a context bind for valid authentication checking, we override login()
369      * <p/>
370      * if credentials are not available from the users context or if we are forcing the binding check
371      * then we try a binding authentication check, otherwise if we have the users encoded password then
372      * we can try authentication via that mechanic
373      *
374      * @return true if authenticated, false otherwise
375      * @throws LoginException
376      */
377     public boolean login() throws LoginException
378     {
379         try
380         {
381             if (getCallbackHandler() == null)
382             {
383                 throw new LoginException("No callback handler");
384             }
385 
386             Callback[] callbacks = configureCallbacks();
387             getCallbackHandler().handle(callbacks);
388 
389             String webUserName = ((NameCallback) callbacks[0]).getName();
390             Object webCredential = ((ObjectCallback) callbacks[1]).getObject();
391 
392             if (webUserName == null || webCredential == null)
393             {
394                 setAuthenticated(false);
395                 return isAuthenticated();
396             }
397 
398             if (_forceBindingLogin)
399             {
400                 return bindingLogin(webUserName, webCredential);
401             }
402 
403             // This sets read and the credential
404             UserInfo userInfo = getUserInfo(webUserName);
405 
406             if (userInfo == null)
407             {
408                 setAuthenticated(false);
409                 return false;
410             }
411 
412             setCurrentUser(new JAASUserInfo(userInfo));
413 
414             if (webCredential instanceof String)
415             {
416                 return credentialLogin(Credential.getCredential((String) webCredential));
417             }
418 
419             return credentialLogin(webCredential);
420         }
421         catch (UnsupportedCallbackException e)
422         {
423             throw new LoginException("Error obtaining callback information.");
424         }
425         catch (IOException e)
426         {
427             if (_debug)
428             {
429                 e.printStackTrace();
430             }
431             throw new LoginException("IO Error performing login.");
432         }
433         catch (Exception e)
434         {
435             if (_debug)
436             {
437                 e.printStackTrace();
438             }
439             throw new LoginException("Error obtaining user info.");
440         }
441     }
442 
443     /**
444      * password supplied authentication check
445      *
446      * @param webCredential
447      * @return true if authenticated
448      * @throws LoginException
449      */
450     protected boolean credentialLogin(Object webCredential) throws LoginException
451     {
452         setAuthenticated(getCurrentUser().checkCredential(webCredential));
453         return isAuthenticated();
454     }
455 
456     /**
457      * binding authentication check
458      * This method of authentication works only if the user branch of the DIT (ldap tree)
459      * has an ACI (access control instruction) that allow the access to any user or at least
460      * for the user that logs in.
461      *
462      * @param username
463      * @param password
464      * @return true always
465      * @throws LoginException
466      */
467     public boolean bindingLogin(String username, Object password) throws LoginException, NamingException
468     {
469         SearchResult searchResult = findUser(username);
470 
471         String userDn = searchResult.getNameInNamespace();
472 
473         LOG.info("Attempting authentication: " + userDn);
474 
475         Hashtable<Object,Object> environment = getEnvironment();
476         environment.put(Context.SECURITY_PRINCIPAL, userDn);
477         environment.put(Context.SECURITY_CREDENTIALS, password);
478 
479         DirContext dirContext = new InitialDirContext(environment);
480         List<String> roles = getUserRolesByDn(dirContext, userDn);
481 
482         UserInfo userInfo = new UserInfo(username, null, roles);
483         setCurrentUser(new JAASUserInfo(userInfo));
484         setAuthenticated(true);
485 
486         return true;
487     }
488 
489     private SearchResult findUser(String username) throws NamingException, LoginException
490     {
491         SearchControls ctls = new SearchControls();
492         ctls.setCountLimit(1);
493         ctls.setDerefLinkFlag(true);
494         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
495 
496         String filter = "(&(objectClass={0})({1}={2}))";
497 
498         LOG.info("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn);
499 
500         Object[] filterArguments = new Object[]{
501             _userObjectClass,
502             _userIdAttribute,
503             username
504         };
505         NamingEnumeration<SearchResult> results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls);
506 
507         LOG.info("Found user?: " + results.hasMoreElements());
508 
509         if (!results.hasMoreElements())
510         {
511             throw new LoginException("User not found.");
512         }
513 
514         return (SearchResult) results.nextElement();
515     }
516 
517 
518     /**
519      * Init LoginModule.
520      * Called once by JAAS after new instance is created.
521      *
522      * @param subject
523      * @param callbackHandler
524      * @param sharedState
525      * @param options
526      */
527     public void initialize(Subject subject,
528                            CallbackHandler callbackHandler,
529                            Map<String,?> sharedState,
530                            Map<String,?> options)
531     {
532         super.initialize(subject, callbackHandler, sharedState, options);
533 
534         _hostname = (String) options.get("hostname");
535         _port = Integer.parseInt((String) options.get("port"));
536         _contextFactory = (String) options.get("contextFactory");
537         _bindDn = (String) options.get("bindDn");
538         _bindPassword = (String) options.get("bindPassword");
539         _authenticationMethod = (String) options.get("authenticationMethod");
540 
541         _userBaseDn = (String) options.get("userBaseDn");
542 
543         _roleBaseDn = (String) options.get("roleBaseDn");
544 
545         if (options.containsKey("forceBindingLogin"))
546         {
547             _forceBindingLogin = Boolean.parseBoolean((String) options.get("forceBindingLogin"));
548         }
549         
550         if (options.containsKey("useLdaps"))
551         {
552             _useLdaps = Boolean.parseBoolean((String) options.get("useLdaps"));
553         }     
554         
555         _userObjectClass = getOption(options, "userObjectClass", _userObjectClass);
556         _userRdnAttribute = getOption(options, "userRdnAttribute", _userRdnAttribute);
557         _userIdAttribute = getOption(options, "userIdAttribute", _userIdAttribute);
558         _userPasswordAttribute = getOption(options, "userPasswordAttribute", _userPasswordAttribute);
559         _roleObjectClass = getOption(options, "roleObjectClass", _roleObjectClass);
560         _roleMemberAttribute = getOption(options, "roleMemberAttribute", _roleMemberAttribute);
561         _roleNameAttribute = getOption(options, "roleNameAttribute", _roleNameAttribute);
562         _debug = Boolean.parseBoolean(String.valueOf(getOption(options, "debug", Boolean.toString(_debug))));
563 
564         try
565         {
566             _rootContext = new InitialDirContext(getEnvironment());
567         }
568         catch (NamingException ex)
569         {
570             throw new IllegalStateException("Unable to establish root context", ex);
571         }
572     }
573 
574     public boolean commit() throws LoginException 
575     {
576         try 
577         {
578             _rootContext.close();
579         } 
580         catch (NamingException e) 
581         {
582             throw new LoginException( "error closing root context: " + e.getMessage() );
583         }
584 
585         return super.commit();
586     }
587 
588     public boolean abort() throws LoginException 
589     {
590         try 
591         {
592             _rootContext.close();
593         } 
594         catch (NamingException e) 
595         {
596             throw new LoginException( "error closing root context: " + e.getMessage() );
597         }
598 
599         return super.abort();
600     }
601 
602     private String getOption(Map<String,?> options, String key, String defaultValue)
603     {
604         Object value = options.get(key);
605 
606         if (value == null)
607         {
608             return defaultValue;
609         }
610 
611         return (String) value;
612     }
613 
614     /**
615      * get the context for connection
616      *
617      * @return the environment details for the context
618      */
619     public Hashtable<Object, Object> getEnvironment()
620     {
621         Properties env = new Properties();
622 
623         env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory);
624 
625         if (_hostname != null)
626         {
627             env.put(Context.PROVIDER_URL, (_useLdaps?"ldaps://":"ldap://") + _hostname + (_port==0?"":":"+_port) +"/");
628         }
629 
630         if (_authenticationMethod != null)
631         {
632             env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod);
633         }
634 
635         if (_bindDn != null)
636         {
637             env.put(Context.SECURITY_PRINCIPAL, _bindDn);
638         }
639 
640         if (_bindPassword != null)
641         {
642             env.put(Context.SECURITY_CREDENTIALS, _bindPassword);
643         }
644 
645         return env;
646     }
647 
648     public static String convertCredentialJettyToLdap(String encryptedPassword)
649     {
650         if ("MD5:".startsWith(encryptedPassword.toUpperCase()))
651         {
652             return "{MD5}" + encryptedPassword.substring("MD5:".length(), encryptedPassword.length());
653         }
654 
655         if ("CRYPT:".startsWith(encryptedPassword.toUpperCase()))
656         {
657             return "{CRYPT}" + encryptedPassword.substring("CRYPT:".length(), encryptedPassword.length());
658         }
659 
660         return encryptedPassword;
661     }
662 
663     public static String convertCredentialLdapToJetty(String encryptedPassword)
664     {
665         if (encryptedPassword == null)
666         {
667             return encryptedPassword;
668         }
669 
670         if ("{MD5}".startsWith(encryptedPassword.toUpperCase()))
671         {
672             return "MD5:" + encryptedPassword.substring("{MD5}".length(), encryptedPassword.length());
673         }
674 
675         if ("{CRYPT}".startsWith(encryptedPassword.toUpperCase()))
676         {
677             return "CRYPT:" + encryptedPassword.substring("{CRYPT}".length(), encryptedPassword.length());
678         }
679 
680         return encryptedPassword;
681     }
682 }