3 * StatusNet, the distributed open-source microblogging tool
5 * Plugin to enable LDAP Authentication and Authorization
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 INSTALLDIR.'/plugins/Authentication/AuthenticationPlugin.php';
35 require_once 'Net/LDAP2.php';
37 class LdapAuthenticationPlugin extends AuthenticationPlugin
42 public $starttls=null;
49 public $password_encoding=null;
50 public $attributes=array();
52 function onInitializePlugin(){
53 parent::onInitializePlugin();
54 if(!isset($this->host)){
55 throw new Exception("must specify a host");
57 if(!isset($this->basedn)){
58 throw new Exception("must specify a basedn");
60 if(!isset($this->attributes['nickname'])){
61 throw new Exception("must specify a nickname attribute");
63 if(!isset($this->attributes['username'])){
64 throw new Exception("must specify a username attribute");
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");
70 //---interface implementation---//
72 function checkPassword($username, $password)
74 $entry = $this->ldap_get_user($username);
78 $config = $this->ldap_get_config();
79 $config['binddn']=$entry->dn();
80 $config['bindpw']=$password;
81 if($this->ldap_get_connection($config)){
89 function autoRegister($username)
91 $entry = $this->ldap_get_user($username,$this->attributes);
93 $registration_data = array();
94 foreach($this->attributes as $sn_attribute=>$ldap_attribute){
95 $registration_data[$sn_attribute]=$entry->getValue($ldap_attribute,'single');
97 if(isset($registration_data['email']) && !empty($registration_data['email'])){
98 $registration_data['email_confirmed']=true;
100 //set the database saved password to a random string.
101 $registration_data['password']=common_good_rand(16);
102 return User::register($registration_data);
104 //user isn't in ldap, so we cannot register him
109 function changePassword($username,$oldpassword,$newpassword)
111 if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
112 //throw new Exception(_('Sorry, changing LDAP passwords is not supported at this time'));
115 $entry = $this->ldap_get_user($username);
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);
125 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
126 if ($newCryptedPassword===false) {
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 ));
134 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
135 if( Net_LDAP2::isError($entry->upate()) ) {
147 //---utility functions---//
148 function ldap_get_config(){
150 $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
151 foreach($keys as $key){
152 $value = $this->$key;
154 $config[$key]=$value;
160 function ldap_get_connection($config = null){
162 $config = $this->ldap_get_config();
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);
171 if (Net_LDAP2::isError($err)) {
172 common_log(LOG_WARNING, 'Could not connect to LDAP server: '.$err->getMessage());
179 * get an LDAP entry for a user with a given username
181 * @param string $username
182 * $param array $attributes LDAP attributes to retrieve
185 function ldap_get_user($username,$attributes=array(),$ldap=null){
187 $ldap = $this->ldap_get_connection();
189 $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals', $username);
192 'attributes' => $attributes
194 $search = $ldap->search(null,$filter,$options);
196 if (PEAR::isError($search)) {
197 common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
201 if($search->count()==0){
203 }else if($search->count()==1){
204 $entry = $search->shiftEntry();
207 common_log(LOG_WARNING, 'Found ' . $search->count() . ' ldap user with the username: ' . $username);
213 * Code originaly from the phpLDAPadmin development team
214 * http://phpldapadmin.sourceforge.net/
216 * Hashes a password and returns the hash based on the specified enc_type.
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.
225 function hashPassword( $passwordClear, $encodageType )
227 $encodageType = strtolower( $encodageType );
228 switch( $encodageType ) {
230 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2));
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) );
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) );
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
250 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
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) );
260 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
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 );
270 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
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 );
280 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
285 $cryptedPassword = '';
286 $passwordClear = "\"" . $passwordClear . "\"";
287 $len = strlen($passwordClear);
288 for ($i = 0; $i < $len; $i++) {
289 $cryptedPassword .= "{$passwordClear{$i}}\000";
294 $cryptedPassword = $passwordClear;
297 return $cryptedPassword;
301 * Code originaly from the phpLDAPadmin development team
302 * http://phpldapadmin.sourceforge.net/
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.
309 * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
310 * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
312 * @param int $length The length of the salt string to generate.
313 * @return string The generated salt string.
316 function randomSalt( $length )
318 $possible = '0123456789'.
319 'abcdefghijklmnopqrstuvwxyz'.
320 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
323 mt_srand((double)microtime() * 1000000);
325 while( strlen( $str ) < $length )
326 $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );