Access.php 68 KB

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