-
Notifications
You must be signed in to change notification settings - Fork 223
/
Fuzzer.py
executable file
·949 lines (669 loc) · 23.6 KB
/
Fuzzer.py
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# "Fuzzing: Breaking Things with Random Inputs" - a chapter of "The Fuzzing Book"
# Web site: https://www.fuzzingbook.org/html/Fuzzer.html
# Last change: 2024-01-18 18:14:12+01:00
#
# Copyright (c) 2021-2023 CISPA Helmholtz Center for Information Security
# Copyright (c) 2018-2020 Saarland University, authors, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
r'''
The Fuzzing Book - Fuzzing: Breaking Things with Random Inputs
This file can be _executed_ as a script, running all experiments:
$ python Fuzzer.py
or _imported_ as a package, providing classes, functions, and constants:
>>> from fuzzingbook.Fuzzer import <identifier>
but before you do so, _read_ it and _interact_ with it at:
https://www.fuzzingbook.org/html/Fuzzer.html
This chapter provides two important classes, introduced in [A Fuzzing Architecture](#A-Fuzzing-Architecture):
* `Fuzzer` as a base class for fuzzers; and
* `Runner` as a base class for programs under test.
### Fuzzers
`Fuzzer` is a base class for fuzzers, with `RandomFuzzer` as a simple instantiation. The `fuzz()` method of `Fuzzer` objects returns a string with a generated input.
>>> random_fuzzer = RandomFuzzer()
>>> random_fuzzer.fuzz()
'%$?99$%7!!*#96=>2&-/(5*)=$;0$$+;>> print(RandomFuzzer.__init__.__doc__)
Produce strings of `min_length` to `max_length` characters
in the range [`char_start`, `char_start` + `char_range`)
>>> random_fuzzer = RandomFuzzer(min_length=10, max_length=20, char_start=65, char_range=26)
>>> random_fuzzer.fuzz()
'XGZVDDPZOOW'
### Runners
A `Fuzzer` can be paired with a `Runner`, which takes the fuzzed strings as input. Its result is a class-specific _status_ and an _outcome_ (`PASS`, `FAIL`, or `UNRESOLVED`). A `PrintRunner` will simply print out the given input and return a `PASS` outcome:
>>> print_runner = PrintRunner()
>>> random_fuzzer.run(print_runner)
EQYGAXPTVPJGTYHXFJ
('EQYGAXPTVPJGTYHXFJ', 'UNRESOLVED')
A `ProgramRunner` will feed the generated input into an external program. Its result is a pair of the program status (a `CompletedProcess` instance) and an _outcome_ (`PASS`, `FAIL`, or `UNRESOLVED`):
>>> cat = ProgramRunner('cat')
>>> random_fuzzer.run(cat)
(CompletedProcess(args='cat', returncode=0, stdout='BZOQTXFBTEOVYX', stderr=''),
'PASS')
For more details, source, and documentation, see
"The Fuzzing Book - Fuzzing: Breaking Things with Random Inputs"
at https://www.fuzzingbook.org/html/Fuzzer.html
'''
# Allow to use 'from . import <module>' when run as script (cf. PEP 366)
if __name__ == '__main__' and __package__ is None:
__package__ = 'fuzzingbook'
# Fuzzing: Breaking Things with Random Inputs
# ===========================================
if __name__ == '__main__':
print('# Fuzzing: Breaking Things with Random Inputs')
if __name__ == '__main__':
from .bookutils import YouTubeVideo
YouTubeVideo('YjO1pIx7wS4')
if __name__ == '__main__':
# We use the same fixed seed as the notebook to ensure consistency
import random
random.seed(2001)
from typing import Dict, Tuple, Union, List, Any
from . import Intro_Testing
## Synopsis
## --------
if __name__ == '__main__':
print('\n## Synopsis')
## A Testing Assignment
## --------------------
if __name__ == '__main__':
print('\n## A Testing Assignment')
## A Simple Fuzzer
## ---------------
if __name__ == '__main__':
print('\n## A Simple Fuzzer')
import random
def fuzzer(max_length: int = 100, char_start: int = 32, char_range: int = 32) -> str:
"""A string of up to `max_length` characters
in the range [`char_start`, `char_start` + `char_range`)"""
string_length = random.randrange(0, max_length + 1)
out = ""
for i in range(0, string_length):
out += chr(random.randrange(char_start, char_start + char_range))
return out
if __name__ == '__main__':
fuzzer()
if __name__ == '__main__':
fuzzer(1000, ord('a'), 26)
from .bookutils import quiz
if __name__ == '__main__':
quiz("Which of these produces strings with arbitrary long decimal numbers?",
[
"`fuzzer(100, 1, 100)`",
"`fuzzer(100, 100, 0)`",
"`fuzzer(100, 10, ord('0'))`",
"`fuzzer(100, ord('0'), 10)`",
], "1 ** (2 % 3) * 4")
if __name__ == '__main__':
fuzzer(100, ord('0'), 10)
## Fuzzing External Programs
## -------------------------
if __name__ == '__main__':
print('\n## Fuzzing External Programs')
### Creating Input Files
if __name__ == '__main__':
print('\n### Creating Input Files')
import os
import tempfile
if __name__ == '__main__':
basename = "input.txt"
tempdir = tempfile.mkdtemp()
FILE = os.path.join(tempdir, basename)
print(FILE)
if __name__ == '__main__':
data = fuzzer()
with open(FILE, "w") as f:
f.write(data)
if __name__ == '__main__':
contents = open(FILE).read()
print(contents)
assert(contents == data)
### Invoking External Programs
if __name__ == '__main__':
print('\n### Invoking External Programs')
import os
import subprocess
if __name__ == '__main__':
program = "bc"
with open(FILE, "w") as f:
f.write("2 + 2\n")
result = subprocess.run([program, FILE],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True) # Will be "text" in Python 3.7
if __name__ == '__main__':
result.stdout
if __name__ == '__main__':
result.returncode
if __name__ == '__main__':
result.stderr
if __name__ == '__main__':
quiz("Just for the fun of it, imagine you would test a file removal program - "
"say `rm -fr FILE`, where `FILE` is a string produced by `fuzzer()`. "
"What is the chance of `fuzzer()` (with default arguments) producing a `FILE` "
"argument that results in deleting all your files?",
[
"About one in a billion",
"About one in a million",
"About one in a thousand",
"About one in ten"
], "9 ** 0.5")
if __name__ == '__main__':
1/101 * 2/32
if __name__ == '__main__':
3/94 * 1/94 * 99/101
if __name__ == '__main__':
2/32 * 1/32 * 99/101
### Long-Running Fuzzing
if __name__ == '__main__':
print('\n### Long-Running Fuzzing')
if __name__ == '__main__':
trials = 100
program = "bc"
runs = []
for i in range(trials):
data = fuzzer()
with open(FILE, "w") as f:
f.write(data)
result = subprocess.run([program, FILE],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
runs.append((data, result))
if __name__ == '__main__':
sum(1 for (data, result) in runs if result.stderr == "")
if __name__ == '__main__':
errors = [(data, result) for (data, result) in runs if result.stderr != ""]
(first_data, first_result) = errors[0]
print(repr(first_data))
print(first_result.stderr)
if __name__ == '__main__':
[result.stderr for (data, result) in runs if
result.stderr != ""
and "illegal character" not in result.stderr
and "parse error" not in result.stderr
and "syntax error" not in result.stderr]
if __name__ == '__main__':
sum(1 for (data, result) in runs if result.returncode != 0)
## Bugs Fuzzers Find
## -----------------
if __name__ == '__main__':
print('\n## Bugs Fuzzers Find')
### Buffer Overflows
if __name__ == '__main__':
print('\n### Buffer Overflows')
def crash_if_too_long(s):
buffer = "Thursday"
if len(s) > len(buffer):
raise ValueError
from .ExpectError import ExpectError
if __name__ == '__main__':
trials = 100
with ExpectError():
for i in range(trials):
s = fuzzer()
crash_if_too_long(s)
### Missing Error Checks
if __name__ == '__main__':
print('\n### Missing Error Checks')
def hang_if_no_space(s):
i = 0
while True:
if i < len(s):
if s[i] == ' ':
break
i += 1
from .ExpectError import ExpectTimeout
if __name__ == '__main__':
trials = 100
with ExpectTimeout(2):
for i in range(trials):
s = fuzzer()
hang_if_no_space(s)
def collapse_if_too_large(s):
if int(s) > 1000:
raise ValueError
if __name__ == '__main__':
long_number = fuzzer(100, ord('0'), 10)
print(long_number)
if __name__ == '__main__':
with ExpectError():
collapse_if_too_large(long_number)
## Catching Errors
## ---------------
if __name__ == '__main__':
print('\n## Catching Errors')
### Generic Checkers
if __name__ == '__main__':
print('\n### Generic Checkers')
#### Checking Memory Accesses
if __name__ == '__main__':
print('\n#### Checking Memory Accesses')
if __name__ == '__main__':
with open("program.c", "w") as f:
f.write("""
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
/* Create an array with 100 bytes, initialized with 42 */
char *buf = malloc(100);
memset(buf, 42, 100);
/* Read the N-th element, with N being the first command-line argument */
int index = atoi(argv[1]);
char val = buf[index];
/* Clean up memory so we don't leak */
free(buf);
return val;
}
""")
from .bookutils import print_file
if __name__ == '__main__':
print_file("program.c")
if __name__ == '__main__':
import os
os.system(f'clang -fsanitize=address -g -o program program.c')
if __name__ == '__main__':
import os
os.system(f'./program 99; echo $?')
if __name__ == '__main__':
import os
os.system(f'./program 110')
if __name__ == '__main__':
import os
os.system(f'rm -fr program program.*')
#### Information Leaks
if __name__ == '__main__':
print('\n#### Information Leaks')
if __name__ == '__main__':
secrets = ("<space for reply>" + fuzzer(100) +
"<secret-certificate>" + fuzzer(100) +
"<secret-key>" + fuzzer(100) + "<other-secrets>")
if __name__ == '__main__':
uninitialized_memory_marker = "deadbeef"
while len(secrets) < 2048:
secrets += uninitialized_memory_marker
def heartbeat(reply: str, length: int, memory: str) -> str:
# Store reply in memory
memory = reply + memory[len(reply):]
# Send back heartbeat
s = ""
for i in range(length):
s += memory[i]
return s
if __name__ == '__main__':
heartbeat("potato", 6, memory=secrets)
if __name__ == '__main__':
heartbeat("bird", 4, memory=secrets)
if __name__ == '__main__':
heartbeat("hat", 500, memory=secrets)
from .ExpectError import ExpectError
if __name__ == '__main__':
with ExpectError():
for i in range(10):
s = heartbeat(fuzzer(), random.randint(1, 500), memory=secrets)
assert not s.find(uninitialized_memory_marker)
assert not s.find("secret")
### Program-Specific Checkers
if __name__ == '__main__':
print('\n### Program-Specific Checkers')
if __name__ == '__main__':
airport_codes: Dict[str, str] = {
"YVR": "Vancouver",
"JFK": "New York-JFK",
"CDG": "Paris-Charles de Gaulle",
"CAI": "Cairo",
"LED": "St. Petersburg",
"PEK": "Beijing",
"HND": "Tokyo-Haneda",
"AKL": "Auckland"
} # plus many more
if __name__ == '__main__':
airport_codes["YVR"]
if __name__ == '__main__':
"AKL" in airport_codes
def code_repOK(code: str) -> bool:
assert len(code) == 3, "Airport code must have three characters: " + repr(code)
for c in code:
assert c.isalpha(), "Non-letter in airport code: " + repr(code)
assert c.isupper(), "Lowercase letter in airport code: " + repr(code)
return True
if __name__ == '__main__':
assert code_repOK("SEA")
def airport_codes_repOK():
for code in airport_codes:
assert code_repOK(code)
return True
if __name__ == '__main__':
with ExpectError():
assert airport_codes_repOK()
if __name__ == '__main__':
airport_codes["YMML"] = "Melbourne"
if __name__ == '__main__':
with ExpectError():
assert airport_codes_repOK()
def add_new_airport(code: str, city: str) -> None:
assert code_repOK(code)
airport_codes[code] = city
if __name__ == '__main__':
with ExpectError(): # For BER, ExpectTimeout would be more appropriate
add_new_airport("BER", "Berlin")
if __name__ == '__main__':
with ExpectError():
add_new_airport("London-Heathrow", "LHR")
def add_new_airport_2(code: str, city: str) -> None:
assert code_repOK(code)
assert airport_codes_repOK()
airport_codes[code] = city
assert airport_codes_repOK()
if __name__ == '__main__':
with ExpectError():
add_new_airport_2("IST", "Istanbul Yeni Havalimanı")
class RedBlackTree:
def repOK(self):
assert self.rootHasNoParent()
assert self.rootIsBlack()
assert self.rootNodesHaveOnlyBlackChildren()
assert self.treeIsAcyclic()
assert self.parentsAreConsistent()
return True
def rootIsBlack(self):
if self.parent is None:
assert self.color == BLACK
return True
def add_element(self, elem):
assert self.repOK()
... # Add the element
assert self.repOK()
def delete_element(self, elem):
assert self.repOK()
... # Delete the element
assert self.repOK()
### Static Code Checkers
if __name__ == '__main__':
print('\n### Static Code Checkers')
if __name__ == '__main__':
typed_airport_codes: Dict[str, str] = {
"YVR": "Vancouver", # etc
}
if __name__ == '__main__':
typed_airport_codes[1] = "First" # type: ignore
## A Fuzzing Architecture
## ----------------------
if __name__ == '__main__':
print('\n## A Fuzzing Architecture')
### Runner Classes
if __name__ == '__main__':
print('\n### Runner Classes')
Outcome = str
class Runner:
"""Base class for testing inputs."""
# Test outcomes
PASS = "PASS"
FAIL = "FAIL"
UNRESOLVED = "UNRESOLVED"
def __init__(self) -> None:
"""Initialize"""
pass
def run(self, inp: str) -> Any:
"""Run the runner with the given input"""
return (inp, Runner.UNRESOLVED)
class PrintRunner(Runner):
"""Simple runner, printing the input."""
def run(self, inp) -> Any:
"""Print the given input"""
print(inp)
return (inp, Runner.UNRESOLVED)
if __name__ == '__main__':
p = PrintRunner()
(result, outcome) = p.run("Some input")
if __name__ == '__main__':
result
if __name__ == '__main__':
outcome
class ProgramRunner(Runner):
"""Test a program with inputs."""
def __init__(self, program: Union[str, List[str]]) -> None:
"""Initialize.
`program` is a program spec as passed to `subprocess.run()`"""
self.program = program
def run_process(self, inp: str = "") -> subprocess.CompletedProcess:
"""Run the program with `inp` as input.
Return result of `subprocess.run()`."""
return subprocess.run(self.program,
input=inp,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
def run(self, inp: str = "") -> Tuple[subprocess.CompletedProcess, Outcome]:
"""Run the program with `inp` as input.
Return test outcome based on result of `subprocess.run()`."""
result = self.run_process(inp)
if result.returncode == 0:
outcome = self.PASS
elif result.returncode < 0:
outcome = self.FAIL
else:
outcome = self.UNRESOLVED
return (result, outcome)
class BinaryProgramRunner(ProgramRunner):
def run_process(self, inp: str = "") -> subprocess.CompletedProcess:
"""Run the program with `inp` as input.
Return result of `subprocess.run()`."""
return subprocess.run(self.program,
input=inp.encode(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if __name__ == '__main__':
cat = ProgramRunner(program="cat")
cat.run("hello")
### Fuzzer Classes
if __name__ == '__main__':
print('\n### Fuzzer Classes')
class Fuzzer:
"""Base class for fuzzers."""
def __init__(self) -> None:
"""Constructor"""
pass
def fuzz(self) -> str:
"""Return fuzz input"""
return ""
def run(self, runner: Runner = Runner()) \
-> Tuple[subprocess.CompletedProcess, Outcome]:
"""Run `runner` with fuzz input"""
return runner.run(self.fuzz())
def runs(self, runner: Runner = PrintRunner(), trials: int = 10) \
-> List[Tuple[subprocess.CompletedProcess, Outcome]]:
"""Run `runner` with fuzz input, `trials` times"""
return [self.run(runner) for i in range(trials)]
class RandomFuzzer(Fuzzer):
"""Produce random inputs."""
def __init__(self, min_length: int = 10, max_length: int = 100,
char_start: int = 32, char_range: int = 32) -> None:
"""Produce strings of `min_length` to `max_length` characters
in the range [`char_start`, `char_start` + `char_range`)"""
self.min_length = min_length
self.max_length = max_length
self.char_start = char_start
self.char_range = char_range
def fuzz(self) -> str:
string_length = random.randrange(self.min_length, self.max_length + 1)
out = ""
for i in range(0, string_length):
out += chr(random.randrange(self.char_start,
self.char_start + self.char_range))
return out
if __name__ == '__main__':
random_fuzzer = RandomFuzzer(min_length=20, max_length=20)
for i in range(10):
print(random_fuzzer.fuzz())
if __name__ == '__main__':
for i in range(10):
inp = random_fuzzer.fuzz()
result, outcome = cat.run(inp)
assert result.stdout == inp
assert outcome == Runner.PASS
if __name__ == '__main__':
random_fuzzer.run(cat)
if __name__ == '__main__':
random_fuzzer.runs(cat, 10)
## Synopsis
## --------
if __name__ == '__main__':
print('\n## Synopsis')
### Fuzzers
if __name__ == '__main__':
print('\n### Fuzzers')
if __name__ == '__main__':
random_fuzzer = RandomFuzzer()
random_fuzzer.fuzz()
if __name__ == '__main__':
print(RandomFuzzer.__init__.__doc__)
if __name__ == '__main__':
random_fuzzer = RandomFuzzer(min_length=10, max_length=20, char_start=65, char_range=26)
random_fuzzer.fuzz()
from .ClassDiagram import display_class_hierarchy
if __name__ == '__main__':
display_class_hierarchy(RandomFuzzer,
public_methods=[
Fuzzer.__init__,
Fuzzer.fuzz,
Fuzzer.run,
Fuzzer.runs,
RandomFuzzer.fuzz,
RandomFuzzer.__init__,
],
project='fuzzingbook')
### Runners
if __name__ == '__main__':
print('\n### Runners')
if __name__ == '__main__':
print_runner = PrintRunner()
random_fuzzer.run(print_runner)
if __name__ == '__main__':
cat = ProgramRunner('cat')
random_fuzzer.run(cat)
if __name__ == '__main__':
display_class_hierarchy([ProgramRunner, PrintRunner],
public_methods=[
Runner.__init__,
Runner.run,
ProgramRunner.__init__,
ProgramRunner.run,
PrintRunner.run
],
project='fuzzingbook')
## Lessons Learned
## ---------------
if __name__ == '__main__':
print('\n## Lessons Learned')
if __name__ == '__main__':
os.remove(FILE)
os.removedirs(tempdir)
## Next Steps
## ----------
if __name__ == '__main__':
print('\n## Next Steps')
## Background
## ----------
if __name__ == '__main__':
print('\n## Background')
## Exercises
## ---------
if __name__ == '__main__':
print('\n## Exercises')
### Exercise 1: Simulate Troff
if __name__ == '__main__':
print('\n### Exercise 1: Simulate Troff')
import string
def no_backslash_d(inp):
pattern = "\\D"
index = inp.find(pattern)
if index < 0 or index + len(pattern) >= len(inp):
return True
c = inp[index + len(pattern)]
assert c in string.printable
if __name__ == '__main__':
with ExpectError():
no_backslash_d("\\D\0")
def no_8bit(inp):
for i in range(len(inp) - 1):
assert ord(inp[i]) <= 127 or inp[i + 1] != '\n'
return True
if __name__ == '__main__':
with ExpectError():
no_8bit("ä\n")
def no_dot(inp):
assert inp != ".\n"
return True
### Exercise 2: Run Simulated Troff
if __name__ == '__main__':
print('\n### Exercise 2: Run Simulated Troff')
class TroffRunner(Runner):
def __init__(self):
self.no_backslash_d_failures = 0
self.no_8bit_failures = 0
self.no_dot_failures = 0
def run(self, inp):
try:
no_backslash_d(inp)
except AssertionError:
self.no_backslash_d_failures += 1
try:
no_8bit(inp)
except AssertionError:
self.no_8bit_failures += 1
try:
no_dot(inp)
except:
self.no_dot_failures += 1
return inp
if __name__ == '__main__':
random_fuzzer = RandomFuzzer(char_start=0, char_range=256, max_length=10)
troff_runner = TroffRunner()
if __name__ == '__main__':
trials = 100000
for i in range(trials):
random_fuzzer.run(troff_runner)
if __name__ == '__main__':
troff_runner.no_backslash_d_failures
if __name__ == '__main__':
troff_runner.no_8bit_failures
if __name__ == '__main__':
troff_runner.no_dot_failures
# %matplotlib inline
#
# ys = [troff_runner.no_backslash_d_failures,
# troff_runner.no_8bit_failures,
# troff_runner.no_dot_failures]
#
# import matplotlib.pyplot as plt
# plt.bar(["\\D", "8bit", "dot"], ys)
# plt.title("Occurrences of error classes");
### Exercise 3: Run Real Troff
if __name__ == '__main__':
print('\n### Exercise 3: Run Real Troff')
if __name__ == '__main__':
real_troff_runner = BinaryProgramRunner("troff")
for i in range(100):
result, outcome = random_fuzzer.run(real_troff_runner)
if outcome == Runner.FAIL:
print(result)