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