1
0

Group_LDAP.php 44 KB

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