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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
"""GuardBench pattern set v2. Six shapes per pattern.

The guard is always at distance from the sink - a helper above, a decorator, a module constant,
or a branch several lines up. Two safe shapes per pattern (`covers`, `covers_alt`) so the safe
class is not a rounding error in the scoring.
"""
P2 = []
def pattern(fn): P2.append(fn); return fn

@pattern
def ssrf_redirect(_):
    cls = "server-side request forgery"
    head = '''import requests
from urllib.parse import urlparse

ALLOWED = {"api.partner.com", "cdn.partner.com"}

def _checked(url):
    if urlparse(url).hostname not in ALLOWED:
        raise ValueError("host not allowed")
    return url

'''
    return cls, dict(
      none = head + '''def fetch_avatar(url):
    return requests.get(url, timeout=5).content''',
      covers = head + '''def fetch_avatar(url):
    return requests.get(_checked(url), timeout=5, allow_redirects=False).content''',
      covers_alt = head + '''def fetch_avatar(url):
    r = requests.get(_checked(url), timeout=5, allow_redirects=True)
    _checked(r.url)
    return r.content''',
      wrong_value = head + '''def fetch_avatar(url, fallback):
    _checked(fallback)
    return requests.get(url, timeout=5).content''',
      irrelevant = head + '''def fetch_avatar(url):
    if not url.startswith("https://"):
        raise ValueError("https only")
    return requests.get(url, timeout=5).content''',
      elsewhere = head + '''def fetch_manifest(url):
    return requests.get(_checked(url), timeout=5, allow_redirects=False).json()

def fetch_avatar(url):
    return requests.get(url, timeout=5).content''')

@pattern
def csrf_missing(_):
    cls = "cross-site request forgery"
    head = '''from functools import wraps

def require_csrf(fn):
    @wraps(fn)
    def inner(request, *a, **kw):
        if request.form.get("csrf") != request.session.get("csrf"):
            abort(403)
        return fn(request, *a, **kw)
    return inner

'''
    return cls, dict(
      none = head + '''@app.post("/account/email")
def change_email(request):
    request.user.email = request.form["email"]
    request.user.save()''',
      covers = head + '''@app.post("/account/email")
@require_csrf
def change_email(request):
    request.user.email = request.form["email"]
    request.user.save()''',
      covers_alt = head + '''@app.post("/account/email")
def change_email(request):
    if request.headers.get("Sec-Fetch-Site") != "same-origin":
        abort(403)
    if request.form.get("csrf") != request.session.get("csrf"):
        abort(403)
    request.user.email = request.form["email"]
    request.user.save()''',
      wrong_value = head + '''@app.post("/account/email")
def change_email(request):
    if request.form.get("csrf") != request.form.get("csrf_echo"):
        abort(403)
    request.user.email = request.form["email"]
    request.user.save()''',
      irrelevant = head + '''@app.post("/account/email")
def change_email(request):
    if "@" not in request.form["email"]:
        abort(400)
    request.user.email = request.form["email"]
    request.user.save()''',
      elsewhere = head + '''@app.post("/account/password")
@require_csrf
def change_password(request):
    request.user.set_password(request.form["pw"])

@app.post("/account/email")
def change_email(request):
    request.user.email = request.form["email"]
    request.user.save()''')

@pattern
def toctou_symlink(_):
    cls = "time-of-check time-of-use"
    head = '''import os

SPOOL = "/var/spool/uploads"

def _create_exclusive(path):
    fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
    return os.fdopen(fd, "wb")

'''
    return cls, dict(
      none = head + '''def save_upload(name, data):
    path = os.path.join(SPOOL, name)
    if os.path.exists(path):
        raise FileExistsError(name)
    with open(path, "wb") as fh:
        fh.write(data)''',
      covers = head + '''def save_upload(name, data):
    with _create_exclusive(os.path.join(SPOOL, name)) as fh:
        fh.write(data)''',
      covers_alt = head + '''def save_upload(name, data):
    fd = os.open(os.path.join(SPOOL, name),
                 os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
    with os.fdopen(fd, "wb") as fh:
        fh.write(data)''',
      wrong_value = head + '''def save_upload(name, data, tmpname):
    _create_exclusive(os.path.join(SPOOL, tmpname)).close()
    with open(os.path.join(SPOOL, name), "wb") as fh:
        fh.write(data)''',
      irrelevant = head + '''def save_upload(name, data):
    if "/" in name or name.startswith("."):
        raise ValueError("bad name")
    path = os.path.join(SPOOL, name)
    with open(path, "wb") as fh:
        fh.write(data)''',
      elsewhere = head + '''def save_temp(name, data):
    with _create_exclusive(os.path.join(SPOOL, name)) as fh:
        fh.write(data)

def save_upload(name, data):
    with open(os.path.join(SPOOL, name), "wb") as fh:
        fh.write(data)''')

