Skip to content
Path traversal Write-up Intermediate

Pwn for fun: path traversal bypass using NFKD in sanitize-filename on PyPI

Version 1.2.0 of the Python sanitize-filename package filtered path separators before applying NFKD Unicode normalisation, so fullwidth slash characters survived the blacklist and were later converted into ASCII slashes. An attacker could therefore make sanitize() return a path traversal payload that, when joined to a base directory, escapes it and may read files the application account can access.

yeswehack.com

Published on yeswehack.com

Welcome to Pwn for Fun, our new series dissecting vulnerabilities affecting open-source projects.

The author, on yeswehack.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

This is the first entry in a series that dissects vulnerabilities in open-source projects. The subject is a CWE-22 path traversal flaw in version 1.2.0 of the Python package sanitize-filename, published on PyPI and imported as sanitize_filename. The package has now been fixed.

The package's job is to turn an untrusted filename into something safe to use on disk. Its sanitize() function removes path separators and characters the package treats as invalid, strips control characters, trims surrounding whitespace, and preserves the rest of the name. The intended behaviour is simple: a relative path such as ../outside.txt should come back as a single harmless filename.

JavaScript
1from sanitize_filename import sanitize2
3print(sanitize("../outside.txt"))4# ..outside.txt

Removing the ASCII slash collapses the relative path into one filename. That is the contract an application relies on when it joins the sanitised value to a trusted upload directory.

Setup

The proof of concept uses version 1.2.0 from PyPI together with the Python standard library modules unicodedata and posixpath. No accounts, roles or remote services are involved. The precondition for exploitation is an application that calls sanitize() on user-controlled input and then uses the result as a path component, for example by joining it to a base directory.

Finding it

The researcher describes the bug as the kind of flaw you meet in a Capture the Flag challenge. The approach was to trace every operation a filename sanitiser performs, in the order it performs them: decoding, normalisation, filtering and shortening. The question asked at each step is whether a later operation can recreate a dangerous character after validation has already passed.

In version 1.2.0 the order is wrong. The package filters the path first and only then applies NFKD normalisation, so the filter inspects one string and the filesystem later receives another.

Exploitation

Step 1: map the order of operations

The relevant lines of version 1.2.0 run in this sequence:

JavaScript
1blacklist = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|", "\0"]2# ...3filename = "".join(c for c in filename if c not in blacklist)4# ...5filename = "".join(c for c in filename if 31 < ord(c))6filename = unicodedata.normalize("NFKD", filename)

The first filtering line drops every character in the blacklist, which includes the backslash and the forward slash. The second line drops control characters by keeping only characters whose code point is above 31. Only after both checks does unicodedata.normalize("NFKD", filename) rewrite the string.

That ordering is the whole vulnerability. NFKD compatibility decomposition maps several fullwidth Unicode characters onto their ASCII equivalents. The researcher searched for characters that survive the blacklist but normalise into filesystem path syntax, and found fullwidth characters that do.

Step 2: send fullwidth slashes through sanitize()

The first payload places fullwidth slashes (U+FF0F) between ordinary ASCII .. components and the target path:

JavaScript
1from sanitize_filename import sanitize2
3payload = "\uFF0F..\uFF0F..\uFF0F..\uFF0Fetc\uFF0Fpasswd"4print(sanitize(payload))5# /../../../etc/passwd

The payload travels through the function like this:

  1. The blacklist looks for the ASCII slash /. Every separator in the input is U+FF0F instead, so nothing is removed.
  2. U+FF0F is not a control character, so the control-character check leaves it alone as well.
  3. NFKD normalisation converts each fullwidth slash into an ASCII /.
  4. The later trimming, reserved-name and length checks do not remove the newly created separators.
  5. The function returns the normalised string without checking for separators a second time.

The blacklist validated one sequence of characters; the filesystem receives a different one. Normalisation manufactures exactly the path syntax the blacklist existed to remove.

Step 3: show the escape with a realistic join

A minimal script reproduces the effect an application would see when it joins the sanitised value to an upload directory:

JavaScript
1import posixpath2from sanitize_filename import sanitize3
4base_directory = "/var/app/uploads"5payload = "\uFF0F..\uFF0F..\uFF0F..\uFF0Fetc\uFF0Fpasswd"6sanitized = sanitize(payload)7final_path = posixpath.join(base_directory, sanitized)8
9print(sanitized)10# Output: /../../../etc/passwd11
12print(posixpath.normpath(final_path))13# Output: /etc/passwd

