1
0

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. */
  86. class Connection extends LDAPUtility {
  87. private ?\LDAP\Connection $ldapConnectionRes = null;
  88. private string $configPrefix;
  89. private ?string $configID;
  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 \OCP\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(ILDAPWrapper $ldap, string $configPrefix = '', ?string $configID = 'user_ldap') {
  129. parent::__construct($ldap);
  130. $this->configPrefix = $configPrefix;
  131. $this->configID = $configID;
  132. $this->configuration = new Configuration($configPrefix, !is_null($configID));
  133. $memcache = \OC::$server->getMemCacheFactory();
  134. if ($memcache->isAvailable()) {
  135. $this->cache = $memcache->createDistributed();
  136. }
  137. $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
  138. $this->doNotValidate = !in_array($this->configPrefix,
  139. $helper->getServerConfigurationPrefixes());
  140. $this->logger = \OC::$server->get(LoggerInterface::class);
  141. }
  142. public function __destruct() {
  143. if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
  144. @$this->ldap->unbind($this->ldapConnectionRes);
  145. $this->bindResult = [];
  146. }
  147. }
  148. /**
  149. * defines behaviour when the instance is cloned
  150. */
  151. public function __clone() {
  152. $this->configuration = new Configuration($this->configPrefix,
  153. !is_null($this->configID));
  154. if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
  155. $this->bindResult = [];
  156. }
  157. $this->ldapConnectionRes = null;
  158. $this->dontDestruct = true;
  159. }
  160. public function __get(string $name) {
  161. if (!$this->configured) {
  162. $this->readConfiguration();
  163. }
  164. return $this->configuration->$name;
  165. }
  166. /**
  167. * @param string $name
  168. * @param mixed $value
  169. */
  170. public function __set($name, $value) {
  171. $this->doNotValidate = false;
  172. $before = $this->configuration->$name;
  173. $this->configuration->$name = $value;
  174. $after = $this->configuration->$name;
  175. if ($before !== $after) {
  176. if ($this->configID !== '' && $this->configID !== null) {
  177. $this->configuration->saveConfiguration();
  178. }
  179. $this->validateConfiguration();
  180. }
  181. }
  182. /**
  183. * @param string $rule
  184. * @return array
  185. * @throws \RuntimeException
  186. */
  187. public function resolveRule($rule) {
  188. return $this->configuration->resolveRule($rule);
  189. }
  190. /**
  191. * sets whether the result of the configuration validation shall
  192. * be ignored when establishing the connection. Used by the Wizard
  193. * in early configuration state.
  194. * @param bool $state
  195. */
  196. public function setIgnoreValidation($state) {
  197. $this->ignoreValidation = (bool)$state;
  198. }
  199. /**
  200. * initializes the LDAP backend
  201. * @param bool $force read the config settings no matter what
  202. */
  203. public function init($force = false) {
  204. $this->readConfiguration($force);
  205. $this->establishConnection();
  206. }
  207. /**
  208. * @return \LDAP\Connection The LDAP resource
  209. */
  210. public function getConnectionResource(): \LDAP\Connection {
  211. if (!$this->ldapConnectionRes) {
  212. $this->init();
  213. }
  214. if (is_null($this->ldapConnectionRes)) {
  215. $this->logger->error(
  216. 'No LDAP Connection to server ' . $this->configuration->ldapHost,
  217. ['app' => 'user_ldap']
  218. );
  219. throw new ServerNotAvailableException('Connection to LDAP server could not be established');
  220. }
  221. return $this->ldapConnectionRes;
  222. }
  223. /**
  224. * resets the connection resource
  225. */
  226. public function resetConnectionResource(): void {
  227. if (!is_null($this->ldapConnectionRes)) {
  228. @$this->ldap->unbind($this->ldapConnectionRes);
  229. $this->ldapConnectionRes = null;
  230. $this->bindResult = [];
  231. }
  232. }
  233. /**
  234. * @param string|null $key
  235. */
  236. private function getCacheKey($key): string {
  237. $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
  238. if (is_null($key)) {
  239. return $prefix;
  240. }
  241. return $prefix.hash('sha256', $key);
  242. }
  243. /**
  244. * @param string $key
  245. * @return mixed|null
  246. */
  247. public function getFromCache($key) {
  248. if (!$this->configured) {
  249. $this->readConfiguration();
  250. }
  251. if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
  252. return null;
  253. }
  254. $key = $this->getCacheKey($key);
  255. return json_decode(base64_decode($this->cache->get($key) ?? ''), true);
  256. }
  257. public function getConfigPrefix(): string {
  258. return $this->configPrefix;
  259. }
  260. /**
  261. * @param string $key
  262. * @param mixed $value
  263. */
  264. public function writeToCache($key, $value, ?int $ttlOverride = null): void {
  265. if (!$this->configured) {
  266. $this->readConfiguration();
  267. }
  268. if (is_null($this->cache)
  269. || !$this->configuration->ldapCacheTTL
  270. || !$this->configuration->ldapConfigurationActive) {
  271. return;
  272. }
  273. $key = $this->getCacheKey($key);
  274. $value = base64_encode(json_encode($value));
  275. $ttl = $ttlOverride ?? $this->configuration->ldapCacheTTL;
  276. $this->cache->set($key, $value, $ttl);
  277. }
  278. public function clearCache() {
  279. if (!is_null($this->cache)) {
  280. $this->cache->clear($this->getCacheKey(null));
  281. }
  282. }
  283. /**
  284. * Caches the general LDAP configuration.
  285. * @param bool $force optional. true, if the re-read should be forced. defaults
  286. * to false.
  287. */
  288. private function readConfiguration(bool $force = false): void {
  289. if ((!$this->configured || $force) && !is_null($this->configID)) {
  290. $this->configuration->readConfiguration();
  291. $this->configured = $this->validateConfiguration();
  292. }
  293. }
  294. /**
  295. * set LDAP configuration with values delivered by an array, not read from configuration
  296. * @param array $config array that holds the config parameters in an associated array
  297. * @param array &$setParameters optional; array where the set fields will be given to
  298. * @return bool true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  299. */
  300. public function setConfiguration($config, &$setParameters = null): bool {
  301. if (is_null($setParameters)) {
  302. $setParameters = [];
  303. }
  304. $this->doNotValidate = false;
  305. $this->configuration->setConfiguration($config, $setParameters);
  306. if (count($setParameters) > 0) {
  307. $this->configured = $this->validateConfiguration();
  308. }
  309. return $this->configured;
  310. }
  311. /**
  312. * saves the current Configuration in the database and empties the
  313. * cache
  314. * @return null
  315. */
  316. public function saveConfiguration() {
  317. $this->configuration->saveConfiguration();
  318. $this->clearCache();
  319. }
  320. /**
  321. * get the current LDAP configuration
  322. * @return array
  323. */
  324. public function getConfiguration() {
  325. $this->readConfiguration();
  326. $config = $this->configuration->getConfiguration();
  327. $cta = $this->configuration->getConfigTranslationArray();
  328. $result = [];
  329. foreach ($cta as $dbkey => $configkey) {
  330. switch ($configkey) {
  331. case 'homeFolderNamingRule':
  332. if (str_starts_with($config[$configkey], 'attr:')) {
  333. $result[$dbkey] = substr($config[$configkey], 5);
  334. } else {
  335. $result[$dbkey] = '';
  336. }
  337. break;
  338. case 'ldapBase':
  339. case 'ldapBaseUsers':
  340. case 'ldapBaseGroups':
  341. case 'ldapAttributesForUserSearch':
  342. case 'ldapAttributesForGroupSearch':
  343. if (is_array($config[$configkey])) {
  344. $result[$dbkey] = implode("\n", $config[$configkey]);
  345. break;
  346. } //else follows default
  347. // no break
  348. default:
  349. $result[$dbkey] = $config[$configkey];
  350. }
  351. }
  352. return $result;
  353. }
  354. private function doSoftValidation(): void {
  355. //if User or Group Base are not set, take over Base DN setting
  356. foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
  357. $val = $this->configuration->$keyBase;
  358. if (empty($val)) {
  359. $this->configuration->$keyBase = $this->configuration->ldapBase;
  360. }
  361. }
  362. foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
  363. 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
  364. 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. }