Connection.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. */
  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. /**
  273. * @param string $key
  274. * @param mixed $value
  275. */
  276. public function writeToCache($key, $value, int $ttlOverride = null): void {
  277. if (!$this->configured) {
  278. $this->readConfiguration();
  279. }
  280. if (is_null($this->cache)
  281. || !$this->configuration->ldapCacheTTL
  282. || !$this->configuration->ldapConfigurationActive) {
  283. return;
  284. }
  285. $key = $this->getCacheKey($key);
  286. $value = base64_encode(json_encode($value));
  287. $ttl = $ttlOverride ?? $this->configuration->ldapCacheTTL;
  288. $this->cache->set($key, $value, $ttl);
  289. }
  290. public function clearCache() {
  291. if (!is_null($this->cache)) {
  292. $this->cache->clear($this->getCacheKey(null));
  293. }
  294. }
  295. /**
  296. * Caches the general LDAP configuration.
  297. * @param bool $force optional. true, if the re-read should be forced. defaults
  298. * to false.
  299. * @return null
  300. */
  301. private function readConfiguration($force = false) {
  302. if ((!$this->configured || $force) && !is_null($this->configID)) {
  303. $this->configuration->readConfiguration();
  304. $this->configured = $this->validateConfiguration();
  305. }
  306. }
  307. /**
  308. * set LDAP configuration with values delivered by an array, not read from configuration
  309. * @param array $config array that holds the config parameters in an associated array
  310. * @param array &$setParameters optional; array where the set fields will be given to
  311. * @return bool true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  312. */
  313. public function setConfiguration($config, &$setParameters = null): bool {
  314. if (is_null($setParameters)) {
  315. $setParameters = [];
  316. }
  317. $this->doNotValidate = false;
  318. $this->configuration->setConfiguration($config, $setParameters);
  319. if (count($setParameters) > 0) {
  320. $this->configured = $this->validateConfiguration();
  321. }
  322. return $this->configured;
  323. }
  324. /**
  325. * saves the current Configuration in the database and empties the
  326. * cache
  327. * @return null
  328. */
  329. public function saveConfiguration() {
  330. $this->configuration->saveConfiguration();
  331. $this->clearCache();
  332. }
  333. /**
  334. * get the current LDAP configuration
  335. * @return array
  336. */
  337. public function getConfiguration() {
  338. $this->readConfiguration();
  339. $config = $this->configuration->getConfiguration();
  340. $cta = $this->configuration->getConfigTranslationArray();
  341. $result = [];
  342. foreach ($cta as $dbkey => $configkey) {
  343. switch ($configkey) {
  344. case 'homeFolderNamingRule':
  345. if (str_starts_with($config[$configkey], 'attr:')) {
  346. $result[$dbkey] = substr($config[$configkey], 5);
  347. } else {
  348. $result[$dbkey] = '';
  349. }
  350. break;
  351. case 'ldapBase':
  352. case 'ldapBaseUsers':
  353. case 'ldapBaseGroups':
  354. case 'ldapAttributesForUserSearch':
  355. case 'ldapAttributesForGroupSearch':
  356. if (is_array($config[$configkey])) {
  357. $result[$dbkey] = implode("\n", $config[$configkey]);
  358. break;
  359. } //else follows default
  360. // no break
  361. default:
  362. $result[$dbkey] = $config[$configkey];
  363. }
  364. }
  365. return $result;
  366. }
  367. private function doSoftValidation() {
  368. //if User or Group Base are not set, take over Base DN setting
  369. foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
  370. $val = $this->configuration->$keyBase;
  371. if (empty($val)) {
  372. $this->configuration->$keyBase = $this->configuration->ldapBase;
  373. }
  374. }
  375. foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
  376. 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
  377. as $expertSetting => $effectiveSetting) {
  378. $uuidOverride = $this->configuration->$expertSetting;
  379. if (!empty($uuidOverride)) {
  380. $this->configuration->$effectiveSetting = $uuidOverride;
  381. } else {
  382. $uuidAttributes = Access::UUID_ATTRIBUTES;
  383. array_unshift($uuidAttributes, 'auto');
  384. if (!in_array($this->configuration->$effectiveSetting, $uuidAttributes)
  385. && !is_null($this->configID)) {
  386. $this->configuration->$effectiveSetting = 'auto';
  387. $this->configuration->saveConfiguration();
  388. $this->logger->info(
  389. 'Illegal value for the '.$effectiveSetting.', reset to autodetect.',
  390. ['app' => 'user_ldap']
  391. );
  392. }
  393. }
  394. }
  395. $backupPort = (int)$this->configuration->ldapBackupPort;
  396. if ($backupPort <= 0) {
  397. $this->configuration->backupPort = $this->configuration->ldapPort;
  398. }
  399. //make sure empty search attributes are saved as simple, empty array
  400. $saKeys = ['ldapAttributesForUserSearch',
  401. 'ldapAttributesForGroupSearch'];
  402. foreach ($saKeys as $key) {
  403. $val = $this->configuration->$key;
  404. if (is_array($val) && count($val) === 1 && empty($val[0])) {
  405. $this->configuration->$key = [];
  406. }
  407. }
  408. if ((stripos((string)$this->configuration->ldapHost, 'ldaps://') === 0)
  409. && $this->configuration->ldapTLS) {
  410. $this->configuration->ldapTLS = false;
  411. $this->logger->info(
  412. 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
  413. ['app' => 'user_ldap']
  414. );
  415. }
  416. }
  417. /**
  418. * @return bool
  419. */
  420. private function doCriticalValidation() {
  421. $configurationOK = true;
  422. $errorStr = 'Configuration Error (prefix '.
  423. (string)$this->configPrefix .'): ';
  424. //options that shall not be empty
  425. $options = ['ldapHost', 'ldapUserDisplayName',
  426. 'ldapGroupDisplayName', 'ldapLoginFilter'];
  427. //ldapPort should not be empty either unless ldapHost is pointing to a socket
  428. if (!$this->configuration->usesLdapi()) {
  429. $options[] = 'ldapPort';
  430. }
  431. foreach ($options as $key) {
  432. $val = $this->configuration->$key;
  433. if (empty($val)) {
  434. switch ($key) {
  435. case 'ldapHost':
  436. $subj = 'LDAP Host';
  437. break;
  438. case 'ldapPort':
  439. $subj = 'LDAP Port';
  440. break;
  441. case 'ldapUserDisplayName':
  442. $subj = 'LDAP User Display Name';
  443. break;
  444. case 'ldapGroupDisplayName':
  445. $subj = 'LDAP Group Display Name';
  446. break;
  447. case 'ldapLoginFilter':
  448. $subj = 'LDAP Login Filter';
  449. break;
  450. default:
  451. $subj = $key;
  452. break;
  453. }
  454. $configurationOK = false;
  455. $this->logger->warning(
  456. $errorStr.'No '.$subj.' given!',
  457. ['app' => 'user_ldap']
  458. );
  459. }
  460. }
  461. //combinations
  462. $agent = $this->configuration->ldapAgentName;
  463. $pwd = $this->configuration->ldapAgentPassword;
  464. if (
  465. ($agent === '' && $pwd !== '')
  466. || ($agent !== '' && $pwd === '')
  467. ) {
  468. $this->logger->warning(
  469. $errorStr.'either no password is given for the user ' .
  470. 'agent or a password is given, but not an LDAP agent.',
  471. ['app' => 'user_ldap']
  472. );
  473. $configurationOK = false;
  474. }
  475. $base = $this->configuration->ldapBase;
  476. $baseUsers = $this->configuration->ldapBaseUsers;
  477. $baseGroups = $this->configuration->ldapBaseGroups;
  478. if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
  479. $this->logger->warning(
  480. $errorStr.'Not a single Base DN given.',
  481. ['app' => 'user_ldap']
  482. );
  483. $configurationOK = false;
  484. }
  485. if (mb_strpos((string)$this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
  486. === false) {
  487. $this->logger->warning(
  488. $errorStr.'login filter does not contain %uid place holder.',
  489. ['app' => 'user_ldap']
  490. );
  491. $configurationOK = false;
  492. }
  493. return $configurationOK;
  494. }
  495. /**
  496. * Validates the user specified configuration
  497. * @return bool true if configuration seems OK, false otherwise
  498. */
  499. private function validateConfiguration() {
  500. if ($this->doNotValidate) {
  501. //don't do a validation if it is a new configuration with pure
  502. //default values. Will be allowed on changes via __set or
  503. //setConfiguration
  504. return false;
  505. }
  506. // first step: "soft" checks: settings that are not really
  507. // necessary, but advisable. If left empty, give an info message
  508. $this->doSoftValidation();
  509. //second step: critical checks. If left empty or filled wrong, mark as
  510. //not configured and give a warning.
  511. return $this->doCriticalValidation();
  512. }
  513. /**
  514. * Connects and Binds to LDAP
  515. *
  516. * @throws ServerNotAvailableException
  517. */
  518. private function establishConnection() {
  519. if (!$this->configuration->ldapConfigurationActive) {
  520. return null;
  521. }
  522. static $phpLDAPinstalled = true;
  523. if (!$phpLDAPinstalled) {
  524. return false;
  525. }
  526. if (!$this->ignoreValidation && !$this->configured) {
  527. $this->logger->warning(
  528. 'Configuration is invalid, cannot connect',
  529. ['app' => 'user_ldap']
  530. );
  531. return false;
  532. }
  533. if (!$this->ldapConnectionRes) {
  534. if (!$this->ldap->areLDAPFunctionsAvailable()) {
  535. $phpLDAPinstalled = false;
  536. $this->logger->error(
  537. 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
  538. ['app' => 'user_ldap']
  539. );
  540. return false;
  541. }
  542. if ($this->configuration->turnOffCertCheck) {
  543. if (putenv('LDAPTLS_REQCERT=never')) {
  544. $this->logger->debug(
  545. 'Turned off SSL certificate validation successfully.',
  546. ['app' => 'user_ldap']
  547. );
  548. } else {
  549. $this->logger->warning(
  550. 'Could not turn off SSL certificate validation.',
  551. ['app' => 'user_ldap']
  552. );
  553. }
  554. }
  555. $hasBackupHost = (trim($this->configuration->ldapBackupHost ?? '') !== '');
  556. $hasBackgroundHost = (trim($this->configuration->ldapBackgroundHost ?? '') !== '');
  557. $useBackgroundHost = (\OC::$CLI && $hasBackgroundHost);
  558. $overrideCacheKey = ($useBackgroundHost ? 'overrideBackgroundServer' : 'overrideMainServer');
  559. $forceBackupHost = ($this->configuration->ldapOverrideMainServer || $this->getFromCache($overrideCacheKey));
  560. $bindStatus = false;
  561. if (!$forceBackupHost) {
  562. try {
  563. $host = $this->configuration->ldapHost ?? '';
  564. $port = $this->configuration->ldapPort ?? '';
  565. if ($useBackgroundHost) {
  566. $host = $this->configuration->ldapBackgroundHost ?? '';
  567. $port = $this->configuration->ldapBackgroundPort ?? '';
  568. }
  569. $this->doConnect($host, $port);
  570. return $this->bind();
  571. } catch (ServerNotAvailableException $e) {
  572. if (!$hasBackupHost) {
  573. throw $e;
  574. }
  575. }
  576. $this->logger->warning(
  577. 'Main LDAP not reachable, connecting to backup',
  578. [
  579. 'app' => 'user_ldap'
  580. ]
  581. );
  582. }
  583. // if LDAP server is not reachable, try the Backup (Replica!) Server
  584. $this->doConnect($this->configuration->ldapBackupHost ?? '', $this->configuration->ldapBackupPort ?? '');
  585. $this->bindResult = [];
  586. $bindStatus = $this->bind();
  587. $error = $this->ldap->isResource($this->ldapConnectionRes) ?
  588. $this->ldap->errno($this->ldapConnectionRes) : -1;
  589. if ($bindStatus && $error === 0 && !$forceBackupHost) {
  590. //when bind to backup server succeeded and failed to main server,
  591. //skip contacting it for 15min
  592. $this->writeToCache($overrideCacheKey, true, 60 * 15);
  593. }
  594. return $bindStatus;
  595. }
  596. return null;
  597. }
  598. /**
  599. * @param string $host
  600. * @param string $port
  601. * @return bool
  602. * @throws \OC\ServerNotAvailableException
  603. */
  604. private function doConnect($host, $port) {
  605. if ($host === '') {
  606. return false;
  607. }
  608. $this->ldapConnectionRes = $this->ldap->connect($host, $port);
  609. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  610. throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
  611. }
  612. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  613. throw new ServerNotAvailableException('Could not disable LDAP referrals.');
  614. }
  615. if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_NETWORK_TIMEOUT, $this->configuration->ldapConnectionTimeout)) {
  616. throw new ServerNotAvailableException('Could not set network timeout');
  617. }
  618. if ($this->configuration->ldapTLS) {
  619. if (!$this->ldap->startTls($this->ldapConnectionRes)) {
  620. throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
  621. }
  622. }
  623. return true;
  624. }
  625. /**
  626. * Binds to LDAP
  627. */
  628. public function bind() {
  629. if (!$this->configuration->ldapConfigurationActive) {
  630. return false;
  631. }
  632. $cr = $this->ldapConnectionRes;
  633. if (!$this->ldap->isResource($cr)) {
  634. $cr = $this->getConnectionResource();
  635. }
  636. if (
  637. count($this->bindResult) !== 0
  638. && $this->bindResult['sum'] === md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword)
  639. ) {
  640. // don't attempt to bind again with the same data as before
  641. // bind might have been invoked via getConnectionResource(),
  642. // but we need results specifically for e.g. user login
  643. return $this->bindResult['result'];
  644. }
  645. $ldapLogin = @$this->ldap->bind($cr,
  646. $this->configuration->ldapAgentName,
  647. $this->configuration->ldapAgentPassword);
  648. $this->bindResult = [
  649. 'sum' => md5($this->configuration->ldapAgentName . $this->configPrefix . $this->configuration->ldapAgentPassword),
  650. 'result' => $ldapLogin,
  651. ];
  652. if (!$ldapLogin) {
  653. $errno = $this->ldap->errno($cr);
  654. $this->logger->warning(
  655. 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
  656. ['app' => 'user_ldap']
  657. );
  658. // Set to failure mode, if LDAP error code is not one of
  659. // - LDAP_SUCCESS (0)
  660. // - LDAP_INVALID_CREDENTIALS (49)
  661. // - LDAP_INSUFFICIENT_ACCESS (50, spotted Apple Open Directory)
  662. // - LDAP_UNWILLING_TO_PERFORM (53, spotted eDirectory)
  663. if (!in_array($errno, [0, 49, 50, 53], true)) {
  664. $this->ldapConnectionRes = null;
  665. }
  666. return false;
  667. }
  668. return true;
  669. }
  670. }