index.php 12 KB

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