User_LDAP.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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. if($this->ocConfig->getSystemValue('loglevel', ILogger::WARN) === ILogger::DEBUG) {
  175. \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
  176. }
  177. return false;
  178. }
  179. $dn = $ldapRecord['dn'][0];
  180. $user = $this->access->userManager->get($dn);
  181. if(!$user instanceof User) {
  182. Util::writeLog('user_ldap',
  183. 'LDAP Login: Could not get user object for DN ' . $dn .
  184. '. Maybe the LDAP entry has no set display name attribute?',
  185. ILogger::WARN);
  186. return false;
  187. }
  188. if($user->getUsername() !== false) {
  189. //are the credentials OK?
  190. if(!$this->access->areCredentialsValid($dn, $password)) {
  191. return false;
  192. }
  193. $this->access->cacheUserExists($user->getUsername());
  194. $user->processAttributes($ldapRecord);
  195. $user->markLogin();
  196. return $user->getUsername();
  197. }
  198. return false;
  199. }
  200. /**
  201. * Set password
  202. * @param string $uid The username
  203. * @param string $password The new password
  204. * @return bool
  205. */
  206. public function setPassword($uid, $password) {
  207. if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
  208. return $this->userPluginManager->setPassword($uid, $password);
  209. }
  210. $user = $this->access->userManager->get($uid);
  211. if(!$user instanceof User) {
  212. throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
  213. '. Maybe the LDAP entry has no set display name attribute?');
  214. }
  215. if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
  216. $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
  217. $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
  218. if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
  219. //remove last password expiry warning if any
  220. $notification = $this->notificationManager->createNotification();
  221. $notification->setApp('user_ldap')
  222. ->setUser($uid)
  223. ->setObject('pwd_exp_warn', $uid)
  224. ;
  225. $this->notificationManager->markProcessed($notification);
  226. }
  227. return true;
  228. }
  229. return false;
  230. }
  231. /**
  232. * Get a list of all users
  233. *
  234. * @param string $search
  235. * @param integer $limit
  236. * @param integer $offset
  237. * @return string[] an array of all uids
  238. */
  239. public function getUsers($search = '', $limit = 10, $offset = 0) {
  240. $search = $this->access->escapeFilterPart($search, true);
  241. $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
  242. //check if users are cached, if so return
  243. $ldap_users = $this->access->connection->getFromCache($cachekey);
  244. if(!is_null($ldap_users)) {
  245. return $ldap_users;
  246. }
  247. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  248. // error. With a limit of 0, we get 0 results. So we pass null.
  249. if($limit <= 0) {
  250. $limit = null;
  251. }
  252. $filter = $this->access->combineFilterWithAnd(array(
  253. $this->access->connection->ldapUserFilter,
  254. $this->access->connection->ldapUserDisplayName . '=*',
  255. $this->access->getFilterPartForUserSearch($search)
  256. ));
  257. Util::writeLog('user_ldap',
  258. 'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
  259. ILogger::DEBUG);
  260. //do the search and translate results to Nextcloud names
  261. $ldap_users = $this->access->fetchListOfUsers(
  262. $filter,
  263. $this->access->userManager->getAttributes(true),
  264. $limit, $offset);
  265. $ldap_users = $this->access->nextcloudUserNames($ldap_users);
  266. Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
  267. $this->access->connection->writeToCache($cachekey, $ldap_users);
  268. return $ldap_users;
  269. }
  270. /**
  271. * checks whether a user is still available on LDAP
  272. *
  273. * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
  274. * name or an instance of that user
  275. * @return bool
  276. * @throws \Exception
  277. * @throws \OC\ServerNotAvailableException
  278. */
  279. public function userExistsOnLDAP($user) {
  280. if(is_string($user)) {
  281. $user = $this->access->userManager->get($user);
  282. }
  283. if(is_null($user)) {
  284. return false;
  285. }
  286. $dn = $user->getDN();
  287. //check if user really still exists by reading its entry
  288. if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
  289. try {
  290. $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
  291. if (!$uuid) {
  292. return false;
  293. }
  294. $newDn = $this->access->getUserDnByUuid($uuid);
  295. //check if renamed user is still valid by reapplying the ldap filter
  296. if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
  297. return false;
  298. }
  299. $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
  300. return true;
  301. } catch (ServerNotAvailableException $e) {
  302. throw $e;
  303. } catch (\Exception $e) {
  304. return false;
  305. }
  306. }
  307. if($user instanceof OfflineUser) {
  308. $user->unmark();
  309. }
  310. return true;
  311. }
  312. /**
  313. * check if a user exists
  314. * @param string $uid the username
  315. * @return boolean
  316. * @throws \Exception when connection could not be established
  317. */
  318. public function userExists($uid) {
  319. $userExists = $this->access->connection->getFromCache('userExists'.$uid);
  320. if(!is_null($userExists)) {
  321. return (bool)$userExists;
  322. }
  323. //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
  324. $user = $this->access->userManager->get($uid);
  325. if(is_null($user)) {
  326. Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
  327. $this->access->connection->ldapHost, ILogger::DEBUG);
  328. $this->access->connection->writeToCache('userExists'.$uid, false);
  329. return false;
  330. } else if($user instanceof OfflineUser) {
  331. //express check for users marked as deleted. Returning true is
  332. //necessary for cleanup
  333. return true;
  334. }
  335. $result = $this->userExistsOnLDAP($user);
  336. $this->access->connection->writeToCache('userExists'.$uid, $result);
  337. return $result;
  338. }
  339. /**
  340. * returns whether a user was deleted in LDAP
  341. *
  342. * @param string $uid The username of the user to delete
  343. * @return bool
  344. */
  345. public function deleteUser($uid) {
  346. if ($this->userPluginManager->canDeleteUser()) {
  347. $status = $this->userPluginManager->deleteUser($uid);
  348. if($status === false) {
  349. return false;
  350. }
  351. }
  352. $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
  353. if((int)$marked === 0) {
  354. \OC::$server->getLogger()->notice(
  355. 'User '.$uid . ' is not marked as deleted, not cleaning up.',
  356. ['app' => 'user_ldap']);
  357. return false;
  358. }
  359. \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
  360. ['app' => 'user_ldap']);
  361. $this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
  362. $this->access->userManager->invalidate($uid);
  363. return true;
  364. }
  365. /**
  366. * get the user's home directory
  367. *
  368. * @param string $uid the username
  369. * @return bool|string
  370. * @throws NoUserException
  371. * @throws \Exception
  372. */
  373. public function getHome($uid) {
  374. // user Exists check required as it is not done in user proxy!
  375. if(!$this->userExists($uid)) {
  376. return false;
  377. }
  378. if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
  379. return $this->userPluginManager->getHome($uid);
  380. }
  381. $cacheKey = 'getHome'.$uid;
  382. $path = $this->access->connection->getFromCache($cacheKey);
  383. if(!is_null($path)) {
  384. return $path;
  385. }
  386. // early return path if it is a deleted user
  387. $user = $this->access->userManager->get($uid);
  388. if($user instanceof OfflineUser) {
  389. if($this->currentUserInDeletionProcess !== null
  390. && $this->currentUserInDeletionProcess === $user->getOCName()
  391. ) {
  392. return $user->getHomePath();
  393. } else {
  394. throw new NoUserException($uid . ' is not a valid user anymore');
  395. }
  396. } else if ($user === null) {
  397. throw new NoUserException($uid . ' is not a valid user anymore');
  398. }
  399. $path = $user->getHomePath();
  400. $this->access->cacheUserHome($uid, $path);
  401. return $path;
  402. }
  403. /**
  404. * get display name of the user
  405. * @param string $uid user ID of the user
  406. * @return string|false display name
  407. */
  408. public function getDisplayName($uid) {
  409. if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
  410. return $this->userPluginManager->getDisplayName($uid);
  411. }
  412. if(!$this->userExists($uid)) {
  413. return false;
  414. }
  415. $cacheKey = 'getDisplayName'.$uid;
  416. if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  417. return $displayName;
  418. }
  419. //Check whether the display name is configured to have a 2nd feature
  420. $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
  421. $displayName2 = '';
  422. if ($additionalAttribute !== '') {
  423. $displayName2 = $this->access->readAttribute(
  424. $this->access->username2dn($uid),
  425. $additionalAttribute);
  426. }
  427. $displayName = $this->access->readAttribute(
  428. $this->access->username2dn($uid),
  429. $this->access->connection->ldapUserDisplayName);
  430. if($displayName && (count($displayName) > 0)) {
  431. $displayName = $displayName[0];
  432. if (is_array($displayName2)){
  433. $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
  434. }
  435. $user = $this->access->userManager->get($uid);
  436. if ($user instanceof User) {
  437. $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
  438. $this->access->connection->writeToCache($cacheKey, $displayName);
  439. }
  440. if ($user instanceof OfflineUser) {
  441. /** @var OfflineUser $user*/
  442. $displayName = $user->getDisplayName();
  443. }
  444. return $displayName;
  445. }
  446. return null;
  447. }
  448. /**
  449. * set display name of the user
  450. * @param string $uid user ID of the user
  451. * @param string $displayName new display name of the user
  452. * @return string|false display name
  453. */
  454. public function setDisplayName($uid, $displayName) {
  455. if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
  456. $this->userPluginManager->setDisplayName($uid, $displayName);
  457. $this->access->cacheUserDisplayName($uid, $displayName);
  458. return $displayName;
  459. }
  460. return false;
  461. }
  462. /**
  463. * Get a list of all display names
  464. *
  465. * @param string $search
  466. * @param string|null $limit
  467. * @param string|null $offset
  468. * @return array an array of all displayNames (value) and the corresponding uids (key)
  469. */
  470. public function getDisplayNames($search = '', $limit = null, $offset = null) {
  471. $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
  472. if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
  473. return $displayNames;
  474. }
  475. $displayNames = array();
  476. $users = $this->getUsers($search, $limit, $offset);
  477. foreach ($users as $user) {
  478. $displayNames[$user] = $this->getDisplayName($user);
  479. }
  480. $this->access->connection->writeToCache($cacheKey, $displayNames);
  481. return $displayNames;
  482. }
  483. /**
  484. * Check if backend implements actions
  485. * @param int $actions bitwise-or'ed actions
  486. * @return boolean
  487. *
  488. * Returns the supported actions as int to be
  489. * compared with \OC\User\Backend::CREATE_USER etc.
  490. */
  491. public function implementsActions($actions) {
  492. return (bool)((Backend::CHECK_PASSWORD
  493. | Backend::GET_HOME
  494. | Backend::GET_DISPLAYNAME
  495. | (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
  496. | Backend::COUNT_USERS
  497. | (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
  498. | $this->userPluginManager->getImplementedActions())
  499. & $actions);
  500. }
  501. /**
  502. * @return bool
  503. */
  504. public function hasUserListings() {
  505. return true;
  506. }
  507. /**
  508. * counts the users in LDAP
  509. *
  510. * @return int|bool
  511. */
  512. public function countUsers() {
  513. if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
  514. return $this->userPluginManager->countUsers();
  515. }
  516. $filter = $this->access->getFilterForUserCount();
  517. $cacheKey = 'countUsers-'.$filter;
  518. if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
  519. return $entries;
  520. }
  521. $entries = $this->access->countUsers($filter);
  522. $this->access->connection->writeToCache($cacheKey, $entries);
  523. return $entries;
  524. }
  525. /**
  526. * Backend name to be shown in user management
  527. * @return string the name of the backend to be shown
  528. */
  529. public function getBackendName(){
  530. return 'LDAP';
  531. }
  532. /**
  533. * Return access for LDAP interaction.
  534. * @param string $uid
  535. * @return Access instance of Access for LDAP interaction
  536. */
  537. public function getLDAPAccess($uid) {
  538. return $this->access;
  539. }
  540. /**
  541. * Return LDAP connection resource from a cloned connection.
  542. * The cloned connection needs to be closed manually.
  543. * of the current access.
  544. * @param string $uid
  545. * @return resource of the LDAP connection
  546. */
  547. public function getNewLDAPConnection($uid) {
  548. $connection = clone $this->access->getConnection();
  549. return $connection->getConnectionResource();
  550. }
  551. /**
  552. * create new user
  553. * @param string $username username of the new user
  554. * @param string $password password of the new user
  555. * @throws \UnexpectedValueException
  556. * @return bool
  557. */
  558. public function createUser($username, $password) {
  559. if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
  560. if ($dn = $this->userPluginManager->createUser($username, $password)) {
  561. if (is_string($dn)) {
  562. //updates user mapping
  563. $this->access->dn2ocname($dn, $username, true);
  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. }