LDAP.php 11 KB

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