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

Access.php 66KB

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