connection.php 16 KB

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