Programming Search⌘K

Weaknesscore

Improper input validation

Also called insufficient input validation, missing input validation, cwe-20.

Improper input validation happens when a program uses input without a correct check of the properties it needs, such as type, range and format, so values it cannot handle get through.

Abstraction
class
OWASP Top 10 (2025)
A05
CWE Top 25 (2025)
rank 18
Languages affected
any

Description

A program reads data from outside: a form field, a header, a file, a message from another service. Each part of the program assumes that the data has certain properties. A quantity is a positive number. An id has exactly 64 hexadecimal digits. An end date comes after a start date. Improper input validation happens when the program receives input but does not validate, or incorrectly validates, that the input has the properties that it needs to process the data safely and correctly.1 CWE lists the properties to check: quantities, indexes, well-formedness, type, consistency between fields, business rules, equivalence and authenticity.1

The weakness is easy to make for three reasons. The test data that a developer types is always well formed, so the missing check never fails. The checks that exist often look for bad characters, and the real problem is a value that is well formed but wrong, such as a negative quantity. And the checks are often in the wrong place: in the browser, which the attacker controls, or deep in the code, after part of the input was already used.

CWE-20 is a class weakness. It is a child of CWE-707, Improper Neutralization, and it can precede path traversal, injection, out-of-bounds access and allocation without limits.1 CWE discourages its use as the mapping of a real vulnerability, because reports often use it when a more precise weakness fits.1 CWE also separates validation, which checks whether an input is already safe, from techniques that transform input into something safe, such as escaping.1 CWE-20 is rank 18 on the 2025 CWE Top 25, down from rank 12 the year before.3 The OWASP Top 10:2025 maps it to A05:2025 Injection.4

This page is about the check itself. The weaknesses that follow a missing check have their own pages: SQL injection, OS command injection, Path traversal, Integer overflow or wraparound and Uncontrolled resource consumption.

History

The Seven Pernicious Kingdoms taxonomy of 2005 put Input Validation and Representation first of its seven kingdoms. It said that these problems are caused by metacharacters, alternate encodings and numeric representations, and that the security problems result from trusting input.2 CWE-20 came from this taxonomy in July 2006, under the name Insufficient Input Validation. CWE gave it its present name in January 2009.1

Allow lists and deny lists

A deny list names the inputs that are not allowed. CWE-184 describes its usual failure: the list is incomplete.7 There are many encodings and spellings of a bad value, and the list cannot know about the ones that do not exist yet. A deny list also checks the wrong property. It looks for characters that are dangerous in one context, such as a quote, and it does not check what the field means.

An allow list states what each field accepts, and it rejects everything else. The OWASP Input Validation Cheat Sheet says to define what the application accepts, and not to try to recognize every malicious string.5 It notes that blocking apostrophes rejects legitimate names and still does not make a database query safe.5 CWE rates an accept-known-good strategy as highly effective, and gives an example: if the field is a colour, the value "boat" is syntactically valid, but it is not a colour.1

Parse, do not validate

Alexis King gave this slogan in 2019.6 A validator checks a value and then returns the same value, with the same loose type. The rest of the program cannot tell whether the check ran. A parser turns the loose input into a value of a precise type, and it fails when it cannot. After the parse, the type itself carries the result of the check. King advises that the program gets the data into the most precise representation it needs as early as it can, at the boundary of the system and before it acts on any of the data.6 The same post quotes the language-theoretic security term "shotgun parsing": checks mixed with the processing code and spread across it, so that the program may act on part of an input before a later check rejects it.6

Validation at the trust boundary

A trust boundary is the point where data enters from a less trusted place. The server is the place that enforces the check. A check in the browser gives the user fast feedback, but CWE notes that attackers can bypass client-side checks, so the server must duplicate them.1 Data from internal services, queues, partner feeds and the database also crosses a boundary. The cheat sheet lists trust in internal sources as a common pitfall.5

Vulnerable code

The function below takes the fields of an order form as text. It has a deny list of characters that look dangerous, and it converts the quantity with int. The second call sends the quantity -3. This is the case of the first demonstrative example of CWE-20, where the code never checks that the quantity is positive.1

