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

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