Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions docs/Secure-Coding-Guide-for-Python/CWE-664/CWE-404/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# CWE-404: Improper Resource Shutdown or Release

Always close resources explicitly and ensure proper cleanup even if an error occurs.

Improper resource shutdown or release happens when a program allocates a resource, such as a file, socket, or database connection, and fails to release it when finished. Unlike normal objects (like numbers or strings), these resources are tied to the operating system and are not freed automatically by garbage collection. If left open, they can pile up and cause memory leaks, file handle exhaustion, or stalled network connections.

In Python, use the `with` statement to ensure handles are cleaned up automatically; note that `with` manages resource cleanup, not memory deallocation. Special care is required for long-running scripts, multiprocessing, or multithreading, where lingering handles can accumulate over time and exhaust system resources.

## Non-Compliant Code Example

In this `noncompliant01.py` code example, two elements are added to the list. Although the list continues to hold these two elements, they are never properly released, leading to retained memory that is never reclaimed. This can cause resource exhaustion or leaks.

[*noncompliant01.py:*](noncompliant01.py)

```py
"""Non-Compliant Code Example"""

my_list = []


def append_resource(name):
print(f"Allocating resource {name}")
resource = {"name": name, "active": True} # Simulated resource
my_list.append(resource)


append_resource("A")
append_resource("B")

# Forgot to release resources
#####################
# attempting to exploit above code example
#####################
for resource in my_list:
print(resource["name"], "active?", resource["active"])

if not any(resource["active"] for resource in my_list):
print("All resources released.")

```

## Compliant Solution

After adding two elements, to the list, the list in this `compliant01.py` code example now contains zero elements because they have been cleared and properly released.

[*compliant01.py:*](compliant01.py)

```py
"""Compliant Code Example"""

my_list = []


def append_resource(name):
print(f"Allocating resource {name}")
resource = {"name": name, "active": True} # Simulated resource
my_list.append(resource)


append_resource("A")
append_resource("B")

# Properly release resources
for resource in my_list:
resource["active"] = False
my_list.clear()


#####################
# attempting to exploit above code example
#####################
for resource in my_list:
print(resource["name"], "active?", resource["active"])

if not any(resource["active"] for resource in my_list):
print("All resources released.")

```

## Related Guidelines

|||
|:---|:---|
|[MITRE CWE](http://cwe.mitre.org/)|Pillar [CWE-664: Improper Control of a Resource Through its Lifetime (4.13) (mitre.org)](https://cwe.mitre.org/data/definitions/664.html)|
|[MITRE CWE](http://cwe.mitre.org/)|Class [CWE-404: Improper Resource Shutdown or Release (4.12)](https://cwe.mitre.org/data/definitions/404.html)|
|[SEI CERT Oracle Coding Standard for Java](https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java)|[EXP04-J. Do not pass arguments to certain Java Collections Framework methods that are a different type than the collection parameter type](https://wiki.sei.cmu.edu/confluence/display/java/EXP04-J.+Do+not+pass+arguments+to+certain+Java+Collections+Framework+methods+that+are+a+different+type+than+the+collection+parameter+type)|

## Bibliography

|||
|:---|:---|
|\[Python Docs\]|<https://docs.python.org/3/tutorial/datastructures.html>|
30 changes: 30 additions & 0 deletions docs/Secure-Coding-Guide-for-Python/CWE-664/CWE-404/compliant01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
"""Compliant Code Example"""

my_list = []


def append_resource(name):
print(f"Allocating resource {name}")
resource = {"name": name, "active": True} # Simulated resource
my_list.append(resource)


append_resource("A")
append_resource("B")

# Properly release resources
for resource in my_list:
resource["active"] = False
my_list.clear()


#####################
# attempting to exploit above code example
#####################
for resource in my_list:
print(resource["name"], "active?", resource["active"])

if not any(resource["active"] for resource in my_list):
print("All resources released.")
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
"""Non-Compliant Code Example"""

my_list = []


def append_resource(name):
print(f"Allocating resource {name}")
resource = {"name": name, "active": True} # Simulated resource
my_list.append(resource)


append_resource("A")
append_resource("B")

# Forgot to release resources
#####################
# attempting to exploit above code example
#####################
for resource in my_list:
print(resource["name"], "active?", resource["active"])

if not any(resource["active"] for resource in my_list):
print("All resources released.")
1 change: 1 addition & 0 deletions docs/Secure-Coding-Guide-for-Python/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ It is __not production code__ and requires code-style or python best practices t
|[CWE-197: Control rounding when converting to less precise numbers](CWE-664/CWE-197/01/README.md)||
|[CWE-209: Generation of Error Message Containing Sensitive Information](CWE-664/CWE-209/README.md)|[CVE-2013-0773](https://www.cvedetails.com/cve/CVE-2013-0773/),<br/>CVSSv3.1:__3.3__,<br/>EPSS: __00.95__ (23.11.2023)|
|[CWE-400: Uncontrolled Resource Consumption](CWE-664/CWE-400/README.md)||
|[CWE-404: Improper Resource Shutdown or Release](CWE-664/CWE-404/README.md)||
|[CWE-409: Improper Handling of Highly Compressed Data (Data Amplification)](CWE-664/CWE-409/README.md)||
|[CWE-410: Insufficient Resource Pool](CWE-664/CWE-410/README.md)||
|[CWE-426: Untrusted Search Path](CWE-664/CWE-426/README.md)|[CVE-2015-1326](https://www.cvedetails.com/cve/CVE-2015-1326),<br/>CVSSv3.0: __8.8__,<br/>EPSS: __00.20__ (23.11.2023)|
Expand Down