This code runs but gives a wrong answer on purpose.

PRICES = {"pen": 150, "book": 1200}  # in cents
BLOCKED = ("<", ">", "'", '"', ";", "--")


def order_total(product, quantity):
    for bad in BLOCKED:
        if bad in product or bad in quantity:
            raise ValueError("blocked character")
    return PRICES[product] * int(quantity)


print(order_total("book", "2"))
print(order_total("book", "-3"))
print(order_total("book", " 2\n"))
print(order_total("book", "٣"))  # ARABIC-INDIC DIGIT THREE
Output
2400
-3600
2400
3600

The deny list passes every call, because no call has a blocked character. The total of the second order is negative, so the shop would pay the customer. The last two calls show that int is more lenient than the developer thought. It strips white space, and it accepts any Unicode decimal digit. Neither one is an attack, but the program accepts inputs that its author did not plan for.

Fixed code

The fixed code parses the form into an Order at the boundary. The parser checks each field against an allow list: the product must be a key of the price table, and the quantity must be one to three ASCII digits with a value from 1 to 100. It rejects the input and does not try to repair it. The function that computes the total takes an Order, so it cannot get the raw text.

import re
from dataclasses import dataclass

PRICES = {"pen": 150, "book": 1200}  # in cents
QUANTITY = re.compile(r"[0-9]{1,3}")


@dataclass(frozen=True)
class Order:
    product: str
    quantity: int


def parse_order(form):
    product = form.get("product", "")
    if product not in PRICES:
        raise ValueError("unknown product")
    text = form.get("quantity", "")
    if not QUANTITY.fullmatch(text):
        raise ValueError("quantity must be 1 to 3 ASCII digits")
    quantity = int(text)
    if not 1 <= quantity <= 100:
        raise ValueError("quantity must be from 1 to 100")
    return Order(product, quantity)


def order_total(order: Order) -> int:
    return PRICES[order.product] * order.quantity


forms = [
    {"product": "book", "quantity": "2"},
    {"product": "book", "quantity": "-3"},
    {"product": "book", "quantity": " 2\n"},
    {"product": "book", "quantity": "٣"},
    {"product": "book", "quantity": "0"},
    {"product": "boat", "quantity": "1"},
]
for form in forms:
    try:
        print(order_total(parse_order(form)))
    except ValueError as error:
        print("rejected:", error)
Output
2400
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be from 1 to 100
rejected: unknown product

Three details of the pattern matter. It uses fullmatch, because $ in Python also matches before a newline at the end of the string.9 It uses [0-9] and not \d, because \d in a str pattern matches any Unicode decimal digit.9 And the range check comes after the conversion, because a value with the right type can still be the wrong quantity.5 The example files show the same parse in other languages. In Rust and Java, the type system then keeps code outside the parser from making an Order that was not checked.

Canonical form first

A check is true only for the exact value that it checked. If the program changes the value later, by decoding, normalizing or trimming, the check may no longer hold. CWE-179 names this order of steps: the product validates input before it applies the mechanisms that modify it.8 Decode or normalize once, then validate that result, and then use that same result.5 The Python example file shows the effect with Unicode normalization: the compatibility form NFKC changes the ligature ffi into the three letters ffi,10 so a length check made before the normalization does not hold after it.

How to detect it

  • Code review at each entry point. List where data enters: request handlers, message consumers, file readers and the results of calls to other services. For each field, find the code that turns it into a precise value, and check that no code reads the raw value first.
  • Look for lenient conversions. int() in Python, Number() in JavaScript, atoi in C and Integer.parseInt in Java each accept forms that a reader may not expect. The example files show which ones.
  • Fuzzing. CWE lists fuzzing as a detection method for this weakness.1 Go has fuzzing in its standard toolchain.11 A fuzz target that calls the parser and then checks the properties of the result finds inputs that pass the parser but break the rules.
  • Boundary tests. Test zero, negative values, the largest value and one more, empty strings, white space, a trailing newline and non-ASCII digits. The cheat sheet also asks for tests of missing fields, invalid nested items and oversized arrays.5
  • Static analysis. CWE notes that automated static analysis might not recognize when proper validation is performed, which leads to false positives. Custom checks such as business rules need manual analysis.1 A taint tool finds the routes from input to a dangerous function, but it cannot know the rule that a quantity is positive.

