2
0

Ldap.php 17 KB

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