sftpgo-auth.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php declare(strict_types=1);
  2. // ServNest authenticator for SFTPGo https://github.com/drakkan/sftpgo/blob/main/docs/external-auth.md
  3. const DEBUG = false;
  4. !DEBUG or ob_start();
  5. require 'init.php';
  6. function deny(string $reason): never {
  7. !DEBUG or file_put_contents(ROOT_PATH . '/db/debug.txt', ob_get_contents() . $reason . LF);
  8. http_response_code(403);
  9. exit();
  10. }
  11. if (CONF['common']['services']['ht'] !== 'enabled')
  12. deny('Service not enabled.');
  13. $auth_data = json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR);
  14. $username = hashUsername($auth_data['username']);
  15. if (usernameExists($username) !== true)
  16. deny('This username doesn\'t exist.');
  17. $account = query('select', 'users', ['username' => $username])[0];
  18. if (!in_array('ht', explode(',', $account['services']), true))
  19. deny('Service not enabled for this user.');
  20. const SFTPGO_DENY_PERMS = ['/' => ['list']];
  21. const SFTPGO_ALLOW_PERMS = ['list', 'download', 'upload', 'overwrite', 'delete_files', 'delete_dirs', 'rename_files', 'rename_dirs', 'create_dirs', 'chmod', 'chtimes'];
  22. if ($auth_data['password'] !== '') {
  23. if (checkPassword($account['id'], $auth_data['password']) !== true)
  24. deny('Wrong password.');
  25. $permissions['/'] = SFTPGO_ALLOW_PERMS;
  26. } else if ($auth_data['public_key'] !== '') {
  27. $permissions = SFTPGO_DENY_PERMS;
  28. foreach (query('select', 'ssh-keys', ['username' => $account['id']]) as $key)
  29. if (hash_equals('ssh-ed25519 ' . $key['key'] . LF, $auth_data['public_key']))
  30. $permissions[$key['directory']] = SFTPGO_ALLOW_PERMS;
  31. if ($permissions === SFTPGO_DENY_PERMS)
  32. deny('No matching SSH key allowed.');
  33. } else
  34. deny('Unknown authentication method.');
  35. echo json_encode([
  36. 'status' => 1,
  37. 'username' => $auth_data['username'],
  38. 'home_dir' => CONF['ht']['ht_path'] . '/fs/' . $account['id'],
  39. 'quota_size' => ($account['type'] === 'approved') ? CONF['ht']['user_quota_approved'] : CONF['ht']['user_quota_testing'],
  40. 'permissions' => $permissions,
  41. ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
  42. !DEBUG or file_put_contents(ROOT_PATH . '/db/debug.txt', ob_get_contents() . 'accepted');
  43. http_response_code(200);