Repository navigation
Expand file tree
/
Copy pathcompliant01.py
More file actions
51 lines (43 loc) · 1.84 KB
/
Copy pathcompliant01.py
File metadata and controls
51 lines (43 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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 pyscg-0044: Canonicalize Input Before Validating
# 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
# - pyscg-0016: Propagate Exceptions and Preserve Context
# TODO: log the error with a unique error_id and apply:
# - pyscg-0022: Neutralize Untrusted Data in Logs
# - pyscg-0019: Exclude Sensitive Data From Logs
# 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"])