connection.php 21 KB

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