DAST with ZAP

Test the running app as a job service, then fix what it finds.

Advanced13 min · lesson 15 of 17
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (19 files, 7 KB): dast.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/ci-gitlab/dast.tar.gz && tar -xzf dast.tar.gz, which creates ~/lab/dast/. SHA-256: fa91b1b463ec2930edd03529d7099aeba6b1e62e34379c6112eca51e30cc7901

SAST reads the code, and dependency and image scans read package lists. None of them sees what the running application sends back: the headers, the cookies, the error pages. Dynamic application security testing (DAST) sends requests to a running app and checks the responses. GitLab's own DAST needs the Ultimate tier. ZAP, the open-source scanner GitLab's earlier DAST analyzer was built on, runs in an ordinary job on any tier.

THE DEFENSE-IN-DEPTH SCAN PIPELINE
1test
SAST + secret detection + SCA (source & deps)
2build
build the container image
3scan-image
Trivy scans image, gates the registry push
4deploy-staging
deploy a live test instance
5dast
OWASP ZAP probes the running staging app
6deploy-prod
manual, protected environment
Each stage catches what the others miss; every stage reports fully but gates only on the actionable subset.

The app

webapp/server.py
"""A tiny web app for the DAST lab. It sets a session cookie and sends no security headers."""
from http.server import BaseHTTPRequestHandler, HTTPServer
HARDENED = False # the solution flips this
class App(BaseHTTPRequestHandler):
def do_GET(self):
body = b"<html><head><title>Lab shop</title></head><body><h1>Lab shop</h1><a href='/about'>About</a></body></html>"
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
if HARDENED:
self.send_header("Set-Cookie", "session=abc123; HttpOnly; Secure; SameSite=Strict; Path=/")
self.send_header("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'")
self.send_header("X-Content-Type-Options", "nosniff")
else:
self.send_header("Set-Cookie", "session=abc123; Path=/")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
HTTPServer(("0.0.0.0", 8000), App).serve_forever()

A shop page with a session cookie and no security headers. Build its image on the runner's host, so a job can start it as a service, and check what it sends. That works only because the lab runner uses a local image when one exists. In production, push the app image to a registry and start the service from it by digest:

ubuntu@secopslog-cicd:~/lab/dast · GitLab 19.5.3
$ ./up.sh
runner lab-runner: online (tags: lab,docker) GitLab 19.5.3 is up on http://127.0.0.1:8929
$ docker build -q -t secopslog-dastapp:1 webapp >/dev/null && docker run -d --rm --name lab-dastapp-probe secopslog-dastapp:1 >/dev/null && sleep 2 && docker exec lab-dastapp-probe python -c "import urllib.request as u; r=u.urlopen(\"http://127.0.0.1:8000\"); print(r.status, dict(r.headers)[\"Set-Cookie\"])"; docker rm -f lab-dastapp-probe >/dev/null
200 session=abc123; Path=/

ZAP against a job service

app/.gitlab-ci.yml
# DAST against the running app: the app starts as a service, ZAP's baseline scan crawls it and
# checks the responses passively. GitLab's own DAST needs the Ultimate tier; ZAP runs on any tier.
dast:
image:
name: zaproxy/zap-stable:2.17.0@sha256:9624669db72f54d86c4b46a7064518bd9bf79d8c61a4c31befa9923489f328af
entrypoint: [""]
services:
- name: secopslog-dastapp:1
alias: app
script:
- mkdir -p /zap/wrk && cp zap-rules.tsv /zap/wrk/
# One scan. Exit codes: 0 clean, 1 a FAIL rule matched, 2 warnings only, 3 the scan itself broke.
- zap-baseline.py -t http://app:8000 -c zap-rules.tsv -J zap.json -m 1 > zap.log 2>&1 || rc=$?
- cp /zap/wrk/zap.json . || true
- grep -E '^(FAIL-NEW|WARN-NEW|Total of)' zap.log | sed -E 's/ x [0-9]+.*$//'
- echo "zap-baseline exit code ${rc:-0}"
- test "${rc:-0}" -eq 0 || test "${rc:-0}" -eq 2
artifacts:
when: always
paths: [zap.json, zap.log]

