User_LDAP.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\User_LDAP;
  8. use OC\ServerNotAvailableException;
  9. use OC\User\Backend;
  10. use OC\User\NoUserException;
  11. use OCA\User_LDAP\Exceptions\NotOnLDAP;
  12. use OCA\User_LDAP\User\DeletedUsersIndex;
  13. use OCA\User_LDAP\User\OfflineUser;
  14. use OCA\User_LDAP\User\User;
  15. use OCP\IUserBackend;
  16. use OCP\Notification\IManager as INotificationManager;
  17. use OCP\User\Backend\ICountMappedUsersBackend;
  18. use OCP\User\Backend\ICountUsersBackend;
  19. use OCP\User\Backend\IProvideEnabledStateBackend;
  20. use OCP\UserInterface;
  21. use Psr\Log\LoggerInterface;
  22. class User_LDAP extends BackendUtility implements IUserBackend, UserInterface, IUserLDAP, ICountUsersBackend, ICountMappedUsersBackend, IProvideEnabledStateBackend {
  23. protected INotificationManager $notificationManager;
  24. protected UserPluginManager $userPluginManager;
  25. protected LoggerInterface $logger;
  26. protected DeletedUsersIndex $deletedUsersIndex;
  27. public function __construct(
  28. Access $access,
  29. INotificationManager $notificationManager,
  30. UserPluginManager $userPluginManager,
  31. LoggerInterface $logger,
  32. DeletedUsersIndex $deletedUsersIndex,
  33. ) {
  34. parent::__construct($access);
  35. $this->notificationManager = $notificationManager;
  36. $this->userPluginManager = $userPluginManager;
  37. $this->logger = $logger;
  38. $this->deletedUsersIndex = $deletedUsersIndex;
  39. }
  40. /**
  41. * checks whether the user is allowed to change his avatar in Nextcloud
  42. *
  43. * @param string $uid the Nextcloud user name
  44. * @return boolean either the user can or cannot
  45. * @throws \Exception
  46. */
  47. public function canChangeAvatar($uid) {
  48. if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
  49. return $this->userPluginManager->canChangeAvatar($uid);
  50. }
  51. if (!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
  52. return true;
  53. }
  54. $user = $this->access->userManager->get($uid);
  55. if (!$user instanceof User) {
  56. return false;
  57. }
  58. $imageData = $user->getAvatarImage();
  59. if ($imageData === false) {
  60. return true;
  61. }
  62. return !$user->updateAvatar(true);
  63. }
  64. /**
  65. * Return the username for the given login name, if available
  66. *
  67. * @param string $loginName
  68. * @return string|false
  69. * @throws \Exception
  70. */
  71. public function loginName2UserName($loginName, bool $forceLdapRefetch = false) {
  72. $cacheKey = 'loginName2UserName-' . $loginName;
  73. $username = $this->access->connection->getFromCache($cacheKey);
  74. $ignoreCache = ($username === false && $forceLdapRefetch);
  75. if ($username !== null && !$ignoreCache) {
  76. return $username;
  77. }
  78. try {
  79. $ldapRecord = $this->getLDAPUserByLoginName($loginName);
  80. $user = $this->access->userManager->get($ldapRecord['dn'][0]);
  81. if ($user === null || $user instanceof OfflineUser) {
  82. // this path is not really possible, however get() is documented
  83. // to return User, OfflineUser or null so we are very defensive here.
  84. $this->access->connection->writeToCache($cacheKey, false);
  85. return false;
  86. }
  87. $username = $user->getUsername();
  88. $this->access->connection->writeToCache($cacheKey, $username);
  89. if ($forceLdapRefetch) {
  90. $user->processAttributes($ldapRecord);
  91. }
  92. return $username;
  93. } catch (NotOnLDAP $e) {
  94. $this->access->connection->writeToCache($cacheKey, false);
  95. return false;
  96. }
  97. }
  98. /**
  99. * returns the username for the given LDAP DN, if available
  100. *
  101. * @param string $dn
  102. * @return string|false with the username
  103. */
  104. public function dn2UserName($dn) {
  105. return $this->access->dn2username($dn);
  106. }
  107. /**
  108. * returns an LDAP record based on a given login name
  109. *
  110. * @param string $loginName
  111. * @return array
  112. * @throws NotOnLDAP
  113. */
  114. public function getLDAPUserByLoginName($loginName) {
  115. //find out dn of the user name
  116. $attrs = $this->access->userManager->getAttributes();
  117. $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
  118. if (count($users) < 1) {
  119. throw new NotOnLDAP('No user available for the given login name on ' .
  120. $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
  121. }
  122. return $users[0];
  123. }
  124. /**
  125. * Check if the password is correct without logging in the user
  126. *
  127. * @param string $uid The username
  128. * @param string $password The password
  129. * @return false|string
  130. */
  131. public function checkPassword($uid, $password) {
  132. $username = $this->loginName2UserName($uid, true);
  133. if ($username === false) {
  134. return false;
  135. }
  136. $dn = $this->access->username2dn($username);
  137. $user = $this->access->userManager->get($dn);
  138. if (!$user instanceof User) {
  139. $this->logger->warning(
  140. 'LDAP Login: Could not get user object for DN ' . $dn .
  141. '. Maybe the LDAP entry has no set display name attribute?',
  142. ['app' => 'user_ldap']
  143. );
  144. return false;
  145. }
  146. if ($user->getUsername() !== false) {
  147. //are the credentials OK?
  148. if (!$this->access->areCredentialsValid($dn, $password)) {
  149. return false;
  150. }
  151. $this->access->cacheUserExists($user->getUsername());
  152. $user->markLogin();
  153. return $user->getUsername();
  154. }
  155. return false;
  156. }
  157. /**
  158. * Set password
  159. * @param string $uid The username
  160. * @param string $password The new password
  161. * @return bool
  162. */
  163. public function setPassword($uid, $password) {
  164. if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
  165. return $this->userPluginManager->setPassword($uid, $password);
  166. }
  167. $user = $this->access->userManager->get($uid);
  168. if (!$user instanceof User) {
  169. throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
  170. '. Maybe the LDAP entry has no set display name attribute?');
  171. }
  172. if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
  173. $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
  174. $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
  175. if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
  176. //remove last password expiry warning if any
  177. $notification = $this->notificationManager->createNotification();
  178. $notification->setApp('user_ldap')
  179. ->setUser($uid)
  180. ->setObject('pwd_exp_warn', $uid)
  181. ;
  182. $this->notificationManager->markProcessed($notification);
  183. }
  184. return true;
  185. }
  186. return false;
  187. }
  188. /**
  189. * Get a list of all users
  190. *
  191. * @param string $search
  192. * @param integer $limit
  193. * @param integer $offset
  194. * @return string[] an array of all uids
  195. */
  196. public function getUsers($search = '', $limit = 10, $offset = 0) {
  197. $search = $this->access->escapeFilterPart($search, true);
  198. $cachekey = 'getUsers-' . $search . '-' . $limit . '-' . $offset;
  199. //check if users are cached, if so return
  200. $ldap_users = $this->access->connection->getFromCache($cachekey);
  201. if (!is_null($ldap_users)) {
  202. return $ldap_users;
  203. }
  204. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  205. // error. With a limit of 0, we get 0 results. So we pass null.
  206. if ($limit <= 0) {
  207. $limit = null;
  208. }
  209. $filter = $this->access->combineFilterWithAnd([
  210. $this->access->connection->ldapUserFilter,
  211. $this->access->connection->ldapUserDisplayName . '=*',
  212. $this->access->getFilterPartForUserSearch($search)
  213. ]);
  214. $this->logger->debug(
  215. 'getUsers: Options: search ' . $search . ' limit ' . $limit . ' offset ' . $offset . ' Filter: ' . $filter,
  216. ['app' => 'user_ldap']
  217. );
  218. //do the search and translate results to Nextcloud names
  219. $ldap_users = $this->access->fetchListOfUsers(
  220. $filter,
  221. $this->access->userManager->getAttributes(true),
  222. $limit, $offset);
  223. $ldap_users = $this->access->nextcloudUserNames($ldap_users);
  224. $this->logger->debug(
  225. 'getUsers: ' . count($ldap_users) . ' Users found',
  226. ['app' => 'user_ldap']
  227. );
  228. $this->access->connection->writeToCache($cachekey, $ldap_users);
  229. return $ldap_users;
  230. }
  231. /**
  232. * checks whether a user is still available on LDAP
  233. *
  234. * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
  235. * name or an instance of that user
  236. * @throws \Exception
  237. * @throws \OC\ServerNotAvailableException
  238. */
  239. public function userExistsOnLDAP($user, bool $ignoreCache = false): bool {
  240. if (is_string($user)) {
  241. $user = $this->access->userManager->get($user);
  242. }
  243. if (is_null($user)) {
  244. return false;
  245. }
  246. $uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
  247. $cacheKey = 'userExistsOnLDAP' . $uid;
  248. if (!$ignoreCache) {
  249. $userExists = $this->access->connection->getFromCache($cacheKey);
  250. if (!is_null($userExists)) {
  251. return (bool)$userExists;
  252. }
  253. }
  254. $dn = $user->getDN();
  255. //check if user really still exists by reading its entry
  256. if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
  257. try {
  258. $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
  259. if (!$uuid) {
  260. $this->access->connection->writeToCache($cacheKey, false);
  261. return false;
  262. }
  263. $newDn = $this->access->getUserDnByUuid($uuid);
  264. //check if renamed user is still valid by reapplying the ldap filter
  265. if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
  266. $this->access->connection->writeToCache($cacheKey, false);
  267. return false;
  268. }
  269. $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
  270. } catch (ServerNotAvailableException $e) {
  271. throw $e;
  272. } catch (\Exception $e) {
  273. $this->access->connection->writeToCache($cacheKey, false);
  274. return false;
  275. }
  276. }
  277. if ($user instanceof OfflineUser) {
  278. $user->unmark();
  279. }
  280. $this->access->connection->writeToCache($cacheKey, true);
  281. return true;
  282. }
  283. /**
  284. * check if a user exists
  285. * @param string $uid the username
  286. * @return boolean
  287. * @throws \Exception when connection could not be established
  288. */
  289. public function userExists($uid) {
  290. $userExists = $this->access->connection->getFromCache('userExists' . $uid);
  291. if (!is_null($userExists)) {
  292. return (bool)$userExists;
  293. }
  294. $userExists = $this->access->userManager->exists($uid);
  295. if (!$userExists) {
  296. $this->logger->debug(
  297. 'No DN found for ' . $uid . ' on ' . $this->access->connection->ldapHost,
  298. ['app' => 'user_ldap']
  299. );
  300. $this->access->connection->writeToCache('userExists' . $uid, false);
  301. return false;
  302. }
  303. $this->access->connection->writeToCache('userExists' . $uid, true);
  304. return true;
  305. }
  306. /**
  307. * returns whether a user was deleted in LDAP
  308. *
  309. * @param string $uid The username of the user to delete
  310. * @return bool
  311. */
  312. public function deleteUser($uid) {
  313. if ($this->userPluginManager->canDeleteUser()) {
  314. $status = $this->userPluginManager->deleteUser($uid);
  315. if ($status === false) {
  316. return false;
  317. }
  318. }
  319. $marked = $this->deletedUsersIndex->isUserMarked($uid);
  320. if (!$marked) {
  321. try {
  322. $user = $this->access->userManager->get($uid);
  323. if (($user instanceof User) && !$this->userExistsOnLDAP($uid, true)) {
  324. $user->markUser();
  325. $marked = true;
  326. }
  327. } catch (\Exception $e) {
  328. $this->logger->debug(
  329. $e->getMessage(),
  330. ['app' => 'user_ldap', 'exception' => $e]
  331. );
  332. }
  333. if (!$marked) {
  334. $this->logger->notice(
  335. 'User ' . $uid . ' is not marked as deleted, not cleaning up.',
  336. ['app' => 'user_ldap']
  337. );
  338. return false;
  339. }
  340. }
  341. $this->logger->info('Cleaning up after user ' . $uid,
  342. ['app' => 'user_ldap']);
  343. $this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
  344. $this->access->userManager->invalidate($uid);
  345. $this->access->connection->clearCache();
  346. return true;
  347. }
  348. /**
  349. * get the user's home directory
  350. *
  351. * @param string $uid the username
  352. * @return bool|string
  353. * @throws NoUserException
  354. * @throws \Exception
  355. */
  356. public function getHome($uid) {
  357. // user Exists check required as it is not done in user proxy!
  358. if (!$this->userExists($uid)) {
  359. return false;
  360. }
  361. if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
  362. return $this->userPluginManager->getHome($uid);
  363. }
  364. $cacheKey = 'getHome' . $uid;
  365. $path = $this->access->connection->getFromCache($cacheKey);
  366. if (!is_null($path)) {
  367. return $path;
  368. }
  369. // early return path if it is a deleted user
  370. $user = $this->access->userManager->get($uid);
  371. if ($user instanceof User || $user instanceof OfflineUser) {
  372. $path = $user->getHomePath() ?: false;
  373. } else {
  374. throw new NoUserException($uid . ' is not a valid user anymore');
  375. }
  376. $this->access->cacheUserHome($uid, $path);
  377. return $path;
  378. }
  379. /**
  380. * get display name of the user
  381. * @param string $uid user ID of the user
  382. * @return string|false display name
  383. */
  384. public function getDisplayName($uid) {
  385. if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
  386. return $this->userPluginManager->getDisplayName($uid);
  387. }
  388. if (!$this->userExists($uid)) {
  389. return false;
  390. }
  391. $cacheKey = 'getDisplayName' . $uid;
  392. if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  393. return $displayName;
  394. }
  395. //Check whether the display name is configured to have a 2nd feature
  396. $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
  397. $displayName2 = '';
  398. if ($additionalAttribute !== '') {
  399. $displayName2 = $this->access->readAttribute(
  400. $this->access->username2dn($uid),
  401. $additionalAttribute);
  402. }
  403. $displayName = $this->access->readAttribute(
  404. $this->access->username2dn($uid),
  405. $this->access->connection->ldapUserDisplayName);
  406. if ($displayName && (count($displayName) > 0)) {
  407. $displayName = $displayName[0];
  408. if (is_array($displayName2)) {
  409. $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
  410. }
  411. $user = $this->access->userManager->get($uid);
  412. if ($user instanceof User) {
  413. $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
  414. $this->access->connection->writeToCache($cacheKey, $displayName);
  415. }
  416. if ($user instanceof OfflineUser) {
  417. $displayName = $user->getDisplayName();
  418. }
  419. return $displayName;
  420. }
  421. return null;
  422. }
  423. /**
  424. * set display name of the user
  425. * @param string $uid user ID of the user
  426. * @param string $displayName new display name of the user
  427. * @return string|false display name
  428. */
  429. public function setDisplayName($uid, $displayName) {
  430. if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
  431. $this->userPluginManager->setDisplayName($uid, $displayName);
  432. $this->access->cacheUserDisplayName($uid, $displayName);
  433. return $displayName;
  434. }
  435. return false;
  436. }
  437. /**
  438. * Get a list of all display names
  439. *
  440. * @param string $search
  441. * @param int|null $limit
  442. * @param int|null $offset
  443. * @return array an array of all displayNames (value) and the corresponding uids (key)
  444. */
  445. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  446. $cacheKey = 'getDisplayNames-' . $search . '-' . $limit . '-' . $offset;
  447. if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
  448. return $displayNames;
  449. }
  450. $displayNames = [];
  451. $users = $this->getUsers($search, $limit, $offset);
  452. foreach ($users as $user) {
  453. $displayNames[$user] = $this->getDisplayName($user);
  454. }
  455. $this->access->connection->writeToCache($cacheKey, $displayNames);
  456. return $displayNames;
  457. }
  458. /**
  459. * Check if backend implements actions
  460. * @param int $actions bitwise-or'ed actions
  461. * @return boolean
  462. *
  463. * Returns the supported actions as int to be
  464. * compared with \OC\User\Backend::CREATE_USER etc.
  465. */
  466. public function implementsActions($actions) {
  467. return (bool)((Backend::CHECK_PASSWORD
  468. | Backend::GET_HOME
  469. | Backend::GET_DISPLAYNAME
  470. | (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
  471. | Backend::COUNT_USERS
  472. | (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
  473. | $this->userPluginManager->getImplementedActions())
  474. & $actions);
  475. }
  476. /**
  477. * @return bool
  478. */
  479. public function hasUserListings() {
  480. return true;
  481. }
  482. /**
  483. * counts the users in LDAP
  484. *
  485. * @return int|false
  486. */
  487. public function countUsers() {
  488. if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
  489. return $this->userPluginManager->countUsers();
  490. }
  491. $filter = $this->access->getFilterForUserCount();
  492. $cacheKey = 'countUsers-' . $filter;
  493. if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
  494. return $entries;
  495. }
  496. $entries = $this->access->countUsers($filter);
  497. $this->access->connection->writeToCache($cacheKey, $entries);
  498. return $entries;
  499. }
  500. public function countMappedUsers(): int {
  501. return $this->access->getUserMapper()->count();
  502. }
  503. /**
  504. * Backend name to be shown in user management
  505. * @return string the name of the backend to be shown
  506. */
  507. public function getBackendName() {
  508. return 'LDAP';
  509. }
  510. /**
  511. * Return access for LDAP interaction.
  512. * @param string $uid
  513. * @return Access instance of Access for LDAP interaction
  514. */
  515. public function getLDAPAccess($uid) {
  516. return $this->access;
  517. }
  518. /**
  519. * Return LDAP connection resource from a cloned connection.
  520. * The cloned connection needs to be closed manually.
  521. * of the current access.
  522. * @param string $uid
  523. * @return \LDAP\Connection The LDAP connection
  524. */
  525. public function getNewLDAPConnection($uid) {
  526. $connection = clone $this->access->getConnection();
  527. return $connection->getConnectionResource();
  528. }
  529. /**
  530. * create new user
  531. * @param string $username username of the new user
  532. * @param string $password password of the new user
  533. * @throws \UnexpectedValueException
  534. * @return bool
  535. */
  536. public function createUser($username, $password) {
  537. if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
  538. if ($dn = $this->userPluginManager->createUser($username, $password)) {
  539. if (is_string($dn)) {
  540. // the NC user creation work flow requires a know user id up front
  541. $uuid = $this->access->getUUID($dn, true);
  542. if (is_string($uuid)) {
  543. $this->access->mapAndAnnounceIfApplicable(
  544. $this->access->getUserMapper(),
  545. $dn,
  546. $username,
  547. $uuid,
  548. true
  549. );
  550. } else {
  551. $this->logger->warning(
  552. 'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
  553. [
  554. 'app' => 'user_ldap',
  555. 'userid' => $username,
  556. ]
  557. );
  558. }
  559. } else {
  560. throw new \UnexpectedValueException('LDAP Plugin: Method createUser changed to return the user DN instead of boolean.');
  561. }
  562. }
  563. return (bool)$dn;
  564. }
  565. return false;
  566. }
  567. public function isUserEnabled(string $uid, callable $queryDatabaseValue): bool {
  568. if ($this->deletedUsersIndex->isUserMarked($uid) && ((int)$this->access->connection->markRemnantsAsDisabled === 1)) {
  569. return false;
  570. } else {
  571. return $queryDatabaseValue();
  572. }
  573. }
  574. public function setUserEnabled(string $uid, bool $enabled, callable $queryDatabaseValue, callable $setDatabaseValue): bool {
  575. $setDatabaseValue($enabled);
  576. return $enabled;
  577. }
  578. public function getDisabledUserList(?int $limit = null, int $offset = 0, string $search = ''): array {
  579. throw new \Exception('This is implemented directly in User_Proxy');
  580. }
  581. }