Group_LDAP.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Alexander Bergolth <leo@strike.wu.ac.at>
  6. * @author Alex Weirig <alex.weirig@technolink.lu>
  7. * @author alexweirig <alex.weirig@technolink.lu>
  8. * @author Andreas Fischer <bantu@owncloud.com>
  9. * @author Andreas Pflug <dev@admin4.org>
  10. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  11. * @author Bart Visscher <bartv@thisnet.nl>
  12. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  13. * @author Clement Wong <git@clement.hk>
  14. * @author Frédéric Fortier <frederic.fortier@oronospolytechnique.com>
  15. * @author Joas Schilling <coding@schilljs.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Nicolas Grekas <nicolas.grekas@gmail.com>
  19. * @author Robin McCorkell <robin@mccorkell.me.uk>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Roland Tapken <roland@bitarbeiter.net>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Tobias Perschon <tobias@perschon.at>
  24. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  25. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  26. * @author Xuanwo <xuanwo@yunify.com>
  27. * @author Carl Schwan <carl@carlschwan.eu>
  28. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  29. *
  30. * @license AGPL-3.0
  31. *
  32. * This code is free software: you can redistribute it and/or modify
  33. * it under the terms of the GNU Affero General Public License, version 3,
  34. * as published by the Free Software Foundation.
  35. *
  36. * This program is distributed in the hope that it will be useful,
  37. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  39. * GNU Affero General Public License for more details.
  40. *
  41. * You should have received a copy of the GNU Affero General Public License, version 3,
  42. * along with this program. If not, see <http://www.gnu.org/licenses/>
  43. *
  44. */
  45. namespace OCA\User_LDAP;
  46. use Exception;
  47. use OC\ServerNotAvailableException;
  48. use OCA\User_LDAP\User\OfflineUser;
  49. use OCP\Cache\CappedMemoryCache;
  50. use OCP\Group\Backend\IIsAdminBackend;
  51. use OCP\GroupInterface;
  52. use OCP\Group\Backend\IDeleteGroupBackend;
  53. use OCP\Group\Backend\IGetDisplayNameBackend;
  54. use OCP\IConfig;
  55. use OCP\IUserManager;
  56. use OCP\Server;
  57. use Psr\Log\LoggerInterface;
  58. use function json_decode;
  59. class Group_LDAP extends BackendUtility implements GroupInterface, IGroupLDAP, IGetDisplayNameBackend, IDeleteGroupBackend, IIsAdminBackend {
  60. protected bool $enabled = false;
  61. /** @var CappedMemoryCache<string[]> $cachedGroupMembers array of users with gid as key */
  62. protected CappedMemoryCache $cachedGroupMembers;
  63. /** @var CappedMemoryCache<array[]> $cachedGroupsByMember array of groups with uid as key */
  64. protected CappedMemoryCache $cachedGroupsByMember;
  65. /** @var CappedMemoryCache<string[]> $cachedNestedGroups array of groups with gid (DN) as key */
  66. protected CappedMemoryCache $cachedNestedGroups;
  67. protected GroupPluginManager $groupPluginManager;
  68. protected LoggerInterface $logger;
  69. /**
  70. * @var string $ldapGroupMemberAssocAttr contains the LDAP setting (in lower case) with the same name
  71. */
  72. protected string $ldapGroupMemberAssocAttr;
  73. private IConfig $config;
  74. private IUserManager $ncUserManager;
  75. public function __construct(
  76. Access $access,
  77. GroupPluginManager $groupPluginManager,
  78. IConfig $config,
  79. IUserManager $ncUserManager
  80. ) {
  81. parent::__construct($access);
  82. $filter = $this->access->connection->ldapGroupFilter;
  83. $gAssoc = $this->access->connection->ldapGroupMemberAssocAttr;
  84. if (!empty($filter) && !empty($gAssoc)) {
  85. $this->enabled = true;
  86. }
  87. $this->cachedGroupMembers = new CappedMemoryCache();
  88. $this->cachedGroupsByMember = new CappedMemoryCache();
  89. $this->cachedNestedGroups = new CappedMemoryCache();
  90. $this->groupPluginManager = $groupPluginManager;
  91. $this->logger = Server::get(LoggerInterface::class);
  92. $this->ldapGroupMemberAssocAttr = strtolower((string)$gAssoc);
  93. $this->config = $config;
  94. $this->ncUserManager = $ncUserManager;
  95. }
  96. /**
  97. * Check if user is in group
  98. *
  99. * @param string $uid uid of the user
  100. * @param string $gid gid of the group
  101. * @throws Exception
  102. * @throws ServerNotAvailableException
  103. */
  104. public function inGroup($uid, $gid): bool {
  105. if (!$this->enabled) {
  106. return false;
  107. }
  108. $cacheKey = 'inGroup' . $uid . ':' . $gid;
  109. $inGroup = $this->access->connection->getFromCache($cacheKey);
  110. if (!is_null($inGroup)) {
  111. return (bool)$inGroup;
  112. }
  113. $userDN = $this->access->username2dn($uid);
  114. if (isset($this->cachedGroupMembers[$gid])) {
  115. return in_array($userDN, $this->cachedGroupMembers[$gid]);
  116. }
  117. $cacheKeyMembers = 'inGroup-members:' . $gid;
  118. $members = $this->access->connection->getFromCache($cacheKeyMembers);
  119. if (!is_null($members)) {
  120. $this->cachedGroupMembers[$gid] = $members;
  121. $isInGroup = in_array($userDN, $members, true);
  122. $this->access->connection->writeToCache($cacheKey, $isInGroup);
  123. return $isInGroup;
  124. }
  125. $groupDN = $this->access->groupname2dn($gid);
  126. // just in case
  127. if (!$groupDN || !$userDN) {
  128. $this->access->connection->writeToCache($cacheKey, false);
  129. return false;
  130. }
  131. //check primary group first
  132. if ($gid === $this->getUserPrimaryGroup($userDN)) {
  133. $this->access->connection->writeToCache($cacheKey, true);
  134. return true;
  135. }
  136. //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
  137. $members = $this->_groupMembers($groupDN);
  138. //extra work if we don't get back user DNs
  139. switch ($this->ldapGroupMemberAssocAttr) {
  140. case 'memberuid':
  141. case 'zimbramailforwardingaddress':
  142. $requestAttributes = $this->access->userManager->getAttributes(true);
  143. $users = [];
  144. $filterParts = [];
  145. $bytes = 0;
  146. foreach ($members as $mid) {
  147. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  148. $parts = explode('@', $mid); //making sure we get only the uid
  149. $mid = $parts[0];
  150. }
  151. $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
  152. $filterParts[] = $filter;
  153. $bytes += strlen($filter);
  154. if ($bytes >= 9000000) {
  155. // AD has a default input buffer of 10 MB, we do not want
  156. // to take even the chance to exceed it
  157. // so we fetch results with the filterParts we collected so far
  158. $filter = $this->access->combineFilterWithOr($filterParts);
  159. $search = $this->access->fetchListOfUsers($filter, $requestAttributes, count($filterParts));
  160. $bytes = 0;
  161. $filterParts = [];
  162. $users = array_merge($users, $search);
  163. }
  164. }
  165. if (count($filterParts) > 0) {
  166. // if there are filterParts left we need to add their result
  167. $filter = $this->access->combineFilterWithOr($filterParts);
  168. $search = $this->access->fetchListOfUsers($filter, $requestAttributes, count($filterParts));
  169. $users = array_merge($users, $search);
  170. }
  171. // now we cleanup the users array to get only dns
  172. $dns = [];
  173. foreach ($users as $record) {
  174. $dns[$record['dn'][0]] = 1;
  175. }
  176. $members = array_keys($dns);
  177. break;
  178. }
  179. if (count($members) === 0) {
  180. $this->access->connection->writeToCache($cacheKey, false);
  181. return false;
  182. }
  183. $isInGroup = in_array($userDN, $members);
  184. $this->access->connection->writeToCache($cacheKey, $isInGroup);
  185. $this->access->connection->writeToCache($cacheKeyMembers, $members);
  186. $this->cachedGroupMembers[$gid] = $members;
  187. return $isInGroup;
  188. }
  189. /**
  190. * For a group that has user membership defined by an LDAP search url
  191. * attribute returns the users that match the search url otherwise returns
  192. * an empty array.
  193. *
  194. * @throws ServerNotAvailableException
  195. */
  196. public function getDynamicGroupMembers(string $dnGroup): array {
  197. $dynamicGroupMemberURL = strtolower((string)$this->access->connection->ldapDynamicGroupMemberURL);
  198. if (empty($dynamicGroupMemberURL)) {
  199. return [];
  200. }
  201. $dynamicMembers = [];
  202. $memberURLs = $this->access->readAttribute(
  203. $dnGroup,
  204. $dynamicGroupMemberURL,
  205. $this->access->connection->ldapGroupFilter
  206. );
  207. if ($memberURLs !== false) {
  208. // this group has the 'memberURL' attribute so this is a dynamic group
  209. // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
  210. // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
  211. $pos = strpos($memberURLs[0], '(');
  212. if ($pos !== false) {
  213. $memberUrlFilter = substr($memberURLs[0], $pos);
  214. $foundMembers = $this->access->searchUsers($memberUrlFilter, ['dn']);
  215. $dynamicMembers = [];
  216. foreach ($foundMembers as $value) {
  217. $dynamicMembers[$value['dn'][0]] = 1;
  218. }
  219. } else {
  220. $this->logger->debug('No search filter found on member url of group {dn}',
  221. [
  222. 'app' => 'user_ldap',
  223. 'dn' => $dnGroup,
  224. ]
  225. );
  226. }
  227. }
  228. return $dynamicMembers;
  229. }
  230. /**
  231. * Get group members from dn.
  232. * @psalm-param array<string, bool> $seen List of DN that have already been processed.
  233. * @throws ServerNotAvailableException
  234. */
  235. private function _groupMembers(string $dnGroup, array $seen = [], bool &$recursive = false): array {
  236. if (isset($seen[$dnGroup])) {
  237. $recursive = true;
  238. return [];
  239. }
  240. $seen[$dnGroup] = true;
  241. // used extensively in cron job, caching makes sense for nested groups
  242. $cacheKey = '_groupMembers' . $dnGroup;
  243. $groupMembers = $this->access->connection->getFromCache($cacheKey);
  244. if ($groupMembers !== null) {
  245. return $groupMembers;
  246. }
  247. if ($this->access->connection->ldapNestedGroups
  248. && $this->access->connection->useMemberOfToDetectMembership
  249. && $this->access->connection->hasMemberOfFilterSupport
  250. && $this->access->connection->ldapMatchingRuleInChainState !== Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE
  251. ) {
  252. $attemptedLdapMatchingRuleInChain = true;
  253. // Use matching rule 1.2.840.113556.1.4.1941 if available (LDAP_MATCHING_RULE_IN_CHAIN)
  254. $filter = $this->access->combineFilterWithAnd([
  255. $this->access->connection->ldapUserFilter,
  256. $this->access->connection->ldapUserDisplayName . '=*',
  257. 'memberof:1.2.840.113556.1.4.1941:=' . $dnGroup
  258. ]);
  259. $memberRecords = $this->access->fetchListOfUsers(
  260. $filter,
  261. $this->access->userManager->getAttributes(true)
  262. );
  263. $result = array_reduce($memberRecords, function ($carry, $record) {
  264. $carry[] = $record['dn'][0];
  265. return $carry;
  266. }, []);
  267. if ($this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_AVAILABLE) {
  268. $this->access->connection->writeToCache($cacheKey, $result);
  269. return $result;
  270. } elseif (!empty($memberRecords)) {
  271. $this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_AVAILABLE;
  272. $this->access->connection->saveConfiguration();
  273. $this->access->connection->writeToCache($cacheKey, $result);
  274. return $result;
  275. }
  276. // when feature availability is unknown, and the result is empty, continue and test with original approach
  277. }
  278. $allMembers = [];
  279. $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
  280. if (is_array($members)) {
  281. if ((int)$this->access->connection->ldapNestedGroups === 1) {
  282. while ($recordDn = array_shift($members)) {
  283. $nestedMembers = $this->_groupMembers($recordDn, $seen, $recursive);
  284. if (!empty($nestedMembers)) {
  285. // Group, queue its members for processing
  286. $members = array_merge($members, $nestedMembers);
  287. } else {
  288. // User (or empty group, or previously seen group), add it to the member list
  289. $allMembers[] = $recordDn;
  290. }
  291. }
  292. } else {
  293. $allMembers = $members;
  294. }
  295. }
  296. $allMembers += $this->getDynamicGroupMembers($dnGroup);
  297. $allMembers = array_unique($allMembers);
  298. // A group cannot be a member of itself
  299. $index = array_search($dnGroup, $allMembers, true);
  300. if ($index !== false) {
  301. unset($allMembers[$index]);
  302. }
  303. if (!$recursive) {
  304. $this->access->connection->writeToCache($cacheKey, $allMembers);
  305. }
  306. if (isset($attemptedLdapMatchingRuleInChain)
  307. && $this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_UNKNOWN
  308. && !empty($allMembers)
  309. ) {
  310. $this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE;
  311. $this->access->connection->saveConfiguration();
  312. }
  313. return $allMembers;
  314. }
  315. /**
  316. * @return string[]
  317. * @throws ServerNotAvailableException
  318. */
  319. private function _getGroupDNsFromMemberOf(string $dn, array &$seen = []): array {
  320. if (isset($seen[$dn])) {
  321. return [];
  322. }
  323. $seen[$dn] = true;
  324. if (isset($this->cachedNestedGroups[$dn])) {
  325. return $this->cachedNestedGroups[$dn];
  326. }
  327. $allGroups = [];
  328. $groups = $this->access->readAttribute($dn, 'memberOf');
  329. if (is_array($groups)) {
  330. if ((int)$this->access->connection->ldapNestedGroups === 1) {
  331. while ($recordDn = array_shift($groups)) {
  332. $nestedParents = $this->_getGroupDNsFromMemberOf($recordDn, $seen);
  333. $groups = array_merge($groups, $nestedParents);
  334. $allGroups[] = $recordDn;
  335. }
  336. } else {
  337. $allGroups = $groups;
  338. }
  339. }
  340. // We do not perform array_unique here at it is done in getUserGroups later
  341. $this->cachedNestedGroups[$dn] = $allGroups;
  342. return $this->filterValidGroups($allGroups);
  343. }
  344. /**
  345. * Translates a gidNumber into the Nextcloud internal name.
  346. *
  347. * @return string|false The nextcloud internal name.
  348. * @throws Exception
  349. * @throws ServerNotAvailableException
  350. */
  351. public function gidNumber2Name(string $gid, string $dn) {
  352. $cacheKey = 'gidNumberToName' . $gid;
  353. $groupName = $this->access->connection->getFromCache($cacheKey);
  354. if (!is_null($groupName) && isset($groupName)) {
  355. return $groupName;
  356. }
  357. //we need to get the DN from LDAP
  358. $filter = $this->access->combineFilterWithAnd([
  359. $this->access->connection->ldapGroupFilter,
  360. 'objectClass=posixGroup',
  361. $this->access->connection->ldapGidNumber . '=' . $gid
  362. ]);
  363. return $this->getNameOfGroup($filter, $cacheKey) ?? false;
  364. }
  365. /**
  366. * @return string|null|false The name of the group
  367. * @throws ServerNotAvailableException
  368. * @throws Exception
  369. */
  370. private function getNameOfGroup(string $filter, string $cacheKey) {
  371. $result = $this->access->searchGroups($filter, ['dn'], 1);
  372. if (empty($result)) {
  373. $this->access->connection->writeToCache($cacheKey, false);
  374. return null;
  375. }
  376. $dn = $result[0]['dn'][0];
  377. //and now the group name
  378. //NOTE once we have separate Nextcloud group IDs and group names we can
  379. //directly read the display name attribute instead of the DN
  380. $name = $this->access->dn2groupname($dn);
  381. $this->access->connection->writeToCache($cacheKey, $name);
  382. return $name;
  383. }
  384. /**
  385. * @return string|bool The entry's gidNumber
  386. * @throws ServerNotAvailableException
  387. */
  388. private function getEntryGidNumber(string $dn, string $attribute) {
  389. $value = $this->access->readAttribute($dn, $attribute);
  390. if (is_array($value) && !empty($value)) {
  391. return $value[0];
  392. }
  393. return false;
  394. }
  395. /**
  396. * @return string|bool The group's gidNumber
  397. * @throws ServerNotAvailableException
  398. */
  399. public function getGroupGidNumber(string $dn) {
  400. return $this->getEntryGidNumber($dn, 'gidNumber');
  401. }
  402. /**
  403. * @return string|bool The user's gidNumber
  404. * @throws ServerNotAvailableException
  405. */
  406. public function getUserGidNumber(string $dn) {
  407. $gidNumber = false;
  408. if ($this->access->connection->hasGidNumber) {
  409. // FIXME: when $dn does not exist on LDAP anymore, this will be set wrongly to false :/
  410. $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
  411. if ($gidNumber === false) {
  412. $this->access->connection->hasGidNumber = false;
  413. }
  414. }
  415. return $gidNumber;
  416. }
  417. /**
  418. * @throws ServerNotAvailableException
  419. * @throws Exception
  420. */
  421. private function prepareFilterForUsersHasGidNumber(string $groupDN, string $search = ''): string {
  422. $groupID = $this->getGroupGidNumber($groupDN);
  423. if ($groupID === false) {
  424. throw new Exception('Not a valid group');
  425. }
  426. $filterParts = [];
  427. $filterParts[] = $this->access->getFilterForUserCount();
  428. if ($search !== '') {
  429. $filterParts[] = $this->access->getFilterPartForUserSearch($search);
  430. }
  431. $filterParts[] = $this->access->connection->ldapGidNumber . '=' . $groupID;
  432. return $this->access->combineFilterWithAnd($filterParts);
  433. }
  434. /**
  435. * @return array<int,string> A list of users that have the given group as gid number
  436. * @throws ServerNotAvailableException
  437. */
  438. public function getUsersInGidNumber(
  439. string $groupDN,
  440. string $search = '',
  441. ?int $limit = -1,
  442. ?int $offset = 0
  443. ): array {
  444. try {
  445. $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
  446. $users = $this->access->fetchListOfUsers(
  447. $filter,
  448. $this->access->userManager->getAttributes(true),
  449. $limit,
  450. $offset
  451. );
  452. return $this->access->nextcloudUserNames($users);
  453. } catch (ServerNotAvailableException $e) {
  454. throw $e;
  455. } catch (Exception $e) {
  456. return [];
  457. }
  458. }
  459. /**
  460. * @throws ServerNotAvailableException
  461. * @return false|string
  462. */
  463. public function getUserGroupByGid(string $dn) {
  464. $groupID = $this->getUserGidNumber($dn);
  465. if ($groupID !== false) {
  466. $groupName = $this->gidNumber2Name($groupID, $dn);
  467. if ($groupName !== false) {
  468. return $groupName;
  469. }
  470. }
  471. return false;
  472. }
  473. /**
  474. * Translates a primary group ID into an Nextcloud internal name
  475. *
  476. * @return string|false
  477. * @throws Exception
  478. * @throws ServerNotAvailableException
  479. */
  480. public function primaryGroupID2Name(string $gid, string $dn) {
  481. $cacheKey = 'primaryGroupIDtoName_' . $gid;
  482. $groupName = $this->access->connection->getFromCache($cacheKey);
  483. if (!is_null($groupName)) {
  484. return $groupName;
  485. }
  486. $domainObjectSid = $this->access->getSID($dn);
  487. if ($domainObjectSid === false) {
  488. return false;
  489. }
  490. //we need to get the DN from LDAP
  491. $filter = $this->access->combineFilterWithAnd([
  492. $this->access->connection->ldapGroupFilter,
  493. 'objectsid=' . $domainObjectSid . '-' . $gid
  494. ]);
  495. return $this->getNameOfGroup($filter, $cacheKey) ?? false;
  496. }
  497. /**
  498. * @return string|false The entry's group Id
  499. * @throws ServerNotAvailableException
  500. */
  501. private function getEntryGroupID(string $dn, string $attribute) {
  502. $value = $this->access->readAttribute($dn, $attribute);
  503. if (is_array($value) && !empty($value)) {
  504. return $value[0];
  505. }
  506. return false;
  507. }
  508. /**
  509. * @return string|false The entry's primary group Id
  510. * @throws ServerNotAvailableException
  511. */
  512. public function getGroupPrimaryGroupID(string $dn) {
  513. return $this->getEntryGroupID($dn, 'primaryGroupToken');
  514. }
  515. /**
  516. * @return string|false
  517. * @throws ServerNotAvailableException
  518. */
  519. public function getUserPrimaryGroupIDs(string $dn) {
  520. $primaryGroupID = false;
  521. if ($this->access->connection->hasPrimaryGroups) {
  522. $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
  523. if ($primaryGroupID === false) {
  524. $this->access->connection->hasPrimaryGroups = false;
  525. }
  526. }
  527. return $primaryGroupID;
  528. }
  529. /**
  530. * @throws Exception
  531. * @throws ServerNotAvailableException
  532. */
  533. private function prepareFilterForUsersInPrimaryGroup(string $groupDN, string $search = ''): string {
  534. $groupID = $this->getGroupPrimaryGroupID($groupDN);
  535. if ($groupID === false) {
  536. throw new Exception('Not a valid group');
  537. }
  538. $filterParts = [];
  539. $filterParts[] = $this->access->getFilterForUserCount();
  540. if ($search !== '') {
  541. $filterParts[] = $this->access->getFilterPartForUserSearch($search);
  542. }
  543. $filterParts[] = 'primaryGroupID=' . $groupID;
  544. return $this->access->combineFilterWithAnd($filterParts);
  545. }
  546. /**
  547. * @throws ServerNotAvailableException
  548. * @return array<int,string>
  549. */
  550. public function getUsersInPrimaryGroup(
  551. string $groupDN,
  552. string $search = '',
  553. ?int $limit = -1,
  554. ?int $offset = 0
  555. ): array {
  556. try {
  557. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  558. $users = $this->access->fetchListOfUsers(
  559. $filter,
  560. $this->access->userManager->getAttributes(true),
  561. $limit,
  562. $offset
  563. );
  564. return $this->access->nextcloudUserNames($users);
  565. } catch (ServerNotAvailableException $e) {
  566. throw $e;
  567. } catch (Exception $e) {
  568. return [];
  569. }
  570. }
  571. /**
  572. * @throws ServerNotAvailableException
  573. */
  574. public function countUsersInPrimaryGroup(
  575. string $groupDN,
  576. string $search = '',
  577. int $limit = -1,
  578. int $offset = 0
  579. ): int {
  580. try {
  581. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  582. $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
  583. return (int)$users;
  584. } catch (ServerNotAvailableException $e) {
  585. throw $e;
  586. } catch (Exception $e) {
  587. return 0;
  588. }
  589. }
  590. /**
  591. * @return string|false
  592. * @throws ServerNotAvailableException
  593. */
  594. public function getUserPrimaryGroup(string $dn) {
  595. $groupID = $this->getUserPrimaryGroupIDs($dn);
  596. if ($groupID !== false) {
  597. $groupName = $this->primaryGroupID2Name($groupID, $dn);
  598. if ($groupName !== false) {
  599. return $groupName;
  600. }
  601. }
  602. return false;
  603. }
  604. private function isUserOnLDAP(string $uid): bool {
  605. // forces a user exists check - but does not help if a positive result is cached, while group info is not
  606. $ncUser = $this->ncUserManager->get($uid);
  607. if ($ncUser === null) {
  608. return false;
  609. }
  610. $backend = $ncUser->getBackend();
  611. if ($backend instanceof User_Proxy) {
  612. // ignoring cache as safeguard (and we are behind the group cache check anyway)
  613. return $backend->userExistsOnLDAP($uid, true);
  614. }
  615. return false;
  616. }
  617. protected function getCachedGroupsForUserId(string $uid): array {
  618. $groupStr = $this->config->getUserValue($uid, 'user_ldap', 'cached-group-memberships-' . $this->access->connection->getConfigPrefix(), '[]');
  619. return json_decode($groupStr, true) ?? [];
  620. }
  621. /**
  622. * This function fetches all groups a user belongs to. It does not check
  623. * if the user exists at all.
  624. *
  625. * This function includes groups based on dynamic group membership.
  626. *
  627. * @param string $uid Name of the user
  628. * @return string[] Group names
  629. * @throws Exception
  630. * @throws ServerNotAvailableException
  631. */
  632. public function getUserGroups($uid): array {
  633. if (!$this->enabled) {
  634. return [];
  635. }
  636. $ncUid = $uid;
  637. $cacheKey = 'getUserGroups' . $uid;
  638. $userGroups = $this->access->connection->getFromCache($cacheKey);
  639. if (!is_null($userGroups)) {
  640. return $userGroups;
  641. }
  642. $user = $this->access->userManager->get($uid);
  643. if ($user instanceof OfflineUser) {
  644. // We load known group memberships from configuration for remnants,
  645. // because LDAP server does not contain them anymore
  646. return $this->getCachedGroupsForUserId($uid);
  647. }
  648. $userDN = $this->access->username2dn($uid);
  649. if (!$userDN) {
  650. $this->access->connection->writeToCache($cacheKey, []);
  651. return [];
  652. }
  653. $groups = [];
  654. $primaryGroup = $this->getUserPrimaryGroup($userDN);
  655. $gidGroupName = $this->getUserGroupByGid($userDN);
  656. $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
  657. if (!empty($dynamicGroupMemberURL)) {
  658. // look through dynamic groups to add them to the result array if needed
  659. $groupsToMatch = $this->access->fetchListOfGroups(
  660. $this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
  661. foreach ($groupsToMatch as $dynamicGroup) {
  662. if (!isset($dynamicGroup[$dynamicGroupMemberURL][0])) {
  663. continue;
  664. }
  665. $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
  666. if ($pos !== false) {
  667. $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
  668. // apply filter via ldap search to see if this user is in this
  669. // dynamic group
  670. $userMatch = $this->access->readAttribute(
  671. $userDN,
  672. $this->access->connection->ldapUserDisplayName,
  673. $memberUrlFilter
  674. );
  675. if ($userMatch !== false) {
  676. // match found so this user is in this group
  677. $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
  678. if (is_string($groupName)) {
  679. // be sure to never return false if the dn could not be
  680. // resolved to a name, for whatever reason.
  681. $groups[] = $groupName;
  682. }
  683. }
  684. } else {
  685. $this->logger->debug('No search filter found on member url of group {dn}',
  686. [
  687. 'app' => 'user_ldap',
  688. 'dn' => $dynamicGroup,
  689. ]
  690. );
  691. }
  692. }
  693. }
  694. // if possible, read out membership via memberOf. It's far faster than
  695. // performing a search, which still is a fallback later.
  696. // memberof doesn't support memberuid, so skip it here.
  697. if ((int)$this->access->connection->hasMemberOfFilterSupport === 1
  698. && (int)$this->access->connection->useMemberOfToDetectMembership === 1
  699. && $this->ldapGroupMemberAssocAttr !== 'memberuid'
  700. && $this->ldapGroupMemberAssocAttr !== 'zimbramailforwardingaddress') {
  701. $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
  702. foreach ($groupDNs as $dn) {
  703. $groupName = $this->access->dn2groupname($dn);
  704. if (is_string($groupName)) {
  705. // be sure to never return false if the dn could not be
  706. // resolved to a name, for whatever reason.
  707. $groups[] = $groupName;
  708. }
  709. }
  710. } else {
  711. // uniqueMember takes DN, memberuid the uid, so we need to distinguish
  712. switch ($this->ldapGroupMemberAssocAttr) {
  713. case 'uniquemember':
  714. case 'member':
  715. $uid = $userDN;
  716. break;
  717. case 'memberuid':
  718. case 'zimbramailforwardingaddress':
  719. $result = $this->access->readAttribute($userDN, 'uid');
  720. if ($result === false) {
  721. $this->logger->debug('No uid attribute found for DN {dn} on {host}',
  722. [
  723. 'app' => 'user_ldap',
  724. 'dn' => $userDN,
  725. 'host' => $this->access->connection->ldapHost,
  726. ]
  727. );
  728. $uid = false;
  729. } else {
  730. $uid = $result[0];
  731. }
  732. break;
  733. default:
  734. // just in case
  735. $uid = $userDN;
  736. break;
  737. }
  738. if ($uid !== false) {
  739. $groupsByMember = array_values($this->getGroupsByMember($uid));
  740. $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
  741. $groups = array_merge($groups, $groupsByMember);
  742. }
  743. }
  744. if ($primaryGroup !== false) {
  745. $groups[] = $primaryGroup;
  746. }
  747. if ($gidGroupName !== false) {
  748. $groups[] = $gidGroupName;
  749. }
  750. if (empty($groups) && !$this->isUserOnLDAP($ncUid)) {
  751. // Groups are enabled, but you user has none? Potentially suspicious:
  752. // it could be that the user was deleted from LDAP, but we are not
  753. // aware of it yet.
  754. $groups = $this->getCachedGroupsForUserId($ncUid);
  755. $this->access->connection->writeToCache($cacheKey, $groups);
  756. return $groups;
  757. }
  758. $groups = array_values(array_unique($groups, SORT_LOCALE_STRING));
  759. $this->access->connection->writeToCache($cacheKey, $groups);
  760. $groupStr = \json_encode($groups);
  761. $this->config->setUserValue($ncUid, 'user_ldap', 'cached-group-memberships-' . $this->access->connection->getConfigPrefix(), $groupStr);
  762. return $groups;
  763. }
  764. /**
  765. * @return array[]
  766. * @throws ServerNotAvailableException
  767. */
  768. private function getGroupsByMember(string $dn, array &$seen = []): array {
  769. if (isset($seen[$dn])) {
  770. return [];
  771. }
  772. $seen[$dn] = true;
  773. if (isset($this->cachedGroupsByMember[$dn])) {
  774. return $this->cachedGroupsByMember[$dn];
  775. }
  776. $filter = $this->access->connection->ldapGroupMemberAssocAttr . '=' . $dn;
  777. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  778. //in this case the member entries are email addresses
  779. $filter .= '@*';
  780. }
  781. $nesting = (int)$this->access->connection->ldapNestedGroups;
  782. if ($nesting === 0) {
  783. $filter = $this->access->combineFilterWithAnd([$filter, $this->access->connection->ldapGroupFilter]);
  784. }
  785. $allGroups = [];
  786. $groups = $this->access->fetchListOfGroups($filter,
  787. [strtolower($this->access->connection->ldapGroupMemberAssocAttr), $this->access->connection->ldapGroupDisplayName, 'dn']);
  788. if ($nesting === 1) {
  789. while ($record = array_shift($groups)) {
  790. // Note: this has no effect when ldapGroupMemberAssocAttr is uid based
  791. $nestedParents = $this->getGroupsByMember($record['dn'][0], $seen);
  792. $groups = array_merge($groups, $nestedParents);
  793. $allGroups[] = $record;
  794. }
  795. } else {
  796. $allGroups = $groups;
  797. }
  798. $visibleGroups = $this->filterValidGroups($allGroups);
  799. $this->cachedGroupsByMember[$dn] = $visibleGroups;
  800. return $visibleGroups;
  801. }
  802. /**
  803. * get a list of all users in a group
  804. *
  805. * @param string $gid
  806. * @param string $search
  807. * @param int $limit
  808. * @param int $offset
  809. * @return array<int,string> user ids
  810. * @throws Exception
  811. * @throws ServerNotAvailableException
  812. */
  813. public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  814. if (!$this->enabled) {
  815. return [];
  816. }
  817. if (!$this->groupExists($gid)) {
  818. return [];
  819. }
  820. $search = $this->access->escapeFilterPart($search, true);
  821. $cacheKey = 'usersInGroup-' . $gid . '-' . $search . '-' . $limit . '-' . $offset;
  822. // check for cache of the exact query
  823. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  824. if (!is_null($groupUsers)) {
  825. return $groupUsers;
  826. }
  827. if ($limit === -1) {
  828. $limit = null;
  829. }
  830. // check for cache of the query without limit and offset
  831. $groupUsers = $this->access->connection->getFromCache('usersInGroup-' . $gid . '-' . $search);
  832. if (!is_null($groupUsers)) {
  833. $groupUsers = array_slice($groupUsers, $offset, $limit);
  834. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  835. return $groupUsers;
  836. }
  837. $groupDN = $this->access->groupname2dn($gid);
  838. if (!$groupDN) {
  839. // group couldn't be found, return empty result-set
  840. $this->access->connection->writeToCache($cacheKey, []);
  841. return [];
  842. }
  843. $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
  844. $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
  845. $members = $this->_groupMembers($groupDN);
  846. if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
  847. //in case users could not be retrieved, return empty result set
  848. $this->access->connection->writeToCache($cacheKey, []);
  849. return [];
  850. }
  851. $groupUsers = [];
  852. $attrs = $this->access->userManager->getAttributes(true);
  853. foreach ($members as $member) {
  854. switch ($this->ldapGroupMemberAssocAttr) {
  855. /** @noinspection PhpMissingBreakStatementInspection */
  856. case 'zimbramailforwardingaddress':
  857. //we get email addresses and need to convert them to uids
  858. $parts = explode('@', $member);
  859. $member = $parts[0];
  860. //no break needed because we just needed to remove the email part and now we have uids
  861. case 'memberuid':
  862. //we got uids, need to get their DNs to 'translate' them to user names
  863. $filter = $this->access->combineFilterWithAnd([
  864. str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
  865. $this->access->combineFilterWithAnd([
  866. $this->access->getFilterPartForUserSearch($search),
  867. $this->access->connection->ldapUserFilter
  868. ])
  869. ]);
  870. $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
  871. if (empty($ldap_users)) {
  872. break;
  873. }
  874. $uid = $this->access->dn2username($ldap_users[0]['dn'][0]);
  875. if (!$uid) {
  876. break;
  877. }
  878. $groupUsers[] = $uid;
  879. break;
  880. default:
  881. //we got DNs, check if we need to filter by search or we can give back all of them
  882. $uid = $this->access->dn2username($member);
  883. if (!$uid) {
  884. break;
  885. }
  886. $cacheKey = 'userExistsOnLDAP' . $uid;
  887. $userExists = $this->access->connection->getFromCache($cacheKey);
  888. if ($userExists === false) {
  889. break;
  890. }
  891. if ($userExists === null || $search !== '') {
  892. if (!$this->access->readAttribute($member,
  893. $this->access->connection->ldapUserDisplayName,
  894. $this->access->combineFilterWithAnd([
  895. $this->access->getFilterPartForUserSearch($search),
  896. $this->access->connection->ldapUserFilter
  897. ]))) {
  898. if ($search === '') {
  899. $this->access->connection->writeToCache($cacheKey, false);
  900. }
  901. break;
  902. }
  903. $this->access->connection->writeToCache($cacheKey, true);
  904. }
  905. $groupUsers[] = $uid;
  906. break;
  907. }
  908. }
  909. $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
  910. natsort($groupUsers);
  911. $this->access->connection->writeToCache('usersInGroup-' . $gid . '-' . $search, $groupUsers);
  912. $groupUsers = array_slice($groupUsers, $offset, $limit);
  913. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  914. return $groupUsers;
  915. }
  916. /**
  917. * returns the number of users in a group, who match the search term
  918. *
  919. * @param string $gid the internal group name
  920. * @param string $search optional, a search string
  921. * @return int|bool
  922. * @throws Exception
  923. * @throws ServerNotAvailableException
  924. */
  925. public function countUsersInGroup($gid, $search = '') {
  926. if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
  927. return $this->groupPluginManager->countUsersInGroup($gid, $search);
  928. }
  929. $cacheKey = 'countUsersInGroup-' . $gid . '-' . $search;
  930. if (!$this->enabled || !$this->groupExists($gid)) {
  931. return false;
  932. }
  933. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  934. if (!is_null($groupUsers)) {
  935. return $groupUsers;
  936. }
  937. $groupDN = $this->access->groupname2dn($gid);
  938. if (!$groupDN) {
  939. // group couldn't be found, return empty result set
  940. $this->access->connection->writeToCache($cacheKey, false);
  941. return false;
  942. }
  943. $members = $this->_groupMembers($groupDN);
  944. $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
  945. if (!$members && $primaryUserCount === 0) {
  946. //in case users could not be retrieved, return empty result set
  947. $this->access->connection->writeToCache($cacheKey, false);
  948. return false;
  949. }
  950. if ($search === '') {
  951. $groupUsers = count($members) + $primaryUserCount;
  952. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  953. return $groupUsers;
  954. }
  955. $search = $this->access->escapeFilterPart($search, true);
  956. $isMemberUid =
  957. ($this->ldapGroupMemberAssocAttr === 'memberuid' ||
  958. $this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress');
  959. //we need to apply the search filter
  960. //alternatives that need to be checked:
  961. //a) get all users by search filter and array_intersect them
  962. //b) a, but only when less than 1k 10k ?k users like it is
  963. //c) put all DNs|uids in a LDAP filter, combine with the search string
  964. // and let it count.
  965. //For now this is not important, because the only use of this method
  966. //does not supply a search string
  967. $groupUsers = [];
  968. foreach ($members as $member) {
  969. if ($isMemberUid) {
  970. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  971. //we get email addresses and need to convert them to uids
  972. $parts = explode('@', $member);
  973. $member = $parts[0];
  974. }
  975. //we got uids, need to get their DNs to 'translate' them to user names
  976. $filter = $this->access->combineFilterWithAnd([
  977. str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
  978. $this->access->getFilterPartForUserSearch($search)
  979. ]);
  980. $ldap_users = $this->access->fetchListOfUsers($filter, ['dn'], 1);
  981. if (count($ldap_users) < 1) {
  982. continue;
  983. }
  984. $groupUsers[] = $this->access->dn2username($ldap_users[0]);
  985. } else {
  986. //we need to apply the search filter now
  987. if (!$this->access->readAttribute($member,
  988. $this->access->connection->ldapUserDisplayName,
  989. $this->access->getFilterPartForUserSearch($search))) {
  990. continue;
  991. }
  992. // dn2username will also check if the users belong to the allowed base
  993. if ($ncGroupId = $this->access->dn2username($member)) {
  994. $groupUsers[] = $ncGroupId;
  995. }
  996. }
  997. }
  998. //and get users that have the group as primary
  999. $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
  1000. return count($groupUsers) + $primaryUsers;
  1001. }
  1002. /**
  1003. * get a list of all groups using a paged search
  1004. *
  1005. * @param string $search
  1006. * @param int $limit
  1007. * @param int $offset
  1008. * @return array with group names
  1009. *
  1010. * Returns a list with all groups
  1011. * Uses a paged search if available to override a
  1012. * server side search limit.
  1013. * (active directory has a limit of 1000 by default)
  1014. * @throws Exception
  1015. */
  1016. public function getGroups($search = '', $limit = -1, $offset = 0) {
  1017. if (!$this->enabled) {
  1018. return [];
  1019. }
  1020. $search = $this->access->escapeFilterPart($search, true);
  1021. $cacheKey = 'getGroups-' . $search . '-' . $limit . '-' . $offset;
  1022. //Check cache before driving unnecessary searches
  1023. $ldap_groups = $this->access->connection->getFromCache($cacheKey);
  1024. if (!is_null($ldap_groups)) {
  1025. return $ldap_groups;
  1026. }
  1027. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  1028. // error. With a limit of 0, we get 0 results. So we pass null.
  1029. if ($limit <= 0) {
  1030. $limit = null;
  1031. }
  1032. $filter = $this->access->combineFilterWithAnd([
  1033. $this->access->connection->ldapGroupFilter,
  1034. $this->access->getFilterPartForGroupSearch($search)
  1035. ]);
  1036. $ldap_groups = $this->access->fetchListOfGroups($filter,
  1037. [$this->access->connection->ldapGroupDisplayName, 'dn'],
  1038. $limit,
  1039. $offset);
  1040. $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
  1041. $this->access->connection->writeToCache($cacheKey, $ldap_groups);
  1042. return $ldap_groups;
  1043. }
  1044. /**
  1045. * check if a group exists
  1046. *
  1047. * @param string $gid
  1048. * @return bool
  1049. * @throws ServerNotAvailableException
  1050. */
  1051. public function groupExists($gid) {
  1052. $groupExists = $this->access->connection->getFromCache('groupExists' . $gid);
  1053. if (!is_null($groupExists)) {
  1054. return (bool)$groupExists;
  1055. }
  1056. //getting dn, if false the group does not exist. If dn, it may be mapped
  1057. //only, requires more checking.
  1058. $dn = $this->access->groupname2dn($gid);
  1059. if (!$dn) {
  1060. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1061. return false;
  1062. }
  1063. if (!$this->access->isDNPartOfBase($dn, $this->access->connection->ldapBaseGroups)) {
  1064. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1065. return false;
  1066. }
  1067. //if group really still exists, we will be able to read its objectClass
  1068. if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapGroupFilter))) {
  1069. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1070. return false;
  1071. }
  1072. $this->access->connection->writeToCache('groupExists' . $gid, true);
  1073. return true;
  1074. }
  1075. /**
  1076. * @template T
  1077. * @param array<array-key, T> $listOfGroups
  1078. * @return array<array-key, T>
  1079. * @throws ServerNotAvailableException
  1080. * @throws Exception
  1081. */
  1082. protected function filterValidGroups(array $listOfGroups): array {
  1083. $validGroupDNs = [];
  1084. foreach ($listOfGroups as $key => $item) {
  1085. $dn = is_string($item) ? $item : $item['dn'][0];
  1086. if (is_array($item) && !isset($item[$this->access->connection->ldapGroupDisplayName][0])) {
  1087. continue;
  1088. }
  1089. $name = $item[$this->access->connection->ldapGroupDisplayName][0] ?? null;
  1090. $gid = $this->access->dn2groupname($dn, $name);
  1091. if (!$gid) {
  1092. continue;
  1093. }
  1094. if ($this->groupExists($gid)) {
  1095. $validGroupDNs[$key] = $item;
  1096. }
  1097. }
  1098. return $validGroupDNs;
  1099. }
  1100. /**
  1101. * Check if backend implements actions
  1102. *
  1103. * @param int $actions bitwise-or'ed actions
  1104. * @return boolean
  1105. *
  1106. * Returns the supported actions as int to be
  1107. * compared with GroupInterface::CREATE_GROUP etc.
  1108. */
  1109. public function implementsActions($actions): bool {
  1110. return (bool)((GroupInterface::COUNT_USERS |
  1111. GroupInterface::DELETE_GROUP |
  1112. GroupInterface::IS_ADMIN |
  1113. $this->groupPluginManager->getImplementedActions()) & $actions);
  1114. }
  1115. /**
  1116. * Return access for LDAP interaction.
  1117. *
  1118. * @return Access instance of Access for LDAP interaction
  1119. */
  1120. public function getLDAPAccess($gid) {
  1121. return $this->access;
  1122. }
  1123. /**
  1124. * create a group
  1125. *
  1126. * @param string $gid
  1127. * @return bool
  1128. * @throws Exception
  1129. * @throws ServerNotAvailableException
  1130. */
  1131. public function createGroup($gid) {
  1132. if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
  1133. if ($dn = $this->groupPluginManager->createGroup($gid)) {
  1134. //updates group mapping
  1135. $uuid = $this->access->getUUID($dn, false);
  1136. if (is_string($uuid)) {
  1137. $this->access->mapAndAnnounceIfApplicable(
  1138. $this->access->getGroupMapper(),
  1139. $dn,
  1140. $gid,
  1141. $uuid,
  1142. false
  1143. );
  1144. $this->access->cacheGroupExists($gid);
  1145. }
  1146. }
  1147. return $dn != null;
  1148. }
  1149. throw new Exception('Could not create group in LDAP backend.');
  1150. }
  1151. /**
  1152. * delete a group
  1153. *
  1154. * @param string $gid gid of the group to delete
  1155. * @throws Exception
  1156. */
  1157. public function deleteGroup(string $gid): bool {
  1158. if ($this->groupPluginManager->canDeleteGroup()) {
  1159. if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
  1160. // Delete group in nextcloud internal db
  1161. $this->access->getGroupMapper()->unmap($gid);
  1162. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1163. }
  1164. return $ret;
  1165. }
  1166. // Getting dn, if false the group is not mapped
  1167. $dn = $this->access->groupname2dn($gid);
  1168. if (!$dn) {
  1169. throw new Exception('Could not delete unknown group '.$gid.' in LDAP backend.');
  1170. }
  1171. if (!$this->groupExists($gid)) {
  1172. // The group does not exist in the LDAP, remove the mapping
  1173. $this->access->getGroupMapper()->unmap($gid);
  1174. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1175. return true;
  1176. }
  1177. throw new Exception('Could not delete existing group '.$gid.' in LDAP backend.');
  1178. }
  1179. /**
  1180. * Add a user to a group
  1181. *
  1182. * @param string $uid Name of the user to add to group
  1183. * @param string $gid Name of the group in which add the user
  1184. * @return bool
  1185. * @throws Exception
  1186. */
  1187. public function addToGroup($uid, $gid) {
  1188. if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
  1189. if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
  1190. $this->access->connection->clearCache();
  1191. unset($this->cachedGroupMembers[$gid]);
  1192. }
  1193. return $ret;
  1194. }
  1195. throw new Exception('Could not add user to group in LDAP backend.');
  1196. }
  1197. /**
  1198. * Removes a user from a group
  1199. *
  1200. * @param string $uid Name of the user to remove from group
  1201. * @param string $gid Name of the group from which remove the user
  1202. * @return bool
  1203. * @throws Exception
  1204. */
  1205. public function removeFromGroup($uid, $gid) {
  1206. if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
  1207. if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
  1208. $this->access->connection->clearCache();
  1209. unset($this->cachedGroupMembers[$gid]);
  1210. }
  1211. return $ret;
  1212. }
  1213. throw new Exception('Could not remove user from group in LDAP backend.');
  1214. }
  1215. /**
  1216. * Gets group details
  1217. *
  1218. * @param string $gid Name of the group
  1219. * @return array|false
  1220. * @throws Exception
  1221. */
  1222. public function getGroupDetails($gid) {
  1223. if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
  1224. return $this->groupPluginManager->getGroupDetails($gid);
  1225. }
  1226. throw new Exception('Could not get group details in LDAP backend.');
  1227. }
  1228. /**
  1229. * Return LDAP connection resource from a cloned connection.
  1230. * The cloned connection needs to be closed manually.
  1231. * of the current access.
  1232. *
  1233. * @param string $gid
  1234. * @return resource|\LDAP\Connection The LDAP connection
  1235. * @throws ServerNotAvailableException
  1236. */
  1237. public function getNewLDAPConnection($gid) {
  1238. $connection = clone $this->access->getConnection();
  1239. return $connection->getConnectionResource();
  1240. }
  1241. /**
  1242. * @throws ServerNotAvailableException
  1243. */
  1244. public function getDisplayName(string $gid): string {
  1245. if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
  1246. return $this->groupPluginManager->getDisplayName($gid);
  1247. }
  1248. $cacheKey = 'group_getDisplayName' . $gid;
  1249. if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  1250. return $displayName;
  1251. }
  1252. $displayName = $this->access->readAttribute(
  1253. $this->access->groupname2dn($gid),
  1254. $this->access->connection->ldapGroupDisplayName);
  1255. if (($displayName !== false) && (count($displayName) > 0)) {
  1256. $displayName = $displayName[0];
  1257. } else {
  1258. $displayName = '';
  1259. }
  1260. $this->access->connection->writeToCache($cacheKey, $displayName);
  1261. return $displayName;
  1262. }
  1263. /**
  1264. * @throws ServerNotAvailableException
  1265. */
  1266. public function isAdmin(string $uid): bool {
  1267. if (!$this->enabled) {
  1268. return false;
  1269. }
  1270. $ldapAdminGroup = $this->access->connection->ldapAdminGroup;
  1271. if ($ldapAdminGroup === '') {
  1272. return false;
  1273. }
  1274. return $this->inGroup($uid, $ldapAdminGroup);
  1275. }
  1276. }