1
0

Access.php 64 KB

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