Skip to content

Commit 4635a67

Browse files
committed
Resolved CodeQL warnings about log injection and path traversal
1 parent 97e9757 commit 4635a67

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/murfey/server/demo_api.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ class Settings(BaseSettings):
110110

111111
settings = Settings()
112112

113-
machine_config: dict = {}
113+
machine_config: dict[str, MachineConfig] = {}
114114
if settings.murfey_machine_configuration:
115115
microscope = get_microscope()
116116
machine_config = from_file(Path(settings.murfey_machine_configuration), microscope)
@@ -1290,12 +1290,18 @@ def suggest_path(
12901290
instrument_name = (
12911291
db.exec(select(Session).where(Session.id == session_id)).one().instrument_name
12921292
)
1293-
check_path = (
1294-
machine_config[instrument_name].rsync_basepath / params.base_path
1293+
rsync_basepath = (
1294+
machine_config[instrument_name].rsync_basepath
12951295
if machine_config
1296-
else Path(f"/dls/{get_microscope()}") / params.base_path
1296+
else Path(f"/dls/{get_microscope()}")
12971297
)
1298+
check_path = rsync_basepath / params.base_path
12981299
check_path = check_path.parent / f"{check_path.stem}{count}{check_path.suffix}"
1300+
check_path = check_path.resolve()
1301+
1302+
# Check for path traversal attempt
1303+
if not str(check_path).startswith(str(rsync_basepath)):
1304+
raise Exception(f"Path traversal attempt detected: {str(check_path)!r}")
12991305

13001306
# Check previous year to account for the year rolling over during data collection
13011307
if not sanitise_path(check_path).exists():
@@ -1307,16 +1313,17 @@ def suggest_path(
13071313
base_path_parts[year_idx] = str(int(part) - 1)
13081314
base_path = "/".join(base_path_parts)
13091315
check_path_prev = check_path
1310-
check_path = (
1311-
machine_config[instrument_name].rsync_basepath / base_path
1312-
if machine_config
1313-
else Path(f"/dls/{get_microscope()}") / base_path
1314-
)
1316+
check_path = rsync_basepath / base_path
13151317
check_path = check_path.parent / f"{check_path.stem}{count}{check_path.suffix}"
1318+
check_path = check_path.resolve()
1319+
1320+
# Check for path traversal attempt
1321+
if not str(check_path).startswith(str(rsync_basepath)):
1322+
raise Exception(f"Path traversal attempt detected: {str(check_path)!r}")
13161323

13171324
# If visit is not in the previous year either, it's a genuine error
13181325
if not check_path.exists():
1319-
log_message = (
1326+
log_message = sanitise(
13201327
"Unable to find current visit folder under "
13211328
f"{str(check_path_prev)!r} or {str(check_path)!r}"
13221329
)

0 commit comments

Comments
 (0)