The sanitised value is /../../../etc/passwd. Because it begins with a slash it is an absolute path, and posixpath.join() discards the base directory when a later segment is absolute. Normalising the result resolves the .. components and lands on /etc/passwd, well outside /var/app/uploads.

Root cause

The mistake is the order of operations: the blacklist filter and the control-character filter run before NFKD normalisation, and the output of normalisation is never re-validated. NFKD compatibility decomposition is lossy with respect to the security checks, because it maps fullwidth characters such as U+FF0F onto ASCII characters that the blacklist would otherwise have rejected.

Two separate escape mechanisms combine here. The ../ sequences climb out of the permitted directory, and the leading slash turns the result into an absolute path that overrides the base directory in os.path.join()/posixpath.join(). Applications need to reject both forms, and a sanitiser that only inspects the pre-normalised string rejects neither.

Impact

If an application joins the sanitised value to a trusted base directory, the absolute path replaces that directory and the resolved path escapes it. An attacker may then reach any file that the application's operating system account is allowed to read. The impact is bounded by that account's permissions and by whether the application actually uses the returned value in a file operation; the report does not describe a specific affected application.

Fix

The vulnerability has been fixed in the package. The report does not describe the patch itself.

Variants to test

  • Other fullwidth or compatibility characters that decompose to path syntax under NFKD, such as fullwidth backslash, colon or dot forms. A positive result is a sanitize() output containing /, \ or .. that was absent from the input.
  • Sanitisers that normalise after filtering in other languages and ecosystems. Feed a payload built from compatibility characters and check whether the returned value differs from the filtered one.
  • Absolute-path handling: any payload that comes back starting with / or \ is a candidate for overriding a base directory in a join.
  • Reserved-name and length checks that run after normalisation: confirm whether they can be bypassed by characters that only become meaningful once decomposed.

Hunting notes

This class of bug hides in filename and path sanitisers, upload handlers and archive extractors, anywhere a string is filtered and then transformed. During review, list the operations in execution order and look for any transformation, decoding or normalisation that runs after a blacklist or allowlist. A sanitiser that returns a value containing separators it claims to strip is the signal. The report demonstrates impact with a script showing the sanitised value and the normalised join result.

From the original on yeswehack.com
Article hero image
Article hero image

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

What happened, in plain words

A small Python package called sanitize-filename has one job: take a filename that came from a user and make it safe to use on disk. Version 1.2.0 of that package did the job in the wrong order, and as a result a crafted filename could slip past its safety checks and come back out as a path that points outside the folder the application intended to use.

Think of a building receptionist who is told to cross out any visitor badge that contains the word "basement". A visitor writes "base-ment" with a hyphen. The receptionist reads it, sees no "basement", and lets them through. Later, a clerk who tidies up badges removes the hyphen, and now the badge says "basement". The check happened before the tidying, so the tidying undid the check. That is exactly the shape of this bug: the package filters the filename first and only afterwards rewrites it into a different form, and the rewritten form contains the dangerous characters the filter was supposed to remove.

The researcher found it while researching the package, not by attacking a live website. The report calls it the kind of flaw you meet in a Capture the Flag challenge, meaning a deliberately planted puzzle in a security competition. The package has since been fixed.

Background: what the package does

sanitize-filename is published on PyPI. PyPI is the public warehouse where Python programmers download reusable code packages, a bit like an app store for programming libraries. You install the package under the name sanitize-filename and, inside your Python program, you import it under the name sanitize_filename. The two names differ only in the hyphen versus the underscore, which is a Python naming convention.

The package's central function is sanitize(). You give it a filename, and it returns a cleaned-up version. According to the report, it removes path separators and characters the package treats as invalid, strips control characters, trims surrounding whitespace, and keeps the rest of the name.

A path separator is the character that separates folder names in a file path. On Linux and macOS the forward slash / does this, so /home/ana/notes.txt means the file notes.txt inside the folder ana, inside the folder home. On Windows the backslash \ does the same job. If a filename contains a separator, it is no longer just a name: it describes a route through folders.

A control character is an invisible character that was originally used to send instructions to printers and terminals, such as a newline or a bell. They have no place in a filename, so sanitisers remove them.

The intended behaviour is simple. Give it a relative path such as ../outside.txt and it should hand back a single harmless filename:

JavaScript
1from sanitize_filename import sanitize2
3print(sanitize("../outside.txt"))4# ..outside.txt

