AbstractMapping.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\User_LDAP\Mapping;
  8. use Doctrine\DBAL\Exception;
  9. use OCP\DB\IPreparedStatement;
  10. use OCP\DB\QueryBuilder\IQueryBuilder;
  11. use OCP\IDBConnection;
  12. use Psr\Log\LoggerInterface;
  13. /**
  14. * Class AbstractMapping
  15. *
  16. * @package OCA\User_LDAP\Mapping
  17. */
  18. abstract class AbstractMapping {
  19. /**
  20. * @var \OCP\IDBConnection $dbc
  21. */
  22. protected $dbc;
  23. /**
  24. * returns the DB table name which holds the mappings
  25. *
  26. * @return string
  27. */
  28. abstract protected function getTableName(bool $includePrefix = true);
  29. /**
  30. * @param \OCP\IDBConnection $dbc
  31. */
  32. public function __construct(\OCP\IDBConnection $dbc) {
  33. $this->dbc = $dbc;
  34. }
  35. /** @var array caches Names (value) by DN (key) */
  36. protected $cache = [];
  37. /**
  38. * checks whether a provided string represents an existing table col
  39. *
  40. * @param string $col
  41. * @return bool
  42. */
  43. public function isColNameValid($col) {
  44. switch ($col) {
  45. case 'ldap_dn':
  46. case 'ldap_dn_hash':
  47. case 'owncloud_name':
  48. case 'directory_uuid':
  49. return true;
  50. default:
  51. return false;
  52. }
  53. }
  54. /**
  55. * Gets the value of one column based on a provided value of another column
  56. *
  57. * @param string $fetchCol
  58. * @param string $compareCol
  59. * @param string $search
  60. * @return string|false
  61. * @throws \Exception
  62. */
  63. protected function getXbyY($fetchCol, $compareCol, $search) {
  64. if (!$this->isColNameValid($fetchCol)) {
  65. //this is used internally only, but we don't want to risk
  66. //having SQL injection at all.
  67. throw new \Exception('Invalid Column Name');
  68. }
  69. $query = $this->dbc->prepare('
  70. SELECT `' . $fetchCol . '`
  71. FROM `' . $this->getTableName() . '`
  72. WHERE `' . $compareCol . '` = ?
  73. ');
  74. try {
  75. $res = $query->execute([$search]);
  76. $data = $res->fetchOne();
  77. $res->closeCursor();
  78. return $data;
  79. } catch (Exception $e) {
  80. return false;
  81. }
  82. }
  83. /**
  84. * Performs a DELETE or UPDATE query to the database.
  85. *
  86. * @param IPreparedStatement $statement
  87. * @param array $parameters
  88. * @return bool true if at least one row was modified, false otherwise
  89. */
  90. protected function modify(IPreparedStatement $statement, $parameters) {
  91. try {
  92. $result = $statement->execute($parameters);
  93. $updated = $result->rowCount() > 0;
  94. $result->closeCursor();
  95. return $updated;
  96. } catch (Exception $e) {
  97. return false;
  98. }
  99. }
  100. /**
  101. * Gets the LDAP DN based on the provided name.
  102. * Replaces Access::ocname2dn
  103. *
  104. * @param string $name
  105. * @return string|false
  106. */
  107. public function getDNByName($name) {
  108. $dn = array_search($name, $this->cache);
  109. if ($dn === false && ($dn = $this->getXbyY('ldap_dn', 'owncloud_name', $name)) !== false) {
  110. $this->cache[$dn] = $name;
  111. }
  112. return $dn;
  113. }
  114. /**
  115. * Updates the DN based on the given UUID
  116. *
  117. * @param string $fdn
  118. * @param string $uuid
  119. * @return bool
  120. */
  121. public function setDNbyUUID($fdn, $uuid) {
  122. $oldDn = $this->getDnByUUID($uuid);
  123. $statement = $this->dbc->prepare('
  124. UPDATE `' . $this->getTableName() . '`
  125. SET `ldap_dn_hash` = ?, `ldap_dn` = ?
  126. WHERE `directory_uuid` = ?
  127. ');
  128. $r = $this->modify($statement, [$this->getDNHash($fdn), $fdn, $uuid]);
  129. if ($r && is_string($oldDn) && isset($this->cache[$oldDn])) {
  130. $this->cache[$fdn] = $this->cache[$oldDn];
  131. unset($this->cache[$oldDn]);
  132. }
  133. return $r;
  134. }
  135. /**
  136. * Updates the UUID based on the given DN
  137. *
  138. * required by Migration/UUIDFix
  139. *
  140. * @param $uuid
  141. * @param $fdn
  142. * @return bool
  143. */
  144. public function setUUIDbyDN($uuid, $fdn): bool {
  145. $statement = $this->dbc->prepare('
  146. UPDATE `' . $this->getTableName() . '`
  147. SET `directory_uuid` = ?
  148. WHERE `ldap_dn_hash` = ?
  149. ');
  150. unset($this->cache[$fdn]);
  151. return $this->modify($statement, [$uuid, $this->getDNHash($fdn)]);
  152. }
  153. /**
  154. * Get the hash to store in database column ldap_dn_hash for a given dn
  155. */
  156. protected function getDNHash(string $fdn): string {
  157. return hash('sha256', $fdn, false);
  158. }
  159. /**
  160. * Gets the name based on the provided LDAP DN.
  161. *
  162. * @param string $fdn
  163. * @return string|false
  164. */
  165. public function getNameByDN($fdn) {
  166. if (!isset($this->cache[$fdn])) {
  167. $this->cache[$fdn] = $this->getXbyY('owncloud_name', 'ldap_dn_hash', $this->getDNHash($fdn));
  168. }
  169. return $this->cache[$fdn];
  170. }
  171. /**
  172. * @param array<string> $hashList
  173. */
  174. protected function prepareListOfIdsQuery(array $hashList): IQueryBuilder {
  175. $qb = $this->dbc->getQueryBuilder();
  176. $qb->select('owncloud_name', 'ldap_dn_hash', 'ldap_dn')
  177. ->from($this->getTableName(false))
  178. ->where($qb->expr()->in('ldap_dn_hash', $qb->createNamedParameter($hashList, IQueryBuilder::PARAM_STR_ARRAY)));
  179. return $qb;
  180. }
  181. protected function collectResultsFromListOfIdsQuery(IQueryBuilder $qb, array &$results): void {
  182. $stmt = $qb->executeQuery();
  183. while ($entry = $stmt->fetch(\Doctrine\DBAL\FetchMode::ASSOCIATIVE)) {
  184. $results[$entry['ldap_dn']] = $entry['owncloud_name'];
  185. $this->cache[$entry['ldap_dn']] = $entry['owncloud_name'];
  186. }
  187. $stmt->closeCursor();
  188. }
  189. /**
  190. * @param array<string> $fdns
  191. * @return array<string,string>
  192. */
  193. public function getListOfIdsByDn(array $fdns): array {
  194. $totalDBParamLimit = 65000;
  195. $sliceSize = 1000;
  196. $maxSlices = $this->dbc->getDatabaseProvider() === IDBConnection::PLATFORM_SQLITE ? 9 : $totalDBParamLimit / $sliceSize;
  197. $results = [];
  198. $slice = 1;
  199. $fdns = array_map([$this, 'getDNHash'], $fdns);
  200. $fdnsSlice = count($fdns) > $sliceSize ? array_slice($fdns, 0, $sliceSize) : $fdns;
  201. $qb = $this->prepareListOfIdsQuery($fdnsSlice);
  202. while (isset($fdnsSlice[999])) {
  203. // Oracle does not allow more than 1000 values in the IN list,
  204. // but allows slicing
  205. $slice++;
  206. $fdnsSlice = array_slice($fdns, $sliceSize * ($slice - 1), $sliceSize);
  207. /** @see https://github.com/vimeo/psalm/issues/4995 */
  208. /** @psalm-suppress TypeDoesNotContainType */
  209. if (!isset($qb)) {
  210. $qb = $this->prepareListOfIdsQuery($fdnsSlice);
  211. continue;
  212. }
  213. if (!empty($fdnsSlice)) {
  214. $qb->orWhere($qb->expr()->in('ldap_dn_hash', $qb->createNamedParameter($fdnsSlice, IQueryBuilder::PARAM_STR_ARRAY)));
  215. }
  216. if ($slice % $maxSlices === 0) {
  217. $this->collectResultsFromListOfIdsQuery($qb, $results);
  218. unset($qb);
  219. }
  220. }
  221. if (isset($qb)) {
  222. $this->collectResultsFromListOfIdsQuery($qb, $results);
  223. }
  224. return $results;
  225. }
  226. /**
  227. * Searches mapped names by the giving string in the name column
  228. *
  229. * @return string[]
  230. */
  231. public function getNamesBySearch(string $search, string $prefixMatch = "", string $postfixMatch = ""): array {
  232. $statement = $this->dbc->prepare('
  233. SELECT `owncloud_name`
  234. FROM `' . $this->getTableName() . '`
  235. WHERE `owncloud_name` LIKE ?
  236. ');
  237. try {
  238. $res = $statement->execute([$prefixMatch . $this->dbc->escapeLikeParameter($search) . $postfixMatch]);
  239. } catch (Exception $e) {
  240. return [];
  241. }
  242. $names = [];
  243. while ($row = $res->fetch()) {
  244. $names[] = $row['owncloud_name'];
  245. }
  246. return $names;
  247. }
  248. /**
  249. * Gets the name based on the provided LDAP UUID.
  250. *
  251. * @param string $uuid
  252. * @return string|false
  253. */
  254. public function getNameByUUID($uuid) {
  255. return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
  256. }
  257. public function getDnByUUID($uuid) {
  258. return $this->getXbyY('ldap_dn', 'directory_uuid', $uuid);
  259. }
  260. /**
  261. * Gets the UUID based on the provided LDAP DN
  262. *
  263. * @param string $dn
  264. * @return false|string
  265. * @throws \Exception
  266. */
  267. public function getUUIDByDN($dn) {
  268. return $this->getXbyY('directory_uuid', 'ldap_dn_hash', $this->getDNHash($dn));
  269. }
  270. public function getList(int $offset = 0, ?int $limit = null, bool $invalidatedOnly = false): array {
  271. $select = $this->dbc->getQueryBuilder();
  272. $select->selectAlias('ldap_dn', 'dn')
  273. ->selectAlias('owncloud_name', 'name')
  274. ->selectAlias('directory_uuid', 'uuid')
  275. ->from($this->getTableName())
  276. ->setMaxResults($limit)
  277. ->setFirstResult($offset);
  278. if ($invalidatedOnly) {
  279. $select->where($select->expr()->like('directory_uuid', $select->createNamedParameter('invalidated_%')));
  280. }
  281. $result = $select->executeQuery();
  282. $entries = $result->fetchAll();
  283. $result->closeCursor();
  284. return $entries;
  285. }
  286. /**
  287. * attempts to map the given entry
  288. *
  289. * @param string $fdn fully distinguished name (from LDAP)
  290. * @param string $name
  291. * @param string $uuid a unique identifier as used in LDAP
  292. * @return bool
  293. */
  294. public function map($fdn, $name, $uuid) {
  295. if (mb_strlen($fdn) > 4000) {
  296. \OCP\Server::get(LoggerInterface::class)->error(
  297. 'Cannot map, because the DN exceeds 4000 characters: {dn}',
  298. [
  299. 'app' => 'user_ldap',
  300. 'dn' => $fdn,
  301. ]
  302. );
  303. return false;
  304. }
  305. $row = [
  306. 'ldap_dn_hash' => $this->getDNHash($fdn),
  307. 'ldap_dn' => $fdn,
  308. 'owncloud_name' => $name,
  309. 'directory_uuid' => $uuid
  310. ];
  311. try {
  312. $result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
  313. if ((bool)$result === true) {
  314. $this->cache[$fdn] = $name;
  315. }
  316. // insertIfNotExist returns values as int
  317. return (bool)$result;
  318. } catch (\Exception $e) {
  319. return false;
  320. }
  321. }
  322. /**
  323. * removes a mapping based on the owncloud_name of the entry
  324. *
  325. * @param string $name
  326. * @return bool
  327. */
  328. public function unmap($name) {
  329. $statement = $this->dbc->prepare('
  330. DELETE FROM `' . $this->getTableName() . '`
  331. WHERE `owncloud_name` = ?');
  332. $dn = array_search($name, $this->cache);
  333. if ($dn !== false) {
  334. unset($this->cache[$dn]);
  335. }
  336. return $this->modify($statement, [$name]);
  337. }
  338. /**
  339. * Truncates the mapping table
  340. *
  341. * @return bool
  342. */
  343. public function clear() {
  344. $sql = $this->dbc
  345. ->getDatabasePlatform()
  346. ->getTruncateTableSQL('`' . $this->getTableName() . '`');
  347. try {
  348. $this->dbc->executeQuery($sql);
  349. return true;
  350. } catch (Exception $e) {
  351. return false;
  352. }
  353. }
  354. /**
  355. * clears the mapping table one by one and executing a callback with
  356. * each row's id (=owncloud_name col)
  357. *
  358. * @param callable $preCallback
  359. * @param callable $postCallback
  360. * @return bool true on success, false when at least one row was not
  361. * deleted
  362. */
  363. public function clearCb(callable $preCallback, callable $postCallback): bool {
  364. $picker = $this->dbc->getQueryBuilder();
  365. $picker->select('owncloud_name')
  366. ->from($this->getTableName());
  367. $cursor = $picker->executeQuery();
  368. $result = true;
  369. while (($id = $cursor->fetchOne()) !== false) {
  370. $preCallback($id);
  371. if ($isUnmapped = $this->unmap($id)) {
  372. $postCallback($id);
  373. }
  374. $result = $result && $isUnmapped;
  375. }
  376. $cursor->closeCursor();
  377. return $result;
  378. }
  379. /**
  380. * returns the number of entries in the mappings table
  381. *
  382. * @return int
  383. */
  384. public function count(): int {
  385. $query = $this->dbc->getQueryBuilder();
  386. $query->select($query->func()->count('ldap_dn_hash'))
  387. ->from($this->getTableName());
  388. $res = $query->execute();
  389. $count = $res->fetchOne();
  390. $res->closeCursor();
  391. return (int)$count;
  392. }
  393. public function countInvalidated(): int {
  394. $query = $this->dbc->getQueryBuilder();
  395. $query->select($query->func()->count('ldap_dn_hash'))
  396. ->from($this->getTableName())
  397. ->where($query->expr()->like('directory_uuid', $query->createNamedParameter('invalidated_%')));
  398. $res = $query->execute();
  399. $count = $res->fetchOne();
  400. $res->closeCursor();
  401. return (int)$count;
  402. }
  403. }