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 function onEndShowPageNotice($action)
82 $name = $action->trimmed('action');
88 if($this->autoregistration) {
89 $instr = 'Have an LDAP account? Use your standard username and password.';
93 $instr = 'Have an LDAP account? Use your standard username and password.';
100 $output = common_markup_to_html($instr);
101 $action->raw($output);
106 //---interface implementation---//
108 function checkPassword($username, $password)
110 $entry = $this->ldap_get_user($username);
114 $config = $this->ldap_get_config();
115 $config['binddn']=$entry->dn();
116 $config['bindpw']=$password;
117 if($this->ldap_get_connection($config)){
125 function autoRegister($username, $nickname)
127 if(is_null($nickname)){
128 $nickname = $username;
130 $entry = $this->ldap_get_user($username,$this->attributes);
132 $registration_data = array();
133 foreach($this->attributes as $sn_attribute=>$ldap_attribute){
134 $registration_data[$sn_attribute]=$entry->getValue($ldap_attribute,'single');
136 if(isset($registration_data['email']) && !empty($registration_data['email'])){
137 $registration_data['email_confirmed']=true;
139 $registration_data['nickname'] = $nickname;
140 //set the database saved password to a random string.
141 $registration_data['password']=common_good_rand(16);
142 return User::register($registration_data);
144 //user isn't in ldap, so we cannot register him
149 function changePassword($username,$oldpassword,$newpassword)
151 if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
152 //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
155 $entry = $this->ldap_get_user($username);
159 $config = $this->ldap_get_config();
160 $config['binddn']=$entry->dn();
161 $config['bindpw']=$oldpassword;
162 if($ldap = $this->ldap_get_connection($config)){
163 $entry = $this->ldap_get_user($username,array(),$ldap);
165 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
166 if ($newCryptedPassword===false) {
169 if($this->password_encoding=='ad') {
170 //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
171 $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
172 $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
174 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
175 if( Net_LDAP2::isError($entry->upate()) ) {
187 function suggestNicknameForUsername($username)
189 $entry = $this->ldap_get_user($username, $this->attributes);
191 //this really shouldn't happen
192 $nickname = $username;
194 $nickname = $entry->getValue($this->attributes['nickname'],'single');
196 $nickname = $username;
199 return common_nicknamize($nickname);
202 //---utility functions---//
203 function ldap_get_config(){
205 $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
206 foreach($keys as $key){
207 $value = $this->$key;
209 $config[$key]=$value;
215 function ldap_get_connection($config = null){
216 if($config == null && isset($this->default_ldap)){
217 return $this->default_ldap;
220 //cannot use Net_LDAP2::connect() as StatusNet uses
221 //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
222 //PEAR handling can be overridden on instance objects, so we do that.
223 $ldap = new Net_LDAP2(isset($config)?$config:$this->ldap_get_config());
224 $ldap->setErrorHandling(PEAR_ERROR_RETURN);
226 if (Net_LDAP2::isError($err)) {
227 // if we were called with a config, assume caller will handle
228 // incorrect username/password (LDAP_INVALID_CREDENTIALS)
229 if (isset($config) && $err->getCode() == 0x31) {
232 throw new Exception('Could not connect to LDAP server: '.$err->getMessage());
234 if($config == null) $this->default_ldap=$ldap;
236 $c = common_memcache();
238 $cacheObj = new MemcacheSchemaCache(
240 'cacheKey' => common_cache_key('ldap_schema:' . crc32(serialize($config)))));
241 $ldap->registerSchemaCache($cacheObj);
247 * get an LDAP entry for a user with a given username
249 * @param string $username
250 * $param array $attributes LDAP attributes to retrieve
253 function ldap_get_user($username,$attributes=array(),$ldap=null){
255 $ldap = $this->ldap_get_connection();
257 $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals', $username);
259 'attributes' => $attributes
261 $search = $ldap->search($this->basedn, $filter, $options);
263 if (PEAR::isError($search)) {
264 common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
268 $searchcount = $search->count();
269 if($searchcount == 0) {
271 }else if($searchcount == 1) {
272 $entry = $search->shiftEntry();
275 common_log(LOG_WARNING, 'Found ' . $searchcount . ' ldap user with the username: ' . $username);
281 * Code originaly from the phpLDAPadmin development team
282 * http://phpldapadmin.sourceforge.net/
284 * Hashes a password and returns the hash based on the specified enc_type.
286 * @param string $passwordClear The password to hash in clear text.
287 * @param string $encodageType Standard LDAP encryption type which must be one of
288 * crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
289 * @return string The hashed password.
293 function hashPassword( $passwordClear, $encodageType )
295 $encodageType = strtolower( $encodageType );
296 switch( $encodageType ) {
298 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2));
302 // extended des crypt. see OpenBSD crypt man page.
303 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
304 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
308 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
309 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
313 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
314 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
318 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
322 if( function_exists('sha1') ) {
323 // use php 4.3.0+ sha1 function, if it is available.
324 $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
325 } elseif( function_exists( 'mhash' ) ) {
326 $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
328 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
333 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
334 mt_srand( (double) microtime() * 1000000 );
335 $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
336 $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
338 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
343 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
344 mt_srand( (double) microtime() * 1000000 );
345 $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
346 $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
348 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
353 $cryptedPassword = '';
354 $passwordClear = "\"" . $passwordClear . "\"";
355 $len = strlen($passwordClear);
356 for ($i = 0; $i < $len; $i++) {
357 $cryptedPassword .= "{$passwordClear{$i}}\000";
362 $cryptedPassword = $passwordClear;
365 return $cryptedPassword;
369 * Code originaly from the phpLDAPadmin development team
370 * http://phpldapadmin.sourceforge.net/
372 * Used to generate a random salt for crypt-style passwords. Salt strings are used
373 * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
374 * not only the user's password but also a randomly generated string. The string is
375 * stored as the first N characters of the hash for reference of hashing algorithms later.
377 * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
378 * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
380 * @param int $length The length of the salt string to generate.
381 * @return string The generated salt string.
384 function randomSalt( $length )
386 $possible = '0123456789'.
387 'abcdefghijklmnopqrstuvwxyz'.
388 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
391 mt_srand((double)microtime() * 1000000);
393 while( strlen( $str ) < $length )
394 $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
399 function onPluginVersion(&$versions)
401 $versions[] = array('name' => 'LDAP Authentication',
402 'version' => STATUSNET_VERSION,
403 'author' => 'Craig Andrews',
404 'homepage' => 'http://status.net/wiki/Plugin:LdapAuthentication',
406 _m('The LDAP Authentication plugin allows for StatusNet to handle authentication through LDAP.'));