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