]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LdapCommon/LdapCommon.php
Fix some regressions caused by refactor of LDAP plugin
[quix0rs-gnu-social.git] / plugins / LdapCommon / LdapCommon.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Utility class of LDAP functions
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
24  * @author    Craig Andrews <candrews@integralblue.com>
25  * @copyright 2009 Craig Andrews http://candrews.integralblue.com
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 class LdapCommon
35 {
36     protected static $ldap_connections = array();
37     public $host=null;
38     public $port=null;
39     public $version=null;
40     public $starttls=null;
41     public $binddn=null;
42     public $bindpw=null;
43     public $basedn=null;
44     public $options=null;
45     public $filter=null;
46     public $scope=null;
47     public $uniqueMember_attribute = null;
48     public $attributes=array();
49     public $password_encoding=null;
50
51     public function __construct($config)
52     {
53         Event::addHandler('Autoload',array($this,'onAutoload'));
54         foreach($config as $key=>$value) {
55             $this->$key = $value;
56         }
57         $this->ldap_config = $this->get_ldap_config();
58
59         if(!isset($this->host)){
60             throw new Exception("must specify a host");
61         }
62         if(!isset($this->basedn)){
63             throw new Exception("must specify a basedn");
64         }
65         if(!isset($this->attributes['username'])){
66             throw new Exception("username attribute must be set.");
67         }
68     }
69
70     function onAutoload($cls)
71     {
72         switch ($cls)
73         {
74          case 'MemcacheSchemaCache':
75             require_once(INSTALLDIR.'/plugins/LdapCommon/MemcacheSchemaCache.php');
76             return false;
77          case 'Net_LDAP2':
78             require_once 'Net/LDAP2.php';
79             return false;
80          case 'Net_LDAP2_Filter':
81             require_once 'Net/LDAP2/Filter.php';
82             return false;
83          case 'Net_LDAP2_Filter':
84             require_once 'Net/LDAP2/Filter.php';
85             return false;
86          case 'Net_LDAP2_Entry':
87             require_once 'Net/LDAP2/Entry.php';
88             return false;
89         }
90     }
91
92     function get_ldap_config(){
93         $config = array();
94         $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
95         foreach($keys as $key){
96             $value = $this->$key;
97             if($value!==null){
98                 $config[$key]=$value;
99             }
100         }
101         return $config;
102     }
103
104     function get_ldap_connection($config = null){
105         if($config == null) {
106             $config = $this->ldap_config;
107         }
108         $config_id = crc32(serialize($config));
109         if(array_key_exists($config_id,self::$ldap_connections)) {
110             $ldap = self::$ldap_connections[$config_id];
111         } else {
112             //cannot use Net_LDAP2::connect() as StatusNet uses
113             //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
114             //PEAR handling can be overridden on instance objects, so we do that.
115             $ldap = new Net_LDAP2($config);
116             $ldap->setErrorHandling(PEAR_ERROR_RETURN);
117             $err=$ldap->bind();
118             if (Net_LDAP2::isError($err)) {
119                 // if we were called with a config, assume caller will handle
120                 // incorrect username/password (LDAP_INVALID_CREDENTIALS)
121                 if (isset($config) && $err->getCode() == 0x31) {
122                     throw new LdapInvalidCredentialsException('Could not connect to LDAP server: '.$err->getMessage());
123                 }
124                 throw new Exception('Could not connect to LDAP server: '.$err->getMessage());
125             }
126             $c = common_memcache();
127             if (!empty($c)) {
128                 $cacheObj = new MemcacheSchemaCache(
129                     array('c'=>$c,
130                        'cacheKey' => common_cache_key('ldap_schema:' . $config_id)));
131                 $ldap->registerSchemaCache($cacheObj);
132             }
133             self::$ldap_connections[$config_id] = $ldap;
134         }
135         return $ldap;
136     }
137
138     function checkPassword($username, $password)
139     {
140         $entry = $this->get_user($username);
141         if(!$entry){
142             return false;
143         }else{
144             $config = $this->get_ldap_config();
145             $config['binddn']=$entry->dn();
146             $config['bindpw']=$password;
147             try {
148                 $this->get_ldap_connection($config);
149             } catch (LdapInvalidCredentialsException $e) {
150                 return false;
151             }
152             return true;
153         }
154     }
155
156     function changePassword($username,$oldpassword,$newpassword)
157     {
158         if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
159             //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
160             return false;
161         }
162         $entry = $this->get_user($username);
163         if(!$entry){
164             return false;
165         }else{
166             $config = $this->get_ldap_config();
167             $config['binddn']=$entry->dn();
168             $config['bindpw']=$oldpassword;
169             try {
170                 $ldap = $this->get_ldap_connection($config);
171
172                 $entry = $this->get_user($username,array(),$ldap);
173                 
174                 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
175                 if ($newCryptedPassword===false) {
176                     return false;
177                 }
178                 if($this->password_encoding=='ad') {
179                     //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
180                     $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
181                     $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
182                 }
183                 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
184                 if( Net_LDAP2::isError($entry->upate()) ) {
185                     return false;
186                 }
187                 return true;
188             } catch (LdapInvalidCredentialsException $e) {
189                 return false;
190             }
191         }
192
193         return false;
194     }
195
196     function is_dn_member_of_group($userDn, $groupDn)
197     {
198         $ldap = $this->get_ldap_connection();
199         $link = $ldap->getLink();
200         $r = @ldap_compare($link, $groupDn, $this->uniqueMember_attribute, $userDn);
201         if ($r === true){
202             return true;
203         }else if($r === false){
204             return false;
205         }else{
206             common_log(LOG_ERR, "LDAP error determining if userDn=$userDn is a member of groupDn=$groupDn using uniqueMember_attribute=$this->uniqueMember_attribute error: ".ldap_error($link));
207             return false;
208         }
209     }
210
211     /**
212      * get an LDAP entry for a user with a given username
213      *
214      * @param string $username
215      * $param array $attributes LDAP attributes to retrieve
216      * @return string DN
217      */
218     function get_user($username,$attributes=array()){
219         $ldap = $this->get_ldap_connection();
220         $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals',  $username);
221         $options = array(
222             'attributes' => $attributes
223         );
224         $search = $ldap->search(null,$filter,$options);
225
226         if (PEAR::isError($search)) {
227             common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
228             return false;
229         }
230
231         if($search->count()==0){
232             return false;
233         }else if($search->count()==1){
234             $entry = $search->shiftEntry();
235             return $entry;
236         }else{
237             common_log(LOG_WARNING, 'Found ' . $search->count() . ' ldap user with the username: ' . $username);
238             return false;
239         }
240     }
241
242     /**
243      * Code originaly from the phpLDAPadmin development team
244      * http://phpldapadmin.sourceforge.net/
245      *
246      * Hashes a password and returns the hash based on the specified enc_type.
247      *
248      * @param string $passwordClear The password to hash in clear text.
249      * @param string $encodageType Standard LDAP encryption type which must be one of
250      *        crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
251      * @return string The hashed password.
252      *
253      */
254
255     function hashPassword( $passwordClear, $encodageType ) 
256     {
257         $encodageType = strtolower( $encodageType );
258         switch( $encodageType ) {
259             case 'crypt': 
260                 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2)); 
261                 break;
262                 
263             case 'ext_des':
264                 // extended des crypt. see OpenBSD crypt man page.
265                 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
266                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
267                 break;
268
269             case 'md5crypt':
270                 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
271                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
272                 break;
273
274             case 'blowfish':
275                 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
276                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
277                 break;
278
279             case 'md5':
280                 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
281                 break;
282
283             case 'sha':
284                 if( function_exists('sha1') ) {
285                     // use php 4.3.0+ sha1 function, if it is available.
286                     $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
287                 } elseif( function_exists( 'mhash' ) ) {
288                     $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
289                 } else {
290                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
291                 }
292                 break;
293
294             case 'ssha':
295                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
296                     mt_srand( (double) microtime() * 1000000 );
297                     $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
298                     $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
299                 } else {
300                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
301                 }
302                 break;
303
304             case 'smd5':
305                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
306                     mt_srand( (double) microtime() * 1000000 );
307                     $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
308                     $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
309                 } else {
310                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
311                 }
312                 break;
313
314             case 'ad':
315                 $cryptedPassword = '';
316                 $passwordClear = "\"" . $passwordClear . "\"";
317                 $len = strlen($passwordClear);
318                 for ($i = 0; $i < $len; $i++) {
319                     $cryptedPassword .= "{$passwordClear{$i}}\000";
320                 }
321
322             case 'clear':
323             default:
324                 $cryptedPassword = $passwordClear;
325         }
326
327         return $cryptedPassword;
328     }
329
330     /**
331      * Code originaly from the phpLDAPadmin development team
332      * http://phpldapadmin.sourceforge.net/
333      *
334      * Used to generate a random salt for crypt-style passwords. Salt strings are used
335      * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
336      * not only the user's password but also a randomly generated string. The string is
337      * stored as the first N characters of the hash for reference of hashing algorithms later.
338      *
339      * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
340      * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
341      *
342      * @param int $length The length of the salt string to generate.
343      * @return string The generated salt string.
344      */
345      
346     function randomSalt( $length ) 
347     {
348         $possible = '0123456789'.
349             'abcdefghijklmnopqrstuvwxyz'.
350             'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
351             './';
352         $str = "";
353         mt_srand((double)microtime() * 1000000);
354
355         while( strlen( $str ) < $length )
356             $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
357
358         return $str;
359     }
360
361 }
362
363 class LdapInvalidCredentialsException extends Exception
364 {
365
366 }