Connection.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\User_LDAP;
  8. use OC\ServerNotAvailableException;
  9. use Psr\Log\LoggerInterface;
  10. /**
  11. * magic properties
  12. * responsible for LDAP connections in context with the provided configuration
  13. *
  14. * @property string $ldapHost
  15. * @property string $ldapPort
  16. * @property string $ldapBackupHost
  17. * @property string $ldapBackupPort
  18. * @property string $ldapBackgroundHost
  19. * @property string $ldapBackgroundPort
  20. * @property array|'' $ldapBase
  21. * @property array|'' $ldapBaseUsers
  22. * @property array|'' $ldapBaseGroups
  23. * @property string $ldapAgentName
  24. * @property string $ldapAgentPassword
  25. * @property string $ldapTLS
  26. * @property string $turnOffCertCheck
  27. * @property string $ldapIgnoreNamingRules
  28. * @property string $ldapUserDisplayName
  29. * @property string $ldapUserDisplayName2
  30. * @property string $ldapUserAvatarRule
  31. * @property string $ldapGidNumber
  32. * @property array|'' $ldapUserFilterObjectclass
  33. * @property array|'' $ldapUserFilterGroups
  34. * @property string $ldapUserFilter
  35. * @property string $ldapUserFilterMode
  36. * @property string $ldapGroupFilter
  37. * @property string $ldapGroupFilterMode
  38. * @property array|'' $ldapGroupFilterObjectclass
  39. * @property array|'' $ldapGroupFilterGroups
  40. * @property string $ldapGroupDisplayName
  41. * @property string $ldapGroupMemberAssocAttr
  42. * @property string $ldapLoginFilter
  43. * @property string $ldapLoginFilterMode
  44. * @property string $ldapLoginFilterEmail
  45. * @property string $ldapLoginFilterUsername
  46. * @property array|'' $ldapLoginFilterAttributes
  47. * @property string $ldapQuotaAttribute
  48. * @property string $ldapQuotaDefault
  49. * @property string $ldapEmailAttribute
  50. * @property string $ldapCacheTTL
  51. * @property string $ldapUuidUserAttribute
  52. * @property string $ldapUuidGroupAttribute
  53. * @property string $ldapOverrideMainServer
  54. * @property string $ldapConfigurationActive
  55. * @property array|'' $ldapAttributesForUserSearch
  56. * @property array|'' $ldapAttributesForGroupSearch
  57. * @property string $ldapExperiencedAdmin
  58. * @property string $homeFolderNamingRule
  59. * @property string $hasMemberOfFilterSupport
  60. * @property string $useMemberOfToDetectMembership
  61. * @property string $ldapExpertUsernameAttr
  62. * @property string $ldapExpertUUIDUserAttr
  63. * @property string $ldapExpertUUIDGroupAttr
  64. * @property string $markRemnantsAsDisabled
  65. * @property string $lastJpegPhotoLookup
  66. * @property string $ldapNestedGroups
  67. * @property string $ldapPagingSize
  68. * @property string $turnOnPasswordChange
  69. * @property string $ldapDynamicGroupMemberURL
  70. * @property string $ldapDefaultPPolicyDN
  71. * @property string $ldapExtStorageHomeAttribute
  72. * @property string $ldapMatchingRuleInChainState
  73. * @property string $ldapConnectionTimeout
  74. * @property string $ldapAttributePhone
  75. * @property string $ldapAttributeWebsite
  76. * @property string $ldapAttributeAddress
  77. * @property string $ldapAttributeTwitter
  78. * @property string $ldapAttributeFediverse
  79. * @property string $ldapAttributeOrganisation
  80. * @property string $ldapAttributeRole
  81. * @property string $ldapAttributeHeadline
  82. * @property string $ldapAttributeBiography
  83. * @property string $ldapAdminGroup
  84. * @property string $ldapAttributeBirthDate
  85. * @property string $ldapAttributePronouns
  86. */
  87. class Connection extends LDAPUtility {
  88. private ?\LDAP\Connection $ldapConnectionRes = null;
  89. private string $configPrefix;
  90. private ?string $configID;
  91. private bool $configured = false;
  92. /**
  93. * @var bool whether connection should be kept on __destruct
  94. */
  95. private bool $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 \LDAP\Connection The LDAP resource
  210. */
  211. public function getConnectionResource(): \LDAP\Connection {
  212. if (!$this->ldapConnectionRes) {
  213. $this->init();
  214. }
  215. if (is_null($this->ldapConnectionRes)) {
  216. $this->logger->error(
  217. 'No LDAP Connection to server ' . $this->configuration->ldapHost,
  218. ['app' => 'user_ldap']
  219. );
  220. throw new ServerNotAvailableException('Connection to LDAP server could not be established');
  221. }
  222. return $this->ldapConnectionRes;
  223. }
  224. /**
  225. * resets the connection resource
  226. */
  227. public function resetConnectionResource(): void {
  228. if (!is_null($this->ldapConnectionRes)) {
  229. @$this->ldap->unbind($this->ldapConnectionRes);
  230. $this->ldapConnectionRes = null;
  231. $this->bindResult = [];
  232. }
  233. }
  234. /**
  235. * @param string|null $key
  236. */
  237. private function getCacheKey($key): string {
  238. $prefix = 'LDAP-' . $this->configID . '-' . $this->configPrefix . '-';
  239. if (is_null($key)) {
  240. return $prefix;
  241. }
  242. return $prefix . hash('sha256', $key);
  243. }
  244. /**
  245. * @param string $key
  246. * @return mixed|null
  247. */
  248. public function getFromCache($key) {
  249. if (!$this->configured) {
  250. $this->readConfiguration();
  251. }
  252. if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
  253. return null;
  254. }
  255. $key = $this->getCacheKey($key);
  256. return json_decode(base64_decode($this->cache->get($key) ?? ''), true);
  257. }
  258. public function getConfigPrefix(): string {
  259. return $this->configPrefix;
  260. }
  261. /**
  262. * @param string $key
  263. * @param mixed $value
  264. */
  265. public function writeToCache($key, $value, ?int $ttlOverride = null): void {
  266. if (!$this->configured) {
  267. $this->readConfiguration();
  268. }
  269. if (is_null($this->cache)
  270. || !$this->configuration->ldapCacheTTL
  271. || !$this->configuration->ldapConfigurationActive) {
  272. return;
  273. }
  274. $key = $this->getCacheKey($key);
  275. $value = base64_encode(json_encode($value));
  276. $ttl = $ttlOverride ?? $this->configuration->ldapCacheTTL;
  277. $this->cache->set($key, $value, $ttl);
  278. }
  279. public function clearCache() {
  280. if (!is_null($this->cache)) {
  281. $this->cache->clear($this->getCacheKey(null));
  282. }
  283. }
  284. /**
  285. * Caches the general LDAP configuration.
  286. * @param bool $force optional. true, if the re-read should be forced. defaults
  287. * to false.
  288. */
  289. private function readConfiguration(bool $force = false): void {
  290. if ((!$this->configured || $force) && !is_null($this->configID)) {
  291. $this->configuration->readConfiguration();
  292. $this->configured = $this->validateConfiguration();
  293. }
  294. }
  295. /**
  296. * set LDAP configuration with values delivered by an array, not read from configuration
  297. * @param array $config array that holds the config parameters in an associated array
  298. * @param array &$setParameters optional; array where the set fields will be given to
  299. * @return bool true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  300. */
  301. public function setConfiguration($config, &$setParameters = null): bool {
  302. if (is_null($setParameters)) {
  303. $setParameters = [];
  304. }
  305. $this->doNotValidate = false;
  306. $this->configuration->setConfiguration($config, $setParameters);
  307. if (count($setParameters) > 0) {
  308. $this->configured = $this->validateConfiguration();
  309. }
  310. return $this->configured;
  311. }
  312. /**
  313. * saves the current Configuration in the database and empties the
  314. * cache
  315. * @return null
  316. */
  317. public function saveConfiguration() {
  318. $this->configuration->saveConfiguration();
  319. $this->clearCache();
  320. }
  321. /**
  322. * get the current LDAP configuration
  323. * @return array
  324. */
  325. public function getConfiguration() {
  326. $this->readConfiguration();
  327. $config = $this->configuration->getConfiguration();
  328. $cta = $this->configuration->getConfigTranslationArray();
  329. $result = [];
  330. foreach ($cta as $dbkey => $configkey) {
  331. switch ($configkey) {
  332. case 'homeFolderNamingRule':
  333. if (str_starts_with($config[$configkey], 'attr:')) {
  334. $result[$dbkey] = substr($config[$configkey], 5);
  335. } else {
  336. $result[$dbkey] = '';
  337. }
  338. break;
  339. case 'ldapBase':
  340. case 'ldapBaseUsers':
  341. case 'ldapBaseGroups':
  342. case 'ldapAttributesForUserSearch':
  343. case 'ldapAttributesForGroupSearch':
  344. if (is_array($config[$configkey])) {
  345. $result[$dbkey] = implode("\n", $config[$configkey]);
  346. break;
  347. } //else follows default
  348. // no break
  349. default:
  350. $result[$dbkey] = $config[$configkey];
  351. }
  352. }
  353. return $result;
  354. }
  355. private function doSoftValidation(): void {
  356. //if User or Group Base are not set, take over Base DN setting
  357. foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
  358. $val = $this->configuration->$keyBase;
  359. if (empty($val)) {
  360. $this->configuration->$keyBase = $this->configuration->ldapBase;
  361. }
  362. }
  363. foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
  364. 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] as $expertSetting => $effectiveSetting) {
  365. $uuidOverride = $this->configuration->$expertSetting;
  366. if (!empty($uuidOverride)) {
  367. $this->configuration->$effectiveSetting = $uuidOverride;
  368. } else {
  369. $uuidAttributes = Access::UUID_ATTRIBUTES;
  370. array_unshift($uuidAttributes, 'auto');
  371. if (!in_array($this->configuration->$effectiveSetting, $uuidAttributes)
  372. && !is_null($this->configID)) {
  373. $this->configuration->$effectiveSetting = 'auto';
  374. $this->configuration->saveConfiguration();
  375. $this->logger->info(
  376. 'Illegal value for the ' . $effectiveSetting . ', reset to autodetect.',
  377. ['app' => 'user_ldap']
  378. );
  379. }
  380. }
  381. }
  382. $backupPort = (int)$this->configuration->ldapBackupPort;
  383. if ($backupPort <= 0) {
  384. $this->configuration->ldapBackupPort = $this->configuration->ldapPort;
  385. }
  386. //make sure empty search attributes are saved as simple, empty array
  387. $saKeys = ['ldapAttributesForUserSearch',
  388. 'ldapAttributesForGroupSearch'];
  389. foreach ($saKeys as $key) {
  390. $val = $this->configuration->$key;
  391. if (is_array($val) && count($val) === 1 && empty($val[0])) {
  392. $this->configuration->$key = [];
  393. }
  394. }
  395. if ((stripos((string)$this->configuration->ldapHost, 'ldaps://') === 0)
  396. && $this->configuration->ldapTLS) {
  397. $this->configuration->ldapTLS = (string)false;
  398. $this->logger->info(
  399. 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
  400. ['app' => 'user_ldap']
  401. );
  402. }
  403. }
  404. private function doCriticalValidation(): bool {
  405. $configurationOK = true;
  406. $errorStr = 'Configuration Error (prefix ' . $this->configPrefix . '): ';
  407. //options that shall not be empty
  408. $options = ['ldapHost', 'ldapUserDisplayName',
  409. 'ldapGroupDisplayName', 'ldapLoginFilter'];
  410. //ldapPort should not be empty either unless ldapHost is pointing to a socket
  411. if (!$this->configuration->usesLdapi()) {
  412. $options[] = 'ldapPort';
  413. }
  414. foreach ($options as $key) {
  415. $val = $this->configuration->$key;
  416. if (empty($val)) {
  417. switch ($key) {
  418. case 'ldapHost':
  419. $subj = 'LDAP Host';
  420. break;
  421. case 'ldapPort':
  422. $subj = 'LDAP Port';
  423. break;
  424. case 'ldapUserDisplayName':
  425. $subj = 'LDAP User Display Name';
  426. break;
  427. case 'ldapGroupDisplayName':
  428. $subj = 'LDAP Group Display Name';
  429. break;
  430. case 'ldapLoginFilter':
  431. $subj = 'LDAP Login Filter';
  432. break;
  433. default:
  434. $subj = $key;
  435. break;
  436. }
  437. $configurationOK = false;
  438. $this->logger->warning(
  439. $errorStr . 'No ' . $subj . ' given!',
  440. ['app' => 'user_ldap']
  441. );
  442. }
  443. }
  444. //combinations
  445. $agent = $this->configuration->ldapAgentName;
  446. $pwd = $this->configuration->ldapAgentPassword;
  447. if (
  448. ($agent === '' && $pwd !== '')
  449. || ($agent !== '' && $pwd === '')
  450. ) {
  451. $this->logger->warning(
  452. $errorStr . 'either no password is given for the user ' .
  453. 'agent or a password is given, but not an LDAP agent.',
  454. ['app' => 'user_ldap']
  455. );
  456. $configurationOK = false;
  457. }
  458. $base = $this->configuration->ldapBase;
  459. $baseUsers = $this->configuration->ldapBaseUsers;
  460. $baseGroups = $this->configuration->ldapBaseGroups;
  461. if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
  462. $this->logger->warning(
  463. $errorStr . 'Not a single Base DN given.',
  464. ['app' => 'user_ldap']
  465. );
  466. $configurationOK = false;
  467. }
  468. if (mb_strpos((string)$this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
  469. === false) {
  470. $this->logger->warning(
  471. $errorStr . 'login filter does not contain %uid place holder.',
  472. ['app' => 'user_ldap']
  473. );
  474. $configurationOK = false;
  475. }
  476. return $configurationOK;
  477. }
  478. /**
  479. * Validates the user specified configuration
  480. * @return bool true if configuration seems OK, false otherwise
  481. */
  482. private function validateConfiguration(): bool {
  483. if ($this->doNotValidate) {
  484. //don't do a validation if it is a new configuration with pure
  485. //default values. Will be allowed on changes via __set or
  486. //setConfiguration
  487. return false;
  488. }
  489. // first step: "soft" checks: settings that are not really
  490. // necessary, but advisable. If left empty, give an info message
  491. $this->doSoftValidation();
  492. //second step: critical checks. If left empty or filled wrong, mark as
  493. //not configured and give a warning.
  494. return $this->doCriticalValidation();
  495. }
  496. /**
  497. * Connects and Binds to LDAP
  498. *
  499. * @throws ServerNotAvailableException
  500. */
  501. private function establishConnection(): ?bool {
  502. if (!$this->configuration->ldapConfigurationActive) {
  503. return null;
  504. }
  505. static $phpLDAPinstalled = true;
  506. if (!$phpLDAPinstalled) {
  507. return false;
  508. }
  509. if (!$this->ignoreValidation && !$this->configured) {
  510. $this->logger->warning(
  511. 'Configuration is invalid, cannot connect',
  512. ['app' => 'user_ldap']
  513. );
  514. return false;
  515. }
  516. if (!$this->ldapConnectionRes) {
  517. if (!$this->ldap->areLDAPFunctionsAvailable()) {
  518. $phpLDAPinstalled = false;
  519. $this->logger->error(
  520. 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
  521. ['app' => 'user_ldap']
  522. );
  523. return false;
  524. }
  525. if ($this->configuration->turnOffCertCheck) {
  526. if (putenv('LDAPTLS_REQCERT=never')) {
  527. $this->logger->debug(
  528. 'Turned off SSL certificate validation successfully.',
  529. ['app' => 'user_ldap']
  530. );
  531. } else {
  532. $this->logger->warning(
  533. 'Could not turn off SSL certificate validation.',
  534. ['app' => 'user_ldap']
  535. );
  536. }
  537. }
  538. $hasBackupHost = (trim($this->configuration->ldapBackupHost ?? '') !== '');
  539. $hasBackgroundHost = (trim($this->configuration->ldapBackgroundHost ?? '') !== '');
  540. $useBackgroundHost = (\OC::$CLI && $hasBackgroundHost);
  541. $overrideCacheKey = ($useBackgroundHost ? 'overrideBackgroundServer' : 'overrideMainServer');
  542. $forceBackupHost = ($this->configuration->ldapOverrideMainServer || $this->getFromCache($overrideCacheKey));
  543. $bindStatus = false;
  544. if (!$forceBackupHost) {
  545. try {
  546. $host = $this->configuration->ldapHost ?? '';
  547. $port = $this->configuration->ldapPort ?? '';
  548. if ($useBackgroundHost) {
  549. $host = $this->configuration->ldapBackgroundHost ?? '';
  550. $port = $this->configuration->ldapBackgroundPort ?? '';
  551. }
  552. $this->doConnect($host, $port);
  553. return $this->bind();
  554. } catch (ServerNotAvailableException $e) {
  555. if (!$hasBackupHost) {
  556. throw $e;
  557. }
  558. }
  559. $this->logger->warning(
  560. 'Main LDAP not reachable, connecting to backup',
  561. [
  562. 'app' => 'user_ldap'
  563. ]
  564. );
  565. }
  566. // if LDAP server is not reachable, try the Backup (Replica!) Server
  567. $this->doConnect($this->configuration->ldapBackupHost ?? '', $this->configuration->ldapBackupPort ?? '');
  568. $this->bindResult = [];
  569. $bindStatus = $this->bind();
  570. $error = $this->ldap->isResource($this->ldapConnectionRes) ?
  571. $this->ldap->errno($this->ldapConnectionRes) : -1;
  572. if ($bindStatus && $error === 0 && !$forceBackupHost) {
  573. //when bind to backup server succeeded and failed to main server,
  574. //skip contacting it for 15min
  575. $this->writeToCache($overrideCacheKey, true, 60 * 15);
  576. }
  577. return $bindStatus;
  578. }
  579. return null;
  580. }
  581. /**
  582. * @param string $host
  583. * @param string $port
  584. * @throws \OC\ServerNotAvailableException
  585. */
  586. private function doConnect($host, $port): bool {
  587. if ($host === '') {
  588. return false;
  589. }
  590. $this->ldapConnectionRes = $this->ldap->connect($host, $port) ?: null;
  591. if ($this->ldapConnectionRes === null) {
  592. throw new ServerNotAvailableException('Connection failed');
  593. }
  594. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  595. throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
  596. }
  597. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  598. throw new ServerNotAvailableException('Could not disable LDAP referrals.');
  599. }
  600. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_NETWORK_TIMEOUT, $this->configuration->ldapConnectionTimeout)) {
  601. throw new ServerNotAvailableException('Could not set network timeout');
  602. }
  603. if ($this->configuration->ldapTLS) {
  604. if (!$this->ldap->startTls($this->ldapConnectionRes)) {
  605. throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
  606. }
  607. }
  608. return true;
  609. }
  610. /**
  611. * Binds to LDAP
  612. */
  613. public function bind() {
  614. if (!$this->configuration->ldapConfigurationActive) {
  615. return false;
  616. }
  617. $cr = $this->ldapConnectionRes;
  618. if (!$this->ldap->isResource($cr)) {
  619. $cr = $this->getConnectionResource();
  620. }
  621. if (
  622. count($this->bindResult) !== 0
  623. && $this->bindResult['sum'] === md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword)
  624. ) {
  625. // don't attempt to bind again with the same data as before
  626. // bind might have been invoked via getConnectionResource(),
  627. // but we need results specifically for e.g. user login
  628. return $this->bindResult['result'];
  629. }
  630. $ldapLogin = @$this->ldap->bind($cr,
  631. $this->configuration->ldapAgentName,
  632. $this->configuration->ldapAgentPassword);
  633. $this->bindResult = [
  634. 'sum' => md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword),
  635. 'result' => $ldapLogin,
  636. ];
  637. if (!$ldapLogin) {
  638. $errno = $this->ldap->errno($cr);
  639. $this->logger->warning(
  640. 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
  641. ['app' => 'user_ldap']
  642. );
  643. // Set to failure mode, if LDAP error code is not one of
  644. // - LDAP_SUCCESS (0)
  645. // - LDAP_INVALID_CREDENTIALS (49)
  646. // - LDAP_INSUFFICIENT_ACCESS (50, spotted Apple Open Directory)
  647. // - LDAP_UNWILLING_TO_PERFORM (53, spotted eDirectory)
  648. if (!in_array($errno, [0, 49, 50, 53], true)) {
  649. $this->ldapConnectionRes = null;
  650. }
  651. return false;
  652. }
  653. return true;
  654. }
  655. }