crypt.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Sam Tuke, Frank Karlitschek, Robin Appelman
  6. * @copyright 2012 Sam Tuke samtuke@owncloud.com,
  7. * Robin Appelman icewind@owncloud.com, Frank Karlitschek
  8. * frank@owncloud.org
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  12. * License as published by the Free Software Foundation; either
  13. * version 3 of the License, or any later version.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public
  21. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\Encryption;
  25. require_once __DIR__ . '/../3rdparty/Crypt_Blowfish/Blowfish.php';
  26. /**
  27. * Class for common cryptography functionality
  28. */
  29. class Crypt {
  30. /**
  31. * @brief return encryption mode client or server side encryption
  32. * @param string $user name (use system wide setting if name=null)
  33. * @return string 'client' or 'server'
  34. */
  35. public static function mode($user = null) {
  36. return 'server';
  37. }
  38. /**
  39. * @brief Create a new encryption keypair
  40. * @return array publicKey, privatekey
  41. */
  42. public static function createKeypair() {
  43. $return = false;
  44. $res = openssl_pkey_new(array('private_key_bits' => 4096));
  45. if ($res === false) {
  46. \OCP\Util::writeLog('Encryption library', 'couldn\'t generate users key-pair for ' . \OCP\User::getUser(), \OCP\Util::ERROR);
  47. while ($msg = openssl_error_string()) {
  48. \OCP\Util::writeLog('Encryption library', 'openssl_pkey_new() fails: ' . $msg, \OCP\Util::ERROR);
  49. }
  50. } elseif (openssl_pkey_export($res, $privateKey)) {
  51. // Get public key
  52. $keyDetails = openssl_pkey_get_details($res);
  53. $publicKey = $keyDetails['key'];
  54. $return = array(
  55. 'publicKey' => $publicKey,
  56. 'privateKey' => $privateKey
  57. );
  58. } else {
  59. \OCP\Util::writeLog('Encryption library', 'couldn\'t export users private key, please check your servers openSSL configuration.' . \OCP\User::getUser(), \OCP\Util::ERROR);
  60. \OCP\Util::writeLog('Encryption library', openssl_error_string(), \OCP\Util::ERROR);
  61. }
  62. return $return;
  63. }
  64. /**
  65. * @brief Add arbitrary padding to encrypted data
  66. * @param string $data data to be padded
  67. * @return string padded data
  68. * @note In order to end up with data exactly 8192 bytes long we must
  69. * add two letters. It is impossible to achieve exactly 8192 length
  70. * blocks with encryption alone, hence padding is added to achieve the
  71. * required length.
  72. */
  73. private static function addPadding($data) {
  74. $padded = $data . 'xx';
  75. return $padded;
  76. }
  77. /**
  78. * @brief Remove arbitrary padding to encrypted data
  79. * @param string $padded padded data to remove padding from
  80. * @return string unpadded data on success, false on error
  81. */
  82. private static function removePadding($padded) {
  83. if (substr($padded, -2) === 'xx') {
  84. $data = substr($padded, 0, -2);
  85. return $data;
  86. } else {
  87. // TODO: log the fact that unpadded data was submitted for removal of padding
  88. return false;
  89. }
  90. }
  91. /**
  92. * @brief Check if a file's contents contains an IV and is symmetrically encrypted
  93. * @param $content
  94. * @return boolean
  95. * @note see also OCA\Encryption\Util->isEncryptedPath()
  96. */
  97. public static function isCatfileContent($content) {
  98. if (!$content) {
  99. return false;
  100. }
  101. $noPadding = self::removePadding($content);
  102. // Fetch encryption metadata from end of file
  103. $meta = substr($noPadding, -22);
  104. // Fetch IV from end of file
  105. $iv = substr($meta, -16);
  106. // Fetch identifier from start of metadata
  107. $identifier = substr($meta, 0, 6);
  108. if ($identifier === '00iv00') {
  109. return true;
  110. } else {
  111. return false;
  112. }
  113. }
  114. /**
  115. * Check if a file is encrypted according to database file cache
  116. * @param string $path
  117. * @return bool
  118. */
  119. public static function isEncryptedMeta($path) {
  120. // TODO: Use DI to get \OC\Files\Filesystem out of here
  121. // Fetch all file metadata from DB
  122. $metadata = \OC\Files\Filesystem::getFileInfo($path);
  123. // Return encryption status
  124. return isset($metadata['encrypted']) && ( bool )$metadata['encrypted'];
  125. }
  126. /**
  127. * @brief Check if a file is encrypted via legacy system
  128. * @param $data
  129. * @param string $relPath The path of the file, relative to user/data;
  130. * e.g. filename or /Docs/filename, NOT admin/files/filename
  131. * @return boolean
  132. */
  133. public static function isLegacyEncryptedContent($isCatFileContent, $relPath) {
  134. // Fetch all file metadata from DB
  135. $metadata = \OC\Files\Filesystem::getFileInfo($relPath, '');
  136. // If a file is flagged with encryption in DB, but isn't a
  137. // valid content + IV combination, it's probably using the
  138. // legacy encryption system
  139. if (isset($metadata['encrypted'])
  140. && $metadata['encrypted'] === true
  141. && $isCatFileContent === false
  142. ) {
  143. return true;
  144. } else {
  145. return false;
  146. }
  147. }
  148. /**
  149. * @brief Symmetrically encrypt a string
  150. * @param $plainContent
  151. * @param $iv
  152. * @param string $passphrase
  153. * @return string encrypted file content
  154. */
  155. private static function encrypt($plainContent, $iv, $passphrase = '') {
  156. if ($encryptedContent = openssl_encrypt($plainContent, 'AES-128-CFB', $passphrase, false, $iv)) {
  157. return $encryptedContent;
  158. } else {
  159. \OCP\Util::writeLog('Encryption library', 'Encryption (symmetric) of content failed', \OCP\Util::ERROR);
  160. \OCP\Util::writeLog('Encryption library', openssl_error_string(), \OCP\Util::ERROR);
  161. return false;
  162. }
  163. }
  164. /**
  165. * @brief Symmetrically decrypt a string
  166. * @param $encryptedContent
  167. * @param $iv
  168. * @param $passphrase
  169. * @throws \Exception
  170. * @return string decrypted file content
  171. */
  172. private static function decrypt($encryptedContent, $iv, $passphrase) {
  173. if ($plainContent = openssl_decrypt($encryptedContent, 'AES-128-CFB', $passphrase, false, $iv)) {
  174. return $plainContent;
  175. } else {
  176. throw new \Exception('Encryption library: Decryption (symmetric) of content failed');
  177. }
  178. }
  179. /**
  180. * @brief Concatenate encrypted data with its IV and padding
  181. * @param string $content content to be concatenated
  182. * @param string $iv IV to be concatenated
  183. * @returns string concatenated content
  184. */
  185. private static function concatIv($content, $iv) {
  186. $combined = $content . '00iv00' . $iv;
  187. return $combined;
  188. }
  189. /**
  190. * @brief Split concatenated data and IV into respective parts
  191. * @param string $catFile concatenated data to be split
  192. * @returns array keys: encrypted, iv
  193. */
  194. private static function splitIv($catFile) {
  195. // Fetch encryption metadata from end of file
  196. $meta = substr($catFile, -22);
  197. // Fetch IV from end of file
  198. $iv = substr($meta, -16);
  199. // Remove IV and IV identifier text to expose encrypted content
  200. $encrypted = substr($catFile, 0, -22);
  201. $split = array(
  202. 'encrypted' => $encrypted,
  203. 'iv' => $iv
  204. );
  205. return $split;
  206. }
  207. /**
  208. * @brief Symmetrically encrypts a string and returns keyfile content
  209. * @param string $plainContent content to be encrypted in keyfile
  210. * @param string $passphrase
  211. * @return bool|string
  212. * @return string encrypted content combined with IV
  213. * @note IV need not be specified, as it will be stored in the returned keyfile
  214. * and remain accessible therein.
  215. */
  216. public static function symmetricEncryptFileContent($plainContent, $passphrase = '') {
  217. if (!$plainContent) {
  218. \OCP\Util::writeLog('Encryption library', 'symmetrically encryption failed, no content given.', \OCP\Util::ERROR);
  219. return false;
  220. }
  221. $iv = self::generateIv();
  222. if ($encryptedContent = self::encrypt($plainContent, $iv, $passphrase)) {
  223. // Combine content to encrypt with IV identifier and actual IV
  224. $catfile = self::concatIv($encryptedContent, $iv);
  225. $padded = self::addPadding($catfile);
  226. return $padded;
  227. } else {
  228. \OCP\Util::writeLog('Encryption library', 'Encryption (symmetric) of keyfile content failed', \OCP\Util::ERROR);
  229. return false;
  230. }
  231. }
  232. /**
  233. * @brief Symmetrically decrypts keyfile content
  234. * @param $keyfileContent
  235. * @param string $passphrase
  236. * @throws \Exception
  237. * @return bool|string
  238. * @internal param string $source
  239. * @internal param string $target
  240. * @internal param string $key the decryption key
  241. * @returns string decrypted content
  242. *
  243. * This function decrypts a file
  244. */
  245. public static function symmetricDecryptFileContent($keyfileContent, $passphrase = '') {
  246. if (!$keyfileContent) {
  247. throw new \Exception('Encryption library: no data provided for decryption');
  248. }
  249. // Remove padding
  250. $noPadding = self::removePadding($keyfileContent);
  251. // Split into enc data and catfile
  252. $catfile = self::splitIv($noPadding);
  253. if ($plainContent = self::decrypt($catfile['encrypted'], $catfile['iv'], $passphrase)) {
  254. return $plainContent;
  255. } else {
  256. return false;
  257. }
  258. }
  259. /**
  260. * @brief Decrypt private key and check if the result is a valid keyfile
  261. * @param string $encryptedKey encrypted keyfile
  262. * @param string $passphrase to decrypt keyfile
  263. * @returns encrypted private key or false
  264. *
  265. * This function decrypts a file
  266. */
  267. public static function decryptPrivateKey($encryptedKey, $passphrase) {
  268. $plainKey = self::symmetricDecryptFileContent($encryptedKey, $passphrase);
  269. // check if this a valid private key
  270. $res = openssl_pkey_get_private($plainKey);
  271. if (is_resource($res)) {
  272. $sslInfo = openssl_pkey_get_details($res);
  273. if (!isset($sslInfo['key'])) {
  274. $plainKey = false;
  275. }
  276. } else {
  277. $plainKey = false;
  278. }
  279. return $plainKey;
  280. }
  281. /**
  282. * @brief Create asymmetrically encrypted keyfile content using a generated key
  283. * @param string $plainContent content to be encrypted
  284. * @param array $publicKeys array keys must be the userId of corresponding user
  285. * @returns array keys: keys (array, key = userId), data
  286. * @note symmetricDecryptFileContent() can decrypt files created using this method
  287. */
  288. public static function multiKeyEncrypt($plainContent, array $publicKeys) {
  289. // openssl_seal returns false without errors if $plainContent
  290. // is empty, so trigger our own error
  291. if (empty($plainContent)) {
  292. throw new \Exception('Cannot mutliKeyEncrypt empty plain content');
  293. }
  294. // Set empty vars to be set by openssl by reference
  295. $sealed = '';
  296. $shareKeys = array();
  297. $mappedShareKeys = array();
  298. if (openssl_seal($plainContent, $sealed, $shareKeys, $publicKeys)) {
  299. $i = 0;
  300. // Ensure each shareKey is labelled with its
  301. // corresponding userId
  302. foreach ($publicKeys as $userId => $publicKey) {
  303. $mappedShareKeys[$userId] = $shareKeys[$i];
  304. $i++;
  305. }
  306. return array(
  307. 'keys' => $mappedShareKeys,
  308. 'data' => $sealed
  309. );
  310. } else {
  311. return false;
  312. }
  313. }
  314. /**
  315. * @brief Asymmetrically encrypt a file using multiple public keys
  316. * @param $encryptedContent
  317. * @param $shareKey
  318. * @param $privateKey
  319. * @return bool
  320. * @internal param string $plainContent content to be encrypted
  321. * @returns string $plainContent decrypted string
  322. * @note symmetricDecryptFileContent() can be used to decrypt files created using this method
  323. *
  324. * This function decrypts a file
  325. */
  326. public static function multiKeyDecrypt($encryptedContent, $shareKey, $privateKey) {
  327. if (!$encryptedContent) {
  328. return false;
  329. }
  330. if (openssl_open($encryptedContent, $plainContent, $shareKey, $privateKey)) {
  331. return $plainContent;
  332. } else {
  333. \OCP\Util::writeLog('Encryption library', 'Decryption (asymmetric) of sealed content with share-key "'.$shareKey.'" failed', \OCP\Util::ERROR);
  334. return false;
  335. }
  336. }
  337. /**
  338. * @brief Generates a pseudo random initialisation vector
  339. * @return String $iv generated IV
  340. */
  341. private static function generateIv() {
  342. if ($random = openssl_random_pseudo_bytes(12, $strong)) {
  343. if (!$strong) {
  344. // If OpenSSL indicates randomness is insecure, log error
  345. \OCP\Util::writeLog('Encryption library', 'Insecure symmetric key was generated using openssl_random_pseudo_bytes()', \OCP\Util::WARN);
  346. }
  347. // We encode the iv purely for string manipulation
  348. // purposes - it gets decoded before use
  349. $iv = base64_encode($random);
  350. return $iv;
  351. } else {
  352. throw new \Exception('Generating IV failed');
  353. }
  354. }
  355. /**
  356. * @brief Generate a pseudo random 1024kb ASCII key, used as file key
  357. * @returns $key Generated key
  358. */
  359. public static function generateKey() {
  360. // Generate key
  361. if ($key = base64_encode(openssl_random_pseudo_bytes(183, $strong))) {
  362. if (!$strong) {
  363. // If OpenSSL indicates randomness is insecure, log error
  364. throw new \Exception('Encryption library, Insecure symmetric key was generated using openssl_random_pseudo_bytes()');
  365. }
  366. return $key;
  367. } else {
  368. return false;
  369. }
  370. }
  371. /**
  372. * @brief Get the blowfish encryption handler for a key
  373. * @param $key string (optional)
  374. * @return \Crypt_Blowfish blowfish object
  375. *
  376. * if the key is left out, the default handler will be used
  377. */
  378. private static function getBlowfish($key = '') {
  379. if ($key) {
  380. return new \Crypt_Blowfish($key);
  381. } else {
  382. return false;
  383. }
  384. }
  385. /**
  386. * @brief decrypts content using legacy blowfish system
  387. * @param string $content the cleartext message you want to decrypt
  388. * @param string $passphrase
  389. * @return string cleartext content
  390. *
  391. * This function decrypts an content
  392. */
  393. public static function legacyDecrypt($content, $passphrase = '') {
  394. $bf = self::getBlowfish($passphrase);
  395. $decrypted = $bf->decrypt($content);
  396. return $decrypted;
  397. }
  398. /**
  399. * @param $data
  400. * @param string $key
  401. * @param int $maxLength
  402. * @return string
  403. */
  404. public static function legacyBlockDecrypt($data, $key = '', $maxLength = 0) {
  405. $result = '';
  406. while (strlen($data)) {
  407. $result .= self::legacyDecrypt(substr($data, 0, 8192), $key);
  408. $data = substr($data, 8192);
  409. }
  410. if ($maxLength > 0) {
  411. return substr($result, 0, $maxLength);
  412. } else {
  413. return rtrim($result, "\0");
  414. }
  415. }
  416. }