index.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 == 'des') {
  79. $hash = crypt($password, $salt);
  80. }
  81. // Send hash via tmp file
  82. $v_hash = exec('mktemp -p /tmp');
  83. $fp = fopen($v_hash, "w");
  84. fwrite($fp, $hash."\n");
  85. fclose($fp);
  86. // Check user hash
  87. exec(HESTIA_CMD."v-check-user-hash admin ".$v_hash." ".$v_ip, $output, $return_var);
  88. unset($output);
  89. // Remove tmp file
  90. unlink($v_hash);
  91. // Check API answer
  92. if ($return_var > 0) {
  93. echo 'Error: authentication failed';
  94. exit;
  95. }
  96. } else {
  97. $key = '/usr/local/hestia/data/keys/'.basename($request_data['hash']);
  98. $v_ip = quoteshellarg(get_real_user_ip());
  99. exec(HESTIA_CMD."v-check-api-key ".quoteshellarg($key)." ".$v_ip, $output, $return_var);
  100. unset($output);
  101. // Check API answer
  102. if ($return_var > 0) {
  103. echo 'Error: authentication failed';
  104. exit;
  105. }
  106. }
  107. $hst_return = (($request_data['returncode'] ?? 'no') === 'yes') ? 'code' : 'data';
  108. $hst_cmd = trim($request_data['cmd'] ?? '');
  109. $hst_cmd_args = [];
  110. for ($i = 1; $i <= 9; $i++) {
  111. if (isset($request_data["arg{$i}"])) {
  112. $hst_cmd_args["arg{$i}"] = trim($request_data["arg{$i}"]);
  113. }
  114. }
  115. if (empty($hst_cmd)) {
  116. api_error(E_INVALID, "Command not provided");
  117. } else if (!preg_match('/^[a-zA-Z0-9_-]+$/', $hst_cmd)) {
  118. api_error(E_INVALID, "$hst_cmd command invalid");
  119. }
  120. // Check command
  121. if ($hst_cmd == 'v-make-tmp-file') {
  122. // Used in DNS Cluster
  123. $fp = fopen('/tmp/'.basename(escapeshellcmd($hst_cmd_args['arg2'])), 'w');
  124. fwrite($fp, $hst_cmd_args['arg1']."\n");
  125. fclose($fp);
  126. $return_var = 0;
  127. } else {
  128. // Prepare command
  129. $cmdquery = HESTIA_CMD.escapeshellcmd($hst_cmd);
  130. // Prepare arguments
  131. foreach ($hst_cmd_args as $cmd_arg) {
  132. $cmdquery .= " ".quoteshellarg($cmd_arg);
  133. }
  134. // Run cmd query
  135. exec($cmdquery, $output, $cmd_exit_code);
  136. }
  137. if ((!empty($hst_return)) && ($hst_return == 'code')) {
  138. echo $cmd_exit_code;
  139. } else {
  140. if (($return_var == 0) && (empty($output))) {
  141. echo "OK";
  142. } else {
  143. echo implode("\n", $output)."\n";
  144. }
  145. }
  146. exit;
  147. }
  148. /**
  149. * Connection using access key.
  150. *
  151. * @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
  152. * @return void
  153. */
  154. function api_connection(array $request_data) {
  155. $v_real_user_ip = get_real_user_ip();
  156. exec(HESTIA_CMD."v-list-sys-config json", $output, $return_var);
  157. $settings = json_decode(implode('', $output), true);
  158. unset($output, $return_var);
  159. // Get the status of api
  160. $api_status = (!empty($settings['config']['API_SYSTEM']) && is_numeric($settings['config']['API_SYSTEM'])) ? $settings['config']['API_SYSTEM'] : 0;
  161. if ($api_status == 0) {
  162. // Check if API is disabled for all users
  163. api_error(E_DISABLED, "API has been disabled");
  164. }
  165. // Check if API access is enabled for the user
  166. if ($settings['config']['API_ALLOWED_IP'] != 'allow-all') {
  167. $ip_list = explode(',', $settings['config']['API_ALLOWED_IP']);
  168. $ip_list[] = '';
  169. if (!in_array($v_real_user_ip, $ip_list) && !in_array('0.0.0.0', $ip_list)) {
  170. api_error(E_FORBIDDEN, "IP is not allowed to connect with API");
  171. }
  172. }
  173. // Get POST Params
  174. $hst_access_key_id = trim($request_data['access_key'] ?? '');
  175. $hst_secret_access_key = trim($request_data['secret_key'] ?? '');
  176. $hst_return = (($request_data['returncode'] ?? 'no') === 'yes') ? 'code' : 'data';
  177. $hst_cmd = trim($request_data['cmd'] ?? '');
  178. $hst_cmd_args = [];
  179. for ($i = 1; $i <= 9; $i++) {
  180. if (isset($request_data["arg{$i}"])) {
  181. $hst_cmd_args["arg{$i}"] = trim($request_data["arg{$i}"]);
  182. }
  183. }
  184. if (empty($hst_cmd)) {
  185. api_error(E_INVALID, "Command not provided");
  186. } else if (!preg_match('/^[a-zA-Z0-9_-]+$/', $hst_cmd)) {
  187. api_error(E_INVALID, "$hst_cmd command invalid");
  188. }
  189. if (empty($hst_access_key_id) || empty($hst_secret_access_key)) {
  190. api_error(E_PASSWORD, "Authentication failed");
  191. }
  192. // Authenticates the key and checks permission to run the script
  193. 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);
  194. if ($return_var > 0) {
  195. //api_error($return_var, "Key $hst_access_key_id - authentication failed");
  196. api_error($return_var, $output);
  197. }
  198. $key_data = json_decode(implode('', $output), true) ?? [];
  199. unset($output, $return_var);
  200. $key_user = $key_data['USER'];
  201. $user_arg_position = (isset($key_data['USER_ARG_POSITION']) && is_numeric($key_data['USER_ARG_POSITION'])) ? $key_data['USER_ARG_POSITION'] : -1;
  202. # Check if API access is enabled for nonadmin users
  203. if ($key_user != 'admin' && $api_status < 2) {
  204. api_error(E_DISABLED, "API has been disabled");
  205. }
  206. // Checks if the value entered in the "user" argument matches the user of the key
  207. if ($key_user != 'admin' && $user_arg_position > 0 && $hst_cmd_args["arg{$user_arg_position}"] != $key_user) {
  208. api_error(E_FORBIDDEN, "Key $hst_access_key_id - the \"user\" argument doesn\'t match the key\'s user");
  209. }
  210. // Prepare command
  211. $cmdquery = HESTIA_CMD.escapeshellcmd($hst_cmd);
  212. // Prepare arguments
  213. foreach ($hst_cmd_args as $cmd_arg) {
  214. $cmdquery .= " ".quoteshellarg($cmd_arg);
  215. }
  216. # v-make-temp files is manodory other wise some functions will break
  217. if ($hst_cmd == 'v-make-tmp-file'){
  218. $fp = fopen('/tmp/'.basename($hst_cmd_args['arg2']), 'w');
  219. fwrite($fp, $hst_cmd_args['arg1']."\n");
  220. fclose($fp);
  221. $cmd_exit_code = 0;
  222. }else{
  223. // Run cmd query
  224. exec($cmdquery, $output, $cmd_exit_code);
  225. $cmd_output = trim(implode("\n", $output));
  226. unset($output);
  227. }
  228. header("Hestia-Exit-Code: $cmd_exit_code");
  229. if ($hst_return == 'code') {
  230. echo $cmd_exit_code;
  231. } else {
  232. if ($cmd_exit_code > 0) {
  233. http_response_code(exit_code_to_http_code($cmd_exit_code));
  234. } else {
  235. http_response_code(!empty($cmd_output) ? 200 : 204);
  236. if (!empty($cmd_output) && json_decode($cmd_output, true)) {
  237. header('Content-Type: application/json; charset=utf-8');
  238. }
  239. }
  240. echo $cmd_output;
  241. }
  242. exit;
  243. }
  244. // Get request data
  245. if (isset($_POST['access_key']) || isset($_POST['user']) || isset($_POST['hash'])) {
  246. $request_data = $_POST;
  247. } else if (($json_data = json_decode(file_get_contents("php://input"), true)) != null) {
  248. $request_data = $json_data;
  249. } else {
  250. api_error(405, "Error: data received is null or invalid, check https://docs.hestiacp.com/admin_docs/api.html");
  251. }
  252. // Try to get access key in the hash
  253. if (!isset($request_data['access_key']) && isset($request_data['hash']) && substr_count($request_data['hash'], ':') == 1) {
  254. $hash_parts = explode(':', $request_data['hash']);
  255. if (strlen($hash_parts[0]) == 20 && strlen($hash_parts[1]) == 40) {
  256. $request_data['access_key'] = $hash_parts[0];
  257. $request_data['secret_key'] = $hash_parts[1];
  258. unset($request_data['hash']);
  259. }
  260. }
  261. // Check data format
  262. if (isset($request_data['access_key']) && isset($request_data['secret_key'])) {
  263. api_connection($request_data);
  264. } else if (isset($request_data['user']) || isset($request_data['hash'])) {
  265. api_legacy($request_data);
  266. } else {
  267. api_error(405, "Error: data received is null or invalid, check https://docs.hestiacp.com/admin_docs/api.html");
  268. }