User_LDAP.php 19 KB

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