SecurityPart 2: Application security
Chapter 8Secure development lifecycle
In December 2021 a single feature in the Log4j logging library, CVE-2021-44228 or Log4Shell, let anyone run code on a server by getting it to log a crafted string. The hardest part for most companies was not the patch; it was answering "which of our services even use Log4j?". This chapter builds the habits and the pipeline that answer that question in minutes and catch most bugs before they ship.
After this chapter you can
- Place security activities across the lifecycle, from requirements and design review to release
- Review code for security the way practitioners do: from sources to sinks
- Choose between SAST, DAST, fuzzing, dependency scanning and secrets scanning, knowing what each misses
- Design CI security gates that block real problems without drowning developers
- Prioritise vulnerabilities with CVSS, EPSS and the KEV catalog, and run a disclosure or bug bounty program
- Recognise the new failure modes AI coding assistants bring to code and review
Security across the lifecycle
A secure development lifecycle (SDL) puts the right check at the cheapest moment. A missing authorization rule costs a sentence to fix in a design doc, a day in code review, and an incident response if a researcher finds it in production.
Two frameworks give the lifecycle structure. NIST's Secure Software Development Framework (SSDF, SP 800-218) lists the practices an organisation should have, and is what US government buyers ask vendors to attest to. The OWASP Application Security Verification Standard (ASVS, version 5.0 released in May 2025) turns "secure" into hundreds of testable requirements at three levels, so a requirement reads "passwords are stored with an approved password hashing function" rather than "make login secure".
Good security requirements also include abuse cases: the feature story told from the attacker's side. "As a user I can share a document by link" gains "as an attacker I enumerate share links" and "as an ex-employee I keep using a link after my access is revoked".
Design review
Design review catches the bugs no scanner can see: missing authorization, trust in the wrong component, a data flow that should not exist. The threat modeling method itself is in The security mindset; in practice, a design review is an hour with the engineers and a short list of pointed questions.
| Question | The bug it catches |
|---|---|
| Where does untrusted data enter, and which component validates it? | Injection, SSRF, deserialization |
| Who is allowed to do each action, and where is that enforced? | Broken access control, IDOR |
| What does this service trust that it should not? | Confused deputy, forged headers such as a client-set user ID |
| What secrets does it hold, and who can read them? | Credential leaks, over-privileged roles |
| What happens when a dependency fails or times out? | Fail-open authorization, error pages leaking internals |
| How would we know if it were attacked? | No logging of security events |
Write the answers in the design doc. A review that leaves no written decisions behind gets repeated, or forgotten, at the next change.
Secure code review technique
Reading a diff top to bottom is how you miss bugs. Practitioners instead trace data from sources to sinks. A source is where attacker-controlled data enters (request parameters, headers, files, messages, LLM output). A sink is where that data becomes dangerous (a SQL query, a shell, an HTML response, a file path, a URL fetch, a deserializer).
Map the change
What endpoints, jobs or message handlers does it add or modify? Each one is a new entry point.
List sources and sinks
Grep the diff for sinks first:
execute(,subprocess,innerHTML,|safe,open(,requests.get(,pickle.loads,yaml.load. Then list where each handler's input comes from.Trace each path
Follow the data from source to sink. Ask what validation, encoding or parameterization happens on the way, and whether it fits the sink.
Check the authorization story
For every handler: who may call it, and which line of code enforces that for this specific object? An absent line is the most common finding.
Look for what is missing
Rate limits on login and reset, CSRF protection on new forms, logging of security events, timeouts on outbound calls.
Automated testing: SAST, DAST and fuzzing
Automation scales review, but each technique sees a different slice of the problem. Use them together and know their blind spots.
| Technique | How it works | Finds well | Misses |
|---|---|---|---|
| SAST (static analysis) | Parses source and matches patterns or tracks data flow without running it | Injection sinks, dangerous APIs, hardcoded secrets | Business logic, access control, config at runtime |
| DAST (dynamic analysis) | Sends crafted requests to a running app | Reflected XSS, missing headers, misconfiguration | Code paths it cannot reach, logic bugs |
| Fuzzing | Feeds millions of mutated inputs and watches for crashes | Memory corruption, parser bugs, crashes and hangs | Bugs that do not crash or trip an assertion |
| SCA (dependency scanning) | Matches your dependency versions against vulnerability databases | Known CVEs in libraries | Bugs in your own code, and unknown flaws |
Semgrep matches code patterns that look like the code itself, which makes custom rules quick to write. CodeQL compiles code into a database and runs queries over it, with deep cross-file data flow tracking; GitHub runs it as code scanning. Semgrep is usually the faster first gate, while CodeQL finds longer source-to-sink paths.
DAST tools such as ZAP run against a deployed test environment you own, for example zap-baseline.py against staging. They are best at configuration and response-level issues, and they need authenticated scanning to reach anything interesting.
Fuzzing works by coverage guidance: the fuzzer keeps inputs that reach new code and mutates those further. libFuzzer and AFL++ are the standard engines for C and C++, Atheris and Jazzer bring the same idea to Python and Java, and Google's OSS-Fuzz runs them continuously for open-source projects. You write a small harness that hands bytes to the code under test:
#include <stddef.h>
#include <stdint.h>
int parse_header(const uint8_t *data, size_t len);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
parse_header(data, size); /* crashes and sanitizer reports are the findings */
return 0;
}clang -g -O1 -fsanitize=fuzzer,address fuzz_parser.c parser.c -o fuzz_parser
./fuzz_parser corpus/AddressSanitizer turns silent memory corruption, the subject of Memory safety and binary exploitation, into an immediate report with a stack trace, which is why fuzzing and sanitizers are almost always used together.
Dependencies and secrets
Most of the code you ship, often the large majority, is open-source dependencies. Software composition analysis (SCA) reads lockfiles and manifests and matches each package version against databases such as OSV and the GitHub Advisory Database. Tools include OSV-Scanner, Dependabot, npm audit and pip-audit.
Raw SCA output is noisy, so triage on three questions:
- Is the vulnerable function reachable from our code? Some tools now do reachability analysis.
- Is it exploited in the wild? Check KEV and EPSS, below.
- Is there a fixed version, and how disruptive is the upgrade?
Secrets in code are a separate, urgent class. Scanners such as Gitleaks and TruffleHog match token formats and high-entropy strings across the whole git history, because deleting a key in a later commit does not remove it from history. Run them in three places: a pre-commit hook, CI, and the platform's push protection.
Security gates in CI
A gate is a CI check that can fail the build. The design challenge is trust: a gate that blocks on false positives gets disabled within a month.
Rules of thumb that keep gates trusted:
- Block only on new findings in changed code, against a baseline of existing debt that you burn down separately.
- Block only on high-confidence rules. Run noisier rules in report-only mode until you have tuned them.
- Keep the PR gate fast, a few minutes at most; move slow scans to nightly jobs.
- Give every finding a fix message that tells the developer what to write instead.
- Provide a documented escape hatch, such as an inline
nosemgrepcomment with a reason, that is itself reviewed.
Vulnerability management and disclosure
Every scanner produces findings faster than any team can fix them, so vulnerability management is mainly prioritisation. Four public data sources do most of the work.
| Source | What it tells you | Use it for |
|---|---|---|
| CVE | A unique identifier for a publicly known vulnerability | Naming and tracking the same bug across tools |
| CVSS (v4.0 current) | Severity from 0 to 10 based on how a bug can be exploited and its impact | Rough severity, not urgency |
| EPSS | A daily-updated probability that a CVE will be exploited in the next 30 days | Ranking which high-severity issues are likely to be attacked |
| CISA KEV | A catalog of CVEs with evidence of active exploitation, around 1,800 entries by late 2026 | Patch now, regardless of other scores |
A workable policy: anything in KEV that you run gets fixed within days; high EPSS or critical CVSS on internet-facing systems within a short SLA; the rest on a regular cycle. CVSS alone ranks too many bugs as critical to be useful for scheduling.
Not every bug comes from your tools. Publish a security.txt file (RFC 9116) telling researchers where to report, respond quickly, and credit them. A bug bounty pays for valid findings, typically through a platform such as HackerOne or Bugcrowd. Start with a private program and a tight scope; a public bounty on an immature application mostly buys duplicate reports of issues your own scanners should have found.
AI coding assistants and the review problem
AI assistants change both sides of review. They write a large share of new code, and they are increasingly used as reviewers. Each role brings new failure modes.
| Failure mode | What happens | Control |
|---|---|---|
| Insecure patterns at scale | Models reproduce common code, including string-built SQL and disabled TLS checks | SAST gates apply to generated code like any other |
| Hallucinated packages | The assistant imports a package that does not exist; attackers register that name ("slopsquatting") | Dependency allowlists or review of every new dependency |
| Plausible but wrong fixes | A "fix" that silences a scanner without removing the root cause | Require tests that demonstrate the exploit fails |
| Review fatigue | Larger diffs, produced faster, reviewed more shallowly | Smaller PRs, source-to-sink review on risky files |
| Prompt injection via repository content | Comments or docs instruct an agent to weaken code or leak secrets | Least-privilege agent tokens; see Securing AI agents and tool use |
| Secrets in prompts | Developers paste keys or customer data into assistants | Approved tools with data controls, and secrets scanning |
Key terms
- SDL
- Secure development lifecycle: security activities built into each phase of software development.
- Abuse case
- A requirement written from the attacker's perspective, describing how a feature could be misused.
- Source and sink
- Where untrusted data enters a program, and where it can cause harm if mishandled.
- SAST
- Static application security testing: analysing source code without running it.
- DAST
- Dynamic application security testing: probing a running application from outside.
- Coverage-guided fuzzing
- Generating inputs by mutating those that reach new code paths, to find crashes.
- SCA
- Software composition analysis: identifying dependencies and their known vulnerabilities.
- EPSS
- Exploit Prediction Scoring System: the estimated probability a CVE will be exploited in the next 30 days.
- KEV
- CISA's Known Exploited Vulnerabilities catalog of CVEs with evidence of active exploitation.
Build a security pipeline with Semgrep, OSV-Scanner and Gitleaks
Goal: create a small, deliberately flawed repository, add three security gates to GitHub Actions, write and test two custom Semgrep rules, and watch the pipeline fail and then pass.
You need: a free GitHub account, git, and Docker (or Python with pip install semgrep on supported platforms) to run tools locally. This repo is your own sample code; never paste real credentials into it.
-
Create the sample app in a new folder called
sdl-pipeline-lab:app.py import sqlite3 import subprocess from flask import Flask, request app = Flask(__name__) db = sqlite3.connect("shop.db", check_same_thread=False) def require_admin(f): return f # placeholder for a real check @app.route("/product") def product(): pid = request.args["id"] row = db.execute(f"SELECT name FROM products WHERE id = {pid}").fetchone() return {"name": row[0] if row else None} @app.route("/ping") def ping(): out = subprocess.run("ping -c 1 " + request.args["host"], shell=True, capture_output=True) return out.stdout @app.route("/admin/users") def admin_users(): return {"users": [r[0] for r in db.execute("SELECT email FROM users")]} @app.route("/admin/stats") @require_admin def admin_stats(): return {"ok": True}requirements.txt flask==0.12.2 requests==2.19.1 pyyaml==5.3 -
Add a fake secret so the secret scanner has something to find. Generate a random string in GitHub token format:
python3 -c "import secrets,string; print('GITHUB_TOKEN = \"ghp_' + ''.join(secrets.choice(string.ascii_letters+string.digits) for _ in range(36)) + '\"')" > config.py -
Write two house rules. Generic rulesets cannot know your conventions, such as "every
/adminroute needs@require_admin":semgrep-rules/house-rules.yml rules: - id: sql-built-with-string-formatting languages: [python] severity: ERROR message: >- SQL built with string formatting reaches $DB.execute. Pass values as parameters instead, for example db.execute("... WHERE id = ?", (pid,)). pattern-either: - pattern: $DB.execute(f"...", ...) - pattern: $DB.execute("..." + $X, ...) - pattern: $DB.execute("..." % $X, ...) - pattern: $DB.execute("...".format(...), ...) - id: admin-route-missing-require-admin languages: [python] severity: ERROR message: Route $PATH is under /admin but is not decorated with @require_admin. patterns: - pattern: | @$APP.route($PATH, ...) def $FUNC(...): ... - pattern-not: | @$APP.route($PATH, ...) @require_admin def $FUNC(...): ... - metavariable-regex: metavariable: $PATH regex: ^['"]/admin -
Test the rules. A file with the same base name holds annotated examples;
ruleidlines must match andoklines must not:semgrep-rules/house-rules.py from flask import Flask app = Flask(__name__) def bad(db, pid): # ruleid: sql-built-with-string-formatting db.execute(f"SELECT * FROM t WHERE id = {pid}") # ruleid: sql-built-with-string-formatting db.execute("SELECT * FROM t WHERE id = " + pid) def good(db, pid): # ok: sql-built-with-string-formatting db.execute("SELECT * FROM t WHERE id = ?", (pid,)) # ruleid: admin-route-missing-require-admin @app.route("/admin/delete") def delete(): return "deleted" # ok: admin-route-missing-require-admin @app.route("/admin/audit") @require_admin def audit(): return "audit"docker run --rm -v "$PWD:/src" -w /src semgrep/semgrep semgrep --test semgrep-rules/ docker run --rm -v "$PWD:/src" -w /src semgrep/semgrep \ semgrep scan --config semgrep-rules/ --exclude semgrep-rules --metrics=off --error .Expect a line ending in
All tests passed, then two blocking findings inapp.py: the f-string query on the product route and the unprotected/admin/usersroute. -
Add the pipeline:
.github/workflows/security.yml name: security on: pull_request: push: branches: [main] permissions: contents: read jobs: semgrep: runs-on: ubuntu-latest container: image: semgrep/semgrep steps: - uses: actions/checkout@v4 - run: semgrep --test semgrep-rules/ - run: >- semgrep scan --config p/python --config semgrep-rules/ --exclude semgrep-rules --metrics=off --error . dependencies: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: stable - run: go install github.com/google/osv-scanner/v2/cmd/osv-scanner@latest - run: ~/go/bin/osv-scanner scan source -r . secrets: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0 # full history, so old commits are scanned too - run: docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:latest git /repo --redact --verboseIn production, pin each action and image to a full commit SHA or digest rather than a tag; Software supply chain security explains why.
-
Create a new public repository on GitHub named
sdl-pipeline-lab, then commit and push everything tomain. If GitHub's push protection flags the fake token, that is a platform-level secret control doing its job; since the token is random, you may bypass it for this lab. -
Open the Actions tab. All three jobs should fail: Semgrep reports your two house-rule findings plus registry findings such as the
shell=Truecall, OSV-Scanner lists CVEs for the pinned old packages, and Gitleaks reports agithub-patfinding inconfig.pywith the value redacted. -
Fix everything on a branch: parameterize the query, replace the shell call with an argument list and no
shell=True, add@require_adminto/admin/users, upgrade the three packages to current versions, and deleteconfig.py. Open a pull request. -
Notice that Gitleaks still fails: the secret is in the history. Decide, and write down in the PR description, what you would do with a real token: revoke and rotate it, then optionally rewrite history. For the lab, add a
.gitleaksignorefile at the repository root containing theFingerprintvalue Gitleaks printed, and push again. -
In Settings, Branches (or Rules), require the three
securityjobs to pass before merging intomain.
Check your work: the first run shows three red jobs with the expected findings; the pull request shows three green jobs; your custom rule tests pass in CI; and merging is blocked when you open a test PR that reintroduces an f-string query.
Stretch: add a third custom rule for a dangerous pattern of your choice (for example yaml.load without a safe loader, or requests.get with verify=False), with tests. Then add a scheduled nightly workflow that runs CodeQL through GitHub code scanning and compare its findings with Semgrep's.
Check yourself
A team adds a SAST gate that blocks every pull request with any finding, including hundreds of existing ones. What is the most likely outcome?
Which bug is a SAST tool least likely to find on its own?
A developer committed an API key, then removed it in the next commit before pushing both to a public repo. What should happen first?
You have two CVEs to schedule. One has CVSS 9.8 and EPSS 0.2%, not in KEV. The other has CVSS 7.5, is listed in KEV and affects an internet-facing service you run. Which do you fix first?
An AI assistant suggests importing a package name that does not appear on the package registry. What is the main risk if a developer installs whatever later appears under that name?
Recap
- Put each security check where it is cheapest: requirements and design review catch what no scanner can.
- Review code by tracing untrusted data from sources to sinks, and by asking where each authorization check lives.
- SAST, DAST, fuzzing, SCA and secrets scanning each see a different slice; combine them and know their blind spots.
- CI gates stay trusted when they block only new, high-confidence findings and tell developers how to fix them.
- Prioritise with KEV first, EPSS second and CVSS for severity, and give researchers a clear way to report.
- AI assistants speed up both bug creation and review; keep deterministic gates as the floor.
Go deeper
- NIST SP 800-218, Secure Software Development Framework: the reference list of SDL practices.
- OWASP ASVS: testable security requirements to turn into acceptance criteria.
- Semgrep: Write rules: pattern syntax and rule testing for custom rules.
- libFuzzer: how coverage-guided fuzzing and harnesses work in practice.
- FIRST EPSS: the model, data and API for exploit prediction scores.
- CISA Known Exploited Vulnerabilities Catalog: the list of what attackers are using right now.