Line by line:

  1. from sanitize_filename import sanitize loads the sanitize function out of the installed package so the program can call it. This is Python's way of saying "fetch this tool from that toolbox".
  2. The blank line is just spacing.
  3. print(sanitize("../outside.txt")) calls sanitize on the text ../outside.txt and prints whatever comes back. The .. part is special in file paths: it means "the folder one level up". So ../outside.txt means "the file outside.txt in the parent folder".
  4. The comment # ..outside.txt shows the result. The slash was removed, so the two dots and the filename were glued together into ..outside.txt, which is now just an odd-looking but harmless single filename.

That is the promise an application relies on. The application takes a name from a user, runs it through sanitize(), and then sticks the result onto the end of a trusted folder path, expecting the file to land inside that folder.

Background: what path traversal is

Path traversal, also called a dot-dot-slash attack, is a class of bug where user-supplied input lets a file operation escape the folder it was supposed to stay in. The formal catalogue of software weaknesses gives it the number CWE-22, short for "Improper Limitation of a Pathname to a Restricted Directory".

Picture an application that stores uploaded files in /var/app/uploads. If the application takes the name ../outside.txt from a user and glues it onto that folder, the resulting path is /var/app/uploads/../outside.txt. The .. means "go up one level", so the real location is /var/app/outside.txt, which is outside the uploads folder. The user has effectively walked out of the room they were confined to.

Python programs often glue path pieces together with a function called os.path.join(). Its behaviour has a sharp edge: if any later piece is an absolute path, meaning it starts with a slash, the function throws away everything that came before it. So os.path.join("/var/app/uploads", "/etc/passwd") does not produce /var/app/uploads/etc/passwd; it produces /etc/passwd. The base folder is simply discarded.

That gives an attacker two separate ways out of the folder: a chain of ../ pieces that climb upwards, or a value that starts with a slash and therefore replaces the base folder entirely. A correct application has to reject both. The report makes this point explicitly.

Background: what NFKD normalisation is

Computers store text as numbers called code points. Every character has one. The letter A is U+0041, the digit 7 is U+0037, and so on. Unicode, the standard that assigns these numbers, also defines several characters that look like other characters but are technically different.

One example is the fullwidth slash, U+FF0F. It is a slash drawn to occupy the same width as a Chinese or Japanese character, so it looks like / rather than /. It exists so that text in East Asian scripts can line up neatly. To a human it is obviously a slash. To a computer comparing characters one by one, it is a completely different character from the ordinary ASCII slash U+002F.

Normalisation is the process of rewriting text into a standard form so that equivalent-looking strings compare equal. NFKD is one specific normalisation form. Its full name is compatibility decomposition, and its practical effect here is that it maps fullwidth characters back onto their ordinary ASCII equivalents. After NFKD, U+FF0F becomes the plain /.

This is useful for display and comparison, but it is dangerous when it runs after a security check. The check inspects one string; the filesystem later receives a different one.

The setup

The proof of concept uses version 1.2.0 from PyPI with the Python standard library modules unicodedata and posixpath.

The precondition for real-world exploitation is an application that calls sanitize() on input a user controls and then uses the returned value as part of a file path, for example by joining it to a base folder. Without such an application, the bug is a flaw in a library, not an attack on a live system.

How the researcher found it

The approach was to trace every operation the sanitiser performs, in order. When reviewing a filename sanitiser, the researcher traces every operation it performs, in the order it performs them: decoding, normalisation, filtering and shortening. At each step the question is whether a later operation can recreate a dangerous character after validation has already passed.

In version 1.2.0 the order is wrong. The package filters the path first and only then applies NFKD normalisation, so the filter inspects one string and the filesystem later receives another.

Step 1: map the order of operations

The relevant lines of version 1.2.0 run in this sequence:

JavaScript
1blacklist = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|", "\0"]2# ...3filename = "".join(c for c in filename if c not in blacklist)4# ...5filename = "".join(c for c in filename if 31 < ord(c))6filename = unicodedata.normalize("NFKD", filename)

Line by line:

  1. blacklist = ["\\", "/", ":", "*", "?", "\"", "<", ">", "|", "\0"] defines a list of characters the package refuses to allow. The list includes the backslash, the forward slash, the colon, the asterisk, the question mark, the double quote, the angle brackets, the pipe and the null character. These are characters that cause trouble on at least one operating system's filesystem, so the package bans them outright. A blacklist, in security, is a list of things you forbid; the opposite, an allowlist, is a list of things you permit and nothing else.
  2. # ... is a comment meaning "other code sits here that the report is not showing".
  3. filename = "".join(c for c in filename if c not in blacklist) walks over every character c in the filename and keeps only those not in the blacklist, then glues the survivors back together with "".join(...). This is the filter step. It is the moment the package believes it has removed the dangerous characters.
  4. # ... again marks omitted code.
  5. filename = "".join(c for c in filename if 31 < ord(c)) is the control-character filter. ord(c) returns the numeric code point of the character c, and 31 < ord(c) keeps only characters whose number is above 31. Code points 0 to 31 are the classic control characters, so this line drops them.
  6. filename = unicodedata.normalize("NFKD", filename) is the normalisation step, and it runs last. It rewrites the already-filtered string into NFKD form.

