index.php 11 KB

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