Util.php 10 KB

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