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