Wizard.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Alexander Bergolth <leo@strike.wu.ac.at>
  6. * @author Allan Nordhøy <epost@anotheragency.no>
  7. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  8. * @author Bart Visscher <bartv@thisnet.nl>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Jean-Louis Dupond <jean-louis@dupond.be>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Nicolas Grekas <nicolas.grekas@gmail.com>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Stefan Weil <sw@weilnetz.de>
  19. * @author Tobias Perschon <tobias@perschon.at>
  20. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  21. * @author Xuanwo <xuanwo@yunify.com>
  22. * @author Vincent Van Houtte <vvh@aplusv.be>
  23. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OCA\User_LDAP;
  41. use OC\ServerNotAvailableException;
  42. use OCP\IL10N;
  43. use OCP\L10N\IFactory as IL10NFactory;
  44. use Psr\Log\LoggerInterface;
  45. class Wizard extends LDAPUtility {
  46. protected static ?IL10N $l = null;
  47. protected Access $access;
  48. protected ?\LDAP\Connection $cr = null;
  49. protected Configuration $configuration;
  50. protected WizardResult $result;
  51. protected LoggerInterface $logger;
  52. public const LRESULT_PROCESSED_OK = 2;
  53. public const LRESULT_PROCESSED_INVALID = 3;
  54. public const LRESULT_PROCESSED_SKIP = 4;
  55. public const LFILTER_LOGIN = 2;
  56. public const LFILTER_USER_LIST = 3;
  57. public const LFILTER_GROUP_LIST = 4;
  58. public const LFILTER_MODE_ASSISTED = 2;
  59. public const LFILTER_MODE_RAW = 1;
  60. public const LDAP_NW_TIMEOUT = 4;
  61. public function __construct(
  62. Configuration $configuration,
  63. ILDAPWrapper $ldap,
  64. Access $access
  65. ) {
  66. parent::__construct($ldap);
  67. $this->configuration = $configuration;
  68. if (is_null(static::$l)) {
  69. static::$l = \OC::$server->get(IL10NFactory::class)->get('user_ldap');
  70. }
  71. $this->access = $access;
  72. $this->result = new WizardResult();
  73. $this->logger = \OC::$server->get(LoggerInterface::class);
  74. }
  75. public function __destruct() {
  76. if ($this->result->hasChanges()) {
  77. $this->configuration->saveConfiguration();
  78. }
  79. }
  80. /**
  81. * counts entries in the LDAP directory
  82. *
  83. * @param string $filter the LDAP search filter
  84. * @param string $type a string being either 'users' or 'groups';
  85. * @throws \Exception
  86. */
  87. public function countEntries(string $filter, string $type): int {
  88. $reqs = ['ldapHost', 'ldapBase'];
  89. if (!$this->configuration->usesLdapi()) {
  90. $reqs[] = 'ldapPort';
  91. }
  92. if ($type === 'users') {
  93. $reqs[] = 'ldapUserFilter';
  94. }
  95. if (!$this->checkRequirements($reqs)) {
  96. throw new \Exception('Requirements not met', 400);
  97. }
  98. $attr = ['dn']; // default
  99. $limit = 1001;
  100. if ($type === 'groups') {
  101. $result = $this->access->countGroups($filter, $attr, $limit);
  102. } elseif ($type === 'users') {
  103. $result = $this->access->countUsers($filter, $attr, $limit);
  104. } elseif ($type === 'objects') {
  105. $result = $this->access->countObjects($limit);
  106. } else {
  107. throw new \Exception('Internal error: Invalid object type', 500);
  108. }
  109. return (int)$result;
  110. }
  111. /**
  112. * @return WizardResult|false
  113. */
  114. public function countGroups() {
  115. $filter = $this->configuration->ldapGroupFilter;
  116. if (empty($filter)) {
  117. $output = self::$l->n('%n group found', '%n groups found', 0);
  118. $this->result->addChange('ldap_group_count', $output);
  119. return $this->result;
  120. }
  121. try {
  122. $groupsTotal = $this->countEntries($filter, 'groups');
  123. } catch (\Exception $e) {
  124. //400 can be ignored, 500 is forwarded
  125. if ($e->getCode() === 500) {
  126. throw $e;
  127. }
  128. return false;
  129. }
  130. if ($groupsTotal > 1000) {
  131. $output = self::$l->t('> 1000 groups found');
  132. } else {
  133. $output = self::$l->n(
  134. '%n group found',
  135. '%n groups found',
  136. $groupsTotal
  137. );
  138. }
  139. $this->result->addChange('ldap_group_count', $output);
  140. return $this->result;
  141. }
  142. /**
  143. * @throws \Exception
  144. */
  145. public function countUsers(): WizardResult {
  146. $filter = $this->access->getFilterForUserCount();
  147. $usersTotal = $this->countEntries($filter, 'users');
  148. if ($usersTotal > 1000) {
  149. $output = self::$l->t('> 1000 users found');
  150. } else {
  151. $output = self::$l->n(
  152. '%n user found',
  153. '%n users found',
  154. $usersTotal
  155. );
  156. }
  157. $this->result->addChange('ldap_user_count', $output);
  158. return $this->result;
  159. }
  160. /**
  161. * counts any objects in the currently set base dn
  162. *
  163. * @throws \Exception
  164. */
  165. public function countInBaseDN(): WizardResult {
  166. // we don't need to provide a filter in this case
  167. $total = $this->countEntries('', 'objects');
  168. $this->result->addChange('ldap_test_base', $total);
  169. return $this->result;
  170. }
  171. /**
  172. * counts users with a specified attribute
  173. * @return int|false
  174. */
  175. public function countUsersWithAttribute(string $attr, bool $existsCheck = false) {
  176. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  177. if (!$this->configuration->usesLdapi()) {
  178. $reqs[] = 'ldapPort';
  179. }
  180. if (!$this->checkRequirements($reqs)) {
  181. return false;
  182. }
  183. $filter = $this->access->combineFilterWithAnd([
  184. $this->configuration->ldapUserFilter,
  185. $attr . '=*'
  186. ]);
  187. $limit = $existsCheck ? null : 1;
  188. return $this->access->countUsers($filter, ['dn'], $limit);
  189. }
  190. /**
  191. * detects the display name attribute. If a setting is already present that
  192. * returns at least one hit, the detection will be canceled.
  193. * @return WizardResult|false
  194. * @throws \Exception
  195. */
  196. public function detectUserDisplayNameAttribute() {
  197. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  198. if (!$this->configuration->usesLdapi()) {
  199. $reqs[] = 'ldapPort';
  200. }
  201. if (!$this->checkRequirements($reqs)) {
  202. return false;
  203. }
  204. $attr = $this->configuration->ldapUserDisplayName;
  205. if ($attr !== '' && $attr !== 'displayName') {
  206. // most likely not the default value with upper case N,
  207. // verify it still produces a result
  208. $count = (int)$this->countUsersWithAttribute($attr, true);
  209. if ($count > 0) {
  210. //no change, but we sent it back to make sure the user interface
  211. //is still correct, even if the ajax call was cancelled meanwhile
  212. $this->result->addChange('ldap_display_name', $attr);
  213. return $this->result;
  214. }
  215. }
  216. // first attribute that has at least one result wins
  217. $displayNameAttrs = ['displayname', 'cn'];
  218. foreach ($displayNameAttrs as $attr) {
  219. $count = (int)$this->countUsersWithAttribute($attr, true);
  220. if ($count > 0) {
  221. $this->applyFind('ldap_display_name', $attr);
  222. return $this->result;
  223. }
  224. }
  225. throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
  226. }
  227. /**
  228. * detects the most often used email attribute for users applying to the
  229. * user list filter. If a setting is already present that returns at least
  230. * one hit, the detection will be canceled.
  231. * @return WizardResult|bool
  232. */
  233. public function detectEmailAttribute() {
  234. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  235. if (!$this->configuration->usesLdapi()) {
  236. $reqs[] = 'ldapPort';
  237. }
  238. if (!$this->checkRequirements($reqs)) {
  239. return false;
  240. }
  241. $attr = $this->configuration->ldapEmailAttribute;
  242. if ($attr !== '') {
  243. $count = (int)$this->countUsersWithAttribute($attr, true);
  244. if ($count > 0) {
  245. return false;
  246. }
  247. $writeLog = true;
  248. } else {
  249. $writeLog = false;
  250. }
  251. $emailAttributes = ['mail', 'mailPrimaryAddress'];
  252. $winner = '';
  253. $maxUsers = 0;
  254. foreach ($emailAttributes as $attr) {
  255. $count = $this->countUsersWithAttribute($attr);
  256. if ($count > $maxUsers) {
  257. $maxUsers = $count;
  258. $winner = $attr;
  259. }
  260. }
  261. if ($winner !== '') {
  262. $this->applyFind('ldap_email_attr', $winner);
  263. if ($writeLog) {
  264. $this->logger->info(
  265. 'The mail attribute has automatically been reset, '.
  266. 'because the original value did not return any results.',
  267. ['app' => 'user_ldap']
  268. );
  269. }
  270. }
  271. return $this->result;
  272. }
  273. /**
  274. * @return WizardResult|false
  275. * @throws \Exception
  276. */
  277. public function determineAttributes() {
  278. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  279. if (!$this->configuration->usesLdapi()) {
  280. $reqs[] = 'ldapPort';
  281. }
  282. if (!$this->checkRequirements($reqs)) {
  283. return false;
  284. }
  285. $attributes = $this->getUserAttributes();
  286. if (!is_array($attributes)) {
  287. throw new \Exception('Failed to determine user attributes');
  288. }
  289. natcasesort($attributes);
  290. $attributes = array_values($attributes);
  291. $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
  292. $selected = $this->configuration->ldapLoginFilterAttributes;
  293. if (is_array($selected) && !empty($selected)) {
  294. $this->result->addChange('ldap_loginfilter_attributes', $selected);
  295. }
  296. return $this->result;
  297. }
  298. /**
  299. * detects the available LDAP attributes
  300. * @return array|false
  301. * @throws \Exception
  302. */
  303. private function getUserAttributes() {
  304. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  305. if (!$this->configuration->usesLdapi()) {
  306. $reqs[] = 'ldapPort';
  307. }
  308. if (!$this->checkRequirements($reqs)) {
  309. return false;
  310. }
  311. $cr = $this->getConnection();
  312. if (!$cr) {
  313. throw new \Exception('Could not connect to LDAP');
  314. }
  315. $base = $this->configuration->ldapBase[0];
  316. $filter = $this->configuration->ldapUserFilter;
  317. $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
  318. if (!$this->ldap->isResource($rr)) {
  319. return false;
  320. }
  321. /** @var \LDAP\Result $rr */
  322. $er = $this->ldap->firstEntry($cr, $rr);
  323. $attributes = $this->ldap->getAttributes($cr, $er);
  324. if ($attributes === false) {
  325. return false;
  326. }
  327. $pureAttributes = [];
  328. for ($i = 0; $i < $attributes['count']; $i++) {
  329. $pureAttributes[] = $attributes[$i];
  330. }
  331. return $pureAttributes;
  332. }
  333. /**
  334. * detects the available LDAP groups
  335. * @return WizardResult|false the instance's WizardResult instance
  336. */
  337. public function determineGroupsForGroups() {
  338. return $this->determineGroups('ldap_groupfilter_groups',
  339. 'ldapGroupFilterGroups',
  340. false);
  341. }
  342. /**
  343. * detects the available LDAP groups
  344. * @return WizardResult|false the instance's WizardResult instance
  345. */
  346. public function determineGroupsForUsers() {
  347. return $this->determineGroups('ldap_userfilter_groups',
  348. 'ldapUserFilterGroups');
  349. }
  350. /**
  351. * detects the available LDAP groups
  352. * @return WizardResult|false the instance's WizardResult instance
  353. * @throws \Exception
  354. */
  355. private function determineGroups(string $dbKey, string $confKey, bool $testMemberOf = true) {
  356. $reqs = ['ldapHost', 'ldapBase'];
  357. if (!$this->configuration->usesLdapi()) {
  358. $reqs[] = 'ldapPort';
  359. }
  360. if (!$this->checkRequirements($reqs)) {
  361. return false;
  362. }
  363. $cr = $this->getConnection();
  364. if (!$cr) {
  365. throw new \Exception('Could not connect to LDAP');
  366. }
  367. $this->fetchGroups($dbKey, $confKey);
  368. if ($testMemberOf) {
  369. $this->configuration->hasMemberOfFilterSupport = (string)$this->testMemberOf();
  370. $this->result->markChange();
  371. if (!$this->configuration->hasMemberOfFilterSupport) {
  372. throw new \Exception('memberOf is not supported by the server');
  373. }
  374. }
  375. return $this->result;
  376. }
  377. /**
  378. * fetches all groups from LDAP and adds them to the result object
  379. *
  380. * @throws \Exception
  381. */
  382. public function fetchGroups(string $dbKey, string $confKey): array {
  383. $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
  384. $filterParts = [];
  385. foreach ($obclasses as $obclass) {
  386. $filterParts[] = 'objectclass='.$obclass;
  387. }
  388. //we filter for everything
  389. //- that looks like a group and
  390. //- has the group display name set
  391. $filter = $this->access->combineFilterWithOr($filterParts);
  392. $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']);
  393. $groupNames = [];
  394. $groupEntries = [];
  395. $limit = 400;
  396. $offset = 0;
  397. do {
  398. // we need to request dn additionally here, otherwise memberOf
  399. // detection will fail later
  400. $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
  401. foreach ($result as $item) {
  402. if (!isset($item['cn']) || !is_array($item['cn']) || !isset($item['cn'][0])) {
  403. // just in case - no issue known
  404. continue;
  405. }
  406. $groupNames[] = $item['cn'][0];
  407. $groupEntries[] = $item;
  408. }
  409. $offset += $limit;
  410. } while ($this->access->hasMoreResults());
  411. if (count($groupNames) > 0) {
  412. natsort($groupNames);
  413. $this->result->addOptions($dbKey, array_values($groupNames));
  414. } else {
  415. throw new \Exception(self::$l->t('Could not find the desired feature'));
  416. }
  417. $setFeatures = $this->configuration->$confKey;
  418. if (is_array($setFeatures) && !empty($setFeatures)) {
  419. //something is already configured? pre-select it.
  420. $this->result->addChange($dbKey, $setFeatures);
  421. }
  422. return $groupEntries;
  423. }
  424. /**
  425. * @return WizardResult|false
  426. */
  427. public function determineGroupMemberAssoc() {
  428. $reqs = ['ldapHost', 'ldapGroupFilter'];
  429. if (!$this->configuration->usesLdapi()) {
  430. $reqs[] = 'ldapPort';
  431. }
  432. if (!$this->checkRequirements($reqs)) {
  433. return false;
  434. }
  435. $attribute = $this->detectGroupMemberAssoc();
  436. if ($attribute === false) {
  437. return false;
  438. }
  439. $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
  440. $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
  441. return $this->result;
  442. }
  443. /**
  444. * Detects the available object classes
  445. * @return WizardResult|false the instance's WizardResult instance
  446. * @throws \Exception
  447. */
  448. public function determineGroupObjectClasses() {
  449. $reqs = ['ldapHost', 'ldapBase'];
  450. if (!$this->configuration->usesLdapi()) {
  451. $reqs[] = 'ldapPort';
  452. }
  453. if (!$this->checkRequirements($reqs)) {
  454. return false;
  455. }
  456. $cr = $this->getConnection();
  457. if (!$cr) {
  458. throw new \Exception('Could not connect to LDAP');
  459. }
  460. $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*'];
  461. $this->determineFeature($obclasses,
  462. 'objectclass',
  463. 'ldap_groupfilter_objectclass',
  464. 'ldapGroupFilterObjectclass',
  465. false);
  466. return $this->result;
  467. }
  468. /**
  469. * detects the available object classes
  470. * @return WizardResult|false
  471. * @throws \Exception
  472. */
  473. public function determineUserObjectClasses() {
  474. $reqs = ['ldapHost', 'ldapBase'];
  475. if (!$this->configuration->usesLdapi()) {
  476. $reqs[] = 'ldapPort';
  477. }
  478. if (!$this->checkRequirements($reqs)) {
  479. return false;
  480. }
  481. $cr = $this->getConnection();
  482. if (!$cr) {
  483. throw new \Exception('Could not connect to LDAP');
  484. }
  485. $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson',
  486. 'user', 'posixAccount', '*'];
  487. $filter = $this->configuration->ldapUserFilter;
  488. //if filter is empty, it is probably the first time the wizard is called
  489. //then, apply suggestions.
  490. $this->determineFeature($obclasses,
  491. 'objectclass',
  492. 'ldap_userfilter_objectclass',
  493. 'ldapUserFilterObjectclass',
  494. empty($filter));
  495. return $this->result;
  496. }
  497. /**
  498. * @return WizardResult|false
  499. * @throws \Exception
  500. */
  501. public function getGroupFilter() {
  502. $reqs = ['ldapHost', 'ldapBase'];
  503. if (!$this->configuration->usesLdapi()) {
  504. $reqs[] = 'ldapPort';
  505. }
  506. if (!$this->checkRequirements($reqs)) {
  507. return false;
  508. }
  509. //make sure the use display name is set
  510. $displayName = $this->configuration->ldapGroupDisplayName;
  511. if ($displayName === '') {
  512. $d = $this->configuration->getDefaults();
  513. $this->applyFind('ldap_group_display_name',
  514. $d['ldap_group_display_name']);
  515. }
  516. $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
  517. $this->applyFind('ldap_group_filter', $filter);
  518. return $this->result;
  519. }
  520. /**
  521. * @return WizardResult|false
  522. * @throws \Exception
  523. */
  524. public function getUserListFilter() {
  525. $reqs = ['ldapHost', 'ldapBase'];
  526. if (!$this->configuration->usesLdapi()) {
  527. $reqs[] = 'ldapPort';
  528. }
  529. if (!$this->checkRequirements($reqs)) {
  530. return false;
  531. }
  532. //make sure the use display name is set
  533. $displayName = $this->configuration->ldapUserDisplayName;
  534. if ($displayName === '') {
  535. $d = $this->configuration->getDefaults();
  536. $this->applyFind('ldap_display_name', $d['ldap_display_name']);
  537. }
  538. $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
  539. if (!$filter) {
  540. throw new \Exception('Cannot create filter');
  541. }
  542. $this->applyFind('ldap_userlist_filter', $filter);
  543. return $this->result;
  544. }
  545. /**
  546. * @return WizardResult|false
  547. * @throws \Exception
  548. */
  549. public function getUserLoginFilter() {
  550. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  551. if (!$this->configuration->usesLdapi()) {
  552. $reqs[] = 'ldapPort';
  553. }
  554. if (!$this->checkRequirements($reqs)) {
  555. return false;
  556. }
  557. $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
  558. if (!$filter) {
  559. throw new \Exception('Cannot create filter');
  560. }
  561. $this->applyFind('ldap_login_filter', $filter);
  562. return $this->result;
  563. }
  564. /**
  565. * @return WizardResult|false
  566. * @throws \Exception
  567. */
  568. public function testLoginName(string $loginName) {
  569. $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
  570. if (!$this->configuration->usesLdapi()) {
  571. $reqs[] = 'ldapPort';
  572. }
  573. if (!$this->checkRequirements($reqs)) {
  574. return false;
  575. }
  576. $cr = $this->access->connection->getConnectionResource();
  577. if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
  578. === false) {
  579. throw new \Exception('missing placeholder');
  580. }
  581. $users = $this->access->countUsersByLoginName($loginName);
  582. if ($this->ldap->errno($cr) !== 0) {
  583. throw new \Exception($this->ldap->error($cr));
  584. }
  585. $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
  586. $this->result->addChange('ldap_test_loginname', $users);
  587. $this->result->addChange('ldap_test_effective_filter', $filter);
  588. return $this->result;
  589. }
  590. /**
  591. * Tries to determine the port, requires given Host, User DN and Password
  592. * @return WizardResult|false WizardResult on success, false otherwise
  593. * @throws \Exception
  594. */
  595. public function guessPortAndTLS() {
  596. if (!$this->checkRequirements(['ldapHost',
  597. ])) {
  598. return false;
  599. }
  600. $this->checkHost();
  601. $portSettings = $this->getPortSettingsToTry();
  602. //proceed from the best configuration and return on first success
  603. foreach ($portSettings as $setting) {
  604. $p = $setting['port'];
  605. $t = $setting['tls'];
  606. $this->logger->debug(
  607. 'Wiz: trying port '. $p . ', TLS '. $t,
  608. ['app' => 'user_ldap']
  609. );
  610. //connectAndBind may throw Exception, it needs to be caught by the
  611. //callee of this method
  612. try {
  613. $settingsFound = $this->connectAndBind($p, $t);
  614. } catch (\Exception $e) {
  615. // any reply other than -1 (= cannot connect) is already okay,
  616. // because then we found the server
  617. // unavailable startTLS returns -11
  618. if ($e->getCode() > 0) {
  619. $settingsFound = true;
  620. } else {
  621. throw $e;
  622. }
  623. }
  624. if ($settingsFound === true) {
  625. $config = [
  626. 'ldapPort' => (string)$p,
  627. 'ldapTLS' => (string)$t,
  628. ];
  629. $this->configuration->setConfiguration($config);
  630. $this->logger->debug(
  631. 'Wiz: detected Port ' . $p,
  632. ['app' => 'user_ldap']
  633. );
  634. $this->result->addChange('ldap_port', $p);
  635. return $this->result;
  636. }
  637. }
  638. //custom port, undetected (we do not brute force)
  639. return false;
  640. }
  641. /**
  642. * tries to determine a base dn from User DN or LDAP Host
  643. * @return WizardResult|false WizardResult on success, false otherwise
  644. */
  645. public function guessBaseDN() {
  646. $reqs = ['ldapHost'];
  647. if (!$this->configuration->usesLdapi()) {
  648. $reqs[] = 'ldapPort';
  649. }
  650. if (!$this->checkRequirements($reqs)) {
  651. return false;
  652. }
  653. //check whether a DN is given in the agent name (99.9% of all cases)
  654. $base = null;
  655. $i = stripos($this->configuration->ldapAgentName, 'dc=');
  656. if ($i !== false) {
  657. $base = substr($this->configuration->ldapAgentName, $i);
  658. if ($this->testBaseDN($base)) {
  659. $this->applyFind('ldap_base', $base);
  660. return $this->result;
  661. }
  662. }
  663. //this did not help :(
  664. //Let's see whether we can parse the Host URL and convert the domain to
  665. //a base DN
  666. $helper = \OC::$server->get(Helper::class);
  667. $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
  668. if (!$domain) {
  669. return false;
  670. }
  671. $dparts = explode('.', $domain);
  672. while (count($dparts) > 0) {
  673. $base2 = 'dc=' . implode(',dc=', $dparts);
  674. if ($base !== $base2 && $this->testBaseDN($base2)) {
  675. $this->applyFind('ldap_base', $base2);
  676. return $this->result;
  677. }
  678. array_shift($dparts);
  679. }
  680. return false;
  681. }
  682. /**
  683. * sets the found value for the configuration key in the WizardResult
  684. * as well as in the Configuration instance
  685. * @param string $key the configuration key
  686. * @param string $value the (detected) value
  687. *
  688. */
  689. private function applyFind(string $key, string $value): void {
  690. $this->result->addChange($key, $value);
  691. $this->configuration->setConfiguration([$key => $value]);
  692. }
  693. /**
  694. * Checks, whether a port was entered in the Host configuration
  695. * field. In this case the port will be stripped off, but also stored as
  696. * setting.
  697. */
  698. private function checkHost(): void {
  699. $host = $this->configuration->ldapHost;
  700. $hostInfo = parse_url($host);
  701. //removes Port from Host
  702. if (is_array($hostInfo) && isset($hostInfo['port'])) {
  703. $port = $hostInfo['port'];
  704. $host = str_replace(':'.$port, '', $host);
  705. $this->applyFind('ldap_host', $host);
  706. $this->applyFind('ldap_port', (string)$port);
  707. }
  708. }
  709. /**
  710. * tries to detect the group member association attribute which is
  711. * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
  712. * @return string|false string with the attribute name, false on error
  713. * @throws \Exception
  714. */
  715. private function detectGroupMemberAssoc() {
  716. $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber', 'zimbraMailForwardingAddress'];
  717. $filter = $this->configuration->ldapGroupFilter;
  718. if (empty($filter)) {
  719. return false;
  720. }
  721. $cr = $this->getConnection();
  722. if (!$cr) {
  723. throw new \Exception('Could not connect to LDAP');
  724. }
  725. $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
  726. $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
  727. if (!$this->ldap->isResource($rr)) {
  728. return false;
  729. }
  730. /** @var \LDAP\Result $rr */
  731. $er = $this->ldap->firstEntry($cr, $rr);
  732. while ($this->ldap->isResource($er)) {
  733. $this->ldap->getDN($cr, $er);
  734. $attrs = $this->ldap->getAttributes($cr, $er);
  735. $result = [];
  736. $possibleAttrsCount = count($possibleAttrs);
  737. for ($i = 0; $i < $possibleAttrsCount; $i++) {
  738. if (isset($attrs[$possibleAttrs[$i]])) {
  739. $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
  740. }
  741. }
  742. if (!empty($result)) {
  743. natsort($result);
  744. return key($result);
  745. }
  746. $er = $this->ldap->nextEntry($cr, $er);
  747. }
  748. return false;
  749. }
  750. /**
  751. * Checks whether for a given BaseDN results will be returned
  752. * @param string $base the BaseDN to test
  753. * @return bool true on success, false otherwise
  754. * @throws \Exception
  755. */
  756. private function testBaseDN(string $base): bool {
  757. $cr = $this->getConnection();
  758. if (!$cr) {
  759. throw new \Exception('Could not connect to LDAP');
  760. }
  761. //base is there, let's validate it. If we search for anything, we should
  762. //get a result set > 0 on a proper base
  763. $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
  764. if (!$this->ldap->isResource($rr)) {
  765. $errorNo = $this->ldap->errno($cr);
  766. $errorMsg = $this->ldap->error($cr);
  767. $this->logger->info(
  768. 'Wiz: Could not search base '.$base.' Error '.$errorNo.': '.$errorMsg,
  769. ['app' => 'user_ldap']
  770. );
  771. return false;
  772. }
  773. /** @var \LDAP\Result $rr */
  774. $entries = $this->ldap->countEntries($cr, $rr);
  775. return ($entries !== false) && ($entries > 0);
  776. }
  777. /**
  778. * Checks whether the server supports memberOf in LDAP Filter.
  779. * Note: at least in OpenLDAP, availability of memberOf is dependent on
  780. * a configured objectClass. I.e. not necessarily for all available groups
  781. * memberOf does work.
  782. *
  783. * @return bool true if it does, false otherwise
  784. * @throws \Exception
  785. */
  786. private function testMemberOf(): bool {
  787. $cr = $this->getConnection();
  788. if (!$cr) {
  789. throw new \Exception('Could not connect to LDAP');
  790. }
  791. $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
  792. if (is_int($result) && $result > 0) {
  793. return true;
  794. }
  795. return false;
  796. }
  797. /**
  798. * creates an LDAP Filter from given configuration
  799. * @param int $filterType int, for which use case the filter shall be created
  800. * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
  801. * self::LFILTER_GROUP_LIST
  802. * @throws \Exception
  803. */
  804. private function composeLdapFilter(int $filterType): string {
  805. $filter = '';
  806. $parts = 0;
  807. switch ($filterType) {
  808. case self::LFILTER_USER_LIST:
  809. $objcs = $this->configuration->ldapUserFilterObjectclass;
  810. //glue objectclasses
  811. if (is_array($objcs) && count($objcs) > 0) {
  812. $filter .= '(|';
  813. foreach ($objcs as $objc) {
  814. $filter .= '(objectclass=' . ldap_escape($objc, '', LDAP_ESCAPE_FILTER) . ')';
  815. }
  816. $filter .= ')';
  817. $parts++;
  818. }
  819. //glue group memberships
  820. if ($this->configuration->hasMemberOfFilterSupport) {
  821. $cns = $this->configuration->ldapUserFilterGroups;
  822. if (is_array($cns) && count($cns) > 0) {
  823. $filter .= '(|';
  824. $cr = $this->getConnection();
  825. if (!$cr) {
  826. throw new \Exception('Could not connect to LDAP');
  827. }
  828. $base = $this->configuration->ldapBase[0];
  829. foreach ($cns as $cn) {
  830. $rr = $this->ldap->search($cr, $base, 'cn=' . ldap_escape($cn, '', LDAP_ESCAPE_FILTER), ['dn', 'primaryGroupToken']);
  831. if (!$this->ldap->isResource($rr)) {
  832. continue;
  833. }
  834. /** @var \LDAP\Result $rr */
  835. $er = $this->ldap->firstEntry($cr, $rr);
  836. $attrs = $this->ldap->getAttributes($cr, $er);
  837. $dn = $this->ldap->getDN($cr, $er);
  838. if ($dn === false || $dn === '') {
  839. continue;
  840. }
  841. $filterPart = '(memberof=' . ldap_escape($dn, '', LDAP_ESCAPE_FILTER) . ')';
  842. if (isset($attrs['primaryGroupToken'])) {
  843. $pgt = $attrs['primaryGroupToken'][0];
  844. $primaryFilterPart = '(primaryGroupID=' . ldap_escape($pgt, '', LDAP_ESCAPE_FILTER) .')';
  845. $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
  846. }
  847. $filter .= $filterPart;
  848. }
  849. $filter .= ')';
  850. }
  851. $parts++;
  852. }
  853. //wrap parts in AND condition
  854. if ($parts > 1) {
  855. $filter = '(&' . $filter . ')';
  856. }
  857. if ($filter === '') {
  858. $filter = '(objectclass=*)';
  859. }
  860. break;
  861. case self::LFILTER_GROUP_LIST:
  862. $objcs = $this->configuration->ldapGroupFilterObjectclass;
  863. //glue objectclasses
  864. if (is_array($objcs) && count($objcs) > 0) {
  865. $filter .= '(|';
  866. foreach ($objcs as $objc) {
  867. $filter .= '(objectclass=' . ldap_escape($objc, '', LDAP_ESCAPE_FILTER) . ')';
  868. }
  869. $filter .= ')';
  870. $parts++;
  871. }
  872. //glue group memberships
  873. $cns = $this->configuration->ldapGroupFilterGroups;
  874. if (is_array($cns) && count($cns) > 0) {
  875. $filter .= '(|';
  876. foreach ($cns as $cn) {
  877. $filter .= '(cn=' . ldap_escape($cn, '', LDAP_ESCAPE_FILTER) . ')';
  878. }
  879. $filter .= ')';
  880. }
  881. $parts++;
  882. //wrap parts in AND condition
  883. if ($parts > 1) {
  884. $filter = '(&' . $filter . ')';
  885. }
  886. break;
  887. case self::LFILTER_LOGIN:
  888. $ulf = $this->configuration->ldapUserFilter;
  889. $loginpart = '=%uid';
  890. $filterUsername = '';
  891. $userAttributes = $this->getUserAttributes();
  892. if ($userAttributes === false) {
  893. throw new \Exception('Failed to get user attributes');
  894. }
  895. $userAttributes = array_change_key_case(array_flip($userAttributes));
  896. $parts = 0;
  897. if ($this->configuration->ldapLoginFilterUsername === '1') {
  898. $attr = '';
  899. if (isset($userAttributes['uid'])) {
  900. $attr = 'uid';
  901. } elseif (isset($userAttributes['samaccountname'])) {
  902. $attr = 'samaccountname';
  903. } elseif (isset($userAttributes['cn'])) {
  904. //fallback
  905. $attr = 'cn';
  906. }
  907. if ($attr !== '') {
  908. $filterUsername = '(' . $attr . $loginpart . ')';
  909. $parts++;
  910. }
  911. }
  912. $filterEmail = '';
  913. if ($this->configuration->ldapLoginFilterEmail === '1') {
  914. $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
  915. $parts++;
  916. }
  917. $filterAttributes = '';
  918. $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
  919. if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
  920. $filterAttributes = '(|';
  921. foreach ($attrsToFilter as $attribute) {
  922. $filterAttributes .= '(' . $attribute . $loginpart . ')';
  923. }
  924. $filterAttributes .= ')';
  925. $parts++;
  926. }
  927. $filterLogin = '';
  928. if ($parts > 1) {
  929. $filterLogin = '(|';
  930. }
  931. $filterLogin .= $filterUsername;
  932. $filterLogin .= $filterEmail;
  933. $filterLogin .= $filterAttributes;
  934. if ($parts > 1) {
  935. $filterLogin .= ')';
  936. }
  937. $filter = '(&'.$ulf.$filterLogin.')';
  938. break;
  939. }
  940. $this->logger->debug(
  941. 'Wiz: Final filter '.$filter,
  942. ['app' => 'user_ldap']
  943. );
  944. return $filter;
  945. }
  946. /**
  947. * Connects and Binds to an LDAP Server
  948. *
  949. * @param int $port the port to connect with
  950. * @param bool $tls whether startTLS is to be used
  951. * @throws \Exception
  952. */
  953. private function connectAndBind(int $port, bool $tls): bool {
  954. //connect, does not really trigger any server communication
  955. $host = $this->configuration->ldapHost;
  956. $hostInfo = parse_url((string)$host);
  957. if (!is_string($host) || !$hostInfo) {
  958. throw new \Exception(self::$l->t('Invalid Host'));
  959. }
  960. $this->logger->debug(
  961. 'Wiz: Attempting to connect',
  962. ['app' => 'user_ldap']
  963. );
  964. $cr = $this->ldap->connect($host, (string)$port);
  965. if (!$this->ldap->isResource($cr)) {
  966. throw new \Exception(self::$l->t('Invalid Host'));
  967. }
  968. /** @var \LDAP\Connection $cr */
  969. //set LDAP options
  970. $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
  971. $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
  972. $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
  973. try {
  974. if ($tls) {
  975. $isTlsWorking = @$this->ldap->startTls($cr);
  976. if (!$isTlsWorking) {
  977. return false;
  978. }
  979. }
  980. $this->logger->debug(
  981. 'Wiz: Attempting to Bind',
  982. ['app' => 'user_ldap']
  983. );
  984. //interesting part: do the bind!
  985. $login = $this->ldap->bind($cr,
  986. $this->configuration->ldapAgentName,
  987. $this->configuration->ldapAgentPassword
  988. );
  989. $errNo = $this->ldap->errno($cr);
  990. $error = $this->ldap->error($cr);
  991. $this->ldap->unbind($cr);
  992. } catch (ServerNotAvailableException $e) {
  993. return false;
  994. }
  995. if ($login === true) {
  996. $this->logger->debug(
  997. 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls,
  998. ['app' => 'user_ldap']
  999. );
  1000. return true;
  1001. }
  1002. if ($errNo === -1) {
  1003. //host, port or TLS wrong
  1004. return false;
  1005. }
  1006. throw new \Exception($error, $errNo);
  1007. }
  1008. /**
  1009. * checks whether a valid combination of agent and password has been
  1010. * provided (either two values or nothing for anonymous connect)
  1011. * @return bool true if everything is fine, false otherwise
  1012. */
  1013. private function checkAgentRequirements(): bool {
  1014. $agent = $this->configuration->ldapAgentName;
  1015. $pwd = $this->configuration->ldapAgentPassword;
  1016. return
  1017. ($agent !== '' && $pwd !== '')
  1018. || ($agent === '' && $pwd === '')
  1019. ;
  1020. }
  1021. private function checkRequirements(array $reqs): bool {
  1022. $this->checkAgentRequirements();
  1023. foreach ($reqs as $option) {
  1024. $value = $this->configuration->$option;
  1025. if (empty($value)) {
  1026. return false;
  1027. }
  1028. }
  1029. return true;
  1030. }
  1031. /**
  1032. * does a cumulativeSearch on LDAP to get different values of a
  1033. * specified attribute
  1034. * @param string[] $filters array, the filters that shall be used in the search
  1035. * @param string $attr the attribute of which a list of values shall be returned
  1036. * @param int $dnReadLimit the amount of how many DNs should be analyzed.
  1037. * The lower, the faster
  1038. * @param string $maxF string. if not null, this variable will have the filter that
  1039. * yields most result entries
  1040. * @return array|false an array with the values on success, false otherwise
  1041. */
  1042. public function cumulativeSearchOnAttribute(array $filters, string $attr, int $dnReadLimit = 3, ?string &$maxF = null) {
  1043. $dnRead = [];
  1044. $foundItems = [];
  1045. $maxEntries = 0;
  1046. if (!is_array($this->configuration->ldapBase)
  1047. || !isset($this->configuration->ldapBase[0])) {
  1048. return false;
  1049. }
  1050. $base = $this->configuration->ldapBase[0];
  1051. $cr = $this->getConnection();
  1052. if (!$this->ldap->isResource($cr)) {
  1053. return false;
  1054. }
  1055. /** @var \LDAP\Connection $cr */
  1056. $lastFilter = null;
  1057. if (isset($filters[count($filters) - 1])) {
  1058. $lastFilter = $filters[count($filters) - 1];
  1059. }
  1060. foreach ($filters as $filter) {
  1061. if ($lastFilter === $filter && count($foundItems) > 0) {
  1062. //skip when the filter is a wildcard and results were found
  1063. continue;
  1064. }
  1065. // 20k limit for performance and reason
  1066. $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
  1067. if (!$this->ldap->isResource($rr)) {
  1068. continue;
  1069. }
  1070. /** @var \LDAP\Result $rr */
  1071. $entries = $this->ldap->countEntries($cr, $rr);
  1072. $getEntryFunc = 'firstEntry';
  1073. if (($entries !== false) && ($entries > 0)) {
  1074. if (!is_null($maxF) && $entries > $maxEntries) {
  1075. $maxEntries = $entries;
  1076. $maxF = $filter;
  1077. }
  1078. $dnReadCount = 0;
  1079. do {
  1080. $entry = $this->ldap->$getEntryFunc($cr, $rr);
  1081. $getEntryFunc = 'nextEntry';
  1082. if (!$this->ldap->isResource($entry)) {
  1083. continue 2;
  1084. }
  1085. $rr = $entry; //will be expected by nextEntry next round
  1086. $attributes = $this->ldap->getAttributes($cr, $entry);
  1087. $dn = $this->ldap->getDN($cr, $entry);
  1088. if ($attributes === false || $dn === false || in_array($dn, $dnRead)) {
  1089. continue;
  1090. }
  1091. $newItems = [];
  1092. $state = $this->getAttributeValuesFromEntry(
  1093. $attributes,
  1094. $attr,
  1095. $newItems
  1096. );
  1097. $dnReadCount++;
  1098. $foundItems = array_merge($foundItems, $newItems);
  1099. $dnRead[] = $dn;
  1100. } while ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit);
  1101. }
  1102. }
  1103. return array_unique($foundItems);
  1104. }
  1105. /**
  1106. * determines if and which $attr are available on the LDAP server
  1107. * @param string[] $objectclasses the objectclasses to use as search filter
  1108. * @param string $attr the attribute to look for
  1109. * @param string $dbkey the dbkey of the setting the feature is connected to
  1110. * @param string $confkey the confkey counterpart for the $dbkey as used in the
  1111. * Configuration class
  1112. * @param bool $po whether the objectClass with most result entries
  1113. * shall be pre-selected via the result
  1114. * @return array list of found items.
  1115. * @throws \Exception
  1116. */
  1117. private function determineFeature(array $objectclasses, string $attr, string $dbkey, string $confkey, bool $po = false): array {
  1118. $cr = $this->getConnection();
  1119. if (!$cr) {
  1120. throw new \Exception('Could not connect to LDAP');
  1121. }
  1122. $p = 'objectclass=';
  1123. foreach ($objectclasses as $key => $value) {
  1124. $objectclasses[$key] = $p.$value;
  1125. }
  1126. $maxEntryObjC = '';
  1127. //how deep to dig?
  1128. //When looking for objectclasses, testing few entries is sufficient,
  1129. $dig = 3;
  1130. $availableFeatures =
  1131. $this->cumulativeSearchOnAttribute($objectclasses, $attr,
  1132. $dig, $maxEntryObjC);
  1133. if (is_array($availableFeatures)
  1134. && count($availableFeatures) > 0) {
  1135. natcasesort($availableFeatures);
  1136. //natcasesort keeps indices, but we must get rid of them for proper
  1137. //sorting in the web UI. Therefore: array_values
  1138. $this->result->addOptions($dbkey, array_values($availableFeatures));
  1139. } else {
  1140. throw new \Exception(self::$l->t('Could not find the desired feature'));
  1141. }
  1142. $setFeatures = $this->configuration->$confkey;
  1143. if (is_array($setFeatures) && !empty($setFeatures)) {
  1144. //something is already configured? pre-select it.
  1145. $this->result->addChange($dbkey, $setFeatures);
  1146. } elseif ($po && $maxEntryObjC !== '') {
  1147. //pre-select objectclass with most result entries
  1148. $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
  1149. $this->applyFind($dbkey, $maxEntryObjC);
  1150. $this->result->addChange($dbkey, $maxEntryObjC);
  1151. }
  1152. return $availableFeatures;
  1153. }
  1154. /**
  1155. * appends a list of values fr
  1156. * @param array $result the return value from ldap_get_attributes
  1157. * @param string $attribute the attribute values to look for
  1158. * @param array &$known new values will be appended here
  1159. * @return int state on of the class constants LRESULT_PROCESSED_OK,
  1160. * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
  1161. */
  1162. private function getAttributeValuesFromEntry(array $result, string $attribute, array &$known): int {
  1163. if (!isset($result['count'])
  1164. || !$result['count'] > 0) {
  1165. return self::LRESULT_PROCESSED_INVALID;
  1166. }
  1167. // strtolower on all keys for proper comparison
  1168. $result = \OCP\Util::mb_array_change_key_case($result);
  1169. $attribute = strtolower($attribute);
  1170. if (isset($result[$attribute])) {
  1171. foreach ($result[$attribute] as $key => $val) {
  1172. if ($key === 'count') {
  1173. continue;
  1174. }
  1175. if (!in_array($val, $known)) {
  1176. $known[] = $val;
  1177. }
  1178. }
  1179. return self::LRESULT_PROCESSED_OK;
  1180. } else {
  1181. return self::LRESULT_PROCESSED_SKIP;
  1182. }
  1183. }
  1184. /**
  1185. * @return \LDAP\Connection|false a link resource on success, otherwise false
  1186. */
  1187. private function getConnection(): \LDAP\Connection|false {
  1188. if (!is_null($this->cr)) {
  1189. return $this->cr;
  1190. }
  1191. $cr = $this->ldap->connect(
  1192. $this->configuration->ldapHost,
  1193. $this->configuration->ldapPort
  1194. );
  1195. if ($cr === false) {
  1196. return false;
  1197. }
  1198. $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
  1199. $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
  1200. $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
  1201. if ($this->configuration->ldapTLS) {
  1202. $this->ldap->startTls($cr);
  1203. }
  1204. $lo = @$this->ldap->bind($cr,
  1205. $this->configuration->ldapAgentName,
  1206. $this->configuration->ldapAgentPassword);
  1207. if ($lo === true) {
  1208. $this->cr = $cr;
  1209. return $cr;
  1210. }
  1211. return false;
  1212. }
  1213. /**
  1214. * @return array<array{port:int,tls:bool}>
  1215. */
  1216. private function getDefaultLdapPortSettings(): array {
  1217. static $settings = [
  1218. ['port' => 7636, 'tls' => false],
  1219. ['port' => 636, 'tls' => false],
  1220. ['port' => 7389, 'tls' => true],
  1221. ['port' => 389, 'tls' => true],
  1222. ['port' => 7389, 'tls' => false],
  1223. ['port' => 389, 'tls' => false],
  1224. ];
  1225. return $settings;
  1226. }
  1227. /**
  1228. * @return array<array{port:int,tls:bool}>
  1229. */
  1230. private function getPortSettingsToTry(): array {
  1231. //389 ← LDAP / Unencrypted or StartTLS
  1232. //636 ← LDAPS / SSL
  1233. //7xxx ← UCS. need to be checked first, because both ports may be open
  1234. $host = $this->configuration->ldapHost;
  1235. $port = (int)$this->configuration->ldapPort;
  1236. $portSettings = [];
  1237. //In case the port is already provided, we will check this first
  1238. if ($port > 0) {
  1239. $hostInfo = parse_url($host);
  1240. if (!(is_array($hostInfo)
  1241. && isset($hostInfo['scheme'])
  1242. && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
  1243. $portSettings[] = ['port' => $port, 'tls' => true];
  1244. }
  1245. $portSettings[] = ['port' => $port, 'tls' => false];
  1246. } elseif ($this->configuration->usesLdapi()) {
  1247. $portSettings[] = ['port' => 0, 'tls' => false];
  1248. }
  1249. //default ports
  1250. $portSettings = array_merge($portSettings,
  1251. $this->getDefaultLdapPortSettings());
  1252. return $portSettings;
  1253. }
  1254. }