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