Access.php 64 KB

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