Ldap.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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-2014 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-2014 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 setUsername()}
  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 an 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. /*
  285. * Fixes problem when authenticated user is not allowed to retrieve
  286. * group-membership information or own account.
  287. * This requires that the user specified with "username" and optionally
  288. * "password" in the Zend_Ldap options is able to retrieve the required
  289. * information.
  290. */
  291. $requireRebind = false;
  292. if (isset($options['username'])) {
  293. $ldap->bind();
  294. $requireRebind = true;
  295. }
  296. $dn = $ldap->getCanonicalAccountName($canonicalName, Zend_Ldap::ACCTNAME_FORM_DN);
  297. $groupResult = $this->_checkGroupMembership($ldap, $canonicalName, $dn, $adapterOptions);
  298. if ($groupResult === true) {
  299. $this->_authenticatedDn = $dn;
  300. $messages[0] = '';
  301. $messages[1] = '';
  302. $messages[] = "$canonicalName authentication successful";
  303. if ($requireRebind === true) {
  304. // rebinding with authenticated user
  305. $ldap->bind($dn, $password);
  306. }
  307. return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $canonicalName, $messages);
  308. } else {
  309. $messages[0] = 'Account is not a member of the specified group';
  310. $messages[1] = $groupResult;
  311. $failedAuthorities[$dname] = $groupResult;
  312. }
  313. } catch (Zend_Ldap_Exception $zle) {
  314. /* LDAP based authentication is notoriously difficult to diagnose. Therefore
  315. * we bend over backwards to capture and record every possible bit of
  316. * information when something goes wrong.
  317. */
  318. $err = $zle->getCode();
  319. if ($err == Zend_Ldap_Exception::LDAP_X_DOMAIN_MISMATCH) {
  320. /* This error indicates that the domain supplied in the
  321. * username did not match the domains in the server options
  322. * and therefore we should just skip to the next set of
  323. * server options.
  324. */
  325. continue;
  326. } else if ($err == Zend_Ldap_Exception::LDAP_NO_SUCH_OBJECT) {
  327. $code = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
  328. $messages[0] = "Account not found: $username";
  329. $failedAuthorities[$dname] = $zle->getMessage();
  330. } else if ($err == Zend_Ldap_Exception::LDAP_INVALID_CREDENTIALS) {
  331. $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
  332. $messages[0] = 'Invalid credentials';
  333. $failedAuthorities[$dname] = $zle->getMessage();
  334. } else {
  335. $line = $zle->getLine();
  336. $messages[] = $zle->getFile() . "($line): " . $zle->getMessage();
  337. $messages[] = preg_replace(
  338. '/\b'.preg_quote(substr($password, 0, 15), '/').'\b/',
  339. '*****',
  340. $zle->getTraceAsString()
  341. );
  342. $messages[0] = 'An unexpected failure occurred';
  343. }
  344. $messages[1] = $zle->getMessage();
  345. }
  346. }
  347. $msg = isset($messages[1]) ? $messages[1] : $messages[0];
  348. $messages[] = "$username authentication failed: $msg";
  349. return new Zend_Auth_Result($code, $username, $messages);
  350. }
  351. /**
  352. * Sets the LDAP specific options on the Zend_Ldap instance
  353. *
  354. * @param Zend_Ldap $ldap
  355. * @param array $options
  356. * @return array of auth-adapter specific options
  357. */
  358. protected function _prepareOptions(Zend_Ldap $ldap, array $options)
  359. {
  360. $adapterOptions = array(
  361. 'group' => null,
  362. 'groupDn' => $ldap->getBaseDn(),
  363. 'groupScope' => Zend_Ldap::SEARCH_SCOPE_SUB,
  364. 'groupAttr' => 'cn',
  365. 'groupFilter' => 'objectClass=groupOfUniqueNames',
  366. 'memberAttr' => 'uniqueMember',
  367. 'memberIsDn' => true
  368. );
  369. foreach ($adapterOptions as $key => $value) {
  370. if (array_key_exists($key, $options)) {
  371. $value = $options[$key];
  372. unset($options[$key]);
  373. switch ($key) {
  374. case 'groupScope':
  375. $value = (int)$value;
  376. if (in_array($value, array(Zend_Ldap::SEARCH_SCOPE_BASE,
  377. Zend_Ldap::SEARCH_SCOPE_ONE, Zend_Ldap::SEARCH_SCOPE_SUB), true)) {
  378. $adapterOptions[$key] = $value;
  379. }
  380. break;
  381. case 'memberIsDn':
  382. $adapterOptions[$key] = ($value === true ||
  383. $value === '1' || strcasecmp($value, 'true') == 0);
  384. break;
  385. default:
  386. $adapterOptions[$key] = trim($value);
  387. break;
  388. }
  389. }
  390. }
  391. $ldap->setOptions($options);
  392. return $adapterOptions;
  393. }
  394. /**
  395. * Checks the group membership of the bound user
  396. *
  397. * @param Zend_Ldap $ldap
  398. * @param string $canonicalName
  399. * @param string $dn
  400. * @param array $adapterOptions
  401. * @return string|true
  402. */
  403. protected function _checkGroupMembership(Zend_Ldap $ldap, $canonicalName, $dn, array $adapterOptions)
  404. {
  405. if ($adapterOptions['group'] === null) {
  406. return true;
  407. }
  408. if ($adapterOptions['memberIsDn'] === false) {
  409. $user = $canonicalName;
  410. } else {
  411. $user = $dn;
  412. }
  413. /**
  414. * @see Zend_Ldap_Filter
  415. */
  416. require_once 'Zend/Ldap/Filter.php';
  417. $groupName = Zend_Ldap_Filter::equals($adapterOptions['groupAttr'], $adapterOptions['group']);
  418. $membership = Zend_Ldap_Filter::equals($adapterOptions['memberAttr'], $user);
  419. $group = Zend_Ldap_Filter::andFilter($groupName, $membership);
  420. $groupFilter = $adapterOptions['groupFilter'];
  421. if (!empty($groupFilter)) {
  422. $group = $group->addAnd($groupFilter);
  423. }
  424. $result = $ldap->count($group, $adapterOptions['groupDn'], $adapterOptions['groupScope']);
  425. if ($result === 1) {
  426. return true;
  427. } else {
  428. return 'Failed to verify group membership with ' . $group->toString();
  429. }
  430. }
  431. /**
  432. * getAccountObject() - Returns the result entry as a stdClass object
  433. *
  434. * This resembles the feature {@see Zend_Auth_Adapter_DbTable::getResultRowObject()}.
  435. * Closes ZF-6813
  436. *
  437. * @param array $returnAttribs
  438. * @param array $omitAttribs
  439. * @return stdClass|boolean
  440. */
  441. public function getAccountObject(array $returnAttribs = array(), array $omitAttribs = array())
  442. {
  443. if (!$this->_authenticatedDn) {
  444. return false;
  445. }
  446. $returnObject = new stdClass();
  447. $returnAttribs = array_map('strtolower', $returnAttribs);
  448. $omitAttribs = array_map('strtolower', $omitAttribs);
  449. $returnAttribs = array_diff($returnAttribs, $omitAttribs);
  450. $entry = $this->getLdap()->getEntry($this->_authenticatedDn, $returnAttribs, true);
  451. foreach ($entry as $attr => $value) {
  452. if (in_array($attr, $omitAttribs)) {
  453. // skip attributes marked to be omitted
  454. continue;
  455. }
  456. if (is_array($value)) {
  457. $returnObject->$attr = (count($value) > 1) ? $value : $value[0];
  458. } else {
  459. $returnObject->$attr = $value;
  460. }
  461. }
  462. return $returnObject;
  463. }
  464. /**
  465. * Converts options to string
  466. *
  467. * @param array $options
  468. * @return string
  469. */
  470. private function _optionsToString(array $options)
  471. {
  472. $str = '';
  473. foreach ($options as $key => $val) {
  474. if ($key === 'password')
  475. $val = '*****';
  476. if ($str)
  477. $str .= ',';
  478. $str .= $key . '=' . $val;
  479. }
  480. return $str;
  481. }
  482. }