User_LDAP.php 19 KB

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