TExcelTAD
Home › Cybersecurity › Input Validation & Path Handling

Input Validation & Path Handling

Every value that reaches your program from outside (form fields, URLs, headers, uploaded files, API payloads, even data from your own database that users once wrote) is untrusted input. Input validation checks that it has the expected shape before it is used. It doesn't replace context-specific defences like parameterized queries and output escaping, but it removes a huge class of surprises.

Allow-list, don't block-list

There are two ways to validate:

  • Block-list (deny-list): reject inputs that contain known bad things (<script>, ', ../). Attackers find encodings and variants you didn't think of.
  • Allow-list: accept only inputs that match exactly what you expect (an integer from 1 to 100, a username of 3–20 letters, digits and underscores). Everything else is rejected.

Prefer allow-lists. Validate on the server (client-side checks are a usability feature; attackers skip them), and validate type, length, range and format.

python · try it yourself
import re

USERNAME = re.compile(r"[a-z0-9_]{3,20}")
COUNTRY_CODES = {"DE", "FR", "GB", "US", "VN"}

def validate_signup(form):
    errors = {}
    username = form.get("username", "")
    if not USERNAME.fullmatch(username):
        errors["username"] = "3-20 characters: lowercase letters, digits, _"
    try:
        age = int(form.get("age", ""))
        if not 13 <= age <= 120:
            errors["age"] = "must be between 13 and 120"
    except ValueError:
        errors["age"] = "must be a whole number"
    if form.get("country") not in COUNTRY_CODES:
        errors["country"] = "unknown country"
    return errors or "OK"

print(validate_signup({"username": "ada_l", "age": "36", "country": "GB"}))
print(validate_signup({"username": "Ada Lovelace!", "age": "-1", "country": "XX"}))
print(validate_signup({"username": "bob", "age": "1e3", "country": "US"}))
OK
{'username': '3-20 characters: lowercase letters, digits, _', 'age': 'must be between 13 and 120', 'country': 'unknown country'}
{'age': 'must be a whole number'}

fullmatch matters: re.match only anchors at the start, so ada_l<script> would pass a pattern checked with match if you forget the $. This is a very common validation bug.

Normalise first, then validate

The same text can be written in several ways. Unicode has look-alike and compatibility characters (fullwidth script, the ligature fi), and paths and URLs have encodings (%2e%2e%2f is ../). If you validate one form and later use another, checks can be bypassed. The rule: decode and normalise to a canonical form once, then validate, then use that same value.

python · try it yourself
import unicodedata

def canonical_username(raw):
    return unicodedata.normalize("NFKC", raw).casefold().strip()

samples = ["Admin", "ADMIN", "admin ", "ᴬdmin"]
reserved = "admin"
for raw in samples:
    canon = canonical_username(raw)
    print(f"{raw!r:<16} -> {canon!r:<10} reserved={canon == reserved}")
'Admin'          -> 'admin'    reserved=True
'ADMIN'          -> 'admin'    reserved=True
'admin\xa0'      -> 'admin'    reserved=True
'ᴬdmin'          -> 'admin'    reserved=True

Without normalisation, someone could register ADMIN (fullwidth letters), which looks like "ADMIN" on screen but is a different string from the reserved name.

Path traversal

Path traversal happens when a user-supplied file name is joined to a directory and the result escapes it: a request for ../../etc/passwd reads a system file. The robust defence is to resolve the final path and check that it is still inside the base directory. Here it is with pathlib.PurePosixPath, which works on paths as strings (no file system needed):

python · try it yourself
import posixpath
from pathlib import PurePosixPath
from urllib.parse import unquote

BASE = PurePosixPath("/srv/app/uploads")

def safe_path(user_name: str):
    name = unquote(user_name)                        # decode %2e%2e%2f etc. once
    if "\x00" in name:
        return None                                  # NUL bytes: reject outright
    joined = posixpath.normpath(posixpath.join(str(BASE), name))
    candidate = PurePosixPath(joined)
    if candidate == BASE or BASE not in candidate.parents:
        return None
    return candidate

for request in ["report.pdf", "2026/invoice-7.pdf", "../../etc/passwd",
                "%2e%2e/%2e%2e/etc/passwd", "/etc/passwd", "a/../../uploads2/x"]:
    result = safe_path(request)
    print(f"{request:<26} -> {result if result else 'REJECTED'}")
report.pdf                 -> /srv/app/uploads/report.pdf
2026/invoice-7.pdf         -> /srv/app/uploads/2026/invoice-7.pdf
../../etc/passwd           -> REJECTED
%2e%2e/%2e%2e/etc/passwd   -> REJECTED
/etc/passwd                -> REJECTED
a/../../uploads2/x         -> REJECTED

Notes on the details:

  • posixpath.join(base, "/etc/passwd") returns /etc/passwd: an absolute user path replaces the base. The containment check catches it.
  • Comparing with startswith("/srv/app/uploads") would wrongly accept /srv/app/uploads2/x. Checking parents compares whole path components.
  • On a real server, also resolve symbolic links (Path.resolve()) before the check, and better still, don't use user-supplied names at all: store uploads under a random ID and keep the original name in the database.

Validating URLs: preventing SSRF

Server-side request forgery (SSRF) happens when a server fetches a URL supplied by a user (a webhook target, an "import from URL" feature) and the user points it at internal systems: http://localhost:8080/admin or the cloud metadata service at 169.254.169.254, which can hand out credentials. A validator should check the scheme and the resolved IP address:

python · try it yourself
import ipaddress
from urllib.parse import urlsplit

def resolve(host):
    # stand-in for DNS so the example runs offline
    fake_dns = {"api.partner.example": "34.120.54.12", "internal.example": "10.0.0.7"}
    return fake_dns.get(host, host)

def url_allowed(url):
    parts = urlsplit(url)
    if parts.scheme not in ("http", "https"):
        return "rejected: scheme"
    if not parts.hostname:
        return "rejected: no host"
    try:
        ip = ipaddress.ip_address(resolve(parts.hostname))
    except ValueError:
        return "rejected: could not resolve"
    if not ip.is_global:
        return f"rejected: {ip} is not a public address"
    return f"allowed ({ip})"

for url in ["https://api.partner.example/hook", "http://internal.example/admin",
            "http://169.254.169.254/latest/meta-data/", "http://127.0.0.1:8080/",
            "file:///etc/passwd", "http://[::1]/"]:
    print(f"{url:<44} {url_allowed(url)}")
https://api.partner.example/hook             allowed (34.120.54.12)
http://internal.example/admin                rejected: 10.0.0.7 is not a public address
http://169.254.169.254/latest/meta-data/     rejected: 169.254.169.254 is not a public address
http://127.0.0.1:8080/                       rejected: 127.0.0.1 is not a public address
file:///etc/passwd                           rejected: scheme
http://[::1]/                                rejected: ::1 is not a public address

In production, make the HTTP client connect to the same IP you checked (to defeat DNS tricks where the name resolves differently the second time), disable redirects or re-validate every hop, and block outbound traffic to internal ranges at the network level as well.

Go further: Path Traversal and SSRF: Allow-Lists and Cloud Metadata take both halves of this lesson further, with detection and fixes.

Test yourself

Why are allow-lists preferred over block-lists for validation?

  1. They are shorter
  2. Attackers find encodings and variants a block-list misses; an allow-list rejects anything unexpected
  3. Block-lists are illegal
  4. Allow-lists don't need testing

A server checks path.startswith("/srv/uploads"). Which path wrongly passes?

  1. /srv/uploads/a.txt
  2. /srv/uploads2/secret.txt
  3. /etc/passwd
  4. uploads/a.txt

What does an SSRF validator need to check besides the URL scheme?

  1. The URL length only
  2. That the resolved IP address is public, not loopback/private/link-local
  3. That the URL ends in .html
  4. Nothing else