1
0

Group_LDAP.php 46 KB

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