index.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. <?php
  2. use function Hestiacp\quoteshellarg\quoteshellarg;
  3. try {
  4. require_once "../inc/vendor/autoload.php";
  5. } catch (Throwable $ex) {
  6. $errstr =
  7. "Unable to load required libraries. Please run v-add-sys-dependencies in command line. Error: " .
  8. $ex->getMessage();
  9. trigger_error($errstr);
  10. echo $errstr;
  11. exit(1);
  12. }
  13. //die("Error: Disabled");
  14. define("HESTIA_DIR_BIN", "/usr/local/hestia/bin/");
  15. define("HESTIA_CMD", "/usr/bin/sudo /usr/local/hestia/bin/");
  16. include $_SERVER["DOCUMENT_ROOT"] . "/inc/helpers.php";
  17. /**
  18. * Displays the error message, checks the proper code and saves a log if needed.
  19. *
  20. * @param int $exit_code
  21. * @param string $message
  22. * @param bool $add_log
  23. * @param string $user
  24. * @return void
  25. */
  26. function api_error($exit_code, $message, $hst_return, bool $add_log = false, $user = "system") {
  27. $message = trim(is_array($message) ? implode("\n", $message) : $message);
  28. // Add log
  29. if ($add_log) {
  30. $v_real_user_ip = get_real_user_ip();
  31. hst_add_history_log("[$v_real_user_ip] $message", "API", "Error", $user);
  32. }
  33. // Print the message with http_code and exit_code
  34. $http_code = $exit_code >= 100 ? $exit_code : exit_code_to_http_code($exit_code);
  35. header("Hestia-Exit-Code: $exit_code");
  36. http_response_code($http_code);
  37. if ($hst_return == "code") {
  38. echo $exit_code;
  39. } else {
  40. echo !preg_match("/^Error:/", $message) ? "Error: $message" : $message;
  41. }
  42. exit();
  43. }
  44. /**
  45. * Legacy connection format using hash or user and password.
  46. *
  47. * @param array{user: string?, pass: string?, hash?: string, cmd: string, arg1?: string, arg2?: string, arg3?: string, arg4?: string, arg5?: string, arg6?: string, arg7?: string, arg8?: string, arg9?: string, returncode?: string} $request_data
  48. * @return void
  49. * @return void
  50. */
  51. function api_legacy(array $request_data) {
  52. $hst_return = ($request_data["returncode"] ?? "no") === "yes" ? "code" : "data";
  53. exec(HESTIA_CMD . "v-list-sys-config json", $output, $return_var);
  54. $settings = json_decode(implode("", $output), true);
  55. unset($output);
  56. if ($settings["config"]["API"] != "yes") {
  57. echo "Error: API has been disabled";
  58. api_error(E_DISABLED, "Error: API Disabled", $hst_return);
  59. }
  60. if ($settings["config"]["API_ALLOWED_IP"] != "allow-all") {
  61. $ip_list = explode(",", $settings["config"]["API_ALLOWED_IP"]);
  62. $ip_list[] = "";
  63. if (!in_array(get_real_user_ip(), $ip_list)) {
  64. api_error(E_FORBIDDEN, "Error: IP is not allowed to connect with API", $hst_return);
  65. }
  66. }
  67. //This exists, so native JSON can be used without the repeating the code twice, so future code changes are easier and don't need to be replicated twice
  68. // Authentication
  69. if (empty($request_data["hash"])) {
  70. exec(HESTIA_CMD . "v-list-sys-config json", $output, $return_var);
  71. $data = json_decode(implode("", $output), true);
  72. $root_user = $data["config"]["ROOT_USER"];
  73. if ($request_data["user"] != "$root_user") {
  74. api_error(E_FORBIDDEN, "Error: authentication failed", $hst_return);
  75. }
  76. $password = $request_data["password"];
  77. if (!isset($password)) {
  78. api_error(E_PASSWORD, "Error: authentication failed", $hst_return);
  79. }
  80. $v_ip = quoteshellarg(get_real_user_ip());
  81. $user = quoteshellarg($root_user);
  82. unset($output);
  83. exec(HESTIA_CMD . "v-get-user-salt " . $user . " " . $v_ip . " json", $output, $return_var);
  84. $pam = json_decode(implode("", $output), true);
  85. $salt = $pam[$root_user]["SALT"];
  86. $method = $pam[$root_user]["METHOD"];
  87. if ($method == "md5") {
  88. $hash = crypt($password, '$1$' . $salt . '$');
  89. }
  90. if ($method == "sha-512") {
  91. $hash = crypt($password, '$6$rounds=5000$' . $salt . '$');
  92. $hash = str_replace('$rounds=5000', "", $hash);
  93. }
  94. if ($method == "yescrypt") {
  95. $fp = tmpfile();
  96. $v_password = stream_get_meta_data($fp)["uri"];
  97. fwrite($fp, $password . "\n");
  98. unset($output);
  99. exec(
  100. HESTIA_CMD .
  101. 'v-check-user-password "admin" ' .
  102. quoteshellarg($v_password) .
  103. " " .
  104. $v_ip .
  105. " yes",
  106. $output,
  107. $return_var,
  108. );
  109. $hash = $output[0];
  110. fclose($fp);
  111. unset($output, $fp, $v_password);
  112. }
  113. if ($method == "des") {
  114. $hash = crypt($password, $salt);
  115. }
  116. // Send hash via tmp file
  117. $v_hash = exec("mktemp -p /tmp");
  118. $fp = fopen($v_hash, "w");
  119. fwrite($fp, $hash . "\n");
  120. fclose($fp);
  121. // Check user hash
  122. exec(
  123. HESTIA_CMD . "v-check-user-hash " . $user . " " . $v_hash . " " . $v_ip,
  124. $output,
  125. $return_var,
  126. );
  127. unset($output);
  128. // Remove tmp file
  129. unlink($v_hash);
  130. // Check API answer
  131. if ($return_var > 0) {
  132. api_error(E_PASSWORD, "Error: authentication failed", $hst_return);
  133. }
  134. } else {
  135. $key = "/usr/local/hestia/data/keys/" . basename($request_data["hash"]);
  136. $v_ip = quoteshellarg(get_real_user_ip());
  137. exec(
  138. HESTIA_CMD . "v-check-api-key " . quoteshellarg($key) . " " . $v_ip,
  139. $output,
  140. $return_var,
  141. );
  142. unset($output);
  143. // Check API answer
  144. if ($return_var > 0) {
  145. api_error(E_PASSWORD, "Error: authentication failed", $hst_return);
  146. }
  147. }
  148. $hst_cmd = trim($request_data["cmd"] ?? "");
  149. $hst_cmd_args = [];
  150. for ($i = 1; $i <= 9; $i++) {
  151. if (isset($request_data["arg{$i}"])) {
  152. $hst_cmd_args["arg{$i}"] = trim($request_data["arg{$i}"]);
  153. }
  154. }
  155. if (empty($hst_cmd)) {
  156. api_error(E_INVALID, "Command not provided", $hst_return);
  157. } elseif (!preg_match('/^[a-zA-Z0-9_-]+$/', $hst_cmd)) {
  158. api_error(E_INVALID, "$hst_cmd command invalid", $hst_return);
  159. }
  160. // Check command
  161. if ($hst_cmd == "v-make-tmp-file") {
  162. // Used in DNS Cluster
  163. $fp = fopen("/tmp/" . basename(escapeshellcmd($hst_cmd_args["arg2"])), "w");
  164. fwrite($fp, $hst_cmd_args["arg1"] . "\n");
  165. fclose($fp);
  166. $return_var = 0;
  167. } else {
  168. // Prepare command
  169. $cmdquery = HESTIA_CMD . escapeshellcmd($hst_cmd);
  170. // Prepare arguments
  171. foreach ($hst_cmd_args as $cmd_arg) {
  172. $cmdquery .= " " . quoteshellarg($cmd_arg);
  173. }
  174. // Run cmd query
  175. exec($cmdquery, $output, $cmd_exit_code);
  176. }
  177. if (!empty($hst_return) && $hst_return == "code") {
  178. echo $cmd_exit_code;
  179. } else {
  180. if ($return_var == 0 && empty($output)) {
  181. echo "OK";
  182. } else {
  183. echo implode("\n", $output) . "\n";
  184. }
  185. }
  186. exit();
  187. }
  188. /**
  189. * Connection using access key.
  190. *
  191. * @param array{access_key: string, secret_key: string, cmd: string, arg1?: string, arg2?: string, arg3?: string, arg4?: string, arg5?: string, arg6?: string, arg7?: string, arg8?: string, arg9?: string, returncode?: string} $request_data
  192. * @return void
  193. */
  194. function api_connection(array $request_data) {
  195. $hst_return = ($request_data["returncode"] ?? "no") === "yes" ? "code" : "data";
  196. $v_real_user_ip = get_real_user_ip();
  197. exec(HESTIA_CMD . "v-list-sys-config json", $output, $return_var);
  198. $settings = json_decode(implode("", $output), true);
  199. unset($output, $return_var);
  200. // Get the status of api
  201. $api_status =
  202. !empty($settings["config"]["API_SYSTEM"]) && is_numeric($settings["config"]["API_SYSTEM"])
  203. ? $settings["config"]["API_SYSTEM"]
  204. : 0;
  205. if ($api_status == 0) {
  206. // Check if API is disabled for all users
  207. api_error(E_DISABLED, "API has been disabled", $hst_return);
  208. }
  209. // Check if API access is enabled for the user
  210. if ($settings["config"]["API_ALLOWED_IP"] != "allow-all") {
  211. $ip_list = explode(",", $settings["config"]["API_ALLOWED_IP"]);
  212. $ip_list[] = "";
  213. if (!in_array($v_real_user_ip, $ip_list) && !in_array("0.0.0.0", $ip_list)) {
  214. api_error(E_FORBIDDEN, "IP is not allowed to connect with API", $hst_return);
  215. }
  216. }
  217. // Get POST Params
  218. $hst_access_key_id = trim($request_data["access_key"] ?? "");
  219. $hst_secret_access_key = trim($request_data["secret_key"] ?? "");
  220. $hst_cmd = trim($request_data["cmd"] ?? "");
  221. $hst_cmd_args = [];
  222. for ($i = 1; $i <= 9; $i++) {
  223. if (isset($request_data["arg{$i}"])) {
  224. $hst_cmd_args["arg{$i}"] = trim($request_data["arg{$i}"]);
  225. }
  226. }
  227. if (empty($hst_cmd)) {
  228. api_error(E_INVALID, "Command not provided", $hst_return);
  229. } elseif (!preg_match('/^[a-zA-Z0-9_-]+$/', $hst_cmd)) {
  230. api_error(E_INVALID, "$hst_cmd command invalid", $hst_return);
  231. }
  232. if (empty($hst_access_key_id) || empty($hst_secret_access_key)) {
  233. api_error(E_PASSWORD, "Authentication failed", $hst_return);
  234. }
  235. // Authenticates the key and checks permission to run the script
  236. exec(
  237. HESTIA_CMD .
  238. "v-check-access-key " .
  239. quoteshellarg($hst_access_key_id) .
  240. " " .
  241. quoteshellarg($hst_secret_access_key) .
  242. " " .
  243. quoteshellarg($hst_cmd) .
  244. " " .
  245. quoteshellarg($v_real_user_ip) .
  246. " json",
  247. $output,
  248. $return_var,
  249. );
  250. if ($return_var > 0) {
  251. //api_error($return_var, "Key $hst_access_key_id - authentication failed", $hst_return);
  252. api_error($return_var, $output, $hst_return);
  253. }
  254. $key_data = json_decode(implode("", $output), true) ?? [];
  255. unset($output, $return_var);
  256. $key_user = $key_data["USER"];
  257. $user_arg_position =
  258. isset($key_data["USER_ARG_POSITION"]) && is_numeric($key_data["USER_ARG_POSITION"])
  259. ? $key_data["USER_ARG_POSITION"]
  260. : -1;
  261. # Check if API access is enabled for nonadmin users
  262. if ($key_user != "admin" && $api_status < 2) {
  263. api_error(E_API_DISABLED, "API has been disabled", $hst_return);
  264. }
  265. // Checks if the value entered in the "user" argument matches the user of the key
  266. if (
  267. $key_user != "admin" &&
  268. $user_arg_position > 0 &&
  269. $hst_cmd_args["arg{$user_arg_position}"] != $key_user
  270. ) {
  271. api_error(
  272. E_FORBIDDEN,
  273. "Key $hst_access_key_id - the \"user\" argument doesn\'t match the key\'s user",
  274. $hst_return,
  275. );
  276. }
  277. // Prepare command
  278. $cmdquery = HESTIA_CMD . escapeshellcmd($hst_cmd);
  279. // Prepare arguments
  280. foreach ($hst_cmd_args as $cmd_arg) {
  281. $cmdquery .= " " . quoteshellarg($cmd_arg);
  282. }
  283. # v-make-temp files is manodory other wise some functions will break
  284. if ($hst_cmd == "v-make-tmp-file") {
  285. $fp = fopen("/tmp/" . basename($hst_cmd_args["arg2"]), "w");
  286. fwrite($fp, $hst_cmd_args["arg1"] . "\n");
  287. fclose($fp);
  288. $cmd_exit_code = 0;
  289. } else {
  290. // Run cmd query
  291. exec($cmdquery, $output, $cmd_exit_code);
  292. $cmd_output = trim(implode("\n", $output));
  293. unset($output);
  294. }
  295. header("Hestia-Exit-Code: $cmd_exit_code");
  296. if ($hst_return == "code") {
  297. echo $cmd_exit_code;
  298. } else {
  299. if ($cmd_exit_code > 0) {
  300. http_response_code(exit_code_to_http_code($cmd_exit_code));
  301. } else {
  302. http_response_code(!empty($cmd_output) ? 200 : 204);
  303. if (!empty($cmd_output) && json_decode($cmd_output, true)) {
  304. header("Content-Type: application/json; charset=utf-8");
  305. }
  306. }
  307. echo $cmd_output;
  308. }
  309. exit();
  310. }
  311. // Get request data
  312. if (isset($_POST["access_key"]) || isset($_POST["user"]) || isset($_POST["hash"])) {
  313. $request_data = $_POST;
  314. } elseif (($json_data = json_decode(file_get_contents("php://input"), true)) != null) {
  315. $request_data = $json_data;
  316. } else {
  317. api_error(
  318. 405,
  319. "Error: data received is null or invalid, check https://hestiacp.com/docs/server-administration/rest-api.html",
  320. "",
  321. );
  322. }
  323. // Try to get access key in the hash
  324. if (
  325. !isset($request_data["access_key"]) &&
  326. isset($request_data["hash"]) &&
  327. substr_count($request_data["hash"], ":") == 1
  328. ) {
  329. $hash_parts = explode(":", $request_data["hash"]);
  330. if (strlen($hash_parts[0]) == 20 && strlen($hash_parts[1]) == 40) {
  331. $request_data["access_key"] = $hash_parts[0];
  332. $request_data["secret_key"] = $hash_parts[1];
  333. unset($request_data["hash"]);
  334. }
  335. }
  336. // Check data format
  337. if (isset($request_data["access_key"]) && isset($request_data["secret_key"])) {
  338. api_connection($request_data);
  339. } elseif (isset($request_data["user"]) || isset($request_data["hash"])) {
  340. api_legacy($request_data);
  341. } else {
  342. api_error(
  343. 405,
  344. "Error: data received is null or invalid, check https://hestiacp.com/docs/server-administration/rest-api.html",
  345. "",
  346. );
  347. }