User_LDAP.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Dominik Schmidt <dev@dominik-schmidt.de>
  8. * @author felixboehm <felix@webhippie.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Renaud Fortier <Renaud.Fortier@fsaa.ulaval.ca>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Tom Needham <tom@owncloud.com>
  18. * @author Roger Szabo <roger.szabo@web.de>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OCA\User_LDAP;
  36. use OC\User\Backend;
  37. use OC\User\NoUserException;
  38. use OCA\User_LDAP\Exceptions\NotOnLDAP;
  39. use OCA\User_LDAP\User\OfflineUser;
  40. use OCA\User_LDAP\User\User;
  41. use OCP\IConfig;
  42. use OCP\Util;
  43. class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
  44. /** @var string[] $homesToKill */
  45. protected $homesToKill = array();
  46. /** @var \OCP\IConfig */
  47. protected $ocConfig;
  48. /**
  49. * @param Access $access
  50. * @param \OCP\IConfig $ocConfig
  51. */
  52. public function __construct(Access $access, IConfig $ocConfig) {
  53. parent::__construct($access);
  54. $this->ocConfig = $ocConfig;
  55. }
  56. /**
  57. * checks whether the user is allowed to change his avatar in ownCloud
  58. * @param string $uid the ownCloud user name
  59. * @return boolean either the user can or cannot
  60. */
  61. public function canChangeAvatar($uid) {
  62. $user = $this->access->userManager->get($uid);
  63. if(!$user instanceof User) {
  64. return false;
  65. }
  66. if($user->getAvatarImage() === false) {
  67. return true;
  68. }
  69. return false;
  70. }
  71. /**
  72. * returns the username for the given login name, if available
  73. *
  74. * @param string $loginName
  75. * @return string|false
  76. */
  77. public function loginName2UserName($loginName) {
  78. $cacheKey = 'loginName2UserName-'.$loginName;
  79. $username = $this->access->connection->getFromCache($cacheKey);
  80. if(!is_null($username)) {
  81. return $username;
  82. }
  83. try {
  84. $ldapRecord = $this->getLDAPUserByLoginName($loginName);
  85. $user = $this->access->userManager->get($ldapRecord['dn'][0]);
  86. if($user instanceof OfflineUser) {
  87. // this path is not really possible, however get() is documented
  88. // to return User or OfflineUser so we are very defensive here.
  89. $this->access->connection->writeToCache($cacheKey, false);
  90. return false;
  91. }
  92. $username = $user->getUsername();
  93. $this->access->connection->writeToCache($cacheKey, $username);
  94. return $username;
  95. } catch (NotOnLDAP $e) {
  96. $this->access->connection->writeToCache($cacheKey, false);
  97. return false;
  98. }
  99. }
  100. /**
  101. * returns the username for the given LDAP DN, if available
  102. *
  103. * @param string $dn
  104. * @return string|false with the username
  105. */
  106. public function dn2UserName($dn) {
  107. return $this->access->dn2username($dn);
  108. }
  109. /**
  110. * returns an LDAP record based on a given login name
  111. *
  112. * @param string $loginName
  113. * @return array
  114. * @throws NotOnLDAP
  115. */
  116. public function getLDAPUserByLoginName($loginName) {
  117. //find out dn of the user name
  118. $attrs = $this->access->userManager->getAttributes();
  119. $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
  120. if(count($users) < 1) {
  121. throw new NotOnLDAP('No user available for the given login name on ' .
  122. $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
  123. }
  124. return $users[0];
  125. }
  126. /**
  127. * Check if the password is correct without logging in the user
  128. *
  129. * @param string $uid The username
  130. * @param string $password The password
  131. * @return false|string
  132. */
  133. public function checkPassword($uid, $password) {
  134. try {
  135. $ldapRecord = $this->getLDAPUserByLoginName($uid);
  136. } catch(NotOnLDAP $e) {
  137. if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
  138. \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
  139. }
  140. return false;
  141. }
  142. $dn = $ldapRecord['dn'][0];
  143. $user = $this->access->userManager->get($dn);
  144. if(!$user instanceof User) {
  145. Util::writeLog('user_ldap',
  146. 'LDAP Login: Could not get user object for DN ' . $dn .
  147. '. Maybe the LDAP entry has no set display name attribute?',
  148. Util::WARN);
  149. return false;
  150. }
  151. if($user->getUsername() !== false) {
  152. //are the credentials OK?
  153. if(!$this->access->areCredentialsValid($dn, $password)) {
  154. return false;
  155. }
  156. $this->access->cacheUserExists($user->getUsername());
  157. $user->processAttributes($ldapRecord);
  158. $user->markLogin();
  159. return $user->getUsername();
  160. }
  161. return false;
  162. }
  163. /**
  164. * Set password
  165. * @param string $uid The username
  166. * @param string $password The new password
  167. * @return bool
  168. */
  169. public function setPassword($uid, $password) {
  170. $user = $this->access->userManager->get($uid);
  171. if(!$user instanceof User) {
  172. throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
  173. '. Maybe the LDAP entry has no set display name attribute?');
  174. }
  175. if($user->getUsername() !== false) {
  176. return $this->access->setPassword($user->getDN(), $password);
  177. }
  178. return false;
  179. }
  180. /**
  181. * Get a list of all users
  182. *
  183. * @param string $search
  184. * @param integer $limit
  185. * @param integer $offset
  186. * @return string[] an array of all uids
  187. */
  188. public function getUsers($search = '', $limit = 10, $offset = 0) {
  189. $search = $this->access->escapeFilterPart($search, true);
  190. $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
  191. //check if users are cached, if so return
  192. $ldap_users = $this->access->connection->getFromCache($cachekey);
  193. if(!is_null($ldap_users)) {
  194. return $ldap_users;
  195. }
  196. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  197. // error. With a limit of 0, we get 0 results. So we pass null.
  198. if($limit <= 0) {
  199. $limit = null;
  200. }
  201. $filter = $this->access->combineFilterWithAnd(array(
  202. $this->access->connection->ldapUserFilter,
  203. $this->access->connection->ldapUserDisplayName . '=*',
  204. $this->access->getFilterPartForUserSearch($search)
  205. ));
  206. Util::writeLog('user_ldap',
  207. 'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
  208. Util::DEBUG);
  209. //do the search and translate results to owncloud names
  210. $ldap_users = $this->access->fetchListOfUsers(
  211. $filter,
  212. $this->access->userManager->getAttributes(true),
  213. $limit, $offset);
  214. $ldap_users = $this->access->ownCloudUserNames($ldap_users);
  215. Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
  216. $this->access->connection->writeToCache($cachekey, $ldap_users);
  217. return $ldap_users;
  218. }
  219. /**
  220. * checks whether a user is still available on LDAP
  221. *
  222. * @param string|\OCA\User_LDAP\User\User $user either the ownCloud user
  223. * name or an instance of that user
  224. * @return bool
  225. * @throws \Exception
  226. * @throws \OC\ServerNotAvailableException
  227. */
  228. public function userExistsOnLDAP($user) {
  229. if(is_string($user)) {
  230. $user = $this->access->userManager->get($user);
  231. }
  232. if(is_null($user)) {
  233. return false;
  234. }
  235. $dn = $user->getDN();
  236. //check if user really still exists by reading its entry
  237. if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
  238. $lcr = $this->access->connection->getConnectionResource();
  239. if(is_null($lcr)) {
  240. throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
  241. }
  242. try {
  243. $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
  244. if(!$uuid) {
  245. return false;
  246. }
  247. $newDn = $this->access->getUserDnByUuid($uuid);
  248. //check if renamed user is still valid by reapplying the ldap filter
  249. if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
  250. return false;
  251. }
  252. $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
  253. return true;
  254. } catch (\Exception $e) {
  255. return false;
  256. }
  257. }
  258. if($user instanceof OfflineUser) {
  259. $user->unmark();
  260. }
  261. return true;
  262. }
  263. /**
  264. * check if a user exists
  265. * @param string $uid the username
  266. * @return boolean
  267. * @throws \Exception when connection could not be established
  268. */
  269. public function userExists($uid) {
  270. $userExists = $this->access->connection->getFromCache('userExists'.$uid);
  271. if(!is_null($userExists)) {
  272. return (bool)$userExists;
  273. }
  274. //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
  275. $user = $this->access->userManager->get($uid);
  276. if(is_null($user)) {
  277. Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
  278. $this->access->connection->ldapHost, Util::DEBUG);
  279. $this->access->connection->writeToCache('userExists'.$uid, false);
  280. return false;
  281. } else if($user instanceof OfflineUser) {
  282. //express check for users marked as deleted. Returning true is
  283. //necessary for cleanup
  284. return true;
  285. }
  286. $result = $this->userExistsOnLDAP($user);
  287. $this->access->connection->writeToCache('userExists'.$uid, $result);
  288. if($result === true) {
  289. $user->update();
  290. }
  291. return $result;
  292. }
  293. /**
  294. * returns whether a user was deleted in LDAP
  295. *
  296. * @param string $uid The username of the user to delete
  297. * @return bool
  298. */
  299. public function deleteUser($uid) {
  300. $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
  301. if(intval($marked) === 0) {
  302. \OC::$server->getLogger()->notice(
  303. 'User '.$uid . ' is not marked as deleted, not cleaning up.',
  304. array('app' => 'user_ldap'));
  305. return false;
  306. }
  307. \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
  308. array('app' => 'user_ldap'));
  309. //Get Home Directory out of user preferences so we can return it later,
  310. //necessary for removing directories as done by OC_User.
  311. $home = $this->ocConfig->getUserValue($uid, 'user_ldap', 'homePath', '');
  312. $this->homesToKill[$uid] = $home;
  313. $this->access->getUserMapper()->unmap($uid);
  314. return true;
  315. }
  316. /**
  317. * get the user's home directory
  318. *
  319. * @param string $uid the username
  320. * @return bool|string
  321. * @throws NoUserException
  322. * @throws \Exception
  323. */
  324. public function getHome($uid) {
  325. if(isset($this->homesToKill[$uid]) && !empty($this->homesToKill[$uid])) {
  326. //a deleted user who needs some clean up
  327. return $this->homesToKill[$uid];
  328. }
  329. // user Exists check required as it is not done in user proxy!
  330. if(!$this->userExists($uid)) {
  331. return false;
  332. }
  333. $cacheKey = 'getHome'.$uid;
  334. $path = $this->access->connection->getFromCache($cacheKey);
  335. if(!is_null($path)) {
  336. return $path;
  337. }
  338. $user = $this->access->userManager->get($uid);
  339. if(is_null($user) || ($user instanceof OfflineUser && !$this->userExistsOnLDAP($user->getOCName()))) {
  340. throw new NoUserException($uid . ' is not a valid user anymore');
  341. }
  342. if($user instanceof OfflineUser) {
  343. // apparently this user survived the userExistsOnLDAP check,
  344. // we request the user instance again in order to retrieve a User
  345. // instance instead
  346. $user = $this->access->userManager->get($uid);
  347. }
  348. $path = $user->getHomePath();
  349. $this->access->cacheUserHome($uid, $path);
  350. return $path;
  351. }
  352. /**
  353. * get display name of the user
  354. * @param string $uid user ID of the user
  355. * @return string|false display name
  356. */
  357. public function getDisplayName($uid) {
  358. if(!$this->userExists($uid)) {
  359. return false;
  360. }
  361. $cacheKey = 'getDisplayName'.$uid;
  362. if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  363. return $displayName;
  364. }
  365. //Check whether the display name is configured to have a 2nd feature
  366. $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
  367. $displayName2 = '';
  368. if ($additionalAttribute !== '') {
  369. $displayName2 = $this->access->readAttribute(
  370. $this->access->username2dn($uid),
  371. $additionalAttribute);
  372. }
  373. $displayName = $this->access->readAttribute(
  374. $this->access->username2dn($uid),
  375. $this->access->connection->ldapUserDisplayName);
  376. if($displayName && (count($displayName) > 0)) {
  377. $displayName = $displayName[0];
  378. if (is_array($displayName2)){
  379. $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
  380. }
  381. $user = $this->access->userManager->get($uid);
  382. if ($user instanceof User) {
  383. $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
  384. $this->access->connection->writeToCache($cacheKey, $displayName);
  385. }
  386. if ($user instanceof OfflineUser) {
  387. /** @var OfflineUser $user*/
  388. $displayName = $user->getDisplayName();
  389. }
  390. return $displayName;
  391. }
  392. return null;
  393. }
  394. /**
  395. * Get a list of all display names
  396. *
  397. * @param string $search
  398. * @param string|null $limit
  399. * @param string|null $offset
  400. * @return array an array of all displayNames (value) and the corresponding uids (key)
  401. */
  402. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  403. $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
  404. if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
  405. return $displayNames;
  406. }
  407. $displayNames = array();
  408. $users = $this->getUsers($search, $limit, $offset);
  409. foreach ($users as $user) {
  410. $displayNames[$user] = $this->getDisplayName($user);
  411. }
  412. $this->access->connection->writeToCache($cacheKey, $displayNames);
  413. return $displayNames;
  414. }
  415. /**
  416. * Check if backend implements actions
  417. * @param int $actions bitwise-or'ed actions
  418. * @return boolean
  419. *
  420. * Returns the supported actions as int to be
  421. * compared with OC_USER_BACKEND_CREATE_USER etc.
  422. */
  423. public function implementsActions($actions) {
  424. return (bool)((Backend::CHECK_PASSWORD
  425. | Backend::GET_HOME
  426. | Backend::GET_DISPLAYNAME
  427. | Backend::PROVIDE_AVATAR
  428. | Backend::COUNT_USERS
  429. | ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0))
  430. & $actions);
  431. }
  432. /**
  433. * @return bool
  434. */
  435. public function hasUserListings() {
  436. return true;
  437. }
  438. /**
  439. * counts the users in LDAP
  440. *
  441. * @return int|bool
  442. */
  443. public function countUsers() {
  444. $filter = $this->access->getFilterForUserCount();
  445. $cacheKey = 'countUsers-'.$filter;
  446. if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
  447. return $entries;
  448. }
  449. $entries = $this->access->countUsers($filter);
  450. $this->access->connection->writeToCache($cacheKey, $entries);
  451. return $entries;
  452. }
  453. /**
  454. * Backend name to be shown in user management
  455. * @return string the name of the backend to be shown
  456. */
  457. public function getBackendName(){
  458. return 'LDAP';
  459. }
  460. /**
  461. * Return access for LDAP interaction.
  462. * @param string $uid
  463. * @return Access instance of Access for LDAP interaction
  464. */
  465. public function getLDAPAccess($uid) {
  466. return $this->access;
  467. }
  468. /**
  469. * Return LDAP connection resource from a cloned connection.
  470. * The cloned connection needs to be closed manually.
  471. * of the current access.
  472. * @param string $uid
  473. * @return resource of the LDAP connection
  474. */
  475. public function getNewLDAPConnection($uid) {
  476. $connection = clone $this->access->getConnection();
  477. return $connection->getConnectionResource();
  478. }
  479. }