]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LdapCommon/LdapCommon.php
Merge branch '0.9.x' into tinymce
[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("must specify a host");
64         }
65         if(!isset($this->basedn)){
66             throw new Exception("must specify a basedn");
67         }
68         if(!isset($this->attributes['username'])){
69             throw new Exception("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 = common_memcache();
130             if (!empty($c)) {
131                 $cacheObj = new MemcacheSchemaCache(
132                     array('c'=>$c,
133                        'cacheKey' => common_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             $config = $this->get_ldap_config();
148             $config['binddn']=$entry->dn();
149             $config['bindpw']=$password;
150             try {
151                 $this->get_ldap_connection($config);
152             } catch (LdapInvalidCredentialsException $e) {
153                 return false;
154             }
155             return true;
156         }
157     }
158
159     function changePassword($username,$oldpassword,$newpassword)
160     {
161         if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
162             //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
163             return false;
164         }
165         $entry = $this->get_user($username);
166         if(!$entry){
167             return false;
168         }else{
169             $config = $this->get_ldap_config();
170             $config['binddn']=$entry->dn();
171             $config['bindpw']=$oldpassword;
172             try {
173                 $ldap = $this->get_ldap_connection($config);
174
175                 $entry = $this->get_user($username,array(),$ldap);
176                 
177                 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
178                 if ($newCryptedPassword===false) {
179                     return false;
180                 }
181                 if($this->password_encoding=='ad') {
182                     //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
183                     $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
184                     $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
185                 }
186                 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
187                 if( Net_LDAP2::isError($entry->upate()) ) {
188                     return false;
189                 }
190                 return true;
191             } catch (LdapInvalidCredentialsException $e) {
192                 return false;
193             }
194         }
195
196         return false;
197     }
198
199     function is_dn_member_of_group($userDn, $groupDn)
200     {
201         $ldap = $this->get_ldap_connection();
202         $link = $ldap->getLink();
203         $r = @ldap_compare($link, $groupDn, $this->uniqueMember_attribute, $userDn);
204         if ($r === true){
205             return true;
206         }else if($r === false){
207             return false;
208         }else{
209             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));
210             return false;
211         }
212     }
213
214     /**
215      * get an LDAP entry for a user with a given username
216      *
217      * @param string $username
218      * $param array $attributes LDAP attributes to retrieve
219      * @return string DN
220      */
221     function get_user($username,$attributes=array()){
222         $ldap = $this->get_ldap_connection();
223         $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals',  $username);
224         $options = array(
225             'attributes' => $attributes
226         );
227         $search = $ldap->search(null,$filter,$options);
228
229         if (PEAR::isError($search)) {
230             common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
231             return false;
232         }
233
234         if($search->count()==0){
235             return false;
236         }else if($search->count()==1){
237             $entry = $search->shiftEntry();
238             return $entry;
239         }else{
240             common_log(LOG_WARNING, 'Found ' . $search->count() . ' ldap user with the username: ' . $username);
241             return false;
242         }
243     }
244
245     /**
246      * Code originaly from the phpLDAPadmin development team
247      * http://phpldapadmin.sourceforge.net/
248      *
249      * Hashes a password and returns the hash based on the specified enc_type.
250      *
251      * @param string $passwordClear The password to hash in clear text.
252      * @param string $encodageType Standard LDAP encryption type which must be one of
253      *        crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
254      * @return string The hashed password.
255      *
256      */
257
258     function hashPassword( $passwordClear, $encodageType ) 
259     {
260         $encodageType = strtolower( $encodageType );
261         switch( $encodageType ) {
262             case 'crypt': 
263                 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2)); 
264                 break;
265                 
266             case 'ext_des':
267                 // extended des crypt. see OpenBSD crypt man page.
268                 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
269                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
270                 break;
271
272             case 'md5crypt':
273                 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
274                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
275                 break;
276
277             case 'blowfish':
278                 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
279                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
280                 break;
281
282             case 'md5':
283                 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
284                 break;
285
286             case 'sha':
287                 if( function_exists('sha1') ) {
288                     // use php 4.3.0+ sha1 function, if it is available.
289                     $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
290                 } elseif( function_exists( 'mhash' ) ) {
291                     $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
292                 } else {
293                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
294                 }
295                 break;
296
297             case 'ssha':
298                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
299                     mt_srand( (double) microtime() * 1000000 );
300                     $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
301                     $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
302                 } else {
303                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
304                 }
305                 break;
306
307             case 'smd5':
308                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
309                     mt_srand( (double) microtime() * 1000000 );
310                     $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
311                     $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
312                 } else {
313                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
314                 }
315                 break;
316
317             case 'ad':
318                 $cryptedPassword = '';
319                 $passwordClear = "\"" . $passwordClear . "\"";
320                 $len = strlen($passwordClear);
321                 for ($i = 0; $i < $len; $i++) {
322                     $cryptedPassword .= "{$passwordClear{$i}}\000";
323                 }
324
325             case 'clear':
326             default:
327                 $cryptedPassword = $passwordClear;
328         }
329
330         return $cryptedPassword;
331     }
332
333     /**
334      * Code originaly from the phpLDAPadmin development team
335      * http://phpldapadmin.sourceforge.net/
336      *
337      * Used to generate a random salt for crypt-style passwords. Salt strings are used
338      * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
339      * not only the user's password but also a randomly generated string. The string is
340      * stored as the first N characters of the hash for reference of hashing algorithms later.
341      *
342      * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
343      * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
344      *
345      * @param int $length The length of the salt string to generate.
346      * @return string The generated salt string.
347      */
348      
349     function randomSalt( $length ) 
350     {
351         $possible = '0123456789'.
352             'abcdefghijklmnopqrstuvwxyz'.
353             'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
354             './';
355         $str = "";
356         mt_srand((double)microtime() * 1000000);
357
358         while( strlen( $str ) < $length )
359             $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
360
361         return $str;
362     }
363
364 }
365
366 class LdapInvalidCredentialsException extends Exception
367 {
368
369 }