FAQ - Help and questions

How do I turn untrusted strings into checked types instead of re-validating everywhere?

#security#validation#typespublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Parse the input once at the edge into a type that can only hold valid values, using a newtype with a private field and TryFrom. The rest of the program takes that type, so an unchecked string can never reach it. Use an allow-list of what is valid, not a block-list of what is bad.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A String can contain anything. If every function that receives a user name has to remember to check it, one of them will forget. Make the check part of the type: construct a Username only through a function that validates, keep its field private, and let every other function ask for a Username.

src/main.rsrust
use std::fmt;

/// A user name that has already been checked. Code that takes a `Username` never re-checks.
#[derive(Debug, Clone, PartialEq)]
pub struct Username(String);

#[derive(Debug, PartialEq)]
pub enum UsernameError {
    Empty,
    TooLong,
    BadCharacter(char),
}

impl fmt::Display for UsernameError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            UsernameError::Empty => write!(f, "user name is empty"),
            UsernameError::TooLong => write!(f, "user name is longer than 32 characters"),
            UsernameError::BadCharacter(c) => write!(f, "user name contains {c:?}"),
        }
    }
}

impl TryFrom<&str> for Username {
    type Error = UsernameError;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        if s.is_empty() {
            return Err(UsernameError::Empty);
        }
        if s.chars().count() > 32 {
            return Err(UsernameError::TooLong);
        }
        if let Some(c) = s.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) {
            return Err(UsernameError::BadCharacter(c));
        }
        Ok(Username(s.to_string()))
    }
}

fn greet(name: &Username) -> String {
    format!("hello {}", name.0)
}

fn main() {
    for input in ["ada_l", "", "bob; DROP TABLE users", "line\nbreak", &"x".repeat(40)] {
        match Username::try_from(input) {
            Ok(u) => println!("{}", greet(&u)),
            Err(e) => println!("rejected: {e}"),
        }
    }
}
text
hello ada_l
rejected: user name is empty
rejected: user name contains ';'
rejected: user name contains '\n'
rejected: user name is longer than 32 characters

(In a real program the type lives in its own module so that the field is private to it; in one file the compiler cannot enforce that.)

How to do it#

  1. List what is valid (length, allowed characters), rather than what is dangerous.
  2. Count characters with chars().count() when the limit is about text, and use len() for bytes when the limit is about storage.
  3. Return a specific error type, so callers and logs say what was wrong without echoing the whole input.
  4. Use the same approach for e-mail addresses, IDs, file names, sort keys and anything else with rules.
  5. Do the check at the boundary: right where the data enters the program.

Common mistakes#

  • Block-lists ("reject ; and '"). Attackers find the character you forgot.
  • Validating, then using the original string. Use the parsed value, so what you checked is what you use.
  • Normalisation after validation. If Unicode text is compared or stored in a normalised form, normalise first, then validate.

Does validation replace escaping or parameterised queries?#

No. Validation reduces what can enter; output encoding and parameterised queries are still required where the data is used. See the threads on SQL queries and on path traversal.

Where do the checks go in a web framework?#

In the extractor or the function that turns the request into your types, so handlers only ever see checked values.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet