1
0

User_LDAP.php 19 KB

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