Simplified LDAP search query by removing not neccessary fields for the task.
[timetracker.git] / WEB-INF / lib / auth / Auth_ldap.class.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/content/time_tracker/open_source/credits.htm
27 // +----------------------------------------------------------------------+
28
29 // NOTES:
30 //
31 // Auth_ldap.class.php was originally written for LDAP authentication with Windows Active Directory.
32 // It June 2011, it was extended to include support for OpenLDAP. The difference in the code is in the format
33 // of user identification that we pass to ldap_bind().
34 //
35 // Windows AD accepts username@domain.com while OpenLDAP needs something like "uid=username,ou=people,dc=domain,dc=com".
36 // Therefore, some branching in the code.
37 //
38 // In April 2012, a previously mandatory search for group membership was put in a conditional block (if ($member_of) -
39 // when mandatory membership in groups is actually defined in config.php).
40 // This made the module work with Sun Directory Server when NO GROUP MEMBERSHIP is specified.
41 // Note 1: search is likely to fail with Sun DS if 'member_of' => array()); is used in config.php.
42 // Note 2: search is likely to not work properly with OpenLDAP as well because of Windows specific filtering code in there
43 // (we are looking for matches for Windows-specific samaccountname property). Search needs to be redone during the next
44 // refactoring effort.
45
46
47 /**
48 * Auth_ldap class to authenticate users against an LDAP server (Windows AD, OpenLDAP, and others).
49 * @package TimeTracker
50 */
51 class Auth_ldap extends Auth {
52   var $params;
53
54   function __construct($params)
55   {
56     $this->params = $params;
57     if (isset($GLOBALS['smarty'])) {
58       $GLOBALS['smarty']->assign('Auth_ldap_params', $this->params);
59     }
60   }
61
62   function ldap_escape($str){
63     $illegal = array("(", ")", "#");
64     $legal = array();
65     foreach ($illegal as $id => $char) {
66       $legal[$id] = "\\".$char;
67     }
68     $str = str_replace($illegal, $legal, $str); //replace them
69     return $str;
70   }
71
72   /**
73    * Authenticate user against LDAP server.
74    *
75    * @param string $login
76    * @param string $password
77    * @return mixed
78    */
79   function authenticate($login, $password)
80   {
81     // Special handling for admin@localhost - authenticate against db, not ldap.
82     // It is a fallback mechanism when admin account in LDAP directory does not exist or is misconfigured.
83     if ($login == 'admin@localhost') {
84         import('auth.Auth_db');
85         return Auth_db::authenticate($login, $password);
86     }
87
88     if (!function_exists('ldap_bind')) {
89       die ('php_ldap extension not loaded!');
90     }
91
92     if (empty($this->params['server']) || empty($this->params['base_dn'])) {
93       die('You must set server and base_dn in AUTH_MODULE_PARAMS in config.php');
94     }
95
96     $member_of = @$this->params['member_of'];
97
98     $lc = ldap_connect($this->params['server']);
99
100     if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
101       echo '<br />';
102       echo '$lc='; var_dump($lc); echo '<br />';
103       echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
104     }
105
106     if (!$lc) return false;
107
108     ldap_set_option($lc, LDAP_OPT_PROTOCOL_VERSION, 3);
109     ldap_set_option($lc, LDAP_OPT_REFERRALS, 0);
110     if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
111       ldap_set_option($lc, LDAP_OPT_DEBUG_LEVEL, 7);
112     }
113
114     // We need to handle Windows AD and OpenLDAP differently.
115     if ($this->params['type'] == 'ad') {
116
117       // Check if user specified full login.
118       if (strpos($login, '@') === false) {
119         // Append default domain.
120         $login .= '@' . $this->params['default_domain'];
121       }
122
123       if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
124         echo '$login='; var_dump($login); echo '<br />';
125       }
126
127       $lb = @ldap_bind($lc, $login, $password);
128
129       if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
130         echo '$lb='; var_dump($lb); echo '<br />';
131         echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
132       }
133
134       if (!$lb) {
135         ldap_unbind($lc);
136         return false;
137       }
138
139       if ($member_of) {
140         // Get groups the user is a member of from AD LDAP server.
141
142         $filter = 'userPrincipalName='.Auth_ldap::ldap_escape($login);
143         $fields = array('memberof');
144         $sr = @ldap_search($lc, $this->params['base_dn'], $filter, $fields);
145
146         if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
147           echo '$sr='; var_dump($sr); echo '<br />';
148           echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
149         }
150
151         if (!$sr) {
152           ldap_unbind($lc);
153           return false;
154         }
155
156         $entries = @ldap_get_entries($lc, $sr);
157
158         if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
159           echo '$entries='; var_dump($entries); echo '<br />';
160           echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
161         }
162
163         if ($entries === false) {
164           ldap_unbind($lc);
165           return false;
166         }
167
168         $groups = array();
169
170         // Extract group names. Assume the groups are in format: CN=<group_name>,...
171         for ($i = 0; $i < @$entries[0]['memberof']['count']; $i++) {
172           $grp = $entries[0]['memberof'][$i];
173           $grp_fields = explode(',', $grp);
174           $groups[] = substr($grp_fields[0], 3);
175         }
176
177         if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
178           echo '$member_of'; var_dump($member_of); echo '<br />';
179         };
180
181         // Check for group membership.
182         foreach ($member_of as $check_grp) {
183           if (!in_array($check_grp, $groups)) {
184             ldap_unbind($lc);
185             return false;
186           }
187         }
188       }
189
190       ldap_unbind($lc);
191       return array('login' => $login, 'data' => $entries, 'member_of' => $groups);
192     }
193
194     if ($this->params['type'] == 'openldap') {
195
196       // Assuming OpenLDAP server.
197       $login_oldap = 'uid='.$login.','.$this->params['base_dn'];
198
199       if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
200         echo '$login_oldap='; var_dump($login_oldap); echo '<br />';
201       }
202
203       // check if the user specified full login
204       if (strpos($login, '@') === false) {
205         // append default domain
206         $login .= '@' . $this->params['default_domain'];
207       }
208
209       $lb = @ldap_bind($lc, $login_oldap, $password);
210
211       if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
212         echo '$lb='; var_dump($lb); echo '<br />';
213         echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
214       }
215
216       if (!$lb) {
217         ldap_unbind($lc);
218         return false;
219       }
220
221       if ($member_of) {
222         // TODO: Fix this for OpenLDAP, as samaccountname has nothing to do with it.
223         // get groups
224
225         $filter = 'samaccountname='.Auth_ldap::ldap_escape($login_oldap);
226         $fields = array('samaccountname', 'mail', 'memberof', 'department', 'displayname', 'telephonenumber', 'primarygroupid');
227         $sr = @ldap_search($lc, $this->params['base_dn'], $filter, $fields);
228
229         if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
230           echo '$sr='; var_dump($sr); echo '<br />';
231           echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
232         }
233
234         // if search failed it's likely that account is disabled
235         if (!$sr) {
236           ldap_unbind($lc);
237           return false;
238         }
239
240         $entries = @ldap_get_entries($lc, $sr);
241
242         if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
243           echo '$entries='; var_dump($entries); echo '<br />';
244           echo 'ldap_error()='; echo ldap_error($lc); echo '<br />';
245         }
246
247         if ($entries === false) {
248           ldap_unbind($lc);
249           return false;
250         }
251
252         $groups = array();
253
254         // extract group names from
255         // assuming the groups are in format: CN=<group_name>,...
256         for ($i = 0; $i < @$entries[0]['memberof']['count']; $i++) {
257           $grp = $entries[0]['memberof'][$i];
258           $grp_fields = explode(',', $grp);
259           $groups[] = substr($grp_fields[0], 3);
260         }
261
262         if (defined('AUTH_DEBUG') && isTrue(AUTH_DEBUG)) {
263           echo '$member_of'; var_dump($member_of); echo '<br />';
264         }
265
266         // check for group membership
267         foreach ($member_of as $check_grp) {
268           if (!in_array($check_grp, $groups)) {
269             ldap_unbind($lc);
270             return false;
271           }
272         }
273       }
274
275       ldap_unbind($lc);
276
277       return array('login' => $login, 'data' => $entries, 'member_of' => $groups);
278     }
279
280     // Server type is neither 'ad' or 'openldap'.
281     return false;
282   }
283
284   function isPasswordExternal() {
285     return true;
286   }
287 }