You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LDAP.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\User_LDAP;
  34. use OC\ServerNotAvailableException;
  35. use OCA\User_LDAP\Exceptions\ConstraintViolationException;
  36. use OCA\User_LDAP\PagedResults\IAdapter;
  37. use OCA\User_LDAP\PagedResults\Php73;
  38. class LDAP implements ILDAPWrapper {
  39. protected $logFile = '';
  40. protected $curFunc = '';
  41. protected $curArgs = [];
  42. /** @var IAdapter */
  43. protected $pagedResultsAdapter;
  44. public function __construct(string $logFile = '') {
  45. $this->pagedResultsAdapter = new Php73();
  46. $this->logFile = $logFile;
  47. }
  48. /**
  49. * @param resource $link
  50. * @param string $dn
  51. * @param string $password
  52. * @return bool|mixed
  53. */
  54. public function bind($link, $dn, $password) {
  55. return $this->invokeLDAPMethod('bind', $link, $dn, $password);
  56. }
  57. /**
  58. * @param string $host
  59. * @param string $port
  60. * @return mixed
  61. */
  62. public function connect($host, $port) {
  63. if (strpos($host, '://') === false) {
  64. $host = 'ldap://' . $host;
  65. }
  66. if (strpos($host, ':', strpos($host, '://') + 1) === false) {
  67. //ldap_connect ignores port parameter when URLs are passed
  68. $host .= ':' . $port;
  69. }
  70. return $this->invokeLDAPMethod('connect', $host);
  71. }
  72. public function controlPagedResultResponse($link, $result, &$cookie): bool {
  73. $this->preFunctionCall(
  74. $this->pagedResultsAdapter->getResponseCallFunc(),
  75. $this->pagedResultsAdapter->getResponseCallArgs([$link, $result, &$cookie])
  76. );
  77. $result = $this->pagedResultsAdapter->responseCall($link);
  78. $cookie = $this->pagedResultsAdapter->getCookie($link);
  79. if ($this->isResultFalse($result)) {
  80. $this->postFunctionCall();
  81. }
  82. return $result;
  83. }
  84. /**
  85. * @param LDAP $link
  86. * @param int $pageSize
  87. * @param bool $isCritical
  88. * @return mixed|true
  89. */
  90. public function controlPagedResult($link, $pageSize, $isCritical) {
  91. $fn = $this->pagedResultsAdapter->getRequestCallFunc();
  92. $this->pagedResultsAdapter->setRequestParameters($link, $pageSize, $isCritical);
  93. if ($fn === null) {
  94. return true;
  95. }
  96. $this->preFunctionCall($fn, $this->pagedResultsAdapter->getRequestCallArgs($link));
  97. $result = $this->pagedResultsAdapter->requestCall($link);
  98. if ($this->isResultFalse($result)) {
  99. $this->postFunctionCall();
  100. }
  101. return $result;
  102. }
  103. /**
  104. * @param LDAP $link
  105. * @param LDAP $result
  106. * @return mixed
  107. */
  108. public function countEntries($link, $result) {
  109. return $this->invokeLDAPMethod('count_entries', $link, $result);
  110. }
  111. /**
  112. * @param LDAP $link
  113. * @return integer
  114. */
  115. public function errno($link) {
  116. return $this->invokeLDAPMethod('errno', $link);
  117. }
  118. /**
  119. * @param LDAP $link
  120. * @return string
  121. */
  122. public function error($link) {
  123. return $this->invokeLDAPMethod('error', $link);
  124. }
  125. /**
  126. * Splits DN into its component parts
  127. * @param string $dn
  128. * @param int @withAttrib
  129. * @return array|false
  130. * @link https://www.php.net/manual/en/function.ldap-explode-dn.php
  131. */
  132. public function explodeDN($dn, $withAttrib) {
  133. return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
  134. }
  135. /**
  136. * @param LDAP $link
  137. * @param LDAP $result
  138. * @return mixed
  139. */
  140. public function firstEntry($link, $result) {
  141. return $this->invokeLDAPMethod('first_entry', $link, $result);
  142. }
  143. /**
  144. * @param LDAP $link
  145. * @param LDAP $result
  146. * @return array|mixed
  147. */
  148. public function getAttributes($link, $result) {
  149. return $this->invokeLDAPMethod('get_attributes', $link, $result);
  150. }
  151. /**
  152. * @param LDAP $link
  153. * @param LDAP $result
  154. * @return mixed|string
  155. */
  156. public function getDN($link, $result) {
  157. return $this->invokeLDAPMethod('get_dn', $link, $result);
  158. }
  159. /**
  160. * @param LDAP $link
  161. * @param LDAP $result
  162. * @return array|mixed
  163. */
  164. public function getEntries($link, $result) {
  165. return $this->invokeLDAPMethod('get_entries', $link, $result);
  166. }
  167. /**
  168. * @param LDAP $link
  169. * @param resource $result
  170. * @return mixed
  171. */
  172. public function nextEntry($link, $result) {
  173. return $this->invokeLDAPMethod('next_entry', $link, $result);
  174. }
  175. /**
  176. * @param LDAP $link
  177. * @param string $baseDN
  178. * @param string $filter
  179. * @param array $attr
  180. * @return mixed
  181. */
  182. public function read($link, $baseDN, $filter, $attr) {
  183. $this->pagedResultsAdapter->setReadArgs($link, $baseDN, $filter, $attr);
  184. return $this->invokeLDAPMethod('read', ...$this->pagedResultsAdapter->getReadArgs($link));
  185. }
  186. /**
  187. * @param LDAP $link
  188. * @param string[] $baseDN
  189. * @param string $filter
  190. * @param array $attr
  191. * @param int $attrsOnly
  192. * @param int $limit
  193. * @return mixed
  194. * @throws \Exception
  195. */
  196. public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
  197. $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
  198. if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
  199. return true;
  200. }
  201. $oldHandler($no, $message, $file, $line);
  202. return true;
  203. });
  204. try {
  205. $this->pagedResultsAdapter->setSearchArgs($link, $baseDN, $filter, $attr, $attrsOnly, $limit);
  206. $result = $this->invokeLDAPMethod('search', ...$this->pagedResultsAdapter->getSearchArgs($link));
  207. restore_error_handler();
  208. return $result;
  209. } catch (\Exception $e) {
  210. restore_error_handler();
  211. throw $e;
  212. }
  213. }
  214. /**
  215. * @param LDAP $link
  216. * @param string $userDN
  217. * @param string $password
  218. * @return bool
  219. */
  220. public function modReplace($link, $userDN, $password) {
  221. return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
  222. }
  223. /**
  224. * @param LDAP $link
  225. * @param string $userDN
  226. * @param string $oldPassword
  227. * @param string $password
  228. * @return bool
  229. */
  230. public function exopPasswd($link, $userDN, $oldPassword, $password) {
  231. return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
  232. }
  233. /**
  234. * @param LDAP $link
  235. * @param string $option
  236. * @param int $value
  237. * @return bool|mixed
  238. */
  239. public function setOption($link, $option, $value) {
  240. return $this->invokeLDAPMethod('set_option', $link, $option, $value);
  241. }
  242. /**
  243. * @param LDAP $link
  244. * @return mixed|true
  245. */
  246. public function startTls($link) {
  247. return $this->invokeLDAPMethod('start_tls', $link);
  248. }
  249. /**
  250. * @param resource $link
  251. * @return bool|mixed
  252. */
  253. public function unbind($link) {
  254. return $this->invokeLDAPMethod('unbind', $link);
  255. }
  256. /**
  257. * Checks whether the server supports LDAP
  258. * @return boolean if it the case, false otherwise
  259. * */
  260. public function areLDAPFunctionsAvailable() {
  261. return function_exists('ldap_connect');
  262. }
  263. /**
  264. * Checks whether the submitted parameter is a resource
  265. * @param Resource $resource the resource variable to check
  266. * @return bool true if it is a resource, false otherwise
  267. */
  268. public function isResource($resource) {
  269. return is_resource($resource);
  270. }
  271. /**
  272. * Checks whether the return value from LDAP is wrong or not.
  273. *
  274. * When using ldap_search we provide an array, in case multiple bases are
  275. * configured. Thus, we need to check the array elements.
  276. *
  277. * @param $result
  278. * @return bool
  279. */
  280. protected function isResultFalse($result) {
  281. if ($result === false) {
  282. return true;
  283. }
  284. if ($this->curFunc === 'ldap_search' && is_array($result)) {
  285. foreach ($result as $singleResult) {
  286. if ($singleResult === false) {
  287. return true;
  288. }
  289. }
  290. }
  291. return false;
  292. }
  293. /**
  294. * @return mixed
  295. */
  296. protected function invokeLDAPMethod() {
  297. $arguments = func_get_args();
  298. $func = 'ldap_' . array_shift($arguments);
  299. if (function_exists($func)) {
  300. $this->preFunctionCall($func, $arguments);
  301. $result = call_user_func_array($func, $arguments);
  302. if ($this->isResultFalse($result)) {
  303. $this->postFunctionCall();
  304. }
  305. return $result;
  306. }
  307. return null;
  308. }
  309. /**
  310. * @param string $functionName
  311. * @param array $args
  312. */
  313. private function preFunctionCall($functionName, $args) {
  314. $this->curFunc = $functionName;
  315. $this->curArgs = $args;
  316. if ($this->logFile !== '' && is_writable($this->logFile)) {
  317. $args = array_reduce($this->curArgs, static function (array $carry, $item): array {
  318. $carry[] = !is_resource($item) ? $item : '(resource)';
  319. return $carry;
  320. }, []);
  321. file_put_contents(
  322. $this->logFile,
  323. $this->curFunc . '::' . json_encode($args) . "\n",
  324. FILE_APPEND
  325. );
  326. }
  327. }
  328. /**
  329. * Analyzes the returned LDAP error and acts accordingly if not 0
  330. *
  331. * @param resource $resource the LDAP Connection resource
  332. * @throws ConstraintViolationException
  333. * @throws ServerNotAvailableException
  334. * @throws \Exception
  335. */
  336. private function processLDAPError($resource) {
  337. $errorCode = ldap_errno($resource);
  338. if ($errorCode === 0) {
  339. return;
  340. }
  341. $errorMsg = ldap_error($resource);
  342. if ($this->curFunc === 'ldap_get_entries'
  343. && $errorCode === -4) {
  344. } elseif ($errorCode === 32) {
  345. //for now
  346. } elseif ($errorCode === 10) {
  347. //referrals, we switch them off, but then there is AD :)
  348. } elseif ($errorCode === -1) {
  349. throw new ServerNotAvailableException('Lost connection to LDAP server.');
  350. } elseif ($errorCode === 52) {
  351. throw new ServerNotAvailableException('LDAP server is shutting down.');
  352. } elseif ($errorCode === 48) {
  353. throw new \Exception('LDAP authentication method rejected', $errorCode);
  354. } elseif ($errorCode === 1) {
  355. throw new \Exception('LDAP Operations error', $errorCode);
  356. } elseif ($errorCode === 19) {
  357. ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
  358. throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
  359. } else {
  360. \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
  361. 'app' => 'user_ldap',
  362. 'message' => $errorMsg,
  363. 'code' => $errorCode,
  364. 'func' => $this->curFunc,
  365. ]);
  366. }
  367. }
  368. /**
  369. * Called after an ldap method is run to act on LDAP error if necessary
  370. * @throw \Exception
  371. */
  372. private function postFunctionCall() {
  373. if ($this->isResource($this->curArgs[0])) {
  374. $resource = $this->curArgs[0];
  375. } elseif (
  376. $this->curFunc === 'ldap_search'
  377. && is_array($this->curArgs[0])
  378. && $this->isResource($this->curArgs[0][0])
  379. ) {
  380. // we use always the same LDAP connection resource, is enough to
  381. // take the first one.
  382. $resource = $this->curArgs[0][0];
  383. } else {
  384. return;
  385. }
  386. $this->processLDAPError($resource);
  387. $this->curFunc = '';
  388. $this->curArgs = [];
  389. }
  390. }