Course contentsShow
← Security
Lesson 1163 of 3,05224. Application Security - Input ValidationFree lesson

Null Byte Injection and String Termination

Using null bytes to truncate strings in lower-level processing, bypassing extension checks and path validation.

Null Byte Injection and String Termination

What you'll learn: How attackers use null bytes to prematurely terminate strings in low-level code, bypassing file extension checks and path validations.

The Core Idea

A null byte (represented as \0, %00 in URL encoding, or byte value 0) is used in C and many low-level languages to mark the end of a string. Many modern languages (like PHP, Python, Ruby) pass data to underlying C-based functions for file operations or system calls. If your application validates input in a high-level language but then passes it to C code, attackers can inject a null byte to truncate the string mid-processing—causing the validation and the actual execution to see different strings.

The Classic Attack

Imagine you're building a file download feature that only allows .pdf files. Your validation checks if the filename ends with .pdf. An attacker submits:

document.pdf%00.exe

Your high-level validation sees the full string and approves it (it contains .pdf). But when the C-based file system function processes it, it stops reading at %00 and only sees document.pdf, while the actual file created might be document.pdf (or the system might process different logic entirely).

Common Bypass Scenarios

  • Extension validation: malicious.php%00.jpg passes a ".jpg only" check but executes as PHP
  • Path validation: /safe/path%00/../../etc/passwd truncates before traversal sequences
  • File inclusion: Including files where the extension is appended server-side

Defense

Always validate after canonicalization and use language-native functions that handle null bytes safely. Reject any input containing null bytes explicitly at your trust boundary.

Key Takeaway: Null byte injection exploits the disconnect between high-level string handling and low-level C string termination, allowing attackers to bypass validation by hiding malicious payloads after the null byte.