1
0

Access.php 65 KB

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