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