User_LDAP.php 19 KB

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