@pattern
def unicode_bypass(_):
    cls = "input validation bypass"
    head = '''import unicodedata, re

BLOCKED = re.compile(r"(?i)\\b(admin|root|system)\\b")

def _canonical(s):
    return unicodedata.normalize("NFKC", s).casefold()

'''
    return cls, dict(
      none = head + '''def register(username):
    return create_user(username)''',
      covers = head + '''def register(username):
    canon = _canonical(username)
    if BLOCKED.search(canon):
        raise ValueError("reserved name")
    return create_user(canon)''',
      covers_alt = head + '''def register(username):
    canon = unicodedata.normalize("NFKC", username).casefold()
    if BLOCKED.search(canon):
        raise ValueError("reserved name")
    return create_user(canon)''',
      wrong_value = head + '''def register(username, display):
    if BLOCKED.search(_canonical(display)):
        raise ValueError("reserved name")
    return create_user(_canonical(username))''',
      irrelevant = head + '''def register(username):
    if len(username) > 32:
        raise ValueError("too long")
    return create_user(_canonical(username))''',
      elsewhere = head + '''def register_org(name):
    canon = _canonical(name)
    if BLOCKED.search(canon):
        raise ValueError("reserved name")
    return create_org(canon)

def register(username):
    return create_user(_canonical(username))''')

@pattern
def cache_poisoning(_):
    cls = "web cache poisoning"
    head = '''KEYED_HEADERS = ("Host", "Accept-Language")

def _cache_key(request):
    parts = [request.path] + [request.headers.get(h, "") for h in KEYED_HEADERS]
    return "|".join(parts)

'''
    return cls, dict(
      none = head + '''def render_page(request):
    key = request.path
    if key in CACHE:
        return CACHE[key]
    body = build(request, base=request.headers.get("X-Forwarded-Host", ""))
    CACHE[key] = body
    return body''',
      covers = head + '''def render_page(request):
    key = _cache_key(request)
    if key in CACHE:
        return CACHE[key]
    body = build(request, base=request.headers.get("Host", ""))
    CACHE[key] = body
    return body''',
      covers_alt = head + '''def render_page(request):
    key = request.path + "|" + request.headers.get("Host", "")
    if key in CACHE:
        return CACHE[key]
    body = build(request, base=request.headers.get("Host", ""))
    CACHE[key] = body
    return body''',
      wrong_value = head + '''def render_page(request):
    key = _cache_key(request)
    if key in CACHE:
        return CACHE[key]
    body = build(request, base=request.headers.get("X-Forwarded-Host", ""))
    CACHE[key] = body
    return body''',
      irrelevant = head + '''def render_page(request):
    if len(request.path) > 512:
        raise ValueError("path too long")
    key = request.path
    if key in CACHE:
        return CACHE[key]
    body = build(request, base=request.headers.get("X-Forwarded-Host", ""))
    CACHE[key] = body
    return body''',
      elsewhere = head + '''def render_asset(request):
    key = _cache_key(request)
    return CACHE.setdefault(key, build_asset(request))

def render_page(request):
    key = request.path
    if key in CACHE:
        return CACHE[key]
    body = build(request, base=request.headers.get("X-Forwarded-Host", ""))
    CACHE[key] = body
    return body''')

@pattern
def int_overflow(_):
    cls = "integer overflow in size check"
    head = '''MAX_TOTAL = 50 * 1024 * 1024

def _fits(count, unit):
    if count < 0 or unit < 0:
        raise ValueError("negative size")
    if count > MAX_TOTAL // max(unit, 1):
        raise ValueError("too large")
    return True

'''
    return cls, dict(
      none = head + '''def allocate_frames(count, unit):
    return bytearray(count * unit)''',
      covers = head + '''def allocate_frames(count, unit):
    _fits(count, unit)
    return bytearray(count * unit)''',
      covers_alt = head + '''def allocate_frames(count, unit):
    if count < 0 or unit < 0 or count > MAX_TOTAL // max(unit, 1):
        raise ValueError("bad size")
    return bytearray(count * unit)''',
      wrong_value = head + '''def allocate_frames(count, unit, stride):
    _fits(count, stride)
    return bytearray(count * unit)''',
      irrelevant = head + '''def allocate_frames(count, unit):
    if count * unit > MAX_TOTAL:
        raise ValueError("too large")
    return bytearray(count * unit)''',
      elsewhere = head + '''def allocate_tiles(count, unit):
    _fits(count, unit)
    return bytearray(count * unit)

def allocate_frames(count, unit):
    return bytearray(count * unit)''')

