LDAP.php 12 KB

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