How to prevent it

  • Parse into a precise type at the boundary. Code inside the boundary takes the parsed type and never the raw text.6
  • Allow-list each field. State the type, the range, the length, the format and the set of values. Reject anything else, and do not try to repair it.15
  • Check the meaning, not only the syntax. A booking needs an end date after the start date. A quantity needs to be positive.5
  • Decode and normalize once, then validate. Validate the form that the program uses, and do not decode it again later.15
  • Check on the server at every trust boundary. Client-side checks give feedback to the user. They are not a control.15
  • Keep the other defences. Validation reduces the risk, but it does not replace parameterized queries or output encoding.5 A valid account id also does not mean that the caller may access the account, which is a question of Missing authorization.5

Real cases

Case Date What happened
CVE-2008-2223 published 2008-05-14 SQL injection through the tid parameter of vShare YouTube Clone 2.6.12 CWE lists it as an id that was supposed to be numeric and was not checked.1
CVE-2020-3452 published 2020-07-22 Cisco ASA and FTD software did not properly validate URLs in HTTP requests. An unauthenticated attacker could use directory traversal to read sensitive files.13
CVE-2021-22205 published 2021-04-23 GitLab CE/EE from version 11.9 did not properly validate image files that it passed to a file parser, which resulted in remote command execution.14
CVE-2024-37032 published 2024-05-31 Ollama before 0.1.34 did not validate the format of a digest, which must be sha256 with 64 hexadecimal digits, when it built the path of a model. Inputs with fewer or more digits, or with a leading ../, were not rejected.15
PythonGitHub

This code runs but gives a wrong answer on purpose.

PRICES = {"pen": 150, "book": 1200}  # in cents
BLOCKED = ("<", ">", "'", '"', ";", "--")


def order_total(product, quantity):
    for bad in BLOCKED:
        if bad in product or bad in quantity:
            raise ValueError("blocked character")
    return PRICES[product] * int(quantity)


print(order_total("book", "2"))
print(order_total("book", "-3"))
print(order_total("book", " 2\n"))
print(order_total("book", "٣"))  # ARABIC-INDIC DIGIT THREE
Output
2400
-3600
2400
3600
import re
from dataclasses import dataclass

PRICES = {"pen": 150, "book": 1200}  # in cents
QUANTITY = re.compile(r"[0-9]{1,3}")


@dataclass(frozen=True)
class Order:
    product: str
    quantity: int


def parse_order(form):
    product = form.get("product", "")
    if product not in PRICES:
        raise ValueError("unknown product")
    text = form.get("quantity", "")
    if not QUANTITY.fullmatch(text):
        raise ValueError("quantity must be 1 to 3 ASCII digits")
    quantity = int(text)
    if not 1 <= quantity <= 100:
        raise ValueError("quantity must be from 1 to 100")
    return Order(product, quantity)


def order_total(order: Order) -> int:
    return PRICES[order.product] * order.quantity


forms = [
    {"product": "book", "quantity": "2"},
    {"product": "book", "quantity": "-3"},
    {"product": "book", "quantity": " 2\n"},
    {"product": "book", "quantity": "٣"},
    {"product": "book", "quantity": "0"},
    {"product": "boat", "quantity": "1"},
]
for form in forms:
    try:
        print(order_total(parse_order(form)))
    except ValueError as error:
        print("rejected:", error)
Output
2400
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be from 1 to 100
rejected: unknown product

This code runs but gives a wrong answer on purpose.

import unicodedata

MAX_LENGTH = 10


def save_name(raw):
    if len(raw) > MAX_LENGTH:
        raise ValueError("name too long")
    name = unicodedata.normalize("NFKC", raw)
    return name