@pattern
def sig_skip_branch(_):
    cls = "missing signature verification"
    head = '''import hmac, hashlib, base64

SCHEME = "v2"

def _verify(payload, header, secret):
    """Header is "v2,<ts>,<b64 mac>"; the MAC covers the timestamp and the payload."""
    try:
        scheme, ts, mac_b64 = header.split(",", 2)
    except ValueError:
        return False
    if scheme != SCHEME:
        return False
    signed = ts.encode() + b"." + payload
    want = base64.b64decode(mac_b64 + "==")
    got = hmac.new(secret, signed, hashlib.sha512).digest()
    return hmac.compare_digest(got, want)

'''
    return cls, dict(
      none = head + '''def handle_hook(request, secret):
    return process(json.loads(request.body))''',
      covers = head + '''def handle_hook(request, secret):
    if not _verify(request.body, request.headers.get("X-Sig", ""), secret):
        abort(401)
    return process(json.loads(request.body))''',
      covers_alt = head + '''def handle_hook(request, secret):
    header = request.headers.get("X-Sig", "")
    scheme, ts, mac_b64 = (header.split(",", 2) + ["", "", ""])[:3]
    signed = ts.encode() + b"." + request.body
    got = hmac.new(secret, signed, hashlib.sha512).digest()
    if scheme != SCHEME or not hmac.compare_digest(got, base64.b64decode(mac_b64 + "==")):
        abort(401)
    return process(json.loads(request.body))''',
      wrong_value = head + '''def handle_hook(request, secret):
    if not _verify(request.headers.get("X-Meta", b""), request.headers.get("X-Sig", ""), secret):
        abort(401)
    return process(json.loads(request.body))''',
      irrelevant = head + '''def handle_hook(request, secret):
    if request.headers.get("Content-Type") != "application/json":
        abort(415)
    return process(json.loads(request.body))''',
      elsewhere = head + '''def handle_billing_hook(request, secret):
    if not _verify(request.body, request.headers.get("X-Sig", ""), secret):
        abort(401)
    return process(json.loads(request.body))

def handle_hook(request, secret):
    return process(json.loads(request.body))''')

@pattern
def reset_token_reuse(_):
    cls = "authentication bypass"
    head = '''def _consume(token):
    """Single-use: returns the user only if the row was still unused."""
    rows = db.execute(
        "UPDATE resets SET used_at = now() WHERE token = %s AND used_at IS NULL RETURNING user_id",
        (token,))
    return rows[0][0] if rows else None

'''
    return cls, dict(
      none = head + '''def apply_reset(token, new_password):
    uid = db.query("SELECT user_id FROM resets WHERE token = %s", (token,))[0][0]
    set_password(uid, new_password)''',
      covers = head + '''def apply_reset(token, new_password):
    uid = _consume(token)
    if uid is None:
        abort(400)
    set_password(uid, new_password)''',
      covers_alt = head + '''def apply_reset(token, new_password):
    rows = db.execute(
        "UPDATE resets SET used_at = now() WHERE token = %s AND used_at IS NULL RETURNING user_id",
        (token,))
    if not rows:
        abort(400)
    set_password(rows[0][0], new_password)''',
      wrong_value = head + '''def apply_reset(token, confirm_token, new_password):
    _consume(confirm_token)
    uid = db.query("SELECT user_id FROM resets WHERE token = %s", (token,))[0][0]
    set_password(uid, new_password)''',
      irrelevant = head + '''def apply_reset(token, new_password):
    row = db.query("SELECT user_id, created_at FROM resets WHERE token = %s", (token,))[0]
    if (now() - row[1]).total_seconds() > 3600:
        abort(400)
    set_password(row[0], new_password)''',
      elsewhere = head + '''def apply_invite(token):
    uid = _consume(token)
    if uid is None:
        abort(400)
    activate(uid)

def apply_reset(token, new_password):
    uid = db.query("SELECT user_id FROM resets WHERE token = %s", (token,))[0][0]
    set_password(uid, new_password)''')

@pattern
def dict_merge(_):
    cls = "mass assignment"
    head = '''PROTECTED = {"is_admin", "org_id", "plan", "__class__"}

def _merge_safe(target, patch):
    for k, v in patch.items():
        if k in PROTECTED:
            continue
        if isinstance(v, dict) and isinstance(target.get(k), dict):
            _merge_safe(target[k], v)
        else:
            target[k] = v
    return target

'''
    return cls, dict(
      none = head + '''def update_settings(user, patch):
    return _deep_merge(user.settings, patch)''',
      covers = head + '''def update_settings(user, patch):
    return _merge_safe(user.settings, patch)''',
      covers_alt = head + '''def update_settings(user, patch):
    clean = {k: v for k, v in patch.items() if k not in PROTECTED}
    return _merge_safe(user.settings, clean)''',
      wrong_value = head + '''def update_settings(user, patch, defaults):
    _merge_safe({}, defaults)
    return _deep_merge(user.settings, patch)''',
      irrelevant = head + '''def update_settings(user, patch):
    if len(patch) > 50:
        raise ValueError("too many keys")
    return _deep_merge(user.settings, patch)''',
      elsewhere = head + '''def update_org_settings(org, patch):
    return _merge_safe(org.settings, patch)

def update_settings(user, patch):
    return _deep_merge(user.settings, patch)''')

