You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Access.php 65KB

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