Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
414 changes: 414 additions & 0 deletions docs/Secure-Coding-Guide-for-Python/CWE-664/CWE-209/README.md

Large diffs are not rendered by default.

51 changes: 51 additions & 0 deletions docs/Secure-Coding-Guide-for-Python/CWE-664/CWE-209/compliant01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """

from pathlib import Path
import random
import logging
import os


def file_reader(args: list):
"""
Compliant example demonstrates split and filter error to the user
It will not go into details on:
- Proper logging
- Proper exception handling for each exception scenario.
"""
filepath = Path(Path.home(), args[0])
# To avoid path traversal attacks,
# use the realpath method
filepath = Path(os.path.realpath(filepath))
# TODO: follow CWE-180: Incorrect Behavior Order: Validate Before Canonicalize.
# Depending on the use case, it can include removing special characters
# from the filename, ensuring it adheres to a predefined regex, etc.
try:
# Restrict provided filepath to a chosen directory
# and throw an exception if user attempt to access confidential areas
if Path.home() not in filepath.parents:
raise PermissionError("Invalid file")
_ = filepath.read_text(encoding='utf8')
except (PermissionError, IsADirectoryError):
error_id = f"{random.getrandbits(64):16x}"

print("***** Backend server-side logging: *****")
logging.exception("ERROR %s", error_id)

# TODO: handle the exception in accordance with
# - CWE-390: Detection of Error Condition without Action
# TODO: log the error with a unique error_id and apply:
# - CWE-117: Improper Output Neutralization for Logs
# - CWE-532: Insertion of Sensitive Information into Log File

# Present a simplified error to the client
print("\n***** Frontend 'client' error: *****")
print(f"ERROR {error_id}: Unable to retrieve file '{filepath.stem}'")


#####################
# Exploiting above code example
#####################
file_reader(["Documents"])
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """

from pathlib import Path


class FileReader:
""" Class that reads files"""
def __init__(self, args: list[str]):
path = Path(Path.home(), args[0])
fh = open(path, 'r', encoding="utf-8")
fh.readlines()


#####################
# exploiting above code example
#####################
fr = FileReader(["Documents"])
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """

from pathlib import Path
import sys


class FileReader:
""" Class that reads files"""
def __init__(self, args: list):
path = Path(Path.home(), args[0])
try:
fh = open(path, 'r', encoding="utf-8")
fh.readlines()
except OSError as e:
# TODO: log the original exception
# For more details, check CWE-693/CWE-778: Insufficient Logging

# Throw a generic exception instead
sys.tracebacklimit = 0
raise Exception("Unable to retrieve file " + str(e.filename)) from None


#####################
# exploiting above code example
#####################
fr = FileReader(["Documents"])
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 """

from pathlib import Path
import sys


class FileReader:
""" Class that reads files"""
def __init__(self, args: list):
path = Path(Path.home(), args[0])
try:
file_handle = open(path, 'r', encoding="utf-8")
file_handle.readlines()
except (PermissionError, FileNotFoundError, IsADirectoryError):
# Re-throw exception without details
sys.tracebacklimit = 0
raise BaseException() from None


#####################
# exploiting above code example
#####################
fr = FileReader(["Documents"])
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 @@ -51,6 +51,7 @@ It is __not production code__ and requires code-style or python best practices t
|[CWE-134: Use of Externally-Controlled Format String](CWE-664/CWE-134/README.md)|[CVE-2022-27177](https://www.cvedetails.com/cve/CVE-2022-27177/),<br/>CVSSv3.1: __9.8__,<br/>EPSS: __00.37__ (01.12.2023)|
|[CWE-197: Numeric Truncation Error](CWE-664/CWE-197/README.md)||
|[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-409: Improper Handling of Highly Compressed Data (Data Amplification)](CWE-664/CWE-409/.)||
|[CWE-410: Insufficient Resource Pool](CWE-664/CWE-410/README.md)||
Expand Down