services starts the app next to the job, reachable as app. zap-baseline.py crawls it for a minute and checks every response passively: it reads what comes back and sends nothing an attack would. The rules file decides what each check means for the pipeline:

app/zap-rules.tsv
10010 FAIL (Cookie No HttpOnly Flag)
10038 FAIL (Content Security Policy Header Not Set)

Checks listed as FAIL fail the job, and everything else stays a warning. The baseline script exits 2 when there are only warnings, which the job accepts, and 1 on a failure.

ubuntu@secopslog-cicd:~/lab/dast · GitLab 19.5.3
$ ./seed.sh app app/ && PIPE_WAIT=900 ./pipeline.sh app/; exit ${PIPESTATUS[0]}
pushed app: 7f0db5e first commit --- job dast (test): failed Starting service secopslog-dastapp:1... Waiting for services to be up and running (timeout 30 seconds)... $ mkdir -p /zap/wrk && cp zap-rules.tsv /zap/wrk/ $ zap-baseline.py -t http://app:8000 -c zap-rules.tsv -J zap.json -m 1 > zap.log 2>&1 || rc=$? $ cp /zap/wrk/zap.json . || true $ grep -E '^(FAIL-NEW|WARN-NEW|Total of)' zap.log | sed -E 's/ x [0-9]+.*$//' Total of 4 URLs WARN-NEW: Missing Anti-clickjacking Header [10020] WARN-NEW: X-Content-Type-Options Header Missing [10021] WARN-NEW: Server Leaks Version Information via "Server" HTTP Response Header Field [10036] WARN-NEW: Storable and Cacheable Content [10049] WARN-NEW: Cookie without SameSite Attribute [10054] WARN-NEW: Permissions Policy Header Not Set [10063] WARN-NEW: Cross-Origin-Embedder-Policy Header Missing or Invalid [90004] FAIL-NEW: Cookie No HttpOnly Flag [10010] FAIL-NEW: Content Security Policy (CSP) Header Not Set [10038] FAIL-NEW: 2 FAIL-INPROG: 0 WARN-NEW: 7 WARN-INPROG: 0 INFO: 0 IGNORE: 0 PASS: 59 $ echo "zap-baseline exit code ${rc:-0}" zap-baseline exit code 1 $ test "${rc:-0}" -eq 0 || test "${rc:-0}" -eq 2 Uploading artifacts... zap.json: found 1 matching artifact files and directories zap.log: found 1 matching artifact files and directories Uploading artifacts as "archive" to coordinator... 201 Created correlation_id=01M743133Y0P769CS2GRMW0WZS id=1 status=201 token=64_BAms_U ERROR: Job failed: exit code 1 pipeline #1: failed

ZAP crawled four URLs and reported nine problems. The two in the rules file are FAIL-NEW: the cookie has no HttpOnly flag, so page scripts can read it, and there is no Content Security Policy. The other seven are warnings, among them X-Content-Type-Options missing and a Server header that gives away the server version. zap-baseline exit code 1 failed the job, and zap.json and zap.log were kept as artifacts, because they are when: always.

Fix the app

The fix sets HttpOnly, Secure and SameSite on the cookie and sends a Content Security Policy and X-Content-Type-Options. Rebuild the image and run the pipeline again:

