LdapCommon.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Utility class of LDAP functions
  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 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/
  28. */
  29. if (!defined('STATUSNET') && !defined('LACONICA')) {
  30. exit(1);
  31. }
  32. // We bundle the Net/LDAP2 library...
  33. set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib');
  34. class LdapCommon
  35. {
  36. protected static $ldap_connections = array();
  37. public $host=null;
  38. public $port=null;
  39. public $version=null;
  40. public $starttls=null;
  41. public $binddn=null;
  42. public $bindpw=null;
  43. public $basedn=null;
  44. public $options=null;
  45. public $filter=null;
  46. public $scope=null;
  47. public $uniqueMember_attribute = null;
  48. public $attributes=array();
  49. public $password_encoding=null;
  50. public function __construct($config)
  51. {
  52. Event::addHandler('Autoload',array($this,'onAutoload'));
  53. foreach($config as $key=>$value) {
  54. $this->$key = $value;
  55. }
  56. $this->ldap_config = $this->get_ldap_config();
  57. if(!isset($this->host)){
  58. // TRANS: Exception thrown when initialising the LDAP Common plugin fails because of an incorrect configuration.
  59. throw new Exception(_m('A host must be specified.'));
  60. }
  61. if(!isset($this->basedn)){
  62. // TRANS: Exception thrown when initialising the LDAP Common plugin fails because of an incorrect configuration.
  63. throw new Exception(_m('"basedn" must be specified.'));
  64. }
  65. if(!isset($this->attributes['username'])){
  66. // TRANS: Exception thrown when initialising the LDAP Common plugin fails because of an incorrect configuration.
  67. throw new Exception(_m('The username attribute must be set.'));
  68. }
  69. }
  70. function onAutoload($cls)
  71. {
  72. // we've added an extra include-path in the beginning of this file
  73. switch ($cls)
  74. {
  75. case 'MemcacheSchemaCache':
  76. require_once(INSTALLDIR.'/plugins/LdapCommon/MemcacheSchemaCache.php');
  77. return false;
  78. case 'Net_LDAP2':
  79. require_once 'Net/LDAP2.php';
  80. return false;
  81. case 'Net_LDAP2_Filter':
  82. require_once 'Net/LDAP2/Filter.php';
  83. return false;
  84. case 'Net_LDAP2_Filter':
  85. require_once 'Net/LDAP2/Filter.php';
  86. return false;
  87. case 'Net_LDAP2_Entry':
  88. require_once 'Net/LDAP2/Entry.php';
  89. return false;
  90. }
  91. return true;
  92. }
  93. function get_ldap_config(){
  94. $config = array();
  95. $keys = array('host','port','version','starttls','binddn','bindpw','basedn','options','filter','scope');
  96. foreach($keys as $key){
  97. $value = $this->$key;
  98. if($value!==null){
  99. $config[$key]=$value;
  100. }
  101. }
  102. return $config;
  103. }
  104. function get_ldap_connection($config = null){
  105. if($config == null) {
  106. $config = $this->ldap_config;
  107. }
  108. $config_id = crc32(serialize($config));
  109. if(array_key_exists($config_id,self::$ldap_connections)) {
  110. $ldap = self::$ldap_connections[$config_id];
  111. } else {
  112. //cannot use Net_LDAP2::connect() as StatusNet uses
  113. //PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handleError');
  114. //PEAR handling can be overridden on instance objects, so we do that.
  115. $ldap = new Net_LDAP2($config);
  116. $ldap->setErrorHandling(PEAR_ERROR_RETURN);
  117. $err=$ldap->bind();
  118. if (Net_LDAP2::isError($err)) {
  119. // if we were called with a config, assume caller will handle
  120. // incorrect username/password (LDAP_INVALID_CREDENTIALS)
  121. if (isset($config) && $err->getCode() == 0x31) {
  122. // TRANS: Exception thrown in the LDAP Common plugin when LDAP server is not available.
  123. // TRANS: %s is the error message.
  124. throw new LdapInvalidCredentialsException(sprintf(_m('Could not connect to LDAP server: %s'),$err->getMessage()));
  125. }
  126. // TRANS: Exception thrown in the LDAP Common plugin when LDAP server is not available.
  127. // TRANS: %s is the error message.
  128. throw new Exception(sprintf(_m('Could not connect to LDAP server: %s.'),$err->getMessage()));
  129. }
  130. $c = Cache::instance();
  131. if (!empty($c)) {
  132. $cacheObj = new MemcacheSchemaCache(
  133. array('c'=>$c,
  134. 'cacheKey' => Cache::key('ldap_schema:' . $config_id)));
  135. $ldap->registerSchemaCache($cacheObj);
  136. }
  137. self::$ldap_connections[$config_id] = $ldap;
  138. }
  139. return $ldap;
  140. }
  141. function checkPassword($username, $password)
  142. {
  143. $entry = $this->get_user($username,array('dn' => 'dn'));
  144. if(!$entry){
  145. return false;
  146. }else{
  147. if(empty($password)) {
  148. //NET_LDAP2 will do an anonymous bind if bindpw is not set / empty string
  149. //which causes all login attempts that involve a blank password to appear
  150. //to succeed. Which is obviously not good.
  151. return false;
  152. }
  153. $config = $this->get_ldap_config();
  154. $config['binddn']=$entry->dn();
  155. $config['bindpw']=$password;
  156. try {
  157. $this->get_ldap_connection($config);
  158. } catch (LdapInvalidCredentialsException $e) {
  159. return false;
  160. }
  161. return true;
  162. }
  163. }
  164. function changePassword($username,$oldpassword,$newpassword)
  165. {
  166. if(! isset($this->attributes['password']) || !isset($this->password_encoding)){
  167. //throw new Exception(_m('Sorry, changing LDAP passwords is not supported at this time.'));
  168. return false;
  169. }
  170. $entry = $this->get_user($username,array('dn' => 'dn'));
  171. if(!$entry){
  172. return false;
  173. }else{
  174. $config = $this->get_ldap_config();
  175. $config['binddn']=$entry->dn();
  176. $config['bindpw']=$oldpassword;
  177. try {
  178. $ldap = $this->get_ldap_connection($config);
  179. $entry = $this->get_user($username,array(),$ldap);
  180. $newCryptedPassword = $this->hashPassword($newpassword, $this->password_encoding);
  181. if ($newCryptedPassword===false) {
  182. return false;
  183. }
  184. if($this->password_encoding=='ad') {
  185. //TODO I believe this code will work once this bug is fixed: http://pear.php.net/bugs/bug.php?id=16796
  186. $oldCryptedPassword = $this->hashPassword($oldpassword, $this->password_encoding);
  187. $entry->delete( array($this->attributes['password'] => $oldCryptedPassword ));
  188. }
  189. $entry->replace( array($this->attributes['password'] => $newCryptedPassword ), true);
  190. if( Net_LDAP2::isError($entry->upate()) ) {
  191. return false;
  192. }
  193. return true;
  194. } catch (LdapInvalidCredentialsException $e) {
  195. return false;
  196. }
  197. }
  198. return false;
  199. }
  200. function is_dn_member_of_group($userDn, $groupDn)
  201. {
  202. $ldap = $this->get_ldap_connection();
  203. $link = $ldap->getLink();
  204. $r = @ldap_compare($link, $groupDn, $this->uniqueMember_attribute, $userDn);
  205. if ($r === true){
  206. return true;
  207. }else if($r === false){
  208. return false;
  209. }else{
  210. 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));
  211. return false;
  212. }
  213. }
  214. /**
  215. * get an LDAP entry for a user with a given username
  216. *
  217. * @param string $username
  218. * $param array $attributes LDAP attributes to retrieve
  219. * @return string DN
  220. */
  221. function get_user($username,$attributes=array()){
  222. $ldap = $this->get_ldap_connection();
  223. $filter = Net_LDAP2_Filter::create($this->attributes['username'], 'equals', $username);
  224. $options = array(
  225. 'attributes' => $attributes
  226. );
  227. $search = $ldap->search(null,$filter,$options);
  228. if (PEAR::isError($search)) {
  229. common_log(LOG_WARNING, 'Error while getting DN for user: '.$search->getMessage());
  230. return false;
  231. }
  232. if($search->count()==0){
  233. return false;
  234. }else if($search->count()==1){
  235. $entry = $search->shiftEntry();
  236. return $entry;
  237. }else{
  238. common_log(LOG_WARNING, 'Found ' . $search->count() . ' ldap user with the username: ' . $username);
  239. return false;
  240. }
  241. }
  242. /**
  243. * Code originaly from the phpLDAPadmin development team
  244. * http://phpldapadmin.sourceforge.net/
  245. *
  246. * Hashes a password and returns the hash based on the specified enc_type.
  247. *
  248. * @param string $passwordClear The password to hash in clear text.
  249. * @param string $encodageType Standard LDAP encryption type which must be one of
  250. * crypt, ext_des, md5crypt, blowfish, md5, sha, smd5, ssha, or clear.
  251. * @return string The hashed password.
  252. *
  253. */
  254. function hashPassword( $passwordClear, $encodageType )
  255. {
  256. $encodageType = strtolower( $encodageType );
  257. switch( $encodageType ) {
  258. case 'crypt':
  259. $cryptedPassword = '{CRYPT}' . crypt($passwordClear,$this->randomSalt(2));
  260. break;
  261. case 'ext_des':
  262. // extended des crypt. see OpenBSD crypt man page.
  263. if ( ! defined( 'CRYPT_EXT_DES' ) || CRYPT_EXT_DES == 0 ) {return FALSE;} //Your system crypt library does not support extended DES encryption.
  264. $cryptedPassword = '{CRYPT}' . crypt( $passwordClear, '_' . $this->randomSalt(8) );
  265. break;
  266. case 'md5crypt':
  267. if( ! defined( 'CRYPT_MD5' ) || CRYPT_MD5 == 0 ) {return FALSE;} //Your system crypt library does not support md5crypt encryption.
  268. $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$1$' . $this->randomSalt(9) );
  269. break;
  270. case 'blowfish':
  271. if( ! defined( 'CRYPT_BLOWFISH' ) || CRYPT_BLOWFISH == 0 ) {return FALSE;} //Your system crypt library does not support blowfish encryption.
  272. $cryptedPassword = '{CRYPT}' . crypt( $passwordClear , '$2a$12$' . $this->randomSalt(13) ); // hardcoded to second blowfish version and set number of rounds
  273. break;
  274. case 'md5':
  275. $cryptedPassword = '{MD5}' . base64_encode( pack( 'H*' , md5( $passwordClear) ) );
  276. break;
  277. case 'sha':
  278. if( function_exists('sha1') ) {
  279. // use php 4.3.0+ sha1 function, if it is available.
  280. $cryptedPassword = '{SHA}' . base64_encode( pack( 'H*' , sha1( $passwordClear) ) );
  281. } elseif( function_exists( 'mhash' ) ) {
  282. $cryptedPassword = '{SHA}' . base64_encode( mhash( MHASH_SHA1, $passwordClear) );
  283. } else {
  284. return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
  285. }
  286. break;
  287. case 'ssha':
  288. if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
  289. mt_srand( (double) microtime() * 1000000 );
  290. $salt = mhash_keygen_s2k( MHASH_SHA1, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
  291. $cryptedPassword = "{SSHA}".base64_encode( mhash( MHASH_SHA1, $passwordClear.$salt ).$salt );
  292. } else {
  293. return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
  294. }
  295. break;
  296. case 'smd5':
  297. if( function_exists( 'mhash' ) && function_exists( 'mhash_keygen_s2k' ) ) {
  298. mt_srand( (double) microtime() * 1000000 );
  299. $salt = mhash_keygen_s2k( MHASH_MD5, $passwordClear, substr( pack( "h*", md5( mt_rand() ) ), 0, 8 ), 4 );
  300. $cryptedPassword = "{SMD5}".base64_encode( mhash( MHASH_MD5, $passwordClear.$salt ).$salt );
  301. } else {
  302. return FALSE; //Your PHP install does not have the mhash() function. Cannot do SHA hashes.
  303. }
  304. break;
  305. case 'ad':
  306. $cryptedPassword = '';
  307. $passwordClear = "\"" . $passwordClear . "\"";
  308. $len = strlen($passwordClear);
  309. for ($i = 0; $i < $len; $i++) {
  310. $cryptedPassword .= "{$passwordClear{$i}}\000";
  311. }
  312. case 'clear':
  313. default:
  314. $cryptedPassword = $passwordClear;
  315. }
  316. return $cryptedPassword;
  317. }
  318. /**
  319. * Code originaly from the phpLDAPadmin development team
  320. * http://phpldapadmin.sourceforge.net/
  321. *
  322. * Used to generate a random salt for crypt-style passwords. Salt strings are used
  323. * to make pre-built hash cracking dictionaries difficult to use as the hash algorithm uses
  324. * not only the user's password but also a randomly generated string. The string is
  325. * stored as the first N characters of the hash for reference of hashing algorithms later.
  326. *
  327. * --- added 20021125 by bayu irawan <bayuir@divnet.telkom.co.id> ---
  328. * --- ammended 20030625 by S C Rigler <srigler@houston.rr.com> ---
  329. *
  330. * @param int $length The length of the salt string to generate.
  331. * @return string The generated salt string.
  332. */
  333. function randomSalt( $length )
  334. {
  335. $possible = '0123456789'.
  336. 'abcdefghijklmnopqrstuvwxyz'.
  337. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
  338. './';
  339. $str = "";
  340. mt_srand((double)microtime() * 1000000);
  341. while( strlen( $str ) < $length )
  342. $str .= substr( $possible, ( rand() % strlen( $possible ) ), 1 );
  343. return $str;
  344. }
  345. }
  346. class LdapInvalidCredentialsException extends Exception
  347. {
  348. }