WebOrbiton
v1.0.1

AtheraStudio Database

142 lines · 5.9 KB
  1. <?php
  2. declare(strict_types=1);
  3. ​
  4. namespace Athera;
  5. ​
  6. defined('ATHERA') || exit;
  7. ​
  8. final class Atbde
  9. {
  10. public const MAGIC = 'ATBDE';
  11. public const VERSION = 1;
  12. public const BLOCK = 1048576;
  13. public const ITERATIONS = 600000;
  14. public const MIN_ITERATIONS = 100000;
  15. public const MAX_ITERATIONS = 10000000;
  16. public const SQL_MYSQL = 1;
  17. public const SQL_SQLITE = 2;
  18. public const SQLITE_DB = 3;
  19. public const SQL_PGSQL = 4;
  20. ​
  21. private $sink;
  22. private string $buf = '';
  23. private int $index = 0;
  24. private string $header;
  25. private string $enc;
  26. private string $prefix;
  27. private bool $done = false;
  28. ​
  29. public function __construct(string $password, int $type, callable $sink, int $iterations = self::ITERATIONS)
  30. {
  31. self::checkPassword($password);
  32. $salt = random_bytes(16);
  33. $this->prefix = random_bytes(8);
  34. $this->header = self::MAGIC . chr(self::VERSION) . "\x01\x01\x01" . chr($type) . "\0\0"
  35. . pack('N', $iterations) . $salt . $this->prefix . pack('N', self::BLOCK) . str_repeat("\0", 20);
  36. [$this->enc, $mac] = self::derive($password, $salt, $iterations);
  37. $this->sink = $sink;
  38. ($this->sink)($this->header . hash_hmac('sha256', $this->header, $mac, true));
  39. }
  40. ​
  41. public static function checkPassword(string $password): void
  42. {
  43. if (mb_strlen($password) < 12) throw new UserError('A-TBDE password must have at least 12 characters', 400, 'atbde_short');
  44. }
  45. ​
  46. private static function derive(string $password, string $salt, int $iterations): array
  47. {
  48. if (class_exists('Normalizer')) $password = (string)\Normalizer::normalize($password, \Normalizer::FORM_C);
  49. $k = hash_pbkdf2('sha256', $password, $salt, $iterations, 64, true);
  50. return [substr($k, 0, 32), substr($k, 32, 32)];
  51. }
  52. ​
  53. public function write(string $data): void
  54. {
  55. if ($this->done) throw new \LogicException('A-TBDE stream closed');
  56. $this->buf .= $data;
  57. while (strlen($this->buf) > self::BLOCK) {
  58. $this->emit(substr($this->buf, 0, self::BLOCK), false);
  59. $this->buf = substr($this->buf, self::BLOCK);
  60. }
  61. }
  62. ​
  63. public function finish(): void
  64. {
  65. if ($this->done) return;
  66. $this->emit($this->buf, true);
  67. $this->buf = '';
  68. $this->done = true;
  69. }
  70. ​
  71. private function emit(string $raw, bool $final): void
  72. {
  73. $packed = gzdeflate($raw, 6);
  74. $aad = $this->header . pack('N', $this->index) . ($final ? "\x01" : "\x00");
  75. $tag = '';
  76. $c = openssl_encrypt($packed, 'aes-256-gcm', $this->enc, OPENSSL_RAW_DATA, $this->prefix . pack('N', $this->index), $tag, $aad, 16);
  77. if ($c === false) throw new \RuntimeException('A-TBDE encryption failed');
  78. ($this->sink)(pack('N', strlen($c) + 16) . $c . $tag);
  79. $this->index++;
  80. }
  81. ​
  82. public static function readHeader($in): array
  83. {
  84. $head = self::readExact($in, 96);
  85. if (strlen($head) < 96 || substr($head, 0, 5) !== self::MAGIC) throw new UserError('Not an A-TBDE file', 400, 'atbde_format');
  86. if (ord($head[5]) !== self::VERSION || ord($head[6]) !== 1 || ord($head[7]) !== 1) throw new UserError('Unsupported A-TBDE version', 400, 'atbde_version');
  87. $iter = unpack('N', substr($head, 12, 4))[1];
  88. if ($iter < self::MIN_ITERATIONS || $iter > self::MAX_ITERATIONS) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
  89. return [
  90. 'header' => substr($head, 0, 64),
  91. 'check' => substr($head, 64, 32),
  92. 'compressed' => ord($head[8]) === 1,
  93. 'type' => ord($head[9]),
  94. 'iterations' => $iter,
  95. 'salt' => substr($head, 16, 16),
  96. 'prefix' => substr($head, 32, 8),
  97. 'block' => unpack('N', substr($head, 40, 4))[1],
  98. ];
  99. }
  100. ​
  101. public static function decrypt($in, callable $out, string $password): int
  102. {
  103. $h = self::readHeader($in);
  104. [$enc, $mac] = self::derive($password, $h['salt'], $h['iterations']);
  105. if (!hash_equals(hash_hmac('sha256', $h['header'], $mac, true), $h['check'])) throw new UserError('Wrong password', 400, 'atbde_password');
  106. $limit = min(64 * 1048576, max(65536, $h['block'] * 2 + 1024));
  107. for ($i = 0; ; $i++) {
  108. $len = self::readExact($in, 4);
  109. if ($len === '') throw new UserError('A-TBDE file is truncated', 400, 'atbde_truncated');
  110. if (strlen($len) !== 4) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
  111. $n = unpack('N', $len)[1];
  112. if ($n < 16 || $n > $limit) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
  113. $blob = self::readExact($in, $n);
  114. if (strlen($blob) !== $n) throw new UserError('A-TBDE file is truncated', 400, 'atbde_truncated');
  115. $plain = null;
  116. foreach (["\x00", "\x01"] as $flag) {
  117. $r = openssl_decrypt(substr($blob, 0, -16), 'aes-256-gcm', $enc, OPENSSL_RAW_DATA, $h['prefix'] . pack('N', $i), substr($blob, -16), $h['header'] . pack('N', $i) . $flag);
  118. if ($r !== false) { $plain = [$r, $flag === "\x01"]; break; }
  119. }
  120. if ($plain === null) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
  121. $data = $h['compressed'] ? @gzinflate($plain[0], max(1, $h['block'])) : $plain[0];
  122. if ($data === false) throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
  123. if ($data !== '') $out($data);
  124. if ($plain[1]) {
  125. if (fread($in, 1) !== '') throw new UserError('Damaged A-TBDE file', 400, 'atbde_damaged');
  126. return $h['type'];
  127. }
  128. }
  129. }
  130. ​
  131. private static function readExact($in, int $n): string
  132. {
  133. $s = '';
  134. while (strlen($s) < $n && !feof($in)) {
  135. $c = fread($in, $n - strlen($s));
  136. if ($c === false || $c === '') break;
  137. $s .= $c;
  138. }
  139. return $s;
  140. }
  141. }
  142. ​