Access.php 67 KB

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