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.

Util.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Björn Schießle <bjoern@schiessle.org>
  6. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Thomas Müller <thomas.mueller@tmit.eu>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OC\Encryption;
  26. use OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException;
  27. use OC\Encryption\Exceptions\EncryptionHeaderToLargeException;
  28. use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
  29. use OC\Files\Filesystem;
  30. use OC\Files\View;
  31. use OCP\Encryption\IEncryptionModule;
  32. use OCP\Files\Storage;
  33. use OCP\IConfig;
  34. class Util {
  35. const HEADER_START = 'HBEGIN';
  36. const HEADER_END = 'HEND';
  37. const HEADER_PADDING_CHAR = '-';
  38. const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
  39. /**
  40. * block size will always be 8192 for a PHP stream
  41. * @see https://bugs.php.net/bug.php?id=21641
  42. * @var integer
  43. */
  44. protected $headerSize = 8192;
  45. /**
  46. * block size will always be 8192 for a PHP stream
  47. * @see https://bugs.php.net/bug.php?id=21641
  48. * @var integer
  49. */
  50. protected $blockSize = 8192;
  51. /** @var View */
  52. protected $rootView;
  53. /** @var array */
  54. protected $ocHeaderKeys;
  55. /** @var \OC\User\Manager */
  56. protected $userManager;
  57. /** @var IConfig */
  58. protected $config;
  59. /** @var array paths excluded from encryption */
  60. protected $excludedPaths;
  61. /** @var \OC\Group\Manager $manager */
  62. protected $groupManager;
  63. /**
  64. *
  65. * @param View $rootView
  66. * @param \OC\User\Manager $userManager
  67. * @param \OC\Group\Manager $groupManager
  68. * @param IConfig $config
  69. */
  70. public function __construct(
  71. View $rootView,
  72. \OC\User\Manager $userManager,
  73. \OC\Group\Manager $groupManager,
  74. IConfig $config) {
  75. $this->ocHeaderKeys = [
  76. self::HEADER_ENCRYPTION_MODULE_KEY
  77. ];
  78. $this->rootView = $rootView;
  79. $this->userManager = $userManager;
  80. $this->groupManager = $groupManager;
  81. $this->config = $config;
  82. $this->excludedPaths[] = 'files_encryption';
  83. $this->excludedPaths[] = 'appdata_' . $config->getSystemValue('instanceid', null);
  84. }
  85. /**
  86. * read encryption module ID from header
  87. *
  88. * @param array $header
  89. * @return string
  90. * @throws ModuleDoesNotExistsException
  91. */
  92. public function getEncryptionModuleId(array $header = null) {
  93. $id = '';
  94. $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
  95. if (isset($header[$encryptionModuleKey])) {
  96. $id = $header[$encryptionModuleKey];
  97. } elseif (isset($header['cipher'])) {
  98. if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
  99. // fall back to default encryption if the user migrated from
  100. // ownCloud <= 8.0 with the old encryption
  101. $id = \OCA\Encryption\Crypto\Encryption::ID;
  102. } else {
  103. throw new ModuleDoesNotExistsException('Default encryption module missing');
  104. }
  105. }
  106. return $id;
  107. }
  108. /**
  109. * create header for encrypted file
  110. *
  111. * @param array $headerData
  112. * @param IEncryptionModule $encryptionModule
  113. * @return string
  114. * @throws EncryptionHeaderToLargeException if header has to many arguments
  115. * @throws EncryptionHeaderKeyExistsException if header key is already in use
  116. */
  117. public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
  118. $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
  119. foreach ($headerData as $key => $value) {
  120. if (in_array($key, $this->ocHeaderKeys)) {
  121. throw new EncryptionHeaderKeyExistsException($key);
  122. }
  123. $header .= $key . ':' . $value . ':';
  124. }
  125. $header .= self::HEADER_END;
  126. if (strlen($header) > $this->getHeaderSize()) {
  127. throw new EncryptionHeaderToLargeException();
  128. }
  129. $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
  130. return $paddedHeader;
  131. }
  132. /**
  133. * go recursively through a dir and collect all files and sub files.
  134. *
  135. * @param string $dir relative to the users files folder
  136. * @return array with list of files relative to the users files folder
  137. */
  138. public function getAllFiles($dir) {
  139. $result = array();
  140. $dirList = array($dir);
  141. while ($dirList) {
  142. $dir = array_pop($dirList);
  143. $content = $this->rootView->getDirectoryContent($dir);
  144. foreach ($content as $c) {
  145. if ($c->getType() === 'dir') {
  146. $dirList[] = $c->getPath();
  147. } else {
  148. $result[] = $c->getPath();
  149. }
  150. }
  151. }
  152. return $result;
  153. }
  154. /**
  155. * check if it is a file uploaded by the user stored in data/user/files
  156. * or a metadata file
  157. *
  158. * @param string $path relative to the data/ folder
  159. * @return boolean
  160. */
  161. public function isFile($path) {
  162. $parts = explode('/', Filesystem::normalizePath($path), 4);
  163. if (isset($parts[2]) && $parts[2] === 'files') {
  164. return true;
  165. }
  166. return false;
  167. }
  168. /**
  169. * return size of encryption header
  170. *
  171. * @return integer
  172. */
  173. public function getHeaderSize() {
  174. return $this->headerSize;
  175. }
  176. /**
  177. * return size of block read by a PHP stream
  178. *
  179. * @return integer
  180. */
  181. public function getBlockSize() {
  182. return $this->blockSize;
  183. }
  184. /**
  185. * get the owner and the path for the file relative to the owners files folder
  186. *
  187. * @param string $path
  188. * @return array
  189. * @throws \BadMethodCallException
  190. */
  191. public function getUidAndFilename($path) {
  192. $parts = explode('/', $path);
  193. $uid = '';
  194. if (count($parts) > 2) {
  195. $uid = $parts[1];
  196. }
  197. if (!$this->userManager->userExists($uid)) {
  198. throw new \BadMethodCallException(
  199. 'path needs to be relative to the system wide data folder and point to a user specific file'
  200. );
  201. }
  202. $ownerPath = implode('/', array_slice($parts, 2));
  203. return array($uid, Filesystem::normalizePath($ownerPath));
  204. }
  205. /**
  206. * Remove .path extension from a file path
  207. * @param string $path Path that may identify a .part file
  208. * @return string File path without .part extension
  209. * @note this is needed for reusing keys
  210. */
  211. public function stripPartialFileExtension($path) {
  212. $extension = pathinfo($path, PATHINFO_EXTENSION);
  213. if ( $extension === 'part') {
  214. $newLength = strlen($path) - 5; // 5 = strlen(".part")
  215. $fPath = substr($path, 0, $newLength);
  216. // if path also contains a transaction id, we remove it too
  217. $extension = pathinfo($fPath, PATHINFO_EXTENSION);
  218. if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
  219. $newLength = strlen($fPath) - strlen($extension) -1;
  220. $fPath = substr($fPath, 0, $newLength);
  221. }
  222. return $fPath;
  223. } else {
  224. return $path;
  225. }
  226. }
  227. public function getUserWithAccessToMountPoint($users, $groups) {
  228. $result = array();
  229. if (in_array('all', $users)) {
  230. $result = \OCP\User::getUsers();
  231. } else {
  232. $result = array_merge($result, $users);
  233. foreach ($groups as $group) {
  234. $result = array_merge($result, \OC_Group::usersInGroup($group));
  235. }
  236. }
  237. return $result;
  238. }
  239. /**
  240. * check if the file is stored on a system wide mount point
  241. * @param string $path relative to /data/user with leading '/'
  242. * @param string $uid
  243. * @return boolean
  244. */
  245. public function isSystemWideMountPoint($path, $uid) {
  246. if (\OCP\App::isEnabled("files_external")) {
  247. $mounts = \OC_Mount_Config::getSystemMountPoints();
  248. foreach ($mounts as $mount) {
  249. if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
  250. if ($this->isMountPointApplicableToUser($mount, $uid)) {
  251. return true;
  252. }
  253. }
  254. }
  255. }
  256. return false;
  257. }
  258. /**
  259. * check if mount point is applicable to user
  260. *
  261. * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
  262. * @param string $uid
  263. * @return boolean
  264. */
  265. private function isMountPointApplicableToUser($mount, $uid) {
  266. $acceptedUids = array('all', $uid);
  267. // check if mount point is applicable for the user
  268. $intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
  269. if (!empty($intersection)) {
  270. return true;
  271. }
  272. // check if mount point is applicable for group where the user is a member
  273. foreach ($mount['applicable']['groups'] as $gid) {
  274. if ($this->groupManager->isInGroup($uid, $gid)) {
  275. return true;
  276. }
  277. }
  278. return false;
  279. }
  280. /**
  281. * check if it is a path which is excluded by ownCloud from encryption
  282. *
  283. * @param string $path
  284. * @return boolean
  285. */
  286. public function isExcluded($path) {
  287. $normalizedPath = Filesystem::normalizePath($path);
  288. $root = explode('/', $normalizedPath, 4);
  289. if (count($root) > 1) {
  290. // detect alternative key storage root
  291. $rootDir = $this->getKeyStorageRoot();
  292. if ($rootDir !== '' &&
  293. 0 === strpos(
  294. Filesystem::normalizePath($path),
  295. Filesystem::normalizePath($rootDir)
  296. )
  297. ) {
  298. return true;
  299. }
  300. //detect system wide folders
  301. if (in_array($root[1], $this->excludedPaths)) {
  302. return true;
  303. }
  304. // detect user specific folders
  305. if ($this->userManager->userExists($root[1])
  306. && in_array($root[2], $this->excludedPaths)) {
  307. return true;
  308. }
  309. }
  310. return false;
  311. }
  312. /**
  313. * check if recovery key is enabled for user
  314. *
  315. * @param string $uid
  316. * @return boolean
  317. */
  318. public function recoveryEnabled($uid) {
  319. $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
  320. return ($enabled === '1') ? true : false;
  321. }
  322. /**
  323. * set new key storage root
  324. *
  325. * @param string $root new key store root relative to the data folder
  326. */
  327. public function setKeyStorageRoot($root) {
  328. $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
  329. }
  330. /**
  331. * get key storage root
  332. *
  333. * @return string key storage root
  334. */
  335. public function getKeyStorageRoot() {
  336. return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
  337. }
  338. }