Skip to content

Harden: Replace os.popen with Python file handling in tools_views.py #856

@securesigner

Description

@securesigner

In tools_views.py, the entropy generation logic uses os.popen("cat /proc/cpuinfo | grep Serial") to gather the CPU serial number for mixing into the seed entropy hash.

try:
    stream = os.popen("cat /proc/cpuinfo | grep Serial")
    output = stream.read()
    serial_num = output.split(":")[-1].strip().encode('utf-8')
    serial_hash = hashlib.sha256(serial_num)
    hash_bytes = serial_hash.digest()
except Exception as e:
    logger.info(repr(e), exc_info=True)
    hash_bytes = b'0'

While this is not currently exploitable (the command string is static), os.popen is deprecated since Python 2.6 and implicitly spawns a shell.

My recommendation is refactor to read cpuinfo directly using Python's built-in file I/O. This avoids spawning external processes (cat, grep) and the shell entirely, improving performance and security posture.

try:
    serial_num = b''
    with open("/proc/cpuinfo", "r") as f:
        for line in f:
            if "Serial" in line:
                serial_num = line.split(":")[-1].strip().encode('utf-8')
                break
    serial_hash = hashlib.sha256(serial_num)
    hash_bytes = serial_hash.digest()
except Exception as e:
    logger.info(repr(e), exc_info=True)
    hash_bytes = b'0'

This also removes the unused import os at the top of the file.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions