Access.php 65 KB

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