# Insecure Multiprocessing Shared Memory Exposure via mmap Leading to Sensitive Data Leak

Language: Python
Severity: Critical
CWE: CWE-732

## Source
9

## Flow
9-11

## Sink
11

## Vulnerable Code
```python
import mmap
import os
def cache_biometric_token(usr_id, bio_token):
    shm_tag = f'/tmp/bio_{usr_id}_session'
    fd = os.open(shm_tag, os.O_CREAT | os.O_RDWR, 0o644)
    os.write(fd, bio_token.encode().ljust(256))
    mem_region = mmap.mmap(fd, 256, access=mmap.ACCESS_WRITE)
    mem_region.seek(0)
    mem_region.write(bio_token.encode().ljust(256))
    mem_region.flush()
    os.close(fd)
    return shm_tag
```

## Explanation

The biometric token is written to a predictable world-readable file path '/tmp/bio_{usr_id}_session' created with permissions 0o644 (readable by all users on the system). The sensitive credential is then mapped into memory and written via both os.write and mmap.write, meaning any local unprivileged process can open the file by guessing or enumerating the path pattern and directly read the biometric token from disk or the memory-mapped region.

## Remediation

The fix addresses three core issues: (1) file permissions are changed from world-readable 0o644 to owner-only 0o600, preventing other users from reading the biometric token; (2) the file is placed in a dedicated directory created with mode 0o700 and includes a cryptographically random suffix (secrets.token_hex) to prevent path enumeration/prediction; (3) O_EXCL is added to prevent symlink/race-condition attacks, and proper resource cleanup is ensured via try/finally blocks for both the mmap region and the file descriptor.

## Secure Code
```python
import mmap
import os
import secrets
import tempfile

def cache_biometric_token(usr_id, bio_token):
    # Use a secure, unpredictable filename in a restricted directory
    secure_dir = os.path.join(tempfile.gettempdir(), 'bio_sessions')
    os.makedirs(secure_dir, mode=0o700, exist_ok=True)

    # Generate an unpredictable filename to prevent enumeration
    random_suffix = secrets.token_hex(16)
    shm_tag = os.path.join(secure_dir, f'bio_{usr_id}_{random_suffix}')

    # Open file with owner-only permissions (0o600) using O_EXCL to avoid race conditions
    fd = os.open(shm_tag, os.O_CREAT | os.O_RDWR | os.O_EXCL, 0o600)
    try:
        os.write(fd, bio_token.encode().ljust(256))
        mem_region = mmap.mmap(fd, 256, access=mmap.ACCESS_WRITE)
        try:
            mem_region.seek(0)
            mem_region.write(bio_token.encode().ljust(256))
            mem_region.flush()
        finally:
            mem_region.close()
    finally:
        os.close(fd)

    return shm_tag
```
