PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/LdapCommon/LdapCommon.php

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