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.

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