Util.php 11 KB

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