PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/apps/user_ldap/lib/connection.php

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