Connection.php 21 KB

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