# Apache Airflow Pentest

> Use for Apache Airflow pentests: mask bypass, fernet loot.

- Skill: `yufeifeio/apache-airflow-pentest` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx get-skill add yufeifeio/apache-airflow-pentest`
- Raw SKILL.md: https://api.skillmd.com/api/skills/yufeifeio/apache-airflow-pentest/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: Yufeifeio (https://skillmd.com/u/yufeifeio)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/yufeifeio/apache-airflow-pentest

---


# Apache Airflow Pentest

Airflow is the highest-yield credential mine in a data stack: every DAG that touches a DB/API has a Connection, every deployment holds a `fernet_key` that decrypts those connections, and the audit log records what the operators rotate. Targets: `/api/v2/*` (3.x FastAPI core API) and `/api/v1/*` (2.x stable REST API).

## Fingerprint
- `GET /api/v2/version` (3.x) / `GET /api/v1/version` (2.x) → `{"version": "3.1.8", ...}`.
- Auth: 3.x = JWT (UI login / `POST /auth/token` on the api-server); 2.x = HTTP basic on `/api/v1`.
- OpenAPI: `/api/v2/openapi.json` (3.x). Dump it — it maps enabled features and probe targets.
- One org usually runs several instances (dev/prod namespaces, e.g. `airflow-api-server.analytics.svc.cluster.local:8080`). Config toggles differ per instance — test each separately.

## Auth pitfalls (validated on 3.1.8)
- **Login success = HTTP 201**, not 200. A script judging `== 200` reports success as failure. Accept 200/201.
- Local auth can be broken per-instance: prod login → HTTP 500 while dev → 201. Per-host, not per-target.
- `GET /api/v2/config` (dumps `sql_alchemy_conn`, `fernet_key`, `secret_key`) is the single most valuable endpoint; commonly closed → **403 = "exists but disabled"; keep probing per instance**.
- `/version`, `/health` answer pre-auth — useless for token validation. Validate against `/api/v2/variables?limit=1` (expect 401 when dead).
- API tokens expire mid-engagement: keep `re-login → re-mint token → write token file` inline in batch scripts so a 401 run self-heals on retry.
- **3.x FAB form login** (`POST /auth/login/`): csrf field = `csrf_token`; parse attribute-order-insensitively (`<input[^>]+name="csrf_token"[^>]+value="([^"]+)"`) — a hidden `type=` between name and value silently breaks naive regexes into 400s; send `Referer: /auth/login/`; success = 302 away from login, while a 302 back to `/auth/login/` = wrong creds. A 5-attempt sample on prod showed no lockout — still keep prod dictionaries tiny.

## Enumeration checklist
- `/api/v2/connections?limit=100` — hosts, logins, schemas (`password` masked). Mine `conn_type`/`host` as the org's **internal DNS map**: `*.vpn.svc` / `*.cluster.local` service names, replica/DB hosts (e.g. `casino2b-databases.vpn.svc`, ClickHouse `main`/`malta`) become pivot leads for any SSRF primitive elsewhere in the stack.
- `/api/v2/variables?limit=100` — masked per rules below.
- `/api/v2/eventLogs` — audit trail. Mine these event types: `cli_users_create` (users + roles), `patch_variable` (value present), `connection.edit`, `cli_*`. Passwords are masked here too — the value is people, targets, rotation cadence.
- `/api/v2/dags` + `/api/v2/dagSources/{id}` / code view — DAG source frequently hardcodes hosts/tokens/URLs. **paginate beyond the live list**: `/api/v2/dagStats` lists ALL dags incl. `is_stale` (file deleted) ones; `/api/v2/dags/{id}` label lookup, `/dagRuns`, `/taskInstances`, `/tries` and `/dagSources/{id}?version_number=N` still return rows for stale dags — deleted pipelines' source + run history are readable from the metadata DB (`dag_code` table stores full source per version).
  Stale-instance dead ends (all dag files deleted / dags list empty): trigger endpoints 404 (`DAG with dag_id ... not found`); `create_backfill` still creates runs but they sit `queued` forever because the scheduler skips stale dags; task execution, dry-run, and clear-and-rerun are all dead — don't chase live task logs or code exec through a fully stale instance. Only a surviving NON-stale dag would execute; `/api/v2/dagStats` state counts (queued/running/success) reveal which dags still tick.
- `/api/v2/importErrors`, `/api/v2/plugins` — library versions, internal hostnames.
- `/api/v2/dagVersions/{id}` per dag → enumerate every historical source version; older refactors sometimes inline creds.
- Task log fetch (`.../taskInstances/{task}/logs/{try}`) proxies to the worker's log server `http://<worker-pod>.<ns>.svc:8793/log/dag_id=.../run_id=.../task_id=.../attempt=N.log` — worker DNS answers only while the pod lives; fetch a live/retained log to harvest internal worker hostnames. `TaskInstanceHistory` rows let you query past tries.
- Scale reference from a real engagement: 79 connections, 148 variables, ~592k audit events. Paginate; don't eyeball.
- **Shared-lab tell**: in multi-tester environments, the audit log + leftover objects from other testers (canary variables named `<tester-id>_*`, `audit_*` demo variables, stray `*ssrf*/zssrf*` connections, notes like `i24168 test`) map exactly which gaps the platform expects to be found — mine them first. An `audit_bulk_*` / `audit_order*` trail is a direct hint the bulk/order masking leaks are in scope.
- **eventLogs pagination cap (measured)**: the API returns ~100 items/page even when you request `limit=1000` — a naive `limit=1000 & offset += 1000` loop silently skips 90% of events. Verify returned page size first, then step by the ACTUAL size. A full 592k dump takes hours and is usually not worth it: enumerate per `event=` type instead — `variable.create`, `post_variable`, `patch_variable`, `bulk_variables`, `delete_variable`, `variables.varimport`, `post_connection`/`patch_connection`/`connection.edit`/`create_default_connections`, `cli_*` (pod names + `full_command`; timestamps component restarts/deploy cadence), `reparse_dag_file`, `create_backfill`, `trigger_dag_run`. Bulk and edit-type events are the ones that carry value bodies.
- **`POST /api/v2/connections/test`**: returns "Testing connections is disabled in Airflow configuration" when `[api] test_connection` is off — verify before planning connection-based SSRF. Sibling testers' leftover connection rows do NOT prove it was recently enabled.

## Masked secrets: architecture (Airflow 3.x)
Masking is applied at the **output datamodel layer** — storage (DB, worker env) stays plaintext/fernet. Paths that read storage beat paths that read the API.

- `airflow-core/src/airflow/api_fastapi/core_api/datamodels/variables.py` → `VariableResponse.redact_val` (`@model_validator(mode="after")`).
- `val` parses as JSON → `redact(val_dict, max_depth=1)` — **the variable's own key name is never consulted**; only key names inside the dict are matched. Content under non-matching top-level keys survives.
- `val` is not JSON → `str(redact(self.val, self.key))` — **key name IS used**; a key containing any sensitive substring masks the whole string.
- Sensitive substrings (case-insensitive, substring match on `name.strip().lower()`): `access_key, access_token, api_key, apikey, authorization, connection_string, passphrase, passwd, password, private_key, proxy, proxies, secret, token, keyfile_dict, service_account`.
- Gate: `HIDE_SENSITIVE_VAR_CONN_FIELDS`. `VariableResponse.is_encrypted` flags encrypted-at-rest values worth chasing.

### Bypass matrix
- DEAD: rename-to-evade — single PATCH requires `body.key == URI key` (400 otherwise); bulk PATCH serializes `model_dump(exclude={"key"})`. Source + live 400s agree.
- DEAD: non-string scalar pass-through (apache/airflow#71275 — int/bool/None unmasked under sensitive names) — the API enforces `val: str`.
- DEAD: event-log mining for connection passwords — masked. NOTE write-side leaks (don't help retro-read): `_mask_variable_fields` only understands flat `{"key":..,"val":..}` bodies — (a) JSON key order `{"value":..,"key":..}` leaves the value raw in the logged body; (b) bulk `PATCH /variables` bodies `{"actions":[{"action":"create","entities":[{"key":..,"value":..}]}]}` log raw values nested inside `actions`; (c) nested-dict values (`{"cfg":{"password":"x"}}`) keep depth>1 strings raw in both API response (max_depth=1) and log. Watch these to catch FUTURE rotations.
- LIVE: **the Task Execution API mounted at `/execution` on the api-server** (also reachable externally when the ingress forwards it). `/execution/variables/{key}` and `/execution/connections/{id}` return RAW values (worker contract needs plaintext; `execution_api/datamodels/variable.py` has no redaction). Routes: variables, connections, xcoms, dag_runs, task_instances, task_reschedules, asset_events, hitl — all behind `JWTBearerDep`, audience `execution_api.jwt_audience`, signed with the same shared `[api_auth] jwt_secret`. Only `/execution/health` is open. Fingerprint the key type via the alg error: HS256 → `The specified alg value is not allowed` while HS512 with a junk key → `Signature verification failed` means symmetric HS512 — then hunt `jwt_secret` (k8s secret / helm values / env) to mint tokens and dump everything raw.
- LIVE: file_token oracle — dag-list `file_token` = `itsdangerous.URLSafeSerializer(conf.get_mandatory_value("api", "secret_key")).dumps({"bundle_name":..,"relative_fileloc":..})` (zlib+base64 payload, deterministic). One captured token = <REDACTED> brute/verify for `[api] secret_key` by comparing `URLSafeSerializer(candidate).dumps(payload)` string-equality** (needs same itsdangerous defaults). `PUT /api/v2/parseDagFile/{file_token}` only re-parses files matching existing dag rows — not a file-read primitive.
- LIVE: JSON-valued variables — structure readable; stash content under a key name avoiding the 16 substrings.
- LIVE: `config` on any instance that still has it open.
- LIVE: fernet key from k8s Secret / `AIRFLOW__CORE__FERNET_KEY` env / GitOps values / config backups → decrypt `connection.password` and `is_encrypted` variables.
- LIVE: sibling systems — data catalogs (OpenMetadata) often store the same ecosystem's connections unmasked; see `openmetadata-pentest`.

Method: pull the exact deployed version's source from `https://raw.githubusercontent.com/apache/airflow/<tag>/<path>` and read the masking layer before black-box probing.

## Loot priorities
1. `/api/v2/config` → fernet key + metadata-DB DSN in one shot.
2. Connections → pick targets (analytics DBs, ad-platform tokens, internal APIs).
3. Variables → JSON blobs with nested service accounts.
4. Event log → people, roles, rotation cadence.
5. DAG source → hardcoded endpoints/tokens.
6. Metadata DB (with DSN + fernet): `connection` / `variable` tables decrypt to plaintext.

## Files
- `references/masking-bypass-airflow-3.x.md` — source-level notes, exact paths, dead-end receipts, probing order.
- `references/execution-api-notes.md` — execution-API raw-value endpoints, JWT wall + oracles, stale-DAG source mining, validated 3.1.8 misc.
