WebOrbiton
v1.3.1

AtheraStudio SyncDrop

468 lines · 18.5 KB
  1. <?php
  2. declare(strict_types=1);
  3. ​
  4. defined('SD_BOOT') || exit;
  5. ​
  6. const SD_SETUP_TTL = 3600;
  7. const SD_STAGE_TTL = 300;
  8. ​
  9. function sd_setup_code(): string
  10. {
  11. $file = sd_path('setup');
  12. $data = is_file($file) ? json_decode((string)@file_get_contents($file), true) : null;
  13. if (is_array($data) && isset($data['code'], $data['exp']) && (int)$data['exp'] > time()) return (string)$data['code'];
  14. $raw = sd_b32_encode(random_bytes(10));
  15. $code = implode('-', str_split(substr($raw, 0, 16), 4));
  16. $content = json_encode(['code' => $code, 'exp' => time() + SD_SETUP_TTL, 'instance' => sd_instance(), 'info' => 'AtheraStudio SyncDrop setup code']);
  17. @file_put_contents($file, $content . "\n", LOCK_EX);
  18. @chmod($file, 0600);
  19. return $code;
  20. }
  21. ​
  22. function sd_norm_code(string $code): string
  23. {
  24. return strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code));
  25. }
  26. ​
  27. function sd_default_target(): ?string
  28. {
  29. $doc = sd_docroot();
  30. $candidates = sd_app() !== $doc ? [$doc] : [];
  31. for ($dir = dirname($doc); dirname($dir) !== $dir; $dir = dirname($dir)) {
  32. if (sd_webroot_named($dir, SD_WEBROOTS)) {
  33. $candidates[] = $dir;
  34. break;
  35. }
  36. }
  37. foreach ($candidates as $dir) {
  38. $path = sd_target_path_check($dir, $err);
  39. if ($path !== null) return $path;
  40. }
  41. return null;
  42. }
  43. ​
  44. function sd_route_setup(): never
  45. {
  46. sd_session_start();
  47. $code = sd_setup_code();
  48. $errors = [];
  49. $old = [];
  50. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  51. $old = ['user' => (string)($_POST['user'] ?? ''), 'email' => (string)($_POST['email'] ?? ''), 'lang' => (string)($_POST['lang'] ?? '')];
  52. if (sd_locked() > 0) {
  53. $errors[] = 'err_locked_short';
  54. } elseif (!sd_csrf_ok() || !sd_honeypot_ok() || !sd_pow_verify('setup')) {
  55. $errors[] = 'err_antibot';
  56. } elseif (!hash_equals(sd_norm_code($code), sd_norm_code((string)($_POST['code'] ?? '')))) {
  57. sd_fail('setup_code');
  58. $errors[] = 'err_setup_code';
  59. } else {
  60. $user = trim($old['user']);
  61. $email = trim($old['email']);
  62. $password = (string)($_POST['password'] ?? '');
  63. $lang = isset(SD_LANGS[$old['lang']]) ? $old['lang'] : sd_lang();
  64. if (!preg_match('/^[A-Za-z0-9._-]{3,32}$/', $user)) $errors[] = 'err_username';
  65. if (!filter_var($email, FILTER_VALIDATE_EMAIL) || preg_match('/[\r\n]/', $email)) $errors[] = 'err_email';
  66. if (!sd_password_strong($password, $user)) $errors[] = 'err_password_weak';
  67. if (!hash_equals($password, (string)($_POST['password2'] ?? ''))) $errors[] = 'err_password_match';
  68. if (!$errors) {
  69. $targets = [];
  70. $main = sd_default_target();
  71. if ($main !== null) {
  72. $targets['main'] = ['name' => basename(dirname($main)) ?: basename($main), 'path' => $main, 'exclude' => SD_DEFAULT_EXCLUDES];
  73. }
  74. sd_env_save([
  75. 'SD_USER' => $user,
  76. 'SD_PASS' => sd_password_hash($password),
  77. 'SD_EMAIL' => $email,
  78. 'SD_ALERTS' => 1,
  79. 'SD_LANG' => $lang,
  80. 'SD_SECRET' => bin2hex(random_bytes(32)),
  81. 'SD_EPOCH' => 1,
  82. 'SD_TOTP' => '',
  83. 'SD_TOTP_STEP' => 0,
  84. 'SD_RECOVERY' => [],
  85. 'SD_TARGETS' => $targets,
  86. 'SD_CREATED' => gmdate('c'),
  87. 'SD_INSTANCE' => sd_instance(),
  88. ]);
  89. @unlink(sd_path('setup'));
  90. sd_set_lang($lang);
  91. sd_session_elevate('enroll');
  92. $_SESSION['stage_at'] = time();
  93. sd_audit('setup_done', ['user' => $user]);
  94. sd_redirect('enroll');
  95. }
  96. }
  97. }
  98. sd_view_setup($errors, $old);
  99. exit;
  100. }
  101. ​
  102. function sd_route_login(): never
  103. {
  104. $error = '';
  105. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  106. $locked = sd_locked();
  107. if ($locked > 0) {
  108. sd_view_login('', $locked);
  109. exit;
  110. }
  111. $captcha = sd_captcha_needed();
  112. if (!sd_csrf_ok() || !sd_honeypot_ok() || !sd_pow_verify('login')) {
  113. sd_fail('antibot');
  114. $error = 'err_antibot';
  115. } elseif (!sd_botcheck_ok()) {
  116. sd_fail('bot');
  117. $error = 'err_antibot';
  118. } elseif ($captcha && !sd_captcha_ok()) {
  119. sd_fail('captcha');
  120. $error = 'err_captcha';
  121. } else {
  122. $env = sd_env();
  123. $user = (string)($_POST['user'] ?? '');
  124. $password = (string)($_POST['password'] ?? '');
  125. $userOk = hash_equals((string)$env['SD_USER'], $user);
  126. $passOk = password_verify($password, (string)$env['SD_PASS']);
  127. if ($userOk && $passOk) {
  128. if (password_needs_rehash((string)$env['SD_PASS'], defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_BCRYPT)) {
  129. sd_env_set(['SD_PASS' => sd_password_hash($password)]);
  130. }
  131. $next = !empty($env['SD_TOTP']) ? '2fa' : 'enroll';
  132. sd_session_elevate($next);
  133. $_SESSION['stage_at'] = time();
  134. $_SESSION['tries'] = 0;
  135. sd_audit('password_ok');
  136. sd_redirect($next);
  137. }
  138. sd_fail('password');
  139. $error = 'err_login';
  140. }
  141. }
  142. sd_view_login($error, sd_locked());
  143. exit;
  144. }
  145. ​
  146. function sd_remember_host(): void
  147. {
  148. $host = sd_host();
  149. if ($host !== '' && (string)(sd_env()['SD_HOST'] ?? '') !== $host) sd_env_set(['SD_HOST' => $host]);
  150. }
  151. ​
  152. function sd_stage_fresh(): bool
  153. {
  154. return time() - (int)($_SESSION['stage_at'] ?? 0) <= SD_STAGE_TTL;
  155. }
  156. ​
  157. function sd_complete_login(string $method): never
  158. {
  159. sd_session_elevate('full');
  160. sd_fail_reset();
  161. sd_shield_trust();
  162. sd_remember_host();
  163. sd_audit('login_ok', ['method' => $method]);
  164. sd_alert('alert_login_subject', 'alert_login_body', ['method' => t('method_' . $method)]);
  165. sd_redirect('sync');
  166. }
  167. ​
  168. function sd_route_twofa(): never
  169. {
  170. if (!sd_stage_fresh()) {
  171. sd_session_reset();
  172. sd_flash('error', t('err_stage_expired'));
  173. sd_redirect('login');
  174. }
  175. $error = '';
  176. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  177. if (!sd_csrf_ok()) sd_redirect('login');
  178. $env = sd_env();
  179. $input = trim((string)($_POST['code'] ?? ''));
  180. if (preg_match('/^\d[\d ]{4,6}\d$/', $input)) {
  181. $step = sd_totp_match((string)$env['SD_TOTP'], $input, (int)($env['SD_TOTP_STEP'] ?? 0));
  182. if ($step !== null) {
  183. sd_env_set(['SD_TOTP_STEP' => $step]);
  184. sd_complete_login('totp');
  185. }
  186. } else {
  187. $norm = sd_recovery_normalize($input);
  188. $codes = (array)($env['SD_RECOVERY'] ?? []);
  189. foreach ($codes as $i => $hash) {
  190. if (strlen($norm) === 12 && password_verify($norm, (string)$hash)) {
  191. unset($codes[$i]);
  192. sd_env_set(['SD_RECOVERY' => array_values($codes)]);
  193. sd_audit('recovery_used', ['left' => count($codes)]);
  194. sd_alert('alert_recovery_subject', 'alert_recovery_body', ['left' => (string)count($codes)]);
  195. sd_complete_login('recovery');
  196. }
  197. }
  198. }
  199. $_SESSION['tries'] = (int)($_SESSION['tries'] ?? 0) + 1;
  200. sd_fail('totp');
  201. if ($_SESSION['tries'] >= 5) {
  202. sd_session_reset();
  203. sd_flash('error', t('err_too_many'));
  204. sd_redirect('login');
  205. }
  206. $error = 'err_code';
  207. }
  208. sd_view_twofa($error);
  209. exit;
  210. }
  211. ​
  212. function sd_store_recovery(): array
  213. {
  214. $codes = sd_recovery_codes();
  215. $hashes = array_map(static fn($c) => password_hash(sd_recovery_normalize($c), PASSWORD_BCRYPT, ['cost' => 10]), $codes);
  216. sd_env_set(['SD_RECOVERY' => $hashes]);
  217. return $codes;
  218. }
  219. ​
  220. function sd_route_enroll(): never
  221. {
  222. if (!sd_stage_fresh() && empty($_SESSION['enroll_secret'])) {
  223. sd_session_reset();
  224. sd_redirect('login');
  225. }
  226. $env = sd_env();
  227. if (!empty($env['SD_TOTP'])) {
  228. sd_session_reset();
  229. sd_redirect('login');
  230. }
  231. if (empty($_SESSION['enroll_secret'])) $_SESSION['enroll_secret'] = sd_totp_secret();
  232. $secret = (string)$_SESSION['enroll_secret'];
  233. $error = '';
  234. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  235. if (!sd_csrf_ok()) sd_redirect('login');
  236. $step = sd_totp_match($secret, (string)($_POST['code'] ?? ''));
  237. if ($step !== null) {
  238. sd_env_set(['SD_TOTP' => $secret, 'SD_TOTP_STEP' => $step]);
  239. $codes = sd_store_recovery();
  240. sd_session_elevate('full');
  241. $_SESSION['recovery_show'] = $codes;
  242. sd_fail_reset();
  243. sd_shield_trust();
  244. sd_remember_host();
  245. sd_audit('totp_enrolled');
  246. sd_alert('alert_2fa_subject', 'alert_2fa_body');
  247. sd_redirect('recovery');
  248. }
  249. $error = 'err_code';
  250. }
  251. sd_view_enroll($secret, sd_totp_uri($secret, (string)$env['SD_USER']), $error);
  252. exit;
  253. }
  254. ​
  255. function sd_route_recovery(): never
  256. {
  257. $codes = $_SESSION['recovery_show'] ?? null;
  258. unset($_SESSION['recovery_show']);
  259. if (!is_array($codes) || !$codes) sd_redirect('sync');
  260. sd_view_recovery($codes, !empty($_SESSION['recovery_app']));
  261. unset($_SESSION['recovery_app']);
  262. exit;
  263. }
  264. ​
  265. function sd_route_history(): never
  266. {
  267. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  268. if (!sd_csrf_ok()) sd_redirect('history');
  269. if (($_POST['action'] ?? '') === 'rollback') {
  270. $result = sd_with_lock(static fn(): array => sd_rollback((string)($_POST['id'] ?? '')));
  271. if (isset($result['ok'])) {
  272. sd_flash($result['skipped'] ? 'warn' : 'ok', t($result['skipped'] ? 'msg_rollback_partial' : 'msg_rollback_ok', ['n' => (string)$result['restored'], 's' => (string)count($result['skipped'])]));
  273. } else {
  274. sd_flash('error', t('err_rollback'));
  275. }
  276. }
  277. sd_redirect('history');
  278. }
  279. sd_view_history();
  280. exit;
  281. }
  282. ​
  283. function sd_verify_current_password(): bool
  284. {
  285. $ok = password_verify((string)($_POST['current'] ?? ''), (string)(sd_env()['SD_PASS'] ?? ''));
  286. if (!$ok) sd_fail('settings_password');
  287. return $ok;
  288. }
  289. ​
  290. function sd_route_settings(): never
  291. {
  292. $errors = [];
  293. if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  294. if (!sd_csrf_ok()) sd_redirect('settings');
  295. $env = sd_env();
  296. $action = (string)($_POST['action'] ?? '');
  297. switch ($action) {
  298. case 'alerts':
  299. $email = trim((string)($_POST['email'] ?? ''));
  300. if (!sd_verify_current_password()) $errors[] = 'err_password_current';
  301. elseif (!filter_var($email, FILTER_VALIDATE_EMAIL) || preg_match('/[\r\n]/', $email)) $errors[] = 'err_email';
  302. else {
  303. $old = (string)$env['SD_EMAIL'];
  304. sd_env_set(['SD_EMAIL' => $email, 'SD_ALERTS' => !empty($_POST['alerts']) ? 1 : 0]);
  305. sd_audit('alerts_changed');
  306. if ($old !== $email) sd_alert('alert_email_subject', 'alert_email_body', ['email' => $email], $old);
  307. if (!empty($_POST['test'])) {
  308. $sent = sd_alert('alert_test_subject', 'alert_test_body');
  309. sd_flash($sent ? 'ok' : 'warn', t($sent ? 'msg_test_sent' : 'msg_test_failed'));
  310. } else {
  311. sd_flash('ok', t('msg_saved'));
  312. }
  313. sd_redirect('settings');
  314. }
  315. break;
  316. case 'password':
  317. $new = (string)($_POST['password'] ?? '');
  318. if (!sd_verify_current_password()) $errors[] = 'err_password_current';
  319. elseif (!sd_password_strong($new, (string)$env['SD_USER'])) $errors[] = 'err_password_weak';
  320. elseif (!hash_equals($new, (string)($_POST['password2'] ?? ''))) $errors[] = 'err_password_match';
  321. else {
  322. sd_env_set(['SD_PASS' => sd_password_hash($new), 'SD_EPOCH' => (int)$env['SD_EPOCH'] + 1]);
  323. sd_session_elevate('full');
  324. sd_audit('password_changed');
  325. sd_alert('alert_password_subject', 'alert_password_body');
  326. sd_flash('ok', t('msg_password_changed'));
  327. sd_redirect('settings');
  328. }
  329. break;
  330. case 'recovery':
  331. $step = sd_totp_match((string)$env['SD_TOTP'], (string)($_POST['code'] ?? ''), (int)($env['SD_TOTP_STEP'] ?? 0));
  332. if ($step === null) {
  333. sd_fail('settings_totp');
  334. $errors[] = 'err_code';
  335. } else {
  336. sd_env_set(['SD_TOTP_STEP' => $step]);
  337. $_SESSION['recovery_show'] = sd_store_recovery();
  338. $_SESSION['recovery_app'] = true;
  339. sd_audit('recovery_regenerated');
  340. sd_alert('alert_recovery_new_subject', 'alert_recovery_new_body');
  341. sd_redirect('recovery');
  342. }
  343. break;
  344. case 'sessions':
  345. sd_env_set(['SD_EPOCH' => (int)$env['SD_EPOCH'] + 1]);
  346. sd_session_elevate('full');
  347. sd_audit('sessions_revoked');
  348. sd_flash('ok', t('msg_sessions'));
  349. sd_redirect('settings');
  350. case 'lang':
  351. $lang = (string)($_POST['lang'] ?? '');
  352. if (isset(SD_LANGS[$lang])) {
  353. sd_env_set(['SD_LANG' => $lang]);
  354. sd_set_lang($lang);
  355. }
  356. sd_redirect('settings');
  357. case 'target_add':
  358. $name = trim((string)($_POST['name'] ?? ''));
  359. $path = sd_target_path_check((string)($_POST['path'] ?? ''), $err);
  360. if ($name === '' || mb_strlen($name) > 60) $errors[] = 'err_target_name';
  361. elseif ($path === null) $errors[] = $err;
  362. else {
  363. $targets = sd_targets();
  364. foreach ($targets as $t) {
  365. if (realpath((string)$t['path']) === $path) {
  366. $errors[] = 'err_target_exists';
  367. break 2;
  368. }
  369. }
  370. $id = 't' . bin2hex(random_bytes(4));
  371. $targets[$id] = ['name' => $name, 'path' => $path, 'exclude' => SD_DEFAULT_EXCLUDES];
  372. sd_env_set(['SD_TARGETS' => $targets]);
  373. sd_audit('target_added', ['id' => $id, 'path' => $path]);
  374. sd_flash('ok', t('msg_saved'));
  375. sd_redirect('settings', ['t' => $id]);
  376. }
  377. break;
  378. case 'target_save':
  379. $id = (string)($_POST['id'] ?? '');
  380. $targets = sd_targets();
  381. if (!isset($targets[$id])) sd_redirect('settings');
  382. if (!empty($_POST['remove'])) {
  383. unset($targets[$id]);
  384. sd_env_set(['SD_TARGETS' => $targets]);
  385. sd_audit('target_removed', ['id' => $id]);
  386. sd_flash('ok', t('msg_saved'));
  387. sd_redirect('settings');
  388. }
  389. $name = trim((string)($_POST['name'] ?? ''));
  390. if ($name === '' || mb_strlen($name) > 60) {
  391. $errors[] = 'err_target_name';
  392. break;
  393. }
  394. $patterns = [];
  395. foreach (preg_split('/\R/', (string)($_POST['exclude'] ?? '')) as $line) {
  396. $line = trim($line);
  397. if ($line !== '' && mb_strlen($line) <= 200 && !preg_match('/[\x00-\x1F]/', $line)) $patterns[] = $line;
  398. }
  399. $targets[$id]['name'] = $name;
  400. $targets[$id]['exclude'] = array_values(array_unique(array_slice($patterns, 0, 200)));
  401. sd_env_set(['SD_TARGETS' => $targets]);
  402. sd_audit('target_saved', ['id' => $id]);
  403. sd_flash('ok', t('msg_saved'));
  404. sd_redirect('settings');
  405. }
  406. }
  407. sd_view_settings($errors);
  408. exit;
  409. }
  410. ​
  411. function sd_boot(): void
  412. {
  413. ini_set('display_errors', '0');
  414. ini_set('log_errors', '1');
  415. ini_set('expose_php', '0');
  416. sd_headers();
  417. if (sd_base() === null) sd_view_fatal(t('fatal_title'), t('fatal_base'));
  418. if (!is_dir(sd_data()) || !is_writable(sd_data())) sd_view_fatal(t('fatal_title'), t('fatal_data'));
  419. ini_set('error_log', sd_data('logs') . '/php-error.log');
  420. sd_shield_gate();
  421. if (!sd_https() && !sd_local()) {
  422. if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
  423. header('Location: https://' . sd_host() . (string)($_SERVER['REQUEST_URI'] ?? '/'), true, 301);
  424. exit;
  425. }
  426. http_response_code(403);
  427. exit;
  428. }
  429. if (!function_exists('hash_hmac') || !function_exists('random_bytes') || !function_exists('mb_strlen')) sd_view_fatal(t('fatal_title'), t('fatal_ext'));
  430. }
  431. ​
  432. function sd_run(): void
  433. {
  434. sd_boot();
  435. $api = $_GET['api'] ?? null;
  436. if (is_string($api)) sd_api($api);
  437. $page = is_string($_GET['p'] ?? null) ? $_GET['p'] : '';
  438. if (sd_env() === null) sd_route_setup();
  439. sd_session_start();
  440. if ($page === 'lang' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  441. if (sd_csrf_ok()) sd_set_lang((string)($_POST['lang'] ?? ''));
  442. sd_redirect(sd_stage() === 'full' ? 'settings' : 'login');
  443. }
  444. if ($page === 'logout' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  445. if (sd_csrf_ok()) {
  446. if (sd_stage() === 'full') sd_audit('logout');
  447. session_destroy();
  448. setcookie(sd_cookie_name(), '', ['expires' => time() - 3600, 'path' => '/', 'secure' => sd_https(), 'httponly' => true, 'samesite' => 'Strict']);
  449. }
  450. sd_redirect('login');
  451. }
  452. $stage = sd_stage();
  453. if ($stage === '2fa') sd_route_twofa();
  454. if ($stage === 'enroll') sd_route_enroll();
  455. if ($stage !== 'full') sd_route_login();
  456. match ($page) {
  457. 'recovery' => sd_route_recovery(),
  458. 'history' => sd_route_history(),
  459. 'shield' => sd_route_shield(),
  460. 'update' => sd_route_update(),
  461. 'settings' => sd_route_settings(),
  462. default => (static function (): never {
  463. sd_view_sync();
  464. exit;
  465. })(),
  466. };
  467. }
  468. ​