diff options
Diffstat (limited to 'apps/user_ldap/lib/LDAP.php')
-rw-r--r-- | apps/user_ldap/lib/LDAP.php | 247 |
1 files changed, 126 insertions, 121 deletions
diff --git a/apps/user_ldap/lib/LDAP.php b/apps/user_ldap/lib/LDAP.php index 3c579596941..1cf20c4b939 100644 --- a/apps/user_ldap/lib/LDAP.php +++ b/apps/user_ldap/lib/LDAP.php @@ -1,65 +1,40 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Alexander Bergolth <leo@strike.wu.ac.at> - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author J0WI <J0WI@users.noreply.github.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Jörn Friedrich Dreyer <jfd@butonic.de> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Peter Kubica <peter@kubica.ch> - * @author Robin McCorkell <robin@mccorkell.me.uk> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Roger Szabo <roger.szabo@web.de> - * @author Carl Schwan <carl@carlschwan.eu> - * - * @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 OCP\Profiler\IProfiler; use OC\ServerNotAvailableException; use OCA\User_LDAP\DataCollector\LdapDataCollector; use OCA\User_LDAP\Exceptions\ConstraintViolationException; -use OCA\User_LDAP\PagedResults\IAdapter; -use OCA\User_LDAP\PagedResults\Php73; +use OCP\IConfig; +use OCP\ILogger; +use OCP\Profiler\IProfiler; +use OCP\Server; +use Psr\Log\LoggerInterface; class LDAP implements ILDAPWrapper { - protected $logFile = ''; - protected $curFunc = ''; - protected $curArgs = []; - - /** @var IAdapter */ - protected $pagedResultsAdapter; + protected array $curArgs = []; + protected LoggerInterface $logger; + protected IConfig $config; private ?LdapDataCollector $dataCollector = null; - public function __construct(string $logFile = '') { - $this->pagedResultsAdapter = new Php73(); - $this->logFile = $logFile; - + public function __construct( + protected string $logFile = '', + ) { /** @var IProfiler $profiler */ - $profiler = \OC::$server->get(IProfiler::class); + $profiler = Server::get(IProfiler::class); if ($profiler->isEnabled()) { $this->dataCollector = new LdapDataCollector(); $profiler->add($this->dataCollector); } + + $this->logger = Server::get(LoggerInterface::class); + $this->config = Server::get(IConfig::class); } /** @@ -73,10 +48,12 @@ class LDAP implements ILDAPWrapper { * {@inheritDoc} */ public function connect($host, $port) { - if (strpos($host, '://') === false) { + $pos = strpos($host, '://'); + if ($pos === false) { $host = 'ldap://' . $host; + $pos = 4; } - if (strpos($host, ':', strpos($host, '://') + 1) === false) { + if (strpos($host, ':', $pos + 1) === false && !empty($port)) { //ldap_connect ignores port parameter when URLs are passed $host .= ':' . $port; } @@ -87,39 +64,30 @@ class LDAP implements ILDAPWrapper { * {@inheritDoc} */ public function controlPagedResultResponse($link, $result, &$cookie): bool { - $this->preFunctionCall( - $this->pagedResultsAdapter->getResponseCallFunc(), - $this->pagedResultsAdapter->getResponseCallArgs([$link, $result, &$cookie]) - ); - - $result = $this->pagedResultsAdapter->responseCall($link); - $cookie = $this->pagedResultsAdapter->getCookie($link); - - if ($this->isResultFalse($result)) { - $this->postFunctionCall(); + $errorCode = 0; + $errorMsg = ''; + $controls = []; + $matchedDn = null; + $referrals = []; + + /** Cannot use invokeLDAPMethod because arguments are passed by reference */ + $this->preFunctionCall('ldap_parse_result', [$link, $result]); + $success = ldap_parse_result($link, $result, + $errorCode, + $matchedDn, + $errorMsg, + $referrals, + $controls); + if ($errorCode !== 0) { + $this->processLDAPError($link, 'ldap_parse_result', $errorCode, $errorMsg); } - - return $result; - } - - /** - * {@inheritDoc} - */ - public function controlPagedResult($link, $pageSize, $isCritical) { - $fn = $this->pagedResultsAdapter->getRequestCallFunc(); - $this->pagedResultsAdapter->setRequestParameters($link, $pageSize, $isCritical); - if ($fn === null) { - return true; + if ($this->dataCollector !== null) { + $this->dataCollector->stopLastLdapRequest(); } - $this->preFunctionCall($fn, $this->pagedResultsAdapter->getRequestCallArgs($link)); - $result = $this->pagedResultsAdapter->requestCall($link); + $cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? ''; - if ($this->isResultFalse($result)) { - $this->postFunctionCall(); - } - - return $result; + return $success; } /** @@ -146,7 +114,7 @@ class LDAP implements ILDAPWrapper { /** * Splits DN into its component parts * @param string $dn - * @param int @withAttrib + * @param int $withAttrib * @return array|false * @link https://www.php.net/manual/en/function.ldap-explode-dn.php */ @@ -193,24 +161,36 @@ class LDAP implements ILDAPWrapper { * {@inheritDoc} */ public function read($link, $baseDN, $filter, $attr) { - $this->pagedResultsAdapter->setReadArgs($link, $baseDN, $filter, $attr); - return $this->invokeLDAPMethod('read', ...$this->pagedResultsAdapter->getReadArgs($link)); + return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr, 0, -1); } /** * {@inheritDoc} */ - public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) { + public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0, int $pageSize = 0, string $cookie = '') { + if ($pageSize > 0 || $cookie !== '') { + $serverControls = [[ + 'oid' => LDAP_CONTROL_PAGEDRESULTS, + 'value' => [ + 'size' => $pageSize, + 'cookie' => $cookie, + ], + 'iscritical' => false, + ]]; + } else { + $serverControls = []; + } + + /** @psalm-suppress UndefinedVariable $oldHandler is defined when the closure is called but psalm fails to get that */ $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) { - if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) { + if (str_contains($message, 'Partial search results returned: Sizelimit exceeded')) { return true; } $oldHandler($no, $message, $file, $line); return true; }); try { - $this->pagedResultsAdapter->setSearchArgs($link, $baseDN, $filter, $attr, $attrsOnly, $limit); - $result = $this->invokeLDAPMethod('search', ...$this->pagedResultsAdapter->getSearchArgs($link)); + $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit, -1, LDAP_DEREF_NEVER, $serverControls); restore_error_handler(); return $result; @@ -230,7 +210,7 @@ class LDAP implements ILDAPWrapper { /** * {@inheritDoc} */ - public function exopPasswd($link, $userDN, $oldPassword, $password) { + public function exopPasswd($link, string $userDN, string $oldPassword, string $password) { return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password); } @@ -276,15 +256,14 @@ class LDAP implements ILDAPWrapper { * When using ldap_search we provide an array, in case multiple bases are * configured. Thus, we need to check the array elements. * - * @param $result - * @return bool + * @param mixed $result */ - protected function isResultFalse($result) { + protected function isResultFalse(string $functionName, $result): bool { if ($result === false) { return true; } - if ($this->curFunc === 'ldap_search' && is_array($result)) { + if ($functionName === 'ldap_search' && is_array($result)) { foreach ($result as $singleResult) { if ($singleResult === false) { return true; @@ -296,16 +275,16 @@ class LDAP implements ILDAPWrapper { } /** + * @param array $arguments * @return mixed */ - protected function invokeLDAPMethod() { - $arguments = func_get_args(); - $func = 'ldap_' . array_shift($arguments); + protected function invokeLDAPMethod(string $func, ...$arguments) { + $func = 'ldap_' . $func; if (function_exists($func)) { $this->preFunctionCall($func, $arguments); $result = call_user_func_array($func, $arguments); - if ($this->isResultFalse($result)) { - $this->postFunctionCall(); + if ($this->isResultFalse($func, $result)) { + $this->postFunctionCall($func); } if ($this->dataCollector !== null) { $this->dataCollector->stopLastLdapRequest(); @@ -315,21 +294,49 @@ class LDAP implements ILDAPWrapper { return null; } + /** + * Turn resources into string, and removes potentially problematic cookie string to avoid breaking logfiles + */ + private function sanitizeFunctionParameters(array $args): array { + return array_map(function ($item) { + if ($this->isResource($item)) { + return '(resource)'; + } + if (isset($item[0]['value']['cookie']) && $item[0]['value']['cookie'] !== '') { + $item[0]['value']['cookie'] = '*opaque cookie*'; + } + return $item; + }, $args); + } + private function preFunctionCall(string $functionName, array $args): void { - $this->curFunc = $functionName; $this->curArgs = $args; + if (strcasecmp($functionName, 'ldap_bind') === 0 || strcasecmp($functionName, 'ldap_exop_passwd') === 0) { + // The arguments are not key value pairs + // \OCA\User_LDAP\LDAP::bind passes 3 arguments, the 3rd being the pw + // Remove it via direct array access for now, although a better solution could be found mebbe? + // @link https://github.com/nextcloud/server/issues/38461 + $args[2] = IConfig::SENSITIVE_VALUE; + } - if ($this->dataCollector !== null) { - $args = array_map(fn ($item) => (!$this->isResource($item) ? $item : '(resource)'), $this->curArgs); + if ($this->config->getSystemValue('loglevel') === ILogger::DEBUG) { + /* Only running this if debug loglevel is on, to avoid processing parameters on production */ + $this->logger->debug('Calling LDAP function {func} with parameters {args}', [ + 'app' => 'user_ldap', + 'func' => $functionName, + 'args' => $this->sanitizeFunctionParameters($args), + ]); + } - $this->dataCollector->startLdapRequest($this->curFunc, $args); + if ($this->dataCollector !== null) { + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + $this->dataCollector->startLdapRequest($functionName, $this->sanitizeFunctionParameters($args), $backtrace); } if ($this->logFile !== '' && is_writable(dirname($this->logFile)) && (!file_exists($this->logFile) || is_writable($this->logFile))) { - $args = array_map(fn ($item) => (!$this->isResource($item) ? $item : '(resource)'), $this->curArgs); file_put_contents( $this->logFile, - $this->curFunc . '::' . json_encode($args) . "\n", + $functionName . '::' . json_encode($this->sanitizeFunctionParameters($args)) . "\n", FILE_APPEND ); } @@ -338,19 +345,19 @@ class LDAP implements ILDAPWrapper { /** * Analyzes the returned LDAP error and acts accordingly if not 0 * - * @param resource|\LDAP\Connection $resource the LDAP Connection resource + * @param \LDAP\Connection $resource the LDAP Connection resource * @throws ConstraintViolationException * @throws ServerNotAvailableException * @throws \Exception */ - private function processLDAPError($resource) { - $errorCode = ldap_errno($resource); - if ($errorCode === 0) { - return; - } - $errorMsg = ldap_error($resource); - - if ($this->curFunc === 'ldap_get_entries' + private function processLDAPError($resource, string $functionName, int $errorCode, string $errorMsg): void { + $this->logger->debug('LDAP error {message} ({code}) after calling {func}', [ + 'app' => 'user_ldap', + 'message' => $errorMsg, + 'code' => $errorCode, + 'func' => $functionName, + ]); + if ($functionName === 'ldap_get_entries' && $errorCode === -4) { } elseif ($errorCode === 32) { //for now @@ -365,27 +372,20 @@ class LDAP implements ILDAPWrapper { } elseif ($errorCode === 1) { throw new \Exception('LDAP Operations error', $errorCode); } elseif ($errorCode === 19) { - ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error); - throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode); - } else { - \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [ - 'app' => 'user_ldap', - 'message' => $errorMsg, - 'code' => $errorCode, - 'func' => $this->curFunc, - ]); + ldap_get_option($resource, LDAP_OPT_ERROR_STRING, $extended_error); + throw new ConstraintViolationException(!empty($extended_error) ? $extended_error : $errorMsg, $errorCode); } } /** * Called after an ldap method is run to act on LDAP error if necessary - * @throw \Exception + * @throws \Exception */ - private function postFunctionCall() { + private function postFunctionCall(string $functionName): void { if ($this->isResource($this->curArgs[0])) { $resource = $this->curArgs[0]; } elseif ( - $this->curFunc === 'ldap_search' + $functionName === 'ldap_search' && is_array($this->curArgs[0]) && $this->isResource($this->curArgs[0][0]) ) { @@ -396,9 +396,14 @@ class LDAP implements ILDAPWrapper { return; } - $this->processLDAPError($resource); + $errorCode = ldap_errno($resource); + if ($errorCode === 0) { + return; + } + $errorMsg = ldap_error($resource); + + $this->processLDAPError($resource, $functionName, $errorCode, $errorMsg); - $this->curFunc = ''; $this->curArgs = []; } } |