Repository navigation
261 lines (245 loc) · 12.1 KB
/
Copy pathsecurity-scan.yml
File metadata and controls
261 lines (245 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
name: Security Scan
run-name: 'Security Scan for CI run ${{ github.event.workflow_run.id }}'
# Statically scans PRs from untrusted authors (anyone GitHub doesn't report as
# OWNER, MEMBER, or COLLABORATOR) for committed secrets, exfiltration and
# obfuscated exec, edits to privileged paths, known-vulnerable locked
# dependencies, and local semgrep rules. It never runs PR code and gets no
# secrets. workflow_run loads this entire workflow from the default branch.
# The PR head is only read, from a separate `pr/` checkout on a hosted runner.
#
# Runs once when PR CI is requested, before its waiting gate can release tests.
# Re-running CI reuses its scan; re-run this workflow to rescan that request.
#
# Adapted from omnigent-ai/omnigent (Apache-2.0), .github/workflows/security-scan.yml.
on: # zizmor: ignore[dangerous-triggers] main-only metadata resolver; separate read-only hosted scan never executes PR code
workflow_run:
workflows: [CI]
types: [requested]
permissions:
contents: read
concurrency:
group: security-scan-${{ github.event.workflow_run.id }}
cancel-in-progress: true
jobs:
resolve:
name: Resolve scan request
if: ${{ github.event.workflow_run.event == 'pull_request' }}
runs-on:
group: databricks-protected-runner-group
labels: linux-ubuntu-latest
timeout-minutes: 5
permissions:
actions: read
pull-requests: read
outputs:
metadata: ${{ steps.pr.outputs.metadata }}
steps:
- name: Validate the requested PR against GitHub
id: pr
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: |
python3 - <<'PY'
import json
import os
import re
import subprocess
import sys
import urllib.parse
event = json.load(open(os.environ["GITHUB_EVENT_PATH"]))
run_id = event["workflow_run"].get("id")
if type(run_id) is not int or run_id <= 0:
sys.exit("::error::Security Scan requires a valid triggering CI run ID.")
repo = os.environ["REPO"]
request = json.loads(subprocess.check_output(
["gh", "api", f"repos/{repo}/actions/runs/{run_id}"], timeout=30
))
if request["id"] != run_id:
sys.exit("::error::GitHub returned a different CI run ID.")
if request["event"] != "pull_request":
sys.exit(f"::error::CI run {run_id} event must be pull_request.")
if request["path"] != ".github/workflows/ci.yml":
sys.exit(f"::error::CI run {run_id} path must be .github/workflows/ci.yml.")
# The run name is the PR title while a fork's CI awaits approval, so find the PR by
# head alone; the title is never a selector, and several open PRs can share a head.
head_repository = request.get("head_repository") or {}
head_branch = request.get("head_branch") or ""
owner = (head_repository.get("owner") or {}).get("login") or ""
if not (head_repository.get("id") and owner and head_branch):
sys.exit(f"::error::CI run {run_id} is missing its head repository or branch.")
head = f"{owner}:{head_branch}"
query = urllib.parse.urlencode({"head": head, "state": "open", "per_page": 100})
candidates = [
c for c in json.loads(subprocess.check_output(
["gh", "api", f"repos/{repo}/pulls?{query}"], timeout=30
))
if c["head"]["sha"] == request["head_sha"] and c["head"]["repo"] and
c["head"]["repo"]["id"] == head_repository["id"]
]
if len(candidates) != 1:
sys.exit(f"::error::CI run {run_id} must match exactly one open PR head, "
f"found {len(candidates)}.")
number = candidates[0]["number"]
pr = json.loads(subprocess.check_output(
["gh", "api", f"repos/{repo}/pulls/{number}"], timeout=30
))
head_repo = pr["head"]["repo"]
if (pr["number"] != number or pr["state"] != "open" or not head_repo or
pr["base"]["repo"]["full_name"] != repo or
pr["head"]["sha"] != request["head_sha"] or
head_repo["id"] != head_repository["id"] or
pr["head"]["ref"] != request["head_branch"]):
sys.exit("::error::CI request no longer matches the open PR's head and repository.")
if not all(re.fullmatch(r"[0-9a-f]{40}", pr[side]["sha"]) for side in ("head", "base")):
sys.exit("::error::GitHub did not return valid PR commit SHAs.")
metadata = {
"head_sha": pr["head"]["sha"], "base_sha": pr["base"]["sha"],
"author_association": pr["author_association"],
"author": pr["user"]["login"], "author_type": pr["user"]["type"],
"head_repo": head_repo["full_name"],
"labels": [label["name"] for label in pr["labels"]],
}
with open(os.environ["GITHUB_OUTPUT"], "a") as output:
output.write("metadata=" + json.dumps(metadata) + "\n")
PY
scan:
name: Security Scan
needs: resolve
runs-on: ubuntu-latest
timeout-minutes: 10
env:
# Hosted runners can't reach the internal pypi-proxy uv.lock points at.
UV_INDEX_URL: https://pypi.org/simple
steps:
- name: Check out scanner from main
env:
REPO: ${{ github.repository }}
POLICY_SHA: ${{ github.workflow_sha }}
run: |
# Plain git, so no action pin supplied by the PR runs before the scan.
git init -q .
git remote add origin "$GITHUB_SERVER_URL/$REPO.git"
git sparse-checkout set --no-cone .github/scripts/security-scan .github/security
git fetch -q --depth=1 origin "$POLICY_SHA"
git checkout -q --detach FETCH_HEAD
- name: Trust gate
id: gate
env:
EVENT_NAME: pull_request
HEAD_SHA: ${{ fromJSON(needs.resolve.outputs.metadata).head_sha }}
AUTHOR_ASSOCIATION: ${{ fromJSON(needs.resolve.outputs.metadata).author_association }}
PR_AUTHOR: ${{ fromJSON(needs.resolve.outputs.metadata).author }}
PR_AUTHOR_TYPE: ${{ fromJSON(needs.resolve.outputs.metadata).author_type }}
PR_HEAD_REPO: ${{ fromJSON(needs.resolve.outputs.metadata).head_repo }}
REPO: ${{ github.repository }}
PR_LABELS: ${{ toJSON(fromJSON(needs.resolve.outputs.metadata).labels) }}
run: bash .github/scripts/security-scan/should-scan.sh
- name: Check out PR head for static analysis
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
REPO: ${{ github.repository }}
HEAD_SHA: ${{ fromJSON(needs.resolve.outputs.metadata).head_sha }}
BASE_SHA: ${{ fromJSON(needs.resolve.outputs.metadata).base_sha }}
run: |
git init -q pr
git -C pr remote add origin "$GITHUB_SERVER_URL/$REPO.git"
git -C pr fetch -q --no-tags origin "$HEAD_SHA" "$BASE_SHA"
git -C pr checkout -q --detach "$HEAD_SHA"
- name: Compute PR diff
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
BASE_SHA: ${{ fromJSON(needs.resolve.outputs.metadata).base_sha }}
run: |
# --no-renames lists a moved file's old path too, so moving a workflow away is caught.
# --text --no-textconv: the PR's .gitattributes can't mark changes binary or rewrite them.
git -C pr diff --no-renames --text --no-textconv "$BASE_SHA...HEAD" > pr.diff
# -z: unquoted, NUL-separated paths, so an unusual name can't dodge the path checks.
git -C pr diff --no-renames --name-only -z "$BASE_SHA...HEAD" > changed.txt
echo "Changed files:"; tr '\0' '\n' < changed.txt
- name: Secret scan (added lines)
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
DIFF_FILE: ${{ github.workspace }}/pr.diff
run: python3 .github/scripts/security-scan/secret-scan.py
- name: Exfil scan (added lines)
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
DIFF_FILE: ${{ github.workspace }}/pr.diff
run: python3 .github/scripts/security-scan/exfil-scan.py
- name: Sensitive-path guard
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
CHANGED_FILES: ${{ github.workspace }}/changed.txt
run: bash .github/scripts/security-scan/sensitive-paths.sh
- name: Install uv
if: ${{ steps.gate.outputs.scan == 'true' }}
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
- name: Advisory scan (uv.lock pins the PR adds or changes)
# Only new pins, so open advisories already on main don't block the PR.
# --no-config: never read the PR's uv settings (it could add a package index).
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
BASE_SHA: ${{ fromJSON(needs.resolve.outputs.metadata).base_sha }}
run: |
git -C pr show "$BASE_SHA:uv.lock" > base-uv.lock 2>/dev/null || : > base-uv.lock
python3 .github/scripts/security-scan/locked-pins.py base-uv.lock | sort > base-pins.txt
python3 .github/scripts/security-scan/locked-pins.py pr/uv.lock | sort > head-pins.txt
comm -13 base-pins.txt head-pins.txt > new-pins.txt
if [ ! -s new-pins.txt ]; then
echo "No new uv.lock pins; skipping advisory scan."
exit 0
fi
echo "New pins:"; cat new-pins.txt
uvx --no-config pip-audit==2.10.1 --requirement new-pins.txt \
--no-deps --disable-pip --vulnerability-service osv
- name: Semgrep (changed files, local rules)
if: ${{ steps.gate.outputs.scan == 'true' }}
env:
RULES: ${{ github.workspace }}/.github/security/semgrep-rules.yml
run: |
# Only PR-changed files still in the head tree, so a contributor is
# never failed for pre-existing findings.
: > targets.txt
while IFS= read -r -d '' f; do
[ -f "pr/$f" ] && [ ! -L "pr/$f" ] && printf 'pr/%s\0' "$f" >> targets.txt
done < changed.txt
if [ ! -s targets.txt ]; then
echo "No changed files to semgrep."; exit 0
fi
echo "Semgrep targets:"; tr '\0' '\n' < targets.txt
# --disable-nosem: the PR's own `# nosemgrep` comments can't waive a rule.
# Warnings are informational; ERROR-severity rules fail the scan.
xargs -0 uvx --no-config semgrep==1.150.0 scan --config "$RULES" --severity=WARNING \
--disable-nosem --metrics=off --quiet < targets.txt || true
# semgrep still exits 0 for a finding on a nosem line, so fail on the JSON results.
xargs -0 uvx --no-config semgrep==1.150.0 scan --config "$RULES" --severity=ERROR \
--disable-nosem --metrics=off --quiet --json < targets.txt > semgrep.json
python3 - semgrep.json <<'EOF'
import json, sys
pending = open(sys.argv[1]).read().strip()
results = []
while True:
report, end = json.JSONDecoder().raw_decode(pending)
results.extend(report["results"])
pending = pending[end:].lstrip()
if not pending:
break
for r in results:
message = " ".join(r["extra"]["message"].split())
print(f"::error file={r['path'].removeprefix('pr/')},line={r['start']['line']}::{message}")
sys.exit(1 if results else 0)
EOF
- name: Explain the maintainer waiver (on failure)
if: ${{ failure() }}
env:
HEAD_SHA: ${{ fromJSON(needs.resolve.outputs.metadata).head_sha }}
run: |
# Re-run all jobs so the resolver reads the updated labels from GitHub.
MSG="A maintainer can skip the Security Scan by applying the 'skip-scan:$HEAD_SHA' label for this commit (requires Triage permission), then re-running all jobs in this Security Scan and re-running failed CI jobs."
echo "::error::$MSG"
{
echo "### Security Scan failed"
echo
echo "$MSG"
} >> "$GITHUB_STEP_SUMMARY"