123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399 |
- <?php
- namespace OCA\User_LDAP;
- use OC\ServerNotAvailableException;
- use OCA\User_LDAP\DataCollector\LdapDataCollector;
- use OCA\User_LDAP\Exceptions\ConstraintViolationException;
- use OCP\IConfig;
- use OCP\Profiler\IProfiler;
- use Psr\Log\LoggerInterface;
- class LDAP implements ILDAPWrapper {
- protected string $logFile = '';
- protected array $curArgs = [];
- protected LoggerInterface $logger;
- private ?LdapDataCollector $dataCollector = null;
- public function __construct(string $logFile = '') {
- $this->logFile = $logFile;
-
- $profiler = \OC::$server->get(IProfiler::class);
- if ($profiler->isEnabled()) {
- $this->dataCollector = new LdapDataCollector();
- $profiler->add($this->dataCollector);
- }
- $this->logger = \OCP\Server::get(LoggerInterface::class);
- }
-
- public function bind($link, $dn, $password) {
- return $this->invokeLDAPMethod('bind', $link, $dn, $password);
- }
-
- public function connect($host, $port) {
- $pos = strpos($host, '://');
- if ($pos === false) {
- $host = 'ldap://' . $host;
- $pos = 4;
- }
- if (strpos($host, ':', $pos + 1) === false && !empty($port)) {
-
- $host .= ':' . $port;
- }
- return $this->invokeLDAPMethod('connect', $host);
- }
-
- public function controlPagedResultResponse($link, $result, &$cookie): bool {
- $errorCode = 0;
- $errorMsg = '';
- $controls = [];
- $matchedDn = null;
- $referrals = [];
-
- $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);
- }
- if ($this->dataCollector !== null) {
- $this->dataCollector->stopLastLdapRequest();
- }
- $cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? '';
- return $success;
- }
-
- public function countEntries($link, $result) {
- return $this->invokeLDAPMethod('count_entries', $link, $result);
- }
-
- public function errno($link) {
- return $this->invokeLDAPMethod('errno', $link);
- }
-
- public function error($link) {
- return $this->invokeLDAPMethod('error', $link);
- }
-
- public function explodeDN($dn, $withAttrib) {
- return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
- }
-
- public function firstEntry($link, $result) {
- return $this->invokeLDAPMethod('first_entry', $link, $result);
- }
-
- public function getAttributes($link, $result) {
- return $this->invokeLDAPMethod('get_attributes', $link, $result);
- }
-
- public function getDN($link, $result) {
- return $this->invokeLDAPMethod('get_dn', $link, $result);
- }
-
- public function getEntries($link, $result) {
- return $this->invokeLDAPMethod('get_entries', $link, $result);
- }
-
- public function nextEntry($link, $result) {
- return $this->invokeLDAPMethod('next_entry', $link, $result);
- }
-
- public function read($link, $baseDN, $filter, $attr) {
- return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr, 0, -1);
- }
-
- 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 = [];
- }
-
- $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
- if (str_contains($message, 'Partial search results returned: Sizelimit exceeded')) {
- return true;
- }
- $oldHandler($no, $message, $file, $line);
- return true;
- });
- try {
- $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit, -1, LDAP_DEREF_NEVER, $serverControls);
- restore_error_handler();
- return $result;
- } catch (\Exception $e) {
- restore_error_handler();
- throw $e;
- }
- }
-
- public function modReplace($link, $userDN, $password) {
- return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
- }
-
- public function exopPasswd($link, string $userDN, string $oldPassword, string $password) {
- return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
- }
-
- public function setOption($link, $option, $value) {
- return $this->invokeLDAPMethod('set_option', $link, $option, $value);
- }
-
- public function startTls($link) {
- return $this->invokeLDAPMethod('start_tls', $link);
- }
-
- public function unbind($link) {
- return $this->invokeLDAPMethod('unbind', $link);
- }
-
- public function areLDAPFunctionsAvailable() {
- return function_exists('ldap_connect');
- }
-
- public function isResource($resource) {
- return is_resource($resource) || is_object($resource);
- }
-
- protected function isResultFalse(string $functionName, $result): bool {
- if ($result === false) {
- return true;
- }
- if ($functionName === 'ldap_search' && is_array($result)) {
- foreach ($result as $singleResult) {
- if ($singleResult === false) {
- return true;
- }
- }
- }
- return false;
- }
-
- 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($func, $result)) {
- $this->postFunctionCall($func);
- }
- if ($this->dataCollector !== null) {
- $this->dataCollector->stopLastLdapRequest();
- }
- return $result;
- }
- return null;
- }
- private function preFunctionCall(string $functionName, array $args): void {
- $this->curArgs = $args;
- if(strcasecmp($functionName, 'ldap_bind') === 0 || strcasecmp($functionName, 'ldap_exop_passwd') === 0) {
-
-
-
-
- $args[2] = IConfig::SENSITIVE_VALUE;
- }
- $this->logger->debug('Calling LDAP function {func} with parameters {args}', [
- 'app' => 'user_ldap',
- 'func' => $functionName,
- 'args' => json_encode($args),
- ]);
- if ($this->dataCollector !== null) {
- $args = 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;
- }, $this->curArgs);
- $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
- $this->dataCollector->startLdapRequest($functionName, $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,
- $functionName . '::' . json_encode($args) . "\n",
- FILE_APPEND
- );
- }
- }
-
- 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) {
-
- } elseif ($errorCode === 10) {
-
- } elseif ($errorCode === -1) {
- throw new ServerNotAvailableException('Lost connection to LDAP server.');
- } elseif ($errorCode === 52) {
- throw new ServerNotAvailableException('LDAP server is shutting down.');
- } elseif ($errorCode === 48) {
- throw new \Exception('LDAP authentication method rejected', $errorCode);
- } elseif ($errorCode === 1) {
- throw new \Exception('LDAP Operations error', $errorCode);
- } elseif ($errorCode === 19) {
- ldap_get_option($resource, LDAP_OPT_ERROR_STRING, $extended_error);
- throw new ConstraintViolationException(!empty($extended_error) ? $extended_error : $errorMsg, $errorCode);
- }
- }
-
- private function postFunctionCall(string $functionName): void {
- if ($this->isResource($this->curArgs[0])) {
- $resource = $this->curArgs[0];
- } elseif (
- $functionName === 'ldap_search'
- && is_array($this->curArgs[0])
- && $this->isResource($this->curArgs[0][0])
- ) {
-
-
- $resource = $this->curArgs[0][0];
- } else {
- return;
- }
- $errorCode = ldap_errno($resource);
- if ($errorCode === 0) {
- return;
- }
- $errorMsg = ldap_error($resource);
- $this->processLDAPError($resource, $functionName, $errorCode, $errorMsg);
- $this->curArgs = [];
- }
- }
|