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.

proxy.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * @author Björn Schießle <schiessle@owncloud.com>
  4. * @author Florin Peter <github@florin-peter.de>
  5. * @author Joas Schilling <nickvergessen@owncloud.com>
  6. * @author Morris Jobke <hey@morrisjobke.de>
  7. * @author Robin Appelman <icewind@owncloud.com>
  8. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  9. * @author Sam Tuke <mail@samtuke.com>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. * @author Vincent Petry <pvince81@owncloud.com>
  12. *
  13. * @copyright Copyright (c) 2015, ownCloud, Inc.
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. /**
  30. * Encryption proxy which handles filesystem operations before and after
  31. * execution and encrypts, and handles keyfiles accordingly. Used for
  32. * webui.
  33. */
  34. namespace OCA\Files_Encryption;
  35. /**
  36. * Class Proxy
  37. * @package OCA\Files_Encryption
  38. */
  39. class Proxy extends \OC_FileProxy {
  40. private static $unencryptedSizes = array(); // remember unencrypted size
  41. private static $fopenMode = array(); // remember the fopen mode
  42. private static $enableEncryption = false; // Enable encryption for the given path
  43. /**
  44. * check if path is excluded from encryption
  45. *
  46. * @param string $path relative to data/
  47. * @return boolean
  48. */
  49. protected function isExcludedPath($path) {
  50. $view = new \OC\Files\View();
  51. $normalizedPath = \OC\Files\Filesystem::normalizePath($path);
  52. $parts = explode('/', $normalizedPath);
  53. // we only encrypt/decrypt files in the files and files_versions folder
  54. if (sizeof($parts) < 3) {
  55. /**
  56. * Less then 3 parts means, we can't match:
  57. * - /{$uid}/files/* nor
  58. * - /{$uid}/files_versions/*
  59. * So this is not a path we are looking for.
  60. */
  61. return true;
  62. }
  63. if(
  64. !($parts[2] === 'files' && \OCP\User::userExists($parts[1])) &&
  65. !($parts[2] === 'files_versions' && \OCP\User::userExists($parts[1]))) {
  66. return true;
  67. }
  68. if (!$view->file_exists($normalizedPath)) {
  69. $normalizedPath = dirname($normalizedPath);
  70. }
  71. // we don't encrypt server-to-server shares
  72. list($storage, ) = \OC\Files\Filesystem::resolvePath($normalizedPath);
  73. /**
  74. * @var \OCP\Files\Storage $storage
  75. */
  76. if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  77. return true;
  78. }
  79. return false;
  80. }
  81. /**
  82. * Check if a file requires encryption
  83. * @param string $path
  84. * @param string $mode type of access
  85. * @return bool
  86. *
  87. * Tests if server side encryption is enabled, and if we should call the
  88. * crypt stream wrapper for the given file
  89. */
  90. private function shouldEncrypt($path, $mode = 'w') {
  91. // don't call the crypt stream wrapper, if...
  92. if (
  93. Crypt::mode() !== 'server' // we are not in server-side-encryption mode
  94. || $this->isExcludedPath($path) // if path is excluded from encryption
  95. || substr($path, 0, 8) === 'crypt://' // we are already in crypt mode
  96. ) {
  97. return false;
  98. }
  99. $userId = Helper::getUser($path);
  100. $view = new \OC\Files\View('');
  101. $util = new Util($view, $userId);
  102. // for write operation we always encrypt the files, for read operations
  103. // we check if the existing file is encrypted or not decide if it needs to
  104. // decrypt it.
  105. if (($mode !== 'r' && $mode !== 'rb') || $util->isEncryptedPath($path)) {
  106. return true;
  107. }
  108. return false;
  109. }
  110. /**
  111. * @param string $path
  112. * @param string $data
  113. * @return bool
  114. */
  115. public function preFile_put_contents($path, &$data) {
  116. if ($this->shouldEncrypt($path)) {
  117. if (!is_resource($data)) {
  118. // get root view
  119. $view = new \OC\Files\View('/');
  120. // get relative path
  121. $relativePath = Helper::stripUserFilesPath($path);
  122. if (!isset($relativePath)) {
  123. return true;
  124. }
  125. // create random cache folder
  126. $cacheFolder = rand();
  127. $path_slices = explode('/', \OC\Files\Filesystem::normalizePath($path));
  128. $path_slices[2] = "cache/".$cacheFolder;
  129. $tmpPath = implode('/', $path_slices);
  130. $handle = fopen('crypt://' . $tmpPath, 'w');
  131. if (is_resource($handle)) {
  132. // write data to stream
  133. fwrite($handle, $data);
  134. // close stream
  135. fclose($handle);
  136. // disable encryption proxy to prevent recursive calls
  137. $proxyStatus = \OC_FileProxy::$enabled;
  138. \OC_FileProxy::$enabled = false;
  139. // get encrypted content
  140. $data = $view->file_get_contents($tmpPath);
  141. // store new unenecrypted size so that it can be updated
  142. // in the post proxy
  143. $tmpFileInfo = $view->getFileInfo($tmpPath);
  144. if ( isset($tmpFileInfo['unencrypted_size']) ) {
  145. self::$unencryptedSizes[\OC\Files\Filesystem::normalizePath($path)] = $tmpFileInfo['unencrypted_size'];
  146. }
  147. // remove our temp file
  148. $view->deleteAll('/' . \OCP\User::getUser() . '/cache/' . $cacheFolder);
  149. // re-enable proxy - our work is done
  150. \OC_FileProxy::$enabled = $proxyStatus;
  151. } else {
  152. return false;
  153. }
  154. }
  155. }
  156. return true;
  157. }
  158. /**
  159. * update file cache with the new unencrypted size after file was written
  160. * @param string $path
  161. * @param mixed $result
  162. * @return mixed
  163. */
  164. public function postFile_put_contents($path, $result) {
  165. $normalizedPath = \OC\Files\Filesystem::normalizePath($path);
  166. if ( isset(self::$unencryptedSizes[$normalizedPath]) ) {
  167. $view = new \OC\Files\View('/');
  168. $view->putFileInfo($normalizedPath,
  169. array('encrypted' => true, 'unencrypted_size' => self::$unencryptedSizes[$normalizedPath]));
  170. unset(self::$unencryptedSizes[$normalizedPath]);
  171. }
  172. return $result;
  173. }
  174. /**
  175. * @param string $path Path of file from which has been read
  176. * @param string $data Data that has been read from file
  177. */
  178. public function postFile_get_contents($path, $data) {
  179. $plainData = null;
  180. // If data is a catfile
  181. if (
  182. Crypt::mode() === 'server'
  183. && $this->shouldEncrypt($path)
  184. && Crypt::isCatfileContent($data)
  185. ) {
  186. $handle = fopen('crypt://' . $path, 'r');
  187. if (is_resource($handle)) {
  188. while (($plainDataChunk = fgets($handle, 8192)) !== false) {
  189. $plainData .= $plainDataChunk;
  190. }
  191. }
  192. }
  193. if (!isset($plainData)) {
  194. $plainData = $data;
  195. }
  196. return $plainData;
  197. }
  198. /**
  199. * remember initial fopen mode because sometimes it gets changed during the request
  200. * @param string $path path
  201. * @param string $mode type of access
  202. */
  203. public function preFopen($path, $mode) {
  204. self::$fopenMode[$path] = $mode;
  205. self::$enableEncryption = $this->shouldEncrypt($path, $mode);
  206. }
  207. /**
  208. * @param string $path
  209. * @param resource $result
  210. * @return resource
  211. */
  212. public function postFopen($path, $result) {
  213. $path = \OC\Files\Filesystem::normalizePath($path);
  214. if (!$result || self::$enableEncryption === false) {
  215. return $result;
  216. }
  217. // if we remember the mode from the pre proxy we re-use it
  218. // otherwise we fall back to stream_get_meta_data()
  219. if (isset(self::$fopenMode[$path])) {
  220. $mode = self::$fopenMode[$path];
  221. unset(self::$fopenMode[$path]);
  222. } else {
  223. $meta = stream_get_meta_data($result);
  224. $mode = $meta['mode'];
  225. }
  226. // Close the original encrypted file
  227. fclose($result);
  228. // Open the file using the crypto stream wrapper
  229. // protocol and let it do the decryption work instead
  230. $result = fopen('crypt://' . $path, $mode);
  231. return $result;
  232. }
  233. /**
  234. * @param string $path
  235. * @param array $data
  236. * @return array
  237. */
  238. public function postGetFileInfo($path, $data) {
  239. // if path is a folder do nothing
  240. if (\OCP\App::isEnabled('files_encryption') && $data !== false && array_key_exists('size', $data)) {
  241. // Disable encryption proxy to prevent recursive calls
  242. $proxyStatus = \OC_FileProxy::$enabled;
  243. \OC_FileProxy::$enabled = false;
  244. // get file size
  245. $data['size'] = self::postFileSize($path, $data['size'], $data);
  246. // Re-enable the proxy
  247. \OC_FileProxy::$enabled = $proxyStatus;
  248. }
  249. return $data;
  250. }
  251. /**
  252. * @param string $path
  253. * @param int $size
  254. * @return int|bool
  255. */
  256. public function postFileSize($path, $size, $fileInfo = null) {
  257. $view = new \OC\Files\View('/');
  258. $userId = Helper::getUser($path);
  259. $util = new Util($view, $userId);
  260. // if encryption is no longer enabled or if the files aren't migrated yet
  261. // we return the default file size
  262. if(!\OCP\App::isEnabled('files_encryption') ||
  263. $util->getMigrationStatus() !== Util::MIGRATION_COMPLETED) {
  264. return $size;
  265. }
  266. // if path is a folder do nothing
  267. if ($view->is_dir($path)) {
  268. $proxyState = \OC_FileProxy::$enabled;
  269. \OC_FileProxy::$enabled = false;
  270. $fileInfo = $view->getFileInfo($path);
  271. \OC_FileProxy::$enabled = $proxyState;
  272. if (isset($fileInfo['unencrypted_size']) && $fileInfo['unencrypted_size'] > 0) {
  273. return $fileInfo['unencrypted_size'];
  274. }
  275. return $size;
  276. }
  277. // get relative path
  278. $relativePath = Helper::stripUserFilesPath($path);
  279. // if path is empty we cannot resolve anything
  280. if (empty($relativePath)) {
  281. return $size;
  282. }
  283. // get file info from database/cache
  284. if (empty($fileInfo)) {
  285. $proxyState = \OC_FileProxy::$enabled;
  286. \OC_FileProxy::$enabled = false;
  287. $fileInfo = $view->getFileInfo($path);
  288. \OC_FileProxy::$enabled = $proxyState;
  289. }
  290. // if file is encrypted return real file size
  291. if (isset($fileInfo['encrypted']) && $fileInfo['encrypted'] === true) {
  292. // try to fix unencrypted file size if it doesn't look plausible
  293. if ((int)$fileInfo['size'] > 0 && (int)$fileInfo['unencrypted_size'] === 0 ) {
  294. $fixSize = $util->getFileSize($path);
  295. $fileInfo['unencrypted_size'] = $fixSize;
  296. // put file info if not .part file
  297. if (!Helper::isPartialFilePath($relativePath)) {
  298. $view->putFileInfo($path, array('unencrypted_size' => $fixSize));
  299. }
  300. }
  301. $size = $fileInfo['unencrypted_size'];
  302. } else {
  303. $fileInfoUpdates = array();
  304. $fixSize = $util->getFileSize($path);
  305. if ($fixSize > 0) {
  306. $size = $fixSize;
  307. $fileInfoUpdates['encrypted'] = true;
  308. $fileInfoUpdates['unencrypted_size'] = $size;
  309. // put file info if not .part file
  310. if (!Helper::isPartialFilePath($relativePath)) {
  311. $view->putFileInfo($path, $fileInfoUpdates);
  312. }
  313. }
  314. }
  315. return $size;
  316. }
  317. }