PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/apps/user_ldap/lib/connection.php

https://github.com/jlgg/simple_trash
PHP | 365 lines | 275 code | 36 blank | 54 comment | 59 complexity | f856e011a45039e9435dbade2d21e23a 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 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 $configID;
  26. private $configured = false;
  27. //cache handler
  28. protected $cache;
  29. //settings
  30. protected $config = array(
  31. 'ldapHost' => null,
  32. 'ldapPort' => null,
  33. 'ldapBase' => null,
  34. 'ldapBaseUsers' => null,
  35. 'ldapBaseGroups' => null,
  36. 'ldapAgentName' => null,
  37. 'ldapAgentPassword' => null,
  38. 'ldapTLS' => null,
  39. 'ldapNoCase' => null,
  40. 'turnOffCertCheck' => null,
  41. 'ldapIgnoreNamingRules' => null,
  42. 'ldapUserDisplayName' => null,
  43. 'ldapUserFilter' => null,
  44. 'ldapGroupFilter' => null,
  45. 'ldapGroupDisplayName' => null,
  46. 'ldapLoginFilter' => null,
  47. 'ldapQuotaAttribute' => null,
  48. 'ldapQuotaDefault' => null,
  49. 'ldapEmailAttribute' => null,
  50. 'ldapCacheTTL' => null,
  51. 'ldapUuidAttribute' => null,
  52. 'ldapOverrideUuidAttribute' => null,
  53. 'homeFolderNamingRule' => null,
  54. 'hasPagedResultSupport' => false,
  55. );
  56. public function __construct($configID = 'user_ldap') {
  57. $this->configID = $configID;
  58. $this->cache = \OC_Cache::getGlobalCache();
  59. $this->config['hasPagedResultSupport'] = (function_exists('ldap_control_paged_result') && function_exists('ldap_control_paged_result_response'));
  60. \OCP\Util::writeLog('user_ldap', 'PHP supports paged results? '.print_r($this->config['hasPagedResultSupport'], true), \OCP\Util::INFO);
  61. }
  62. public function __destruct() {
  63. if(is_resource($this->ldapConnectionRes)) {
  64. @ldap_unbind($this->ldapConnectionRes);
  65. };
  66. }
  67. public function __get($name) {
  68. if(!$this->configured) {
  69. $this->readConfiguration();
  70. }
  71. if(isset($this->config[$name])) {
  72. return $this->config[$name];
  73. }
  74. }
  75. public function __set($name, $value) {
  76. $changed = false;
  77. //omly few options are writable
  78. if($name == 'ldapUuidAttribute') {
  79. \OCP\Util::writeLog('user_ldap', 'Set config ldapUuidAttribute to '.$value, \OCP\Util::DEBUG);
  80. $this->config[$name] = $value;
  81. if(!empty($this->configID)) {
  82. \OCP\Config::setAppValue($this->configID, 'ldap_uuid_attribute', $value);
  83. }
  84. $changed = true;
  85. }
  86. if($changed) {
  87. $this->validateConfiguration();
  88. }
  89. }
  90. /**
  91. * @brief initializes the LDAP backend
  92. * @param $force read the config settings no matter what
  93. *
  94. * initializes the LDAP backend
  95. */
  96. public function init($force = false) {
  97. $this->readConfiguration($force);
  98. $this->establishConnection();
  99. }
  100. /**
  101. * Returns the LDAP handler
  102. */
  103. public function getConnectionResource() {
  104. if(!$this->ldapConnectionRes) {
  105. $this->init();
  106. } else if(!is_resource($this->ldapConnectionRes)) {
  107. $this->ldapConnectionRes = null;
  108. $this->establishConnection();
  109. }
  110. if(is_null($this->ldapConnectionRes)) {
  111. \OCP\Util::writeLog('user_ldap', 'Connection could not be established', \OCP\Util::ERROR);
  112. }
  113. return $this->ldapConnectionRes;
  114. }
  115. private function getCacheKey($key) {
  116. $prefix = 'LDAP-'.$this->configID.'-';
  117. if(is_null($key)) {
  118. return $prefix;
  119. }
  120. return $prefix.md5($key);
  121. }
  122. public function getFromCache($key) {
  123. if(!$this->configured) {
  124. $this->readConfiguration();
  125. }
  126. if(!$this->config['ldapCacheTTL']) {
  127. return null;
  128. }
  129. if(!$this->isCached($key)) {
  130. return null;
  131. }
  132. $key = $this->getCacheKey($key);
  133. return unserialize(base64_decode($this->cache->get($key)));
  134. }
  135. public function isCached($key) {
  136. if(!$this->configured) {
  137. $this->readConfiguration();
  138. }
  139. if(!$this->config['ldapCacheTTL']) {
  140. return false;
  141. }
  142. $key = $this->getCacheKey($key);
  143. return $this->cache->hasKey($key);
  144. }
  145. public function writeToCache($key, $value) {
  146. if(!$this->configured) {
  147. $this->readConfiguration();
  148. }
  149. if(!$this->config['ldapCacheTTL']) {
  150. return null;
  151. }
  152. $key = $this->getCacheKey($key);
  153. $value = base64_encode(serialize($value));
  154. $this->cache->set($key, $value, $this->config['ldapCacheTTL']);
  155. }
  156. public function clearCache() {
  157. $this->cache->clear($this->getCacheKey(null));
  158. }
  159. /**
  160. * Caches the general LDAP configuration.
  161. */
  162. private function readConfiguration($force = false) {
  163. \OCP\Util::writeLog('user_ldap', 'Checking conf state: isConfigured? '.print_r($this->configured, true).' isForce? '.print_r($force, true).' configID? '.print_r($this->configID, true), \OCP\Util::DEBUG);
  164. if((!$this->configured || $force) && !is_null($this->configID)) {
  165. \OCP\Util::writeLog('user_ldap', 'Reading the configuration', \OCP\Util::DEBUG);
  166. $this->config['ldapHost'] = \OCP\Config::getAppValue($this->configID, 'ldap_host', '');
  167. $this->config['ldapPort'] = \OCP\Config::getAppValue($this->configID, 'ldap_port', 389);
  168. $this->config['ldapAgentName'] = \OCP\Config::getAppValue($this->configID, 'ldap_dn', '');
  169. $this->config['ldapAgentPassword'] = base64_decode(\OCP\Config::getAppValue($this->configID, 'ldap_agent_password', ''));
  170. $this->config['ldapBase'] = \OCP\Config::getAppValue($this->configID, 'ldap_base', '');
  171. $this->config['ldapBaseUsers'] = \OCP\Config::getAppValue($this->configID, 'ldap_base_users', $this->config['ldapBase']);
  172. $this->config['ldapBaseGroups'] = \OCP\Config::getAppValue($this->configID, 'ldap_base_groups', $this->config['ldapBase']);
  173. $this->config['ldapTLS'] = \OCP\Config::getAppValue($this->configID, 'ldap_tls', 0);
  174. $this->config['ldapNoCase'] = \OCP\Config::getAppValue($this->configID, 'ldap_nocase', 0);
  175. $this->config['turnOffCertCheck'] = \OCP\Config::getAppValue($this->configID, 'ldap_turn_off_cert_check', 0);
  176. $this->config['ldapUserDisplayName'] = mb_strtolower(\OCP\Config::getAppValue($this->configID, 'ldap_display_name', 'uid'), 'UTF-8');
  177. $this->config['ldapUserFilter'] = \OCP\Config::getAppValue($this->configID, 'ldap_userlist_filter', 'objectClass=person');
  178. $this->config['ldapGroupFilter'] = \OCP\Config::getAppValue($this->configID, 'ldap_group_filter', '(objectClass=posixGroup)');
  179. $this->config['ldapLoginFilter'] = \OCP\Config::getAppValue($this->configID, 'ldap_login_filter', '(uid=%uid)');
  180. $this->config['ldapGroupDisplayName'] = mb_strtolower(\OCP\Config::getAppValue($this->configID, 'ldap_group_display_name', 'uid'), 'UTF-8');
  181. $this->config['ldapQuotaAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_quota_attr', '');
  182. $this->config['ldapQuotaDefault'] = \OCP\Config::getAppValue($this->configID, 'ldap_quota_def', '');
  183. $this->config['ldapEmailAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_email_attr', '');
  184. $this->config['ldapGroupMemberAssocAttr'] = \OCP\Config::getAppValue($this->configID, 'ldap_group_member_assoc_attribute', 'uniqueMember');
  185. $this->config['ldapIgnoreNamingRules'] = \OCP\Config::getSystemValue('ldapIgnoreNamingRules', false);
  186. $this->config['ldapCacheTTL'] = \OCP\Config::getAppValue($this->configID, 'ldap_cache_ttl', 10*60);
  187. $this->config['ldapUuidAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_uuid_attribute', 'auto');
  188. $this->config['ldapOverrideUuidAttribute'] = \OCP\Config::getAppValue($this->configID, 'ldap_override_uuid_attribute', 0);
  189. $this->config['homeFolderNamingRule'] = \OCP\Config::getAppValue($this->configID, 'home_folder_naming_rule', 'opt:username');
  190. $this->configured = $this->validateConfiguration();
  191. }
  192. }
  193. /**
  194. * @brief set LDAP configuration with values delivered by an array, not read from configuration
  195. * @param $config array that holds the config parameters in an associated array
  196. * @param &$setParameters optional; array where the set fields will be given to
  197. * @return true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
  198. */
  199. public function setConfiguration($config, &$setParameters = null) {
  200. if(!is_array($config)) {
  201. return false;
  202. }
  203. $params = array('ldap_host'=>'ldapHost', 'ldap_port'=>'ldapPort', 'ldap_dn'=>'ldapAgentName', 'ldap_agent_password'=>'ldapAgentPassword', 'ldap_base'=>'ldapBase', 'ldap_base_users'=>'ldapBaseUsers', 'ldap_base_groups'=>'ldapBaseGroups', 'ldap_userlist_filter'=>'ldapUserFilter', 'ldap_login_filter'=>'ldapLoginFilter', 'ldap_group_filter'=>'ldapGroupFilter', 'ldap_display_name'=>'ldapUserDisplayName', 'ldap_group_display_name'=>'ldapGroupDisplayName',
  204. 'ldap_tls'=>'ldapTLS', 'ldap_nocase'=>'ldapNoCase', 'ldap_quota_def'=>'ldapQuotaDefault', 'ldap_quota_attr'=>'ldapQuotaAttribute', 'ldap_email_attr'=>'ldapEmailAttribute', 'ldap_group_member_assoc_attribute'=>'ldapGroupMemberAssocAttr', 'ldap_cache_ttl'=>'ldapCacheTTL', 'home_folder_naming_rule' => 'homeFolderNamingRule');
  205. foreach($config as $parameter => $value) {
  206. if(isset($this->config[$parameter])) {
  207. $this->config[$parameter] = $value;
  208. if(is_array($setParameters)) {
  209. $setParameters[] = $parameter;
  210. }
  211. } else if(isset($params[$parameter])) {
  212. $this->config[$params[$parameter]] = $value;
  213. if(is_array($setParameters)) {
  214. $setParameters[] = $params[$parameter];
  215. }
  216. }
  217. }
  218. $this->configured = $this->validateConfiguration();
  219. return $this->configured;
  220. }
  221. /**
  222. * @brief Validates the user specified configuration
  223. * @returns true if configuration seems OK, false otherwise
  224. */
  225. private function validateConfiguration() {
  226. //first step: "soft" checks: settings that are not really necessary, but advisable. If left empty, give an info message
  227. if(empty($this->config['ldapBaseUsers'])) {
  228. \OCP\Util::writeLog('user_ldap', 'Base tree for Users is empty, using Base DN', \OCP\Util::INFO);
  229. $this->config['ldapBaseUsers'] = $this->config['ldapBase'];
  230. }
  231. if(empty($this->config['ldapBaseGroups'])) {
  232. \OCP\Util::writeLog('user_ldap', 'Base tree for Groups is empty, using Base DN', \OCP\Util::INFO);
  233. $this->config['ldapBaseGroups'] = $this->config['ldapBase'];
  234. }
  235. if(empty($this->config['ldapGroupFilter']) && empty($this->config['ldapGroupMemberAssocAttr'])) {
  236. \OCP\Util::writeLog('user_ldap', 'No group filter is specified, LDAP group feature will not be used.', \OCP\Util::INFO);
  237. }
  238. if(!in_array($this->config['ldapUuidAttribute'], array('auto', 'entryuuid', 'nsuniqueid', 'objectguid')) && (!is_null($this->configID))) {
  239. \OCP\Config::setAppValue($this->configID, 'ldap_uuid_attribute', 'auto');
  240. \OCP\Util::writeLog('user_ldap', 'Illegal value for the UUID Attribute, reset to autodetect.', \OCP\Util::INFO);
  241. }
  242. //second step: critical checks. If left empty or filled wrong, set as unconfigured and give a warning.
  243. $configurationOK = true;
  244. if(empty($this->config['ldapHost'])) {
  245. \OCP\Util::writeLog('user_ldap', 'No LDAP host given, won`t connect.', \OCP\Util::WARN);
  246. $configurationOK = false;
  247. }
  248. if(empty($this->config['ldapPort'])) {
  249. \OCP\Util::writeLog('user_ldap', 'No LDAP Port given, won`t connect.', \OCP\Util::WARN);
  250. $configurationOK = false;
  251. }
  252. if((empty($this->config['ldapAgentName']) && !empty($this->config['ldapAgentPassword']))
  253. || (!empty($this->config['ldapAgentName']) && empty($this->config['ldapAgentPassword']))) {
  254. \OCP\Util::writeLog('user_ldap', 'Either no password given for the user agent or a password is given, but no LDAP agent; won`t connect.', \OCP\Util::WARN);
  255. $configurationOK = false;
  256. }
  257. //TODO: check if ldapAgentName is in DN form
  258. if(empty($this->config['ldapBase']) && (empty($this->config['ldapBaseUsers']) && empty($this->config['ldapBaseGroups']))) {
  259. \OCP\Util::writeLog('user_ldap', 'No Base DN given, won`t connect.', \OCP\Util::WARN);
  260. $configurationOK = false;
  261. }
  262. if(empty($this->config['ldapUserDisplayName'])) {
  263. \OCP\Util::writeLog('user_ldap', 'No user display name attribute specified, won`t connect.', \OCP\Util::WARN);
  264. $configurationOK = false;
  265. }
  266. if(empty($this->config['ldapGroupDisplayName'])) {
  267. \OCP\Util::writeLog('user_ldap', 'No group display name attribute specified, won`t connect.', \OCP\Util::WARN);
  268. $configurationOK = false;
  269. }
  270. if(empty($this->config['ldapLoginFilter'])) {
  271. \OCP\Util::writeLog('user_ldap', 'No login filter specified, won`t connect.', \OCP\Util::WARN);
  272. $configurationOK = false;
  273. }
  274. if(mb_strpos($this->config['ldapLoginFilter'], '%uid', 0, 'UTF-8') === false) {
  275. \OCP\Util::writeLog('user_ldap', 'Login filter does not contain %uid place holder, won`t connect.', \OCP\Util::WARN);
  276. \OCP\Util::writeLog('user_ldap', 'Login filter was ' . $this->config['ldapLoginFilter'], \OCP\Util::DEBUG);
  277. $configurationOK = false;
  278. }
  279. return $configurationOK;
  280. }
  281. /**
  282. * Connects and Binds to LDAP
  283. */
  284. private function establishConnection() {
  285. static $phpLDAPinstalled = true;
  286. if(!$phpLDAPinstalled) {
  287. return false;
  288. }
  289. if(!$this->configured) {
  290. \OCP\Util::writeLog('user_ldap', 'Configuration is invalid, cannot connect', \OCP\Util::WARN);
  291. return false;
  292. }
  293. if(!$this->ldapConnectionRes) {
  294. if(!function_exists('ldap_connect')) {
  295. $phpLDAPinstalled = false;
  296. \OCP\Util::writeLog('user_ldap', 'function ldap_connect is not available. Make sure that the PHP ldap module is installed.', \OCP\Util::ERROR);
  297. return false;
  298. }
  299. if($this->config['turnOffCertCheck']) {
  300. if(putenv('LDAPTLS_REQCERT=never')) {
  301. \OCP\Util::writeLog('user_ldap', 'Turned off SSL certificate validation successfully.', \OCP\Util::WARN);
  302. } else {
  303. \OCP\Util::writeLog('user_ldap', 'Could not turn off SSL certificate validation.', \OCP\Util::WARN);
  304. }
  305. }
  306. $this->ldapConnectionRes = ldap_connect($this->config['ldapHost'], $this->config['ldapPort']);
  307. if(ldap_set_option($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
  308. if(ldap_set_option($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
  309. if($this->config['ldapTLS']) {
  310. ldap_start_tls($this->ldapConnectionRes);
  311. }
  312. }
  313. }
  314. return $this->bind();
  315. }
  316. }
  317. /**
  318. * Binds to LDAP
  319. */
  320. public function bind() {
  321. $ldapLogin = @ldap_bind($this->getConnectionResource(), $this->config['ldapAgentName'], $this->config['ldapAgentPassword']);
  322. if(!$ldapLogin) {
  323. \OCP\Util::writeLog('user_ldap', 'Bind failed: ' . ldap_errno($this->ldapConnectionRes) . ': ' . ldap_error($this->ldapConnectionRes), \OCP\Util::ERROR);
  324. $this->ldapConnectionRes = null;
  325. return false;
  326. }
  327. return true;
  328. }
  329. }