WebOrbiton
v1.0.1

AtheraStudio Database

260 lines · 10.0 KB
  1. <?php
  2. declare(strict_types=1);
  3. ​
  4. namespace Athera;
  5. ​
  6. defined('ATHERA') || exit;
  7. ​
  8. final class Auth
  9. {
  10. private static ?array $session = null;
  11. private static string $sidHash = '';
  12. private static ?Db $db = null;
  13. ​
  14. private static function file(string $hash): string
  15. {
  16. return Config::storage('sessions/' . $hash . '.json');
  17. }
  18. ​
  19. private static function write(string $file, array $s): bool
  20. {
  21. $tmp = $file . '.' . bin2hex(random_bytes(4)) . '.tmp';
  22. if (@file_put_contents($tmp, json_encode($s), LOCK_EX) === false) return false;
  23. @chmod($tmp, 0600);
  24. if (@rename($tmp, $file)) return true;
  25. @unlink($tmp);
  26. return is_file($file);
  27. }
  28. ​
  29. private static function fingerprint(): string
  30. {
  31. return hash('sha256', (string)preg_replace('/[\d._]+/', '', (string)($_SERVER['HTTP_USER_AGENT'] ?? '')));
  32. }
  33. ​
  34. public static function load(): ?array
  35. {
  36. if (self::$session !== null) return self::$session;
  37. $sid = Http::cookie('sid');
  38. if (!preg_match('/^[A-Za-z0-9_-]{43}$/', $sid)) return null;
  39. $hash = hash('sha256', $sid);
  40. $file = self::file($hash);
  41. $s = null;
  42. for ($try = 0; $try < 6; $try++) {
  43. $raw = is_file($file) ? @file_get_contents($file) : false;
  44. $s = is_string($raw) ? json_decode($raw, true) : null;
  45. if (is_array($s) && isset($s['last'], $s['created'], $s['fp'], $s['box'])) break;
  46. $s = null;
  47. usleep(25000 * ($try + 1));
  48. }
  49. if ($s === null) return null;
  50. $now = time();
  51. $bindIp = Config::bool('SESSION_BIND_IP') && Security::untrustedProxy() === null && (string)($s['net'] ?? '') !== '';
  52. $ok = $now - (int)$s['last'] <= Config::int('SESSION_IDLE', 60)
  53. && $now - (int)$s['created'] <= Config::int('SESSION_MAX', 300)
  54. && hash_equals((string)$s['fp'], self::fingerprint())
  55. && (!$bindIp || hash_equals((string)$s['net'], Security::network(Security::ip())));
  56. if (!$ok) {
  57. @unlink($file);
  58. return null;
  59. }
  60. if ($now - (int)$s['last'] > 20) {
  61. $s['last'] = $now;
  62. self::write($file, $s);
  63. }
  64. self::$sidHash = $hash;
  65. return self::$session = $s;
  66. }
  67. ​
  68. public static function user(): string
  69. {
  70. $s = self::load();
  71. return $s ? $s['user'] . '@' . $s['host'] : '';
  72. }
  73. ​
  74. public static function isAdmin(): bool
  75. {
  76. $s = self::load();
  77. if (!$s) return false;
  78. $admin = Config::get('ADMIN_USER');
  79. return $admin !== '' && hash_equals($admin, self::user());
  80. }
  81. ​
  82. public static function csrf(): string
  83. {
  84. $s = self::load();
  85. return $s ? (string)$s['csrf'] : '';
  86. }
  87. ​
  88. public static function checkCsrf(string $token): bool
  89. {
  90. $s = self::load();
  91. return $s && $token !== '' && hash_equals((string)$s['csrf'], $token);
  92. }
  93. ​
  94. public static function hostAllowed(string $host, int $port): bool
  95. {
  96. if (Config::bool('DB_ALLOW_ANY_HOST')) return true;
  97. foreach (Config::list('DB_HOSTS') as $h) {
  98. $parts = explode(':', $h, 2);
  99. if (strcasecmp($parts[0], $host) === 0 && (!isset($parts[1]) || (int)$parts[1] === $port || $port === 0)) return true;
  100. }
  101. return false;
  102. }
  103. ​
  104. public static function login(array $in): array
  105. {
  106. $ip = Security::ip();
  107. $user = trim((string)($in['user'] ?? ''));
  108. $pass = (string)($in['pass'] ?? '');
  109. $host = trim((string)($in['host'] ?? '')) ?: (Config::list('DB_HOSTS')[0] ?? 'localhost');
  110. $port = (int)($in['port'] ?? 0);
  111. if (preg_match('/^(.+):(\d+)$/', $host, $m) && !str_contains($m[1], ':')) {
  112. $host = $m[1];
  113. $port = (int)$m[2];
  114. }
  115. $gate = Security::gate($ip);
  116. if ($gate) {
  117. Security::log(['ev' => 'login_denied', 'user' => $user, 'reason' => $gate['reason']]);
  118. throw new UserError('Sign-in is temporarily unavailable. Try again later.', 429, 'locked');
  119. }
  120. if ($user === '' || strlen($user) > 128 || strlen($pass) > 4096 || !preg_match('/^[A-Za-z0-9._\-\[\]:\/]+$/', $host) || $port < 0 || $port > 65535) {
  121. throw new UserError('Invalid sign-in data', 400, 'bad_login');
  122. }
  123. if (!self::hostAllowed($host, $port)) {
  124. Security::fail($ip, $user, 'host_not_allowed');
  125. self::slow();
  126. throw new UserError('Invalid user name, password or server', 401, 'bad_login');
  127. }
  128. $secret = Config::get('TOTP_SECRET');
  129. if ($secret !== '') {
  130. $step = Crypto::totpMatch($secret, (string)($in['totp'] ?? ''));
  131. if (!$step || !Security::totpStep($step)) {
  132. Security::fail($ip, $user, 'totp');
  133. self::slow();
  134. throw new UserError('Invalid user name, password or code', 401, 'bad_login');
  135. }
  136. }
  137. try {
  138. $db = Db::connect($host, $port, $user, $pass);
  139. } catch (\PDOException $e) {
  140. $code = preg_match('/\[(\d{4})\]/', $e->getMessage(), $cm) ? (int)$cm[1] : (int)($e->errorInfo[1] ?? 0);
  141. if (!in_array($code, [2002, 2003, 2005, 2006, 2013], true)) {
  142. Security::fail($ip, $user, 'password');
  143. self::slow();
  144. throw new UserError('Invalid user name, password or server', 401, 'bad_login');
  145. }
  146. Security::log(['ev' => 'login_error', 'user' => $user, 'host' => $host, 'error' => mb_substr($e->getMessage(), 0, 200)]);
  147. throw new UserError('Cannot connect to the database server', 502, 'no_server');
  148. }
  149. if (Config::get('ADMIN_USER') === '') {
  150. Config::save(['ADMIN_USER' => $user . '@' . $host, 'BASE_URL' => Http::origin() . Http::basePath()]);
  151. Security::log(['ev' => 'admin_claim', 'user' => $user . '@' . $host]);
  152. }
  153. $known = Security::success($ip, $user . '@' . $host);
  154. if (!$known && Config::bool('NOTIFY_NEW_IP') && Config::get('ADMIN_EMAIL') !== '') {
  155. Notify::newIp($ip, $user . '@' . $host);
  156. }
  157. self::start($user, $host, $port, $pass);
  158. self::$db = $db;
  159. self::gc();
  160. return ['ok' => true];
  161. }
  162. ​
  163. private static function slow(): void
  164. {
  165. usleep(random_int(250000, 600000));
  166. }
  167. ​
  168. private static function start(string $user, string $host, int $port, string $pass): void
  169. {
  170. $sid = Crypto::b64u(random_bytes(32));
  171. $key = random_bytes(32);
  172. $hash = hash('sha256', $sid);
  173. $now = time();
  174. $s = [
  175. 'user' => $user,
  176. 'host' => $host,
  177. 'port' => $port,
  178. 'box' => base64_encode(Crypto::seal($pass, $key, $hash)),
  179. 'csrf' => Crypto::b64u(random_bytes(32)),
  180. 'created' => $now,
  181. 'last' => $now,
  182. 'fp' => self::fingerprint(),
  183. 'net' => Security::untrustedProxy() === null ? Security::network(Security::ip()) : '',
  184. 'ip' => Security::ip(),
  185. ];
  186. if (!self::write(self::file($hash), $s)) throw new \RuntimeException('Cannot write session');
  187. Http::setCookie('sid', $sid);
  188. Http::setCookie('k', Crypto::b64u($key));
  189. self::$session = $s;
  190. self::$sidHash = $hash;
  191. }
  192. ​
  193. public static function logout(): void
  194. {
  195. if (self::load()) {
  196. @unlink(self::file(self::$sidHash));
  197. Security::log(['ev' => 'logout', 'user' => self::user()]);
  198. }
  199. Http::clearCookie('sid');
  200. Http::clearCookie('k');
  201. self::$session = null;
  202. }
  203. ​
  204. public static function db(): Db
  205. {
  206. if (self::$db) return self::$db;
  207. $s = self::load();
  208. if (!$s) throw new UserError('Session expired', 401, 'session');
  209. $key = Crypto::unb64u(Http::cookie('k'));
  210. $pass = Crypto::open((string)base64_decode((string)$s['box']), $key, self::$sidHash);
  211. if ($pass === null) {
  212. self::logout();
  213. throw new UserError('Session expired', 401, 'session');
  214. }
  215. try {
  216. return self::$db = Db::connect((string)$s['host'], (int)$s['port'], (string)$s['user'], $pass);
  217. } catch (\PDOException $e) {
  218. throw new UserError('Cannot connect to the database server: ' . Db::error($e), 502, 'no_server');
  219. }
  220. }
  221. ​
  222. private static function gc(): void
  223. {
  224. $max = Config::int('SESSION_MAX', 300);
  225. $idle = Config::int('SESSION_IDLE', 60);
  226. $now = time();
  227. foreach (glob(Config::storage('sessions/*.tmp')) ?: [] as $f) {
  228. if (@filemtime($f) < $now - 300) @unlink($f);
  229. }
  230. foreach (glob(Config::storage('sessions/*.json')) ?: [] as $f) {
  231. $m = @filemtime($f);
  232. if ($m !== false && $m < $now - min($max, $idle) - 60) {
  233. $s = json_decode((string)@file_get_contents($f), true);
  234. if (!is_array($s) || $now - (int)$s['last'] > $idle || $now - (int)$s['created'] > $max) @unlink($f);
  235. }
  236. }
  237. }
  238. ​
  239. public static function sessions(): array
  240. {
  241. $out = [];
  242. $now = time();
  243. foreach (glob(Config::storage('sessions/*.json')) ?: [] as $f) {
  244. $s = json_decode((string)@file_get_contents($f), true);
  245. if (!is_array($s) || $now - (int)$s['last'] > Config::int('SESSION_IDLE', 60)) continue;
  246. $id = substr(basename($f, '.json'), 0, 16);
  247. $out[] = ['id' => $id, 'user' => $s['user'] . '@' . $s['host'], 'ip' => $s['ip'] ?? '', 'created' => $s['created'], 'last' => $s['last'], 'current' => str_starts_with(self::$sidHash, $id)];
  248. }
  249. usort($out, function ($a, $b) { return $b['last'] <=> $a['last']; });
  250. return $out;
  251. }
  252. ​
  253. public static function kill(string $id): void
  254. {
  255. if (!preg_match('/^[a-f0-9]{16}$/', $id)) return;
  256. foreach (glob(Config::storage('sessions/' . $id . '*.json')) ?: [] as $f) @unlink($f);
  257. Security::log(['ev' => 'session_kill', 'user' => self::user(), 'session' => $id]);
  258. }
  259. }
  260. ​