index.php 11 KB

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