name = save_name("\ufb03" * 10)
print(len(name), name)
Output
30 ffiffiffiffiffiffiffiffiffiffi
import unicodedata

MAX_LENGTH = 10


def save_name(raw):
    name = unicodedata.normalize("NFKC", raw)
    if len(name) > MAX_LENGTH:
        raise ValueError("name too long")
    return name


print(save_name("Zoe"))
try:
    save_name("\ufb03" * 10)
except ValueError as error:
    print("rejected:", error)
Output
Zoe
rejected: name too long
  • Verdict: stdlib. Python has no validation framework in the standard library, but re.fullmatch, int, dataclasses and unicodedata are enough to write a parser for each field.
  • int accepts surrounding white space, an underscore between digits, a sign, and any Unicode decimal digit. Check the text with a pattern before the conversion when the field must have one exact form.
  • In a str pattern, \d matches any Unicode decimal digit, and $ also matches before a trailing newline. Use [0-9] and fullmatch, or compile with re.ASCII.
  • A frozen dataclass keeps a parsed value from changing later. Python does not stop other code from calling Order(...) with bad values, so the rule "build it only with the parser" is a convention. Add a check in __post_init__ to enforce it.
  • The ligature \ufb03 (ffi) is one character. NFKC turns it into three letters. Ten of them pass the length check of the first function and come out as a name of 30 characters. The second function normalizes first and checks the value it stores.
JavaGitHub

This code runs but gives a wrong answer on purpose.

import java.util.Map;

public class Main {
    static final Map<String, Integer> PRICES = Map.of("pen", 150, "book", 1200); // in cents

    static int orderTotal(String product, String quantity) {
        return PRICES.get(product) * Integer.parseInt(quantity);
    }

    public static void main(String[] args) {
        System.out.println(orderTotal("book", "2"));
        System.out.println(orderTotal("book", "-3"));
        System.out.println(orderTotal("book", "٣")); // ARABIC-INDIC DIGIT THREE
    }
}
Output
2400
-3600
3600
import java.util.Map;
import java.util.regex.Pattern;

public class Main {
    static final Map<String, Integer> PRICES = Map.of("pen", 150, "book", 1200); // in cents
    static final Pattern QUANTITY = Pattern.compile("[0-9]{1,3}");

    record Order(String product, int quantity) {
        Order {
            if (!PRICES.containsKey(product)) {
                throw new IllegalArgumentException("unknown product");
            }
            if (quantity < 1 || quantity > 100) {
                throw new IllegalArgumentException("quantity must be from 1 to 100");
            }
        }

        static Order parse(String product, String quantity) {
            if (!QUANTITY.matcher(quantity).matches()) {
                throw new IllegalArgumentException("quantity must be 1 to 3 ASCII digits");
            }
            return new Order(product, Integer.parseInt(quantity));
        }

        int total() {
            return PRICES.get(product) * quantity;
        }
    }

    public static void main(String[] args) {
        String[][] inputs = {{"book", "2"}, {"book", "-3"}, {"book", "٣"}, {"book", "0"}, {"boat", "1"}};
        for (String[] in : inputs) {
            try {
                System.out.println(Order.parse(in[0], in[1]).total());
            } catch (IllegalArgumentException e) {
                System.out.println("rejected: " + e.getMessage());
            }
        }
    }
}
Output
2400
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be from 1 to 100
rejected: unknown product
  • Verdict: stdlib. java.util.regex checks the form, Integer.parseInt converts, and a record with a compact constructor keeps the range rule.
  • Integer.parseInt accepts every character for which Character.digit returns a value, so it accepts digits from other scripts, such as ٣. It also accepts a leading + or -.
  • Matcher.matches requires the whole input to match. find searches for a match anywhere, which is not a check of the whole value.
  • The compact constructor of the record runs for every new Order(...), so no code can make an Order with a quantity of 0, even code that does not call parse.
  • Jakarta Bean Validation adds annotations such as @Min and @Pattern for the same rules. It is a library, not part of Java SE.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *inputs[] = {"2", "-3", "3 apples", "", "abc"};
    for (int i = 0; i < 5; i++) {
        int quantity = atoi(inputs[i]);
        printf("\"%s\" -> %d, total %d\n", inputs[i], quantity, 1200 * quantity);
    }
    return 0;
}
Output
"2" -> 2, total 2400
"-3" -> -3, total -3600
"3 apples" -> 3, total 3600
"" -> 0, total 0
"abc" -> 0, total 0
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

