{"title":"Race Condition in Check-Then-Use File Permissions","language":"Python","severity":"High","cwe":"CWE-367","source_lines":[8],"flow_lines":[8,9],"sink_lines":[9],"vulnerable_code":"import os\nimport boto3\n\ndef sync_s3_credentials_to_local(bucket_name, credential_file):\n    temp_creds = f'/tmp/aws_temp_{bucket_name}.json'\n    s3_client = boto3.client('s3')\n    s3_client.download_file(bucket_name, credential_file, temp_creds)\n    if os.path.exists(temp_creds) and oct(os.stat(temp_creds).st_mode)[-3:] == '600':\n        with open(temp_creds, 'r') as cred_data:\n            credentials = cred_data.read()\n        return credentials\n    else:\n        raise PermissionError('Credential file has insecure permissions')","explanation":"This code contains a Time-of-Check Time-of-Use (TOCTOU) race condition vulnerability. Between the permission check on line 8 (os.path.exists + os.stat) and the file open operation on line 9 (open(temp_creds, 'r')), an attacker could replace the file or modify its permissions, allowing unauthorized access to credentials or injection of malicious data.","remediation":"The fix eliminates the TOCTOU race condition entirely by avoiding the use of a temporary file on disk. Instead of downloading the credentials to a local path and then re-reading them, the patched code uses s3_client.get_object() to fetch the credentials directly into memory. This removes the window between permission check and file read, and eliminates all symlink, file-swap, and permission-race attack vectors associated with temporary file handling.","secure_code":"import os\nimport boto3\nimport stat\n\ndef sync_s3_credentials_to_local(bucket_name, credential_file):\n    s3_client = boto3.client('s3')\n\n    # Download credentials directly into memory to avoid temp file race conditions\n    response = s3_client.get_object(Bucket=bucket_name, Key=credential_file)\n    credentials = response['Body'].read().decode('utf-8')\n    return credentials"}