3 * StatusNet, the distributed open-source microblogging tool
5 * Plugin to enable LDAP Authentication
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.
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.
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/>.
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/
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
34 require_once 'Net/LDAP2.php';
36 class LdapAuthenticationPlugin extends AuthenticationPlugin
41 public $starttls=null;
48 public $password_encoding=null;
49 public $attributes=array();
51 function onInitializePlugin(){
52 parent::onInitializePlugin();
53 if(!isset($this->host)){
54 throw new Exception("must specify a host");
56 if(!isset($this->basedn)){
57 throw new Exception("must specify a basedn");
59 if(!isset($this->attributes['nickname'])){
60 throw new Exception("must specify a nickname attribute");
62 if(!isset($this->attributes['username'])){
63 throw new Exception("must specify a username attribute");
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");
70 function onAutoload($cls)
74 case 'MemcacheSchemaCache':
75 require_once(INSTALLDIR.'/plugins/LdapAuthentication/MemcacheSchemaCache.php');
80 //---interface implementation---//
82 function checkPassword($username, $password)
84 $entry = $this->ldap_get_user($username);
88 $config = $this->ldap_get_config();
89 $config['binddn']=$entry->dn();
90 $config['bindpw']=$password;
91 if($this->ldap_get_connection($config)){
99 function autoRegister($username)
101 $entry = $this->ldap_get_user($username,$this->attributes);
103 $registration_data = array();
104 foreach($this->attributes as $sn_attribute=>$ldap_attribute){
105 $registration_data[$sn_attribute]=$entry->getValue($ldap_attribute,'single');
107 if(isset($registration_data['email']) && !empty($registration_data['email'])){
108 $registration_data['email_confirmed']=true;
110 //set the database saved password to a random string.
111 $registration_data['password']=common_good_rand(16);
112 return User::register($registration_data);
114 //user isn't in ldap, so we cannot register him
119 function changePassword($username,$oldpassword,$newpassword)
121 if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
122 //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
125 $entry = $this->ldap_get_user($username);
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);
135 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
136 if ($newCryptedPassword===false) {
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 ));
144 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
145 if( Net_LDAP2::isError($entry->upate()) ) {
157 //---utility functions---//
158 function ldap_get_config(){
160 $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
161 foreach($keys as $key){
162 $value = $this->$key;
164 $config[$key]=$value;
170 function ldap_get_connection($config = null){
171 if($config == null && isset($this->default_ldap)){
172 return $this->default_ldap;
175 //cannot use Net_LDAP2::connect() as StatusNet uses
176 //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
177 //PEAR handling can be overridden on instance objects, so we do that.
178 $ldap = new Net_LDAP2(isset($config)?$config:$this->ldap_get_config());
179 $ldap->setErrorHandling(PEAR_ERROR_RETURN);
181 if (Net_LDAP2::isError($err)) {
182 common_log(LOG_WARNING, 'Could not connect to LDAP server: '.$err->getMessage());
185 if($config == null) $this->default_ldap=$ldap;
187 $c = common_memcache();
189 $cacheObj = new MemcacheSchemaCache(
191 'cacheKey' => common_cache_key('ldap_schema:' . crc32(serialize($config)))));
192 $ldap->registerSchemaCache($cacheObj);
198 * get an LDAP entry for a user with a given username
200 * @param string $username
201 * $param array $attributes LDAP attributes to retrieve
204 function ldap_get_user($username,$attributes=array(),$ldap=null){
206 $ldap = $this->ldap_get_connection();
208 $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals', $username);
210 'attributes' => $attributes
212 $search = $ldap->search($this->basedn, $filter, $options);
214 if (PEAR::isError($search)) {
215 common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
219 $searchcount = $search->count();
220 if($searchcount == 0) {
222 }else if($searchcount == 1) {
223 $entry = $search->shiftEntry();
226 common_log(LOG_WARNING, 'Found ' . $searchcount . ' ldap user with the username: ' . $username);
232 * Code originaly from the phpLDAPadmin development team
233 * http://phpldapadmin.sourceforge.net/
235 * Hashes a password and returns the hash based on the specified enc_type.
237 * @param string $passwordClear The password to hash in clear text.
238 * @param string $encodageType Standard LDAP encryption type which must be one of
239 * crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
240 * @return string The hashed password.
244 function hashPassword( $passwordClear, $encodageType )
246 $encodageType = strtolower( $encodageType );
247 switch( $encodageType ) {
249 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2));
253 // extended des crypt. see OpenBSD crypt man page.
254 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
255 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
259 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
260 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
264 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
265 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
269 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
273 if( function_exists('sha1') ) {
274 // use php 4.3.0+ sha1 function, if it is available.
275 $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
276 } elseif( function_exists( 'mhash' ) ) {
277 $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
279 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
284 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
285 mt_srand( (double) microtime() * 1000000 );
286 $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
287 $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
289 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
294 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
295 mt_srand( (double) microtime() * 1000000 );
296 $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
297 $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
299 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
304 $cryptedPassword = '';
305 $passwordClear = "\"" . $passwordClear . "\"";
306 $len = strlen($passwordClear);
307 for ($i = 0; $i < $len; $i++) {
308 $cryptedPassword .= "{$passwordClear{$i}}\000";
313 $cryptedPassword = $passwordClear;
316 return $cryptedPassword;
320 * Code originaly from the phpLDAPadmin development team
321 * http://phpldapadmin.sourceforge.net/
323 * Used to generate a random salt for crypt-style passwords. Salt strings are used
324 * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
325 * not only the user's password but also a randomly generated string. The string is
326 * stored as the first N characters of the hash for reference of hashing algorithms later.
328 * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
329 * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
331 * @param int $length The length of the salt string to generate.
332 * @return string The generated salt string.
335 function randomSalt( $length )
337 $possible = '0123456789'.
338 'abcdefghijklmnopqrstuvwxyz'.
339 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
342 mt_srand((double)microtime() * 1000000);
344 while( strlen( $str ) < $length )
345 $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
350 function onPluginVersion(&$versions)
352 $versions[] = array('name' => 'LDAP Authentication',
353 'version' => STATUSNET_VERSION,
354 'author' => 'Craig Andrews',
355 'homepage' => 'http://status.net/wiki/Plugin:LdapAuthentication',
357 _m('The LDAP Authentication plugin allows for StatusNet to handle authentication through LDAP.'));