Access.php 65 KB

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