connection.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. <?php
  2. /**
  3. * ownCloud – LDAP Access
  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. //cache handler
  31. protected $cache;
  32. //settings
  33. protected $config = array(
  34. 'ldapHost' => null,
  35. 'ldapPort' => null,
  36. 'ldapBackupHost' => null,
  37. 'ldapBackupPort' => null,
  38. 'ldapBase' => null,
  39. 'ldapBaseUsers' => null,
  40. 'ldapBaseGroups' => null,
  41. 'ldapAgentName' => null,
  42. 'ldapAgentPassword' => null,
  43. 'ldapTLS' => null,
  44. 'ldapNoCase' => null,
  45. 'turnOffCertCheck' => null,
  46. 'ldapIgnoreNamingRules' => null,
  47. 'ldapUserDisplayName' => null,
  48. 'ldapUserFilter' => null,
  49. 'ldapGroupFilter' => null,
  50. 'ldapGroupDisplayName' => null,
  51. 'ldapGroupMemberAssocAttr' => null,
  52. 'ldapLoginFilter' => null,
  53. 'ldapQuotaAttribute' => null,
  54. 'ldapQuotaDefault' => null,
  55. 'ldapEmailAttribute' => null,
  56. 'ldapCacheTTL' => null,
  57. 'ldapUuidUserAttribute' => 'auto',
  58. 'ldapUuidGroupAttribute' => 'auto',
  59. 'ldapOverrideUuidAttribute' => null,
  60. 'ldapOverrideMainServer' => false,
  61. 'ldapConfigurationActive' => false,
  62. 'ldapAttributesForUserSearch' => null,
  63. 'ldapAttributesForGroupSearch' => null,
  64. 'homeFolderNamingRule' => null,
  65. 'hasPagedResultSupport' => false,
  66. 'ldapExpertUsernameAttr' => null,
  67. 'ldapExpertUUIDUserAttr' => null,
  68. 'ldapExpertUUIDGroupAttr' => null,
  69. );
  70. /**
  71. * @brief Constructor
  72. * @param $configPrefix a string with the prefix for the configkey column (appconfig table)
  73. * @param $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
  74. */
  75. public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
  76. parent::__construct($ldap);
  77. $this->configPrefix = $configPrefix;
  78. $this->configID = $configID;
  79. $memcache = new \OC\Memcache\Factory();
  80. if($memcache->isAvailable()) {
  81. $this->cache = $memcache->create();
  82. } else {
  83. $this->cache = \OC_Cache::getGlobalCache();
  84. }
  85. $this->config['hasPagedResultSupport'] =
  86. $this->ldap->hasPagedResultSupport();
  87. }
  88. public function __destruct() {
  89. if(!$this->dontDestruct &&
  90. $this->ldap->isResource($this->ldapConnectionRes)) {
  91. @$this->ldap->unbind($this->ldapConnectionRes);
  92. };
  93. }
  94. /**
  95. * @brief defines behaviour when the instance is cloned
  96. */
  97. public function __clone() {
  98. //a cloned instance inherits the connection resource. It may use it,
  99. //but it may not disconnect it
  100. $this->dontDestruct = true;
  101. }
  102. public function __get($name) {
  103. if(!$this->configured) {
  104. $this->readConfiguration();
  105. }
  106. if(isset($this->config[$name])) {
  107. return $this->config[$name];
  108. }
  109. }
  110. public function __set($name, $value) {
  111. $changed = false;
  112. //only few options are writable
  113. if($name === 'ldapUuidUserAttribute' || $name === 'ldapUuidGroupAttribute') {
  114. \OCP\Util::writeLog('user_ldap', 'Set config '.$name.' to '.$value, \OCP\Util::DEBUG);
  115. $this->config[$name] = $value;
  116. if(!empty($this->configID)) {
  117. \OCP\Config::setAppValue($this->configID, $this->configPrefix.$name, $value);
  118. }
  119. $changed = true;
  120. }
  121. if($changed) {
  122. $this->validateConfiguration();
  123. }
  124. }
  125. /**
  126. * @brief initializes the LDAP backend
  127. * @param $force read the config settings no matter what
  128. *
  129. * initializes the LDAP backend
  130. */
  131. public function init($force = false) {
  132. $this->readConfiguration($force);
  133. $this->establishConnection();
  134. }
  135. /**
  136. * Returns the LDAP handler
  137. */
  138. public function getConnectionResource() {
  139. if(!$this->ldapConnectionRes) {
  140. $this->init();
  141. } else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
  142. $this->ldapConnectionRes = null;
  143. $this->establishConnection();
  144. }
  145. if(is_null($this->ldapConnectionRes)) {
  146. \OCP\Util::writeLog('user_ldap', 'Connection could not be established', \OCP\Util::ERROR);
  147. }
  148. return $this->ldapConnectionRes;
  149. }
  150. private function getCacheKey($key) {
  151. $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
  152. if(is_null($key)) {
  153. return $prefix;
  154. }
  155. return $prefix.md5($key);
  156. }
  157. public function getFromCache($key) {
  158. if(!$this->configured) {
  159. $this->readConfiguration();
  160. }
  161. if(!$this->config['ldapCacheTTL']) {
  162. return null;
  163. }
  164. if(!$this->isCached($key)) {
  165. return null;
  166. }
  167. $key = $this->getCacheKey($key);
  168. return unserialize(base64_decode($this->cache->get($key)));
  169. }
  170. public function isCached($key) {
  171. if(!$this->configured) {
  172. $this->readConfiguration();
  173. }
  174. if(!$this->config['ldapCacheTTL']) {
  175. return false;
  176. }
  177. $key = $this->getCacheKey($key);
  178. return $this->cache->hasKey($key);
  179. }
  180. public function writeToCache($key, $value) {
  181. if(!$this->configured) {
  182. $this->readConfiguration();
  183. }
  184. if(!$this->config['ldapCacheTTL']
  185. || !$this->config['ldapConfigurationActive']) {
  186. return null;
  187. }
  188. $key = $this->getCacheKey($key);
  189. $value = base64_encode(serialize($value));
  190. $this->cache->set($key, $value, $this->config['ldapCacheTTL']);
  191. }
  192. public function clearCache() {
  193. $this->cache->clear($this->getCacheKey(null));
  194. }
  195. private function getValue($varname) {
  196. static $defaults;
  197. if(is_null($defaults)) {
  198. $defaults = $this->getDefaults();
  199. }
  200. return \OCP\Config::getAppValue($this->configID,
  201. $this->configPrefix.$varname,
  202. $defaults[$varname]);
  203. }
  204. private function setValue($varname, $value) {
  205. \OCP\Config::setAppValue($this->configID,
  206. $this->configPrefix.$varname,
  207. $value);
  208. }
  209. /**
  210. * Special handling for reading Base Configuration
  211. *
  212. * @param $base the internal name of the config key
  213. * @param $value the value stored for the base
  214. */
  215. private function readBase($base, $value) {
  216. if(empty($value)) {
  217. $value = '';
  218. } else {
  219. $value = preg_split('/\r\n|\r|\n/', $value);
  220. }
  221. $this->config[$base] = $value;
  222. }
  223. /**
  224. * Caches the general LDAP configuration.
  225. */
  226. private function readConfiguration($force = false) {
  227. if((!$this->configured || $force) && !is_null($this->configID)) {
  228. $v = 'getValue';
  229. $this->config['ldapHost'] = $this->$v('ldap_host');
  230. $this->config['ldapBackupHost'] = $this->$v('ldap_backup_host');
  231. $this->config['ldapPort'] = $this->$v('ldap_port');
  232. $this->config['ldapBackupPort'] = $this->$v('ldap_backup_port');
  233. $this->config['ldapOverrideMainServer']
  234. = $this->$v('ldap_override_main_server');
  235. $this->config['ldapAgentName'] = $this->$v('ldap_dn');
  236. $this->config['ldapAgentPassword']
  237. = base64_decode($this->$v('ldap_agent_password'));
  238. $this->readBase('ldapBase', $this->$v('ldap_base'));
  239. $this->readBase('ldapBaseUsers', $this->$v('ldap_base_users'));
  240. $this->readBase('ldapBaseGroups', $this->$v('ldap_base_groups'));
  241. $this->config['ldapTLS'] = $this->$v('ldap_tls');
  242. $this->config['ldapNoCase'] = $this->$v('ldap_nocase');
  243. $this->config['turnOffCertCheck']
  244. = $this->$v('ldap_turn_off_cert_check');
  245. $this->config['ldapUserDisplayName']
  246. = mb_strtolower($this->$v('ldap_display_name'), 'UTF-8');
  247. $this->config['ldapUserFilter']
  248. = $this->$v('ldap_userlist_filter');
  249. $this->config['ldapGroupFilter'] = $this->$v('ldap_group_filter');
  250. $this->config['ldapLoginFilter'] = $this->$v('ldap_login_filter');
  251. $this->config['ldapGroupDisplayName']
  252. = mb_strtolower($this->$v('ldap_group_display_name'), 'UTF-8');
  253. $this->config['ldapQuotaAttribute']
  254. = $this->$v('ldap_quota_attr');
  255. $this->config['ldapQuotaDefault']
  256. = $this->$v('ldap_quota_def');
  257. $this->config['ldapEmailAttribute']
  258. = $this->$v('ldap_email_attr');
  259. $this->config['ldapGroupMemberAssocAttr']
  260. = $this->$v('ldap_group_member_assoc_attribute');
  261. $this->config['ldapIgnoreNamingRules']
  262. = \OCP\Config::getSystemValue('ldapIgnoreNamingRules', false);
  263. $this->config['ldapCacheTTL'] = $this->$v('ldap_cache_ttl');
  264. $this->config['ldapUuidUserAttribute']
  265. = $this->$v('ldap_uuid_user_attribute');
  266. $this->config['ldapUuidGroupAttribute']
  267. = $this->$v('ldap_uuid_group_attribute');
  268. $this->config['ldapOverrideUuidAttribute']
  269. = $this->$v('ldap_override_uuid_attribute');
  270. $this->config['homeFolderNamingRule']
  271. = $this->$v('home_folder_naming_rule');
  272. $this->config['ldapConfigurationActive']
  273. = $this->$v('ldap_configuration_active');
  274. $this->config['ldapAttributesForUserSearch']
  275. = preg_split('/\r\n|\r|\n/', $this->$v('ldap_attributes_for_user_search'));
  276. $this->config['ldapAttributesForGroupSearch']
  277. = preg_split('/\r\n|\r|\n/', $this->$v('ldap_attributes_for_group_search'));
  278. $this->config['ldapExpertUsernameAttr']
  279. = $this->$v('ldap_expert_username_attr');
  280. $this->config['ldapExpertUUIDUserAttr']
  281. = $this->$v('ldap_expert_uuid_user_attr');
  282. $this->config['ldapExpertUUIDGroupAttr']
  283. = $this->$v('ldap_expert_uuid_group_attr');
  284. $this->configured = $this->validateConfiguration();
  285. }
  286. }
  287. /**
  288. * @return returns an array that maps internal variable names to database fields
  289. */
  290. private function getConfigTranslationArray() {
  291. static $array = array(
  292. 'ldap_host'=>'ldapHost',
  293. 'ldap_port'=>'ldapPort',
  294. 'ldap_backup_host'=>'ldapBackupHost',
  295. 'ldap_backup_port'=>'ldapBackupPort',
  296. 'ldap_override_main_server' => 'ldapOverrideMainServer',
  297. 'ldap_dn'=>'ldapAgentName',
  298. 'ldap_agent_password'=>'ldapAgentPassword',
  299. 'ldap_base'=>'ldapBase',
  300. 'ldap_base_users'=>'ldapBaseUsers',
  301. 'ldap_base_groups'=>'ldapBaseGroups',
  302. 'ldap_userlist_filter'=>'ldapUserFilter',
  303. 'ldap_login_filter'=>'ldapLoginFilter',
  304. 'ldap_group_filter'=>'ldapGroupFilter',
  305. 'ldap_display_name'=>'ldapUserDisplayName',
  306. 'ldap_group_display_name'=>'ldapGroupDisplayName',
  307. 'ldap_tls'=>'ldapTLS',
  308. 'ldap_nocase'=>'ldapNoCase',
  309. 'ldap_quota_def'=>'ldapQuotaDefault',
  310. 'ldap_quota_attr'=>'ldapQuotaAttribute',
  311. 'ldap_email_attr'=>'ldapEmailAttribute',
  312. 'ldap_group_member_assoc_attribute'=>'ldapGroupMemberAssocAttr',
  313. 'ldap_cache_ttl'=>'ldapCacheTTL',
  314. 'home_folder_naming_rule' => 'homeFolderNamingRule',
  315. 'ldap_turn_off_cert_check' => 'turnOffCertCheck',
  316. 'ldap_configuration_active' => 'ldapConfigurationActive',
  317. 'ldap_attributes_for_user_search' => 'ldapAttributesForUserSearch',
  318. 'ldap_attributes_for_group_search' => 'ldapAttributesForGroupSearch',
  319. 'ldap_expert_username_attr' => 'ldapExpertUsernameAttr',
  320. 'ldap_expert_uuid_user_attr' => 'ldapExpertUUIDUserAttr',
  321. 'ldap_expert_uuid_group_attr' => 'ldapExpertUUIDGroupAttr',
  322. );
  323. return $array;
  324. }
  325. /**
  326. * @brief set LDAP configuration with values delivered by an array, not read from configuration
  327. * @param $config array that holds the config parameters in an associated array
  328. * @param &$setParameters optional; array where the set fields will be given to
  329. * @return true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  330. */
  331. public function setConfiguration($config, &$setParameters = null) {
  332. if(!is_array($config)) {
  333. return false;
  334. }
  335. $params = $this->getConfigTranslationArray();
  336. foreach($config as $parameter => $value) {
  337. if(($parameter === 'homeFolderNamingRule'
  338. || (isset($params[$parameter])
  339. && $params[$parameter] === 'homeFolderNamingRule'))
  340. && !empty($value)) {
  341. $value = 'attr:'.$value;
  342. } else if (strpos($parameter, 'ldapBase') !== false
  343. || (isset($params[$parameter])
  344. && strpos($params[$parameter], 'ldapBase') !== false)) {
  345. $this->readBase($params[$parameter], $value);
  346. if(is_array($setParameters)) {
  347. $setParameters[] = $parameter;
  348. }
  349. continue;
  350. }
  351. if(isset($this->config[$parameter])) {
  352. $this->config[$parameter] = $value;
  353. if(is_array($setParameters)) {
  354. $setParameters[] = $parameter;
  355. }
  356. } else if(isset($params[$parameter])) {
  357. $this->config[$params[$parameter]] = $value;
  358. if(is_array($setParameters)) {
  359. $setParameters[] = $params[$parameter];
  360. }
  361. }
  362. }
  363. $this->configured = $this->validateConfiguration();
  364. return $this->configured;
  365. }
  366. /**
  367. * @brief saves the current Configuration in the database
  368. */
  369. public function saveConfiguration() {
  370. $trans = array_flip($this->getConfigTranslationArray());
  371. foreach($this->config as $key => $value) {
  372. \OCP\Util::writeLog('user_ldap', 'LDAP: storing key '.$key.
  373. ' value '.print_r($value, true), \OCP\Util::DEBUG);
  374. switch ($key) {
  375. case 'ldapAgentPassword':
  376. $value = base64_encode($value);
  377. break;
  378. case 'ldapBase':
  379. case 'ldapBaseUsers':
  380. case 'ldapBaseGroups':
  381. case 'ldapAttributesForUserSearch':
  382. case 'ldapAttributesForGroupSearch':
  383. if(is_array($value)) {
  384. $value = implode("\n", $value);
  385. }
  386. break;
  387. case 'ldapIgnoreNamingRules':
  388. case 'ldapOverrideUuidAttribute':
  389. case 'ldapUuidUserAttribute':
  390. case 'ldapUuidGroupAttribute':
  391. case 'hasPagedResultSupport':
  392. continue 2;
  393. }
  394. if(is_null($value)) {
  395. $value = '';
  396. }
  397. $this->setValue($trans[$key], $value);
  398. }
  399. $this->clearCache();
  400. }
  401. /**
  402. * @brief get the current LDAP configuration
  403. * @return array
  404. */
  405. public function getConfiguration() {
  406. $this->readConfiguration();
  407. $trans = $this->getConfigTranslationArray();
  408. $config = array();
  409. foreach($trans as $dbKey => $classKey) {
  410. if($classKey === 'homeFolderNamingRule') {
  411. if(strpos($this->config[$classKey], 'attr:') === 0) {
  412. $config[$dbKey] = substr($this->config[$classKey], 5);
  413. } else {
  414. $config[$dbKey] = '';
  415. }
  416. continue;
  417. } else if((strpos($classKey, 'ldapBase') !== false
  418. || strpos($classKey, 'ldapAttributes') !== false)
  419. && is_array($this->config[$classKey])) {
  420. $config[$dbKey] = implode("\n", $this->config[$classKey]);
  421. continue;
  422. }
  423. $config[$dbKey] = $this->config[$classKey];
  424. }
  425. return $config;
  426. }
  427. /**
  428. * @brief Validates the user specified configuration
  429. * @returns true if configuration seems OK, false otherwise
  430. */
  431. private function validateConfiguration() {
  432. // first step: "soft" checks: settings that are not really
  433. // necessary, but advisable. If left empty, give an info message
  434. if(empty($this->config['ldapBaseUsers'])) {
  435. \OCP\Util::writeLog('user_ldap', 'Base tree for Users is empty, using Base DN', \OCP\Util::INFO);
  436. $this->config['ldapBaseUsers'] = $this->config['ldapBase'];
  437. }
  438. if(empty($this->config['ldapBaseGroups'])) {
  439. \OCP\Util::writeLog('user_ldap', 'Base tree for Groups is empty, using Base DN', \OCP\Util::INFO);
  440. $this->config['ldapBaseGroups'] = $this->config['ldapBase'];
  441. }
  442. if(empty($this->config['ldapGroupFilter']) && empty($this->config['ldapGroupMemberAssocAttr'])) {
  443. \OCP\Util::writeLog('user_ldap',
  444. 'No group filter is specified, LDAP group feature will not be used.',
  445. \OCP\Util::INFO);
  446. }
  447. $uuidAttributes = array(
  448. 'auto', 'entryuuid', 'nsuniqueid', 'objectguid', 'guid');
  449. $uuidSettings = array(
  450. 'ldapUuidUserAttribute' => 'ldapExpertUUIDUserAttr',
  451. 'ldapUuidGroupAttribute' => 'ldapExpertUUIDGroupAttr');
  452. $cta = array_flip($this->getConfigTranslationArray());
  453. foreach($uuidSettings as $defaultKey => $overrideKey) {
  454. if( !in_array($this->config[$defaultKey], $uuidAttributes)
  455. && is_null($this->config[$overrideKey])
  456. && !is_null($this->configID)) {
  457. \OCP\Config::setAppValue($this->configID,
  458. $this->configPrefix.$cta[$defaultKey],
  459. 'auto');
  460. \OCP\Util::writeLog('user_ldap',
  461. 'Illegal value for'.$defaultKey.', reset to autodetect.',
  462. \OCP\Util::DEBUG);
  463. }
  464. }
  465. if(empty($this->config['ldapBackupPort'])) {
  466. //force default
  467. $this->config['ldapBackupPort'] = $this->config['ldapPort'];
  468. }
  469. foreach(array('ldapAttributesForUserSearch', 'ldapAttributesForGroupSearch') as $key) {
  470. if(is_array($this->config[$key])
  471. && count($this->config[$key]) === 1
  472. && empty($this->config[$key][0])) {
  473. $this->config[$key] = array();
  474. }
  475. }
  476. if((strpos($this->config['ldapHost'], 'ldaps') === 0)
  477. && $this->config['ldapTLS']) {
  478. $this->config['ldapTLS'] = false;
  479. \OCP\Util::writeLog('user_ldap',
  480. 'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
  481. \OCP\Util::INFO);
  482. }
  483. //second step: critical checks. If left empty or filled wrong, set as unconfigured and give a warning.
  484. $configurationOK = true;
  485. if(empty($this->config['ldapHost'])) {
  486. \OCP\Util::writeLog('user_ldap', 'No LDAP host given, won`t connect.', \OCP\Util::WARN);
  487. $configurationOK = false;
  488. }
  489. if(empty($this->config['ldapPort'])) {
  490. \OCP\Util::writeLog('user_ldap', 'No LDAP Port given, won`t connect.', \OCP\Util::WARN);
  491. $configurationOK = false;
  492. }
  493. if((empty($this->config['ldapAgentName']) && !empty($this->config['ldapAgentPassword']))
  494. || (!empty($this->config['ldapAgentName']) && empty($this->config['ldapAgentPassword']))) {
  495. \OCP\Util::writeLog('user_ldap',
  496. 'Either no password given for the user agent or a password is given, but no LDAP agent; won`t connect.',
  497. \OCP\Util::WARN);
  498. $configurationOK = false;
  499. }
  500. //TODO: check if ldapAgentName is in DN form
  501. if(empty($this->config['ldapBase'])
  502. && (empty($this->config['ldapBaseUsers'])
  503. && empty($this->config['ldapBaseGroups']))) {
  504. \OCP\Util::writeLog('user_ldap', 'No Base DN given, won`t connect.', \OCP\Util::WARN);
  505. $configurationOK = false;
  506. }
  507. if(empty($this->config['ldapUserDisplayName'])) {
  508. \OCP\Util::writeLog('user_ldap',
  509. 'No user display name attribute specified, won`t connect.',
  510. \OCP\Util::WARN);
  511. $configurationOK = false;
  512. }
  513. if(empty($this->config['ldapGroupDisplayName'])) {
  514. \OCP\Util::writeLog('user_ldap',
  515. 'No group display name attribute specified, won`t connect.',
  516. \OCP\Util::WARN);
  517. $configurationOK = false;
  518. }
  519. if(empty($this->config['ldapLoginFilter'])) {
  520. \OCP\Util::writeLog('user_ldap', 'No login filter specified, won`t connect.', \OCP\Util::WARN);
  521. $configurationOK = false;
  522. }
  523. if(mb_strpos($this->config['ldapLoginFilter'], '%uid', 0, 'UTF-8') === false) {
  524. \OCP\Util::writeLog('user_ldap',
  525. 'Login filter does not contain %uid place holder, won`t connect.',
  526. \OCP\Util::WARN);
  527. \OCP\Util::writeLog('user_ldap', 'Login filter was ' . $this->config['ldapLoginFilter'], \OCP\Util::DEBUG);
  528. $configurationOK = false;
  529. }
  530. if(!empty($this->config['ldapExpertUUIDUserAttr'])) {
  531. $this->config['ldapUuidUserAttribute'] = $this->config['ldapExpertUUIDUserAttr'];
  532. }
  533. if(!empty($this->config['ldapExpertUUIDGroupAttr'])) {
  534. $this->config['ldapUuidGroupAttribute'] = $this->config['ldapExpertUUIDGroupAttr'];
  535. }
  536. return $configurationOK;
  537. }
  538. /**
  539. * @returns an associative array with the default values. Keys are correspond
  540. * to config-value entries in the database table
  541. */
  542. static public function getDefaults() {
  543. return array(
  544. 'ldap_host' => '',
  545. 'ldap_port' => '389',
  546. 'ldap_backup_host' => '',
  547. 'ldap_backup_port' => '',
  548. 'ldap_override_main_server' => '',
  549. 'ldap_dn' => '',
  550. 'ldap_agent_password' => '',
  551. 'ldap_base' => '',
  552. 'ldap_base_users' => '',
  553. 'ldap_base_groups' => '',
  554. 'ldap_userlist_filter' => 'objectClass=person',
  555. 'ldap_login_filter' => 'uid=%uid',
  556. 'ldap_group_filter' => 'objectClass=posixGroup',
  557. 'ldap_display_name' => 'cn',
  558. 'ldap_group_display_name' => 'cn',
  559. 'ldap_tls' => 1,
  560. 'ldap_nocase' => 0,
  561. 'ldap_quota_def' => '',
  562. 'ldap_quota_attr' => '',
  563. 'ldap_email_attr' => '',
  564. 'ldap_group_member_assoc_attribute' => 'uniqueMember',
  565. 'ldap_cache_ttl' => 600,
  566. 'ldap_uuid_user_attribute' => 'auto',
  567. 'ldap_uuid_group_attribute' => 'auto',
  568. 'ldap_override_uuid_attribute' => 0,
  569. 'home_folder_naming_rule' => '',
  570. 'ldap_turn_off_cert_check' => 0,
  571. 'ldap_configuration_active' => 1,
  572. 'ldap_attributes_for_user_search' => '',
  573. 'ldap_attributes_for_group_search' => '',
  574. 'ldap_expert_username_attr' => '',
  575. 'ldap_expert_uuid_user_attr' => '',
  576. 'ldap_expert_uuid_group_attr' => '',
  577. );
  578. }
  579. /**
  580. * Connects and Binds to LDAP
  581. */
  582. private function establishConnection() {
  583. if(!$this->config['ldapConfigurationActive']) {
  584. return null;
  585. }
  586. static $phpLDAPinstalled = true;
  587. if(!$phpLDAPinstalled) {
  588. return false;
  589. }
  590. if(!$this->configured) {
  591. \OCP\Util::writeLog('user_ldap', 'Configuration is invalid, cannot connect', \OCP\Util::WARN);
  592. return false;
  593. }
  594. if(!$this->ldapConnectionRes) {
  595. if(!$this->ldap->areLDAPFunctionsAvailable()) {
  596. $phpLDAPinstalled = false;
  597. \OCP\Util::writeLog('user_ldap',
  598. 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
  599. \OCP\Util::ERROR);
  600. return false;
  601. }
  602. if($this->config['turnOffCertCheck']) {
  603. if(putenv('LDAPTLS_REQCERT=never')) {
  604. \OCP\Util::writeLog('user_ldap',
  605. 'Turned off SSL certificate validation successfully.',
  606. \OCP\Util::WARN);
  607. } else {
  608. \OCP\Util::writeLog('user_ldap', 'Could not turn off SSL certificate validation.', \OCP\Util::WARN);
  609. }
  610. }
  611. if(!$this->config['ldapOverrideMainServer'] && !$this->getFromCache('overrideMainServer')) {
  612. $this->doConnect($this->config['ldapHost'], $this->config['ldapPort']);
  613. $bindStatus = $this->bind();
  614. $error = $this->ldap->isResource($this->ldapConnectionRes) ?
  615. $this->ldap->errno($this->ldapConnectionRes) : -1;
  616. } else {
  617. $bindStatus = false;
  618. $error = null;
  619. }
  620. //if LDAP server is not reachable, try the Backup (Replica!) Server
  621. if((!$bindStatus && ($error !== 0))
  622. || $this->config['ldapOverrideMainServer']
  623. || $this->getFromCache('overrideMainServer')) {
  624. $this->doConnect($this->config['ldapBackupHost'], $this->config['ldapBackupPort']);
  625. $bindStatus = $this->bind();
  626. if(!$bindStatus && $error === -1) {
  627. //when bind to backup server succeeded and failed to main server,
  628. //skip contacting him until next cache refresh
  629. $this->writeToCache('overrideMainServer', true);
  630. }
  631. }
  632. return $bindStatus;
  633. }
  634. }
  635. private function doConnect($host, $port) {
  636. if(empty($host)) {
  637. return false;
  638. }
  639. if(strpos($host, '://') !== false) {
  640. //ldap_connect ignores port paramater when URLs are passed
  641. $host .= ':' . $port;
  642. }
  643. $this->ldapConnectionRes = $this->ldap->connect($host, $port);
  644. if($this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  645. if($this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  646. if($this->config['ldapTLS']) {
  647. $this->ldap->startTls($this->ldapConnectionRes);
  648. }
  649. }
  650. }
  651. }
  652. /**
  653. * Binds to LDAP
  654. */
  655. public function bind() {
  656. static $getConnectionResourceAttempt = false;
  657. if(!$this->config['ldapConfigurationActive']) {
  658. return false;
  659. }
  660. if($getConnectionResourceAttempt) {
  661. $getConnectionResourceAttempt = false;
  662. return false;
  663. }
  664. $getConnectionResourceAttempt = true;
  665. $cr = $this->getConnectionResource();
  666. $getConnectionResourceAttempt = false;
  667. if(!$this->ldap->isResource($cr)) {
  668. return false;
  669. }
  670. $ldapLogin = @$this->ldap->bind($cr,
  671. $this->config['ldapAgentName'],
  672. $this->config['ldapAgentPassword']);
  673. if(!$ldapLogin) {
  674. \OCP\Util::writeLog('user_ldap',
  675. 'Bind failed: ' . $this->ldap->errno($cr) . ': ' . $this->ldap->error($cr),
  676. \OCP\Util::ERROR);
  677. $this->ldapConnectionRes = null;
  678. return false;
  679. }
  680. return true;
  681. }
  682. }