AbstractMapping.php 12 KB

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