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

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