1
0

Crypto.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Andreas Fischer <bantu@owncloud.com>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author lynn-stephenson <lynn.stephenson@protonmail.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  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\Security;
  29. use Exception;
  30. use OCP\IConfig;
  31. use OCP\Security\ICrypto;
  32. use OCP\Security\ISecureRandom;
  33. use phpseclib\Crypt\AES;
  34. use phpseclib\Crypt\Hash;
  35. /**
  36. * Class Crypto provides a high-level encryption layer using AES-CBC. If no key has been provided
  37. * it will use the secret defined in config.php as key. Additionally the message will be HMAC'd.
  38. *
  39. * Usage:
  40. * $encryptWithDefaultPassword = \OC::$server->getCrypto()->encrypt('EncryptedText');
  41. * $encryptWithCustompassword = \OC::$server->getCrypto()->encrypt('EncryptedText', 'password');
  42. *
  43. * @package OC\Security
  44. */
  45. class Crypto implements ICrypto {
  46. /** @var AES $cipher */
  47. private $cipher;
  48. /** @var int */
  49. private $ivLength = 16;
  50. /** @var IConfig */
  51. private $config;
  52. /**
  53. * @param IConfig $config
  54. * @param ISecureRandom $random
  55. */
  56. public function __construct(IConfig $config) {
  57. $this->cipher = new AES();
  58. $this->config = $config;
  59. }
  60. /**
  61. * @param string $message The message to authenticate
  62. * @param string $password Password to use (defaults to `secret` in config.php)
  63. * @return string Calculated HMAC
  64. */
  65. public function calculateHMAC(string $message, string $password = ''): string {
  66. if ($password === '') {
  67. $password = $this->config->getSystemValueString('secret');
  68. }
  69. // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
  70. $password = hash('sha512', $password . 'a');
  71. $hash = new Hash('sha512');
  72. $hash->setKey($password);
  73. return $hash->hash($message);
  74. }
  75. /**
  76. * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  77. *
  78. * @param string $plaintext
  79. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  80. * @return string Authenticated ciphertext
  81. * @throws Exception if it was not possible to gather sufficient entropy
  82. * @throws Exception if encrypting the data failed
  83. */
  84. public function encrypt(string $plaintext, string $password = ''): string {
  85. if ($password === '') {
  86. $password = $this->config->getSystemValueString('secret');
  87. }
  88. $keyMaterial = hash_hkdf('sha512', $password);
  89. $this->cipher->setPassword(substr($keyMaterial, 0, 32));
  90. $iv = \random_bytes($this->ivLength);
  91. $this->cipher->setIV($iv);
  92. /** @var string|false $encrypted */
  93. $encrypted = $this->cipher->encrypt($plaintext);
  94. if ($encrypted === false) {
  95. throw new Exception('Encrypting failed.');
  96. }
  97. $ciphertext = bin2hex($encrypted);
  98. $iv = bin2hex($iv);
  99. $hmac = bin2hex($this->calculateHMAC($ciphertext.$iv, substr($keyMaterial, 32)));
  100. return $ciphertext.'|'.$iv.'|'.$hmac.'|3';
  101. }
  102. /**
  103. * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  104. * @param string $authenticatedCiphertext
  105. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  106. * @return string plaintext
  107. * @throws Exception If the HMAC does not match
  108. * @throws Exception If the decryption failed
  109. */
  110. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  111. $secret = $this->config->getSystemValue('secret');
  112. try {
  113. if ($password === '') {
  114. return $this->decryptWithoutSecret($authenticatedCiphertext, $secret);
  115. }
  116. return $this->decryptWithoutSecret($authenticatedCiphertext, $password);
  117. } catch (Exception $e) {
  118. if ($password === '') {
  119. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  120. return $this->decryptWithoutSecret($authenticatedCiphertext, '');
  121. }
  122. throw $e;
  123. }
  124. }
  125. private function decryptWithoutSecret(string $authenticatedCiphertext, string $password = ''): string {
  126. $hmacKey = $encryptionKey = $password;
  127. $parts = explode('|', $authenticatedCiphertext);
  128. $partCount = \count($parts);
  129. if ($partCount < 3 || $partCount > 4) {
  130. throw new Exception('Authenticated ciphertext could not be decoded.');
  131. }
  132. $ciphertext = $this->hex2bin($parts[0]);
  133. $iv = $parts[1];
  134. $hmac = $this->hex2bin($parts[2]);
  135. if ($partCount === 4) {
  136. $version = $parts[3];
  137. if ($version >= '2') {
  138. $iv = $this->hex2bin($iv);
  139. }
  140. if ($version === '3') {
  141. $keyMaterial = hash_hkdf('sha512', $password);
  142. $encryptionKey = substr($keyMaterial, 0, 32);
  143. $hmacKey = substr($keyMaterial, 32);
  144. }
  145. }
  146. $this->cipher->setPassword($encryptionKey);
  147. $this->cipher->setIV($iv);
  148. if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {
  149. throw new Exception('HMAC does not match.');
  150. }
  151. $result = $this->cipher->decrypt($ciphertext);
  152. if ($result === false) {
  153. throw new Exception('Decryption failed');
  154. }
  155. return $result;
  156. }
  157. private function hex2bin(string $hex): string {
  158. if (!ctype_xdigit($hex)) {
  159. throw new \RuntimeException('String contains non hex chars: ' . $hex);
  160. }
  161. if (strlen($hex) % 2 !== 0) {
  162. throw new \RuntimeException('Hex string is not of even length: ' . $hex);
  163. }
  164. $result = hex2bin($hex);
  165. if ($result === false) {
  166. throw new \RuntimeException('Hex to bin conversion failed: ' . $hex);
  167. }
  168. return $result;
  169. }
  170. }