/* Returns 0 and sets *out when text is 1 to 3 ASCII digits with a value
   from 1 to 100. Returns -1 otherwise. */
static int parse_quantity(const char *text, int *out) {
    int len = 0;
    for (const char *p = text; *p != '\0'; p++, len++) {
        if (*p < '0' || *p > '9' || len >= 3) {
            return -1;
        }
    }
    if (len == 0) {
        return -1;
    }
    char *end;
    errno = 0;
    long value = strtol(text, &end, 10);
    if (errno != 0 || *end != '\0' || value < 1 || value > 100) {
        return -1;
    }
    *out = (int)value;
    return 0;
}

int main(void) {
    const char *inputs[] = {"2", "-3", "3 apples", "", "abc", "0", "100"};
    for (int i = 0; i < 7; i++) {
        int quantity;
        if (parse_quantity(inputs[i], &quantity) != 0) {
            printf("\"%s\" rejected\n", inputs[i]);
        } else {
            printf("\"%s\" -> %d, total %d\n", inputs[i], quantity, 1200 * quantity);
        }
    }
    return 0;
}
Output
"2" -> 2, total 2400
"-3" rejected
"3 apples" rejected
"" rejected
"abc" rejected
"0" rejected
"100" -> 100, total 120000
  • Verdict: stdlib. strtol from <stdlib.h> reports where the number ends and sets errno on overflow; the caller writes the checks.
  • atoi has no way to report an error. It returns 0 for "" and for "abc", and 3 for "3 apples". POSIX says that its behaviour is undefined if the value cannot be represented, so a long string of digits is not only wrong but undefined.
  • strtol skips leading white space and accepts a sign. To know that the whole string was a number, check that *end is '\0'. To know that it fits, set errno to 0 before the call and check it after.
  • The parser also limits the length before the conversion. A quantity in C often becomes a size or an index next, where a wrong value is an Out-of-bounds write and not only a wrong total.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

const PRICES = { pen: 150, book: 1200 }; // in cents

function orderTotal(form) {
  const quantity = Number(form.quantity);
  if (Number.isNaN(quantity)) {
    throw new Error("not a number");
  }
  return PRICES[form.product] * quantity;
}

for (const quantity of ["2", "-3", "", "0x10", "1e3"]) {
  console.log(JSON.stringify(quantity), orderTotal({ product: "book", quantity }));
}
console.log(orderTotal({ product: "constructor", quantity: "1" }));
Output
"2" 2400
"-3" -3600
"" 0
"0x10" 19200
"1e3" 1200000
NaN
const PRICES = new Map([["pen", 150], ["book", 1200]]); // in cents

function parseOrder(form) {
  if (typeof form.product !== "string" || !PRICES.has(form.product)) {
    throw new Error("unknown product");
  }
  if (typeof form.quantity !== "string" || !/^[0-9]{1,3}$/.test(form.quantity)) {
    throw new Error("quantity must be 1 to 3 ASCII digits");
  }
  const quantity = Number(form.quantity);
  if (quantity < 1 || quantity > 100) {
    throw new Error("quantity must be from 1 to 100");
  }
  return Object.freeze({ product: form.product, quantity });
}

function orderTotal(order) {
  return PRICES.get(order.product) * order.quantity;
}

