Safeguard
Application Security•

CWE-689 Permission Race Condition During Resource Copy

Copy a file, then lock it down, and there is a window where anyone can read it. CWE-689 shows the pattern in archive extractors and how to close the gap.

Safeguard Security Team
2 min read

CWE-689, Permission Race Condition During Resource Copy, is a timing bug. The product copies or clones a resource and only sets its permissions once the copy is done. For that window the resource is exposed to other users and processes. MITRE lists C and Perl as affected platforms.

How it happens

The pattern is create first, protect later. MITRE's examples:

  • CVE-2002-0760: an archive extractor decompresses files with world-readable permissions, then later sets permissions to what the archive specified.
  • CVE-2005-2174: a product inserts a new object into a database before setting the object's permissions.
  • CVE-2006-5214: an error file has weak permissions before a chmod is performed.
  • CVE-2005-2475: an archive permissions issue using a hard link.

An illustration in Python:

# Vulnerable: file exists with default permissions until chmod runs
shutil.copyfile(src, dst)
os.chmod(dst, 0o600)

Between those two lines, anyone allowed to read the directory can open the file under the default mode.

What an attacker gains

MITRE lists reading and modifying application data, affecting confidentiality and integrity. The attacker needs a local foothold and good timing, but copying a large file widens the window.

How to find it

The MITRE record lists no detection methods. Search for copy, extract or insert calls that are followed by a separate permission call. Anywhere you see create then chmod, you have a candidate.

How to fix it

Set restrictive permissions at creation, so the resource is never exposed.

# Fixed: the file is created owner-only from the start
fd = os.open(dst, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "wb") as out, open(src, "rb") as inp:
    shutil.copyfileobj(inp, out)

Other options include copying into a private directory, then moving into place, and setting a restrictive process umask before extraction. Using O_EXCL also stops the copy from following a pre-planted file.

Quick check

Why is chmod after copy unsafe?

Because the file exists with its default permissions until the chmod runs, and other processes can open it in that window.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.