1
0

User_LDAP.php 19 KB

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