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