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