Access.php 68 KB

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