Util.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Encryption;
  8. use OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException;
  9. use OC\Encryption\Exceptions\EncryptionHeaderToLargeException;
  10. use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
  11. use OC\Files\Filesystem;
  12. use OC\Files\View;
  13. use OCP\Encryption\IEncryptionModule;
  14. use OCP\Files\Mount\ISystemMountPoint;
  15. use OCP\IConfig;
  16. use OCP\IGroupManager;
  17. use OCP\IUser;
  18. use OCP\IUserManager;
  19. class Util {
  20. public const HEADER_START = 'HBEGIN';
  21. public const HEADER_END = 'HEND';
  22. public const HEADER_PADDING_CHAR = '-';
  23. public const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
  24. /**
  25. * block size will always be 8192 for a PHP stream
  26. * @see https://bugs.php.net/bug.php?id=21641
  27. * @var integer
  28. */
  29. protected $headerSize = 8192;
  30. /**
  31. * block size will always be 8192 for a PHP stream
  32. * @see https://bugs.php.net/bug.php?id=21641
  33. * @var integer
  34. */
  35. protected $blockSize = 8192;
  36. /** @var View */
  37. protected $rootView;
  38. /** @var array */
  39. protected $ocHeaderKeys;
  40. /** @var IConfig */
  41. protected $config;
  42. /** @var array paths excluded from encryption */
  43. protected array $excludedPaths = [];
  44. protected IGroupManager $groupManager;
  45. protected IUserManager $userManager;
  46. /**
  47. *
  48. * @param View $rootView
  49. * @param IConfig $config
  50. */
  51. public function __construct(
  52. View $rootView,
  53. IUserManager $userManager,
  54. IGroupManager $groupManager,
  55. IConfig $config) {
  56. $this->ocHeaderKeys = [
  57. self::HEADER_ENCRYPTION_MODULE_KEY
  58. ];
  59. $this->rootView = $rootView;
  60. $this->userManager = $userManager;
  61. $this->groupManager = $groupManager;
  62. $this->config = $config;
  63. $this->excludedPaths[] = 'files_encryption';
  64. $this->excludedPaths[] = 'appdata_' . $config->getSystemValueString('instanceid');
  65. $this->excludedPaths[] = 'files_external';
  66. }
  67. /**
  68. * read encryption module ID from header
  69. *
  70. * @param array $header
  71. * @return string
  72. * @throws ModuleDoesNotExistsException
  73. */
  74. public function getEncryptionModuleId(?array $header = null) {
  75. $id = '';
  76. $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
  77. if (isset($header[$encryptionModuleKey])) {
  78. $id = $header[$encryptionModuleKey];
  79. } elseif (isset($header['cipher'])) {
  80. if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
  81. // fall back to default encryption if the user migrated from
  82. // ownCloud <= 8.0 with the old encryption
  83. $id = \OCA\Encryption\Crypto\Encryption::ID;
  84. } else {
  85. throw new ModuleDoesNotExistsException('Default encryption module missing');
  86. }
  87. }
  88. return $id;
  89. }
  90. /**
  91. * create header for encrypted file
  92. *
  93. * @param array $headerData
  94. * @param IEncryptionModule $encryptionModule
  95. * @return string
  96. * @throws EncryptionHeaderToLargeException if header has to many arguments
  97. * @throws EncryptionHeaderKeyExistsException if header key is already in use
  98. */
  99. public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
  100. $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
  101. foreach ($headerData as $key => $value) {
  102. if (in_array($key, $this->ocHeaderKeys)) {
  103. throw new EncryptionHeaderKeyExistsException($key);
  104. }
  105. $header .= $key . ':' . $value . ':';
  106. }
  107. $header .= self::HEADER_END;
  108. if (strlen($header) > $this->getHeaderSize()) {
  109. throw new EncryptionHeaderToLargeException();
  110. }
  111. $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
  112. return $paddedHeader;
  113. }
  114. /**
  115. * go recursively through a dir and collect all files and sub files.
  116. *
  117. * @param string $dir relative to the users files folder
  118. * @return array with list of files relative to the users files folder
  119. */
  120. public function getAllFiles($dir) {
  121. $result = [];
  122. $dirList = [$dir];
  123. while ($dirList) {
  124. $dir = array_pop($dirList);
  125. $content = $this->rootView->getDirectoryContent($dir);
  126. foreach ($content as $c) {
  127. if ($c->getType() === 'dir') {
  128. $dirList[] = $c->getPath();
  129. } else {
  130. $result[] = $c->getPath();
  131. }
  132. }
  133. }
  134. return $result;
  135. }
  136. /**
  137. * check if it is a file uploaded by the user stored in data/user/files
  138. * or a metadata file
  139. *
  140. * @param string $path relative to the data/ folder
  141. * @return boolean
  142. */
  143. public function isFile($path) {
  144. $parts = explode('/', Filesystem::normalizePath($path), 4);
  145. if (isset($parts[2]) && $parts[2] === 'files') {
  146. return true;
  147. }
  148. return false;
  149. }
  150. /**
  151. * return size of encryption header
  152. *
  153. * @return integer
  154. */
  155. public function getHeaderSize() {
  156. return $this->headerSize;
  157. }
  158. /**
  159. * return size of block read by a PHP stream
  160. *
  161. * @return integer
  162. */
  163. public function getBlockSize() {
  164. return $this->blockSize;
  165. }
  166. /**
  167. * get the owner and the path for the file relative to the owners files folder
  168. *
  169. * @param string $path
  170. * @return array{0: string, 1: string}
  171. * @throws \BadMethodCallException
  172. */
  173. public function getUidAndFilename($path) {
  174. $parts = explode('/', $path);
  175. $uid = '';
  176. if (count($parts) > 2) {
  177. $uid = $parts[1];
  178. }
  179. if (!$this->userManager->userExists($uid)) {
  180. throw new \BadMethodCallException(
  181. 'path needs to be relative to the system wide data folder and point to a user specific file'
  182. );
  183. }
  184. $ownerPath = implode('/', array_slice($parts, 2));
  185. return [$uid, Filesystem::normalizePath($ownerPath)];
  186. }
  187. /**
  188. * Remove .path extension from a file path
  189. * @param string $path Path that may identify a .part file
  190. * @return string File path without .part extension
  191. * @note this is needed for reusing keys
  192. */
  193. public function stripPartialFileExtension($path) {
  194. $extension = pathinfo($path, PATHINFO_EXTENSION);
  195. if ($extension === 'part') {
  196. $newLength = strlen($path) - 5; // 5 = strlen(".part")
  197. $fPath = substr($path, 0, $newLength);
  198. // if path also contains a transaction id, we remove it too
  199. $extension = pathinfo($fPath, PATHINFO_EXTENSION);
  200. if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
  201. $newLength = strlen($fPath) - strlen($extension) - 1;
  202. $fPath = substr($fPath, 0, $newLength);
  203. }
  204. return $fPath;
  205. } else {
  206. return $path;
  207. }
  208. }
  209. public function getUserWithAccessToMountPoint($users, $groups) {
  210. $result = [];
  211. if ($users === [] && $groups === []) {
  212. $users = $this->userManager->search('', null, null);
  213. $result = array_map(function (IUser $user) {
  214. return $user->getUID();
  215. }, $users);
  216. } else {
  217. $result = array_merge($result, $users);
  218. $groupManager = $this->groupManager;
  219. foreach ($groups as $group) {
  220. $groupObject = $groupManager->get($group);
  221. if ($groupObject) {
  222. $foundUsers = $groupObject->searchUsers('', -1, 0);
  223. $userIds = [];
  224. foreach ($foundUsers as $user) {
  225. $userIds[] = $user->getUID();
  226. }
  227. $result = array_merge($result, $userIds);
  228. }
  229. }
  230. }
  231. return $result;
  232. }
  233. /**
  234. * check if the file is stored on a system wide mount point
  235. * @param string $path relative to /data/user with leading '/'
  236. * @param string $uid
  237. * @return boolean
  238. */
  239. public function isSystemWideMountPoint(string $path, string $uid) {
  240. $mount = Filesystem::getMountManager()->find('/' . $uid . $path);
  241. return $mount instanceof ISystemMountPoint;
  242. }
  243. /**
  244. * check if it is a path which is excluded by ownCloud from encryption
  245. *
  246. * @param string $path
  247. * @return boolean
  248. */
  249. public function isExcluded($path) {
  250. $normalizedPath = Filesystem::normalizePath($path);
  251. $root = explode('/', $normalizedPath, 4);
  252. if (count($root) > 1) {
  253. // detect alternative key storage root
  254. $rootDir = $this->getKeyStorageRoot();
  255. if ($rootDir !== '' &&
  256. str_starts_with(Filesystem::normalizePath($path), Filesystem::normalizePath($rootDir))
  257. ) {
  258. return true;
  259. }
  260. //detect system wide folders
  261. if (in_array($root[1], $this->excludedPaths)) {
  262. return true;
  263. }
  264. // detect user specific folders
  265. if ($this->userManager->userExists($root[1])
  266. && in_array($root[2], $this->excludedPaths)) {
  267. return true;
  268. }
  269. }
  270. return false;
  271. }
  272. /**
  273. * Check if recovery key is enabled for user
  274. */
  275. public function recoveryEnabled(string $uid): bool {
  276. $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
  277. return $enabled === '1';
  278. }
  279. /**
  280. * Set new key storage root
  281. *
  282. * @param string $root new key store root relative to the data folder
  283. */
  284. public function setKeyStorageRoot(string $root): void {
  285. $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
  286. }
  287. /**
  288. * Get key storage root
  289. *
  290. * @return string key storage root
  291. */
  292. public function getKeyStorageRoot(): string {
  293. return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
  294. }
  295. /**
  296. * parse raw header to array
  297. *
  298. * @param string $rawHeader
  299. * @return array
  300. */
  301. public function parseRawHeader(string $rawHeader) {
  302. $result = [];
  303. if (str_starts_with($rawHeader, Util::HEADER_START)) {
  304. $header = $rawHeader;
  305. $endAt = strpos($header, Util::HEADER_END);
  306. if ($endAt !== false) {
  307. $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
  308. // +1 to not start with an ':' which would result in empty element at the beginning
  309. $exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
  310. $element = array_shift($exploded);
  311. while ($element !== Util::HEADER_END && $element !== null) {
  312. $result[$element] = array_shift($exploded);
  313. $element = array_shift($exploded);
  314. }
  315. }
  316. }
  317. return $result;
  318. }
  319. /**
  320. * get path to key folder for a given file
  321. *
  322. * @param string $encryptionModuleId
  323. * @param string $path path to the file, relative to data/
  324. * @return string
  325. */
  326. public function getFileKeyDir(string $encryptionModuleId, string $path): string {
  327. [$owner, $filename] = $this->getUidAndFilename($path);
  328. $root = $this->getKeyStorageRoot();
  329. // in case of system-wide mount points the keys are stored directly in the data directory
  330. if ($this->isSystemWideMountPoint($filename, $owner)) {
  331. $keyPath = $root . '/' . '/files_encryption/keys' . $filename . '/';
  332. } else {
  333. $keyPath = $root . '/' . $owner . '/files_encryption/keys' . $filename . '/';
  334. }
  335. return Filesystem::normalizePath($keyPath . $encryptionModuleId . '/', false);
  336. }
  337. }