1
0

Wizard.php 38 KB

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