LDAP.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 OCP\IConfig;
  36. use OCP\Profiler\IProfiler;
  37. use OC\ServerNotAvailableException;
  38. use OCA\User_LDAP\DataCollector\LdapDataCollector;
  39. use OCA\User_LDAP\Exceptions\ConstraintViolationException;
  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. $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
  184. if (str_contains($message, 'Partial search results returned: Sizelimit exceeded')) {
  185. return true;
  186. }
  187. $oldHandler($no, $message, $file, $line);
  188. return true;
  189. });
  190. try {
  191. $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit, -1, LDAP_DEREF_NEVER, $serverControls);
  192. restore_error_handler();
  193. return $result;
  194. } catch (\Exception $e) {
  195. restore_error_handler();
  196. throw $e;
  197. }
  198. }
  199. /**
  200. * {@inheritDoc}
  201. */
  202. public function modReplace($link, $userDN, $password) {
  203. return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
  204. }
  205. /**
  206. * {@inheritDoc}
  207. */
  208. public function exopPasswd($link, string $userDN, string $oldPassword, string $password) {
  209. return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
  210. }
  211. /**
  212. * {@inheritDoc}
  213. */
  214. public function setOption($link, $option, $value) {
  215. return $this->invokeLDAPMethod('set_option', $link, $option, $value);
  216. }
  217. /**
  218. * {@inheritDoc}
  219. */
  220. public function startTls($link) {
  221. return $this->invokeLDAPMethod('start_tls', $link);
  222. }
  223. /**
  224. * {@inheritDoc}
  225. */
  226. public function unbind($link) {
  227. return $this->invokeLDAPMethod('unbind', $link);
  228. }
  229. /**
  230. * Checks whether the server supports LDAP
  231. * @return boolean if it the case, false otherwise
  232. * */
  233. public function areLDAPFunctionsAvailable() {
  234. return function_exists('ldap_connect');
  235. }
  236. /**
  237. * {@inheritDoc}
  238. */
  239. public function isResource($resource) {
  240. return is_resource($resource) || is_object($resource);
  241. }
  242. /**
  243. * Checks whether the return value from LDAP is wrong or not.
  244. *
  245. * When using ldap_search we provide an array, in case multiple bases are
  246. * configured. Thus, we need to check the array elements.
  247. *
  248. * @param mixed $result
  249. */
  250. protected function isResultFalse(string $functionName, $result): bool {
  251. if ($result === false) {
  252. return true;
  253. }
  254. if ($functionName === 'ldap_search' && is_array($result)) {
  255. foreach ($result as $singleResult) {
  256. if ($singleResult === false) {
  257. return true;
  258. }
  259. }
  260. }
  261. return false;
  262. }
  263. /**
  264. * @param array $arguments
  265. * @return mixed
  266. */
  267. protected function invokeLDAPMethod(string $func, ...$arguments) {
  268. $func = 'ldap_' . $func;
  269. if (function_exists($func)) {
  270. $this->preFunctionCall($func, $arguments);
  271. $result = call_user_func_array($func, $arguments);
  272. if ($this->isResultFalse($func, $result)) {
  273. $this->postFunctionCall($func);
  274. }
  275. if ($this->dataCollector !== null) {
  276. $this->dataCollector->stopLastLdapRequest();
  277. }
  278. return $result;
  279. }
  280. return null;
  281. }
  282. private function preFunctionCall(string $functionName, array $args): void {
  283. $this->curArgs = $args;
  284. if(strcasecmp($functionName, 'ldap_bind') === 0) {
  285. // The arguments are not key value pairs
  286. // \OCA\User_LDAP\LDAP::bind passes 3 arguments, the 3rd being the pw
  287. // Remove it via direct array access for now, although a better solution could be found mebbe?
  288. // @link https://github.com/nextcloud/server/issues/38461
  289. $args[2] = IConfig::SENSITIVE_VALUE;
  290. }
  291. $this->logger->debug('Calling LDAP function {func} with parameters {args}', [
  292. 'app' => 'user_ldap',
  293. 'func' => $functionName,
  294. 'args' => json_encode($args),
  295. ]);
  296. if ($this->dataCollector !== null) {
  297. $args = array_map(function ($item) {
  298. if ($this->isResource($item)) {
  299. return '(resource)';
  300. }
  301. if (isset($item[0]['value']['cookie']) && $item[0]['value']['cookie'] !== "") {
  302. $item[0]['value']['cookie'] = "*opaque cookie*";
  303. }
  304. return $item;
  305. }, $this->curArgs);
  306. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  307. $this->dataCollector->startLdapRequest($functionName, $args, $backtrace);
  308. }
  309. if ($this->logFile !== '' && is_writable(dirname($this->logFile)) && (!file_exists($this->logFile) || is_writable($this->logFile))) {
  310. $args = array_map(fn ($item) => (!$this->isResource($item) ? $item : '(resource)'), $this->curArgs);
  311. file_put_contents(
  312. $this->logFile,
  313. $functionName . '::' . json_encode($args) . "\n",
  314. FILE_APPEND
  315. );
  316. }
  317. }
  318. /**
  319. * Analyzes the returned LDAP error and acts accordingly if not 0
  320. *
  321. * @param resource|\LDAP\Connection $resource the LDAP Connection resource
  322. * @throws ConstraintViolationException
  323. * @throws ServerNotAvailableException
  324. * @throws \Exception
  325. */
  326. private function processLDAPError($resource, string $functionName, int $errorCode, string $errorMsg): void {
  327. $this->logger->debug('LDAP error {message} ({code}) after calling {func}', [
  328. 'app' => 'user_ldap',
  329. 'message' => $errorMsg,
  330. 'code' => $errorCode,
  331. 'func' => $functionName,
  332. ]);
  333. if ($functionName === 'ldap_get_entries'
  334. && $errorCode === -4) {
  335. } elseif ($errorCode === 32) {
  336. //for now
  337. } elseif ($errorCode === 10) {
  338. //referrals, we switch them off, but then there is AD :)
  339. } elseif ($errorCode === -1) {
  340. throw new ServerNotAvailableException('Lost connection to LDAP server.');
  341. } elseif ($errorCode === 52) {
  342. throw new ServerNotAvailableException('LDAP server is shutting down.');
  343. } elseif ($errorCode === 48) {
  344. throw new \Exception('LDAP authentication method rejected', $errorCode);
  345. } elseif ($errorCode === 1) {
  346. throw new \Exception('LDAP Operations error', $errorCode);
  347. } elseif ($errorCode === 19) {
  348. ldap_get_option($resource, LDAP_OPT_ERROR_STRING, $extended_error);
  349. throw new ConstraintViolationException(!empty($extended_error) ? $extended_error : $errorMsg, $errorCode);
  350. }
  351. }
  352. /**
  353. * Called after an ldap method is run to act on LDAP error if necessary
  354. * @throw \Exception
  355. */
  356. private function postFunctionCall(string $functionName): void {
  357. if ($this->isResource($this->curArgs[0])) {
  358. $resource = $this->curArgs[0];
  359. } elseif (
  360. $functionName === 'ldap_search'
  361. && is_array($this->curArgs[0])
  362. && $this->isResource($this->curArgs[0][0])
  363. ) {
  364. // we use always the same LDAP connection resource, is enough to
  365. // take the first one.
  366. $resource = $this->curArgs[0][0];
  367. } else {
  368. return;
  369. }
  370. $errorCode = ldap_errno($resource);
  371. if ($errorCode === 0) {
  372. return;
  373. }
  374. $errorMsg = ldap_error($resource);
  375. $this->processLDAPError($resource, $functionName, $errorCode, $errorMsg);
  376. $this->curArgs = [];
  377. }
  378. }