2
0

Ldap.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Auth
  17. * @subpackage Zend_Auth_Adapter
  18. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Auth_Adapter_Interface
  24. */
  25. require_once 'Zend/Auth/Adapter/Interface.php';
  26. /**
  27. * @category Zend
  28. * @package Zend_Auth
  29. * @subpackage Zend_Auth_Adapter
  30. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  31. * @license http://framework.zend.com/license/new-bsd New BSD License
  32. */
  33. class Zend_Auth_Adapter_Ldap implements Zend_Auth_Adapter_Interface
  34. {
  35. /**
  36. * The Zend_Ldap context.
  37. *
  38. * @var Zend_Ldap
  39. */
  40. protected $_ldap = null;
  41. /**
  42. * The array of arrays of Zend_Ldap options passed to the constructor.
  43. *
  44. * @var array
  45. */
  46. protected $_options = null;
  47. /**
  48. * The username of the account being authenticated.
  49. *
  50. * @var string
  51. */
  52. protected $_username = null;
  53. /**
  54. * The password of the account being authenticated.
  55. *
  56. * @var string
  57. */
  58. protected $_password = null;
  59. /**
  60. * The DN of the authenticated account. Used to retrieve the account entry on request.
  61. *
  62. * @var string
  63. */
  64. protected $_authenticatedDn = null;
  65. /**
  66. * Constructor
  67. *
  68. * @param array $options An array of arrays of Zend_Ldap options
  69. * @param string $username The username of the account being authenticated
  70. * @param string $password The password of the account being authenticated
  71. * @return void
  72. */
  73. public function __construct(array $options = array(), $username = null, $password = null)
  74. {
  75. $this->setOptions($options);
  76. if ($username !== null) {
  77. $this->setUsername($username);
  78. }
  79. if ($password !== null) {
  80. $this->setPassword($password);
  81. }
  82. }
  83. /**
  84. * Returns the array of arrays of Zend_Ldap options of this adapter.
  85. *
  86. * @return array|null
  87. */
  88. public function getOptions()
  89. {
  90. return $this->_options;
  91. }
  92. /**
  93. * Sets the array of arrays of Zend_Ldap options to be used by
  94. * this adapter.
  95. *
  96. * @param array $options The array of arrays of Zend_Ldap options
  97. * @return Zend_Auth_Adapter_Ldap Provides a fluent interface
  98. */
  99. public function setOptions($options)
  100. {
  101. $this->_options = is_array($options) ? $options : array();
  102. return $this;
  103. }
  104. /**
  105. * Returns the username of the account being authenticated, or
  106. * NULL if none is set.
  107. *
  108. * @return string|null
  109. */
  110. public function getUsername()
  111. {
  112. return $this->_username;
  113. }
  114. /**
  115. * Sets the username for binding
  116. *
  117. * @param string $username The username for binding
  118. * @return Zend_Auth_Adapter_Ldap Provides a fluent interface
  119. */
  120. public function setUsername($username)
  121. {
  122. $this->_username = (string) $username;
  123. return $this;
  124. }
  125. /**
  126. * Returns the password of the account being authenticated, or
  127. * NULL if none is set.
  128. *
  129. * @return string|null
  130. */
  131. public function getPassword()
  132. {
  133. return $this->_password;
  134. }
  135. /**
  136. * Sets the passwort for the account
  137. *
  138. * @param string $password The password of the account being authenticated
  139. * @return Zend_Auth_Adapter_Ldap Provides a fluent interface
  140. */
  141. public function setPassword($password)
  142. {
  143. $this->_password = (string) $password;
  144. return $this;
  145. }
  146. /**
  147. * setIdentity() - set the identity (username) to be used
  148. *
  149. * Proxies to {@see setPassword()}
  150. *
  151. * Closes ZF-6813
  152. *
  153. * @param string $identity
  154. * @return Zend_Auth_Adapter_Ldap Provides a fluent interface
  155. */
  156. public function setIdentity($identity)
  157. {
  158. return $this->setUsername($identity);
  159. }
  160. /**
  161. * setCredential() - set the credential (password) value to be used
  162. *
  163. * Proxies to {@see setPassword()}
  164. *
  165. * Closes ZF-6813
  166. *
  167. * @param string $credential
  168. * @return Zend_Auth_Adapter_Ldap Provides a fluent interface
  169. */
  170. public function setCredential($credential)
  171. {
  172. return $this->setPassword($credential);
  173. }
  174. /**
  175. * Returns the LDAP Object
  176. *
  177. * @return Zend_Ldap The Zend_Ldap object used to authenticate the credentials
  178. */
  179. public function getLdap()
  180. {
  181. if ($this->_ldap === null) {
  182. /**
  183. * @see Zend_Ldap
  184. */
  185. require_once 'Zend/Ldap.php';
  186. $this->_ldap = new Zend_Ldap();
  187. }
  188. return $this->_ldap;
  189. }
  190. /**
  191. * Set an Ldap connection
  192. *
  193. * @param Zend_Ldap $ldap An existing Ldap object
  194. * @return Zend_Auth_Adapter_Ldap Provides a fluent interface
  195. */
  196. public function setLdap(Zend_Ldap $ldap)
  197. {
  198. $this->_ldap = $ldap;
  199. $this->setOptions(array($ldap->getOptions()));
  200. return $this;
  201. }
  202. /**
  203. * Returns a domain name for the current LDAP options. This is used
  204. * for skipping redundant operations (e.g. authentications).
  205. *
  206. * @return string
  207. */
  208. protected function _getAuthorityName()
  209. {
  210. $options = $this->getLdap()->getOptions();
  211. $name = $options['accountDomainName'];
  212. if (!$name)
  213. $name = $options['accountDomainNameShort'];
  214. return $name ? $name : '';
  215. }
  216. /**
  217. * Authenticate the user
  218. *
  219. * @throws Zend_Auth_Adapter_Exception
  220. * @return Zend_Auth_Result
  221. */
  222. public function authenticate()
  223. {
  224. /**
  225. * @see Zend_Ldap_Exception
  226. */
  227. require_once 'Zend/Ldap/Exception.php';
  228. $messages = array();
  229. $messages[0] = ''; // reserved
  230. $messages[1] = ''; // reserved
  231. $username = $this->_username;
  232. $password = $this->_password;
  233. if (!$username) {
  234. $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
  235. $messages[0] = 'A username is required';
  236. return new Zend_Auth_Result($code, '', $messages);
  237. }
  238. if (!$password) {
  239. /* A password is required because some servers will
  240. * treat an empty password as an anonymous bind.
  241. */
  242. $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
  243. $messages[0] = 'A password is required';
  244. return new Zend_Auth_Result($code, '', $messages);
  245. }
  246. $ldap = $this->getLdap();
  247. $code = Zend_Auth_Result::FAILURE;
  248. $messages[0] = "Authority not found: $username";
  249. $failedAuthorities = array();
  250. /* Iterate through each server and try to authenticate the supplied
  251. * credentials against it.
  252. */
  253. foreach ($this->_options as $name => $options) {
  254. if (!is_array($options)) {
  255. /**
  256. * @see Zend_Auth_Adapter_Exception
  257. */
  258. require_once 'Zend/Auth/Adapter/Exception.php';
  259. throw new Zend_Auth_Adapter_Exception('Adapter options array not in array');
  260. }
  261. $adapterOptions = $this->_prepareOptions($ldap, $options);
  262. $dname = '';
  263. try {
  264. if ($messages[1])
  265. $messages[] = $messages[1];
  266. $messages[1] = '';
  267. $messages[] = $this->_optionsToString($options);
  268. $dname = $this->_getAuthorityName();
  269. if (isset($failedAuthorities[$dname])) {
  270. /* If multiple sets of server options for the same domain
  271. * are supplied, we want to skip redundant authentications
  272. * where the identity or credentials where found to be
  273. * invalid with another server for the same domain. The
  274. * $failedAuthorities array tracks this condition (and also
  275. * serves to supply the original error message).
  276. * This fixes issue ZF-4093.
  277. */
  278. $messages[1] = $failedAuthorities[$dname];
  279. $messages[] = "Skipping previously failed authority: $dname";
  280. continue;
  281. }
  282. $canonicalName = $ldap->getCanonicalAccountName($username);
  283. $ldap->bind($canonicalName, $password);
  284. $dn = $ldap->getCanonicalAccountName($canonicalName, Zend_Ldap::ACCTNAME_FORM_DN);
  285. $groupResult = $this->_checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions);
  286. if ($groupResult === true) {
  287. $this->_authenticatedDn = $dn;
  288. $messages[0] = '';
  289. $messages[1] = '';
  290. $messages[] = "$canonicalName authentication successful";
  291. return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $canonicalName, $messages);
  292. } else {
  293. $messages[0] = 'Account is not a member of the specified group';
  294. $messages[1] = $groupResult;
  295. $failedAuthorities[$dname] = $groupResult;
  296. }
  297. } catch (Zend_Ldap_Exception $zle) {
  298. /* LDAP based authentication is notoriously difficult to diagnose. Therefore
  299. * we bend over backwards to capture and record every possible bit of
  300. * information when something goes wrong.
  301. */
  302. $err = $zle->getCode();
  303. if ($err == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) {
  304. /* This error indicates that the domain supplied in the
  305. * username did not match the domains in the server options
  306. * and therefore we should just skip to the next set of
  307. * server options.
  308. */
  309. continue;
  310. } else if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) {
  311. $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
  312. $messages[0] = "Account not found: $username";
  313. $failedAuthorities[$dname] = $zle->getMessage();
  314. } else if ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) {
  315. $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
  316. $messages[0] = 'Invalid credentials';
  317. $failedAuthorities[$dname] = $zle->getMessage();
  318. } else {
  319. $line = $zle->getLine();
  320. $messages[] = $zle->getFile() . "($line): " . $zle->getMessage();
  321. $messages[] = str_replace($password, '*****', $zle->getTraceAsString());
  322. $messages[0] = 'An unexpected failure occurred';
  323. }
  324. $messages[1] = $zle->getMessage();
  325. }
  326. }
  327. $msg = isset($messages[1]) ? $messages[1] : $messages[0];
  328. $messages[] = "$username authentication failed: $msg";
  329. return new Zend_Auth_Result($code, $username, $messages);
  330. }
  331. /**
  332. * Sets the LDAP specific options on the Zend_Ldap instance
  333. *
  334. * @param Zend_Ldap $ldap
  335. * @param array $options
  336. * @return array of auth-adapter specific options
  337. */
  338. protected function _prepareOptions(Zend_Ldap $ldap, array $options)
  339. {
  340. $adapterOptions = array(
  341. 'group' => null,
  342. 'groupDn' => $ldap->getBaseDn(),
  343. 'groupScope' => Zend_Ldap::SEARCH_SCOPE_SUB,
  344. 'groupAttr' => 'cn',
  345. 'groupFilter' => 'objectClass=groupOfUniqueNames',
  346. 'memberAttr' => 'uniqueMember',
  347. 'memberIsDn' => true
  348. );
  349. foreach ($adapterOptions as $key => $value) {
  350. if (array_key_exists($key, $options)) {
  351. $value = $options[$key];
  352. unset($options[$key]);
  353. switch ($key) {
  354. case 'groupScope':
  355. $value = (int)$value;
  356. if (in_array($value, array(Zend_Ldap::SEARCH_SCOPE_BASE,
  357. Zend_Ldap::SEARCH_SCOPE_ONE, Zend_Ldap::SEARCH_SCOPE_SUB), true)) {
  358. $adapterOptions[$key] = $value;
  359. }
  360. break;
  361. case 'memberIsDn':
  362. $adapterOptions[$key] = ($value === true ||
  363. $value === '1' || strcasecmp($value, 'true') == 0);
  364. break;
  365. default:
  366. $adapterOptions[$key] = trim($value);
  367. break;
  368. }
  369. }
  370. }
  371. $ldap->setOptions($options);
  372. return $adapterOptions;
  373. }
  374. /**
  375. * Checks the group membership of the bound user
  376. *
  377. * @param Zend_Ldap $ldap
  378. * @param string $canonicalName
  379. * @param string $dn
  380. * @param array $adapterOptions
  381. * @return string|true
  382. */
  383. protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, array $adapterOptions)
  384. {
  385. if ($adapterOptions['group'] === null) {
  386. return true;
  387. }
  388. if ($adapterOptions['memberIsDn'] === false) {
  389. $user = $canonicalName;
  390. } else {
  391. $user = $dn;
  392. }
  393. /**
  394. * @see Zend_Ldap_Filter
  395. */
  396. require_once 'Zend/Ldap/Filter.php';
  397. $groupName = Zend_Ldap_Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']);
  398. $membership = Zend_Ldap_Filter::equals($adapterOptions['memberAttr'], $user);
  399. $group = Zend_Ldap_Filter::andFilter($groupName, $membership);
  400. $groupFilter = $adapterOptions['groupFilter'];
  401. if (!empty($groupFilter)) {
  402. $group = $group->addAnd($groupFilter);
  403. }
  404. /*
  405. * Fixes problem when authenticated user is not allowed to retrieve
  406. * group-membership information.
  407. * This requires that the user specified with "username" and "password"
  408. * in the Zend_Ldap options is able to retrieve the required information.
  409. */
  410. $ldap->bind();
  411. $result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']);
  412. if ($result === 1) {
  413. return true;
  414. } else {
  415. return 'Failed to verify group membership with ' . $group->toString();
  416. }
  417. }
  418. /**
  419. * getAccountObject() - Returns the result entry as a stdClass object
  420. *
  421. * This resembles the feature {@see Zend_Auth_Adapter_DbTable::getResultRowObject()}.
  422. * Closes ZF-6813
  423. *
  424. * @param array $returnAttribs
  425. * @return stdClass|boolean
  426. */
  427. public function getAccountObject(array $returnAttribs = array())
  428. {
  429. if (!$this->_authenticatedDn) {
  430. return false;
  431. }
  432. $returnObject = new stdClass();
  433. $entry = $this->getLdap()->getEntry($this->_authenticatedDn, $returnAttribs, true);
  434. foreach ($entry as $attr => $value) {
  435. if (is_array($value)) {
  436. $returnObject->$attr = (count($value) > 1) ? $value : $value[0];
  437. } else {
  438. $returnObject->$attr = $value;
  439. }
  440. }
  441. return $returnObject;
  442. }
  443. /**
  444. * Converts options to string
  445. *
  446. * @param array $options
  447. * @return string
  448. */
  449. private function _optionsToString(array $options)
  450. {
  451. $str = '';
  452. foreach ($options as $key => $val) {
  453. if ($key === 'password')
  454. $val = '*****';
  455. if ($str)
  456. $str .= ',';
  457. $str .= $key . '=' . $val;
  458. }
  459. return $str;
  460. }
  461. }