123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353 |
- <?php
- namespace OCA\User_LDAP;
- use OC\ServerNotAvailableException;
- use OCP\IL10N;
- use OCP\L10N\IFactory as IL10NFactory;
- use Psr\Log\LoggerInterface;
- class Wizard extends LDAPUtility {
- protected static ?IL10N $l = null;
- protected Access $access;
- protected ?\LDAP\Connection $cr = null;
- protected Configuration $configuration;
- protected WizardResult $result;
- protected LoggerInterface $logger;
- public const LRESULT_PROCESSED_OK = 2;
- public const LRESULT_PROCESSED_INVALID = 3;
- public const LRESULT_PROCESSED_SKIP = 4;
- public const LFILTER_LOGIN = 2;
- public const LFILTER_USER_LIST = 3;
- public const LFILTER_GROUP_LIST = 4;
- public const LFILTER_MODE_ASSISTED = 2;
- public const LFILTER_MODE_RAW = 1;
- public const LDAP_NW_TIMEOUT = 4;
- public function __construct(
- Configuration $configuration,
- ILDAPWrapper $ldap,
- Access $access
- ) {
- parent::__construct($ldap);
- $this->configuration = $configuration;
- if (is_null(static::$l)) {
- static::$l = \OC::$server->get(IL10NFactory::class)->get('user_ldap');
- }
- $this->access = $access;
- $this->result = new WizardResult();
- $this->logger = \OC::$server->get(LoggerInterface::class);
- }
- public function __destruct() {
- if ($this->result->hasChanges()) {
- $this->configuration->saveConfiguration();
- }
- }
-
- public function countEntries(string $filter, string $type): int {
- $reqs = ['ldapHost', 'ldapBase'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if ($type === 'users') {
- $reqs[] = 'ldapUserFilter';
- }
- if (!$this->checkRequirements($reqs)) {
- throw new \Exception('Requirements not met', 400);
- }
- $attr = ['dn'];
- $limit = 1001;
- if ($type === 'groups') {
- $result = $this->access->countGroups($filter, $attr, $limit);
- } elseif ($type === 'users') {
- $result = $this->access->countUsers($filter, $attr, $limit);
- } elseif ($type === 'objects') {
- $result = $this->access->countObjects($limit);
- } else {
- throw new \Exception('Internal error: Invalid object type', 500);
- }
- return (int)$result;
- }
-
- public function countGroups() {
- $filter = $this->configuration->ldapGroupFilter;
- if (empty($filter)) {
- $output = self::$l->n('%n group found', '%n groups found', 0);
- $this->result->addChange('ldap_group_count', $output);
- return $this->result;
- }
- try {
- $groupsTotal = $this->countEntries($filter, 'groups');
- } catch (\Exception $e) {
-
- if ($e->getCode() === 500) {
- throw $e;
- }
- return false;
- }
- if ($groupsTotal > 1000) {
- $output = self::$l->t('> 1000 groups found');
- } else {
- $output = self::$l->n(
- '%n group found',
- '%n groups found',
- $groupsTotal
- );
- }
- $this->result->addChange('ldap_group_count', $output);
- return $this->result;
- }
-
- public function countUsers(): WizardResult {
- $filter = $this->access->getFilterForUserCount();
- $usersTotal = $this->countEntries($filter, 'users');
- if ($usersTotal > 1000) {
- $output = self::$l->t('> 1000 users found');
- } else {
- $output = self::$l->n(
- '%n user found',
- '%n users found',
- $usersTotal
- );
- }
- $this->result->addChange('ldap_user_count', $output);
- return $this->result;
- }
-
- public function countInBaseDN(): WizardResult {
-
- $total = $this->countEntries('', 'objects');
- $this->result->addChange('ldap_test_base', $total);
- return $this->result;
- }
-
- public function countUsersWithAttribute(string $attr, bool $existsCheck = false) {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $filter = $this->access->combineFilterWithAnd([
- $this->configuration->ldapUserFilter,
- $attr . '=*'
- ]);
- $limit = $existsCheck ? null : 1;
- return $this->access->countUsers($filter, ['dn'], $limit);
- }
-
- public function detectUserDisplayNameAttribute() {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $attr = $this->configuration->ldapUserDisplayName;
- if ($attr !== '' && $attr !== 'displayName') {
-
-
- $count = (int)$this->countUsersWithAttribute($attr, true);
- if ($count > 0) {
-
-
- $this->result->addChange('ldap_display_name', $attr);
- return $this->result;
- }
- }
-
- $displayNameAttrs = ['displayname', 'cn'];
- foreach ($displayNameAttrs as $attr) {
- $count = (int)$this->countUsersWithAttribute($attr, true);
- if ($count > 0) {
- $this->applyFind('ldap_display_name', $attr);
- return $this->result;
- }
- }
- throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
- }
-
- public function detectEmailAttribute() {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $attr = $this->configuration->ldapEmailAttribute;
- if ($attr !== '') {
- $count = (int)$this->countUsersWithAttribute($attr, true);
- if ($count > 0) {
- return false;
- }
- $writeLog = true;
- } else {
- $writeLog = false;
- }
- $emailAttributes = ['mail', 'mailPrimaryAddress'];
- $winner = '';
- $maxUsers = 0;
- foreach ($emailAttributes as $attr) {
- $count = $this->countUsersWithAttribute($attr);
- if ($count > $maxUsers) {
- $maxUsers = $count;
- $winner = $attr;
- }
- }
- if ($winner !== '') {
- $this->applyFind('ldap_email_attr', $winner);
- if ($writeLog) {
- $this->logger->info(
- 'The mail attribute has automatically been reset, '.
- 'because the original value did not return any results.',
- ['app' => 'user_ldap']
- );
- }
- }
- return $this->result;
- }
-
- public function determineAttributes() {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $attributes = $this->getUserAttributes();
- if (!is_array($attributes)) {
- throw new \Exception('Failed to determine user attributes');
- }
- natcasesort($attributes);
- $attributes = array_values($attributes);
- $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
- $selected = $this->configuration->ldapLoginFilterAttributes;
- if (is_array($selected) && !empty($selected)) {
- $this->result->addChange('ldap_loginfilter_attributes', $selected);
- }
- return $this->result;
- }
-
- private function getUserAttributes() {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $base = $this->configuration->ldapBase[0];
- $filter = $this->configuration->ldapUserFilter;
- $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
- if (!$this->ldap->isResource($rr)) {
- return false;
- }
-
- $er = $this->ldap->firstEntry($cr, $rr);
- $attributes = $this->ldap->getAttributes($cr, $er);
- if ($attributes === false) {
- return false;
- }
- $pureAttributes = [];
- for ($i = 0; $i < $attributes['count']; $i++) {
- $pureAttributes[] = $attributes[$i];
- }
- return $pureAttributes;
- }
-
- public function determineGroupsForGroups() {
- return $this->determineGroups('ldap_groupfilter_groups',
- 'ldapGroupFilterGroups',
- false);
- }
-
- public function determineGroupsForUsers() {
- return $this->determineGroups('ldap_userfilter_groups',
- 'ldapUserFilterGroups');
- }
-
- private function determineGroups(string $dbKey, string $confKey, bool $testMemberOf = true) {
- $reqs = ['ldapHost', 'ldapBase'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $this->fetchGroups($dbKey, $confKey);
- if ($testMemberOf) {
- $this->configuration->hasMemberOfFilterSupport = (string)$this->testMemberOf();
- $this->result->markChange();
- if (!$this->configuration->hasMemberOfFilterSupport) {
- throw new \Exception('memberOf is not supported by the server');
- }
- }
- return $this->result;
- }
-
- public function fetchGroups(string $dbKey, string $confKey): array {
- $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
- $filterParts = [];
- foreach ($obclasses as $obclass) {
- $filterParts[] = 'objectclass='.$obclass;
- }
-
-
-
- $filter = $this->access->combineFilterWithOr($filterParts);
- $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']);
- $groupNames = [];
- $groupEntries = [];
- $limit = 400;
- $offset = 0;
- do {
-
-
- $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
- foreach ($result as $item) {
- if (!isset($item['cn']) || !is_array($item['cn']) || !isset($item['cn'][0])) {
-
- continue;
- }
- $groupNames[] = $item['cn'][0];
- $groupEntries[] = $item;
- }
- $offset += $limit;
- } while ($this->access->hasMoreResults());
- if (count($groupNames) > 0) {
- natsort($groupNames);
- $this->result->addOptions($dbKey, array_values($groupNames));
- } else {
- throw new \Exception(self::$l->t('Could not find the desired feature'));
- }
- $setFeatures = $this->configuration->$confKey;
- if (is_array($setFeatures) && !empty($setFeatures)) {
-
- $this->result->addChange($dbKey, $setFeatures);
- }
- return $groupEntries;
- }
-
- public function determineGroupMemberAssoc() {
- $reqs = ['ldapHost', 'ldapGroupFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $attribute = $this->detectGroupMemberAssoc();
- if ($attribute === false) {
- return false;
- }
- $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
- $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
- return $this->result;
- }
-
- public function determineGroupObjectClasses() {
- $reqs = ['ldapHost', 'ldapBase'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*'];
- $this->determineFeature($obclasses,
- 'objectclass',
- 'ldap_groupfilter_objectclass',
- 'ldapGroupFilterObjectclass',
- false);
- return $this->result;
- }
-
- public function determineUserObjectClasses() {
- $reqs = ['ldapHost', 'ldapBase'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson',
- 'user', 'posixAccount', '*'];
- $filter = $this->configuration->ldapUserFilter;
-
-
- $this->determineFeature($obclasses,
- 'objectclass',
- 'ldap_userfilter_objectclass',
- 'ldapUserFilterObjectclass',
- empty($filter));
- return $this->result;
- }
-
- public function getGroupFilter() {
- $reqs = ['ldapHost', 'ldapBase'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
-
- $displayName = $this->configuration->ldapGroupDisplayName;
- if ($displayName === '') {
- $d = $this->configuration->getDefaults();
- $this->applyFind('ldap_group_display_name',
- $d['ldap_group_display_name']);
- }
- $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
- $this->applyFind('ldap_group_filter', $filter);
- return $this->result;
- }
-
- public function getUserListFilter() {
- $reqs = ['ldapHost', 'ldapBase'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
-
- $displayName = $this->configuration->ldapUserDisplayName;
- if ($displayName === '') {
- $d = $this->configuration->getDefaults();
- $this->applyFind('ldap_display_name', $d['ldap_display_name']);
- }
- $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
- if (!$filter) {
- throw new \Exception('Cannot create filter');
- }
- $this->applyFind('ldap_userlist_filter', $filter);
- return $this->result;
- }
-
- public function getUserLoginFilter() {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
- if (!$filter) {
- throw new \Exception('Cannot create filter');
- }
- $this->applyFind('ldap_login_filter', $filter);
- return $this->result;
- }
-
- public function testLoginName(string $loginName) {
- $reqs = ['ldapHost', 'ldapBase', 'ldapUserFilter'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
- $cr = $this->access->connection->getConnectionResource();
- if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
- === false) {
- throw new \Exception('missing placeholder');
- }
- $users = $this->access->countUsersByLoginName($loginName);
- if ($this->ldap->errno($cr) !== 0) {
- throw new \Exception($this->ldap->error($cr));
- }
- $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
- $this->result->addChange('ldap_test_loginname', $users);
- $this->result->addChange('ldap_test_effective_filter', $filter);
- return $this->result;
- }
-
- public function guessPortAndTLS() {
- if (!$this->checkRequirements(['ldapHost',
- ])) {
- return false;
- }
- $this->checkHost();
- $portSettings = $this->getPortSettingsToTry();
-
- foreach ($portSettings as $setting) {
- $p = $setting['port'];
- $t = $setting['tls'];
- $this->logger->debug(
- 'Wiz: trying port '. $p . ', TLS '. $t,
- ['app' => 'user_ldap']
- );
-
-
- try {
- $settingsFound = $this->connectAndBind($p, $t);
- } catch (\Exception $e) {
-
-
-
- if ($e->getCode() > 0) {
- $settingsFound = true;
- } else {
- throw $e;
- }
- }
- if ($settingsFound === true) {
- $config = [
- 'ldapPort' => (string)$p,
- 'ldapTLS' => (string)$t,
- ];
- $this->configuration->setConfiguration($config);
- $this->logger->debug(
- 'Wiz: detected Port ' . $p,
- ['app' => 'user_ldap']
- );
- $this->result->addChange('ldap_port', $p);
- return $this->result;
- }
- }
-
- return false;
- }
-
- public function guessBaseDN() {
- $reqs = ['ldapHost'];
- if (!$this->configuration->usesLdapi()) {
- $reqs[] = 'ldapPort';
- }
- if (!$this->checkRequirements($reqs)) {
- return false;
- }
-
- $base = null;
- $i = stripos($this->configuration->ldapAgentName, 'dc=');
- if ($i !== false) {
- $base = substr($this->configuration->ldapAgentName, $i);
- if ($this->testBaseDN($base)) {
- $this->applyFind('ldap_base', $base);
- return $this->result;
- }
- }
-
-
-
- $helper = \OC::$server->get(Helper::class);
- $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
- if (!$domain) {
- return false;
- }
- $dparts = explode('.', $domain);
- while (count($dparts) > 0) {
- $base2 = 'dc=' . implode(',dc=', $dparts);
- if ($base !== $base2 && $this->testBaseDN($base2)) {
- $this->applyFind('ldap_base', $base2);
- return $this->result;
- }
- array_shift($dparts);
- }
- return false;
- }
-
- private function applyFind(string $key, string $value): void {
- $this->result->addChange($key, $value);
- $this->configuration->setConfiguration([$key => $value]);
- }
-
- private function checkHost(): void {
- $host = $this->configuration->ldapHost;
- $hostInfo = parse_url($host);
-
- if (is_array($hostInfo) && isset($hostInfo['port'])) {
- $port = $hostInfo['port'];
- $host = str_replace(':'.$port, '', $host);
- $this->applyFind('ldap_host', $host);
- $this->applyFind('ldap_port', (string)$port);
- }
- }
-
- private function detectGroupMemberAssoc() {
- $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber', 'zimbraMailForwardingAddress'];
- $filter = $this->configuration->ldapGroupFilter;
- if (empty($filter)) {
- return false;
- }
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
- $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
- if (!$this->ldap->isResource($rr)) {
- return false;
- }
-
- $er = $this->ldap->firstEntry($cr, $rr);
- while ($this->ldap->isResource($er)) {
- $this->ldap->getDN($cr, $er);
- $attrs = $this->ldap->getAttributes($cr, $er);
- $result = [];
- $possibleAttrsCount = count($possibleAttrs);
- for ($i = 0; $i < $possibleAttrsCount; $i++) {
- if (isset($attrs[$possibleAttrs[$i]])) {
- $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
- }
- }
- if (!empty($result)) {
- natsort($result);
- return key($result);
- }
- $er = $this->ldap->nextEntry($cr, $er);
- }
- return false;
- }
-
- private function testBaseDN(string $base): bool {
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
-
-
- $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
- if (!$this->ldap->isResource($rr)) {
- $errorNo = $this->ldap->errno($cr);
- $errorMsg = $this->ldap->error($cr);
- $this->logger->info(
- 'Wiz: Could not search base '.$base.' Error '.$errorNo.': '.$errorMsg,
- ['app' => 'user_ldap']
- );
- return false;
- }
-
- $entries = $this->ldap->countEntries($cr, $rr);
- return ($entries !== false) && ($entries > 0);
- }
-
- private function testMemberOf(): bool {
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
- if (is_int($result) && $result > 0) {
- return true;
- }
- return false;
- }
-
- private function composeLdapFilter(int $filterType): string {
- $filter = '';
- $parts = 0;
- switch ($filterType) {
- case self::LFILTER_USER_LIST:
- $objcs = $this->configuration->ldapUserFilterObjectclass;
-
- if (is_array($objcs) && count($objcs) > 0) {
- $filter .= '(|';
- foreach ($objcs as $objc) {
- $filter .= '(objectclass=' . ldap_escape($objc, '', LDAP_ESCAPE_FILTER) . ')';
- }
- $filter .= ')';
- $parts++;
- }
-
- if ($this->configuration->hasMemberOfFilterSupport) {
- $cns = $this->configuration->ldapUserFilterGroups;
- if (is_array($cns) && count($cns) > 0) {
- $filter .= '(|';
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $base = $this->configuration->ldapBase[0];
- foreach ($cns as $cn) {
- $rr = $this->ldap->search($cr, $base, 'cn=' . ldap_escape($cn, '', LDAP_ESCAPE_FILTER), ['dn', 'primaryGroupToken']);
- if (!$this->ldap->isResource($rr)) {
- continue;
- }
-
- $er = $this->ldap->firstEntry($cr, $rr);
- $attrs = $this->ldap->getAttributes($cr, $er);
- $dn = $this->ldap->getDN($cr, $er);
- if ($dn === false || $dn === '') {
- continue;
- }
- $filterPart = '(memberof=' . ldap_escape($dn, '', LDAP_ESCAPE_FILTER) . ')';
- if (isset($attrs['primaryGroupToken'])) {
- $pgt = $attrs['primaryGroupToken'][0];
- $primaryFilterPart = '(primaryGroupID=' . ldap_escape($pgt, '', LDAP_ESCAPE_FILTER) .')';
- $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
- }
- $filter .= $filterPart;
- }
- $filter .= ')';
- }
- $parts++;
- }
-
- if ($parts > 1) {
- $filter = '(&' . $filter . ')';
- }
- if ($filter === '') {
- $filter = '(objectclass=*)';
- }
- break;
- case self::LFILTER_GROUP_LIST:
- $objcs = $this->configuration->ldapGroupFilterObjectclass;
-
- if (is_array($objcs) && count($objcs) > 0) {
- $filter .= '(|';
- foreach ($objcs as $objc) {
- $filter .= '(objectclass=' . ldap_escape($objc, '', LDAP_ESCAPE_FILTER) . ')';
- }
- $filter .= ')';
- $parts++;
- }
-
- $cns = $this->configuration->ldapGroupFilterGroups;
- if (is_array($cns) && count($cns) > 0) {
- $filter .= '(|';
- foreach ($cns as $cn) {
- $filter .= '(cn=' . ldap_escape($cn, '', LDAP_ESCAPE_FILTER) . ')';
- }
- $filter .= ')';
- }
- $parts++;
-
- if ($parts > 1) {
- $filter = '(&' . $filter . ')';
- }
- break;
- case self::LFILTER_LOGIN:
- $ulf = $this->configuration->ldapUserFilter;
- $loginpart = '=%uid';
- $filterUsername = '';
- $userAttributes = $this->getUserAttributes();
- if ($userAttributes === false) {
- throw new \Exception('Failed to get user attributes');
- }
- $userAttributes = array_change_key_case(array_flip($userAttributes));
- $parts = 0;
- if ($this->configuration->ldapLoginFilterUsername === '1') {
- $attr = '';
- if (isset($userAttributes['uid'])) {
- $attr = 'uid';
- } elseif (isset($userAttributes['samaccountname'])) {
- $attr = 'samaccountname';
- } elseif (isset($userAttributes['cn'])) {
-
- $attr = 'cn';
- }
- if ($attr !== '') {
- $filterUsername = '(' . $attr . $loginpart . ')';
- $parts++;
- }
- }
- $filterEmail = '';
- if ($this->configuration->ldapLoginFilterEmail === '1') {
- $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
- $parts++;
- }
- $filterAttributes = '';
- $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
- if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
- $filterAttributes = '(|';
- foreach ($attrsToFilter as $attribute) {
- $filterAttributes .= '(' . $attribute . $loginpart . ')';
- }
- $filterAttributes .= ')';
- $parts++;
- }
- $filterLogin = '';
- if ($parts > 1) {
- $filterLogin = '(|';
- }
- $filterLogin .= $filterUsername;
- $filterLogin .= $filterEmail;
- $filterLogin .= $filterAttributes;
- if ($parts > 1) {
- $filterLogin .= ')';
- }
- $filter = '(&'.$ulf.$filterLogin.')';
- break;
- }
- $this->logger->debug(
- 'Wiz: Final filter '.$filter,
- ['app' => 'user_ldap']
- );
- return $filter;
- }
-
- private function connectAndBind(int $port, bool $tls): bool {
-
- $host = $this->configuration->ldapHost;
- $hostInfo = parse_url((string)$host);
- if (!is_string($host) || !$hostInfo) {
- throw new \Exception(self::$l->t('Invalid Host'));
- }
- $this->logger->debug(
- 'Wiz: Attempting to connect',
- ['app' => 'user_ldap']
- );
- $cr = $this->ldap->connect($host, (string)$port);
- if (!$this->ldap->isResource($cr)) {
- throw new \Exception(self::$l->t('Invalid Host'));
- }
-
-
- $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
- $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
- $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
- try {
- if ($tls) {
- $isTlsWorking = @$this->ldap->startTls($cr);
- if (!$isTlsWorking) {
- return false;
- }
- }
- $this->logger->debug(
- 'Wiz: Attempting to Bind',
- ['app' => 'user_ldap']
- );
-
- $login = $this->ldap->bind($cr,
- $this->configuration->ldapAgentName,
- $this->configuration->ldapAgentPassword
- );
- $errNo = $this->ldap->errno($cr);
- $error = $this->ldap->error($cr);
- $this->ldap->unbind($cr);
- } catch (ServerNotAvailableException $e) {
- return false;
- }
- if ($login === true) {
- $this->logger->debug(
- 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls,
- ['app' => 'user_ldap']
- );
- return true;
- }
- if ($errNo === -1) {
-
- return false;
- }
- throw new \Exception($error, $errNo);
- }
-
- private function checkAgentRequirements(): bool {
- $agent = $this->configuration->ldapAgentName;
- $pwd = $this->configuration->ldapAgentPassword;
- return
- ($agent !== '' && $pwd !== '')
- || ($agent === '' && $pwd === '')
- ;
- }
- private function checkRequirements(array $reqs): bool {
- $this->checkAgentRequirements();
- foreach ($reqs as $option) {
- $value = $this->configuration->$option;
- if (empty($value)) {
- return false;
- }
- }
- return true;
- }
-
- public function cumulativeSearchOnAttribute(array $filters, string $attr, int $dnReadLimit = 3, ?string &$maxF = null) {
- $dnRead = [];
- $foundItems = [];
- $maxEntries = 0;
- if (!is_array($this->configuration->ldapBase)
- || !isset($this->configuration->ldapBase[0])) {
- return false;
- }
- $base = $this->configuration->ldapBase[0];
- $cr = $this->getConnection();
- if (!$this->ldap->isResource($cr)) {
- return false;
- }
-
- $lastFilter = null;
- if (isset($filters[count($filters) - 1])) {
- $lastFilter = $filters[count($filters) - 1];
- }
- foreach ($filters as $filter) {
- if ($lastFilter === $filter && count($foundItems) > 0) {
-
- continue;
- }
-
- $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
- if (!$this->ldap->isResource($rr)) {
- continue;
- }
-
- $entries = $this->ldap->countEntries($cr, $rr);
- $getEntryFunc = 'firstEntry';
- if (($entries !== false) && ($entries > 0)) {
- if (!is_null($maxF) && $entries > $maxEntries) {
- $maxEntries = $entries;
- $maxF = $filter;
- }
- $dnReadCount = 0;
- do {
- $entry = $this->ldap->$getEntryFunc($cr, $rr);
- $getEntryFunc = 'nextEntry';
- if (!$this->ldap->isResource($entry)) {
- continue 2;
- }
- $rr = $entry;
- $attributes = $this->ldap->getAttributes($cr, $entry);
- $dn = $this->ldap->getDN($cr, $entry);
- if ($attributes === false || $dn === false || in_array($dn, $dnRead)) {
- continue;
- }
- $newItems = [];
- $state = $this->getAttributeValuesFromEntry(
- $attributes,
- $attr,
- $newItems
- );
- $dnReadCount++;
- $foundItems = array_merge($foundItems, $newItems);
- $dnRead[] = $dn;
- } while ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit);
- }
- }
- return array_unique($foundItems);
- }
-
- private function determineFeature(array $objectclasses, string $attr, string $dbkey, string $confkey, bool $po = false): array {
- $cr = $this->getConnection();
- if (!$cr) {
- throw new \Exception('Could not connect to LDAP');
- }
- $p = 'objectclass=';
- foreach ($objectclasses as $key => $value) {
- $objectclasses[$key] = $p.$value;
- }
- $maxEntryObjC = '';
-
-
- $dig = 3;
- $availableFeatures =
- $this->cumulativeSearchOnAttribute($objectclasses, $attr,
- $dig, $maxEntryObjC);
- if (is_array($availableFeatures)
- && count($availableFeatures) > 0) {
- natcasesort($availableFeatures);
-
-
- $this->result->addOptions($dbkey, array_values($availableFeatures));
- } else {
- throw new \Exception(self::$l->t('Could not find the desired feature'));
- }
- $setFeatures = $this->configuration->$confkey;
- if (is_array($setFeatures) && !empty($setFeatures)) {
-
- $this->result->addChange($dbkey, $setFeatures);
- } elseif ($po && $maxEntryObjC !== '') {
-
- $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
- $this->applyFind($dbkey, $maxEntryObjC);
- $this->result->addChange($dbkey, $maxEntryObjC);
- }
- return $availableFeatures;
- }
-
- private function getAttributeValuesFromEntry(array $result, string $attribute, array &$known): int {
- if (!isset($result['count'])
- || !$result['count'] > 0) {
- return self::LRESULT_PROCESSED_INVALID;
- }
-
- $result = \OCP\Util::mb_array_change_key_case($result);
- $attribute = strtolower($attribute);
- if (isset($result[$attribute])) {
- foreach ($result[$attribute] as $key => $val) {
- if ($key === 'count') {
- continue;
- }
- if (!in_array($val, $known)) {
- $known[] = $val;
- }
- }
- return self::LRESULT_PROCESSED_OK;
- } else {
- return self::LRESULT_PROCESSED_SKIP;
- }
- }
-
- private function getConnection(): \LDAP\Connection|false {
- if (!is_null($this->cr)) {
- return $this->cr;
- }
- $cr = $this->ldap->connect(
- $this->configuration->ldapHost,
- $this->configuration->ldapPort
- );
- if ($cr === false) {
- return false;
- }
- $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
- $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
- $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
- if ($this->configuration->ldapTLS) {
- $this->ldap->startTls($cr);
- }
- $lo = @$this->ldap->bind($cr,
- $this->configuration->ldapAgentName,
- $this->configuration->ldapAgentPassword);
- if ($lo === true) {
- $this->cr = $cr;
- return $cr;
- }
- return false;
- }
-
- private function getDefaultLdapPortSettings(): array {
- static $settings = [
- ['port' => 7636, 'tls' => false],
- ['port' => 636, 'tls' => false],
- ['port' => 7389, 'tls' => true],
- ['port' => 389, 'tls' => true],
- ['port' => 7389, 'tls' => false],
- ['port' => 389, 'tls' => false],
- ];
- return $settings;
- }
-
- private function getPortSettingsToTry(): array {
-
-
-
- $host = $this->configuration->ldapHost;
- $port = (int)$this->configuration->ldapPort;
- $portSettings = [];
-
- if ($port > 0) {
- $hostInfo = parse_url($host);
- if (!(is_array($hostInfo)
- && isset($hostInfo['scheme'])
- && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
- $portSettings[] = ['port' => $port, 'tls' => true];
- }
- $portSettings[] = ['port' => $port, 'tls' => false];
- } elseif ($this->configuration->usesLdapi()) {
- $portSettings[] = ['port' => 0, 'tls' => false];
- }
-
- $portSettings = array_merge($portSettings,
- $this->getDefaultLdapPortSettings());
- return $portSettings;
- }
- }
|