1
0

Access.php 64 KB

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