3 * StatusNet, the distributed open-source microblogging tool
5 * Utility class of LDAP functions
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 Free Software Foundation, Inc http://www.fsf.org
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 // We bundle the Net/LDAP2 library...
35 set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib');
39 protected static $ldap_connections = array();
43 public $starttls=null;
50 public $uniqueMember_attribute = null;
51 public $attributes=array();
52 public $password_encoding=null;
54 public function __construct($config)
56 Event::addHandler('Autoload',array($this,'onAutoload'));
57 foreach($config as $key=>$value) {
60 $this->ldap_config = $this->get_ldap_config();
62 if(!isset($this->host)){
63 // TRANS: Exception thrown when initialising the LDAP Common plugin fails because of an incorrect configuration.
64 throw new Exception(_m('A host must be specified.'));
66 if(!isset($this->basedn)){
67 // TRANS: Exception thrown when initialising the LDAP Common plugin fails because of an incorrect configuration.
68 throw new Exception(_m('"basedn" must be specified.'));
70 if(!isset($this->attributes['username'])){
71 // TRANS: Exception thrown when initialising the LDAP Common plugin fails because of an incorrect configuration.
72 throw new Exception(_m('The username attribute must be set.'));
76 function onAutoload($cls)
78 // we've added an extra include-path in the beginning of this file
81 case 'MemcacheSchemaCache':
82 require_once(INSTALLDIR.'/plugins/LdapCommon/MemcacheSchemaCache.php');
85 require_once 'Net/LDAP2.php';
87 case 'Net_LDAP2_Filter':
88 require_once 'Net/LDAP2/Filter.php';
90 case 'Net_LDAP2_Filter':
91 require_once 'Net/LDAP2/Filter.php';
93 case 'Net_LDAP2_Entry':
94 require_once 'Net/LDAP2/Entry.php';
101 function get_ldap_config(){
103 $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
104 foreach($keys as $key){
105 $value = $this->$key;
107 $config[$key]=$value;
113 function get_ldap_connection($config = null){
114 if($config == null) {
115 $config = $this->ldap_config;
117 $config_id = crc32(serialize($config));
118 if(array_key_exists($config_id,self::$ldap_connections)) {
119 $ldap = self::$ldap_connections[$config_id];
121 //cannot use Net_LDAP2::connect() as StatusNet uses
122 //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
123 //PEAR handling can be overridden on instance objects, so we do that.
124 $ldap = new Net_LDAP2($config);
125 $ldap->setErrorHandling(PEAR_ERROR_RETURN);
127 if (Net_LDAP2::isError($err)) {
128 // if we were called with a config, assume caller will handle
129 // incorrect username/password (LDAP_INVALID_CREDENTIALS)
130 if (isset($config) && $err->getCode() == 0x31) {
131 // TRANS: Exception thrown in the LDAP Common plugin when LDAP server is not available.
132 // TRANS: %s is the error message.
133 throw new LdapInvalidCredentialsException(sprintf(_m('Could not connect to LDAP server: %s'),$err->getMessage()));
135 // TRANS: Exception thrown in the LDAP Common plugin when LDAP server is not available.
136 // TRANS: %s is the error message.
137 throw new Exception(sprintf(_m('Could not connect to LDAP server: %s.'),$err->getMessage()));
139 $c = Cache::instance();
141 $cacheObj = new MemcacheSchemaCache(
143 'cacheKey' => Cache::key('ldap_schema:' . $config_id)));
144 $ldap->registerSchemaCache($cacheObj);
146 self::$ldap_connections[$config_id] = $ldap;
151 function checkPassword($username, $password)
153 $entry = $this->get_user($username,array('dn' => 'dn'));
157 if(empty($password)) {
158 //NET_LDAP2 will do an anonymous bind if bindpw is not set / empty string
159 //which causes all login attempts that involve a blank password to appear
160 //to succeed. Which is obviously not good.
163 $config = $this->get_ldap_config();
164 $config['binddn']=$entry->dn();
165 $config['bindpw']=$password;
167 $this->get_ldap_connection($config);
168 } catch (LdapInvalidCredentialsException $e) {
175 function changePassword($username,$oldpassword,$newpassword)
177 if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
178 //throw new Exception(_m('Sorry, changing LDAP passwords is not supported at this time.'));
181 $entry = $this->get_user($username,array('dn' => 'dn'));
185 $config = $this->get_ldap_config();
186 $config['binddn']=$entry->dn();
187 $config['bindpw']=$oldpassword;
189 $ldap = $this->get_ldap_connection($config);
191 $entry = $this->get_user($username,array(),$ldap);
193 $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
194 if ($newCryptedPassword===false) {
197 if($this->password_encoding=='ad') {
198 //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
199 $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
200 $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
202 $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
203 if( Net_LDAP2::isError($entry->upate()) ) {
207 } catch (LdapInvalidCredentialsException $e) {
215 function is_dn_member_of_group($userDn, $groupDn)
217 $ldap = $this->get_ldap_connection();
218 $link = $ldap->getLink();
219 $r = @ldap_compare($link, $groupDn, $this->uniqueMember_attribute, $userDn);
222 }else if($r === false){
225 common_log(LOG_ERR, "LDAP error determining if userDn=$userDn is a member of groupDn=$groupDn using uniqueMember_attribute=$this->uniqueMember_attribute error: ".ldap_error($link));
231 * get an LDAP entry for a user with a given username
233 * @param string $username
234 * $param array $attributes LDAP attributes to retrieve
237 function get_user($username,$attributes=array()){
238 $ldap = $this->get_ldap_connection();
239 $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals', $username);
241 'attributes' => $attributes
243 $search = $ldap->search(null,$filter,$options);
245 if (PEAR::isError($search)) {
246 common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
250 if($search->count()==0){
252 }else if($search->count()==1){
253 $entry = $search->shiftEntry();
256 common_log(LOG_WARNING, 'Found ' . $search->count() . ' ldap user with the username: ' . $username);
262 * Code originaly from the phpLDAPadmin development team
263 * http://phpldapadmin.sourceforge.net/
265 * Hashes a password and returns the hash based on the specified enc_type.
267 * @param string $passwordClear The password to hash in clear text.
268 * @param string $encodageType Standard LDAP encryption type which must be one of
269 * crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
270 * @return string The hashed password.
273 function hashPassword( $passwordClear, $encodageType )
275 $encodageType = strtolower( $encodageType );
276 switch( $encodageType ) {
278 $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2));
282 // extended des crypt. see OpenBSD crypt man page.
283 if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
284 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
288 if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
289 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
293 if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
294 $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
298 $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
302 if( function_exists('sha1') ) {
303 // use php 4.3.0+ sha1 function, if it is available.
304 $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
305 } elseif( function_exists( 'mhash' ) ) {
306 $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
308 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
313 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
314 mt_srand( (double) microtime() * 1000000 );
315 $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
316 $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
318 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
323 if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
324 mt_srand( (double) microtime() * 1000000 );
325 $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
326 $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
328 return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
333 $cryptedPassword = '';
334 $passwordClear = "\"" . $passwordClear . "\"";
335 $len = strlen($passwordClear);
336 for ($i = 0; $i < $len; $i++) {
337 $cryptedPassword .= "{$passwordClear{$i}}\000";
342 $cryptedPassword = $passwordClear;
345 return $cryptedPassword;
349 * Code originaly from the phpLDAPadmin development team
350 * http://phpldapadmin.sourceforge.net/
352 * Used to generate a random salt for crypt-style passwords. Salt strings are used
353 * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
354 * not only the user's password but also a randomly generated string. The string is
355 * stored as the first N characters of the hash for reference of hashing algorithms later.
357 * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
358 * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
360 * @param int $length The length of the salt string to generate.
361 * @return string The generated salt string.
363 function randomSalt( $length )
365 $possible = '0123456789'.
366 'abcdefghijklmnopqrstuvwxyz'.
367 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
370 mt_srand((double)microtime() * 1000000);
372 while( strlen( $str ) < $length )
373 $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
379 class LdapInvalidCredentialsException extends Exception