You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection.php 16KB

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