{"title":"Insecure Multiprocessing Shared Memory Exposure via mmap Leading to Sensitive Data Leak","language":"Python","severity":"Critical","cwe":"CWE-732","source_lines":[9],"flow_lines":[9,11],"sink_lines":[11],"vulnerable_code":"import mmap\nimport os\ndef cache_biometric_token(usr_id, bio_token):\n    shm_tag = f'/tmp/bio_{usr_id}_session'\n    fd = os.open(shm_tag, os.O_CREAT | os.O_RDWR, 0o644)\n    os.write(fd, bio_token.encode().ljust(256))\n    mem_region = mmap.mmap(fd, 256, access=mmap.ACCESS_WRITE)\n    mem_region.seek(0)\n    mem_region.write(bio_token.encode().ljust(256))\n    mem_region.flush()\n    os.close(fd)\n    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":"import mmap\nimport os\nimport secrets\nimport tempfile\n\ndef cache_biometric_token(usr_id, bio_token):\n    # Use a secure, unpredictable filename in a restricted directory\n    secure_dir = os.path.join(tempfile.gettempdir(), 'bio_sessions')\n    os.makedirs(secure_dir, mode=0o700, exist_ok=True)\n\n    # Generate an unpredictable filename to prevent enumeration\n    random_suffix = secrets.token_hex(16)\n    shm_tag = os.path.join(secure_dir, f'bio_{usr_id}_{random_suffix}')\n\n    # Open file with owner-only permissions (0o600) using O_EXCL to avoid race conditions\n    fd = os.open(shm_tag, os.O_CREAT | os.O_RDWR | os.O_EXCL, 0o600)\n    try:\n        os.write(fd, bio_token.encode().ljust(256))\n        mem_region = mmap.mmap(fd, 256, access=mmap.ACCESS_WRITE)\n        try:\n            mem_region.seek(0)\n            mem_region.write(bio_token.encode().ljust(256))\n            mem_region.flush()\n        finally:\n            mem_region.close()\n    finally:\n        os.close(fd)\n\n    return shm_tag"}