AbstractMapping.php 11 KB

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