aboutsummaryrefslogtreecommitdiffstats
path: root/apps/user_ldap/lib/Connection.php
diff options
context:
space:
mode:
Diffstat (limited to 'apps/user_ldap/lib/Connection.php')
-rw-r--r--apps/user_ldap/lib/Connection.php344
1 files changed, 198 insertions, 146 deletions
diff --git a/apps/user_ldap/lib/Connection.php b/apps/user_ldap/lib/Connection.php
index 7c780ccbb4a..336179ac341 100644
--- a/apps/user_ldap/lib/Connection.php
+++ b/apps/user_ldap/lib/Connection.php
@@ -1,94 +1,100 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Bart Visscher <bartv@thisnet.nl>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Jarkko Lehtoranta <devel@jlranta.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Jörn Friedrich Dreyer <jfd@butonic.de>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Robin McCorkell <robin@mccorkell.me.uk>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Roger Szabo <roger.szabo@web.de>
- * @author root <root@localhost.localdomain>
- * @author Victor Dubiniuk <dubiniuk@owncloud.com>
- * @author Xuanwo <xuanwo@yunify.com>
- * @author Vincent Van Houtte <vvh@aplusv.be>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\User_LDAP;
use OC\ServerNotAvailableException;
+use OCA\User_LDAP\Exceptions\ConfigurationIssueException;
+use OCP\ICache;
+use OCP\ICacheFactory;
+use OCP\IL10N;
+use OCP\Server;
+use OCP\Util;
use Psr\Log\LoggerInterface;
/**
- * magic properties (incomplete)
+ * magic properties
* responsible for LDAP connections in context with the provided configuration
*
- * @property string ldapHost
- * @property string ldapPort holds the port number
- * @property string ldapUserFilter
- * @property string ldapUserDisplayName
- * @property string ldapUserDisplayName2
- * @property string ldapUserAvatarRule
- * @property boolean turnOnPasswordChange
- * @property string[] ldapBaseUsers
- * @property int|null ldapPagingSize holds an integer
- * @property bool|mixed|void ldapGroupMemberAssocAttr
- * @property string ldapUuidUserAttribute
- * @property string ldapUuidGroupAttribute
- * @property string ldapExpertUUIDUserAttr
- * @property string ldapExpertUUIDGroupAttr
- * @property string ldapQuotaAttribute
- * @property string ldapQuotaDefault
- * @property string ldapEmailAttribute
- * @property string ldapExtStorageHomeAttribute
- * @property string homeFolderNamingRule
- * @property bool|string markRemnantsAsDisabled
- * @property bool|string ldapNestedGroups
- * @property string[] ldapBaseGroups
- * @property string ldapGroupFilter
- * @property string ldapGroupDisplayName
- * @property string ldapLoginFilter
- * @property string ldapDynamicGroupMemberURL
- * @property string ldapGidNumber
- * @property int hasMemberOfFilterSupport
- * @property int useMemberOfToDetectMembership
- * @property string ldapMatchingRuleInChainState
- * @property string ldapAttributePhone
- * @property string ldapAttributeWebsite
- * @property string ldapAttributeAddress
- * @property string ldapAttributeTwitter
- * @property string ldapAttributeFediverse
- * @property string ldapAttributeOrganisation
- * @property string ldapAttributeRole
- * @property string ldapAttributeHeadline
- * @property string ldapAttributeBiography
- * @property string ldapAdminGroup
+ * @property string $ldapHost
+ * @property string $ldapPort
+ * @property string $ldapBackupHost
+ * @property string $ldapBackupPort
+ * @property string $ldapBackgroundHost
+ * @property string $ldapBackgroundPort
+ * @property array|'' $ldapBase
+ * @property array|'' $ldapBaseUsers
+ * @property array|'' $ldapBaseGroups
+ * @property string $ldapAgentName
+ * @property string $ldapAgentPassword
+ * @property string $ldapTLS
+ * @property string $turnOffCertCheck
+ * @property string $ldapIgnoreNamingRules
+ * @property string $ldapUserDisplayName
+ * @property string $ldapUserDisplayName2
+ * @property string $ldapUserAvatarRule
+ * @property string $ldapGidNumber
+ * @property array|'' $ldapUserFilterObjectclass
+ * @property array|'' $ldapUserFilterGroups
+ * @property string $ldapUserFilter
+ * @property string $ldapUserFilterMode
+ * @property string $ldapGroupFilter
+ * @property string $ldapGroupFilterMode
+ * @property array|'' $ldapGroupFilterObjectclass
+ * @property array|'' $ldapGroupFilterGroups
+ * @property string $ldapGroupDisplayName
+ * @property string $ldapGroupMemberAssocAttr
+ * @property string $ldapLoginFilter
+ * @property string $ldapLoginFilterMode
+ * @property string $ldapLoginFilterEmail
+ * @property string $ldapLoginFilterUsername
+ * @property array|'' $ldapLoginFilterAttributes
+ * @property string $ldapQuotaAttribute
+ * @property string $ldapQuotaDefault
+ * @property string $ldapEmailAttribute
+ * @property string $ldapCacheTTL
+ * @property string $ldapUuidUserAttribute
+ * @property string $ldapUuidGroupAttribute
+ * @property string $ldapOverrideMainServer
+ * @property string $ldapConfigurationActive
+ * @property array|'' $ldapAttributesForUserSearch
+ * @property array|'' $ldapAttributesForGroupSearch
+ * @property string $ldapExperiencedAdmin
+ * @property string $homeFolderNamingRule
+ * @property string $hasMemberOfFilterSupport
+ * @property string $useMemberOfToDetectMembership
+ * @property string $ldapExpertUsernameAttr
+ * @property string $ldapExpertUUIDUserAttr
+ * @property string $ldapExpertUUIDGroupAttr
+ * @property string $markRemnantsAsDisabled
+ * @property string $lastJpegPhotoLookup
+ * @property string $ldapNestedGroups
+ * @property string $ldapPagingSize
+ * @property string $turnOnPasswordChange
+ * @property string $ldapDynamicGroupMemberURL
+ * @property string $ldapDefaultPPolicyDN
+ * @property string $ldapExtStorageHomeAttribute
+ * @property string $ldapMatchingRuleInChainState
+ * @property string $ldapConnectionTimeout
+ * @property string $ldapAttributePhone
+ * @property string $ldapAttributeWebsite
+ * @property string $ldapAttributeAddress
+ * @property string $ldapAttributeTwitter
+ * @property string $ldapAttributeFediverse
+ * @property string $ldapAttributeOrganisation
+ * @property string $ldapAttributeRole
+ * @property string $ldapAttributeHeadline
+ * @property string $ldapAttributeBiography
+ * @property string $ldapAdminGroup
+ * @property string $ldapAttributeBirthDate
+ * @property string $ldapAttributePronouns
*/
class Connection extends LDAPUtility {
private ?\LDAP\Connection $ldapConnectionRes = null;
- private string $configPrefix;
- private ?string $configID;
private bool $configured = false;
/**
@@ -107,11 +113,11 @@ class Connection extends LDAPUtility {
public $hasGidNumber = true;
/**
- * @var \OCP\ICache|null
+ * @var ICache|null
*/
protected $cache = null;
- /** @var Configuration settings handler **/
+ /** @var Configuration settings handler * */
protected $configuration;
/**
@@ -129,27 +135,30 @@ class Connection extends LDAPUtility {
*/
protected $bindResult = [];
- /** @var LoggerInterface */
- protected $logger;
+ protected LoggerInterface $logger;
+ private IL10N $l10n;
/**
* Constructor
* @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
* @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
*/
- public function __construct(ILDAPWrapper $ldap, string $configPrefix = '', ?string $configID = 'user_ldap') {
+ public function __construct(
+ ILDAPWrapper $ldap,
+ private string $configPrefix = '',
+ private ?string $configID = 'user_ldap',
+ ) {
parent::__construct($ldap);
- $this->configPrefix = $configPrefix;
- $this->configID = $configID;
- $this->configuration = new Configuration($configPrefix, !is_null($configID));
- $memcache = \OC::$server->getMemCacheFactory();
+ $this->configuration = new Configuration($this->configPrefix, !is_null($this->configID));
+ $memcache = Server::get(ICacheFactory::class);
if ($memcache->isAvailable()) {
$this->cache = $memcache->createDistributed();
}
- $helper = new Helper(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection());
+ $helper = Server::get(Helper::class);
$this->doNotValidate = !in_array($this->configPrefix,
$helper->getServerConfigurationPrefixes());
- $this->logger = \OC::$server->get(LoggerInterface::class);
+ $this->logger = Server::get(LoggerInterface::class);
+ $this->l10n = Util::getL10N('user_ldap');
}
public function __destruct() {
@@ -257,11 +266,11 @@ class Connection extends LDAPUtility {
* @param string|null $key
*/
private function getCacheKey($key): string {
- $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
+ $prefix = 'LDAP-' . $this->configID . '-' . $this->configPrefix . '-';
if (is_null($key)) {
return $prefix;
}
- return $prefix.hash('sha256', $key);
+ return $prefix . hash('sha256', $key);
}
/**
@@ -312,7 +321,7 @@ class Connection extends LDAPUtility {
/**
* Caches the general LDAP configuration.
* @param bool $force optional. true, if the re-read should be forced. defaults
- * to false.
+ * to false.
*/
private function readConfiguration(bool $force = false): void {
if ((!$this->configured || $force) && !is_null($this->configID)) {
@@ -325,16 +334,17 @@ class Connection extends LDAPUtility {
* set LDAP configuration with values delivered by an array, not read from configuration
* @param array $config array that holds the config parameters in an associated array
* @param array &$setParameters optional; array where the set fields will be given to
+ * @param bool $throw if true, throw ConfigurationIssueException with details instead of returning false
* @return bool true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
*/
- public function setConfiguration($config, &$setParameters = null): bool {
+ public function setConfiguration(array $config, ?array &$setParameters = null, bool $throw = false): bool {
if (is_null($setParameters)) {
$setParameters = [];
}
$this->doNotValidate = false;
$this->configuration->setConfiguration($config, $setParameters);
if (count($setParameters) > 0) {
- $this->configured = $this->validateConfiguration();
+ $this->configured = $this->validateConfiguration($throw);
}
@@ -396,8 +406,7 @@ class Connection extends LDAPUtility {
}
foreach (['ldapExpertUUIDUserAttr' => 'ldapUuidUserAttribute',
- 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
- as $expertSetting => $effectiveSetting) {
+ 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute'] as $expertSetting => $effectiveSetting) {
$uuidOverride = $this->configuration->$expertSetting;
if (!empty($uuidOverride)) {
$this->configuration->$effectiveSetting = $uuidOverride;
@@ -409,7 +418,7 @@ class Connection extends LDAPUtility {
$this->configuration->$effectiveSetting = 'auto';
$this->configuration->saveConfiguration();
$this->logger->info(
- 'Illegal value for the '.$effectiveSetting.', reset to autodetect.',
+ 'Illegal value for the ' . $effectiveSetting . ', reset to autodetect.',
['app' => 'user_ldap']
);
}
@@ -418,7 +427,7 @@ class Connection extends LDAPUtility {
$backupPort = (int)$this->configuration->ldapBackupPort;
if ($backupPort <= 0) {
- $this->configuration->backupPort = $this->configuration->ldapPort;
+ $this->configuration->ldapBackupPort = $this->configuration->ldapPort;
}
//make sure empty search attributes are saved as simple, empty array
@@ -433,7 +442,7 @@ class Connection extends LDAPUtility {
if ((stripos((string)$this->configuration->ldapHost, 'ldaps://') === 0)
&& $this->configuration->ldapTLS) {
- $this->configuration->ldapTLS = false;
+ $this->configuration->ldapTLS = (string)false;
$this->logger->info(
'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
['app' => 'user_ldap']
@@ -441,10 +450,10 @@ class Connection extends LDAPUtility {
}
}
- private function doCriticalValidation(): bool {
- $configurationOK = true;
- $errorStr = 'Configuration Error (prefix ' . $this->configPrefix . '): ';
-
+ /**
+ * @throws ConfigurationIssueException
+ */
+ private function doCriticalValidation(): void {
//options that shall not be empty
$options = ['ldapHost', 'ldapUserDisplayName',
'ldapGroupDisplayName', 'ldapLoginFilter'];
@@ -477,10 +486,9 @@ class Connection extends LDAPUtility {
$subj = $key;
break;
}
- $configurationOK = false;
- $this->logger->warning(
- $errorStr.'No '.$subj.' given!',
- ['app' => 'user_ldap']
+ throw new ConfigurationIssueException(
+ 'No ' . $subj . ' given!',
+ $this->l10n->t('Mandatory field "%s" left empty', $subj),
);
}
}
@@ -488,47 +496,76 @@ class Connection extends LDAPUtility {
//combinations
$agent = $this->configuration->ldapAgentName;
$pwd = $this->configuration->ldapAgentPassword;
- if (
- ($agent === '' && $pwd !== '')
- || ($agent !== '' && $pwd === '')
- ) {
- $this->logger->warning(
- $errorStr.'either no password is given for the user ' .
- 'agent or a password is given, but not an LDAP agent.',
- ['app' => 'user_ldap']
+ if ($agent === '' && $pwd !== '') {
+ throw new ConfigurationIssueException(
+ 'A password is given, but not an LDAP agent',
+ $this->l10n->t('A password is given, but not an LDAP agent'),
+ );
+ }
+ if ($agent !== '' && $pwd === '') {
+ throw new ConfigurationIssueException(
+ 'No password is given for the user agent',
+ $this->l10n->t('No password is given for the user agent'),
);
- $configurationOK = false;
}
$base = $this->configuration->ldapBase;
$baseUsers = $this->configuration->ldapBaseUsers;
$baseGroups = $this->configuration->ldapBaseGroups;
- if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
- $this->logger->warning(
- $errorStr.'Not a single Base DN given.',
- ['app' => 'user_ldap']
+ if (empty($base)) {
+ throw new ConfigurationIssueException(
+ 'Not a single Base DN given',
+ $this->l10n->t('No LDAP base DN was given'),
);
- $configurationOK = false;
}
- if (mb_strpos((string)$this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
- === false) {
- $this->logger->warning(
- $errorStr.'login filter does not contain %uid place holder.',
- ['app' => 'user_ldap']
+ if (!empty($baseUsers) && !$this->checkBasesAreValid($baseUsers, $base)) {
+ throw new ConfigurationIssueException(
+ 'User base is not in root base',
+ $this->l10n->t('User base DN is not a subnode of global base DN'),
);
- $configurationOK = false;
}
- return $configurationOK;
+ if (!empty($baseGroups) && !$this->checkBasesAreValid($baseGroups, $base)) {
+ throw new ConfigurationIssueException(
+ 'Group base is not in root base',
+ $this->l10n->t('Group base DN is not a subnode of global base DN'),
+ );
+ }
+
+ if (mb_strpos((string)$this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') === false) {
+ throw new ConfigurationIssueException(
+ 'Login filter does not contain %uid placeholder.',
+ $this->l10n->t('Login filter does not contain %s placeholder.', ['%uid']),
+ );
+ }
+ }
+
+ /**
+ * Checks that all bases are subnodes of one of the root bases
+ */
+ private function checkBasesAreValid(array $bases, array $rootBases): bool {
+ foreach ($bases as $base) {
+ $ok = false;
+ foreach ($rootBases as $rootBase) {
+ if (str_ends_with($base, $rootBase)) {
+ $ok = true;
+ break;
+ }
+ }
+ if (!$ok) {
+ return false;
+ }
+ }
+ return true;
}
/**
* Validates the user specified configuration
* @return bool true if configuration seems OK, false otherwise
*/
- private function validateConfiguration(): bool {
+ private function validateConfiguration(bool $throw = false): bool {
if ($this->doNotValidate) {
//don't do a validation if it is a new configuration with pure
//default values. Will be allowed on changes via __set or
@@ -542,7 +579,19 @@ class Connection extends LDAPUtility {
//second step: critical checks. If left empty or filled wrong, mark as
//not configured and give a warning.
- return $this->doCriticalValidation();
+ try {
+ $this->doCriticalValidation();
+ return true;
+ } catch (ConfigurationIssueException $e) {
+ if ($throw) {
+ throw $e;
+ }
+ $this->logger->warning(
+ 'Configuration Error (prefix ' . $this->configPrefix . '): ' . $e->getMessage(),
+ ['exception' => $e]
+ );
+ return false;
+ }
}
@@ -576,19 +625,6 @@ class Connection extends LDAPUtility {
return false;
}
- if ($this->configuration->turnOffCertCheck) {
- if (putenv('LDAPTLS_REQCERT=never')) {
- $this->logger->debug(
- 'Turned off SSL certificate validation successfully.',
- ['app' => 'user_ldap']
- );
- } else {
- $this->logger->warning(
- 'Could not turn off SSL certificate validation.',
- ['app' => 'user_ldap']
- );
- }
- }
$hasBackupHost = (trim($this->configuration->ldapBackupHost ?? '') !== '');
$hasBackgroundHost = (trim($this->configuration->ldapBackgroundHost ?? '') !== '');
@@ -612,9 +648,11 @@ class Connection extends LDAPUtility {
}
}
$this->logger->warning(
- 'Main LDAP not reachable, connecting to backup',
+ 'Main LDAP not reachable, connecting to backup: {msg}',
[
- 'app' => 'user_ldap'
+ 'app' => 'user_ldap',
+ 'msg' => $e->getMessage(),
+ 'exception' => $e,
]
);
}
@@ -623,8 +661,8 @@ class Connection extends LDAPUtility {
$this->doConnect($this->configuration->ldapBackupHost ?? '', $this->configuration->ldapBackupPort ?? '');
$this->bindResult = [];
$bindStatus = $this->bind();
- $error = $this->ldap->isResource($this->ldapConnectionRes) ?
- $this->ldap->errno($this->ldapConnectionRes) : -1;
+ $error = $this->ldap->isResource($this->ldapConnectionRes)
+ ? $this->ldap->errno($this->ldapConnectionRes) : -1;
if ($bindStatus && $error === 0 && !$forceBackupHost) {
//when bind to backup server succeeded and failed to main server,
//skip contacting it for 15min
@@ -665,6 +703,20 @@ class Connection extends LDAPUtility {
}
if ($this->configuration->ldapTLS) {
+ if ($this->configuration->turnOffCertCheck) {
+ if ($this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER)) {
+ $this->logger->debug(
+ 'Turned off SSL certificate validation successfully.',
+ ['app' => 'user_ldap']
+ );
+ } else {
+ $this->logger->warning(
+ 'Could not turn off SSL certificate validation.',
+ ['app' => 'user_ldap']
+ );
+ }
+ }
+
if (!$this->ldap->startTls($this->ldapConnectionRes)) {
throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
}