Fixed authentication issues

This commit is contained in:
Brandon Rozek 2024-01-06 13:58:48 -05:00
parent dba3213855
commit e3326dea9f
No known key found for this signature in database
GPG key ID: 26E457DA82C9F480
2 changed files with 36 additions and 14 deletions

View file

@ -69,10 +69,13 @@ def run_simple_server(address, fn, force_auth=True):
print("Stopping server...") print("Stopping server...")
@contextmanager @contextmanager
def start_server(address): def start_server(address, allow_other=True):
""" """
Opens up a unix domain socket at the specified address Opens up a unix domain socket at the specified address
and listens for connections. and listens for connections.
allow_other: Allow other users on the system to connect
to the unix domain socket
""" """
if os.path.exists(address): if os.path.exists(address):
print(f"{address} exists -- server already running") print(f"{address} exists -- server already running")
@ -84,6 +87,11 @@ def start_server(address):
sock.bind(address) sock.bind(address)
sock.listen() sock.listen()
if allow_other:
# 33279 = '-rwxrwxrwx.'
os.chmod("game.sock", 33279)
os.chmod("challenges", 33279)
try: try:
yield sock yield sock
finally: finally:
@ -106,10 +114,12 @@ def client_connection(sock):
connection.close() connection.close()
def generate_challenge(user): def generate_challenge(user):
SERVER_FOLDER = Path(__file__).parent.absolute()
Path(f"{SERVER_FOLDER}/challenges").mkdir(mode=33279, exist_ok=True)
return ChallengeMessage( return ChallengeMessage(
username=user, username=user,
token=generate_token(TOKEN_LENGTH), token=generate_token(TOKEN_LENGTH),
location=f"/home/{user}/.pubnix_challenge" location=f"{SERVER_FOLDER}/challenges/.{user}_challenge"
) )
def authenticate(connection): def authenticate(connection):
@ -126,7 +136,7 @@ def authenticate(connection):
# Check that challenge file exists # Check that challenge file exists
if not os.path.exists(challenge.location): if not os.path.exists(challenge.location):
close_with_error(connection, "Challange file doesn't exist") close_with_error(connection, f"Authentication Error: Challange file doesn't exist at {challenge.location}")
# Check if user owns the file # Check if user owns the file
if find_owner(challenge.location) != user: if find_owner(challenge.location) != user:
@ -175,9 +185,10 @@ def run_simple_client(address, fn, force_auth=True):
""" """
with start_client(address) as client: with start_client(address) as client:
if force_auth: if force_auth:
user = login(client) user, success = login(client)
send_message(client, StartMessage()) if not force_auth or success:
fn(client, user) send_message(client, StartMessage())
fn(client, user)
@contextmanager @contextmanager
def start_client(address): def start_client(address):
@ -213,12 +224,16 @@ def login(connection):
send_message(connection, ValidationMessage()) send_message(connection, ValidationMessage())
# On success, delete challenge file # On success, delete challenge file
success = True
try: try:
message = receive_message(connection, AuthSuccessMessage) message = receive_message(connection, AuthSuccessMessage)
except ProtocolException as e:
print(e)
success = False
finally: finally:
os.unlink(challenge.location) os.unlink(challenge.location)
return user return user, success
## ##
# Messages # Messages
@ -244,7 +259,11 @@ def receive_message(connection, cls=None):
try: try:
message = cls(**message) message = cls(**message)
except (TypeError, AssertionError): except (TypeError, AssertionError):
close_with_error(connection, "Expected message of type") if "type" in message and message['type'] == "error":
raise ProtocolException(message.get("message"))
else:
print("Received:", message, flush=True)
close_with_error(connection, f"Expected message of type {cls}")
return message return message

View file

@ -41,11 +41,12 @@ class WordGuessServer:
""" """
# 33152 = '-rw-------.' # 33152 = '-rw-------.'
# 33188 = '-rw-r--r--.' # 33188 = '-rw-r--r--.'
SERVER_FOLDER = Path(__file__).parent.absolute()
os.chmod(__file__, 33152) os.chmod(__file__, 33152)
os.chmod("pubnix.py", 33188) os.chmod(f"{SERVER_FOLDER}/pubnix.py", 33188)
os.chmod("wordguess.py", 33188) os.chmod(f"{SERVER_FOLDER}/wordguess.py", 33188)
os.chmod("words.txt", 33188) os.chmod(f"{SERVER_FOLDER}/words.txt", 33188)
os.chmod("client.py", 33188) os.chmod(f"{SERVER_FOLDER}/client.py", 33188)
Path(WordGuess.RESULTS_LOCATION).touch(33188) Path(WordGuess.RESULTS_LOCATION).touch(33188)
Path(SAVE_LOCATION).touch(33152) Path(SAVE_LOCATION).touch(33152)
@ -219,13 +220,13 @@ def make_default_dict_false():
def make_default_dict_set(): def make_default_dict_set():
return defaultdict(set) return defaultdict(set)
SAVE_LOCATION = "state.pickle" SERVER_FOLDER = Path(__file__).parent.absolute()
SAVE_LOCATION = f"{SERVER_FOLDER}/state.pickle"
if __name__ == "__main__": if __name__ == "__main__":
# NOTE: The seed must be kept secret otherwise # NOTE: The seed must be kept secret otherwise
# players can cheat! # players can cheat!
SEED = random.randint(3, 1000000) SEED = random.randint(3, 1000000)
print("Seed: ", SEED)
w = WordGuessServer(SEED) w = WordGuessServer(SEED)
@ -235,6 +236,8 @@ if __name__ == "__main__":
w = pickle.load(file) w = pickle.load(file)
print("Successfully loaded game state") print("Successfully loaded game state")
print("Seed: ", w.seed)
# Make sure permissions are correct # Make sure permissions are correct
# to prevent cheating... # to prevent cheating...
w.fix_permissions() w.fix_permissions()