That ordering is the whole vulnerability. The filter has already finished by the time normalisation changes the string. The researcher searched for characters that survive the blacklist but normalise into filesystem path syntax, and found fullwidth characters that do.

Step 2: send fullwidth slashes through sanitize()

The first payload places fullwidth slashes, U+FF0F, between ordinary ASCII .. components and the target path:

JavaScript
1from sanitize_filename import sanitize2
3payload = "\uFF0F..\uFF0F..\uFF0F..\uFF0Fetc\uFF0Fpasswd"4print(sanitize(payload))5# /../../../etc/passwd

Line by line:

  1. from sanitize_filename import sanitize loads the function, as before.
  2. The blank line is spacing.
  3. payload = "\uFF0F..\uFF0F..\uFF0F..\uFF0Fetc\uFF0Fpasswd" builds the attack string. In Python, \uFF0F is how you write the character with code point FF0F inside a string literal, so each of those escapes is one fullwidth slash. Between them sit ordinary ASCII dots and the ordinary words etc and passwd. The result, if you printed it, would look like /../../../etc/passwd.
  4. print(sanitize(payload)) runs the attack string through the sanitiser and prints the result.
  5. # /../../../etc/passwd is the output. Every fullwidth slash has become an ordinary slash, and the string now reads as a path that climbs up three folders and then points at etc/passwd.

The payload travels through the function like this:

  1. The blacklist looks for the ASCII slash /. Every separator in the input is U+FF0F instead, so nothing is removed. The filter compares characters exactly, and U+FF0F is not U+002F.
  2. U+FF0F is not a control character, so the control-character check leaves it alone as well.
  3. NFKD normalisation converts each fullwidth slash into an ASCII /.
  4. The later trimming, reserved-name and length checks do not remove the newly created separators. Trimming removes whitespace at the ends; reserved-name checks reject names like CON on Windows; length checks cap how long a name may be. None of them looks for slashes.
  5. The function returns the normalised string without checking for separators a second time.

The blacklist validated one sequence of characters; the filesystem receives a different one. Normalisation manufactures exactly the path syntax the blacklist existed to remove.

Step 3: show the escape with a realistic join

A minimal script reproduces the effect an application would see when it joins the sanitised value to an upload folder:

JavaScript
1import posixpath2from sanitize_filename import sanitize3
4base_directory = "/var/app/uploads"5payload = "\uFF0F..\uFF0F..\uFF0F..\uFF0Fetc\uFF0Fpasswd"6sanitized = sanitize(payload)7final_path = posixpath.join(base_directory, sanitized)8
9print(sanitized)10# Output: /../../../etc/passwd11
12print(posixpath.normpath(final_path))13# Output: /etc/passwd

Line by line:

  1. import posixpath loads Python's Unix-style path module, which provides join and normpath.
  2. from sanitize_filename import sanitize loads the sanitiser.
  3. The blank line is spacing.
  4. base_directory = "/var/app/uploads" sets the trusted folder the application intends to use. This is the room the user is supposed to stay in.
  5. payload = "\uFF0F..\uFF0F..\uFF0F..\uFF0Fetc\uFF0Fpasswd" is the same attack string as before.
  6. sanitized = sanitize(payload) runs it through the sanitiser and stores the result.
  7. final_path = posixpath.join(base_directory, sanitized) glues the trusted folder and the sanitised value together, exactly as a careless application would. posixpath.join is the Unix-flavoured sibling of os.path.join and has the same sharp edge: an absolute later piece discards the earlier ones.
  8. The blank line is spacing.
  9. print(sanitized) prints the sanitised value on its own.
  10. # Output: /../../../etc/passwd shows that value. It begins with a slash, so it is an absolute path.
  11. The blank line is spacing.
  12. print(posixpath.normpath(final_path)) tidies the joined path, resolving .. pieces, and prints the result. normpath is the function that collapses a/b/../c into a/c.
  13. # Output: /etc/passwd is the final location. The base folder has vanished and the path points at the system's password file.

