Access.php 62 KB

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