# Race Condition in Check-Then-Use File Permissions

Language: Python
Severity: High
CWE: CWE-367

## Source
8

## Flow
8-9

## Sink
9

## Vulnerable Code
```python
import os
import boto3

def sync_s3_credentials_to_local(bucket_name, credential_file):
    temp_creds = f'/tmp/aws_temp_{bucket_name}.json'
    s3_client = boto3.client('s3')
    s3_client.download_file(bucket_name, credential_file, temp_creds)
    if os.path.exists(temp_creds) and oct(os.stat(temp_creds).st_mode)[-3:] == '600':
        with open(temp_creds, 'r') as cred_data:
            credentials = cred_data.read()
        return credentials
    else:
        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
```python
import os
import boto3
import stat

def sync_s3_credentials_to_local(bucket_name, credential_file):
    s3_client = boto3.client('s3')

    # Download credentials directly into memory to avoid temp file race conditions
    response = s3_client.get_object(Bucket=bucket_name, Key=credential_file)
    credentials = response['Body'].read().decode('utf-8')
    return credentials
```
