Connection.php 23 KB

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