Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Web applications and APIs

Workbook · Hard · 3 hoursFree account

Secure Coding

Review code, run static and dynamic analysis, catch logic bugs, and patch safely.

  • secure-coding
  • input-validation
  • output-encoding
  • code-review
  • secure-sdlc
On this page 5 sections
  1. ·About This Workbook
  2. ·Chapter 1 — Code Review Fundamentals
  3. Locked: Chapter 2 — Analysis Techniques
  4. Locked: Chapter 3 — Logic Bugs
  5. Locked: Chapter 4 — Patching

The cheapest place to kill a vulnerability is in the source, before it ships. Secure code review is a disciplined read of the code with a security mindset: trust boundaries, dangerous APIs, sinks and the data that reaches them. This workbook covers manual review, static analysis with tools such as Semgrep, dynamic analysis with fuzzing, and the logic bugs that scanners cannot see. Each chapter pairs vulnerable code with a patch and a test that proves the patch holds. The techniques apply to any language, with worked examples in web contexts where injection, deserialization and access control decide the outcome.

What You'll Learn

  • Perform structured secure code review
  • Apply static and dynamic analysis
  • Identify injection and logic flaws
  • Write effective patches

About This Workbook

The best place to stop a vulnerability is in the code, before it reaches a target. This workbook teaches secure code review: how to read code with a security mindset, how to use static and dynamic analysis tools, how to find flaws that scanners miss, and how to write a patch that fixes the flaw without breaking the application.

All code samples in this workbook are short, self-contained snippets that you can read and run on your own machine. None of them target a live site. When a chapter shows an attack string, it is the same kind of string a tester sends against a lab target that they own or are authorized to test — never a real system.

Chapter 1 — Code Review Fundamentals

Objectives

  • Define a trust boundary
  • Name five common dangerous functions and the risk each one carries
  • Describe a repeatable code review workflow
  • Trace a value from an untrusted source to a dangerous sink

Explanation

A trust boundary is the line in a program where data crosses from a part you do not control into a part you do. Data from a web form, a URL, a file upload, an HTTP header, a database row written by another user, or an environment variable is untrusted the first time your code reads it. Code review starts at every point where untrusted data enters.

A source is the place untrusted data enters (a request parameter, a cookie, a file). A sink is a function where that data can cause harm if it is not checked first (a database query, a shell command, a file path, an HTML template, a deserializer). A flaw exists when a value flows from a source to a sink with no check in between. Tracing that flow is called taint tracking, and it is the core skill of code review.

Some functions are dangerous because they let data control behavior instead of only holding a value:

Function (language)RiskSafer alternative
eval() / exec() (Python)Runs a string as codeAvoid; use a fixed set of operations
os.system(), subprocess.run(..., shell=True) (Python)Runs a string as a shell commandsubprocess.run([list, of, args]), no shell
String-built SQL ("SELECT * WHERE id=" + id)SQL injectionParameterized queries / prepared statements
pickle.loads() on untrusted data (Python)Runs arbitrary code during deserializationjson.loads(), or a schema-checked format
innerHTML = with untrusted text (JavaScript)Cross-site scriptingtextContent =, or a templating library that encodes by default
Path built from user input (open(base + user_path))Path traversalCanonicalize and check against an allow-listed base directory

A repeatable review workflow has four steps:

  1. Map the entry points. List every route, form, API endpoint, file read, and message queue consumer. Each one is a source.
  2. Trace the data flow. For each entry point, follow the variable through the code until it reaches a sink or is fully validated.
  3. Check the boundary. At each sink, ask: is this value checked against an allow-list, a type, a length, and a range, before it reaches here?
  4. Confirm with a test. Write or run a small test that sends an unexpected value and observes the result, instead of only reading the code.

A security code review is not a style review. Ignore formatting and naming while you review. Follow only the data: where it comes from, and what function uses it.

Worked example

This small Flask route reads a file name from the URL and serves it from a notes folder.

# notes_app.py — teaching sample, not production code
import os
from flask import Flask, request, send_file

app = Flask(__name__)
NOTES_DIR = "/srv/notes"

@app.route("/notes")
def get_note():
    name = request.args.get("file")          # source: untrusted query parameter
    path = os.path.join(NOTES_DIR, name)      # path is built from the source
    return send_file(path)                    # sink: reads a file at that path

Apply the four-step workflow:

  1. Entry point: the file query parameter on GET /notes.
  2. Data flow: name goes straight into os.path.join, then straight into send_file. No check appears between the source and the sink.
  3. Boundary check: there is none. os.path.join does not stop a value like ../../etc/passwd from leaving the NOTES_DIR folder, because .. is a normal path segment, not something os.path.join removes.
  4. Confirm with a test: on a lab copy of this app, running on your own machine, a request such as GET /notes?file=../../etc/passwd would return a file outside NOTES_DIR. This class of flaw is path traversal. You do not need to run the full attack to confirm the flaw during a review — reading the code is already proof. A tester in an authorized engagement sends one such request only against a target they are scoped to test, to confirm the finding before reporting it.

The fix is in Chapter 4.

Practice questions

1. What is the difference between a source and a sink?

Answer

A source is where untrusted data enters the program. A sink is a function where that data can cause harm if it reaches it unchecked. A flaw is a path from a source to a sink with no check in between.

2. A code review finds cursor.execute("SELECT * FROM users WHERE id=" + user_id). Name the sink, the source, and the flaw class.

Answer

The sink is cursor.execute. The source is user_id, wherever it comes from (typically a request parameter). The flaw class is SQL injection, because the query string is built by concatenation instead of parameters.

3. Why is reading the code enough to report the path-traversal flaw in the worked example, without sending a real attack request?

Answer

The data flow from the file parameter to send_file has no check. That absence is visible in the source and is the actual flaw. A proof-of-concept request on an authorized lab copy confirms the finding; it is not what creates the risk.

Sign in to continue

3 more sections are for signed-in members. It is free: sign in with Google.

Related

This workbook is extra practice for the course Web applications and APIs. Do the lessons first.Open the course