1
0

Access.php 62 KB

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