LDAP.php 11 KB

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