The sanitised value is /../../../etc/passwd. Because it begins with a slash it is an absolute path, and posixpath.join() discards the base folder when a later piece is absolute. Normalising the result resolves the .. pieces and lands on /etc/passwd, well outside /var/app/uploads.

Root cause

The mistake is the order of operations: the blacklist filter and the control-character filter run before NFKD normalisation, and the output of normalisation is never re-validated. NFKD compatibility decomposition is lossy with respect to the security checks, because it maps fullwidth characters such as U+FF0F onto ASCII characters that the blacklist would otherwise have rejected.

Two separate escape mechanisms combine here. The ../ sequences climb out of the permitted folder, and the leading slash turns the result into an absolute path that overrides the base folder in os.path.join() or posixpath.join(). Applications need to reject both forms, and a sanitiser that only inspects the pre-normalised string rejects neither.

Impact

If an application joins the sanitised value to a trusted base folder, the absolute path replaces that folder and the resolved path escapes it. An attacker may then reach any file that the application's operating system account is allowed to read. The impact is bounded by that account's permissions and by whether the application actually uses the returned value in a file operation. The report does not describe a specific affected application.

Fix

The vulnerability has been fixed in the package. The report does not describe the patch itself.

Variants to test

  • Other fullwidth or compatibility characters that decompose to path syntax under NFKD, such as fullwidth backslash, colon or dot forms. A positive result is a sanitize() output containing /, \ or .. that was absent from the input.
  • Sanitisers that normalise after filtering in other languages and ecosystems. Feed a payload built from compatibility characters and check whether the returned value differs from the filtered one.
  • Absolute-path handling: any payload that comes back starting with / or \ is a candidate for overriding a base folder in a join.
  • Reserved-name and length checks that run after normalisation: confirm whether they can be bypassed by characters that only become meaningful once decomposed.

Hunting notes

This class of bug hides in filename and path sanitisers, upload handlers and archive extractors, anywhere a string is filtered and then transformed. During review, list the operations in execution order and look for any transformation, decoding or normalisation that runs after a blacklist or allowlist. A sanitiser that returns a value containing separators it claims to strip is the signal. The report demonstrates impact with a script showing the sanitised value and the normalised join result.

From the original on yeswehack.com
Article hero image
Article hero image

Glossary

  • Absolute path: a file path that starts at the root of the filesystem, such as /etc/passwd, and therefore does not depend on any current folder.
  • Allowlist: a list of things that are permitted, with everything else rejected.
  • ASCII: the basic character set that includes the ordinary Latin letters, digits and punctuation such as the plain slash /.
  • Blacklist: a list of things that are forbidden, with everything else allowed.
  • Capture the Flag (CTF): a security competition in which participants solve deliberately planted challenges to find hidden flags.
  • Code point: the number Unicode assigns to a character, written like U+FF0F.
  • Control character: an invisible character with a code point from 0 to 31, originally used to send instructions to terminals and printers.
  • CWE-22: the catalogue number for path traversal, formally "Improper Limitation of a Pathname to a Restricted Directory".
  • Fullwidth character: a character drawn to occupy the same width as East Asian characters, such as the fullwidth slash U+FF0F, which looks like / but is a different character.
  • NFKD: a Unicode normalisation form, compatibility decomposition, that rewrites characters such as fullwidth forms into their ordinary equivalents.
  • Normalisation: rewriting text into a standard form so that equivalent-looking strings compare equal.
  • os.path.join() / posixpath.join(): Python functions that glue path pieces together, discarding earlier pieces when a later piece is absolute.
  • Path separator: the character that separates folder names in a path, / on Unix-like systems and \ on Windows.
  • Path traversal (dot-dot-slash): a bug where user input lets a file operation escape its intended folder, usually via ../ or an absolute path.
  • Payload: the crafted input an attacker sends to trigger a bug.
  • Proof of concept: a small script or set of steps that demonstrates a vulnerability is real.
  • PyPI: the public package index where Python libraries are published and downloaded.
  • Relative path: a path interpreted from the current folder, such as ../outside.txt.
  • Reserved name: a filename that an operating system forbids, such as CON on Windows.
  • sanitize(): the function in the sanitize-filename package that cleans a filename.
  • sanitize-filename / sanitize_filename: the Python package under discussion, installed under the hyphenated name and imported under the underscored one.
  • unicodedata.normalize(): the Python function that applies a Unicode normalisation form such as NFKD to a string.

Similar reports

View all

Same bug class and techniques, clearest first.

Path traversal and file inclusion

The lesson behind this report.

Input that builds a file path escapes the intended folder, reading or writing files the application should never touch.