Access.php 64 KB

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