Util.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. $groupManager = \OC::$server->getGroupManager();
  234. foreach ($groups as $group) {
  235. $groupObject = $groupManager->get($group);
  236. if ($groupObject) {
  237. $foundUsers = $groupObject->searchUsers('', -1, 0);
  238. $userIds = [];
  239. foreach ($foundUsers as $user) {
  240. $userIds[] = $user->getUID();
  241. }
  242. $result = array_merge($result, $userIds);
  243. }
  244. }
  245. }
  246. return $result;
  247. }
  248. /**
  249. * check if the file is stored on a system wide mount point
  250. * @param string $path relative to /data/user with leading '/'
  251. * @param string $uid
  252. * @return boolean
  253. */
  254. public function isSystemWideMountPoint($path, $uid) {
  255. if (\OCP\App::isEnabled("files_external")) {
  256. $mounts = \OC_Mount_Config::getSystemMountPoints();
  257. foreach ($mounts as $mount) {
  258. if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
  259. if ($this->isMountPointApplicableToUser($mount, $uid)) {
  260. return true;
  261. }
  262. }
  263. }
  264. }
  265. return false;
  266. }
  267. /**
  268. * check if mount point is applicable to user
  269. *
  270. * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
  271. * @param string $uid
  272. * @return boolean
  273. */
  274. private function isMountPointApplicableToUser($mount, $uid) {
  275. $acceptedUids = array('all', $uid);
  276. // check if mount point is applicable for the user
  277. $intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
  278. if (!empty($intersection)) {
  279. return true;
  280. }
  281. // check if mount point is applicable for group where the user is a member
  282. foreach ($mount['applicable']['groups'] as $gid) {
  283. if ($this->groupManager->isInGroup($uid, $gid)) {
  284. return true;
  285. }
  286. }
  287. return false;
  288. }
  289. /**
  290. * check if it is a path which is excluded by ownCloud from encryption
  291. *
  292. * @param string $path
  293. * @return boolean
  294. */
  295. public function isExcluded($path) {
  296. $normalizedPath = Filesystem::normalizePath($path);
  297. $root = explode('/', $normalizedPath, 4);
  298. if (count($root) > 1) {
  299. // detect alternative key storage root
  300. $rootDir = $this->getKeyStorageRoot();
  301. if ($rootDir !== '' &&
  302. 0 === strpos(
  303. Filesystem::normalizePath($path),
  304. Filesystem::normalizePath($rootDir)
  305. )
  306. ) {
  307. return true;
  308. }
  309. //detect system wide folders
  310. if (in_array($root[1], $this->excludedPaths)) {
  311. return true;
  312. }
  313. // detect user specific folders
  314. if ($this->userManager->userExists($root[1])
  315. && in_array($root[2], $this->excludedPaths)) {
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. /**
  322. * check if recovery key is enabled for user
  323. *
  324. * @param string $uid
  325. * @return boolean
  326. */
  327. public function recoveryEnabled($uid) {
  328. $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
  329. return ($enabled === '1') ? true : false;
  330. }
  331. /**
  332. * set new key storage root
  333. *
  334. * @param string $root new key store root relative to the data folder
  335. */
  336. public function setKeyStorageRoot($root) {
  337. $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
  338. }
  339. /**
  340. * get key storage root
  341. *
  342. * @return string key storage root
  343. */
  344. public function getKeyStorageRoot() {
  345. return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
  346. }
  347. }