Access.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984
  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 DomainException;
  9. use OC\Hooks\PublicEmitter;
  10. use OC\ServerNotAvailableException;
  11. use OCA\User_LDAP\Exceptions\ConstraintViolationException;
  12. use OCA\User_LDAP\Exceptions\NoMoreResults;
  13. use OCA\User_LDAP\Mapping\AbstractMapping;
  14. use OCA\User_LDAP\User\Manager;
  15. use OCA\User_LDAP\User\OfflineUser;
  16. use OCP\HintException;
  17. use OCP\IAppConfig;
  18. use OCP\IConfig;
  19. use OCP\IUserManager;
  20. use Psr\Log\LoggerInterface;
  21. use function strlen;
  22. use function substr;
  23. /**
  24. * Class Access
  25. *
  26. * @package OCA\User_LDAP
  27. */
  28. class Access extends LDAPUtility {
  29. public const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
  30. /**
  31. * never ever check this var directly, always use getPagedSearchResultState
  32. * @var ?bool
  33. */
  34. protected $pagedSearchedSuccessful;
  35. /** @var ?AbstractMapping */
  36. protected $userMapper;
  37. /** @var ?AbstractMapping */
  38. protected $groupMapper;
  39. private string $lastCookie = '';
  40. public function __construct(
  41. ILDAPWrapper $ldap,
  42. public Connection $connection,
  43. public Manager $userManager,
  44. private Helper $helper,
  45. private IConfig $config,
  46. private IUserManager $ncUserManager,
  47. private LoggerInterface $logger,
  48. private IAppConfig $appConfig,
  49. ) {
  50. parent::__construct($ldap);
  51. $this->connection = $connection;
  52. $this->userManager = $userManager;
  53. $this->userManager->setLdapAccess($this);
  54. $this->helper = $helper;
  55. $this->config = $config;
  56. $this->ncUserManager = $ncUserManager;
  57. $this->logger = $logger;
  58. }
  59. /**
  60. * sets the User Mapper
  61. */
  62. public function setUserMapper(AbstractMapping $mapper): void {
  63. $this->userMapper = $mapper;
  64. }
  65. /**
  66. * @throws \Exception
  67. */
  68. public function getUserMapper(): AbstractMapping {
  69. if (is_null($this->userMapper)) {
  70. throw new \Exception('UserMapper was not assigned to this Access instance.');
  71. }
  72. return $this->userMapper;
  73. }
  74. /**
  75. * sets the Group Mapper
  76. */
  77. public function setGroupMapper(AbstractMapping $mapper): void {
  78. $this->groupMapper = $mapper;
  79. }
  80. /**
  81. * returns the Group Mapper
  82. *
  83. * @throws \Exception
  84. */
  85. public function getGroupMapper(): AbstractMapping {
  86. if (is_null($this->groupMapper)) {
  87. throw new \Exception('GroupMapper was not assigned to this Access instance.');
  88. }
  89. return $this->groupMapper;
  90. }
  91. /**
  92. * @return bool
  93. */
  94. private function checkConnection() {
  95. return ($this->connection instanceof Connection);
  96. }
  97. /**
  98. * returns the Connection instance
  99. *
  100. * @return \OCA\User_LDAP\Connection
  101. */
  102. public function getConnection() {
  103. return $this->connection;
  104. }
  105. /**
  106. * reads a given attribute for an LDAP record identified by a DN
  107. *
  108. * @param string $dn the record in question
  109. * @param string $attr the attribute that shall be retrieved
  110. * if empty, just check the record's existence
  111. * @param string $filter
  112. * @return array|false an array of values on success or an empty
  113. * array if $attr is empty, false otherwise
  114. * @throws ServerNotAvailableException
  115. */
  116. public function readAttribute(string $dn, string $attr, string $filter = 'objectClass=*') {
  117. if (!$this->checkConnection()) {
  118. $this->logger->warning(
  119. 'No LDAP Connector assigned, access impossible for readAttribute.',
  120. ['app' => 'user_ldap']
  121. );
  122. return false;
  123. }
  124. $cr = $this->connection->getConnectionResource();
  125. $attr = mb_strtolower($attr, 'UTF-8');
  126. // the actual read attribute later may contain parameters on a ranged
  127. // request, e.g. member;range=99-199. Depends on server reply.
  128. $attrToRead = $attr;
  129. $values = [];
  130. $isRangeRequest = false;
  131. do {
  132. $result = $this->executeRead($dn, $attrToRead, $filter);
  133. if (is_bool($result)) {
  134. // when an exists request was run and it was successful, an empty
  135. // array must be returned
  136. return $result ? [] : false;
  137. }
  138. if (!$isRangeRequest) {
  139. $values = $this->extractAttributeValuesFromResult($result, $attr);
  140. if (!empty($values)) {
  141. return $values;
  142. }
  143. }
  144. $isRangeRequest = false;
  145. $result = $this->extractRangeData($result, $attr);
  146. if (!empty($result)) {
  147. $normalizedResult = $this->extractAttributeValuesFromResult(
  148. [$attr => $result['values']],
  149. $attr
  150. );
  151. $values = array_merge($values, $normalizedResult);
  152. if ($result['rangeHigh'] === '*') {
  153. // when server replies with * as high range value, there are
  154. // no more results left
  155. return $values;
  156. } else {
  157. $low = $result['rangeHigh'] + 1;
  158. $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
  159. $isRangeRequest = true;
  160. }
  161. }
  162. } while ($isRangeRequest);
  163. $this->logger->debug('Requested attribute ' . $attr . ' not found for ' . $dn, ['app' => 'user_ldap']);
  164. return false;
  165. }
  166. /**
  167. * Runs an read operation against LDAP
  168. *
  169. * @return array|bool false if there was any error, true if an exists check
  170. * was performed and the requested DN found, array with the
  171. * returned data on a successful usual operation
  172. * @throws ServerNotAvailableException
  173. */
  174. public function executeRead(string $dn, string $attribute, string $filter) {
  175. $dn = $this->helper->DNasBaseParameter($dn);
  176. $rr = @$this->invokeLDAPMethod('read', $dn, $filter, [$attribute]);
  177. if (!$this->ldap->isResource($rr)) {
  178. if ($attribute !== '') {
  179. //do not throw this message on userExists check, irritates
  180. $this->logger->debug('readAttribute failed for DN ' . $dn, ['app' => 'user_ldap']);
  181. }
  182. //in case an error occurs , e.g. object does not exist
  183. return false;
  184. }
  185. if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $rr) === 1)) {
  186. $this->logger->debug('readAttribute: ' . $dn . ' found', ['app' => 'user_ldap']);
  187. return true;
  188. }
  189. $er = $this->invokeLDAPMethod('firstEntry', $rr);
  190. if (!$this->ldap->isResource($er)) {
  191. //did not match the filter, return false
  192. return false;
  193. }
  194. //LDAP attributes are not case sensitive
  195. $result = \OCP\Util::mb_array_change_key_case(
  196. $this->invokeLDAPMethod('getAttributes', $er), MB_CASE_LOWER, 'UTF-8');
  197. return $result;
  198. }
  199. /**
  200. * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
  201. * data if present.
  202. *
  203. * DN values are escaped as per RFC 2253
  204. *
  205. * @param array $result from ILDAPWrapper::getAttributes()
  206. * @param string $attribute the attribute name that was read
  207. * @return string[]
  208. */
  209. public function extractAttributeValuesFromResult($result, $attribute) {
  210. $values = [];
  211. if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
  212. $lowercaseAttribute = strtolower($attribute);
  213. for ($i = 0; $i < $result[$attribute]['count']; $i++) {
  214. if ($this->resemblesDN($attribute)) {
  215. $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
  216. } elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
  217. $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
  218. } else {
  219. $values[] = $result[$attribute][$i];
  220. }
  221. }
  222. }
  223. return $values;
  224. }
  225. /**
  226. * Attempts to find ranged data in a getAttribute results and extracts the
  227. * returned values as well as information on the range and full attribute
  228. * name for further processing.
  229. *
  230. * @param array $result from ILDAPWrapper::getAttributes()
  231. * @param string $attribute the attribute name that was read. Without ";range=…"
  232. * @return array If a range was detected with keys 'values', 'attributeName',
  233. * 'attributeFull' and 'rangeHigh', otherwise empty.
  234. */
  235. public function extractRangeData($result, $attribute) {
  236. $keys = array_keys($result);
  237. foreach ($keys as $key) {
  238. if ($key !== $attribute && str_starts_with((string)$key, $attribute)) {
  239. $queryData = explode(';', (string)$key);
  240. if (str_starts_with($queryData[1], 'range=')) {
  241. $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
  242. $data = [
  243. 'values' => $result[$key],
  244. 'attributeName' => $queryData[0],
  245. 'attributeFull' => $key,
  246. 'rangeHigh' => $high,
  247. ];
  248. return $data;
  249. }
  250. }
  251. }
  252. return [];
  253. }
  254. /**
  255. * Set password for an LDAP user identified by a DN
  256. *
  257. * @param string $userDN the user in question
  258. * @param string $password the new password
  259. * @return bool
  260. * @throws HintException
  261. * @throws \Exception
  262. */
  263. public function setPassword($userDN, $password) {
  264. if ((int)$this->connection->turnOnPasswordChange !== 1) {
  265. throw new \Exception('LDAP password changes are disabled.');
  266. }
  267. $cr = $this->connection->getConnectionResource();
  268. try {
  269. // try PASSWD extended operation first
  270. return @$this->invokeLDAPMethod('exopPasswd', $userDN, '', $password) ||
  271. @$this->invokeLDAPMethod('modReplace', $userDN, $password);
  272. } catch (ConstraintViolationException $e) {
  273. throw new HintException('Password change rejected.', \OCP\Util::getL10N('user_ldap')->t('Password change rejected. Hint: ') . $e->getMessage(), (int)$e->getCode());
  274. }
  275. }
  276. /**
  277. * checks whether the given attributes value is probably a DN
  278. *
  279. * @param string $attr the attribute in question
  280. * @return boolean if so true, otherwise false
  281. */
  282. private function resemblesDN($attr) {
  283. $resemblingAttributes = [
  284. 'dn',
  285. 'uniquemember',
  286. 'member',
  287. // memberOf is an "operational" attribute, without a definition in any RFC
  288. 'memberof'
  289. ];
  290. return in_array($attr, $resemblingAttributes);
  291. }
  292. /**
  293. * checks whether the given string is probably a DN
  294. *
  295. * @param string $string
  296. * @return boolean
  297. */
  298. public function stringResemblesDN($string) {
  299. $r = $this->ldap->explodeDN($string, 0);
  300. // if exploding a DN succeeds and does not end up in
  301. // an empty array except for $r[count] being 0.
  302. return (is_array($r) && count($r) > 1);
  303. }
  304. /**
  305. * returns a DN-string that is cleaned from not domain parts, e.g.
  306. * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
  307. * becomes dc=foobar,dc=server,dc=org
  308. *
  309. * @param string $dn
  310. * @return string
  311. */
  312. public function getDomainDNFromDN($dn) {
  313. $allParts = $this->ldap->explodeDN($dn, 0);
  314. if ($allParts === false) {
  315. //not a valid DN
  316. return '';
  317. }
  318. $domainParts = [];
  319. $dcFound = false;
  320. foreach ($allParts as $part) {
  321. if (!$dcFound && str_starts_with($part, 'dc=')) {
  322. $dcFound = true;
  323. }
  324. if ($dcFound) {
  325. $domainParts[] = $part;
  326. }
  327. }
  328. return implode(',', $domainParts);
  329. }
  330. /**
  331. * returns the LDAP DN for the given internal Nextcloud name of the group
  332. *
  333. * @param string $name the Nextcloud name in question
  334. * @return string|false LDAP DN on success, otherwise false
  335. */
  336. public function groupname2dn($name) {
  337. return $this->getGroupMapper()->getDNByName($name);
  338. }
  339. /**
  340. * returns the LDAP DN for the given internal Nextcloud name of the user
  341. *
  342. * @param string $name the Nextcloud name in question
  343. * @return string|false with the LDAP DN on success, otherwise false
  344. */
  345. public function username2dn($name) {
  346. $fdn = $this->getUserMapper()->getDNByName($name);
  347. //Check whether the DN belongs to the Base, to avoid issues on multi-
  348. //server setups
  349. if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
  350. return $fdn;
  351. }
  352. return false;
  353. }
  354. /**
  355. * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
  356. *
  357. * @param string $fdn the dn of the group object
  358. * @param string $ldapName optional, the display name of the object
  359. * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
  360. * @throws \Exception
  361. */
  362. public function dn2groupname($fdn, $ldapName = null) {
  363. //To avoid bypassing the base DN settings under certain circumstances
  364. //with the group support, check whether the provided DN matches one of
  365. //the given Bases
  366. if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
  367. return false;
  368. }
  369. return $this->dn2ocname($fdn, $ldapName, false);
  370. }
  371. /**
  372. * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
  373. *
  374. * @param string $fdn the dn of the user object
  375. * @param string $ldapName optional, the display name of the object
  376. * @return string|false with with the name to use in Nextcloud
  377. * @throws \Exception
  378. */
  379. public function dn2username($fdn, $ldapName = null) {
  380. //To avoid bypassing the base DN settings under certain circumstances
  381. //with the group support, check whether the provided DN matches one of
  382. //the given Bases
  383. if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
  384. return false;
  385. }
  386. return $this->dn2ocname($fdn, $ldapName, true);
  387. }
  388. /**
  389. * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
  390. *
  391. * @param string $fdn the dn of the user object
  392. * @param string|null $ldapName optional, the display name of the object
  393. * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
  394. * @param bool|null $newlyMapped
  395. * @param array|null $record
  396. * @return false|string with with the name to use in Nextcloud
  397. * @throws \Exception
  398. */
  399. public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, ?array $record = null) {
  400. static $intermediates = [];
  401. if (isset($intermediates[($isUser ? 'user-' : 'group-') . $fdn])) {
  402. return false; // is a known intermediate
  403. }
  404. $newlyMapped = false;
  405. if ($isUser) {
  406. $mapper = $this->getUserMapper();
  407. $nameAttribute = $this->connection->ldapUserDisplayName;
  408. $filter = $this->connection->ldapUserFilter;
  409. } else {
  410. $mapper = $this->getGroupMapper();
  411. $nameAttribute = $this->connection->ldapGroupDisplayName;
  412. $filter = $this->connection->ldapGroupFilter;
  413. }
  414. //let's try to retrieve the Nextcloud name from the mappings table
  415. $ncName = $mapper->getNameByDN($fdn);
  416. if (is_string($ncName)) {
  417. return $ncName;
  418. }
  419. //second try: get the UUID and check if it is known. Then, update the DN and return the name.
  420. $uuid = $this->getUUID($fdn, $isUser, $record);
  421. if (is_string($uuid)) {
  422. $ncName = $mapper->getNameByUUID($uuid);
  423. if (is_string($ncName)) {
  424. $mapper->setDNbyUUID($fdn, $uuid);
  425. return $ncName;
  426. }
  427. } else {
  428. //If the UUID can't be detected something is foul.
  429. $this->logger->debug('Cannot determine UUID for ' . $fdn . '. Skipping.', ['app' => 'user_ldap']);
  430. return false;
  431. }
  432. if (is_null($ldapName)) {
  433. $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
  434. if (!isset($ldapName[0]) || empty($ldapName[0])) {
  435. $this->logger->debug('No or empty name for ' . $fdn . ' with filter ' . $filter . '.', ['app' => 'user_ldap']);
  436. $intermediates[($isUser ? 'user-' : 'group-') . $fdn] = true;
  437. return false;
  438. }
  439. $ldapName = $ldapName[0];
  440. }
  441. if ($isUser) {
  442. $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
  443. if ($usernameAttribute !== '') {
  444. $username = $this->readAttribute($fdn, $usernameAttribute);
  445. if (!isset($username[0]) || empty($username[0])) {
  446. $this->logger->debug('No or empty username (' . $usernameAttribute . ') for ' . $fdn . '.', ['app' => 'user_ldap']);
  447. return false;
  448. }
  449. $username = $username[0];
  450. } else {
  451. $username = $uuid;
  452. }
  453. try {
  454. $intName = $this->sanitizeUsername($username);
  455. } catch (\InvalidArgumentException $e) {
  456. $this->logger->warning('Error sanitizing username: ' . $e->getMessage(), [
  457. 'exception' => $e,
  458. ]);
  459. // we don't attempt to set a username here. We can go for
  460. // for an alternative 4 digit random number as we would append
  461. // otherwise, however it's likely not enough space in bigger
  462. // setups, and most importantly: this is not intended.
  463. return false;
  464. }
  465. } else {
  466. $intName = $this->sanitizeGroupIDCandidate($ldapName);
  467. }
  468. //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
  469. //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
  470. //NOTE: mind, disabling cache affects only this instance! Using it
  471. // outside of core user management will still cache the user as non-existing.
  472. $originalTTL = $this->connection->ldapCacheTTL;
  473. $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
  474. if ($intName !== ''
  475. && (($isUser && !$this->ncUserManager->userExists($intName))
  476. || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
  477. )
  478. ) {
  479. $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
  480. $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
  481. if ($newlyMapped) {
  482. return $intName;
  483. }
  484. }
  485. $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
  486. $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
  487. if (is_string($altName)) {
  488. if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
  489. $this->logger->warning(
  490. 'Mapped {fdn} as {altName} because of a name collision on {intName}.',
  491. [
  492. 'fdn' => $fdn,
  493. 'altName' => $altName,
  494. 'intName' => $intName,
  495. 'app' => 'user_ldap',
  496. ]
  497. );
  498. $newlyMapped = true;
  499. return $altName;
  500. }
  501. }
  502. //if everything else did not help..
  503. $this->logger->info('Could not create unique name for ' . $fdn . '.', ['app' => 'user_ldap']);
  504. return false;
  505. }
  506. public function mapAndAnnounceIfApplicable(
  507. AbstractMapping $mapper,
  508. string $fdn,
  509. string $name,
  510. string $uuid,
  511. bool $isUser
  512. ): bool {
  513. if ($mapper->map($fdn, $name, $uuid)) {
  514. if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
  515. $this->cacheUserExists($name);
  516. $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
  517. } elseif (!$isUser) {
  518. $this->cacheGroupExists($name);
  519. }
  520. return true;
  521. }
  522. return false;
  523. }
  524. /**
  525. * gives back the user names as they are used ownClod internally
  526. *
  527. * @param array $ldapUsers as returned by fetchList()
  528. * @return array<int,string> an array with the user names to use in Nextcloud
  529. *
  530. * gives back the user names as they are used ownClod internally
  531. * @throws \Exception
  532. */
  533. public function nextcloudUserNames($ldapUsers) {
  534. return $this->ldap2NextcloudNames($ldapUsers, true);
  535. }
  536. /**
  537. * gives back the group names as they are used ownClod internally
  538. *
  539. * @param array $ldapGroups as returned by fetchList()
  540. * @return array<int,string> an array with the group names to use in Nextcloud
  541. *
  542. * gives back the group names as they are used ownClod internally
  543. * @throws \Exception
  544. */
  545. public function nextcloudGroupNames($ldapGroups) {
  546. return $this->ldap2NextcloudNames($ldapGroups, false);
  547. }
  548. /**
  549. * @param array[] $ldapObjects as returned by fetchList()
  550. * @return array<int,string>
  551. * @throws \Exception
  552. */
  553. private function ldap2NextcloudNames(array $ldapObjects, bool $isUsers): array {
  554. if ($isUsers) {
  555. $nameAttribute = $this->connection->ldapUserDisplayName;
  556. $sndAttribute = $this->connection->ldapUserDisplayName2;
  557. } else {
  558. $nameAttribute = $this->connection->ldapGroupDisplayName;
  559. $sndAttribute = null;
  560. }
  561. $nextcloudNames = [];
  562. foreach ($ldapObjects as $ldapObject) {
  563. $nameByLDAP = $ldapObject[$nameAttribute][0] ?? null;
  564. $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
  565. if ($ncName) {
  566. $nextcloudNames[] = $ncName;
  567. if ($isUsers) {
  568. $this->updateUserState($ncName);
  569. //cache the user names so it does not need to be retrieved
  570. //again later (e.g. sharing dialogue).
  571. if (is_null($nameByLDAP)) {
  572. continue;
  573. }
  574. $sndName = $ldapObject[$sndAttribute][0] ?? '';
  575. $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
  576. } elseif ($nameByLDAP !== null) {
  577. $this->cacheGroupDisplayName($ncName, $nameByLDAP);
  578. }
  579. }
  580. }
  581. return $nextcloudNames;
  582. }
  583. /**
  584. * removes the deleted-flag of a user if it was set
  585. *
  586. * @param string $ncname
  587. * @throws \Exception
  588. */
  589. public function updateUserState($ncname): void {
  590. $user = $this->userManager->get($ncname);
  591. if ($user instanceof OfflineUser) {
  592. $user->unmark();
  593. }
  594. }
  595. /**
  596. * caches the user display name
  597. *
  598. * @param string $ocName the internal Nextcloud username
  599. * @param string|false $home the home directory path
  600. */
  601. public function cacheUserHome(string $ocName, $home): void {
  602. $cacheKey = 'getHome' . $ocName;
  603. $this->connection->writeToCache($cacheKey, $home);
  604. }
  605. /**
  606. * caches a user as existing
  607. */
  608. public function cacheUserExists(string $ocName): void {
  609. $this->connection->writeToCache('userExists' . $ocName, true);
  610. }
  611. /**
  612. * caches a group as existing
  613. */
  614. public function cacheGroupExists(string $gid): void {
  615. $this->connection->writeToCache('groupExists' . $gid, true);
  616. }
  617. /**
  618. * caches the user display name
  619. *
  620. * @param string $ocName the internal Nextcloud username
  621. * @param string $displayName the display name
  622. * @param string $displayName2 the second display name
  623. * @throws \Exception
  624. */
  625. public function cacheUserDisplayName(string $ocName, string $displayName, string $displayName2 = ''): void {
  626. $user = $this->userManager->get($ocName);
  627. if ($user === null) {
  628. return;
  629. }
  630. $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
  631. $cacheKeyTrunk = 'getDisplayName';
  632. $this->connection->writeToCache($cacheKeyTrunk . $ocName, $displayName);
  633. }
  634. public function cacheGroupDisplayName(string $ncName, string $displayName): void {
  635. $cacheKey = 'group_getDisplayName' . $ncName;
  636. $this->connection->writeToCache($cacheKey, $displayName);
  637. }
  638. /**
  639. * creates a unique name for internal Nextcloud use for users. Don't call it directly.
  640. *
  641. * @param string $name the display name of the object
  642. * @return string|false with with the name to use in Nextcloud or false if unsuccessful
  643. *
  644. * Instead of using this method directly, call
  645. * createAltInternalOwnCloudName($name, true)
  646. */
  647. private function _createAltInternalOwnCloudNameForUsers(string $name) {
  648. $attempts = 0;
  649. //while loop is just a precaution. If a name is not generated within
  650. //20 attempts, something else is very wrong. Avoids infinite loop.
  651. while ($attempts < 20) {
  652. $altName = $name . '_' . rand(1000, 9999);
  653. if (!$this->ncUserManager->userExists($altName)) {
  654. return $altName;
  655. }
  656. $attempts++;
  657. }
  658. return false;
  659. }
  660. /**
  661. * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
  662. *
  663. * @param string $name the display name of the object
  664. * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
  665. *
  666. * Instead of using this method directly, call
  667. * createAltInternalOwnCloudName($name, false)
  668. *
  669. * Group names are also used as display names, so we do a sequential
  670. * numbering, e.g. Developers_42 when there are 41 other groups called
  671. * "Developers"
  672. */
  673. private function _createAltInternalOwnCloudNameForGroups(string $name) {
  674. $usedNames = $this->getGroupMapper()->getNamesBySearch($name, "", '_%');
  675. if (count($usedNames) === 0) {
  676. $lastNo = 1; //will become name_2
  677. } else {
  678. natsort($usedNames);
  679. $lastName = array_pop($usedNames);
  680. $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
  681. }
  682. $altName = $name . '_' . (string)($lastNo + 1);
  683. unset($usedNames);
  684. $attempts = 1;
  685. while ($attempts < 21) {
  686. // Check to be really sure it is unique
  687. // while loop is just a precaution. If a name is not generated within
  688. // 20 attempts, something else is very wrong. Avoids infinite loop.
  689. if (!\OC::$server->getGroupManager()->groupExists($altName)) {
  690. return $altName;
  691. }
  692. $altName = $name . '_' . ($lastNo + $attempts);
  693. $attempts++;
  694. }
  695. return false;
  696. }
  697. /**
  698. * creates a unique name for internal Nextcloud use.
  699. *
  700. * @param string $name the display name of the object
  701. * @param bool $isUser whether name should be created for a user (true) or a group (false)
  702. * @return string|false with with the name to use in Nextcloud or false if unsuccessful
  703. */
  704. private function createAltInternalOwnCloudName(string $name, bool $isUser) {
  705. // ensure there is space for the "_1234" suffix
  706. if (strlen($name) > 59) {
  707. $name = substr($name, 0, 59);
  708. }
  709. $originalTTL = $this->connection->ldapCacheTTL;
  710. $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
  711. if ($isUser) {
  712. $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
  713. } else {
  714. $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
  715. }
  716. $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
  717. return $altName;
  718. }
  719. /**
  720. * fetches a list of users according to a provided loginName and utilizing
  721. * the login filter.
  722. */
  723. public function fetchUsersByLoginName(string $loginName, array $attributes = ['dn']): array {
  724. $loginName = $this->escapeFilterPart($loginName);
  725. $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
  726. return $this->fetchListOfUsers($filter, $attributes);
  727. }
  728. /**
  729. * counts the number of users according to a provided loginName and
  730. * utilizing the login filter.
  731. *
  732. * @param string $loginName
  733. * @return false|int
  734. */
  735. public function countUsersByLoginName($loginName) {
  736. $loginName = $this->escapeFilterPart($loginName);
  737. $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
  738. return $this->countUsers($filter);
  739. }
  740. /**
  741. * @throws \Exception
  742. */
  743. public function fetchListOfUsers(string $filter, array $attr, ?int $limit = null, ?int $offset = null, bool $forceApplyAttributes = false): array {
  744. $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
  745. $recordsToUpdate = $ldapRecords;
  746. if (!$forceApplyAttributes) {
  747. $isBackgroundJobModeAjax = $this->appConfig->getValueString('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
  748. $listOfDNs = array_reduce($ldapRecords, function ($listOfDNs, $entry) {
  749. $listOfDNs[] = $entry['dn'][0];
  750. return $listOfDNs;
  751. }, []);
  752. $idsByDn = $this->getUserMapper()->getListOfIdsByDn($listOfDNs);
  753. $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax, $idsByDn) {
  754. $newlyMapped = false;
  755. $uid = $idsByDn[$record['dn'][0]] ?? null;
  756. if ($uid === null) {
  757. $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
  758. }
  759. if (is_string($uid)) {
  760. $this->cacheUserExists($uid);
  761. }
  762. return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
  763. });
  764. }
  765. $this->batchApplyUserAttributes($recordsToUpdate);
  766. return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
  767. }
  768. /**
  769. * provided with an array of LDAP user records the method will fetch the
  770. * user object and requests it to process the freshly fetched attributes and
  771. * and their values
  772. *
  773. * @throws \Exception
  774. */
  775. public function batchApplyUserAttributes(array $ldapRecords): void {
  776. $displayNameAttribute = strtolower((string)$this->connection->ldapUserDisplayName);
  777. foreach ($ldapRecords as $userRecord) {
  778. if (!isset($userRecord[$displayNameAttribute])) {
  779. // displayName is obligatory
  780. continue;
  781. }
  782. $ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
  783. if ($ocName === false) {
  784. continue;
  785. }
  786. $this->updateUserState($ocName);
  787. $user = $this->userManager->get($ocName);
  788. if ($user !== null) {
  789. $user->processAttributes($userRecord);
  790. } else {
  791. $this->logger->debug(
  792. "The ldap user manager returned null for $ocName",
  793. ['app' => 'user_ldap']
  794. );
  795. }
  796. }
  797. }
  798. /**
  799. * @return array[]
  800. */
  801. public function fetchListOfGroups(string $filter, array $attr, ?int $limit = null, ?int $offset = null): array {
  802. $cacheKey = 'fetchListOfGroups_' . $filter . '_' . implode('-', $attr) . '_' . (string)$limit . '_' . (string)$offset;
  803. $listOfGroups = $this->connection->getFromCache($cacheKey);
  804. if (!is_null($listOfGroups)) {
  805. return $listOfGroups;
  806. }
  807. $groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
  808. $listOfDNs = array_reduce($groupRecords, function ($listOfDNs, $entry) {
  809. $listOfDNs[] = $entry['dn'][0];
  810. return $listOfDNs;
  811. }, []);
  812. $idsByDn = $this->getGroupMapper()->getListOfIdsByDn($listOfDNs);
  813. array_walk($groupRecords, function (array $record) use ($idsByDn) {
  814. $newlyMapped = false;
  815. $gid = $idsByDn[$record['dn'][0]] ?? null;
  816. if ($gid === null) {
  817. $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
  818. }
  819. if (!$newlyMapped && is_string($gid)) {
  820. $this->cacheGroupExists($gid);
  821. }
  822. });
  823. $listOfGroups = $this->fetchList($groupRecords, $this->manyAttributes($attr));
  824. $this->connection->writeToCache($cacheKey, $listOfGroups);
  825. return $listOfGroups;
  826. }
  827. private function fetchList(array $list, bool $manyAttributes): array {
  828. if ($manyAttributes) {
  829. return $list;
  830. } else {
  831. $list = array_reduce($list, function ($carry, $item) {
  832. $attribute = array_keys($item)[0];
  833. $carry[] = $item[$attribute][0];
  834. return $carry;
  835. }, []);
  836. return array_unique($list, SORT_LOCALE_STRING);
  837. }
  838. }
  839. /**
  840. * @throws ServerNotAvailableException
  841. */
  842. public function searchUsers(string $filter, ?array $attr = null, ?int $limit = null, ?int $offset = null): array {
  843. $result = [];
  844. foreach ($this->connection->ldapBaseUsers as $base) {
  845. $result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
  846. }
  847. return $result;
  848. }
  849. /**
  850. * @param string[] $attr
  851. * @return false|int
  852. * @throws ServerNotAvailableException
  853. */
  854. public function countUsers(string $filter, array $attr = ['dn'], ?int $limit = null, ?int $offset = null) {
  855. $result = false;
  856. foreach ($this->connection->ldapBaseUsers as $base) {
  857. $count = $this->count($filter, [$base], $attr, $limit ?? 0, $offset ?? 0);
  858. $result = is_int($count) ? (int)$result + $count : $result;
  859. }
  860. return $result;
  861. }
  862. /**
  863. * executes an LDAP search, optimized for Groups
  864. *
  865. * @param ?string[] $attr optional, when certain attributes shall be filtered out
  866. *
  867. * Executes an LDAP search
  868. * @throws ServerNotAvailableException
  869. */
  870. public function searchGroups(string $filter, ?array $attr = null, ?int $limit = null, ?int $offset = null): array {
  871. $result = [];
  872. foreach ($this->connection->ldapBaseGroups as $base) {
  873. $result = array_merge($result, $this->search($filter, $base, $attr, $limit, $offset));
  874. }
  875. return $result;
  876. }
  877. /**
  878. * returns the number of available groups
  879. *
  880. * @return int|bool
  881. * @throws ServerNotAvailableException
  882. */
  883. public function countGroups(string $filter, array $attr = ['dn'], ?int $limit = null, ?int $offset = null) {
  884. $result = false;
  885. foreach ($this->connection->ldapBaseGroups as $base) {
  886. $count = $this->count($filter, [$base], $attr, $limit ?? 0, $offset ?? 0);
  887. $result = is_int($count) ? (int)$result + $count : $result;
  888. }
  889. return $result;
  890. }
  891. /**
  892. * returns the number of available objects on the base DN
  893. *
  894. * @return int|bool
  895. * @throws ServerNotAvailableException
  896. */
  897. public function countObjects(?int $limit = null, ?int $offset = null) {
  898. $result = false;
  899. foreach ($this->connection->ldapBase as $base) {
  900. $count = $this->count('objectclass=*', [$base], ['dn'], $limit ?? 0, $offset ?? 0);
  901. $result = is_int($count) ? (int)$result + $count : $result;
  902. }
  903. return $result;
  904. }
  905. /**
  906. * Returns the LDAP handler
  907. *
  908. * @throws \OC\ServerNotAvailableException
  909. */
  910. /**
  911. * @param mixed[] $arguments
  912. * @return mixed
  913. * @throws \OC\ServerNotAvailableException
  914. */
  915. private function invokeLDAPMethod(string $command, ...$arguments) {
  916. if ($command == 'controlPagedResultResponse') {
  917. // php no longer supports call-time pass-by-reference
  918. // thus cannot support controlPagedResultResponse as the third argument
  919. // is a reference
  920. throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
  921. }
  922. if (!method_exists($this->ldap, $command)) {
  923. return null;
  924. }
  925. array_unshift($arguments, $this->connection->getConnectionResource());
  926. $doMethod = function () use ($command, &$arguments) {
  927. return call_user_func_array([$this->ldap, $command], $arguments);
  928. };
  929. try {
  930. $ret = $doMethod();
  931. } catch (ServerNotAvailableException $e) {
  932. /* Server connection lost, attempt to reestablish it
  933. * Maybe implement exponential backoff?
  934. * This was enough to get solr indexer working which has large delays between LDAP fetches.
  935. */
  936. $this->logger->debug("Connection lost on $command, attempting to reestablish.", ['app' => 'user_ldap']);
  937. $this->connection->resetConnectionResource();
  938. $cr = $this->connection->getConnectionResource();
  939. if (!$this->ldap->isResource($cr)) {
  940. // Seems like we didn't find any resource.
  941. $this->logger->debug("Could not $command, because resource is missing.", ['app' => 'user_ldap']);
  942. throw $e;
  943. }
  944. $arguments[0] = $cr;
  945. $ret = $doMethod();
  946. }
  947. return $ret;
  948. }
  949. /**
  950. * retrieved. Results will according to the order in the array.
  951. *
  952. * @param string $filter
  953. * @param string $base
  954. * @param string[] $attr
  955. * @param int|null $limit optional, maximum results to be counted
  956. * @param int|null $offset optional, a starting point
  957. * @return array|false array with the search result as first value and pagedSearchOK as
  958. * second | false if not successful
  959. * @throws ServerNotAvailableException
  960. */
  961. private function executeSearch(
  962. string $filter,
  963. string $base,
  964. ?array &$attr,
  965. ?int $pageSize,
  966. ?int $offset
  967. ) {
  968. // See if we have a resource, in case not cancel with message
  969. $cr = $this->connection->getConnectionResource();
  970. //check whether paged search should be attempted
  971. try {
  972. [$pagedSearchOK, $pageSize, $cookie] = $this->initPagedSearch($filter, $base, $attr, (int)$pageSize, (int)$offset);
  973. } catch (NoMoreResults $e) {
  974. // beyond last results page
  975. return false;
  976. }
  977. $sr = $this->invokeLDAPMethod('search', $base, $filter, $attr, 0, 0, $pageSize, $cookie);
  978. $error = $this->ldap->errno($this->connection->getConnectionResource());
  979. if (!$this->ldap->isResource($sr) || $error !== 0) {
  980. $this->logger->error('Attempt for Paging? ' . print_r($pagedSearchOK, true), ['app' => 'user_ldap']);
  981. return false;
  982. }
  983. return [$sr, $pagedSearchOK];
  984. }
  985. /**
  986. * processes an LDAP paged search operation
  987. *
  988. * @param \LDAP\Result|\LDAP\Result[] $sr the array containing the LDAP search resources
  989. * @param int $foundItems number of results in the single search operation
  990. * @param int $limit maximum results to be counted
  991. * @param bool $pagedSearchOK whether a paged search has been executed
  992. * @param bool $skipHandling required for paged search when cookies to
  993. * prior results need to be gained
  994. * @return bool cookie validity, true if we have more pages, false otherwise.
  995. * @throws ServerNotAvailableException
  996. */
  997. private function processPagedSearchStatus(
  998. $sr,
  999. int $foundItems,
  1000. int $limit,
  1001. bool $pagedSearchOK,
  1002. bool $skipHandling
  1003. ): bool {
  1004. $cookie = '';
  1005. if ($pagedSearchOK) {
  1006. $cr = $this->connection->getConnectionResource();
  1007. if ($this->ldap->controlPagedResultResponse($cr, $sr, $cookie)) {
  1008. $this->lastCookie = $cookie;
  1009. }
  1010. //browsing through prior pages to get the cookie for the new one
  1011. if ($skipHandling) {
  1012. return false;
  1013. }
  1014. // if count is bigger, then the server does not support
  1015. // paged search. Instead, he did a normal search. We set a
  1016. // flag here, so the callee knows how to deal with it.
  1017. if ($foundItems <= $limit) {
  1018. $this->pagedSearchedSuccessful = true;
  1019. }
  1020. } else {
  1021. if ((int)$this->connection->ldapPagingSize !== 0) {
  1022. $this->logger->debug(
  1023. 'Paged search was not available',
  1024. ['app' => 'user_ldap']
  1025. );
  1026. }
  1027. }
  1028. /* ++ Fixing RHDS searches with pages with zero results ++
  1029. * Return cookie status. If we don't have more pages, with RHDS
  1030. * cookie is null, with openldap cookie is an empty string and
  1031. * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
  1032. */
  1033. return !empty($cookie) || $cookie === '0';
  1034. }
  1035. /**
  1036. * executes an LDAP search, but counts the results only
  1037. *
  1038. * @param string $filter the LDAP filter for the search
  1039. * @param array $bases an array containing the LDAP subtree(s) that shall be searched
  1040. * @param ?string[] $attr optional, array, one or more attributes that shall be
  1041. * retrieved. Results will according to the order in the array.
  1042. * @param int $limit maximum results to be counted, 0 means no limit
  1043. * @param int $offset a starting point, defaults to 0
  1044. * @param bool $skipHandling indicates whether the pages search operation is
  1045. * completed
  1046. * @return int|false Integer or false if the search could not be initialized
  1047. * @throws ServerNotAvailableException
  1048. */
  1049. private function count(
  1050. string $filter,
  1051. array $bases,
  1052. ?array $attr = null,
  1053. int $limit = 0,
  1054. int $offset = 0,
  1055. bool $skipHandling = false
  1056. ) {
  1057. $this->logger->debug('Count filter: {filter}', [
  1058. 'app' => 'user_ldap',
  1059. 'filter' => $filter
  1060. ]);
  1061. $limitPerPage = (int)$this->connection->ldapPagingSize;
  1062. if ($limit < $limitPerPage && $limit > 0) {
  1063. $limitPerPage = $limit;
  1064. }
  1065. $counter = 0;
  1066. $count = null;
  1067. $this->connection->getConnectionResource();
  1068. foreach ($bases as $base) {
  1069. do {
  1070. $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
  1071. if ($search === false) {
  1072. return $counter > 0 ? $counter : false;
  1073. }
  1074. [$sr, $pagedSearchOK] = $search;
  1075. /* ++ Fixing RHDS searches with pages with zero results ++
  1076. * countEntriesInSearchResults() method signature changed
  1077. * by removing $limit and &$hasHitLimit parameters
  1078. */
  1079. $count = $this->countEntriesInSearchResults($sr);
  1080. $counter += $count;
  1081. $hasMorePages = $this->processPagedSearchStatus($sr, $count, $limitPerPage, $pagedSearchOK, $skipHandling);
  1082. $offset += $limitPerPage;
  1083. /* ++ Fixing RHDS searches with pages with zero results ++
  1084. * Continue now depends on $hasMorePages value
  1085. */
  1086. $continue = $pagedSearchOK && $hasMorePages;
  1087. } while ($continue && ($limit <= 0 || $limit > $counter));
  1088. }
  1089. return $counter;
  1090. }
  1091. /**
  1092. * @param \LDAP\Result|\LDAP\Result[] $sr
  1093. * @return int
  1094. * @throws ServerNotAvailableException
  1095. */
  1096. private function countEntriesInSearchResults($sr): int {
  1097. return (int)$this->invokeLDAPMethod('countEntries', $sr);
  1098. }
  1099. /**
  1100. * Executes an LDAP search
  1101. *
  1102. * DN values in the result set are escaped as per RFC 2253
  1103. *
  1104. * @throws ServerNotAvailableException
  1105. */
  1106. public function search(
  1107. string $filter,
  1108. string $base,
  1109. ?array $attr = null,
  1110. ?int $limit = null,
  1111. ?int $offset = null,
  1112. bool $skipHandling = false
  1113. ): array {
  1114. $limitPerPage = (int)$this->connection->ldapPagingSize;
  1115. if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
  1116. $limitPerPage = $limit;
  1117. }
  1118. /* ++ Fixing RHDS searches with pages with zero results ++
  1119. * As we can have pages with zero results and/or pages with less
  1120. * than $limit results but with a still valid server 'cookie',
  1121. * loops through until we get $continue equals true and
  1122. * $findings['count'] < $limit
  1123. */
  1124. $findings = [];
  1125. $offset = $offset ?? 0;
  1126. $savedoffset = $offset;
  1127. $iFoundItems = 0;
  1128. do {
  1129. $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
  1130. if ($search === false) {
  1131. return [];
  1132. }
  1133. [$sr, $pagedSearchOK] = $search;
  1134. if ($skipHandling) {
  1135. //i.e. result do not need to be fetched, we just need the cookie
  1136. //thus pass 1 or any other value as $iFoundItems because it is not
  1137. //used
  1138. $this->processPagedSearchStatus($sr, 1, $limitPerPage, $pagedSearchOK, $skipHandling);
  1139. return [];
  1140. }
  1141. $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $sr));
  1142. $iFoundItems = max($iFoundItems, $findings['count']);
  1143. unset($findings['count']);
  1144. $continue = $this->processPagedSearchStatus($sr, $iFoundItems, $limitPerPage, $pagedSearchOK, $skipHandling);
  1145. $offset += $limitPerPage;
  1146. } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
  1147. // resetting offset
  1148. $offset = $savedoffset;
  1149. if (!is_null($attr)) {
  1150. $selection = [];
  1151. $i = 0;
  1152. foreach ($findings as $item) {
  1153. if (!is_array($item)) {
  1154. continue;
  1155. }
  1156. $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
  1157. foreach ($attr as $key) {
  1158. if (isset($item[$key])) {
  1159. if (is_array($item[$key]) && isset($item[$key]['count'])) {
  1160. unset($item[$key]['count']);
  1161. }
  1162. if ($key !== 'dn') {
  1163. if ($this->resemblesDN($key)) {
  1164. $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
  1165. } elseif ($key === 'objectguid' || $key === 'guid') {
  1166. $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
  1167. } else {
  1168. $selection[$i][$key] = $item[$key];
  1169. }
  1170. } else {
  1171. $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
  1172. }
  1173. }
  1174. }
  1175. $i++;
  1176. }
  1177. $findings = $selection;
  1178. }
  1179. //we slice the findings, when
  1180. //a) paged search unsuccessful, though attempted
  1181. //b) no paged search, but limit set
  1182. if ((!$this->getPagedSearchResultState()
  1183. && $pagedSearchOK)
  1184. || (
  1185. !$pagedSearchOK
  1186. && !is_null($limit)
  1187. )
  1188. ) {
  1189. $findings = array_slice($findings, $offset, $limit);
  1190. }
  1191. return $findings;
  1192. }
  1193. /**
  1194. * @param string $name
  1195. * @return string
  1196. * @throws \InvalidArgumentException
  1197. */
  1198. public function sanitizeUsername($name) {
  1199. $name = trim($name);
  1200. if ($this->connection->ldapIgnoreNamingRules) {
  1201. return $name;
  1202. }
  1203. // Use htmlentities to get rid of accents
  1204. $name = htmlentities($name, ENT_NOQUOTES, 'UTF-8');
  1205. // Remove accents
  1206. $name = preg_replace('#&([A-Za-z])(?:acute|cedil|caron|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $name);
  1207. // Remove ligatures
  1208. $name = preg_replace('#&([A-Za-z]{2})(?:lig);#', '\1', $name);
  1209. // Remove unknown leftover entities
  1210. $name = preg_replace('#&[^;]+;#', '', $name);
  1211. // Replacements
  1212. $name = str_replace(' ', '_', $name);
  1213. // Every remaining disallowed characters will be removed
  1214. $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
  1215. if (strlen($name) > 64) {
  1216. $name = hash('sha256', $name, false);
  1217. }
  1218. if ($name === '') {
  1219. throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
  1220. }
  1221. return $name;
  1222. }
  1223. public function sanitizeGroupIDCandidate(string $candidate): string {
  1224. $candidate = trim($candidate);
  1225. if (strlen($candidate) > 64) {
  1226. $candidate = hash('sha256', $candidate, false);
  1227. }
  1228. if ($candidate === '') {
  1229. throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
  1230. }
  1231. return $candidate;
  1232. }
  1233. /**
  1234. * escapes (user provided) parts for LDAP filter
  1235. *
  1236. * @param string $input , the provided value
  1237. * @param bool $allowAsterisk whether in * at the beginning should be preserved
  1238. * @return string the escaped string
  1239. */
  1240. public function escapeFilterPart($input, $allowAsterisk = false): string {
  1241. $asterisk = '';
  1242. if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
  1243. $asterisk = '*';
  1244. $input = mb_substr($input, 1, null, 'UTF-8');
  1245. }
  1246. return $asterisk . ldap_escape($input, '', LDAP_ESCAPE_FILTER);
  1247. }
  1248. /**
  1249. * combines the input filters with AND
  1250. *
  1251. * @param string[] $filters the filters to connect
  1252. * @return string the combined filter
  1253. */
  1254. public function combineFilterWithAnd($filters): string {
  1255. return $this->combineFilter($filters, '&');
  1256. }
  1257. /**
  1258. * combines the input filters with OR
  1259. *
  1260. * @param string[] $filters the filters to connect
  1261. * @return string the combined filter
  1262. * Combines Filter arguments with OR
  1263. */
  1264. public function combineFilterWithOr($filters) {
  1265. return $this->combineFilter($filters, '|');
  1266. }
  1267. /**
  1268. * combines the input filters with given operator
  1269. *
  1270. * @param string[] $filters the filters to connect
  1271. * @param string $operator either & or |
  1272. * @return string the combined filter
  1273. */
  1274. private function combineFilter(array $filters, string $operator): string {
  1275. $combinedFilter = '(' . $operator;
  1276. foreach ($filters as $filter) {
  1277. if ($filter !== '' && $filter[0] !== '(') {
  1278. $filter = '(' . $filter . ')';
  1279. }
  1280. $combinedFilter .= $filter;
  1281. }
  1282. $combinedFilter .= ')';
  1283. return $combinedFilter;
  1284. }
  1285. /**
  1286. * creates a filter part for to perform search for users
  1287. *
  1288. * @param string $search the search term
  1289. * @return string the final filter part to use in LDAP searches
  1290. */
  1291. public function getFilterPartForUserSearch($search): string {
  1292. return $this->getFilterPartForSearch($search,
  1293. $this->connection->ldapAttributesForUserSearch,
  1294. $this->connection->ldapUserDisplayName);
  1295. }
  1296. /**
  1297. * creates a filter part for to perform search for groups
  1298. *
  1299. * @param string $search the search term
  1300. * @return string the final filter part to use in LDAP searches
  1301. */
  1302. public function getFilterPartForGroupSearch($search): string {
  1303. return $this->getFilterPartForSearch($search,
  1304. $this->connection->ldapAttributesForGroupSearch,
  1305. $this->connection->ldapGroupDisplayName);
  1306. }
  1307. /**
  1308. * creates a filter part for searches by splitting up the given search
  1309. * string into single words
  1310. *
  1311. * @param string $search the search term
  1312. * @param string[]|null|'' $searchAttributes needs to have at least two attributes,
  1313. * otherwise it does not make sense :)
  1314. * @return string the final filter part to use in LDAP searches
  1315. * @throws DomainException
  1316. */
  1317. private function getAdvancedFilterPartForSearch(string $search, $searchAttributes): string {
  1318. if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
  1319. throw new DomainException('searchAttributes must be an array with at least two string');
  1320. }
  1321. $searchWords = explode(' ', trim($search));
  1322. $wordFilters = [];
  1323. foreach ($searchWords as $word) {
  1324. $word = $this->prepareSearchTerm($word);
  1325. //every word needs to appear at least once
  1326. $wordMatchOneAttrFilters = [];
  1327. foreach ($searchAttributes as $attr) {
  1328. $wordMatchOneAttrFilters[] = $attr . '=' . $word;
  1329. }
  1330. $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
  1331. }
  1332. return $this->combineFilterWithAnd($wordFilters);
  1333. }
  1334. /**
  1335. * creates a filter part for searches
  1336. *
  1337. * @param string $search the search term
  1338. * @param string[]|null|'' $searchAttributes
  1339. * @param string $fallbackAttribute a fallback attribute in case the user
  1340. * did not define search attributes. Typically the display name attribute.
  1341. * @return string the final filter part to use in LDAP searches
  1342. */
  1343. private function getFilterPartForSearch(string $search, $searchAttributes, string $fallbackAttribute): string {
  1344. $filter = [];
  1345. $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
  1346. if ($haveMultiSearchAttributes && str_contains(trim($search), ' ')) {
  1347. try {
  1348. return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
  1349. } catch (DomainException $e) {
  1350. // Creating advanced filter for search failed, falling back to simple method. Edge case, but valid.
  1351. }
  1352. }
  1353. $originalSearch = $search;
  1354. $search = $this->prepareSearchTerm($search);
  1355. if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
  1356. if ($fallbackAttribute === '') {
  1357. return '';
  1358. }
  1359. // wildcards don't work with some attributes
  1360. if ($originalSearch !== '') {
  1361. $filter[] = $fallbackAttribute . '=' . $originalSearch;
  1362. }
  1363. $filter[] = $fallbackAttribute . '=' . $search;
  1364. } else {
  1365. foreach ($searchAttributes as $attribute) {
  1366. // wildcards don't work with some attributes
  1367. if ($originalSearch !== '') {
  1368. $filter[] = $attribute . '=' . $originalSearch;
  1369. }
  1370. $filter[] = $attribute . '=' . $search;
  1371. }
  1372. }
  1373. if (count($filter) === 1) {
  1374. return '(' . $filter[0] . ')';
  1375. }
  1376. return $this->combineFilterWithOr($filter);
  1377. }
  1378. /**
  1379. * returns the search term depending on whether we are allowed
  1380. * list users found by ldap with the current input appended by
  1381. * a *
  1382. */
  1383. private function prepareSearchTerm(string $term): string {
  1384. $config = \OC::$server->getConfig();
  1385. $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
  1386. $result = $term;
  1387. if ($term === '') {
  1388. $result = '*';
  1389. } elseif ($allowEnum !== 'no') {
  1390. $result = $term . '*';
  1391. }
  1392. return $result;
  1393. }
  1394. /**
  1395. * returns the filter used for counting users
  1396. */
  1397. public function getFilterForUserCount(): string {
  1398. $filter = $this->combineFilterWithAnd([
  1399. $this->connection->ldapUserFilter,
  1400. $this->connection->ldapUserDisplayName . '=*'
  1401. ]);
  1402. return $filter;
  1403. }
  1404. public function areCredentialsValid(string $name, string $password): bool {
  1405. if ($name === '' || $password === '') {
  1406. return false;
  1407. }
  1408. $name = $this->helper->DNasBaseParameter($name);
  1409. $testConnection = clone $this->connection;
  1410. $credentials = [
  1411. 'ldapAgentName' => $name,
  1412. 'ldapAgentPassword' => $password,
  1413. ];
  1414. if (!$testConnection->setConfiguration($credentials)) {
  1415. return false;
  1416. }
  1417. return $testConnection->bind();
  1418. }
  1419. /**
  1420. * reverse lookup of a DN given a known UUID
  1421. *
  1422. * @param string $uuid
  1423. * @return string
  1424. * @throws \Exception
  1425. */
  1426. public function getUserDnByUuid($uuid) {
  1427. $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
  1428. $filter = $this->connection->ldapUserFilter;
  1429. $bases = $this->connection->ldapBaseUsers;
  1430. if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
  1431. // Sacrebleu! The UUID attribute is unknown :( We need first an
  1432. // existing DN to be able to reliably detect it.
  1433. foreach ($bases as $base) {
  1434. $result = $this->search($filter, $base, ['dn'], 1);
  1435. if (!isset($result[0]) || !isset($result[0]['dn'])) {
  1436. continue;
  1437. }
  1438. $dn = $result[0]['dn'][0];
  1439. if ($hasFound = $this->detectUuidAttribute($dn, true)) {
  1440. break;
  1441. }
  1442. }
  1443. if (!isset($hasFound) || !$hasFound) {
  1444. throw new \Exception('Cannot determine UUID attribute');
  1445. }
  1446. } else {
  1447. // The UUID attribute is either known or an override is given.
  1448. // By calling this method we ensure that $this->connection->$uuidAttr
  1449. // is definitely set
  1450. if (!$this->detectUuidAttribute('', true)) {
  1451. throw new \Exception('Cannot determine UUID attribute');
  1452. }
  1453. }
  1454. $uuidAttr = $this->connection->ldapUuidUserAttribute;
  1455. if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
  1456. $uuid = $this->formatGuid2ForFilterUser($uuid);
  1457. }
  1458. $filter = $uuidAttr . '=' . $uuid;
  1459. $result = $this->searchUsers($filter, ['dn'], 2);
  1460. if (isset($result[0]['dn']) && count($result) === 1) {
  1461. // we put the count into account to make sure that this is
  1462. // really unique
  1463. return $result[0]['dn'][0];
  1464. }
  1465. throw new \Exception('Cannot determine UUID attribute');
  1466. }
  1467. /**
  1468. * auto-detects the directory's UUID attribute
  1469. *
  1470. * @param string $dn a known DN used to check against
  1471. * @param bool $isUser
  1472. * @param bool $force the detection should be run, even if it is not set to auto
  1473. * @param array|null $ldapRecord
  1474. * @return bool true on success, false otherwise
  1475. * @throws ServerNotAvailableException
  1476. */
  1477. private function detectUuidAttribute(string $dn, bool $isUser = true, bool $force = false, ?array $ldapRecord = null): bool {
  1478. if ($isUser) {
  1479. $uuidAttr = 'ldapUuidUserAttribute';
  1480. $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
  1481. } else {
  1482. $uuidAttr = 'ldapUuidGroupAttribute';
  1483. $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
  1484. }
  1485. if (!$force) {
  1486. if ($this->connection->$uuidAttr !== 'auto') {
  1487. return true;
  1488. } elseif (is_string($uuidOverride) && trim($uuidOverride) !== '') {
  1489. $this->connection->$uuidAttr = $uuidOverride;
  1490. return true;
  1491. }
  1492. $attribute = $this->connection->getFromCache($uuidAttr);
  1493. if ($attribute !== null) {
  1494. $this->connection->$uuidAttr = $attribute;
  1495. return true;
  1496. }
  1497. }
  1498. foreach (self::UUID_ATTRIBUTES as $attribute) {
  1499. if ($ldapRecord !== null) {
  1500. // we have the info from LDAP already, we don't need to talk to the server again
  1501. if (isset($ldapRecord[$attribute])) {
  1502. $this->connection->$uuidAttr = $attribute;
  1503. return true;
  1504. }
  1505. }
  1506. $value = $this->readAttribute($dn, $attribute);
  1507. if (is_array($value) && isset($value[0]) && !empty($value[0])) {
  1508. $this->logger->debug(
  1509. 'Setting {attribute} as {subject}',
  1510. [
  1511. 'app' => 'user_ldap',
  1512. 'attribute' => $attribute,
  1513. 'subject' => $uuidAttr
  1514. ]
  1515. );
  1516. $this->connection->$uuidAttr = $attribute;
  1517. $this->connection->writeToCache($uuidAttr, $attribute);
  1518. return true;
  1519. }
  1520. }
  1521. $this->logger->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
  1522. return false;
  1523. }
  1524. /**
  1525. * @param array|null $ldapRecord
  1526. * @return false|string
  1527. * @throws ServerNotAvailableException
  1528. */
  1529. public function getUUID(string $dn, bool $isUser = true, ?array $ldapRecord = null) {
  1530. if ($isUser) {
  1531. $uuidAttr = 'ldapUuidUserAttribute';
  1532. $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
  1533. } else {
  1534. $uuidAttr = 'ldapUuidGroupAttribute';
  1535. $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
  1536. }
  1537. $uuid = false;
  1538. if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
  1539. $attr = $this->connection->$uuidAttr;
  1540. $uuid = $ldapRecord[$attr] ?? $this->readAttribute($dn, $attr);
  1541. if (!is_array($uuid)
  1542. && $uuidOverride !== ''
  1543. && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord)) {
  1544. $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
  1545. ? $ldapRecord[$this->connection->$uuidAttr]
  1546. : $this->readAttribute($dn, $this->connection->$uuidAttr);
  1547. }
  1548. if (is_array($uuid) && !empty($uuid[0])) {
  1549. $uuid = $uuid[0];
  1550. }
  1551. }
  1552. return $uuid;
  1553. }
  1554. /**
  1555. * converts a binary ObjectGUID into a string representation
  1556. *
  1557. * @param string $oguid the ObjectGUID in its binary form as retrieved from AD
  1558. * @link https://www.php.net/manual/en/function.ldap-get-values-len.php#73198
  1559. */
  1560. private function convertObjectGUID2Str(string $oguid): string {
  1561. $hex_guid = bin2hex($oguid);
  1562. $hex_guid_to_guid_str = '';
  1563. for ($k = 1; $k <= 4; ++$k) {
  1564. $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
  1565. }
  1566. $hex_guid_to_guid_str .= '-';
  1567. for ($k = 1; $k <= 2; ++$k) {
  1568. $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
  1569. }
  1570. $hex_guid_to_guid_str .= '-';
  1571. for ($k = 1; $k <= 2; ++$k) {
  1572. $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
  1573. }
  1574. $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
  1575. $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
  1576. return strtoupper($hex_guid_to_guid_str);
  1577. }
  1578. /**
  1579. * the first three blocks of the string-converted GUID happen to be in
  1580. * reverse order. In order to use it in a filter, this needs to be
  1581. * corrected. Furthermore the dashes need to be replaced and \\ prepended
  1582. * to every two hex figures.
  1583. *
  1584. * If an invalid string is passed, it will be returned without change.
  1585. */
  1586. public function formatGuid2ForFilterUser(string $guid): string {
  1587. $blocks = explode('-', $guid);
  1588. if (count($blocks) !== 5) {
  1589. /*
  1590. * Why not throw an Exception instead? This method is a utility
  1591. * called only when trying to figure out whether a "missing" known
  1592. * LDAP user was or was not renamed on the LDAP server. And this
  1593. * even on the use case that a reverse lookup is needed (UUID known,
  1594. * not DN), i.e. when finding users (search dialog, users page,
  1595. * login, …) this will not be fired. This occurs only if shares from
  1596. * a users are supposed to be mounted who cannot be found. Throwing
  1597. * an exception here would kill the experience for a valid, acting
  1598. * user. Instead we write a log message.
  1599. */
  1600. $this->logger->info(
  1601. 'Passed string does not resemble a valid GUID. Known UUID ' .
  1602. '({uuid}) probably does not match UUID configuration.',
  1603. ['app' => 'user_ldap', 'uuid' => $guid]
  1604. );
  1605. return $guid;
  1606. }
  1607. for ($i = 0; $i < 3; $i++) {
  1608. $pairs = str_split($blocks[$i], 2);
  1609. $pairs = array_reverse($pairs);
  1610. $blocks[$i] = implode('', $pairs);
  1611. }
  1612. for ($i = 0; $i < 5; $i++) {
  1613. $pairs = str_split($blocks[$i], 2);
  1614. $blocks[$i] = '\\' . implode('\\', $pairs);
  1615. }
  1616. return implode('', $blocks);
  1617. }
  1618. /**
  1619. * gets a SID of the domain of the given dn
  1620. *
  1621. * @param string $dn
  1622. * @return string|bool
  1623. * @throws ServerNotAvailableException
  1624. */
  1625. public function getSID($dn) {
  1626. $domainDN = $this->getDomainDNFromDN($dn);
  1627. $cacheKey = 'getSID-' . $domainDN;
  1628. $sid = $this->connection->getFromCache($cacheKey);
  1629. if (!is_null($sid)) {
  1630. return $sid;
  1631. }
  1632. $objectSid = $this->readAttribute($domainDN, 'objectsid');
  1633. if (!is_array($objectSid) || empty($objectSid)) {
  1634. $this->connection->writeToCache($cacheKey, false);
  1635. return false;
  1636. }
  1637. $domainObjectSid = $this->convertSID2Str($objectSid[0]);
  1638. $this->connection->writeToCache($cacheKey, $domainObjectSid);
  1639. return $domainObjectSid;
  1640. }
  1641. /**
  1642. * converts a binary SID into a string representation
  1643. *
  1644. * @param string $sid
  1645. * @return string
  1646. */
  1647. public function convertSID2Str($sid) {
  1648. // The format of a SID binary string is as follows:
  1649. // 1 byte for the revision level
  1650. // 1 byte for the number n of variable sub-ids
  1651. // 6 bytes for identifier authority value
  1652. // n*4 bytes for n sub-ids
  1653. //
  1654. // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
  1655. // Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
  1656. $revision = ord($sid[0]);
  1657. $numberSubID = ord($sid[1]);
  1658. $subIdStart = 8; // 1 + 1 + 6
  1659. $subIdLength = 4;
  1660. if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
  1661. // Incorrect number of bytes present.
  1662. return '';
  1663. }
  1664. // 6 bytes = 48 bits can be represented using floats without loss of
  1665. // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
  1666. $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
  1667. $subIDs = [];
  1668. for ($i = 0; $i < $numberSubID; $i++) {
  1669. $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
  1670. $subIDs[] = sprintf('%u', $subID[1]);
  1671. }
  1672. // Result for example above: S-1-5-21-249921958-728525901-1594176202
  1673. return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
  1674. }
  1675. /**
  1676. * checks if the given DN is part of the given base DN(s)
  1677. *
  1678. * @param string[] $bases array containing the allowed base DN or DNs
  1679. */
  1680. public function isDNPartOfBase(string $dn, array $bases): bool {
  1681. $belongsToBase = false;
  1682. $bases = $this->helper->sanitizeDN($bases);
  1683. foreach ($bases as $base) {
  1684. $belongsToBase = true;
  1685. if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
  1686. $belongsToBase = false;
  1687. }
  1688. if ($belongsToBase) {
  1689. break;
  1690. }
  1691. }
  1692. return $belongsToBase;
  1693. }
  1694. /**
  1695. * resets a running Paged Search operation
  1696. *
  1697. * @throws ServerNotAvailableException
  1698. */
  1699. private function abandonPagedSearch(): void {
  1700. if ($this->lastCookie === '') {
  1701. return;
  1702. }
  1703. $this->getPagedSearchResultState();
  1704. $this->lastCookie = '';
  1705. }
  1706. /**
  1707. * checks whether an LDAP paged search operation has more pages that can be
  1708. * retrieved, typically when offset and limit are provided.
  1709. *
  1710. * Be very careful to use it: the last cookie value, which is inspected, can
  1711. * be reset by other operations. Best, call it immediately after a search(),
  1712. * searchUsers() or searchGroups() call. count-methods are probably safe as
  1713. * well. Don't rely on it with any fetchList-method.
  1714. *
  1715. * @return bool
  1716. */
  1717. public function hasMoreResults() {
  1718. if ($this->lastCookie === '') {
  1719. // as in RFC 2696, when all results are returned, the cookie will
  1720. // be empty.
  1721. return false;
  1722. }
  1723. return true;
  1724. }
  1725. /**
  1726. * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
  1727. *
  1728. * @return boolean|null true on success, null or false otherwise
  1729. */
  1730. public function getPagedSearchResultState() {
  1731. $result = $this->pagedSearchedSuccessful;
  1732. $this->pagedSearchedSuccessful = null;
  1733. return $result;
  1734. }
  1735. /**
  1736. * Prepares a paged search, if possible
  1737. *
  1738. * @param string $filter the LDAP filter for the search
  1739. * @param string $base the LDAP subtree that shall be searched
  1740. * @param string[] $attr optional, when a certain attribute shall be filtered outside
  1741. * @param int $limit
  1742. * @param int $offset
  1743. * @return array{bool, int, string}
  1744. * @throws ServerNotAvailableException
  1745. * @throws NoMoreResults
  1746. */
  1747. private function initPagedSearch(
  1748. string $filter,
  1749. string $base,
  1750. ?array $attr,
  1751. int $pageSize,
  1752. int $offset
  1753. ): array {
  1754. $pagedSearchOK = false;
  1755. if ($pageSize !== 0) {
  1756. $this->logger->debug(
  1757. 'initializing paged search for filter {filter}, base {base}, attr {attr}, pageSize {pageSize}, offset {offset}',
  1758. [
  1759. 'app' => 'user_ldap',
  1760. 'filter' => $filter,
  1761. 'base' => $base,
  1762. 'attr' => $attr,
  1763. 'pageSize' => $pageSize,
  1764. 'offset' => $offset
  1765. ]
  1766. );
  1767. // Get the cookie from the search for the previous search, required by LDAP
  1768. if (($this->lastCookie === '') && ($offset > 0)) {
  1769. // no cookie known from a potential previous search. We need
  1770. // to start from 0 to come to the desired page. cookie value
  1771. // of '0' is valid, because 389ds
  1772. $defaultPageSize = (int)$this->connection->ldapPagingSize;
  1773. if ($offset < $defaultPageSize) {
  1774. /* Make a search with offset as page size and dismiss the result, to init the cookie */
  1775. $this->search($filter, $base, $attr, $offset, 0, true);
  1776. } else {
  1777. /* Make a search for previous page and dismiss the result, to init the cookie */
  1778. $reOffset = $offset - $defaultPageSize;
  1779. $this->search($filter, $base, $attr, $defaultPageSize, $reOffset, true);
  1780. }
  1781. if (!$this->hasMoreResults()) {
  1782. // when the cookie is reset with != 0 offset, there are no further
  1783. // results, so stop.
  1784. throw new NoMoreResults();
  1785. }
  1786. }
  1787. if ($this->lastCookie !== '' && $offset === 0) {
  1788. //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
  1789. $this->abandonPagedSearch();
  1790. }
  1791. $this->logger->debug('Ready for a paged search', ['app' => 'user_ldap']);
  1792. return [true, $pageSize, $this->lastCookie];
  1793. /* ++ Fixing RHDS searches with pages with zero results ++
  1794. * We couldn't get paged searches working with our RHDS for login ($limit = 0),
  1795. * due to pages with zero results.
  1796. * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
  1797. * if we don't have a previous paged search.
  1798. */
  1799. } elseif ($this->lastCookie !== '') {
  1800. // a search without limit was requested. However, if we do use
  1801. // Paged Search once, we always must do it. This requires us to
  1802. // initialize it with the configured page size.
  1803. $this->abandonPagedSearch();
  1804. // in case someone set it to 0 … use 500, otherwise no results will
  1805. // be returned.
  1806. $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
  1807. return [true, $pageSize, $this->lastCookie];
  1808. }
  1809. return [false, $pageSize, ''];
  1810. }
  1811. /**
  1812. * Is more than one $attr used for search?
  1813. *
  1814. * @param string|string[]|null $attr
  1815. * @return bool
  1816. */
  1817. private function manyAttributes($attr): bool {
  1818. if (\is_array($attr)) {
  1819. return \count($attr) > 1;
  1820. }
  1821. return false;
  1822. }
  1823. }