Перейти к основному содержимому
Manual Security Code Review: Sinks, Sources & Taint Flows
Урок 22 из 23

Manual Security Code Review: Sinks, Sources & Taint Flows

Trace untrusted input from entry points to dangerous sinks across multi-file web codebases, and combine manual taint analysis with ripgrep and Semgrep to catch logic and injection flaws.

Продвинутый 30 мин Веб-безопасность
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Trace untrusted data from entry sources through helper functions to security-sensitive sinks
  • Choose between sink-first and source-first review strategies depending on the vulnerability class
  • Use ripgrep and custom Semgrep rules to accelerate manual triage across an entire codebase
  • Identify subtle taint-flow bypasses such as double decoding, partial sanitizers, and missing authorization checks

Рекомендуется заранее: Applying OWASP ASVS, Top 10 (2021/2025) & API Top 10Allowlist Input Validation & Context-Aware Output EncodingSecure Database Access: Prepared Statements & Least Privilege

#Why this matters

Automated scanners catch known signatures, outdated dependencies, and single-function bugs, yet they routinely miss the vulnerabilities that cause major breaches. Multi-file taint flows, flawed authorization logic, and custom helper functions that look safe by name often pass every automated check cleanly.

Manual security code review closes that gap. Instead of reading a repository from top to bottom like a novel, an experienced reviewer maps trust boundaries, hunts for high-risk sinks, and proves whether untrusted input can reach them without a valid guard.

#Sources, sinks, and taint flows

Every injection, path traversal, or server-side request forgery (SSRF) bug is a data-flow problem. Untrusted data enters at a source, travels through assignments and function calls, and triggers harm if it reaches a sink without an appropriate sanitizer or allow-list check along the way.

  1. SourceHTTP body, query, header, uploaded filename
  2. TransformParse JSON, URL-decode, pass to helper
  3. GuardAllow-list check, type cast, prepared statement
  4. SinkSQL query, shell command, file open, HTML render

Not every dangerous input comes directly from request.args or $_POST. Second-order sources include values read back from a database, queue messages, archive entry names inside a ZIP upload, and webhook payloads from third-party integrations.

Vulnerability class Common sources Typical sinks (Python / Node / PHP) Required guard
SQL injection Query params, JSON fields cursor.execute, knex.raw, mysqli_query Parameterized query
Command injection Filenames, headers, CLI wrappers subprocess.run(shell=True), exec, shell_exec Argument list, no shell
Path traversal Upload names, path params open, send_file, fs.readFile Canonicalize + base-dir check
SSRF Callback URLs, image fetchers requests.get, fetch, curl_exec Scheme + private-IP allow-list
Template injection Custom themes, error messages render_template_string, Twig::create Static templates + auto-escape

#Sink-first vs. source-first traversal

Trying to read every line of a 100,000-line application wastes hours on boilerplate. Two complementary strategies keep your review focused:

  • Sink-first (bottom-up): Start by searching for high-risk APIs across the repository. Once you find a sink, inspect its arguments and trace backward through callers to see whether any path originates at an untrusted source. This works best for injection, SSRF, unsafe deserialization, and path traversal.
  • Source-first (top-down): Start at the router or controller definitions and follow the request lifecycle forward: authentication middleware, role or ownership checks, input validation, and state changes. This is essential for broken access control (IDOR/BOLA), missing CSRF protection, and multi-step business logic flaws where no "dangerous function" exists.

In a whitebox veb-tahlil assessment, start with ripgrep (rg) to inventory both routes and dangerous sinks in seconds.

Searching a lab repository with ripgrep
$ rg -n "(shell=True|render_template_string|send_file|yaml\.load)" app/
app/routes/export.py:24:    return send_file(target_path, as_attachment=True)
app/utils/archive.py:18:    data = yaml.load(manifest_text, Loader=yaml.Loader)
app/services/diag.py:11:    subprocess.run(f"ping -c 1 {host}", shell=True)

Look closely at line 18 of app/utils/archive.py: yaml.Loader allows arbitrary object instantiation in PyYAML, whereas yaml.SafeLoader (or yaml.safe_load) does not. Meanwhile, send_file on line 24 looks normal until you trace target_path backward through its helper.

app/routes/export.py and app/utils/paths.py
# app/utils/paths.py
import os
from urllib.parse import unquote

def normalize_name(raw: str) -> str:
    # Developer stripped ".." before decoding URL-encoded sequences
    cleaned = raw.replace("..", "")
    return unquote(cleaned)

# app/routes/export.py
def download_report(request):
    name = request.args.get("file", "")
    safe_name = normalize_name(name)
    target_path = os.path.join("/srv/reports", safe_name)
    return send_file(target_path, as_attachment=True)

Here, normalize_name strips ".." before calling unquote(). Sending %2e%2e%2fetc%2fpasswd bypasses .replace("..", ""), decodes to ../etc/passwd, and escapes /srv/reports. Worse, even without URL-encoding, os.path.join("/srv/reports", "/etc/passwd") silently discards the base directory if safe_name starts with a slash.

#Pattern-assisted review with Semgrep

Once manual tracing uncovers a risky pattern, searching with regex alone becomes noisy across comments and multi-line calls. Semgrep parses code into an abstract syntax tree (AST), letting you write structural queries in YAML and sweep the entire repository for variants.

rules/python-sinks.yaml
rules:
  - id: flask-path-join-send-file
    mode: taint
    pattern-sources:
      - pattern: request.args.get(...)
      - pattern: request.form.get(...)
    pattern-sanitizers:
      - pattern: werkzeug.utils.secure_filename(...)
    pattern-sinks:
      - pattern: send_file(...)
    message: Untrusted input flows into send_file without secure_filename.
    languages: [python]
    severity: ERROR

You can run this rule locally with semgrep --config rules/python-sinks.yaml app/. Semgrep taint mode tracks data across local variables and ignores comments, turning a single manual discovery into an automated guard you can drop into CI. Still, never assume a listed sanitizer is sufficient by name alone: always read the sanitizer's implementation and verify it matches the sink context.

#Common mistakes

  • Reading files alphabetically: Auditing models/ before knowing which routes are public or privileged wastes time on unreachable code. Map routes and sinks first.
  • Trusting reassuring function names: Helpers named sanitize_input, safe_path, or is_admin often hide naive string replacements or broken logic. Always read the body.
  • Stopping at the first finding: If one endpoint concatenates SQL or trusts unquote after validation, assume sibling endpoints do too and sweep the codebase with ripgrep or Semgrep.
  • Ignoring missing-control bugs: Sink-first scanning cannot find an endpoint that simply forgot @require_auth or an ownership WHERE user_id = ? clause. Always pair sink-first sweeps with source-first route audits.

#Summary

  • Security code review traces untrusted sources through transformations to sensitive sinks while checking whether valid sanitizers or guards stand on every path.
  • Combine sink-first searches (via ripgrep and Semgrep) for injection, SSRF, and path traversal with source-first route reviews for authentication and authorization gaps.
  • Treat helper functions, second-order data stores, and post-validation decoding or normalization as prime places where taint checks break.
  • Turn manual findings into custom Semgrep rules so the same vulnerability pattern is caught across all sibling files and future pull requests.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания