]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/LdapAuthentication/LdapAuthenticationPlugin.php
Merge branch 'testing' of gitorious.org:statusnet/mainline into 0.9.x
[quix0rs-gnu-social.git] / plugins / LdapAuthentication / LdapAuthenticationPlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Plugin to enable LDAP Authentication
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 require_once 'Net/LDAP2.php';
35
36 class LdapAuthenticationPlugin extends AuthenticationPlugin
37 {
38     public $host=null;
39     public $port=null;
40     public $version=null;
41     public $starttls=null;
42     public $binddn=null;
43     public $bindpw=null;
44     public $basedn=null;
45     public $options=null;
46     public $filter=null;
47     public $scope=null;
48     public $password_encoding=null;
49     public $attributes=array();
50
51     function onInitializePlugin(){
52         parent::onInitializePlugin();
53         if(!isset($this->host)){
54             throw new Exception("must specify a host");
55         }
56         if(!isset($this->basedn)){
57             throw new Exception("must specify a basedn");
58         }
59         if(!isset($this->attributes['nickname'])){
60             throw new Exception("must specify a nickname attribute");
61         }
62         if(!isset($this->attributes['username'])){
63             throw new Exception("must specify a username attribute");
64         }
65         if($this->password_changeable && (! isset($this->attributes['password']) || !isset($this->password_encoding))){
66             throw new Exception("if password_changeable is set, the password attribute and password_encoding must also be specified");
67         }
68     }
69
70     function onAutoload($cls)
71     {   
72         switch ($cls)
73         {
74          case 'MemcacheSchemaCache':
75             require_once(INSTALLDIR.'/plugins/LdapAuthentication/MemcacheSchemaCache.php');
76             return false;
77         }
78     }
79     
80     //---interface implementation---//
81
82     function checkPassword($username, $password)
83     {
84         $entry = $this->ldap_get_user($username);
85         if(!$entry){
86             return false;
87         }else{
88             $config = $this->ldap_get_config();
89             $config['binddn']=$entry->dn();
90             $config['bindpw']=$password;
91             if($this->ldap_get_connection($config)){
92                 return true;
93             }else{
94                 return false;
95             }
96         }
97     }
98
99     function autoRegister($username, $nickname)
100     {
101         if(is_null($nickname)){
102             $nickname = $username;
103         }
104         $entry = $this->ldap_get_user($username,$this->attributes);
105         if($entry){
106             $registration_data = array();
107             foreach($this->attributes as $sn_attribute=>$ldap_attribute){
108                 $registration_data[$sn_attribute]=$entry->getValue($ldap_attribute,'single');
109             }
110             if(isset($registration_data['email']) && !empty($registration_data['email'])){
111                 $registration_data['email_confirmed']=true;
112             }
113             $registration_data['nickname'] = $nickname;
114             //set the database saved password to a random string.
115             $registration_data['password']=common_good_rand(16);
116             return User::register($registration_data);
117         }else{
118             //user isn't in ldap, so we cannot register him
119             return false;
120         }
121     }
122
123     function changePassword($username,$oldpassword,$newpassword)
124     {
125         if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
126             //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
127             return false;
128         }
129         $entry = $this->ldap_get_user($username);
130         if(!$entry){
131             return false;
132         }else{
133             $config = $this->ldap_get_config();
134             $config['binddn']=$entry->dn();
135             $config['bindpw']=$oldpassword;
136             if($ldap = $this->ldap_get_connection($config)){
137                 $entry = $this->ldap_get_user($username,array(),$ldap);
138                 
139                 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
140                 if ($newCryptedPassword===false) {
141                     return false;
142                 }
143                 if($this->password_encoding=='ad') {
144                     //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
145                     $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
146                     $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
147                 }
148                 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
149                 if( Net_LDAP2::isError($entry->upate()) ) {
150                     return false;
151                 }
152                 return true;
153             }else{
154                 return false;
155             }
156         }
157
158         return false;
159     }
160
161     function suggestNicknameForUsername($username)
162     {
163         $entry = $this->ldap_get_user($username, $this->attributes);
164         if(!$entry){
165             //this really shouldn't happen
166             return $username;
167         }else{
168             $nickname = $entry->getValue($this->attributes['nickname'],'single');
169             if($nickname){
170                 return $nickname;
171             }else{
172                 return $username;
173             }
174         }
175     }
176     
177     //---utility functions---//
178     function ldap_get_config(){
179         $config = array();
180         $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
181         foreach($keys as $key){
182             $value = $this->$key;
183             if($value!==null){
184                 $config[$key]=$value;
185             }
186         }
187         return $config;
188     }
189     
190     function ldap_get_connection($config = null){
191         if($config == null && isset($this->default_ldap)){
192             return $this->default_ldap;
193         }
194         
195         //cannot use Net_LDAP2::connect() as StatusNet uses
196         //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
197         //PEAR handling can be overridden on instance objects, so we do that.
198         $ldap = new Net_LDAP2(isset($config)?$config:$this->ldap_get_config());
199         $ldap->setErrorHandling(PEAR_ERROR_RETURN);
200         $err=$ldap->bind();
201         if (Net_LDAP2::isError($err)) {
202             common_log(LOG_WARNING, 'Could not connect to LDAP server: '.$err->getMessage());
203             return false;
204         }
205         if($config == null) $this->default_ldap=$ldap;
206
207         $c = common_memcache();
208         if (!empty($c)) {
209             $cacheObj = new MemcacheSchemaCache(
210                 array('c'=>$c,
211                    'cacheKey' => common_cache_key('ldap_schema:' . crc32(serialize($config)))));
212             $ldap->registerSchemaCache($cacheObj);
213         }
214         return $ldap;
215     }
216     
217     /**
218      * get an LDAP entry for a user with a given username
219      * 
220      * @param string $username
221      * $param array $attributes LDAP attributes to retrieve
222      * @return string DN
223      */
224     function ldap_get_user($username,$attributes=array(),$ldap=null){
225         if($ldap==null) {
226             $ldap = $this->ldap_get_connection();
227         }
228         $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals',  $username);
229         $options = array(
230             'attributes' => $attributes
231         );
232         $search = $ldap->search($this->basedn, $filter, $options);
233         
234         if (PEAR::isError($search)) {
235             common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
236             return false;
237         }
238
239         $searchcount = $search->count();
240         if($searchcount == 0) {
241             return false;
242         }else if($searchcount == 1) {
243             $entry = $search->shiftEntry();
244             return $entry;
245         }else{
246             common_log(LOG_WARNING, 'Found ' . $searchcount . ' 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
264     function hashPassword( $passwordClear, $encodageType ) 
265     {
266         $encodageType = strtolower( $encodageType );
267         switch( $encodageType ) {
268             case 'crypt': 
269                 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2)); 
270                 break;
271                 
272             case 'ext_des':
273                 // extended des crypt. see OpenBSD crypt man page.
274                 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
275                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
276                 break;
277
278             case 'md5crypt':
279                 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
280                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
281                 break;
282
283             case 'blowfish':
284                 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
285                 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
286                 break;
287
288             case 'md5':
289                 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
290                 break;
291
292             case 'sha':
293                 if( function_exists('sha1') ) {
294                     // use php 4.3.0+ sha1 function, if it is available.
295                     $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
296                 } elseif( function_exists( 'mhash' ) ) {
297                     $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
298                 } else {
299                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
300                 }
301                 break;
302
303             case 'ssha':
304                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
305                     mt_srand( (double) microtime() * 1000000 );
306                     $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
307                     $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
308                 } else {
309                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
310                 }
311                 break;
312
313             case 'smd5':
314                 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
315                     mt_srand( (double) microtime() * 1000000 );
316                     $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
317                     $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
318                 } else {
319                     return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
320                 }
321                 break;
322
323             case 'ad':
324                 $cryptedPassword = '';
325                 $passwordClear = "\"" . $passwordClear . "\"";
326                 $len = strlen($passwordClear);
327                 for ($i = 0; $i < $len; $i++) {
328                     $cryptedPassword .= "{$passwordClear{$i}}\000";
329                 }
330
331             case 'clear':
332             default:
333                 $cryptedPassword = $passwordClear;
334         }
335
336         return $cryptedPassword;
337     }
338
339     /**
340      * Code originaly from the phpLDAPadmin development team
341      * http://phpldapadmin.sourceforge.net/
342      *
343      * Used to generate a random salt for crypt-style passwords. Salt strings are used
344      * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
345      * not only the user's password but also a randomly generated string. The string is
346      * stored as the first N characters of the hash for reference of hashing algorithms later.
347      *
348      * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
349      * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
350      *
351      * @param int $length The length of the salt string to generate.
352      * @return string The generated salt string.
353      */
354      
355     function randomSalt( $length ) 
356     {
357         $possible = '0123456789'.
358             'abcdefghijklmnopqrstuvwxyz'.
359             'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
360             './';
361         $str = "";
362         mt_srand((double)microtime() * 1000000);
363
364         while( strlen( $str ) < $length )
365             $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
366
367         return $str;
368     }
369
370     function onPluginVersion(&$versions)
371     {
372         $versions[] = array('name' => 'LDAP Authentication',
373                             'version' => STATUSNET_VERSION,
374                             'author' => 'Craig Andrews',
375                             'homepage' => 'http://status.net/wiki/Plugin:LdapAuthentication',
376                             'rawdescription' =>
377                             _m('The LDAP Authentication plugin allows for StatusNet to handle authentication through LDAP.'));
378         return true;
379     }
380 }