index.php 11 KB

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