const forms = [
  { product: "book", quantity: "2" },
  { product: "book", quantity: "-3" },
  { product: "book", quantity: "" },
  { product: "book", quantity: "0x10" },
  { product: "book", quantity: "1e3" },
  { product: "constructor", quantity: "1" },
];
for (const form of forms) {
  try {
    console.log(orderTotal(parseOrder(form)));
  } catch (error) {
    console.log("rejected:", error.message);
  }
}
Output
2400
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: unknown product
  • Verdict: stdlib. JavaScript has no validation library in the language, but a regular expression, Number and Map are enough for a parser per field.
  • Number ignores white space at both ends, reads 0x as hexadecimal and accepts exponents and Infinity. It turns an empty string into 0. A check for NaN alone misses all of these.
  • A plain object as an allow list also answers for keys from Object.prototype. In the first program, PRICES["constructor"] is a function, so the product name passes the lookup and the total is NaN. Use a Map, an object made with Object.create(null), or Object.hasOwn.
  • In a JavaScript pattern without the m flag, $ matches only at the end of the input, so ^...$ matches the whole string. A pattern with the m flag matches at each line end.
  • Types in TypeScript do not exist at run time. A parameter typed as number still gets whatever the JSON had. Parse at the boundary, then give the rest of the code the parsed type.

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"strconv"
)

var prices = map[string]int{"pen": 150, "book": 1200} // in cents

func orderTotal(product, quantity string) (int, error) {
	n, err := strconv.Atoi(quantity)
	if err != nil {
		return 0, err
	}
	return prices[product] * n, nil
}

func main() {
	for _, q := range []string{"2", "-3", "+2"} {
		total, err := orderTotal("book", q)
		fmt.Println(q, total, err)
	}
	total, err := orderTotal("boat", "1")
	fmt.Println("boat", total, err)
}
Output
2 2400 <nil>
-3 -3600 <nil>
+2 2400 <nil>
boat 0 <nil>
package main

import (
	"errors"
	"fmt"
	"strconv"
)

var prices = map[string]int{"pen": 150, "book": 1200} // in cents

// Order has unexported fields. Code in other packages can only get one
// from ParseOrder, so every Order it sees was checked.
type Order struct {
	product  string
	quantity int
}

func ParseOrder(product, quantity string) (Order, error) {
	if _, ok := prices[product]; !ok {
		return Order{}, errors.New("unknown product")
	}
	if len(quantity) < 1 || len(quantity) > 3 {
		return Order{}, errors.New("quantity must be 1 to 3 ASCII digits")
	}
	for _, c := range []byte(quantity) {
		if c < '0' || c > '9' {
			return Order{}, errors.New("quantity must be 1 to 3 ASCII digits")
		}
	}
	n, err := strconv.Atoi(quantity)
	if err != nil {
		return Order{}, err
	}
	if n < 1 || n > 100 {
		return Order{}, errors.New("quantity must be from 1 to 100")
	}
	return Order{product, n}, nil
}

func (o Order) Total() int { return prices[o.product] * o.quantity }

func main() {
	inputs := [][2]string{{"book", "2"}, {"book", "-3"}, {"book", "+2"}, {"boat", "1"}}
	for _, in := range inputs {
		order, err := ParseOrder(in[0], in[1])
		if err != nil {
			fmt.Println("rejected:", err)
			continue
		}
		fmt.Println(order.Total())
	}
}
Output
2400
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: unknown product
  • Verdict: stdlib. strconv converts and reports errors; the parser adds the checks of format and range.
  • strconv.Atoi accepts a leading + or -. It rejects white space and non-ASCII digits. It returns an error when the value does not fit in an int.
  • A missing key in a Go map gives the zero value. In the first program, the unknown product boat costs 0, and no error is reported. Use the two-value form v, ok := m[k].
  • Unexported fields make the parsed type a real guarantee across packages: other packages can only get an Order from ParseOrder. Inside the same package, code can still write Order{}, so keep the type in a small package of its own.
  • go test -fuzz runs a fuzz target in the standard toolchain. A target that calls ParseOrder and checks that every accepted order has a quantity from 1 to 100 tests the rule directly.
RustGitHub
mod order {
    pub struct Order {
        product: &'static str,
        quantity: u8,
    }