ubuntu@secopslog-cicd:~/lab/dast · GitLab 19.5.3
$ cp solutions/server.py webapp/ && docker build -q -t secopslog-dastapp:1 webapp >/dev/null && ./gl.sh "/projects/root%2Fapp/pipeline" -X POST -d ref=main -o /dev/null && sleep 3 && PIPE_WAIT=900 ./pipeline.sh app/
--- job dast (test): success Starting service secopslog-dastapp:1... Waiting for services to be up and running (timeout 30 seconds)... Removing zap.json Removing zap.log $ mkdir -p /zap/wrk && cp zap-rules.tsv /zap/wrk/ $ zap-baseline.py -t http://app:8000 -c zap-rules.tsv -J zap.json -m 1 > zap.log 2>&1 || rc=$? $ cp /zap/wrk/zap.json . || true $ grep -E '^(FAIL-NEW|WARN-NEW|Total of)' zap.log | sed -E 's/ x [0-9]+.*$//' Total of 4 URLs WARN-NEW: Server Leaks Version Information via "Server" HTTP Response Header Field [10036] WARN-NEW: Storable and Cacheable Content [10049] WARN-NEW: CSP: Failure to Define Directive with No Fallback [10055] WARN-NEW: Permissions Policy Header Not Set [10063] WARN-NEW: Cross-Origin-Embedder-Policy Header Missing or Invalid [90004] FAIL-NEW: 0 FAIL-INPROG: 0 WARN-NEW: 5 WARN-INPROG: 0 INFO: 0 IGNORE: 0 PASS: 63 $ echo "zap-baseline exit code ${rc:-0}" zap-baseline exit code 2 $ test "${rc:-0}" -eq 0 || test "${rc:-0}" -eq 2 Uploading artifacts... zap.json: found 1 matching artifact files and directories zap.log: found 1 matching artifact files and directories Uploading artifacts as "archive" to coordinator... 201 Created correlation_id=01M7433R23MBMTD3XD9D3NQSG1 id=2 status=201 token=64_CAkjmi pipeline #2: success

No failures, and the job passed with zap-baseline exit code 2: warnings only. Both failing checks and three of the warnings are gone, and a new warning appeared, CSP: Failure to Define Directive with No Fallback. ZAP can only judge a policy once there is one. Five warnings remain, and they stay warnings until you decide otherwise.

TestLooks atFinds
SASTSource codeDangerous calls, weak crypto
Dependency scanningPinned package versionsKnown vulnerable libraries
Container scanningPackages in an imageKnown vulnerable OS packages
DAST baseline (passive)Responses of the running appMissing headers, weak cookies, information leaks
DAST active scanThe app under attackInjection and other exploitable bugs
Watch out
An active scan sends real attacks: it fills forms, injects payloads and can change or delete data. Run it only against an environment you own and can reset, never against production or a site you don't control. The baseline scan used here is passive, but its spider still follows every link with a GET request, and a GET that logs out or deletes something still does it. Run even the baseline against a disposable copy, like this service container, not a shared environment. An unauthenticated scan also only sees what a logged-out visitor sees.

Hands-on

The fixed app still produces warnings. Make one of them fail the pipeline: add the line 10036\tFAIL\t(Server Leaks Version Information) to app/zap-rules.tsv (the separators are tabs, so printf it rather than typing it), push with ./commit.sh and run ./pipeline.sh app/. What does the app reveal, and how would you remove it? Finish with ./down.sh.

What you should see: FAIL-NEW: Server Leaks Version Information via "Server" HTTP Response Header Field [10036], exit code 1, and a failed pipeline. Python's built-in HTTP server sends a Server header with its own name and the Python version. To fix it, set the header yourself (in http.server, override version_string()), or let the reverse proxy in front of the app replace it. The rules file is where a team records which checks it has decided to enforce.

Remember

Run a passive baseline scan against the app as a job service on every pipeline, decide in a rules file which checks fail the build, and keep active scans for environments you own and can reset.

Quick check
01What kind of testing is ZAP's baseline scan?
Incorrect — That is SAST, which reads source code.
Incorrect — That is an active scan.
Correct — It crawls and inspects responses, such as headers and cookies, without attacking.
Incorrect — That is dependency scanning, a different job.
02How did the lab job reach the app it scanned?
Correct — Services start next to the job, on the job's network.
Incorrect — ZAP only sends requests to a running app.
Incorrect — The job used the service alias, not a host port.
Incorrect — This lab has no deployment step.
03Why is an active DAST scan not run against production?
Incorrect — Speed is not the main concern.
Correct — Use an environment you own and can reset.
Incorrect — They can be crawled like any other site.
Incorrect — DAST works from the outside.

Related