@pattern
def arg_injection(_):
    cls = "argument injection"
    head = '''import subprocess

def _as_operand(value):
    """Stops a value beginning with '-' from being read as a flag."""
    if value.startswith("-"):
        raise ValueError("operand may not start with a dash")
    return value

'''
    return cls, dict(
      none = head + '''def count_matches(pattern, path):
    return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''',
      covers = head + '''def count_matches(pattern, path):
    return subprocess.run(["grep", "-c", "-e", pattern, "--", path],
                          capture_output=True).stdout''',
      covers_alt = head + '''def count_matches(pattern, path):
    return subprocess.run(["grep", "-c", "--", _as_operand(pattern), _as_operand(path)],
                          capture_output=True).stdout''',
      wrong_value = head + '''def count_matches(pattern, path):
    _as_operand(path)
    return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''',
      irrelevant = head + '''def count_matches(pattern, path):
    if ";" in pattern or "|" in pattern or "$" in pattern:
        raise ValueError("shell metacharacter")
    return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''',
      elsewhere = head + '''def list_matches(pattern, path):
    return subprocess.run(["grep", "-n", "-e", pattern, "--", path],
                          capture_output=True).stdout

def count_matches(pattern, path):
    return subprocess.run(["grep", "-c", pattern, path], capture_output=True).stdout''')

@pattern
def tar_symlink(_):
    cls = "path traversal"
    head = '''import tarfile, os

def _safe_members(tar, root):
    root = os.path.realpath(root)
    for m in tar.getmembers():
        if m.issym() or m.islnk():
            continue
        dest = os.path.realpath(os.path.join(root, m.name))
        if os.path.commonpath([dest, root]) != root:
            raise ValueError("entry escapes destination")
        yield m

'''
    return cls, dict(
      none = head + '''def unpack_bundle(path, dest):
    with tarfile.open(path) as t:
        t.extractall(dest)''',
      covers = head + '''def unpack_bundle(path, dest):
    with tarfile.open(path) as t:
        t.extractall(dest, members=_safe_members(t, dest))''',
      covers_alt = head + '''def unpack_bundle(path, dest):
    with tarfile.open(path) as t:
        t.extractall(dest, filter="data")''',
      wrong_value = head + '''def unpack_bundle(path, dest, staging):
    with tarfile.open(path) as t:
        list(_safe_members(t, staging))
        t.extractall(dest)''',
      irrelevant = head + '''def unpack_bundle(path, dest):
    with tarfile.open(path) as t:
        if sum(m.size for m in t.getmembers()) > 100 * 1024 * 1024:
            raise ValueError("bundle too large")
        t.extractall(dest)''',
      elsewhere = head + '''def unpack_theme(path, dest):
    with tarfile.open(path) as t:
        t.extractall(dest, members=_safe_members(t, dest))

def unpack_bundle(path, dest):
    with tarfile.open(path) as t:
        t.extractall(dest)''')

@pattern
def jwt_audience(_):
    cls = "authentication bypass"
    head = '''import jwt

ISSUER = "https://auth.example.com/"
AUDIENCE = "api.example.com"

def _claims(token, key):
    return jwt.decode(token, key, algorithms=["RS256"],
                      audience=AUDIENCE, issuer=ISSUER,
                      options={"require": ["exp", "iss", "aud", "sub"]})

'''
    return cls, dict(
      none = head + '''def current_user(token, key):
    claims = jwt.decode(token, key, algorithms=["RS256"])
    return User.get(claims["sub"])''',
      covers = head + '''def current_user(token, key):
    return User.get(_claims(token, key)["sub"])''',
      covers_alt = head + '''def current_user(token, key):
    claims = jwt.decode(token, key, algorithms=["RS256"],
                        audience=AUDIENCE, issuer=ISSUER,
                        options={"require": ["exp", "iss", "aud", "sub"]})
    return User.get(claims["sub"])''',
      wrong_value = head + '''def current_user(token, refresh_token, key):
    _claims(refresh_token, key)
    claims = jwt.decode(token, key, algorithms=["RS256"])
    return User.get(claims["sub"])''',
      irrelevant = head + '''def current_user(token, key):
    claims = jwt.decode(token, key, algorithms=["RS256"])
    if claims.get("exp", 0) < time.time():
        abort(401)
    return User.get(claims["sub"])''',
      elsewhere = head + '''def service_account(token, key):
    return Service.get(_claims(token, key)["sub"])

def current_user(token, key):
    claims = jwt.decode(token, key, algorithms=["RS256"])
    return User.get(claims["sub"])''')