1
0

Connection.php 21 KB

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