Ldap.php 17 KB

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