Connection.php 21 KB

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