    const PRICES: [(&str, u32); 2] = [("pen", 150), ("book", 1200)]; // in cents

    impl Order {
        pub fn parse(product: &str, quantity: &str) -> Result<Order, String> {
            let (name, _) = PRICES
                .iter()
                .find(|(name, _)| *name == product)
                .ok_or("unknown product")?;
            if quantity.is_empty() || quantity.len() > 3 || !quantity.bytes().all(|b| b.is_ascii_digit()) {
                return Err("quantity must be 1 to 3 ASCII digits".into());
            }
            let quantity: u8 = quantity.parse().map_err(|_| "quantity is too large")?;
            if !(1..=100).contains(&quantity) {
                return Err("quantity must be from 1 to 100".into());
            }
            Ok(Order { product: name, quantity })
        }

        pub fn total(&self) -> u32 {
            let (_, price) = PRICES.iter().find(|(name, _)| *name == self.product).unwrap();
            price * u32::from(self.quantity)
        }
    }
}

fn main() {
    for (product, quantity) in [("book", "2"), ("book", "-3"), ("book", "+2"), ("book", "300"), ("boat", "1")] {
        match order::Order::parse(product, quantity) {
            Ok(order) => println!("{}", order.total()),
            Err(error) => println!("rejected: {error}"),
        }
    }
}
Output
2400
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity must be 1 to 3 ASCII digits
rejected: quantity is too large
rejected: unknown product

This code does not compile, on purpose.

mod order {
    pub struct Order {
        product: &'static str,
        quantity: u8,
    }
}

fn main() {
    let order = order::Order { product: "book", quantity: 0 };
    let _ = order;
}
  • Verdict: stdlib. str::parse into a sized integer type and a struct with private fields give "parse, do not validate" with no library.
  • Parsing to u8 rejects -3 and values above 255 by the type alone. The range check from 1 to 100 still has to be written.
  • u8::from_str accepts a leading +, so "+2" parses to 2. The parser rejects it before the conversion, because the field allows digits only.
  • The fields of Order are private to the module order. The second program tries to build an Order with quantity 0 from outside the module, and the compiler rejects it. So every Order in the program came from Order::parse.

References

  1. CWE-20: Improper Input Validation, Description; Extended Description; Relationships; Modes Of Introduction; Potential Mitigations; Detection Methods; Demonstrative Examples, Example 1; Observed Examples; Notes; Mapping Notes; Content History
  2. Katrina Tsipenyuk, Brian Chess and Gary McGraw, Seven Pernicious Kingdoms: A Taxonomy of Software Security Errors, NIST Workshop on Software Security Assurance Tools, Techniques and Metrics, November 2005, the list of the seven kingdoms; section 1, Input Validation and Representation
  3. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 18, Rank Last Year
  4. OWASP Top 10:2025, A05:2025 Injection, List of Mapped CWEs
  5. OWASP Cheat Sheet Series, Input Validation Cheat Sheet, Introduction; Input Validation Strategies; Allowlist vs Denylist; Parse Safely, Then Validate; Validating Free-form Unicode Text; Regular Expressions (Regex); Common Pitfalls
  6. Alexis King, Parse, don't validate, 5 November 2019, the introduction; the section on the power of parsing, with the quotation on shotgun parsing; the list of practical advice
  7. CWE-184: Incomplete List of Disallowed Inputs, Description; Alternate Terms
  8. CWE-179: Incorrect Behavior Order: Early Validation, Description
  9. The Python Standard Library, re, Python 3.14, Regular Expression Syntax, the entries for $ and \d; Module Contents, re.fullmatch
  10. The Python Standard Library, unicodedata, Python 3.14, unicodedata.normalize
  11. Go documentation, Go Fuzzing, Overview
  12. CVE-2008-2223, vShare YouTube Clone, the description and the publication date
  13. CVE-2020-3452, Cisco ASA and FTD Software, the description, the CWE and the publication date
  14. CVE-2021-22205, GitLab CE/EE, the description and the publication date
  15. CVE-2024-37032, Ollama, the description and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/PAFC4G/text.yaml