LDAP.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\User_LDAP;
  8. use OC\ServerNotAvailableException;
  9. use OCA\User_LDAP\DataCollector\LdapDataCollector;
  10. use OCA\User_LDAP\Exceptions\ConstraintViolationException;
  11. use OCP\IConfig;
  12. use OCP\Profiler\IProfiler;
  13. use OCP\Server;
  14. use Psr\Log\LoggerInterface;
  15. class LDAP implements ILDAPWrapper {
  16. protected array $curArgs = [];
  17. protected LoggerInterface $logger;
  18. private ?LdapDataCollector $dataCollector = null;
  19. public function __construct(
  20. protected string $logFile = '',
  21. ) {
  22. /** @var IProfiler $profiler */
  23. $profiler = \OC::$server->get(IProfiler::class);
  24. if ($profiler->isEnabled()) {
  25. $this->dataCollector = new LdapDataCollector();
  26. $profiler->add($this->dataCollector);
  27. }
  28. $this->logger = Server::get(LoggerInterface::class);
  29. }
  30. /**
  31. * {@inheritDoc}
  32. */
  33. public function bind($link, $dn, $password) {
  34. return $this->invokeLDAPMethod('bind', $link, $dn, $password);
  35. }
  36. /**
  37. * {@inheritDoc}
  38. */
  39. public function connect($host, $port) {
  40. $pos = strpos($host, '://');
  41. if ($pos === false) {
  42. $host = 'ldap://' . $host;
  43. $pos = 4;
  44. }
  45. if (strpos($host, ':', $pos + 1) === false && !empty($port)) {
  46. //ldap_connect ignores port parameter when URLs are passed
  47. $host .= ':' . $port;
  48. }
  49. return $this->invokeLDAPMethod('connect', $host);
  50. }
  51. /**
  52. * {@inheritDoc}
  53. */
  54. public function controlPagedResultResponse($link, $result, &$cookie): bool {
  55. $errorCode = 0;
  56. $errorMsg = '';
  57. $controls = [];
  58. $matchedDn = null;
  59. $referrals = [];
  60. /** Cannot use invokeLDAPMethod because arguments are passed by reference */
  61. $this->preFunctionCall('ldap_parse_result', [$link, $result]);
  62. $success = ldap_parse_result($link, $result,
  63. $errorCode,
  64. $matchedDn,
  65. $errorMsg,
  66. $referrals,
  67. $controls);
  68. if ($errorCode !== 0) {
  69. $this->processLDAPError($link, 'ldap_parse_result', $errorCode, $errorMsg);
  70. }
  71. if ($this->dataCollector !== null) {
  72. $this->dataCollector->stopLastLdapRequest();
  73. }
  74. $cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? '';
  75. return $success;
  76. }
  77. /**
  78. * {@inheritDoc}
  79. */
  80. public function countEntries($link, $result) {
  81. return $this->invokeLDAPMethod('count_entries', $link, $result);
  82. }
  83. /**
  84. * {@inheritDoc}
  85. */
  86. public function errno($link) {
  87. return $this->invokeLDAPMethod('errno', $link);
  88. }
  89. /**
  90. * {@inheritDoc}
  91. */
  92. public function error($link) {
  93. return $this->invokeLDAPMethod('error', $link);
  94. }
  95. /**
  96. * Splits DN into its component parts
  97. * @param string $dn
  98. * @param int $withAttrib
  99. * @return array|false
  100. * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
  101. */
  102. public function explodeDN($dn, $withAttrib) {
  103. return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
  104. }
  105. /**
  106. * {@inheritDoc}
  107. */
  108. public function firstEntry($link, $result) {
  109. return $this->invokeLDAPMethod('first_entry', $link, $result);
  110. }
  111. /**
  112. * {@inheritDoc}
  113. */
  114. public function getAttributes($link, $result) {
  115. return $this->invokeLDAPMethod('get_attributes', $link, $result);
  116. }
  117. /**
  118. * {@inheritDoc}
  119. */
  120. public function getDN($link, $result) {
  121. return $this->invokeLDAPMethod('get_dn', $link, $result);
  122. }
  123. /**
  124. * {@inheritDoc}
  125. */
  126. public function getEntries($link, $result) {
  127. return $this->invokeLDAPMethod('get_entries', $link, $result);
  128. }
  129. /**
  130. * {@inheritDoc}
  131. */
  132. public function nextEntry($link, $result) {
  133. return $this->invokeLDAPMethod('next_entry', $link, $result);
  134. }
  135. /**
  136. * {@inheritDoc}
  137. */
  138. public function read($link, $baseDN, $filter, $attr) {
  139. return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr, 0, -1);
  140. }
  141. /**
  142. * {@inheritDoc}
  143. */
  144. public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0, int $pageSize = 0, string $cookie = '') {
  145. if ($pageSize > 0 || $cookie !== '') {
  146. $serverControls = [[
  147. 'oid' => LDAP_CONTROL_PAGEDRESULTS,
  148. 'value' => [
  149. 'size' => $pageSize,
  150. 'cookie' => $cookie,
  151. ],
  152. 'iscritical' => false,
  153. ]];
  154. } else {
  155. $serverControls = [];
  156. }
  157. /** @psalm-suppress UndefinedVariable $oldHandler is defined when the closure is called but psalm fails to get that */
  158. $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
  159. if (str_contains($message, 'Partial search results returned: Sizelimit exceeded')) {
  160. return true;
  161. }
  162. $oldHandler($no, $message, $file, $line);
  163. return true;
  164. });
  165. try {
  166. $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit, -1, LDAP_DEREF_NEVER, $serverControls);
  167. restore_error_handler();
  168. return $result;
  169. } catch (\Exception $e) {
  170. restore_error_handler();
  171. throw $e;
  172. }
  173. }
  174. /**
  175. * {@inheritDoc}
  176. */
  177. public function modReplace($link, $userDN, $password) {
  178. return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
  179. }
  180. /**
  181. * {@inheritDoc}
  182. */
  183. public function exopPasswd($link, string $userDN, string $oldPassword, string $password) {
  184. return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
  185. }
  186. /**
  187. * {@inheritDoc}
  188. */
  189. public function setOption($link, $option, $value) {
  190. return $this->invokeLDAPMethod('set_option', $link, $option, $value);
  191. }
  192. /**
  193. * {@inheritDoc}
  194. */
  195. public function startTls($link) {
  196. return $this->invokeLDAPMethod('start_tls', $link);
  197. }
  198. /**
  199. * {@inheritDoc}
  200. */
  201. public function unbind($link) {
  202. return $this->invokeLDAPMethod('unbind', $link);
  203. }
  204. /**
  205. * Checks whether the server supports LDAP
  206. * @return boolean if it the case, false otherwise
  207. * */
  208. public function areLDAPFunctionsAvailable() {
  209. return function_exists('ldap_connect');
  210. }
  211. /**
  212. * {@inheritDoc}
  213. */
  214. public function isResource($resource) {
  215. return is_resource($resource) || is_object($resource);
  216. }
  217. /**
  218. * Checks whether the return value from LDAP is wrong or not.
  219. *
  220. * When using ldap_search we provide an array, in case multiple bases are
  221. * configured. Thus, we need to check the array elements.
  222. *
  223. * @param mixed $result
  224. */
  225. protected function isResultFalse(string $functionName, $result): bool {
  226. if ($result === false) {
  227. return true;
  228. }
  229. if ($functionName === 'ldap_search' && is_array($result)) {
  230. foreach ($result as $singleResult) {
  231. if ($singleResult === false) {
  232. return true;
  233. }
  234. }
  235. }
  236. return false;
  237. }
  238. /**
  239. * @param array $arguments
  240. * @return mixed
  241. */
  242. protected function invokeLDAPMethod(string $func, ...$arguments) {
  243. $func = 'ldap_' . $func;
  244. if (function_exists($func)) {
  245. $this->preFunctionCall($func, $arguments);
  246. $result = call_user_func_array($func, $arguments);
  247. if ($this->isResultFalse($func, $result)) {
  248. $this->postFunctionCall($func);
  249. }
  250. if ($this->dataCollector !== null) {
  251. $this->dataCollector->stopLastLdapRequest();
  252. }
  253. return $result;
  254. }
  255. return null;
  256. }
  257. private function preFunctionCall(string $functionName, array $args): void {
  258. $this->curArgs = $args;
  259. if (strcasecmp($functionName, 'ldap_bind') === 0 || strcasecmp($functionName, 'ldap_exop_passwd') === 0) {
  260. // The arguments are not key value pairs
  261. // \OCA\User_LDAP\LDAP::bind passes 3 arguments, the 3rd being the pw
  262. // Remove it via direct array access for now, although a better solution could be found mebbe?
  263. // @link https://github.com/nextcloud/server/issues/38461
  264. $args[2] = IConfig::SENSITIVE_VALUE;
  265. }
  266. $this->logger->debug('Calling LDAP function {func} with parameters {args}', [
  267. 'app' => 'user_ldap',
  268. 'func' => $functionName,
  269. 'args' => json_encode($args),
  270. ]);
  271. if ($this->dataCollector !== null) {
  272. $args = array_map(function ($item) {
  273. if ($this->isResource($item)) {
  274. return '(resource)';
  275. }
  276. if (isset($item[0]['value']['cookie']) && $item[0]['value']['cookie'] !== '') {
  277. $item[0]['value']['cookie'] = '*opaque cookie*';
  278. }
  279. return $item;
  280. }, $this->curArgs);
  281. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  282. $this->dataCollector->startLdapRequest($functionName, $args, $backtrace);
  283. }
  284. if ($this->logFile !== '' && is_writable(dirname($this->logFile)) && (!file_exists($this->logFile) || is_writable($this->logFile))) {
  285. $args = array_map(fn ($item) => (!$this->isResource($item) ? $item : '(resource)'), $this->curArgs);
  286. file_put_contents(
  287. $this->logFile,
  288. $functionName . '::' . json_encode($args) . "\n",
  289. FILE_APPEND
  290. );
  291. }
  292. }
  293. /**
  294. * Analyzes the returned LDAP error and acts accordingly if not 0
  295. *
  296. * @param \LDAP\Connection $resource the LDAP Connection resource
  297. * @throws ConstraintViolationException
  298. * @throws ServerNotAvailableException
  299. * @throws \Exception
  300. */
  301. private function processLDAPError($resource, string $functionName, int $errorCode, string $errorMsg): void {
  302. $this->logger->debug('LDAP error {message} ({code}) after calling {func}', [
  303. 'app' => 'user_ldap',
  304. 'message' => $errorMsg,
  305. 'code' => $errorCode,
  306. 'func' => $functionName,
  307. ]);
  308. if ($functionName === 'ldap_get_entries'
  309. && $errorCode === -4) {
  310. } elseif ($errorCode === 32) {
  311. //for now
  312. } elseif ($errorCode === 10) {
  313. //referrals, we switch them off, but then there is AD :)
  314. } elseif ($errorCode === -1) {
  315. throw new ServerNotAvailableException('Lost connection to LDAP server.');
  316. } elseif ($errorCode === 52) {
  317. throw new ServerNotAvailableException('LDAP server is shutting down.');
  318. } elseif ($errorCode === 48) {
  319. throw new \Exception('LDAP authentication method rejected', $errorCode);
  320. } elseif ($errorCode === 1) {
  321. throw new \Exception('LDAP Operations error', $errorCode);
  322. } elseif ($errorCode === 19) {
  323. ldap_get_option($resource, LDAP_OPT_ERROR_STRING, $extended_error);
  324. throw new ConstraintViolationException(!empty($extended_error) ? $extended_error : $errorMsg, $errorCode);
  325. }
  326. }
  327. /**
  328. * Called after an ldap method is run to act on LDAP error if necessary
  329. * @throws \Exception
  330. */
  331. private function postFunctionCall(string $functionName): void {
  332. if ($this->isResource($this->curArgs[0])) {
  333. $resource = $this->curArgs[0];
  334. } elseif (
  335. $functionName === 'ldap_search'
  336. && is_array($this->curArgs[0])
  337. && $this->isResource($this->curArgs[0][0])
  338. ) {
  339. // we use always the same LDAP connection resource, is enough to
  340. // take the first one.
  341. $resource = $this->curArgs[0][0];
  342. } else {
  343. return;
  344. }
  345. $errorCode = ldap_errno($resource);
  346. if ($errorCode === 0) {
  347. return;
  348. }
  349. $errorMsg = ldap_error($resource);
  350. $this->processLDAPError($resource, $functionName, $errorCode, $errorMsg);
  351. $this->curArgs = [];
  352. }
  353. }