From f49be1d85e4440666daac1914071c11b47ea259a Mon Sep 17 00:00:00 2001 From: anima Date: Wed, 28 Oct 2026 22:52:41 +0100 Subject: [PATCH] #15 - optimise file handling --- main.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 33e63c1..e27c3b9 100644 --- a/main.py +++ b/main.py @@ -69,8 +69,15 @@ class MatrixBot: 'next_batch': self.client.next_batch } logging.debug('save session file') - with open(self.session_file, 'w') as f: - yaml.dump(session, f) + # Secure file handling: set appropriate permissions (owner read/write only) + old_umask = os.umask(0o077) # Restrict file permissions to owner only + try: + with open(self.session_file, 'w') as f: + yaml.dump(session, f) + # Explicitly set file permissions to owner-only read/write (no execute) + os.chmod(self.session_file, 0o600) + finally: + os.umask(old_umask) # Restore original umask return True except Exception as e: logging.error(f'Failed to save session to {self.session_file}: {str(e)}') @@ -86,6 +93,12 @@ class MatrixBot: logging.info(f'No session file found at {self.session_file}') return False try: + # Security check: verify file permissions + file_stat = os.stat(self.session_file) + if file_stat.st_mode & 0o077: # Check if other users have permissions + logging.warning(f'Session file {self.session_file} has insecure permissions') + return False + logging.info(f'restore session from file {self.session_file}') with open(self.session_file, 'r') as f: session = yaml.safe_load(f) @@ -96,6 +109,11 @@ class MatrixBot: logging.warning('Session file exists but is incomplete') return False + # Additional integrity check: validate access token format + if not isinstance(session['access_token'], str) or len(session['access_token']) < 10: + logging.warning('Session file contains invalid access token') + return False + self.client.access_token = session['access_token'] self.client.device_id = session['device_id'] self.client.next_batch = session['next_batch']