connection.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. /**
  3. * @author Arthur Schiwon <blizzz@owncloud.com>
  4. * @author Bart Visscher <bartv@thisnet.nl>
  5. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  6. * @author Lukas Reschke <lukas@owncloud.com>
  7. * @author Lyonel Vincent <lyonel@ezix.org>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <icewind@owncloud.com>
  10. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  11. * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @copyright Copyright (c) 2015, ownCloud, Inc.
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\user_ldap\lib;
  31. //magic properties (incomplete)
  32. /**
  33. * responsible for LDAP connections in context with the provided configuration
  34. *
  35. * @property string ldapUserFilter
  36. * @property string ldapUserDisplayName
  37. * @property boolean hasPagedResultSupport
  38. * @property string[] ldapBaseUsers
  39. * @property int|string ldapPagingSize holds an integer
  40. * @property bool|mixed|void ldapGroupMemberAssocAttr
  41. */
  42. class Connection extends LDAPUtility {
  43. private $ldapConnectionRes = null;
  44. private $configPrefix;
  45. private $configID;
  46. private $configured = false;
  47. //whether connection should be kept on __destruct
  48. private $dontDestruct = false;
  49. private $hasPagedResultSupport = true;
  50. //cache handler
  51. protected $cache;
  52. //settings handler
  53. protected $configuration;
  54. protected $doNotValidate = false;
  55. protected $ignoreValidation = false;
  56. /**
  57. * Constructor
  58. * @param ILDAPWrapper $ldap
  59. * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
  60. * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
  61. */
  62. public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
  63. parent::__construct($ldap);
  64. $this->configPrefix = $configPrefix;
  65. $this->configID = $configID;
  66. $this->configuration = new Configuration($configPrefix,
  67. !is_null($configID));
  68. $memcache = \OC::$server->getMemCacheFactory();
  69. if($memcache->isAvailable()) {
  70. $this->cache = $memcache->create();
  71. } else {
  72. $this->cache = \OC\Cache::getGlobalCache();
  73. }
  74. $this->hasPagedResultSupport =
  75. $this->ldap->hasPagedResultSupport();
  76. $helper = new Helper();
  77. $this->doNotValidate = !in_array($this->configPrefix,
  78. $helper->getServerConfigurationPrefixes());
  79. }
  80. public function __destruct() {
  81. if(!$this->dontDestruct &&
  82. $this->ldap->isResource($this->ldapConnectionRes)) {
  83. @$this->ldap->unbind($this->ldapConnectionRes);
  84. };
  85. }
  86. /**
  87. * defines behaviour when the instance is cloned
  88. */
  89. public function __clone() {
  90. //a cloned instance inherits the connection resource. It may use it,
  91. //but it may not disconnect it
  92. $this->dontDestruct = true;
  93. $this->configuration = new Configuration($this->configPrefix,
  94. !is_null($this->configID));
  95. }
  96. /**
  97. * @param string $name
  98. * @return bool|mixed|void
  99. */
  100. public function __get($name) {
  101. if(!$this->configured) {
  102. $this->readConfiguration();
  103. }
  104. if($name === 'hasPagedResultSupport') {
  105. return $this->hasPagedResultSupport;
  106. }
  107. return $this->configuration->$name;
  108. }
  109. /**
  110. * @param string $name
  111. * @param mixed $value
  112. */
  113. public function __set($name, $value) {
  114. $this->doNotValidate = false;
  115. $before = $this->configuration->$name;
  116. $this->configuration->$name = $value;
  117. $after = $this->configuration->$name;
  118. if($before !== $after) {
  119. if(!empty($this->configID)) {
  120. $this->configuration->saveConfiguration();
  121. }
  122. $this->validateConfiguration();
  123. }
  124. }
  125. /**
  126. * sets whether the result of the configuration validation shall
  127. * be ignored when establishing the connection. Used by the Wizard
  128. * in early configuration state.
  129. * @param bool $state
  130. */
  131. public function setIgnoreValidation($state) {
  132. $this->ignoreValidation = (bool)$state;
  133. }
  134. /**
  135. * initializes the LDAP backend
  136. * @param bool $force read the config settings no matter what
  137. */
  138. public function init($force = false) {
  139. $this->readConfiguration($force);
  140. $this->establishConnection();
  141. }
  142. /**
  143. * Returns the LDAP handler
  144. */
  145. public function getConnectionResource() {
  146. if(!$this->ldapConnectionRes) {
  147. $this->init();
  148. } else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
  149. $this->ldapConnectionRes = null;
  150. $this->establishConnection();
  151. }
  152. if(is_null($this->ldapConnectionRes)) {
  153. \OCP\Util::writeLog('user_ldap', 'Connection could not be established', \OCP\Util::ERROR);
  154. }
  155. return $this->ldapConnectionRes;
  156. }
  157. /**
  158. * @param string|null $key
  159. * @return string
  160. */
  161. private function getCacheKey($key) {
  162. $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
  163. if(is_null($key)) {
  164. return $prefix;
  165. }
  166. return $prefix.md5($key);
  167. }
  168. /**
  169. * @param string $key
  170. * @return mixed|null
  171. */
  172. public function getFromCache($key) {
  173. if(!$this->configured) {
  174. $this->readConfiguration();
  175. }
  176. if(!$this->configuration->ldapCacheTTL) {
  177. return null;
  178. }
  179. if(!$this->isCached($key)) {
  180. return null;
  181. }
  182. $key = $this->getCacheKey($key);
  183. return unserialize(base64_decode($this->cache->get($key)));
  184. }
  185. /**
  186. * @param string $key
  187. * @return bool
  188. */
  189. public function isCached($key) {
  190. if(!$this->configured) {
  191. $this->readConfiguration();
  192. }
  193. if(!$this->configuration->ldapCacheTTL) {
  194. return false;
  195. }
  196. $key = $this->getCacheKey($key);
  197. return $this->cache->hasKey($key);
  198. }
  199. /**
  200. * @param string $key
  201. * @param mixed $value
  202. */
  203. public function writeToCache($key, $value) {
  204. if(!$this->configured) {
  205. $this->readConfiguration();
  206. }
  207. if(!$this->configuration->ldapCacheTTL
  208. || !$this->configuration->ldapConfigurationActive) {
  209. return null;
  210. }
  211. $key = $this->getCacheKey($key);
  212. $value = base64_encode(serialize($value));
  213. $this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
  214. }
  215. public function clearCache() {
  216. $this->cache->clear($this->getCacheKey(null));
  217. }
  218. /**
  219. * Caches the general LDAP configuration.
  220. * @param bool $force optional. true, if the re-read should be forced. defaults
  221. * to false.
  222. * @return null
  223. */
  224. private function readConfiguration($force = false) {
  225. if((!$this->configured || $force) && !is_null($this->configID)) {
  226. $this->configuration->readConfiguration();
  227. $this->configured = $this->validateConfiguration();
  228. }
  229. }
  230. /**
  231. * set LDAP configuration with values delivered by an array, not read from configuration
  232. * @param array $config array that holds the config parameters in an associated array
  233. * @param array &$setParameters optional; array where the set fields will be given to
  234. * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  235. */
  236. public function setConfiguration($config, &$setParameters = null) {
  237. if(is_null($setParameters)) {
  238. $setParameters = array();
  239. }
  240. $this->doNotValidate = false;
  241. $this->configuration->setConfiguration($config, $setParameters);
  242. if(count($setParameters) > 0) {
  243. $this->configured = $this->validateConfiguration();
  244. }
  245. return $this->configured;
  246. }
  247. /**
  248. * saves the current Configuration in the database and empties the
  249. * cache
  250. * @return null
  251. */
  252. public function saveConfiguration() {
  253. $this->configuration->saveConfiguration();
  254. $this->clearCache();
  255. }
  256. /**
  257. * get the current LDAP configuration
  258. * @return array
  259. */
  260. public function getConfiguration() {
  261. $this->readConfiguration();
  262. $config = $this->configuration->getConfiguration();
  263. $cta = $this->configuration->getConfigTranslationArray();
  264. $result = array();
  265. foreach($cta as $dbkey => $configkey) {
  266. switch($configkey) {
  267. case 'homeFolderNamingRule':
  268. if(strpos($config[$configkey], 'attr:') === 0) {
  269. $result[$dbkey] = substr($config[$configkey], 5);
  270. } else {
  271. $result[$dbkey] = '';
  272. }
  273. break;
  274. case 'ldapBase':
  275. case 'ldapBaseUsers':
  276. case 'ldapBaseGroups':
  277. case 'ldapAttributesForUserSearch':
  278. case 'ldapAttributesForGroupSearch':
  279. if(is_array($config[$configkey])) {
  280. $result[$dbkey] = implode("\n", $config[$configkey]);
  281. break;
  282. } //else follows default
  283. default:
  284. $result[$dbkey] = $config[$configkey];
  285. }
  286. }
  287. return $result;
  288. }
  289. private function doSoftValidation() {
  290. //if User or Group Base are not set, take over Base DN setting
  291. foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
  292. $val = $this->configuration->$keyBase;
  293. if(empty($val)) {
  294. $obj = strpos('Users', $keyBase) !== false ? 'Users' : 'Groups';
  295. \OCP\Util::writeLog('user_ldap',
  296. 'Base tree for '.$obj.
  297. ' is empty, using Base DN',
  298. \OCP\Util::INFO);
  299. $this->configuration->$keyBase = $this->configuration->ldapBase;
  300. }
  301. }
  302. $groupFilter = $this->configuration->ldapGroupFilter;
  303. if(empty($groupFilter)) {
  304. \OCP\Util::writeLog('user_ldap',
  305. 'No group filter is specified, LDAP group '.
  306. 'feature will not be used.',
  307. \OCP\Util::INFO);
  308. }
  309. foreach(array('ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
  310. 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
  311. as $expertSetting => $effectiveSetting) {
  312. $uuidOverride = $this->configuration->$expertSetting;
  313. if(!empty($uuidOverride)) {
  314. $this->configuration->$effectiveSetting = $uuidOverride;
  315. } else {
  316. $uuidAttributes = array('auto', 'entryuuid', 'nsuniqueid',
  317. 'objectguid', 'guid');
  318. if(!in_array($this->configuration->$effectiveSetting,
  319. $uuidAttributes)
  320. && (!is_null($this->configID))) {
  321. $this->configuration->$effectiveSetting = 'auto';
  322. $this->configuration->saveConfiguration();
  323. \OCP\Util::writeLog('user_ldap',
  324. 'Illegal value for the '.
  325. $effectiveSetting.', '.'reset to '.
  326. 'autodetect.', \OCP\Util::INFO);
  327. }
  328. }
  329. }
  330. $backupPort = $this->configuration->ldapBackupPort;
  331. if(empty($backupPort)) {
  332. $this->configuration->backupPort = $this->configuration->ldapPort;
  333. }
  334. //make sure empty search attributes are saved as simple, empty array
  335. $saKeys = array('ldapAttributesForUserSearch',
  336. 'ldapAttributesForGroupSearch');
  337. foreach($saKeys as $key) {
  338. $val = $this->configuration->$key;
  339. if(is_array($val) && count($val) === 1 && empty($val[0])) {
  340. $this->configuration->$key = array();
  341. }
  342. }
  343. if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
  344. && $this->configuration->ldapTLS) {
  345. $this->configuration->ldapTLS = false;
  346. \OCP\Util::writeLog('user_ldap',
  347. 'LDAPS (already using secure connection) and '.
  348. 'TLS do not work together. Switched off TLS.',
  349. \OCP\Util::INFO);
  350. }
  351. }
  352. /**
  353. * @return bool
  354. */
  355. private function doCriticalValidation() {
  356. $configurationOK = true;
  357. $errorStr = 'Configuration Error (prefix '.
  358. strval($this->configPrefix).'): ';
  359. //options that shall not be empty
  360. $options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
  361. 'ldapGroupDisplayName', 'ldapLoginFilter');
  362. foreach($options as $key) {
  363. $val = $this->configuration->$key;
  364. if(empty($val)) {
  365. switch($key) {
  366. case 'ldapHost':
  367. $subj = 'LDAP Host';
  368. break;
  369. case 'ldapPort':
  370. $subj = 'LDAP Port';
  371. break;
  372. case 'ldapUserDisplayName':
  373. $subj = 'LDAP User Display Name';
  374. break;
  375. case 'ldapGroupDisplayName':
  376. $subj = 'LDAP Group Display Name';
  377. break;
  378. case 'ldapLoginFilter':
  379. $subj = 'LDAP Login Filter';
  380. break;
  381. default:
  382. $subj = $key;
  383. break;
  384. }
  385. $configurationOK = false;
  386. \OCP\Util::writeLog('user_ldap',
  387. $errorStr.'No '.$subj.' given!',
  388. \OCP\Util::WARN);
  389. }
  390. }
  391. //combinations
  392. $agent = $this->configuration->ldapAgentName;
  393. $pwd = $this->configuration->ldapAgentPassword;
  394. if((empty($agent) && !empty($pwd)) || (!empty($agent) && empty($pwd))) {
  395. \OCP\Util::writeLog('user_ldap',
  396. $errorStr.'either no password is given for the'.
  397. 'user agent or a password is given, but not an'.
  398. 'LDAP agent.',
  399. \OCP\Util::WARN);
  400. $configurationOK = false;
  401. }
  402. $base = $this->configuration->ldapBase;
  403. $baseUsers = $this->configuration->ldapBaseUsers;
  404. $baseGroups = $this->configuration->ldapBaseGroups;
  405. if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
  406. \OCP\Util::writeLog('user_ldap',
  407. $errorStr.'Not a single Base DN given.',
  408. \OCP\Util::WARN);
  409. $configurationOK = false;
  410. }
  411. if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
  412. === false) {
  413. \OCP\Util::writeLog('user_ldap',
  414. $errorStr.'login filter does not contain %uid '.
  415. 'place holder.',
  416. \OCP\Util::WARN);
  417. $configurationOK = false;
  418. }
  419. return $configurationOK;
  420. }
  421. /**
  422. * Validates the user specified configuration
  423. * @return bool true if configuration seems OK, false otherwise
  424. */
  425. private function validateConfiguration() {
  426. if($this->doNotValidate) {
  427. //don't do a validation if it is a new configuration with pure
  428. //default values. Will be allowed on changes via __set or
  429. //setConfiguration
  430. return false;
  431. }
  432. // first step: "soft" checks: settings that are not really
  433. // necessary, but advisable. If left empty, give an info message
  434. $this->doSoftValidation();
  435. //second step: critical checks. If left empty or filled wrong, mark as
  436. //not configured and give a warning.
  437. return $this->doCriticalValidation();
  438. }
  439. /**
  440. * Connects and Binds to LDAP
  441. */
  442. private function establishConnection() {
  443. if(!$this->configuration->ldapConfigurationActive) {
  444. return null;
  445. }
  446. static $phpLDAPinstalled = true;
  447. if(!$phpLDAPinstalled) {
  448. return false;
  449. }
  450. if(!$this->ignoreValidation && !$this->configured) {
  451. \OCP\Util::writeLog('user_ldap',
  452. 'Configuration is invalid, cannot connect',
  453. \OCP\Util::WARN);
  454. return false;
  455. }
  456. if(!$this->ldapConnectionRes) {
  457. if(!$this->ldap->areLDAPFunctionsAvailable()) {
  458. $phpLDAPinstalled = false;
  459. \OCP\Util::writeLog('user_ldap',
  460. 'function ldap_connect is not available. Make '.
  461. 'sure that the PHP ldap module is installed.',
  462. \OCP\Util::ERROR);
  463. return false;
  464. }
  465. if($this->configuration->turnOffCertCheck) {
  466. if(putenv('LDAPTLS_REQCERT=never')) {
  467. \OCP\Util::writeLog('user_ldap',
  468. 'Turned off SSL certificate validation successfully.',
  469. \OCP\Util::DEBUG);
  470. } else {
  471. \OCP\Util::writeLog('user_ldap',
  472. 'Could not turn off SSL certificate validation.',
  473. \OCP\Util::WARN);
  474. }
  475. }
  476. if(!$this->configuration->ldapOverrideMainServer
  477. && !$this->getFromCache('overrideMainServer')) {
  478. $this->doConnect($this->configuration->ldapHost,
  479. $this->configuration->ldapPort);
  480. $bindStatus = $this->bind();
  481. $error = $this->ldap->isResource($this->ldapConnectionRes) ?
  482. $this->ldap->errno($this->ldapConnectionRes) : -1;
  483. } else {
  484. $bindStatus = false;
  485. $error = null;
  486. }
  487. //if LDAP server is not reachable, try the Backup (Replica!) Server
  488. if((!$bindStatus && ($error !== 0))
  489. || $this->configuration->ldapOverrideMainServer
  490. || $this->getFromCache('overrideMainServer')) {
  491. $this->doConnect($this->configuration->ldapBackupHost,
  492. $this->configuration->ldapBackupPort);
  493. $bindStatus = $this->bind();
  494. if(!$bindStatus && $error === -1) {
  495. //when bind to backup server succeeded and failed to main server,
  496. //skip contacting him until next cache refresh
  497. $this->writeToCache('overrideMainServer', true);
  498. }
  499. }
  500. return $bindStatus;
  501. }
  502. }
  503. /**
  504. * @param string $host
  505. * @param string $port
  506. * @return false|void
  507. */
  508. private function doConnect($host, $port) {
  509. if(empty($host)) {
  510. return false;
  511. }
  512. if(strpos($host, '://') !== false) {
  513. //ldap_connect ignores port parameter when URLs are passed
  514. $host .= ':' . $port;
  515. }
  516. $this->ldapConnectionRes = $this->ldap->connect($host, $port);
  517. if($this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  518. if($this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  519. if($this->configuration->ldapTLS) {
  520. $this->ldap->startTls($this->ldapConnectionRes);
  521. }
  522. }
  523. }
  524. }
  525. /**
  526. * Binds to LDAP
  527. */
  528. public function bind() {
  529. static $getConnectionResourceAttempt = false;
  530. if(!$this->configuration->ldapConfigurationActive) {
  531. return false;
  532. }
  533. if($getConnectionResourceAttempt) {
  534. $getConnectionResourceAttempt = false;
  535. return false;
  536. }
  537. $getConnectionResourceAttempt = true;
  538. $cr = $this->getConnectionResource();
  539. $getConnectionResourceAttempt = false;
  540. if(!$this->ldap->isResource($cr)) {
  541. return false;
  542. }
  543. $ldapLogin = @$this->ldap->bind($cr,
  544. $this->configuration->ldapAgentName,
  545. $this->configuration->ldapAgentPassword);
  546. if(!$ldapLogin) {
  547. \OCP\Util::writeLog('user_ldap',
  548. 'Bind failed: ' . $this->ldap->errno($cr) . ': ' . $this->ldap->error($cr),
  549. \OCP\Util::WARN);
  550. $this->ldapConnectionRes = null;
  551. return false;
  552. }
  553. return true;
  554. }
  555. }