LDAP.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 OCA\User_LDAP\PagedResults\IAdapter;
  40. use OCA\User_LDAP\PagedResults\Php73;
  41. class LDAP implements ILDAPWrapper {
  42. protected $logFile = '';
  43. protected $curFunc = '';
  44. protected $curArgs = [];
  45. /** @var IAdapter */
  46. protected $pagedResultsAdapter;
  47. private ?LdapDataCollector $dataCollector = null;
  48. public function __construct(string $logFile = '') {
  49. $this->pagedResultsAdapter = new Php73();
  50. $this->logFile = $logFile;
  51. /** @var IProfiler $profiler */
  52. $profiler = \OC::$server->get(IProfiler::class);
  53. if ($profiler->isEnabled()) {
  54. $this->dataCollector = new LdapDataCollector();
  55. $profiler->add($this->dataCollector);
  56. }
  57. }
  58. /**
  59. * {@inheritDoc}
  60. */
  61. public function bind($link, $dn, $password) {
  62. return $this->invokeLDAPMethod('bind', $link, $dn, $password);
  63. }
  64. /**
  65. * {@inheritDoc}
  66. */
  67. public function connect($host, $port) {
  68. if (strpos($host, '://') === false) {
  69. $host = 'ldap://' . $host;
  70. }
  71. if (strpos($host, ':', strpos($host, '://') + 1) === false) {
  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. $this->preFunctionCall(
  82. $this->pagedResultsAdapter->getResponseCallFunc(),
  83. $this->pagedResultsAdapter->getResponseCallArgs([$link, $result, &$cookie])
  84. );
  85. $result = $this->pagedResultsAdapter->responseCall($link);
  86. $cookie = $this->pagedResultsAdapter->getCookie($link);
  87. if ($this->isResultFalse($result)) {
  88. $this->postFunctionCall();
  89. }
  90. return $result;
  91. }
  92. /**
  93. * {@inheritDoc}
  94. */
  95. public function controlPagedResult($link, $pageSize, $isCritical) {
  96. $fn = $this->pagedResultsAdapter->getRequestCallFunc();
  97. $this->pagedResultsAdapter->setRequestParameters($link, $pageSize, $isCritical);
  98. if ($fn === null) {
  99. return true;
  100. }
  101. $this->preFunctionCall($fn, $this->pagedResultsAdapter->getRequestCallArgs($link));
  102. $result = $this->pagedResultsAdapter->requestCall($link);
  103. if ($this->isResultFalse($result)) {
  104. $this->postFunctionCall();
  105. }
  106. return $result;
  107. }
  108. /**
  109. * {@inheritDoc}
  110. */
  111. public function countEntries($link, $result) {
  112. return $this->invokeLDAPMethod('count_entries', $link, $result);
  113. }
  114. /**
  115. * {@inheritDoc}
  116. */
  117. public function errno($link) {
  118. return $this->invokeLDAPMethod('errno', $link);
  119. }
  120. /**
  121. * {@inheritDoc}
  122. */
  123. public function error($link) {
  124. return $this->invokeLDAPMethod('error', $link);
  125. }
  126. /**
  127. * Splits DN into its component parts
  128. * @param string $dn
  129. * @param int @withAttrib
  130. * @return array|false
  131. * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
  132. */
  133. public function explodeDN($dn, $withAttrib) {
  134. return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
  135. }
  136. /**
  137. * {@inheritDoc}
  138. */
  139. public function firstEntry($link, $result) {
  140. return $this->invokeLDAPMethod('first_entry', $link, $result);
  141. }
  142. /**
  143. * {@inheritDoc}
  144. */
  145. public function getAttributes($link, $result) {
  146. return $this->invokeLDAPMethod('get_attributes', $link, $result);
  147. }
  148. /**
  149. * {@inheritDoc}
  150. */
  151. public function getDN($link, $result) {
  152. return $this->invokeLDAPMethod('get_dn', $link, $result);
  153. }
  154. /**
  155. * {@inheritDoc}
  156. */
  157. public function getEntries($link, $result) {
  158. return $this->invokeLDAPMethod('get_entries', $link, $result);
  159. }
  160. /**
  161. * {@inheritDoc}
  162. */
  163. public function nextEntry($link, $result) {
  164. return $this->invokeLDAPMethod('next_entry', $link, $result);
  165. }
  166. /**
  167. * {@inheritDoc}
  168. */
  169. public function read($link, $baseDN, $filter, $attr) {
  170. $this->pagedResultsAdapter->setReadArgs($link, $baseDN, $filter, $attr);
  171. return $this->invokeLDAPMethod('read', ...$this->pagedResultsAdapter->getReadArgs($link));
  172. }
  173. /**
  174. * {@inheritDoc}
  175. */
  176. public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
  177. $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
  178. if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
  179. return true;
  180. }
  181. $oldHandler($no, $message, $file, $line);
  182. return true;
  183. });
  184. try {
  185. $this->pagedResultsAdapter->setSearchArgs($link, $baseDN, $filter, $attr, $attrsOnly, $limit);
  186. $result = $this->invokeLDAPMethod('search', ...$this->pagedResultsAdapter->getSearchArgs($link));
  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, $userDN, $oldPassword, $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 $result
  244. * @return bool
  245. */
  246. protected function isResultFalse($result) {
  247. if ($result === false) {
  248. return true;
  249. }
  250. if ($this->curFunc === 'ldap_search' && is_array($result)) {
  251. foreach ($result as $singleResult) {
  252. if ($singleResult === false) {
  253. return true;
  254. }
  255. }
  256. }
  257. return false;
  258. }
  259. /**
  260. * @return mixed
  261. */
  262. protected function invokeLDAPMethod() {
  263. $arguments = func_get_args();
  264. $func = 'ldap_' . array_shift($arguments);
  265. if (function_exists($func)) {
  266. $this->preFunctionCall($func, $arguments);
  267. $result = call_user_func_array($func, $arguments);
  268. if ($this->isResultFalse($result)) {
  269. $this->postFunctionCall();
  270. }
  271. if ($this->dataCollector !== null) {
  272. $this->dataCollector->stopLastLdapRequest();
  273. }
  274. return $result;
  275. }
  276. return null;
  277. }
  278. private function preFunctionCall(string $functionName, array $args): void {
  279. $this->curFunc = $functionName;
  280. $this->curArgs = $args;
  281. if ($this->dataCollector !== null) {
  282. $args = array_map(function ($item) {
  283. if ($this->isResource($item)) {
  284. return '(resource)';
  285. }
  286. if (isset($item[0]['value']['cookie']) && $item[0]['value']['cookie'] !== "") {
  287. $item[0]['value']['cookie'] = "*opaque cookie*";
  288. }
  289. return $item;
  290. }, $this->curArgs);
  291. $this->dataCollector->startLdapRequest($this->curFunc, $args);
  292. }
  293. if ($this->logFile !== '' && is_writable(dirname($this->logFile)) && (!file_exists($this->logFile) || is_writable($this->logFile))) {
  294. $args = array_map(fn ($item) => (!$this->isResource($item) ? $item : '(resource)'), $this->curArgs);
  295. file_put_contents(
  296. $this->logFile,
  297. $this->curFunc . '::' . json_encode($args) . "\n",
  298. FILE_APPEND
  299. );
  300. }
  301. }
  302. /**
  303. * Analyzes the returned LDAP error and acts accordingly if not 0
  304. *
  305. * @param resource|\LDAP\Connection $resource the LDAP Connection resource
  306. * @throws ConstraintViolationException
  307. * @throws ServerNotAvailableException
  308. * @throws \Exception
  309. */
  310. private function processLDAPError($resource) {
  311. $errorCode = ldap_errno($resource);
  312. if ($errorCode === 0) {
  313. return;
  314. }
  315. $errorMsg = ldap_error($resource);
  316. if ($this->curFunc === 'ldap_get_entries'
  317. && $errorCode === -4) {
  318. } elseif ($errorCode === 32) {
  319. //for now
  320. } elseif ($errorCode === 10) {
  321. //referrals, we switch them off, but then there is AD :)
  322. } elseif ($errorCode === -1) {
  323. throw new ServerNotAvailableException('Lost connection to LDAP server.');
  324. } elseif ($errorCode === 52) {
  325. throw new ServerNotAvailableException('LDAP server is shutting down.');
  326. } elseif ($errorCode === 48) {
  327. throw new \Exception('LDAP authentication method rejected', $errorCode);
  328. } elseif ($errorCode === 1) {
  329. throw new \Exception('LDAP Operations error', $errorCode);
  330. } elseif ($errorCode === 19) {
  331. ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
  332. throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
  333. } else {
  334. \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
  335. 'app' => 'user_ldap',
  336. 'message' => $errorMsg,
  337. 'code' => $errorCode,
  338. 'func' => $this->curFunc,
  339. ]);
  340. }
  341. }
  342. /**
  343. * Called after an ldap method is run to act on LDAP error if necessary
  344. * @throw \Exception
  345. */
  346. private function postFunctionCall() {
  347. if ($this->isResource($this->curArgs[0])) {
  348. $resource = $this->curArgs[0];
  349. } elseif (
  350. $this->curFunc === 'ldap_search'
  351. && is_array($this->curArgs[0])
  352. && $this->isResource($this->curArgs[0][0])
  353. ) {
  354. // we use always the same LDAP connection resource, is enough to
  355. // take the first one.
  356. $resource = $this->curArgs[0][0];
  357. } else {
  358. return;
  359. }
  360. $this->processLDAPError($resource);
  361. $this->curFunc = '';
  362. $this->curArgs = [];
  363. }
  364. }