Connection.php 23 KB

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