Secure Coding and Input Validation

Write code that handles untrusted input safely using validation, output encoding, parameterised queries and safe defaults.

Intermediate · about 10 hours · difficulty 3/5

Learn first: Threat Modelling with STRIDE, HTTP for Security Work

Most application vulnerabilities come from a handful of recurring mistakes. As a defender or developer, your goal is to make them structurally hard to introduce.

Core principles

  • Treat all input as untrusted: request parameters, headers, files, webhooks, messages from other services, even data from your own database if users wrote it.
  • Validate on the server with allow-lists: expected type, length, range and format. Reject rather than try to "clean" bad input.
  • Encode output for its context: HTML, attributes, JavaScript, URLs and SQL each need different handling. Modern template engines and frameworks auto-escape; do not disable that.
  • Keep code and data separate: use parameterised queries or an ORM for databases, and pass arguments as arrays instead of building shell commands from strings.
  • Fail safely: generic error messages to users, detailed errors to logs.
  • Least privilege: database users and service accounts get only the permissions they need.

Other safe defaults

  • Use vetted libraries for authentication, password hashing and cryptography instead of writing your own.
  • Enforce authorisation checks on every request server-side, not only in the UI.
  • Set secure cookie flags and security headers such as Content-Security-Policy.
  • Log security-relevant events without logging secrets or personal data unnecessarily.

Learning references

The OWASP Top 10 describes the most common risk categories, and the OWASP Cheat Sheet Series gives concrete defensive guidance per topic.

Pitfalls

  • Relying on client-side validation alone.
  • Deny-list filters that miss encodings and edge cases.

Good enough to move on: you can review a small code sample, point out where untrusted input reaches a query, command or page, and rewrite it using the safe pattern.

Key concepts

  • Untrusted input sources
  • Server-side allow-list validation
  • Context-aware output encoding
  • Parameterised queries
  • Server-side authorisation checks
  • Safe error handling and logging
  • Security headers and CSP
  • OWASP Top 10 categories

Mini project

Take a small CRUD app you wrote, add schema-based input validation on every endpoint, switch any string-built queries to parameterised ones, add security headers and document each change in a pull request.

Check yourself

Why is allow-list validation preferred over trying to strip dangerous characters from input?

Free resources