[+] Security update

[+] Security update
This commit is contained in:
charleslemaux 2024-07-11 17:27:06 +02:00 committed by GitHub
commit ca33732efc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 45 additions and 17 deletions

View File

@ -107,11 +107,16 @@ def server_create(user: UserRecord, name: str, version: str, framework: str = "p
def server_delete(name: str, user: UserRecord) -> tuple[HTTPStatus, str or None]: def server_delete(name: str, user: UserRecord) -> tuple[HTTPStatus, str or None]:
user_id = user.uid user_id = user.uid
try:
port: int = firebase_manager.get_server_port(user_id)
mc_manager.stop_server_forcefully(port)
except Exception as e:
file_manager.log_error(type(e).__name__, str(e)+f" error when stopping server {name}")
server_path: str = f"users/{user_id}/{name}" server_path: str = f"users/{user_id}/{name}"
try: try:
firebase_manager.delete_server(user_id, name) firebase_manager.delete_server(user_id, name)
file_manager.delete_non_empty_folder(server_path) file_manager.delete_non_empty_folder(server_path)
return HTTPStatus.OK, f"Successfully deleted server {name}." return HTTPStatus.OK, f"Successfully deleted server '{name}'."
except Exception as e: except Exception as e:
file_manager.log_error(type(e).__name__, str(e)) file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR, None return HTTPStatus.INTERNAL_SERVER_ERROR, None
@ -132,7 +137,7 @@ def account_delete(user: UserRecord) -> tuple[HTTPStatus, str or None]:
return HTTPStatus.EXPECTATION_FAILED, f"Database deletion failed | {e}" return HTTPStatus.EXPECTATION_FAILED, f"Database deletion failed | {e}"
try: try:
file_manager.delete_non_empty_folder("users/" + user_id) file_manager.delete_non_empty_folder("users/" + user_id)
return HTTPStatus.OK, f"Successfully deleted user {user_id}." return HTTPStatus.OK, f"Successfully deleted user '{user_id}'."
except Exception as e: except Exception as e:
file_manager.log_error(type(e).__name__, str(e)) file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error deleting user '{user_id}' on the server." return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error deleting user '{user_id}' on the server."
@ -140,6 +145,7 @@ def account_delete(user: UserRecord) -> tuple[HTTPStatus, str or None]:
def server_run(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]: def server_run(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]:
user_id = user.uid user_id = user.uid
mc_manager.set_cooldown(user_id=user_id)
try: try:
port: int = firebase_manager.get_server_port(user_id) port: int = firebase_manager.get_server_port(user_id)
server_id = mc_manager.start_server(f"users/{user_id}/{name}", port) server_id = mc_manager.start_server(f"users/{user_id}/{name}", port)
@ -151,7 +157,7 @@ def server_run(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]:
except Exception as e: except Exception as e:
return HTTPStatus.INTERNAL_SERVER_ERROR, (f"Error updating server {name}'s running state in database. " return HTTPStatus.INTERNAL_SERVER_ERROR, (f"Error updating server {name}'s running state in database. "
f"{type(e).__name__}{str(e)}.") f"{type(e).__name__}{str(e)}.")
return HTTPStatus.ACCEPTED, f"Successfully started server {name}." return HTTPStatus.ACCEPTED, f"Successfully started server '{name}'."
except Exception as e: except Exception as e:
file_manager.log_error(type(e).__name__, str(e)) file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error when running server: {e}" return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error when running server: {e}"
@ -159,21 +165,26 @@ def server_run(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]:
def server_stop(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]: def server_stop(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]:
port = None port = None
user_id: str = user.uid
if mc_manager.has_cooldown(user_id=user_id):
return HTTPStatus.FORBIDDEN, f"Wait 30 seconds before stopping '{name}'."
mc_manager.set_cooldown(user_id=user_id)
try: try:
port = firebase_manager.get_server_port(user.uid) port = firebase_manager.get_server_port(user_id)
if port is None: if port is None:
return HTTPStatus.NOT_FOUND, f"Server {name} not found in firestore." return HTTPStatus.NOT_FOUND, f"Server '{name}' not found in firestore."
exists: bool = mc_manager.stop_server(port) exists: bool = mc_manager.stop_server(port)
if exists: if exists:
firebase_manager.update_server_running_state(user.uid, name, False) firebase_manager.update_server_running_state(user_id, name, False)
return HTTPStatus.OK, f"Successfully stopped server {name}." return HTTPStatus.OK, f"Successfully stopped server '{name}'."
return HTTPStatus.OK, f"Server {name} already stopped." return HTTPStatus.OK, f"Server '{name}' already stopped."
except Exception as e: except Exception as e:
file_manager.log_error(type(e).__name__, str(e)) file_manager.log_error(type(e).__name__, str(e))
if port: if port:
mc_manager.stop_server_forcefully(port) mc_manager.stop_server_forcefully(port)
return HTTPStatus.OK, f"Successfully stopped server {name}." firebase_manager.update_server_running_state(user_id, name, False)
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error occurred when stopping server {name}." return HTTPStatus.OK, f"Successfully stopped server '{name}'."
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error occurred when stopping server '{name}'."
def update_property(uid: str, name: str, prop: str, value: str) -> tuple[HTTPStatus, str or None]: def update_property(uid: str, name: str, prop: str, value: str) -> tuple[HTTPStatus, str or None]:
@ -202,14 +213,14 @@ def update_properties(user: UserRecord, name: str, props: list[tuple[str, str]])
errors.append(message) errors.append(message)
if len(errors) > 0: if len(errors) > 0:
return HTTPStatus.IM_A_TEAPOT, errors return HTTPStatus.IM_A_TEAPOT, errors
return HTTPStatus.OK, f"Successfully updated server {name}." return HTTPStatus.OK, f"Successfully updated server '{name}'."
def run_command(user: UserRecord, command: str, name: str) -> tuple[HTTPStatus, str or None]: def run_command(user: UserRecord, command: str, name: str) -> tuple[HTTPStatus, str or None]:
try: try:
port = firebase_manager.get_server_port(user.uid) port = firebase_manager.get_server_port(user.uid)
if port is None: if port is None:
return HTTPStatus.NOT_FOUND, f"Server {name} not found in firestore." return HTTPStatus.NOT_FOUND, f"Server '{name}' not found in firestore."
mc_manager.execute_server_command(port, command) mc_manager.execute_server_command(port, command)
return HTTPStatus.OK, f"Command '{command}' executed successfully." return HTTPStatus.OK, f"Command '{command}' executed successfully."
except Exception as e: except Exception as e:

View File

@ -1,5 +1,6 @@
import subprocess import subprocess
import shlex import shlex
import time
class MinecraftServerManager: class MinecraftServerManager:
@ -9,6 +10,7 @@ class MinecraftServerManager:
def __init__(self): def __init__(self):
self.servers: dict = {} self.servers: dict = {}
self.servers_count: int = 0 self.servers_count: int = 0
self.cooldowns = {}
def start_server(self, server_directory: str, port: int, def start_server(self, server_directory: str, port: int,
java_executable='java', jar_file='server.jar', memory_size='2048M') -> int or None: java_executable='java', jar_file='server.jar', memory_size='2048M') -> int or None:
@ -16,7 +18,7 @@ class MinecraftServerManager:
if port in self.servers: if port in self.servers:
return None return None
command = f"{java_executable} -Xmx{memory_size} -Xms{memory_size} -jar {jar_file} > /dev/null" command = f"{java_executable} -Xmx{memory_size} -Xms{memory_size} -jar {jar_file} --nogui > /dev/null"
process = subprocess.Popen(shlex.split(command), cwd=server_directory, stdin=subprocess.PIPE) process = subprocess.Popen(shlex.split(command), cwd=server_directory, stdin=subprocess.PIPE)
self.servers_count = len(self.servers) + 1 self.servers_count = len(self.servers) + 1
@ -43,12 +45,12 @@ class MinecraftServerManager:
del self.servers[port] del self.servers[port]
return True return True
def stop_server_forcefully(self, server_id) -> bool: def stop_server_forcefully(self, port) -> bool:
if server_id not in self.servers: if port not in self.servers:
return False return False
process = self.servers[server_id]['process'] process = self.servers[port]['process']
process.terminate() process.terminate()
del self.servers[server_id] del self.servers[port]
return True return True
def get_servers(self): def get_servers(self):
@ -60,6 +62,21 @@ class MinecraftServerManager:
return server_id return server_id
return None return None
def set_cooldown(self, user_id):
expiry_timestamp = time.time() + 30
self.cooldowns[user_id] = expiry_timestamp
def has_cooldown(self, user_id):
expiry_timestamp = self.cooldowns.get(user_id)
if expiry_timestamp is None:
return False
current_time = time.time()
if current_time < expiry_timestamp:
return True
else:
del self.cooldowns[user_id]
return False
if __name__ == "__main__": if __name__ == "__main__":
pass pass