Connection.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Jarkko Lehtoranta <devel@jlranta.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Roger Szabo <roger.szabo@web.de>
  18. * @author root <root@localhost.localdomain>
  19. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  20. * @author Xuanwo <xuanwo@yunify.com>
  21. * @author Vincent Van Houtte <vvh@aplusv.be>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OCA\User_LDAP;
  39. use OC\ServerNotAvailableException;
  40. use Psr\Log\LoggerInterface;
  41. /**
  42. * magic properties (incomplete)
  43. * responsible for LDAP connections in context with the provided configuration
  44. *
  45. * @property string ldapHost
  46. * @property string ldapPort holds the port number
  47. * @property string ldapUserFilter
  48. * @property string ldapUserDisplayName
  49. * @property string ldapUserDisplayName2
  50. * @property string ldapUserAvatarRule
  51. * @property boolean turnOnPasswordChange
  52. * @property string[] ldapBaseUsers
  53. * @property int|null ldapPagingSize holds an integer
  54. * @property bool|mixed|void ldapGroupMemberAssocAttr
  55. * @property string ldapUuidUserAttribute
  56. * @property string ldapUuidGroupAttribute
  57. * @property string ldapExpertUUIDUserAttr
  58. * @property string ldapExpertUUIDGroupAttr
  59. * @property string ldapQuotaAttribute
  60. * @property string ldapQuotaDefault
  61. * @property string ldapEmailAttribute
  62. * @property string ldapExtStorageHomeAttribute
  63. * @property string homeFolderNamingRule
  64. * @property bool|string ldapNestedGroups
  65. * @property string[] ldapBaseGroups
  66. * @property string ldapGroupFilter
  67. * @property string ldapGroupDisplayName
  68. * @property string ldapLoginFilter
  69. * @property string ldapDynamicGroupMemberURL
  70. * @property string ldapGidNumber
  71. * @property int hasMemberOfFilterSupport
  72. * @property int useMemberOfToDetectMembership
  73. * @property string ldapMatchingRuleInChainState
  74. */
  75. class Connection extends LDAPUtility {
  76. /**
  77. * @var resource|\LDAP\Connection|null
  78. */
  79. private $ldapConnectionRes = null;
  80. /**
  81. * @var string
  82. */
  83. private $configPrefix;
  84. /**
  85. * @var ?string
  86. */
  87. private $configID;
  88. /**
  89. * @var bool
  90. */
  91. private $configured = false;
  92. /**
  93. * @var bool whether connection should be kept on __destruct
  94. */
  95. private $dontDestruct = false;
  96. /**
  97. * @var bool runtime flag that indicates whether supported primary groups are available
  98. */
  99. public $hasPrimaryGroups = true;
  100. /**
  101. * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
  102. */
  103. public $hasGidNumber = true;
  104. /**
  105. * @var \OCP\ICache|null
  106. */
  107. protected $cache = null;
  108. /** @var Configuration settings handler **/
  109. protected $configuration;
  110. /**
  111. * @var bool
  112. */
  113. protected $doNotValidate = false;
  114. /**
  115. * @var bool
  116. */
  117. protected $ignoreValidation = false;
  118. /**
  119. * @var array{sum?: string, result?: bool}
  120. */
  121. protected $bindResult = [];
  122. /** @var LoggerInterface */
  123. protected $logger;
  124. /**
  125. * Constructor
  126. * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
  127. * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
  128. */
  129. public function __construct(ILDAPWrapper $ldap, string $configPrefix = '', ?string $configID = 'user_ldap') {
  130. parent::__construct($ldap);
  131. $this->configPrefix = $configPrefix;
  132. $this->configID = $configID;
  133. $this->configuration = new Configuration($configPrefix, !is_null($configID));
  134. $memcache = \OC::$server->getMemCacheFactory();
  135. if ($memcache->isAvailable()) {
  136. $this->cache = $memcache->createDistributed();
  137. }
  138. $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
  139. $this->doNotValidate = !in_array($this->configPrefix,
  140. $helper->getServerConfigurationPrefixes());
  141. $this->logger = \OC::$server->get(LoggerInterface::class);
  142. }
  143. public function __destruct() {
  144. if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
  145. @$this->ldap->unbind($this->ldapConnectionRes);
  146. $this->bindResult = [];
  147. }
  148. }
  149. /**
  150. * defines behaviour when the instance is cloned
  151. */
  152. public function __clone() {
  153. $this->configuration = new Configuration($this->configPrefix,
  154. !is_null($this->configID));
  155. if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
  156. $this->bindResult = [];
  157. }
  158. $this->ldapConnectionRes = null;
  159. $this->dontDestruct = true;
  160. }
  161. public function __get(string $name) {
  162. if (!$this->configured) {
  163. $this->readConfiguration();
  164. }
  165. return $this->configuration->$name;
  166. }
  167. /**
  168. * @param string $name
  169. * @param mixed $value
  170. */
  171. public function __set($name, $value) {
  172. $this->doNotValidate = false;
  173. $before = $this->configuration->$name;
  174. $this->configuration->$name = $value;
  175. $after = $this->configuration->$name;
  176. if ($before !== $after) {
  177. if ($this->configID !== '' && $this->configID !== null) {
  178. $this->configuration->saveConfiguration();
  179. }
  180. $this->validateConfiguration();
  181. }
  182. }
  183. /**
  184. * @param string $rule
  185. * @return array
  186. * @throws \RuntimeException
  187. */
  188. public function resolveRule($rule) {
  189. return $this->configuration->resolveRule($rule);
  190. }
  191. /**
  192. * sets whether the result of the configuration validation shall
  193. * be ignored when establishing the connection. Used by the Wizard
  194. * in early configuration state.
  195. * @param bool $state
  196. */
  197. public function setIgnoreValidation($state) {
  198. $this->ignoreValidation = (bool)$state;
  199. }
  200. /**
  201. * initializes the LDAP backend
  202. * @param bool $force read the config settings no matter what
  203. */
  204. public function init($force = false) {
  205. $this->readConfiguration($force);
  206. $this->establishConnection();
  207. }
  208. /**
  209. * @return resource|\LDAP\Connection The LDAP resource
  210. */
  211. public function getConnectionResource() {
  212. if (!$this->ldapConnectionRes) {
  213. $this->init();
  214. } elseif (!$this->ldap->isResource($this->ldapConnectionRes)) {
  215. $this->ldapConnectionRes = null;
  216. $this->establishConnection();
  217. }
  218. if (is_null($this->ldapConnectionRes)) {
  219. $this->logger->error(
  220. 'No LDAP Connection to server ' . $this->configuration->ldapHost,
  221. ['app' => 'user_ldap']
  222. );
  223. throw new ServerNotAvailableException('Connection to LDAP server could not be established');
  224. }
  225. return $this->ldapConnectionRes;
  226. }
  227. /**
  228. * resets the connection resource
  229. */
  230. public function resetConnectionResource() {
  231. if (!is_null($this->ldapConnectionRes)) {
  232. @$this->ldap->unbind($this->ldapConnectionRes);
  233. $this->ldapConnectionRes = null;
  234. $this->bindResult = [];
  235. }
  236. }
  237. /**
  238. * @param string|null $key
  239. * @return string
  240. */
  241. private function getCacheKey($key) {
  242. $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
  243. if (is_null($key)) {
  244. return $prefix;
  245. }
  246. return $prefix.hash('sha256', $key);
  247. }
  248. /**
  249. * @param string $key
  250. * @return mixed|null
  251. */
  252. public function getFromCache($key) {
  253. if (!$this->configured) {
  254. $this->readConfiguration();
  255. }
  256. if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
  257. return null;
  258. }
  259. $key = $this->getCacheKey($key);
  260. return json_decode(base64_decode($this->cache->get($key) ?? ''), true);
  261. }
  262. /**
  263. * @param string $key
  264. * @param mixed $value
  265. */
  266. public function writeToCache($key, $value, int $ttlOverride = null): void {
  267. if (!$this->configured) {
  268. $this->readConfiguration();
  269. }
  270. if (is_null($this->cache)
  271. || !$this->configuration->ldapCacheTTL
  272. || !$this->configuration->ldapConfigurationActive) {
  273. return;
  274. }
  275. $key = $this->getCacheKey($key);
  276. $value = base64_encode(json_encode($value));
  277. $ttl = $ttlOverride ?? $this->configuration->ldapCacheTTL;
  278. $this->cache->set($key, $value, $ttl);
  279. }
  280. public function clearCache() {
  281. if (!is_null($this->cache)) {
  282. $this->cache->clear($this->getCacheKey(null));
  283. }
  284. }
  285. /**
  286. * Caches the general LDAP configuration.
  287. * @param bool $force optional. true, if the re-read should be forced. defaults
  288. * to false.
  289. * @return null
  290. */
  291. private function readConfiguration($force = false) {
  292. if ((!$this->configured || $force) && !is_null($this->configID)) {
  293. $this->configuration->readConfiguration();
  294. $this->configured = $this->validateConfiguration();
  295. }
  296. }
  297. /**
  298. * set LDAP configuration with values delivered by an array, not read from configuration
  299. * @param array $config array that holds the config parameters in an associated array
  300. * @param array &$setParameters optional; array where the set fields will be given to
  301. * @return bool true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  302. */
  303. public function setConfiguration($config, &$setParameters = null): bool {
  304. if (is_null($setParameters)) {
  305. $setParameters = [];
  306. }
  307. $this->doNotValidate = false;
  308. $this->configuration->setConfiguration($config, $setParameters);
  309. if (count($setParameters) > 0) {
  310. $this->configured = $this->validateConfiguration();
  311. }
  312. return $this->configured;
  313. }
  314. /**
  315. * saves the current Configuration in the database and empties the
  316. * cache
  317. * @return null
  318. */
  319. public function saveConfiguration() {
  320. $this->configuration->saveConfiguration();
  321. $this->clearCache();
  322. }
  323. /**
  324. * get the current LDAP configuration
  325. * @return array
  326. */
  327. public function getConfiguration() {
  328. $this->readConfiguration();
  329. $config = $this->configuration->getConfiguration();
  330. $cta = $this->configuration->getConfigTranslationArray();
  331. $result = [];
  332. foreach ($cta as $dbkey => $configkey) {
  333. switch ($configkey) {
  334. case 'homeFolderNamingRule':
  335. if (strpos($config[$configkey], 'attr:') === 0) {
  336. $result[$dbkey] = substr($config[$configkey], 5);
  337. } else {
  338. $result[$dbkey] = '';
  339. }
  340. break;
  341. case 'ldapBase':
  342. case 'ldapBaseUsers':
  343. case 'ldapBaseGroups':
  344. case 'ldapAttributesForUserSearch':
  345. case 'ldapAttributesForGroupSearch':
  346. if (is_array($config[$configkey])) {
  347. $result[$dbkey] = implode("\n", $config[$configkey]);
  348. break;
  349. } //else follows default
  350. // no break
  351. default:
  352. $result[$dbkey] = $config[$configkey];
  353. }
  354. }
  355. return $result;
  356. }
  357. private function doSoftValidation() {
  358. //if User or Group Base are not set, take over Base DN setting
  359. foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
  360. $val = $this->configuration->$keyBase;
  361. if (empty($val)) {
  362. $this->configuration->$keyBase = $this->configuration->ldapBase;
  363. }
  364. }
  365. foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
  366. 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
  367. as $expertSetting => $effectiveSetting) {
  368. $uuidOverride = $this->configuration->$expertSetting;
  369. if (!empty($uuidOverride)) {
  370. $this->configuration->$effectiveSetting = $uuidOverride;
  371. } else {
  372. $uuidAttributes = Access::UUID_ATTRIBUTES;
  373. array_unshift($uuidAttributes, 'auto');
  374. if (!in_array($this->configuration->$effectiveSetting, $uuidAttributes)
  375. && !is_null($this->configID)) {
  376. $this->configuration->$effectiveSetting = 'auto';
  377. $this->configuration->saveConfiguration();
  378. $this->logger->info(
  379. 'Illegal value for the '.$effectiveSetting.', reset to autodetect.',
  380. ['app' => 'user_ldap']
  381. );
  382. }
  383. }
  384. }
  385. $backupPort = (int)$this->configuration->ldapBackupPort;
  386. if ($backupPort <= 0) {
  387. $this->configuration->backupPort = $this->configuration->ldapPort;
  388. }
  389. //make sure empty search attributes are saved as simple, empty array
  390. $saKeys = ['ldapAttributesForUserSearch',
  391. 'ldapAttributesForGroupSearch'];
  392. foreach ($saKeys as $key) {
  393. $val = $this->configuration->$key;
  394. if (is_array($val) && count($val) === 1 && empty($val[0])) {
  395. $this->configuration->$key = [];
  396. }
  397. }
  398. if ((stripos((string)$this->configuration->ldapHost, 'ldaps://') === 0)
  399. && $this->configuration->ldapTLS) {
  400. $this->configuration->ldapTLS = false;
  401. $this->logger->info(
  402. 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
  403. ['app' => 'user_ldap']
  404. );
  405. }
  406. }
  407. /**
  408. * @return bool
  409. */
  410. private function doCriticalValidation() {
  411. $configurationOK = true;
  412. $errorStr = 'Configuration Error (prefix '.
  413. (string)$this->configPrefix .'): ';
  414. //options that shall not be empty
  415. $options = ['ldapHost', 'ldapUserDisplayName',
  416. 'ldapGroupDisplayName', 'ldapLoginFilter'];
  417. //ldapPort should not be empty either unless ldapHost is pointing to a socket
  418. if (!$this->configuration->usesLdapi()) {
  419. $options[] = 'ldapPort';
  420. }
  421. foreach ($options as $key) {
  422. $val = $this->configuration->$key;
  423. if (empty($val)) {
  424. switch ($key) {
  425. case 'ldapHost':
  426. $subj = 'LDAP Host';
  427. break;
  428. case 'ldapPort':
  429. $subj = 'LDAP Port';
  430. break;
  431. case 'ldapUserDisplayName':
  432. $subj = 'LDAP User Display Name';
  433. break;
  434. case 'ldapGroupDisplayName':
  435. $subj = 'LDAP Group Display Name';
  436. break;
  437. case 'ldapLoginFilter':
  438. $subj = 'LDAP Login Filter';
  439. break;
  440. default:
  441. $subj = $key;
  442. break;
  443. }
  444. $configurationOK = false;
  445. $this->logger->warning(
  446. $errorStr.'No '.$subj.' given!',
  447. ['app' => 'user_ldap']
  448. );
  449. }
  450. }
  451. //combinations
  452. $agent = $this->configuration->ldapAgentName;
  453. $pwd = $this->configuration->ldapAgentPassword;
  454. if (
  455. ($agent === '' && $pwd !== '')
  456. || ($agent !== '' && $pwd === '')
  457. ) {
  458. $this->logger->warning(
  459. $errorStr.'either no password is given for the user ' .
  460. 'agent or a password is given, but not an LDAP agent.',
  461. ['app' => 'user_ldap']
  462. );
  463. $configurationOK = false;
  464. }
  465. $base = $this->configuration->ldapBase;
  466. $baseUsers = $this->configuration->ldapBaseUsers;
  467. $baseGroups = $this->configuration->ldapBaseGroups;
  468. if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
  469. $this->logger->warning(
  470. $errorStr.'Not a single Base DN given.',
  471. ['app' => 'user_ldap']
  472. );
  473. $configurationOK = false;
  474. }
  475. if (mb_strpos((string)$this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
  476. === false) {
  477. $this->logger->warning(
  478. $errorStr.'login filter does not contain %uid place holder.',
  479. ['app' => 'user_ldap']
  480. );
  481. $configurationOK = false;
  482. }
  483. return $configurationOK;
  484. }
  485. /**
  486. * Validates the user specified configuration
  487. * @return bool true if configuration seems OK, false otherwise
  488. */
  489. private function validateConfiguration() {
  490. if ($this->doNotValidate) {
  491. //don't do a validation if it is a new configuration with pure
  492. //default values. Will be allowed on changes via __set or
  493. //setConfiguration
  494. return false;
  495. }
  496. // first step: "soft" checks: settings that are not really
  497. // necessary, but advisable. If left empty, give an info message
  498. $this->doSoftValidation();
  499. //second step: critical checks. If left empty or filled wrong, mark as
  500. //not configured and give a warning.
  501. return $this->doCriticalValidation();
  502. }
  503. /**
  504. * Connects and Binds to LDAP
  505. *
  506. * @throws ServerNotAvailableException
  507. */
  508. private function establishConnection() {
  509. if (!$this->configuration->ldapConfigurationActive) {
  510. return null;
  511. }
  512. static $phpLDAPinstalled = true;
  513. if (!$phpLDAPinstalled) {
  514. return false;
  515. }
  516. if (!$this->ignoreValidation && !$this->configured) {
  517. $this->logger->warning(
  518. 'Configuration is invalid, cannot connect',
  519. ['app' => 'user_ldap']
  520. );
  521. return false;
  522. }
  523. if (!$this->ldapConnectionRes) {
  524. if (!$this->ldap->areLDAPFunctionsAvailable()) {
  525. $phpLDAPinstalled = false;
  526. $this->logger->error(
  527. 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
  528. ['app' => 'user_ldap']
  529. );
  530. return false;
  531. }
  532. if ($this->configuration->turnOffCertCheck) {
  533. if (putenv('LDAPTLS_REQCERT=never')) {
  534. $this->logger->debug(
  535. 'Turned off SSL certificate validation successfully.',
  536. ['app' => 'user_ldap']
  537. );
  538. } else {
  539. $this->logger->warning(
  540. 'Could not turn off SSL certificate validation.',
  541. ['app' => 'user_ldap']
  542. );
  543. }
  544. }
  545. $hasBackupHost = (trim($this->configuration->ldapBackupHost ?? '') !== '');
  546. $hasBackgroundHost = (trim($this->configuration->ldapBackgroundHost ?? '') !== '');
  547. $useBackgroundHost = (\OC::$CLI && $hasBackgroundHost);
  548. $overrideCacheKey = ($useBackgroundHost ? 'overrideBackgroundServer' : 'overrideMainServer');
  549. $forceBackupHost = ($this->configuration->ldapOverrideMainServer || $this->getFromCache($overrideCacheKey));
  550. $bindStatus = false;
  551. if (!$forceBackupHost) {
  552. try {
  553. $host = $this->configuration->ldapHost ?? '';
  554. $port = $this->configuration->ldapPort ?? '';
  555. if ($useBackgroundHost) {
  556. $host = $this->configuration->ldapBackgroundHost ?? '';
  557. $port = $this->configuration->ldapBackgroundPort ?? '';
  558. }
  559. $this->doConnect($host, $port);
  560. return $this->bind();
  561. } catch (ServerNotAvailableException $e) {
  562. if (!$hasBackupHost) {
  563. throw $e;
  564. }
  565. }
  566. $this->logger->warning(
  567. 'Main LDAP not reachable, connecting to backup',
  568. [
  569. 'app' => 'user_ldap'
  570. ]
  571. );
  572. }
  573. // if LDAP server is not reachable, try the Backup (Replica!) Server
  574. $this->doConnect($this->configuration->ldapBackupHost ?? '', $this->configuration->ldapBackupPort ?? '');
  575. $this->bindResult = [];
  576. $bindStatus = $this->bind();
  577. $error = $this->ldap->isResource($this->ldapConnectionRes) ?
  578. $this->ldap->errno($this->ldapConnectionRes) : -1;
  579. if ($bindStatus && $error === 0 && !$forceBackupHost) {
  580. //when bind to backup server succeeded and failed to main server,
  581. //skip contacting it for 15min
  582. $this->writeToCache($overrideCacheKey, true, 60 * 15);
  583. }
  584. return $bindStatus;
  585. }
  586. return null;
  587. }
  588. /**
  589. * @param string $host
  590. * @param string $port
  591. * @return bool
  592. * @throws \OC\ServerNotAvailableException
  593. */
  594. private function doConnect($host, $port) {
  595. if ($host === '') {
  596. return false;
  597. }
  598. $this->ldapConnectionRes = $this->ldap->connect($host, $port);
  599. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  600. throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
  601. }
  602. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  603. throw new ServerNotAvailableException('Could not disable LDAP referrals.');
  604. }
  605. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_NETWORK_TIMEOUT, $this->configuration->ldapConnectionTimeout)) {
  606. throw new ServerNotAvailableException('Could not set network timeout');
  607. }
  608. if ($this->configuration->ldapTLS) {
  609. if (!$this->ldap->startTls($this->ldapConnectionRes)) {
  610. throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
  611. }
  612. }
  613. return true;
  614. }
  615. /**
  616. * Binds to LDAP
  617. */
  618. public function bind() {
  619. if (!$this->configuration->ldapConfigurationActive) {
  620. return false;
  621. }
  622. $cr = $this->ldapConnectionRes;
  623. if (!$this->ldap->isResource($cr)) {
  624. $cr = $this->getConnectionResource();
  625. }
  626. if (
  627. count($this->bindResult) !== 0
  628. && $this->bindResult['sum'] === md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword)
  629. ) {
  630. // don't attempt to bind again with the same data as before
  631. // bind might have been invoked via getConnectionResource(),
  632. // but we need results specifically for e.g. user login
  633. return $this->bindResult['result'];
  634. }
  635. $ldapLogin = @$this->ldap->bind($cr,
  636. $this->configuration->ldapAgentName,
  637. $this->configuration->ldapAgentPassword);
  638. $this->bindResult = [
  639. 'sum' => md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword),
  640. 'result' => $ldapLogin,
  641. ];
  642. if (!$ldapLogin) {
  643. $errno = $this->ldap->errno($cr);
  644. $this->logger->warning(
  645. 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
  646. ['app' => 'user_ldap']
  647. );
  648. // Set to failure mode, if LDAP error code is not one of
  649. // - LDAP_SUCCESS (0)
  650. // - LDAP_INVALID_CREDENTIALS (49)
  651. // - LDAP_INSUFFICIENT_ACCESS (50, spotted Apple Open Directory)
  652. // - LDAP_UNWILLING_TO_PERFORM (53, spotted eDirectory)
  653. if (!in_array($errno, [0, 49, 50, 53], true)) {
  654. $this->ldapConnectionRes = null;
  655. }
  656. return false;
  657. }
  658. return true;
  659. }
  660. }