keymanager.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Bjoern Schiessle
  6. * @copyright 2012 Bjoern Schiessle <schiessle@owncloud.com>
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. namespace OCA\Encryption;
  23. /**
  24. * @brief Class to manage storage and retrieval of encryption keys
  25. * @note Where a method requires a view object, it's root must be '/'
  26. */
  27. class Keymanager {
  28. /**
  29. * @brief retrieve the ENCRYPTED private key from a user
  30. *
  31. * @param \OC_FilesystemView $view
  32. * @param string $user
  33. * @return string private key or false (hopefully)
  34. * @note the key returned by this method must be decrypted before use
  35. */
  36. public static function getPrivateKey(\OC_FilesystemView $view, $user) {
  37. $path = '/' . $user . '/' . 'files_encryption' . '/' . $user . '.private.key';
  38. $proxyStatus = \OC_FileProxy::$enabled;
  39. \OC_FileProxy::$enabled = false;
  40. $key = $view->file_get_contents($path);
  41. \OC_FileProxy::$enabled = $proxyStatus;
  42. return $key;
  43. }
  44. /**
  45. * @brief retrieve public key for a specified user
  46. * @param \OC_FilesystemView $view
  47. * @param $userId
  48. * @return string public key or false
  49. */
  50. public static function getPublicKey(\OC_FilesystemView $view, $userId) {
  51. $proxyStatus = \OC_FileProxy::$enabled;
  52. \OC_FileProxy::$enabled = false;
  53. $result = $view->file_get_contents('/public-keys/' . $userId . '.public.key');
  54. \OC_FileProxy::$enabled = $proxyStatus;
  55. return $result;
  56. }
  57. /**
  58. * @brief Retrieve a user's public and private key
  59. * @param \OC_FilesystemView $view
  60. * @param $userId
  61. * @return array keys: privateKey, publicKey
  62. */
  63. public static function getUserKeys(\OC_FilesystemView $view, $userId) {
  64. return array(
  65. 'publicKey' => self::getPublicKey($view, $userId),
  66. 'privateKey' => self::getPrivateKey($view, $userId)
  67. );
  68. }
  69. /**
  70. * @brief Retrieve public keys for given users
  71. * @param \OC_FilesystemView $view
  72. * @param array $userIds
  73. * @return array of public keys for the specified users
  74. */
  75. public static function getPublicKeys(\OC_FilesystemView $view, array $userIds) {
  76. $keys = array();
  77. foreach ($userIds as $userId) {
  78. $keys[$userId] = self::getPublicKey($view, $userId);
  79. }
  80. return $keys;
  81. }
  82. /**
  83. * @brief store file encryption key
  84. *
  85. * @param \OC_FilesystemView $view
  86. * @param string $path relative path of the file, including filename
  87. * @param $userId
  88. * @param $catfile
  89. * @internal param string $key
  90. * @return bool true/false
  91. * @note The keyfile is not encrypted here. Client code must
  92. * asymmetrically encrypt the keyfile before passing it to this method
  93. */
  94. public static function setFileKey(\OC_FilesystemView $view, $path, $userId, $catfile) {
  95. $proxyStatus = \OC_FileProxy::$enabled;
  96. \OC_FileProxy::$enabled = false;
  97. //here we need the currently logged in user, while userId can be a different user
  98. $util = new Util($view, \OCP\User::getUser());
  99. list($owner, $filename) = $util->getUidAndFilename($path);
  100. // in case of system wide mount points the keys are stored directly in the data directory
  101. if ($util->isSystemWideMountPoint($filename)) {
  102. $basePath = '/files_encryption/keyfiles';
  103. } else {
  104. $basePath = '/' . $owner . '/files_encryption/keyfiles';
  105. }
  106. $targetPath = self::keySetPreparation($view, $filename, $basePath, $owner);
  107. if (!$view->is_dir($basePath . '/' . $targetPath)) {
  108. // create all parent folders
  109. $info = pathinfo($basePath . '/' . $targetPath);
  110. $keyfileFolderName = $view->getLocalFolder($info['dirname']);
  111. if (!file_exists($keyfileFolderName)) {
  112. mkdir($keyfileFolderName, 0750, true);
  113. }
  114. }
  115. // try reusing key file if part file
  116. if (self::isPartialFilePath($targetPath)) {
  117. $result = $view->file_put_contents(
  118. $basePath . '/' . self::fixPartialFilePath($targetPath) . '.key', $catfile);
  119. } else {
  120. $result = $view->file_put_contents($basePath . '/' . $targetPath . '.key', $catfile);
  121. }
  122. \OC_FileProxy::$enabled = $proxyStatus;
  123. return $result;
  124. }
  125. /**
  126. * @brief Remove .path extension from a file path
  127. * @param string $path Path that may identify a .part file
  128. * @return string File path without .part extension
  129. * @note this is needed for reusing keys
  130. */
  131. public static function fixPartialFilePath($path) {
  132. if (preg_match('/\.part$/', $path) || preg_match('/\.etmp$/', $path)) {
  133. $newLength = strlen($path) - 5;
  134. $fPath = substr($path, 0, $newLength);
  135. return $fPath;
  136. } else {
  137. return $path;
  138. }
  139. }
  140. /**
  141. * @brief Check if a path is a .part file
  142. * @param string $path Path that may identify a .part file
  143. * @return bool
  144. */
  145. public static function isPartialFilePath($path) {
  146. if (preg_match('/\.part$/', $path) || preg_match('/\.etmp$/', $path)) {
  147. return true;
  148. } else {
  149. return false;
  150. }
  151. }
  152. /**
  153. * @brief retrieve keyfile for an encrypted file
  154. * @param \OC_FilesystemView $view
  155. * @param $userId
  156. * @param $filePath
  157. * @internal param \OCA\Encryption\file $string name
  158. * @return string file key or false
  159. * @note The keyfile returned is asymmetrically encrypted. Decryption
  160. * of the keyfile must be performed by client code
  161. */
  162. public static function getFileKey(\OC_FilesystemView $view, $userId, $filePath) {
  163. // try reusing key file if part file
  164. if (self::isPartialFilePath($filePath)) {
  165. $result = self::getFileKey($view, $userId, self::fixPartialFilePath($filePath));
  166. if ($result) {
  167. return $result;
  168. }
  169. }
  170. $util = new Util($view, \OCP\User::getUser());
  171. list($owner, $filename) = $util->getUidAndFilename($filePath);
  172. $filePath_f = ltrim($filename, '/');
  173. // in case of system wide mount points the keys are stored directly in the data directory
  174. if ($util->isSystemWideMountPoint($filename)) {
  175. $keyfilePath = '/files_encryption/keyfiles/' . $filePath_f . '.key';
  176. } else {
  177. $keyfilePath = '/' . $owner . '/files_encryption/keyfiles/' . $filePath_f . '.key';
  178. }
  179. $proxyStatus = \OC_FileProxy::$enabled;
  180. \OC_FileProxy::$enabled = false;
  181. if ($view->file_exists($keyfilePath)) {
  182. $result = $view->file_get_contents($keyfilePath);
  183. } else {
  184. $result = false;
  185. }
  186. \OC_FileProxy::$enabled = $proxyStatus;
  187. return $result;
  188. }
  189. /**
  190. * @brief Delete a keyfile
  191. *
  192. * @param \OC_FilesystemView $view
  193. * @param string $userId username
  194. * @param string $path path of the file the key belongs to
  195. * @return bool Outcome of unlink operation
  196. * @note $path must be relative to data/user/files. e.g. mydoc.txt NOT
  197. * /data/admin/files/mydoc.txt
  198. */
  199. public static function deleteFileKey(\OC_FilesystemView $view, $userId, $path) {
  200. $trimmed = ltrim($path, '/');
  201. $util = new Util($view, \OCP\User::getUser());
  202. if($util->isSystemWideMountPoint($path)) {
  203. $keyPath = '/files_encryption/keyfiles/' . $trimmed;
  204. } else {
  205. $keyPath = '/' . $userId . '/files_encryption/keyfiles/' . $trimmed;
  206. }
  207. $result = false;
  208. if ($view->is_dir($keyPath)) {
  209. $result = $view->unlink($keyPath);
  210. } else {
  211. if ($view->file_exists($keyPath . '.key')) {
  212. $result = $view->unlink($keyPath . '.key');
  213. }
  214. }
  215. if (!$result) {
  216. \OCP\Util::writeLog('Encryption library',
  217. 'Could not delete keyfile; does not exist: "' . $keyPath, \OCP\Util::ERROR);
  218. }
  219. return $result;
  220. }
  221. /**
  222. * @brief store private key from the user
  223. * @param string $key
  224. * @return bool
  225. * @note Encryption of the private key must be performed by client code
  226. * as no encryption takes place here
  227. */
  228. public static function setPrivateKey($key) {
  229. $user = \OCP\User::getUser();
  230. $view = new \OC_FilesystemView('/' . $user . '/files_encryption');
  231. $proxyStatus = \OC_FileProxy::$enabled;
  232. \OC_FileProxy::$enabled = false;
  233. if (!$view->file_exists(''))
  234. $view->mkdir('');
  235. $result = $view->file_put_contents($user . '.private.key', $key);
  236. \OC_FileProxy::$enabled = $proxyStatus;
  237. return $result;
  238. }
  239. /**
  240. * @brief store share key
  241. *
  242. * @param \OC_FilesystemView $view
  243. * @param string $path where the share key is stored
  244. * @param $shareKey
  245. * @return bool true/false
  246. * @note The keyfile is not encrypted here. Client code must
  247. * asymmetrically encrypt the keyfile before passing it to this method
  248. */
  249. private static function setShareKey(\OC_FilesystemView $view, $path, $shareKey) {
  250. $proxyStatus = \OC_FileProxy::$enabled;
  251. \OC_FileProxy::$enabled = false;
  252. $result = $view->file_put_contents($path, $shareKey);
  253. \OC_FileProxy::$enabled = $proxyStatus;
  254. if (is_int($result) && $result > 0) {
  255. return true;
  256. } else {
  257. return false;
  258. }
  259. }
  260. /**
  261. * @brief store multiple share keys for a single file
  262. * @param \OC_FilesystemView $view
  263. * @param $path
  264. * @param array $shareKeys
  265. * @return bool
  266. */
  267. public static function setShareKeys(\OC_FilesystemView $view, $path, array $shareKeys) {
  268. // $shareKeys must be an array with the following format:
  269. // [userId] => [encrypted key]
  270. // Here we need the currently logged in user, while userId can be a different user
  271. $util = new Util($view, \OCP\User::getUser());
  272. list($owner, $filename) = $util->getUidAndFilename($path);
  273. // in case of system wide mount points the keys are stored directly in the data directory
  274. if ($util->isSystemWideMountPoint($filename)) {
  275. $basePath = '/files_encryption/share-keys';
  276. } else {
  277. $basePath = '/' . $owner . '/files_encryption/share-keys';
  278. }
  279. $shareKeyPath = self::keySetPreparation($view, $filename, $basePath, $owner);
  280. $result = true;
  281. foreach ($shareKeys as $userId => $shareKey) {
  282. // try reusing key file if part file
  283. if (self::isPartialFilePath($shareKeyPath)) {
  284. $writePath = $basePath . '/' . self::fixPartialFilePath($shareKeyPath) . '.' . $userId . '.shareKey';
  285. } else {
  286. $writePath = $basePath . '/' . $shareKeyPath . '.' . $userId . '.shareKey';
  287. }
  288. if (!self::setShareKey($view, $writePath, $shareKey)) {
  289. // If any of the keys are not set, flag false
  290. $result = false;
  291. }
  292. }
  293. // Returns false if any of the keys weren't set
  294. return $result;
  295. }
  296. /**
  297. * @brief retrieve shareKey for an encrypted file
  298. * @param \OC_FilesystemView $view
  299. * @param string $userId
  300. * @param string $filePath
  301. * @internal param \OCA\Encryption\file $string name
  302. * @return string file key or false
  303. * @note The sharekey returned is encrypted. Decryption
  304. * of the keyfile must be performed by client code
  305. */
  306. public static function getShareKey(\OC_FilesystemView $view, $userId, $filePath) {
  307. // try reusing key file if part file
  308. if (self::isPartialFilePath($filePath)) {
  309. $result = self::getShareKey($view, $userId, self::fixPartialFilePath($filePath));
  310. if ($result) {
  311. return $result;
  312. }
  313. }
  314. $proxyStatus = \OC_FileProxy::$enabled;
  315. \OC_FileProxy::$enabled = false;
  316. //here we need the currently logged in user, while userId can be a different user
  317. $util = new Util($view, \OCP\User::getUser());
  318. list($owner, $filename) = $util->getUidAndFilename($filePath);
  319. // in case of system wide mount points the keys are stored directly in the data directory
  320. if ($util->isSystemWideMountPoint($filename)) {
  321. $shareKeyPath = '/files_encryption/share-keys/' . $filename . '.' . $userId . '.shareKey';
  322. } else {
  323. $shareKeyPath = '/' . $owner . '/files_encryption/share-keys/' . $filename . '.' . $userId . '.shareKey';
  324. }
  325. if ($view->file_exists($shareKeyPath)) {
  326. $result = $view->file_get_contents($shareKeyPath);
  327. } else {
  328. $result = false;
  329. }
  330. \OC_FileProxy::$enabled = $proxyStatus;
  331. return $result;
  332. }
  333. /**
  334. * @brief delete all share keys of a given file
  335. * @param \OC_FilesystemView $view
  336. * @param string $userId owner of the file
  337. * @param string $filePath path to the file, relative to the owners file dir
  338. */
  339. public static function delAllShareKeys(\OC_FilesystemView $view, $userId, $filePath) {
  340. $util = new util($view, $userId);
  341. if ($util->isSystemWideMountPoint($filePath)) {
  342. $baseDir = '/files_encryption/share-keys/';
  343. } else {
  344. $baseDir = $userId . '/files_encryption/share-keys/';
  345. }
  346. if ($view->is_dir($userId . '/files/' . $filePath)) {
  347. $view->unlink($baseDir . $filePath);
  348. } else {
  349. $localKeyPath = $view->getLocalFile($baseDir . $filePath);
  350. $escapedPath = Helper::escapeGlobPattern($localKeyPath);
  351. $matches = glob($escapedPath . '*.shareKey');
  352. foreach ($matches as $ma) {
  353. $result = unlink($ma);
  354. if (!$result) {
  355. \OCP\Util::writeLog('Encryption library',
  356. 'Keyfile or shareKey could not be deleted for file "' . $filePath . '"', \OCP\Util::ERROR);
  357. }
  358. }
  359. }
  360. }
  361. /**
  362. * @brief Delete a single user's shareKey for a single file
  363. */
  364. public static function delShareKey(\OC_FilesystemView $view, $userIds, $filePath) {
  365. $proxyStatus = \OC_FileProxy::$enabled;
  366. \OC_FileProxy::$enabled = false;
  367. //here we need the currently logged in user, while userId can be a different user
  368. $util = new Util($view, \OCP\User::getUser());
  369. list($owner, $filename) = $util->getUidAndFilename($filePath);
  370. if ($util->isSystemWideMountPoint($filename)) {
  371. $shareKeyPath = \OC\Files\Filesystem::normalizePath('/files_encryption/share-keys/' . $filename);
  372. } else {
  373. $shareKeyPath = \OC\Files\Filesystem::normalizePath('/' . $owner . '/files_encryption/share-keys/' . $filename);
  374. }
  375. if ($view->is_dir($shareKeyPath)) {
  376. $localPath = \OC\Files\Filesystem::normalizePath($view->getLocalFolder($shareKeyPath));
  377. self::recursiveDelShareKeys($localPath, $userIds);
  378. } else {
  379. foreach ($userIds as $userId) {
  380. if (!$view->unlink($shareKeyPath . '.' . $userId . '.shareKey')) {
  381. \OCP\Util::writeLog('Encryption library',
  382. 'Could not delete shareKey; does not exist: "' . $shareKeyPath . '.' . $userId
  383. . '.shareKey"', \OCP\Util::ERROR);
  384. }
  385. }
  386. }
  387. \OC_FileProxy::$enabled = $proxyStatus;
  388. }
  389. /**
  390. * @brief recursively delete share keys from given users
  391. *
  392. * @param string $dir directory
  393. * @param array $userIds user ids for which the share keys should be deleted
  394. */
  395. private static function recursiveDelShareKeys($dir, $userIds) {
  396. foreach ($userIds as $userId) {
  397. $extension = '.' . $userId . '.shareKey';
  398. $escapedDir = Helper::escapeGlobPattern($dir);
  399. $escapedExtension = Helper::escapeGlobPattern($extension);
  400. $matches = glob($escapedDir . '/*' . $escapedExtension);
  401. }
  402. /** @var $matches array */
  403. foreach ($matches as $ma) {
  404. if (!unlink($ma)) {
  405. \OCP\Util::writeLog('Encryption library',
  406. 'Could not delete shareKey; does not exist: "' . $ma . '"', \OCP\Util::ERROR);
  407. }
  408. }
  409. $subdirs = $directories = glob($escapedDir . '/*', GLOB_ONLYDIR);
  410. foreach ($subdirs as $subdir) {
  411. self::recursiveDelShareKeys($subdir, $userIds);
  412. }
  413. }
  414. /**
  415. * @brief Make preparations to vars and filesystem for saving a keyfile
  416. */
  417. public static function keySetPreparation(\OC_FilesystemView $view, $path, $basePath, $userId) {
  418. $targetPath = ltrim($path, '/');
  419. $path_parts = pathinfo($targetPath);
  420. // If the file resides within a subdirectory, create it
  421. if (
  422. isset($path_parts['dirname'])
  423. && !$view->file_exists($basePath . '/' . $path_parts['dirname'])
  424. ) {
  425. $sub_dirs = explode(DIRECTORY_SEPARATOR, $basePath . '/' . $path_parts['dirname']);
  426. $dir = '';
  427. foreach ($sub_dirs as $sub_dir) {
  428. $dir .= '/' . $sub_dir;
  429. if (!$view->is_dir($dir)) {
  430. $view->mkdir($dir);
  431. }
  432. }
  433. }
  434. return $targetPath;
  435. }
  436. }