]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LdapCommon/LdapCommon.php
Refactor common parts of LdapAuthorization and LdapAuthentication plugins into a...
[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         }
81     }
82
83     function get_ldap_config(){
84         $config = array();
85         $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
86         foreach($keys as $key){
87             $value = $this->$key;
88             if($value!==null){
89                 $config[$key]=$value;
90             }
91         }
92         return $config;
93     }
94
95     function get_ldap_connection($config = null){
96         if($config == null) {
97             $config = $this->ldap_config;
98         }
99         $config_id = crc32(serialize($config));
100         $ldap = self::$ldap_connections[$config_id];
101         if(! isset($ldap)) {
102             //cannot use Net_LDAP2::connect() as StatusNet uses
103             //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
104             //PEAR handling can be overridden on instance objects, so we do that.
105             $ldap = new Net_LDAP2($config);
106             $ldap->setErrorHandling(PEAR_ERROR_RETURN);
107             $err=$ldap->bind();
108             if (Net_LDAP2::isError($err)) {
109                 // if we were called with a config, assume caller will handle
110                 // incorrect username/password (LDAP_INVALID_CREDENTIALS)
111                 if (isset($config) && $err->getCode() == 0x31) {
112                     throw new LdapInvalidCredentialsException('Could not connect to LDAP server: '.$err->getMessage());
113                 }
114                 throw new Exception('Could not connect to LDAP server: '.$err->getMessage());
115             }
116             $c = common_memcache();
117             if (!empty($c)) {
118                 $cacheObj = new MemcacheSchemaCache(
119                     array('c'=>$c,
120                        'cacheKey' => common_cache_key('ldap_schema:' . $config_id)));
121                 $ldap->registerSchemaCache($cacheObj);
122             }
123             self::$ldap_connections[$config_id] = $ldap;
124         }
125         return $ldap;
126     }
127
128     function checkPassword($username, $password)
129     {
130         $entry = $this->get_user($username);
131         if(!$entry){
132             return false;
133         }else{
134             $config = $this->get_ldap_config();
135             $config['binddn']=$entry->dn();
136             $config['bindpw']=$password;
137             try {
138                 $this->get_ldap_connection($config);
139             } catch (LdapInvalidCredentialsException $e) {
140                 return false;
141             }
142             return true;
143         }
144     }
145
146     function changePassword($username,$oldpassword,$newpassword)
147     {
148         if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
149             //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
150             return false;
151         }
152         $entry = $this->get_user($username);
153         if(!$entry){
154             return false;
155         }else{
156             $config = $this->get_ldap_config();
157             $config['binddn']=$entry->dn();
158             $config['bindpw']=$oldpassword;
159             try {
160                 $ldap = $this->get_ldap_connection($config);
161
162                 $entry = $this->get_user($username,array(),$ldap);
163                 
164                 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
165                 if ($newCryptedPassword===false) {
166                     return false;
167                 }
168                 if($this->password_encoding=='ad') {
169                     //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
170                     $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
171                     $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
172                 }
173                 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
174                 if( Net_LDAP2::isError($entry->upate()) ) {
175                     return false;
176                 }
177                 return true;
178             } catch (LdapInvalidCredentialsException $e) {
179                 return false;
180             }
181         }
182
183         return false;
184     }
185
186     function is_dn_member_of_group($userDn, $groupDn)
187     {
188         $ldap = $this->get_ldap_connection();
189         $link = $ldap->getLink();
190         $r = @ldap_compare($link, $groupDn, $this->uniqueMember_attribute, $userDn);
191         if ($r === true){
192             return true;
193         }else if($r === false){
194             return false;
195         }else{
196             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));
197             return false;
198         }
199     }
200     
201     /**
202      * get an LDAP entry for a user with a given username
203      * 
204      * @param string $username
205      * $param array $attributes LDAP attributes to retrieve
206      * @return string DN
207      */
208     function get_user($username,$attributes=array()){
209         $ldap = $this->get_ldap_connection();
210         $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals',  $username);
211         $options = array(
212             'attributes' => $attributes
213         );
214         $search = $ldap->search(null,$filter,$options);
215         
216         if (PEAR::isError($search)) {
217             common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
218             return false;
219         }
220
221         if($search->count()==0){
222             return false;
223         }else if($search->count()==1){
224             $entry = $search->shiftEntry();
225             return $entry;
226         }else{
227             common_log(LOG_WARNING, 'Found ' . $search->count() . ' ldap user with the username: ' . $username);
228             return false;
229         }
230     }
231
232     /**
233      * Code originaly from the phpLDAPadmin development team
234      * http://phpldapadmin.sourceforge.net/
235      *
236      * Hashes a password and returns the hash based on the specified enc_type.
237      *
238      * @param string $passwordClear The password to hash in clear text.
239      * @param string $encodageType Standard LDAP encryption type which must be one of
240      *        crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
241      * @return string The hashed password.
242      *
243      */
244
245     function hashPassword( $passwordClear, $encodageType ) 
246     {
247         $encodageType = strtolower( $encodageType );
248         switch( $encodageType ) {
249             case 'crypt': 
250                 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2)); 
251                 break;
252                 
253             case 'ext_des':
254                 // extended des crypt. see OpenBSD crypt man page.
255                 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
256                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
257                 break;
258
259             case 'md5crypt':
260                 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
261                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
262                 break;
263
264             case 'blowfish':
265                 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
266                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
267                 break;
268
269             case 'md5':
270                 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
271                 break;
272
273             case 'sha':
274                 if( function_exists('sha1') ) {
275                     // use php 4.3.0+ sha1 function, if it is available.
276                     $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
277                 } elseif( function_exists( 'mhash' ) ) {
278                     $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
279                 } else {
280                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
281                 }
282                 break;
283
284             case 'ssha':
285                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
286                     mt_srand( (double) microtime() * 1000000 );
287                     $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
288                     $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
289                 } else {
290                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
291                 }
292                 break;
293
294             case 'smd5':
295                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
296                     mt_srand( (double) microtime() * 1000000 );
297                     $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
298                     $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $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 'ad':
305                 $cryptedPassword = '';
306                 $passwordClear = "\"" . $passwordClear . "\"";
307                 $len = strlen($passwordClear);
308                 for ($i = 0; $i < $len; $i++) {
309                     $cryptedPassword .= "{$passwordClear{$i}}\000";
310                 }
311
312             case 'clear':
313             default:
314                 $cryptedPassword = $passwordClear;
315         }
316
317         return $cryptedPassword;
318     }
319
320     /**
321      * Code originaly from the phpLDAPadmin development team
322      * http://phpldapadmin.sourceforge.net/
323      *
324      * Used to generate a random salt for crypt-style passwords. Salt strings are used
325      * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
326      * not only the user's password but also a randomly generated string. The string is
327      * stored as the first N characters of the hash for reference of hashing algorithms later.
328      *
329      * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
330      * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
331      *
332      * @param int $length The length of the salt string to generate.
333      * @return string The generated salt string.
334      */
335      
336     function randomSalt( $length ) 
337     {
338         $possible = '0123456789'.
339             'abcdefghijklmnopqrstuvwxyz'.
340             'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
341             './';
342         $str = "";
343         mt_srand((double)microtime() * 1000000);
344
345         while( strlen( $str ) < $length )
346             $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
347
348         return $str;
349     }
350
351 }
352
353 class LdapInvalidCredentialsException extends Exception
354 {
355
356 }