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