Connection.php 21 KB

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