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