]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Users/authentication/LDAPAuthenticate/LDAPAuthenticateUser.php
Release 6.5.0
[Github/sugarcrm.git] / modules / Users / authentication / LDAPAuthenticate / LDAPAuthenticateUser.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39
40
41 /**
42  * This file is where the user authentication occurs. No redirection should happen in this file.
43  *
44  */
45 require_once('modules/Users/authentication/LDAPAuthenticate/LDAPConfigs/default.php');
46 require_once('modules/Users/authentication/SugarAuthenticate/SugarAuthenticateUser.php');
47
48 define('DEFAULT_PORT', 389);
49 class LDAPAuthenticateUser extends SugarAuthenticateUser{
50
51         /**
52          * Does the actual authentication of the user and returns an id that will be used
53          * to load the current user (loadUserOnSession)
54          *
55          * @param STRING $name
56          * @param STRING $password
57          * @return STRING id - used for loading the user
58          *
59          * Contributions by Erik Mitchell erikm@logicpd.com
60          */
61         function authenticateUser($name, $password) {
62
63                 $server = $GLOBALS['ldap_config']->settings['ldap_hostname'];
64                 $port = $GLOBALS['ldap_config']->settings['ldap_port'];
65                 if(!$port)
66                         $port = DEFAULT_PORT;
67                 $GLOBALS['log']->debug("ldapauth: Connecting to LDAP server: $server");
68                 $ldapconn = ldap_connect($server, $port);
69                  $error = ldap_errno($ldapconn);
70                 if($this->loginError($error)){
71                         return '';
72                 }
73                 @ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
74                 @ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); // required for AD
75
76
77
78                 $bind_user = $this->ldap_rdn_lookup($name, $password);
79                 $GLOBALS['log']->debug("ldapauth.ldap_authenticate_user: ldap_rdn_lookup returned bind_user=" . $bind_user);
80                 if (!$bind_user) {
81                         $GLOBALS['log']->fatal("SECURITY: ldapauth: failed LDAP bind (login) by " .
82                                                                         $name . ", could not construct bind_user");
83                         return '';
84                 }
85
86                 // MRF - Bug #18578 - punctuation was being passed as HTML entities, i.e. &amp;
87                 $bind_password = html_entity_decode($password,ENT_QUOTES);
88                 $GLOBALS['log']->info("ldapauth: Binding user " . $bind_user);
89
90                 $bind = ldap_bind($ldapconn, $bind_user, $bind_password);
91                  $error = ldap_errno($ldapconn);
92         if($this->loginError($error)){
93                         $GLOBALS['log']->fatal('[LDAP] ATTEMPTING BIND USING BASE DN PARAMS');
94                                 $bind = ldap_bind($ldapconn, $GLOBALS['ldap_config']->settings['ldap_bind_attr'] . "=" . $bind_user . "," . $GLOBALS['ldap_config']->settings['ldap_base_dn'], $bind_password);
95                                 $error = ldap_errno($ldapconn);
96                                 if($this->loginError($error)){
97                                 return '';
98                                 }
99                 }
100
101                 $GLOBALS['log']->info("ldapauth: Bind attempt complete.");
102
103                 if ($bind) {
104                         // Authentication succeeded, get info from LDAP directory
105                         $attrs = array_keys($GLOBALS['ldapConfig']['users']['fields']);
106                         $base_dn = $GLOBALS['ldap_config']->settings['ldap_base_dn'];
107                         $name_filter = $this->getUserNameFilter($name);
108
109                         //add the group user attribute that we will compare to the group attribute for membership validation if group membership is turned on
110                         if(!empty($GLOBALS['ldap_config']->settings['ldap_group']) && !empty($GLOBALS['ldap_config']->settings['ldap_group_user_attr']) && !empty($GLOBALS['ldap_config']->settings['ldap_group_attr'])){
111                                 if(!in_array($attrs, $GLOBALS['ldap_config']->settings['ldap_group_user_attr'])){
112                                         $attrs[] = $GLOBALS['ldap_config']->settings['ldap_group_user_attr'];
113                                 }
114                         }
115
116                         $GLOBALS['log']->debug("ldapauth: Fetching user info from Directory.");
117                         $result = @ldap_search($ldapconn, $base_dn, $name_filter, $attrs);
118                         $error = ldap_errno($ldapconn);
119                          if($this->loginError($error)){
120                         return '';
121                         }
122                         $GLOBALS['log']->debug("ldapauth: ldap_search complete.");
123
124                         $info = @ldap_get_entries($ldapconn, $result);
125                          $error = ldap_errno($ldapconn);
126                 if($this->loginError($error)){
127                         return '';
128                         }
129
130
131
132                         $GLOBALS['log']->debug("ldapauth: User info from Directory fetched.");
133
134                         // some of these don't seem to work
135                         $this->ldapUserInfo = array();
136                         foreach($GLOBALS['ldapConfig']['users']['fields'] as $key=>$value){
137                                 //MRF - BUG:19765
138                                 $key = strtolower($key);
139                                 if(isset($info[0]) && isset($info[0][$key]) && isset($info[0][$key][0])){
140                                         $this->ldapUserInfo[$value] = $info[0][$key][0];
141                                 }
142                         }
143
144                         //we should check that a user is a member of a specific group
145                         if(!empty($GLOBALS['ldap_config']->settings['ldap_group'])){
146                                 $GLOBALS['log']->debug("LDAPAuth: scanning group for user membership");
147                                 $group_user_attr = $GLOBALS['ldap_config']->settings['ldap_group_user_attr'];
148                                 $group_attr = $GLOBALS['ldap_config']->settings['ldap_group_attr'];
149                                 if(!isset($info[0][$group_user_attr])){
150                                         $GLOBALS['log']->fatal("ldapauth: $group_user_attr not found for user $name cannot authenticate against an LDAP group");
151                                         ldap_close($ldapconn);
152                                         return '';
153                                 }else{
154                                         $user_uid = $info[0][$group_user_attr];
155                                 }
156                                 //user is not a member of the group if the count is zero get the logs and return no id so it fails login
157                                 if(!isset($user_uid[0]) || ldap_count_entries($ldapconn, ldap_search($ldapconn,$GLOBALS['ldap_config']->settings['ldap_group_name'] . ",". $GLOBALS['ldap_config']->settings['ldap_group_dn']  ,"($group_attr=" . $user_uid[0] . ")")) ==  0){
158                                         $GLOBALS['log']->fatal("ldapauth: User ($name) is not a member of the LDAP group");
159                                         $user_id = var_export($user_uid, true);
160                                         $GLOBALS['log']->debug("ldapauth: Group DN:{$GLOBALS['ldap_config']->settings['ldap_group_dn']} Group Name: " . $GLOBALS['ldap_config']->settings['ldap_group_name']  . " Group Attribute: $group_attr  User Attribute: $group_user_attr :(" . $user_uid[0] . ")");
161                                         ldap_close($ldapconn);
162                                         return '';
163                                 }
164
165
166                         }
167
168
169
170                         ldap_close($ldapconn);
171                         $dbresult = $GLOBALS['db']->query("SELECT id, status FROM users WHERE user_name='" . $name . "' AND deleted = 0");
172
173                         //user already exists use this one
174                         if($row = $GLOBALS['db']->fetchByAssoc($dbresult)){
175                                 if($row['status'] != 'Inactive')
176                                         return $row['id'];
177                                 else
178                                         return '';
179                         }
180
181                         //create a new user and return the user
182                         if($GLOBALS['ldap_config']->settings['ldap_auto_create_users']){
183                                 return $this->createUser($name);
184
185                         }
186                         return '';
187
188                 } else {
189                         $GLOBALS['log']->fatal("SECURITY: failed LDAP bind (login) by $this->user_name using bind_user=$bind_user");
190                         $GLOBALS['log']->fatal("ldapauth: failed LDAP bind (login) by $this->user_name using bind_user=$bind_user");
191                         ldap_close($ldapconn);
192                         return '';
193                 }
194         }
195
196         /**
197          * takes in a name and creates the appropriate search filter for that user name including any additional filters specified in the system settings page
198          * @param $name
199          * @return String
200          */
201         function getUserNameFilter($name){
202                         $name_filter = "(" . $GLOBALS['ldap_config']->settings['ldap_login_attr']. "=" . $name . ")";
203                         //add the additional user filter if it is specified
204                         if(!empty($GLOBALS['ldap_config']->settings['ldap_login_filter'])){
205                                 $add_filter = $GLOBALS['ldap_config']->settings['ldap_login_filter'];
206                                 if(substr($add_filter, 0, 1) !== "("){
207                                         $add_filter = "(" . $add_filter . ")";
208                                 }
209                                 $name_filter = "(&" . $name_filter . $add_filter . ")";
210                         }
211                         return $name_filter;
212         }
213
214         /**
215          * Creates a user with the given User Name and returns the id of that new user
216          * populates the user with what was set in ldapUserInfo
217          *
218          * @param STRING $name
219          * @return STRING $id
220          */
221         function createUser($name){
222
223                         $user = new User();
224                         $user->user_name = $name;
225                         foreach($this->ldapUserInfo as $key=>$value){
226                                 $user->$key = $value;
227                         }
228                         $user->employee_status = 'Active';
229                         $user->status = 'Active';
230                         $user->is_admin = 0;
231                         $user->external_auth_only = 1;
232                         $user->save();
233                         return $user->id;
234
235         }
236         /**
237          * this is called when a user logs in
238          *
239          * @param STRING $name
240          * @param STRING $password
241          * @return boolean
242          */
243         function loadUserOnLogin($name, $password) {
244
245             global $mod_strings;
246
247             // Check if the LDAP extensions are loaded
248             if(!function_exists('ldap_connect')) {
249                $error = $mod_strings['LBL_LDAP_EXTENSION_ERROR'];
250                $GLOBALS['log']->fatal($error);
251                $_SESSION['login_error'] = $error;
252                return false;
253             }
254
255                 global $login_error;
256                 $GLOBALS['ldap_config']  = new Administration();
257                 $GLOBALS['ldap_config']->retrieveSettings('ldap');
258                 $GLOBALS['log']->debug("Starting user load for ". $name);
259                 if(empty($name) || empty($password)) return false;
260                 checkAuthUserStatus();
261
262                 $user_id = $this->authenticateUser($name, $password);
263                 if(empty($user_id)) {
264                         //check if the user can login as a normal sugar user
265                         $GLOBALS['log']->fatal('SECURITY: User authentication for '.$name.' failed');
266                         return false;
267                 }
268                 $this->loadUserOnSession($user_id);
269                 return true;
270         }
271
272
273         /**
274          * Called with the error number of the last call if the error number is 0
275          * there was no error otherwise it converts the error to a string and logs it as fatal
276          *
277          * @param INT $error
278          * @return boolean
279          */
280         function loginError($error){
281                 if(empty($error)) return false;
282                 $errorstr = ldap_err2str($error);
283                 // BEGIN SUGAR INT
284                 $_SESSION['login_error'] = $errorstr;
285                 /*
286                 // END SUGAR INT
287                 $_SESSION['login_error'] = translate('ERR_INVALID_PASSWORD', 'Users');
288                 // BEGIN SUGAR INT
289                 */
290                 // END SUGAR INT
291                 $GLOBALS['log']->fatal('[LDAP ERROR]['. $error . ']'.$errorstr);
292                 return true;
293         }
294
295          /**
296     * @return string appropriate value for username when binding to directory server.
297     * @param string $user_name the value provided in login form
298     * @desc Take the login username and return either said username for AD or lookup
299      * distinguished name using anonymous credentials for OpenLDAP.
300      * Contributions by Erik Mitchell erikm@logicpd.com
301     */
302     function ldap_rdn_lookup($user_name, $password) {
303
304         // MFH BUG# 14547 - Added htmlspecialchars_decode()
305         $server = $GLOBALS['ldap_config']->settings['ldap_hostname'];
306         $base_dn = htmlspecialchars_decode($GLOBALS['ldap_config']->settings['ldap_base_dn']);
307                 if(!empty($GLOBALS['ldap_config']->settings['ldap_authentication'])){
308                 $admin_user = htmlspecialchars_decode($GLOBALS['ldap_config']->settings['ldap_admin_user']);
309                 $admin_password = htmlspecialchars_decode($GLOBALS['ldap_config']->settings['ldap_admin_password']);
310                 }else{
311                         $admin_user = '';
312                 $admin_password = '';
313                 }
314         $user_attr = $GLOBALS['ldap_config']->settings['ldap_login_attr'];
315         $bind_attr = $GLOBALS['ldap_config']->settings['ldap_bind_attr'];
316         $port = $GLOBALS['ldap_config']->settings['ldap_port'];
317                 if(!$port)
318                         $port = DEFAULT_PORT;
319         $ldapconn = ldap_connect($server, $port);
320         $error = ldap_errno($ldapconn);
321         if($this->loginError($error)){
322                 return false;
323                 }
324         ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
325         ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0); // required for AD
326         //if we are going to connect anonymously lets at least try to connect with the user connecting
327         if(empty($admin_user)){
328                         $bind = @ldap_bind($ldapconn, $user_name, $password);
329                 $error = ldap_errno($ldapconn);
330         }
331         if(empty($bind)){
332                 $bind = @ldap_bind($ldapconn, $admin_user, $admin_password);
333                 $error = ldap_errno($ldapconn);
334         }
335
336         if($this->loginError($error)){
337                 return false;
338                 }
339         if (!$bind) {
340                    $GLOBALS['log']->warn("ldapauth.ldap_rdn_lookup: Could not bind with admin user, trying to bind anonymously");
341             $bind = @ldap_bind($ldapconn);
342              $error = ldap_errno($ldapconn);
343
344                  if($this->loginError($error)){
345                         return false;
346                         }
347             if (!$bind) {
348                         $GLOBALS['log']->warn("ldapauth.ldap_rdn_lookup: Could not bind anonymously, returning username");
349                         return $user_name;
350             }
351         }
352
353                 // If we get here we were able to bind somehow
354         $search_filter = $this->getUserNameFilter($user_name);
355
356         $GLOBALS['log']->info("ldapauth.ldap_rdn_lookup: Bind succeeded, searching for $user_attr=$user_name");
357         $GLOBALS['log']->debug("ldapauth.ldap_rdn_lookup: base_dn:$base_dn , search_filter:$search_filter");
358
359         $result = @ldap_search($ldapconn, $base_dn , $search_filter, array("dn", $bind_attr));
360          $error = ldap_errno($ldapconn);
361          if($this->loginError($error)){
362                 return false;
363                 }
364         $info = ldap_get_entries($ldapconn, $result);
365          if($info['count'] == 0){
366
367                 return false;
368
369         }
370         ldap_unbind($ldapconn);
371
372         $GLOBALS['log']->info("ldapauth.ldap_rdn_lookup: Search result:\nldapauth.ldap_rdn_lookup: " . count($info));
373
374         if ($bind_attr == "dn") {
375                         $found_bind_user = $info[0]['dn'];
376         } else {
377                 $found_bind_user = $info[0][strtolower($bind_attr)][0];
378         }
379
380         $GLOBALS['log']->info("ldapauth.ldap_rdn_lookup: found_bind_user=" . $found_bind_user);
381
382         if (!empty($found_bind_user)) {
383             return $found_bind_user;
384         } elseif ($user_attr == $bind_attr) {
385             return $user_name;
386         } else {
387             return false;
388         }
389     }
390
391
392
393
394
395
396
397
398
399 }
400
401 ?>