Debian Codegraph @

tests/fuzz_idna_api.py

raw
1 #!/usr/bin/env python3
2 """OSS-Fuzz target for the whole-domain and per-label API.
3
4 Each input selects an operation and flag combination from its leading bytes
5 and feeds the remainder as the domain or label. The harness asserts the same
6 invariants as ``tests/test_idna_properties.py``: only :class:`idna.IDNAError`
7 may escape, successful output is bounded ASCII, encoding then decoding then
8 encoding again is stable, and UTS #46 remapping is NFC and idempotent.
9
10 OSS-Fuzz builds every ``fuzz_*.py`` it finds in the checkout, so this file
11 needs no registration there. To run it locally::
12
13 pip install atheris .
14 python tests/fuzz_idna_api.py -max_total_time=60
15
16 Any libFuzzer flag is accepted; a crash writes a ``crash-*`` file which can be
17 passed back as an argument to reproduce. ``tests/test_idna_fuzz_targets.py``
18 smoke-tests this harness in the ordinary test suite without atheris.
19 """
20
21 import sys
22 import unicodedata
23
24 import atheris # ty: ignore[unresolved-import]
25
26 with atheris.instrument_imports():
27 import idna
28
29 MAX_INPUT = 1100 # just past idna's 1024-character input cap
30 STD3_ASCII = frozenset("abcdefghijklmnopqrstuvwxyz0123456789-.")
31
32
33 def _only_idnaerror(fn, *args, **kwargs):
34 try:
35 return fn(*args, **kwargs)
36 except idna.IDNAError:
37 return None
38
39
40 def fuzz_encode(fdp):
41 strict, uts46, std3 = fdp.ConsumeBool(), fdp.ConsumeBool(), fdp.ConsumeBool()
42 s = fdp.ConsumeUnicode(MAX_INPUT)
43 encoded = _only_idnaerror(idna.encode, s, strict=strict, uts46=uts46, std3_rules=std3)
44 if encoded is None:
45 return
46 encoded.decode("ascii")
47 assert len(encoded) <= 254, encoded
48 for label in encoded.rstrip(b".").split(b"."):
49 assert 0 < len(label) <= 63, encoded
50 # Anything encode() produced must decode, and re-encode to itself
51 # (up to ASCII case, since ulabel() lowercases while alabel() does not).
52 decoded = idna.decode(encoded)
53 assert idna.encode(decoded) == encoded.lower(), (encoded, decoded)
54 assert idna.decode(encoded, display=True) == decoded
55
56
57 def fuzz_decode(fdp):
58 strict, uts46, std3, display = fdp.ConsumeBool(), fdp.ConsumeBool(), fdp.ConsumeBool(), fdp.ConsumeBool()
59 data = fdp.ConsumeUnicode(MAX_INPUT) if fdp.ConsumeBool() else fdp.ConsumeBytes(MAX_INPUT)
60 decoded = _only_idnaerror(idna.decode, data, strict=strict, uts46=uts46, std3_rules=std3, display=display)
61 if decoded is None or not strict or uts46 or display:
62 return
63 # RFC 5891 §5.3: an A-label that decodes must re-encode to itself, so
64 # under strict non-UTS46 processing any ASCII input that decodes is (up
65 # to case) its own encoding. decode() does not enforce the 63-octet
66 # label limit (nor does UTS #46 ToUnicode) but encode() does, so skip
67 # overlong labels.
68 if isinstance(data, str):
69 if not data.isascii():
70 return
71 data = data.encode("ascii")
72 if all(len(label) <= 63 for label in data.split(b".")):
73 assert idna.encode(decoded, strict=True) == data.lower(), (data, decoded)
74
75
76 def fuzz_uts46_remap(fdp):
77 std3 = fdp.ConsumeBool()
78 s = fdp.ConsumeUnicode(MAX_INPUT)
79 out = _only_idnaerror(idna.uts46_remap, s, std3_rules=std3)
80 if out is None:
81 return
82 assert unicodedata.is_normalized("NFC", out), out
83 assert idna.uts46_remap(out, std3_rules=std3) == out, out
84 if std3: # UTS #46 §4.1 UseSTD3ASCIIRules
85 assert all(c in STD3_ASCII for c in out if c.isascii()), out
86
87
88 def fuzz_labels(fdp):
89 label = fdp.ConsumeUnicode(MAX_INPUT)
90 for fn in (
91 idna.alabel,
92 idna.ulabel,
93 idna.check_label,
94 idna.check_bidi,
95 idna.check_hyphen_ok,
96 idna.check_initial_combiner,
97 idna.check_nfc,
98 idna.valid_label_length,
99 ):
100 _only_idnaerror(fn, label)
101 _only_idnaerror(idna.ulabel, label.encode("utf-8", "surrogatepass"))
102 _only_idnaerror(idna.check_label, label.encode("utf-8", "surrogatepass"))
103 encoded = _only_idnaerror(idna.alabel, label)
104 if encoded is not None:
105 assert idna.alabel(idna.ulabel(encoded)) == encoded.lower(), (label, encoded)
106
107
108 OPERATIONS = (fuzz_encode, fuzz_decode, fuzz_uts46_remap, fuzz_labels)
109
110
111 def TestOneInput(data):
112 fdp = atheris.FuzzedDataProvider(data)
113 OPERATIONS[fdp.ConsumeIntInRange(0, len(OPERATIONS) - 1)](fdp)
114
115
116 def main():
117 atheris.Setup(sys.argv, TestOneInput, enable_python_coverage=True)
118 atheris.Fuzz()
119
120
121 if __name__ == "__main__":
122 main()