Crypto.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\Security;
  9. use Exception;
  10. use OCP\IConfig;
  11. use OCP\Security\ICrypto;
  12. use phpseclib\Crypt\AES;
  13. use phpseclib\Crypt\Hash;
  14. /**
  15. * Class Crypto provides a high-level encryption layer using AES-CBC. If no key has been provided
  16. * it will use the secret defined in config.php as key. Additionally the message will be HMAC'd.
  17. *
  18. * Usage:
  19. * $encryptWithDefaultPassword = \OC::$server->getCrypto()->encrypt('EncryptedText');
  20. * $encryptWithCustompassword = \OC::$server->getCrypto()->encrypt('EncryptedText', 'password');
  21. *
  22. * @package OC\Security
  23. */
  24. class Crypto implements ICrypto {
  25. private AES $cipher;
  26. private int $ivLength = 16;
  27. public function __construct(
  28. private IConfig $config,
  29. ) {
  30. $this->cipher = new AES();
  31. }
  32. /**
  33. * @param string $message The message to authenticate
  34. * @param string $password Password to use (defaults to `secret` in config.php)
  35. * @return string Calculated HMAC
  36. */
  37. public function calculateHMAC(string $message, string $password = ''): string {
  38. if ($password === '') {
  39. $password = $this->config->getSystemValueString('secret');
  40. }
  41. // Append an "a" behind the password and hash it to prevent reusing the same password as for encryption
  42. $password = hash('sha512', $password . 'a');
  43. $hash = new Hash('sha512');
  44. $hash->setKey($password);
  45. return $hash->hash($message);
  46. }
  47. /**
  48. * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  49. *
  50. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  51. * @return string Authenticated ciphertext
  52. * @throws Exception if it was not possible to gather sufficient entropy
  53. * @throws Exception if encrypting the data failed
  54. */
  55. public function encrypt(string $plaintext, string $password = ''): string {
  56. if ($password === '') {
  57. $password = $this->config->getSystemValueString('secret');
  58. }
  59. $keyMaterial = hash_hkdf('sha512', $password);
  60. $this->cipher->setPassword(substr($keyMaterial, 0, 32));
  61. $iv = \random_bytes($this->ivLength);
  62. $this->cipher->setIV($iv);
  63. /** @var string|false $encrypted */
  64. $encrypted = $this->cipher->encrypt($plaintext);
  65. if ($encrypted === false) {
  66. throw new Exception('Encrypting failed.');
  67. }
  68. $ciphertext = bin2hex($encrypted);
  69. $iv = bin2hex($iv);
  70. $hmac = bin2hex($this->calculateHMAC($ciphertext . $iv, substr($keyMaterial, 32)));
  71. return $ciphertext . '|' . $iv . '|' . $hmac . '|3';
  72. }
  73. /**
  74. * Decrypts a value and verifies the HMAC (Encrypt-Then-Mac)
  75. * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  76. * @throws Exception If the HMAC does not match
  77. * @throws Exception If the decryption failed
  78. */
  79. public function decrypt(string $authenticatedCiphertext, string $password = ''): string {
  80. $secret = $this->config->getSystemValue('secret');
  81. try {
  82. if ($password === '') {
  83. return $this->decryptWithoutSecret($authenticatedCiphertext, $secret);
  84. }
  85. return $this->decryptWithoutSecret($authenticatedCiphertext, $password);
  86. } catch (Exception $e) {
  87. if ($password === '') {
  88. // Retry with empty secret as a fallback for instances where the secret might not have been set by accident
  89. return $this->decryptWithoutSecret($authenticatedCiphertext, '');
  90. }
  91. throw $e;
  92. }
  93. }
  94. private function decryptWithoutSecret(string $authenticatedCiphertext, string $password = ''): string {
  95. $hmacKey = $encryptionKey = $password;
  96. $parts = explode('|', $authenticatedCiphertext);
  97. $partCount = \count($parts);
  98. if ($partCount < 3 || $partCount > 4) {
  99. throw new Exception('Authenticated ciphertext could not be decoded.');
  100. }
  101. /*
  102. * Rearrange arguments for legacy ownCloud migrations
  103. *
  104. * The original scheme consistent of three parts. Nextcloud added a
  105. * fourth at the end as "2" or later "3", ownCloud added "v2" at the
  106. * beginning.
  107. */
  108. $originalParts = $parts;
  109. $isOwnCloudV2Migration = $partCount === 4 && $originalParts[0] === 'v2';
  110. if ($isOwnCloudV2Migration) {
  111. $parts = [
  112. $parts[1],
  113. $parts[2],
  114. $parts[3],
  115. '2'
  116. ];
  117. }
  118. // Convert hex-encoded values to binary
  119. $ciphertext = $this->hex2bin($parts[0]);
  120. $iv = $parts[1];
  121. $hmac = $this->hex2bin($parts[2]);
  122. if ($partCount === 4) {
  123. $version = $parts[3];
  124. if ($version >= '2') {
  125. $iv = $this->hex2bin($iv);
  126. }
  127. if ($version === '3' || $isOwnCloudV2Migration) {
  128. $keyMaterial = hash_hkdf('sha512', $password);
  129. $encryptionKey = substr($keyMaterial, 0, 32);
  130. $hmacKey = substr($keyMaterial, 32);
  131. }
  132. }
  133. $this->cipher->setPassword($encryptionKey);
  134. $this->cipher->setIV($iv);
  135. if ($isOwnCloudV2Migration) {
  136. // ownCloud uses the binary IV for HMAC calculation
  137. if (!hash_equals($this->calculateHMAC($parts[0] . $iv, $hmacKey), $hmac)) {
  138. throw new Exception('HMAC does not match.');
  139. }
  140. } else {
  141. if (!hash_equals($this->calculateHMAC($parts[0] . $parts[1], $hmacKey), $hmac)) {
  142. throw new Exception('HMAC does not match.');
  143. }
  144. }
  145. $result = $this->cipher->decrypt($ciphertext);
  146. if ($result === false) {
  147. throw new Exception('Decryption failed');
  148. }
  149. return $result;
  150. }
  151. private function hex2bin(string $hex): string {
  152. if (!ctype_xdigit($hex)) {
  153. throw new \RuntimeException('String contains non hex chars: ' . $hex);
  154. }
  155. if (strlen($hex) % 2 !== 0) {
  156. throw new \RuntimeException('Hex string is not of even length: ' . $hex);
  157. }
  158. $result = hex2bin($hex);
  159. if ($result === false) {
  160. throw new \RuntimeException('Hex to bin conversion failed: ' . $hex);
  161. }
  162. return $result;
  163. }
  164. }