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