Connection.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. public function getConfigPrefix(): string {
  263. return $this->configPrefix;
  264. }
  265. /**
  266. * @param string $key
  267. * @param mixed $value
  268. */
  269. public function writeToCache($key, $value, int $ttlOverride = null): void {
  270. if (!$this->configured) {
  271. $this->readConfiguration();
  272. }
  273. if (is_null($this->cache)
  274. || !$this->configuration->ldapCacheTTL
  275. || !$this->configuration->ldapConfigurationActive) {
  276. return;
  277. }
  278. $key = $this->getCacheKey($key);
  279. $value = base64_encode(json_encode($value));
  280. $ttl = $ttlOverride ?? $this->configuration->ldapCacheTTL;
  281. $this->cache->set($key, $value, $ttl);
  282. }
  283. public function clearCache() {
  284. if (!is_null($this->cache)) {
  285. $this->cache->clear($this->getCacheKey(null));
  286. }
  287. }
  288. /**
  289. * Caches the general LDAP configuration.
  290. * @param bool $force optional. true, if the re-read should be forced. defaults
  291. * to false.
  292. * @return null
  293. */
  294. private function readConfiguration($force = false) {
  295. if ((!$this->configured || $force) && !is_null($this->configID)) {
  296. $this->configuration->readConfiguration();
  297. $this->configured = $this->validateConfiguration();
  298. }
  299. }
  300. /**
  301. * set LDAP configuration with values delivered by an array, not read from configuration
  302. * @param array $config array that holds the config parameters in an associated array
  303. * @param array &$setParameters optional; array where the set fields will be given to
  304. * @return bool true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  305. */
  306. public function setConfiguration($config, &$setParameters = null): bool {
  307. if (is_null($setParameters)) {
  308. $setParameters = [];
  309. }
  310. $this->doNotValidate = false;
  311. $this->configuration->setConfiguration($config, $setParameters);
  312. if (count($setParameters) > 0) {
  313. $this->configured = $this->validateConfiguration();
  314. }
  315. return $this->configured;
  316. }
  317. /**
  318. * saves the current Configuration in the database and empties the
  319. * cache
  320. * @return null
  321. */
  322. public function saveConfiguration() {
  323. $this->configuration->saveConfiguration();
  324. $this->clearCache();
  325. }
  326. /**
  327. * get the current LDAP configuration
  328. * @return array
  329. */
  330. public function getConfiguration() {
  331. $this->readConfiguration();
  332. $config = $this->configuration->getConfiguration();
  333. $cta = $this->configuration->getConfigTranslationArray();
  334. $result = [];
  335. foreach ($cta as $dbkey => $configkey) {
  336. switch ($configkey) {
  337. case 'homeFolderNamingRule':
  338. if (strpos($config[$configkey], 'attr:') === 0) {
  339. $result[$dbkey] = substr($config[$configkey], 5);
  340. } else {
  341. $result[$dbkey] = '';
  342. }
  343. break;
  344. case 'ldapBase':
  345. case 'ldapBaseUsers':
  346. case 'ldapBaseGroups':
  347. case 'ldapAttributesForUserSearch':
  348. case 'ldapAttributesForGroupSearch':
  349. if (is_array($config[$configkey])) {
  350. $result[$dbkey] = implode("\n", $config[$configkey]);
  351. break;
  352. } //else follows default
  353. // no break
  354. default:
  355. $result[$dbkey] = $config[$configkey];
  356. }
  357. }
  358. return $result;
  359. }
  360. private function doSoftValidation() {
  361. //if User or Group Base are not set, take over Base DN setting
  362. foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
  363. $val = $this->configuration->$keyBase;
  364. if (empty($val)) {
  365. $this->configuration->$keyBase = $this->configuration->ldapBase;
  366. }
  367. }
  368. foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
  369. 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
  370. as $expertSetting => $effectiveSetting) {
  371. $uuidOverride = $this->configuration->$expertSetting;
  372. if (!empty($uuidOverride)) {
  373. $this->configuration->$effectiveSetting = $uuidOverride;
  374. } else {
  375. $uuidAttributes = Access::UUID_ATTRIBUTES;
  376. array_unshift($uuidAttributes, 'auto');
  377. if (!in_array($this->configuration->$effectiveSetting, $uuidAttributes)
  378. && !is_null($this->configID)) {
  379. $this->configuration->$effectiveSetting = 'auto';
  380. $this->configuration->saveConfiguration();
  381. $this->logger->info(
  382. 'Illegal value for the '.$effectiveSetting.', reset to autodetect.',
  383. ['app' => 'user_ldap']
  384. );
  385. }
  386. }
  387. }
  388. $backupPort = (int)$this->configuration->ldapBackupPort;
  389. if ($backupPort <= 0) {
  390. $this->configuration->backupPort = $this->configuration->ldapPort;
  391. }
  392. //make sure empty search attributes are saved as simple, empty array
  393. $saKeys = ['ldapAttributesForUserSearch',
  394. 'ldapAttributesForGroupSearch'];
  395. foreach ($saKeys as $key) {
  396. $val = $this->configuration->$key;
  397. if (is_array($val) && count($val) === 1 && empty($val[0])) {
  398. $this->configuration->$key = [];
  399. }
  400. }
  401. if ((stripos((string)$this->configuration->ldapHost, 'ldaps://') === 0)
  402. && $this->configuration->ldapTLS) {
  403. $this->configuration->ldapTLS = false;
  404. $this->logger->info(
  405. 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
  406. ['app' => 'user_ldap']
  407. );
  408. }
  409. }
  410. /**
  411. * @return bool
  412. */
  413. private function doCriticalValidation() {
  414. $configurationOK = true;
  415. $errorStr = 'Configuration Error (prefix '.
  416. (string)$this->configPrefix .'): ';
  417. //options that shall not be empty
  418. $options = ['ldapHost', 'ldapUserDisplayName',
  419. 'ldapGroupDisplayName', 'ldapLoginFilter'];
  420. //ldapPort should not be empty either unless ldapHost is pointing to a socket
  421. if (!$this->configuration->usesLdapi()) {
  422. $options[] = 'ldapPort';
  423. }
  424. foreach ($options as $key) {
  425. $val = $this->configuration->$key;
  426. if (empty($val)) {
  427. switch ($key) {
  428. case 'ldapHost':
  429. $subj = 'LDAP Host';
  430. break;
  431. case 'ldapPort':
  432. $subj = 'LDAP Port';
  433. break;
  434. case 'ldapUserDisplayName':
  435. $subj = 'LDAP User Display Name';
  436. break;
  437. case 'ldapGroupDisplayName':
  438. $subj = 'LDAP Group Display Name';
  439. break;
  440. case 'ldapLoginFilter':
  441. $subj = 'LDAP Login Filter';
  442. break;
  443. default:
  444. $subj = $key;
  445. break;
  446. }
  447. $configurationOK = false;
  448. $this->logger->warning(
  449. $errorStr.'No '.$subj.' given!',
  450. ['app' => 'user_ldap']
  451. );
  452. }
  453. }
  454. //combinations
  455. $agent = $this->configuration->ldapAgentName;
  456. $pwd = $this->configuration->ldapAgentPassword;
  457. if (
  458. ($agent === '' && $pwd !== '')
  459. || ($agent !== '' && $pwd === '')
  460. ) {
  461. $this->logger->warning(
  462. $errorStr.'either no password is given for the user ' .
  463. 'agent or a password is given, but not an LDAP agent.',
  464. ['app' => 'user_ldap']
  465. );
  466. $configurationOK = false;
  467. }
  468. $base = $this->configuration->ldapBase;
  469. $baseUsers = $this->configuration->ldapBaseUsers;
  470. $baseGroups = $this->configuration->ldapBaseGroups;
  471. if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
  472. $this->logger->warning(
  473. $errorStr.'Not a single Base DN given.',
  474. ['app' => 'user_ldap']
  475. );
  476. $configurationOK = false;
  477. }
  478. if (mb_strpos((string)$this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
  479. === false) {
  480. $this->logger->warning(
  481. $errorStr.'login filter does not contain %uid place holder.',
  482. ['app' => 'user_ldap']
  483. );
  484. $configurationOK = false;
  485. }
  486. return $configurationOK;
  487. }
  488. /**
  489. * Validates the user specified configuration
  490. * @return bool true if configuration seems OK, false otherwise
  491. */
  492. private function validateConfiguration() {
  493. if ($this->doNotValidate) {
  494. //don't do a validation if it is a new configuration with pure
  495. //default values. Will be allowed on changes via __set or
  496. //setConfiguration
  497. return false;
  498. }
  499. // first step: "soft" checks: settings that are not really
  500. // necessary, but advisable. If left empty, give an info message
  501. $this->doSoftValidation();
  502. //second step: critical checks. If left empty or filled wrong, mark as
  503. //not configured and give a warning.
  504. return $this->doCriticalValidation();
  505. }
  506. /**
  507. * Connects and Binds to LDAP
  508. *
  509. * @throws ServerNotAvailableException
  510. */
  511. private function establishConnection() {
  512. if (!$this->configuration->ldapConfigurationActive) {
  513. return null;
  514. }
  515. static $phpLDAPinstalled = true;
  516. if (!$phpLDAPinstalled) {
  517. return false;
  518. }
  519. if (!$this->ignoreValidation && !$this->configured) {
  520. $this->logger->warning(
  521. 'Configuration is invalid, cannot connect',
  522. ['app' => 'user_ldap']
  523. );
  524. return false;
  525. }
  526. if (!$this->ldapConnectionRes) {
  527. if (!$this->ldap->areLDAPFunctionsAvailable()) {
  528. $phpLDAPinstalled = false;
  529. $this->logger->error(
  530. 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
  531. ['app' => 'user_ldap']
  532. );
  533. return false;
  534. }
  535. if ($this->configuration->turnOffCertCheck) {
  536. if (putenv('LDAPTLS_REQCERT=never')) {
  537. $this->logger->debug(
  538. 'Turned off SSL certificate validation successfully.',
  539. ['app' => 'user_ldap']
  540. );
  541. } else {
  542. $this->logger->warning(
  543. 'Could not turn off SSL certificate validation.',
  544. ['app' => 'user_ldap']
  545. );
  546. }
  547. }
  548. $hasBackupHost = (trim($this->configuration->ldapBackupHost ?? '') !== '');
  549. $hasBackgroundHost = (trim($this->configuration->ldapBackgroundHost ?? '') !== '');
  550. $useBackgroundHost = (\OC::$CLI && $hasBackgroundHost);
  551. $overrideCacheKey = ($useBackgroundHost ? 'overrideBackgroundServer' : 'overrideMainServer');
  552. $forceBackupHost = ($this->configuration->ldapOverrideMainServer || $this->getFromCache($overrideCacheKey));
  553. $bindStatus = false;
  554. if (!$forceBackupHost) {
  555. try {
  556. $host = $this->configuration->ldapHost ?? '';
  557. $port = $this->configuration->ldapPort ?? '';
  558. if ($useBackgroundHost) {
  559. $host = $this->configuration->ldapBackgroundHost ?? '';
  560. $port = $this->configuration->ldapBackgroundPort ?? '';
  561. }
  562. $this->doConnect($host, $port);
  563. return $this->bind();
  564. } catch (ServerNotAvailableException $e) {
  565. if (!$hasBackupHost) {
  566. throw $e;
  567. }
  568. }
  569. $this->logger->warning(
  570. 'Main LDAP not reachable, connecting to backup',
  571. [
  572. 'app' => 'user_ldap'
  573. ]
  574. );
  575. }
  576. // if LDAP server is not reachable, try the Backup (Replica!) Server
  577. $this->doConnect($this->configuration->ldapBackupHost ?? '', $this->configuration->ldapBackupPort ?? '');
  578. $this->bindResult = [];
  579. $bindStatus = $this->bind();
  580. $error = $this->ldap->isResource($this->ldapConnectionRes) ?
  581. $this->ldap->errno($this->ldapConnectionRes) : -1;
  582. if ($bindStatus && $error === 0 && !$forceBackupHost) {
  583. //when bind to backup server succeeded and failed to main server,
  584. //skip contacting it for 15min
  585. $this->writeToCache($overrideCacheKey, true, 60 * 15);
  586. }
  587. return $bindStatus;
  588. }
  589. return null;
  590. }
  591. /**
  592. * @param string $host
  593. * @param string $port
  594. * @return bool
  595. * @throws \OC\ServerNotAvailableException
  596. */
  597. private function doConnect($host, $port) {
  598. if ($host === '') {
  599. return false;
  600. }
  601. $this->ldapConnectionRes = $this->ldap->connect($host, $port);
  602. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  603. throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
  604. }
  605. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  606. throw new ServerNotAvailableException('Could not disable LDAP referrals.');
  607. }
  608. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_NETWORK_TIMEOUT, $this->configuration->ldapConnectionTimeout)) {
  609. throw new ServerNotAvailableException('Could not set network timeout');
  610. }
  611. if ($this->configuration->ldapTLS) {
  612. if (!$this->ldap->startTls($this->ldapConnectionRes)) {
  613. throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
  614. }
  615. }
  616. return true;
  617. }
  618. /**
  619. * Binds to LDAP
  620. */
  621. public function bind() {
  622. if (!$this->configuration->ldapConfigurationActive) {
  623. return false;
  624. }
  625. $cr = $this->ldapConnectionRes;
  626. if (!$this->ldap->isResource($cr)) {
  627. $cr = $this->getConnectionResource();
  628. }
  629. if (
  630. count($this->bindResult) !== 0
  631. && $this->bindResult['sum'] === md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword)
  632. ) {
  633. // don't attempt to bind again with the same data as before
  634. // bind might have been invoked via getConnectionResource(),
  635. // but we need results specifically for e.g. user login
  636. return $this->bindResult['result'];
  637. }
  638. $ldapLogin = @$this->ldap->bind($cr,
  639. $this->configuration->ldapAgentName,
  640. $this->configuration->ldapAgentPassword);
  641. $this->bindResult = [
  642. 'sum' => md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword),
  643. 'result' => $ldapLogin,
  644. ];
  645. if (!$ldapLogin) {
  646. $errno = $this->ldap->errno($cr);
  647. $this->logger->warning(
  648. 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
  649. ['app' => 'user_ldap']
  650. );
  651. // Set to failure mode, if LDAP error code is not one of
  652. // - LDAP_SUCCESS (0)
  653. // - LDAP_INVALID_CREDENTIALS (49)
  654. // - LDAP_INSUFFICIENT_ACCESS (50, spotted Apple Open Directory)
  655. // - LDAP_UNWILLING_TO_PERFORM (53, spotted eDirectory)
  656. if (!in_array($errno, [0, 49, 50, 53], true)) {
  657. $this->ldapConnectionRes = null;
  658. }
  659. return false;
  660. }
  661. return true;
  662. }
  663. }