Access.php 57 KB

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