Safeguard
Application Security•

CWE-666 Operation on a Resource in the Wrong Lifetime Phase

Using a resource before it is ready or after it is released causes corruption and crashes. Know the lifecycle of every resource you touch.

Safeguard Security Team
2 min read

CWE-666 covers code that performs an operation on a resource at the wrong phase of its lifecycle. MITRE describes three phases: initialization, use and release. Each has its own valid operations, and the code needs to be sure the resource is in the expected phase before acting. It applies to files, memory, sockets, locks, handles and objects in any language.

How it happens

Using a resource before it is fully initialized can corrupt data or use incorrect values. Using it after release can read data that belongs to someone else or crash. Releasing twice, or releasing something that was never acquired, breaks the state of whatever manages it.

A short example:

/* Vulnerable: the handler frees the buffer while main code may still use it */
char *buf;

void handler(int sig) { free(buf); }   /* runs at an arbitrary moment */

void work(void) {
    buf = malloc(64);
    /* ...a signal here frees buf mid-use... */
    strcpy(buf, input);
}

The record's example, CVE-2006-5051, is a chain: a signal handler contains too much functionality (CWE-828), introducing a race condition (CWE-362) that leads to a double free (CWE-415).

What an attacker gains

The record lists the consequence as "Other". The impact depends on what the resource is. In the chain above the end state is a double free, a memory corruption class that is often exploitable.

How to find it

Static analysis (SAST) can find some instances by modeling data flow. Add a manual pass: for each resource, write down its phases and check that every operation in the code is valid for the phase the resource will be in at that point, on every path including errors and signals.

How to fix it

MITRE's mitigation is to follow the resource's lifecycle from creation to release. Concretely:

  1. Do not publish a resource until initialization is complete.
  2. Track state explicitly if the phase is not obvious from the code.
  3. Keep release in one place, and clear references after release.
  4. Keep asynchronous handlers small so they cannot release resources the main code is using.

Quick check

What are the three phases MITRE names?

Initialization, use and release.

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.