Kitxuuu commited on
Commit
912ed30
·
verified ·
1 Parent(s): 53b3e4d

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/sanlib.py +227 -0
  2. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/os_command_injection.py +52 -0
  3. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/build.sh +22 -0
  4. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.dict +1 -0
  5. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_simple.py +54 -0
  6. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/test_data/culprit-commit.txt +30 -0
  7. local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.sum +30 -0
  8. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/base_runner_utils.py +33 -0
  9. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers.py +217 -0
  10. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py +48 -0
  11. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/example_cifuzz.yml +33 -0
  12. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore_utils_test.py +50 -0
  13. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/generate_coverage_report.py +48 -0
  14. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/get_coverage_test.py +253 -0
  15. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers.py +321 -0
  16. local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py +475 -0
  17. local-test-tika-delta-02/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp +493 -0
  18. local-test-tika-delta-02/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp +39 -0
  19. local-test-tika-delta-02/fuzz-tooling/infra/experimental/SystemSan/vuln.dict +3 -0
  20. local-test-tika-delta-02/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts +71 -0
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/sanlib.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+ """Core routines for pysecsan library."""
17
+
18
+ # pylint: disable=protected-access
19
+
20
+ import re
21
+ import os
22
+ import functools
23
+ import subprocess
24
+ import traceback
25
+ import importlib.util
26
+
27
+ from typing import Any, Callable, Optional
28
+ from pysecsan import command_injection, redos, yaml_deserialization
29
+
30
+ LOG_DEBUG = 0
31
+ LOG_INFO = 1
32
+ PYSECSAN_LOG_LVL = LOG_INFO
33
+
34
+ # Message that will be printed to stdout when an issue is found.
35
+ PYSECSAN_BUG_LABEL = r'===BUG DETECTED: PySecSan:'
36
+
37
+
38
+ # pylint: disable=global-statement
39
+ def sanitizer_log(msg, log_level, force=False, log_prefix=True):
40
+ """Helper printing function."""
41
+ global PYSECSAN_LOG_LVL
42
+ if log_level >= PYSECSAN_LOG_LVL or force:
43
+ if log_prefix:
44
+ print(f'[PYSECSAN] {msg}')
45
+ else:
46
+ print(f'{msg}')
47
+
48
+
49
+ def sanitizer_log_always(msg, log_prefix=True):
50
+ """Wrapper for sanitizer logging. Will always log"""
51
+ sanitizer_log(msg, 0, force=True, log_prefix=log_prefix)
52
+
53
+
54
+ def is_module_present(mod_name):
55
+ """Identify if module is importable."""
56
+ # pylint: disable=deprecated-method
57
+ return importlib.util.find_spec(mod_name) is not None
58
+
59
+
60
+ def _log_bug(bug_title):
61
+ sanitizer_log_always('%s %s ===' % (PYSECSAN_BUG_LABEL, bug_title),
62
+ log_prefix=False)
63
+
64
+
65
+ def abort_with_issue(msg, bug_title):
66
+ """Print message, display stacktrace and force process exit.
67
+
68
+ Use this function for signalling an issue is found and use the messages
69
+ logged from this function to determine if a fuzzer found a bug.
70
+ """
71
+ # Show breaker string using an ASAN approach (uses 65 =)
72
+ sanitizer_log_always("=" * 65, log_prefix=False)
73
+
74
+ # Log issue message
75
+ _log_bug(bug_title)
76
+ sanitizer_log_always(msg)
77
+
78
+ # Log stacktrace
79
+ sanitizer_log_always("Stacktrace:")
80
+ traceback.print_stack()
81
+
82
+ # Force exit
83
+ # Use os._exit here to force exit. sys.exit will exit
84
+ # by throwing a SystemExit exception which the interpreter
85
+ # handles by exiting. However, code may catch this exception,
86
+ # and thus to avoid this we exit the process without exceptions.
87
+ # pylint: disable=protected-access
88
+ sanitizer_log_always("Exiting")
89
+ os._exit(1)
90
+
91
+
92
+ def is_exact_taint(stream) -> bool:
93
+ """Checks if stream is an exact match for taint from fuzzer."""
94
+ # The fuzzer has to get 8 characters right. This may be a bit much,
95
+ # however, when found it shows a high level of control over the data.
96
+ if stream == 'FROMFUZZ':
97
+ return True
98
+
99
+ return False
100
+
101
+
102
+ def create_object_wrapper(**methods):
103
+ """Hooks functions in an object.
104
+
105
+ This is needed for hooking built-in types and object attributes.
106
+
107
+ Example use case is if we want to find ReDOS vulnerabilities, that
108
+ have a pattern of
109
+
110
+ ```
111
+ import re
112
+ r = re.compile(REGEX)
113
+ for _ in r.findall(...)
114
+ ```
115
+
116
+ In the above case r.findall is a reference to
117
+ re.Pattern.findall, which is a built-in type that is non-writeable.
118
+
119
+ In order to hook such calls we need to wrap the object, and also hook the
120
+ re.compile function to return the wrapped/hooked object.
121
+ """
122
+
123
+ class Wrapper():
124
+ """Wrap an object by hiding attributes."""
125
+
126
+ def __init__(self, instance):
127
+ object.__setattr__(self, 'instance', instance)
128
+
129
+ def __setattr__(self, name, value):
130
+ object.__setattr__(object.__getattribute__(self, 'instance'), name, value)
131
+
132
+ def __getattribute__(self, name):
133
+ instance = object.__getattribute__(self, 'instance')
134
+
135
+ def _hook_func(self, pre_hook, post_hook, orig, *args, **kargs):
136
+ if pre_hook is not None:
137
+ pre_hook(self, *args, **kargs)
138
+ # No need to pass instance here because when we extracted
139
+ # the function we used instance.__getattribute__(name) which
140
+ # seems to include it. I think.
141
+ orig_retval = orig(*args, **kargs)
142
+
143
+ if post_hook is not None:
144
+ post_hook(self, *args, **kargs)
145
+ return orig_retval
146
+
147
+ # If this is a wrapped method, return a bound method
148
+ if name in methods:
149
+ pre_hook = methods[name][0]
150
+ post_hook = methods[name][1]
151
+ orig = instance.__getattribute__(name)
152
+ return (lambda *args, **kargs: _hook_func(self, pre_hook, post_hook,
153
+ orig, *args, **kargs))
154
+
155
+ # Otherwise, just return attribute of instance
156
+ return instance.__getattribute__(name)
157
+
158
+ return Wrapper
159
+
160
+
161
+ # pylint: disable=unsubscriptable-object
162
+ def add_hook(function: Callable[[Any], Any],
163
+ pre_exec_hook: Optional[Callable[[Any], Any]] = None,
164
+ post_exec_hook: Optional[Callable[[Any], Any]] = None):
165
+ """Hook a function.
166
+
167
+ Hooks can be placed pre and post function call. At least one hook is
168
+ needed.
169
+
170
+ This hooking is intended on non-object hooks. In order to hook functions
171
+ in objects the `create_object_wrapper` function is used in combination
172
+ with function hooking initialisation functions post execution.
173
+ """
174
+ if pre_exec_hook is None and post_exec_hook is None:
175
+ raise Exception('Some hooks must be included')
176
+
177
+ @functools.wraps(function)
178
+ def run(*args, **kwargs):
179
+ sanitizer_log(f'Hook start {str(function)}', LOG_DEBUG)
180
+
181
+ # Call hook
182
+ if pre_exec_hook is not None:
183
+ pre_exec_hook(*args, **kwargs)
184
+
185
+ # Call the original function in the even the hook did not indicate
186
+ # failure.
187
+ ret = function(*args, **kwargs)
188
+
189
+ # Post execution hook. Overwrite return value if anything is returned
190
+ # by post hook.
191
+ if post_exec_hook is not None:
192
+ tmp_ret = post_exec_hook(ret, *args, **kwargs)
193
+ if tmp_ret is not None:
194
+ sanitizer_log('Overwriting return value', LOG_DEBUG)
195
+ ret = tmp_ret
196
+ sanitizer_log(f'Hook end {str(function)}', LOG_DEBUG)
197
+ return ret
198
+
199
+ return run
200
+
201
+
202
+ def add_hooks():
203
+ """Sets up hooks."""
204
+ sanitizer_log('Starting', LOG_INFO)
205
+ os.system = add_hook(os.system,
206
+ pre_exec_hook=command_injection.hook_pre_exec_os_system)
207
+ subprocess.Popen = add_hook(
208
+ subprocess.Popen,
209
+ pre_exec_hook=command_injection.hook_pre_exec_subprocess_Popen)
210
+
211
+ __builtins__['eval'] = add_hook(
212
+ __builtins__['eval'], pre_exec_hook=command_injection.hook_pre_exec_eval)
213
+
214
+ re.compile = add_hook(re.compile,
215
+ pre_exec_hook=redos.hook_pre_exec_re_compile,
216
+ post_exec_hook=redos.hook_post_exec_re_compile)
217
+
218
+ # Hack to determine if yaml is elligible, because pkg_resources does
219
+ # not seem to work from pyinstaller.
220
+ # pylint: disable=import-outside-toplevel
221
+ if is_module_present('yaml'):
222
+ import yaml
223
+ sanitizer_log('Hooking pyyaml.load', LOG_DEBUG)
224
+ yaml.load = add_hook(
225
+ yaml.load,
226
+ pre_exec_hook=yaml_deserialization.hook_pre_exec_pyyaml_load,
227
+ )
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/os_command_injection.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fuzzer targetting command injection of os.system."""
16
+
17
+ import os
18
+ import sys
19
+ import atheris
20
+ import pysecsan
21
+
22
+
23
+ def list_files_perhaps(param, magicval):
24
+ """Pass fuzzer data into os.system."""
25
+ if 'B' not in param:
26
+ return
27
+ if magicval == 1338:
28
+ os.system('exec-san')
29
+ elif magicval == 1339:
30
+ os.system('ls -la FROMFUZZ')
31
+ else:
32
+ os.system('ls -la ./')
33
+
34
+
35
+ def test_one_input(data):
36
+ """Fuzzer entrypoint."""
37
+ fdp = atheris.FuzzedDataProvider(data)
38
+ list_files_perhaps(fdp.ConsumeUnicodeNoSurrogates(24),
39
+ fdp.ConsumeIntInRange(500, 1500))
40
+
41
+
42
+ def main():
43
+ """Set up and start fuzzing."""
44
+ pysecsan.add_hooks()
45
+
46
+ atheris.instrument_all()
47
+ atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True)
48
+ atheris.Fuzz()
49
+
50
+
51
+ if __name__ == '__main__':
52
+ main()
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/build.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eu
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ git clone --depth 1 --branch 1.5.10 https://github.com/PyTorchLightning/pytorch-lightning.git
19
+ cd pytorch-lightning
20
+ python3 -m pip install .
21
+ cd ../
22
+ python3 ./fuzz_pytorch_lightning.py
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.dict ADDED
@@ -0,0 +1 @@
 
 
1
+ "os.system('exec-sanitizer')"
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_simple.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Fuzzer triggering insecure yaml serialization."""
16
+
17
+ import sys
18
+ import yaml
19
+ import atheris
20
+ import pysecsan
21
+
22
+
23
+ def serialize_with_tainted_data(param, magicval):
24
+ """Pass data to insecure yaml functions."""
25
+ if magicval == 1337:
26
+ try:
27
+ yaml.load(param, yaml.Loader)
28
+ except yaml.YAMLError:
29
+ pass
30
+ elif magicval == 1338:
31
+ try:
32
+ yaml.load('FROMFUZZ', yaml.Loader)
33
+ except yaml.YAMLError:
34
+ pass
35
+
36
+
37
+ def test_one_input(data):
38
+ """Fuzzer entrypoint."""
39
+ fdp = atheris.FuzzedDataProvider(data)
40
+ serialize_with_tainted_data(fdp.ConsumeUnicodeNoSurrogates(32),
41
+ fdp.ConsumeIntInRange(500, 1500))
42
+
43
+
44
+ def main():
45
+ """Set up and start fuzzing."""
46
+ pysecsan.add_hooks()
47
+
48
+ atheris.instrument_all()
49
+ atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True)
50
+ atheris.Fuzz()
51
+
52
+
53
+ if __name__ == '__main__':
54
+ main()
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/test_data/culprit-commit.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ac9ee01fcbfac745aaedca0393a8e1c8a33acd8d is the first bad commit
2
+ commit ac9ee01fcbfac745aaedca0393a8e1c8a33acd8d
3
+ Author: John Doe <johndoe@example.com>
4
+ Date: Tue Aug 6 08:41:53 2019 +0000
5
+
6
+ [compiler-rt] Implement getrandom interception
7
+
8
+ Summary:
9
+ Straightforward implementation of `getrandom` syscall and libc
10
+ hooks.
11
+
12
+ Test Plan: Local MSAN failures caused by uninstrumented `getrandom`
13
+ calls stop failing.
14
+
15
+ Patch by John Doe 3.
16
+
17
+ Reviewers: jonhdoe2, johndoe
18
+
19
+ Reviewed By: johndoe
20
+
21
+ Subscribers: johndoe4, johndoe5, #sanitizers, llvm-commits
22
+
23
+ Tags: #sanitizers, #llvm
24
+
25
+ Differential Revision: https://reviews.llvm.org/D65551
26
+
27
+ llvm-svn: 367999
28
+
29
+ :040000 040000 8db10511ca83cc7b0265c7703684cd386350151b 62508fdc5e8919bbb2a0bd185cc109868192cdb0 M compiler-rt
30
+ bisect run success
local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.sum ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
2
+ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
3
+ github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
4
+ github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5 h1:zIaiqGYDQwa4HVx5wGRTXbx38Pqxjemn4BP98wpzpXo=
5
+ github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
6
+ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
7
+ github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
8
+ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
9
+ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
10
+ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
11
+ golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
12
+ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
13
+ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
14
+ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
15
+ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
16
+ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
17
+ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
18
+ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
19
+ golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
20
+ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
21
+ golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
22
+ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
23
+ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
24
+ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
25
+ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
26
+ golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY=
27
+ golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
28
+ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
29
+ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
30
+ golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/base_runner_utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utilities for scripts from ghcr.io/aixcc-finals/base-runner."""
15
+
16
+ import os
17
+
18
+ import config_utils
19
+
20
+
21
+ def get_env(config, workspace):
22
+ """Returns a dictionary containing the current environment with additional env
23
+ vars set to values needed to run a fuzzer."""
24
+ env = os.environ.copy()
25
+ env['SANITIZER'] = config.sanitizer
26
+ env['FUZZING_LANGUAGE'] = config.language
27
+ env['OUT'] = workspace.out
28
+ env['CIFUZZ'] = 'True'
29
+ env['FUZZING_ENGINE'] = config_utils.DEFAULT_ENGINE
30
+ env['ARCHITECTURE'] = config.architecture
31
+ # Do this so we don't fail in tests.
32
+ env['FUZZER_ARGS'] = '-rss_limit_mb=2560 -timeout=25'
33
+ return env
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module used by CI tools in order to interact with fuzzers. This module helps
15
+ CI tools to build fuzzers."""
16
+
17
+ import logging
18
+ import os
19
+ import sys
20
+
21
+ import affected_fuzz_targets
22
+ import base_runner_utils
23
+ import clusterfuzz_deployment
24
+ import continuous_integration
25
+ import docker
26
+ import logs
27
+ import workspace_utils
28
+
29
+ # pylint: disable=wrong-import-position,import-error
30
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
31
+ import helper
32
+ import utils
33
+
34
+ logs.init()
35
+
36
+
37
+ def check_project_src_path(project_src_path):
38
+ """Returns True if |project_src_path| exists."""
39
+ if not os.path.exists(project_src_path):
40
+ logging.error(
41
+ 'PROJECT_SRC_PATH: %s does not exist. '
42
+ 'Are you mounting it correctly?', project_src_path)
43
+ return False
44
+ return True
45
+
46
+
47
+ # pylint: disable=too-many-arguments
48
+
49
+
50
+ class Builder: # pylint: disable=too-many-instance-attributes
51
+ """Class for fuzzer builders."""
52
+
53
+ def __init__(self, config, ci_system):
54
+ self.config = config
55
+ self.ci_system = ci_system
56
+ self.workspace = workspace_utils.Workspace(config)
57
+ self.workspace.initialize_dir(self.workspace.out)
58
+ self.workspace.initialize_dir(self.workspace.work)
59
+ self.clusterfuzz_deployment = (
60
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
61
+ self.config, self.workspace))
62
+ self.image_repo_path = None
63
+ self.host_repo_path = None
64
+ self.repo_manager = None
65
+
66
+ def build_image_and_checkout_src(self):
67
+ """Builds the project builder image and checkout source code for the patch
68
+ we want to fuzz (if necessary). Returns True on success."""
69
+ result = self.ci_system.prepare_for_fuzzer_build()
70
+ if not result.success:
71
+ return False
72
+ self.image_repo_path = result.image_repo_path
73
+ self.repo_manager = result.repo_manager
74
+ if self.config.output_sarif:
75
+ self.workspace.make_repo_for_sarif(self.repo_manager)
76
+ logging.info('repo_dir: %s.', self.repo_manager.repo_dir)
77
+ self.host_repo_path = self.repo_manager.repo_dir
78
+ return True
79
+
80
+ def build_fuzzers(self):
81
+ """Moves the source code we want to fuzz into the project builder and builds
82
+ the fuzzers from that source code. Returns True on success."""
83
+ docker_args, docker_container = docker.get_base_docker_run_args(
84
+ self.workspace, self.config.sanitizer, self.config.language,
85
+ self.config.architecture, self.config.docker_in_docker)
86
+ if not docker_container:
87
+ docker_args.extend(
88
+ _get_docker_build_fuzzers_args_not_container(self.host_repo_path))
89
+
90
+ build_command = self.ci_system.get_build_command(self.host_repo_path,
91
+ self.image_repo_path)
92
+
93
+ # Set extra environment variables so that they are visible to the build.
94
+ for key in self.config.extra_environment_variables:
95
+ # Don't specify their value in case they get echoed.
96
+ docker_args.extend(['-e', key])
97
+
98
+ docker_args.extend([
99
+ docker.get_project_image_name(self.config.oss_fuzz_project_name),
100
+ '/bin/bash',
101
+ '-c',
102
+ build_command,
103
+ ])
104
+ logging.info('Building with %s sanitizer.', self.config.sanitizer)
105
+
106
+ # TODO(metzman): Stop using helper.docker_run so we can get rid of
107
+ # docker.get_base_docker_run_args and merge its contents into
108
+ # docker.get_base_docker_run_command.
109
+ if not helper.docker_run(docker_args):
110
+ logging.error('Building fuzzers failed.')
111
+ return False
112
+
113
+ return True
114
+
115
+ def upload_build(self):
116
+ """Upload build."""
117
+ if self.config.upload_build:
118
+ self.clusterfuzz_deployment.upload_build(
119
+ self.repo_manager.get_current_commit())
120
+
121
+ return True
122
+
123
+ def check_fuzzer_build(self):
124
+ """Checks the fuzzer build. Returns True on success or if config specifies
125
+ to skip check."""
126
+ if not self.config.bad_build_check:
127
+ return True
128
+
129
+ return check_fuzzer_build(self.config)
130
+
131
+ def build(self):
132
+ """Builds the image, checkouts the source (if needed), builds the fuzzers
133
+ and then removes the unaffectted fuzzers. Returns True on success."""
134
+ methods = [
135
+ self.build_image_and_checkout_src,
136
+ self.build_fuzzers,
137
+ self.remove_unaffected_fuzz_targets,
138
+ self.upload_build,
139
+ self.check_fuzzer_build,
140
+ ]
141
+ for method in methods:
142
+ if not method():
143
+ return False
144
+ return True
145
+
146
+ def remove_unaffected_fuzz_targets(self):
147
+ """Removes the fuzzers unaffected by the patch."""
148
+ if self.config.keep_unaffected_fuzz_targets:
149
+ logging.info('Not removing unaffected fuzz targets.')
150
+ return True
151
+
152
+ logging.info('Removing unaffected fuzz targets.')
153
+ changed_files = self.ci_system.get_changed_code_under_test(
154
+ self.repo_manager)
155
+ affected_fuzz_targets.remove_unaffected_fuzz_targets(
156
+ self.clusterfuzz_deployment, self.workspace.out, changed_files,
157
+ self.image_repo_path)
158
+ return True
159
+
160
+
161
+ def build_fuzzers(config):
162
+ """Builds all of the fuzzers for a specific OSS-Fuzz project.
163
+
164
+ Args:
165
+ config: The configuration object for building fuzzers.
166
+
167
+ Returns:
168
+ True if build succeeded.
169
+ """
170
+ # Do some quick validation.
171
+ if config.project_src_path and not check_project_src_path(
172
+ config.project_src_path):
173
+ return False
174
+
175
+ # Get the builder and then build the fuzzers.
176
+ ci_system = continuous_integration.get_ci(config)
177
+ logging.info('ci_system: %s.', ci_system)
178
+ builder = Builder(config, ci_system)
179
+ return builder.build()
180
+
181
+
182
+ def check_fuzzer_build(config):
183
+ """Checks the integrity of the built fuzzers.
184
+
185
+ Args:
186
+ config: The config object.
187
+
188
+ Returns:
189
+ True if fuzzers pass OSS-Fuzz's build check.
190
+ """
191
+ workspace = workspace_utils.Workspace(config)
192
+ if not os.path.exists(workspace.out):
193
+ logging.error('Invalid out directory: %s.', workspace.out)
194
+ return False
195
+ if not os.listdir(workspace.out):
196
+ logging.error('No fuzzers found in out directory: %s.', workspace.out)
197
+ return False
198
+
199
+ env = base_runner_utils.get_env(config, workspace)
200
+ if config.allowed_broken_targets_percentage is not None:
201
+ env['ALLOWED_BROKEN_TARGETS_PERCENTAGE'] = (
202
+ config.allowed_broken_targets_percentage)
203
+
204
+ stdout, stderr, retcode = utils.execute('test_all.py', env=env)
205
+ print(f'Build check: stdout: {stdout}\nstderr: {stderr}')
206
+ if retcode == 0:
207
+ logging.info('Build check passed.')
208
+ return True
209
+ logging.error('Build check failed.')
210
+ return False
211
+
212
+
213
+ def _get_docker_build_fuzzers_args_not_container(host_repo_path):
214
+ """Returns arguments to the docker build arguments that are needed to use
215
+ |host_repo_path| when the host of the OSS-Fuzz builder container is not
216
+ another container."""
217
+ return ['-v', f'{host_repo_path}:{host_repo_path}']
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """End-to-End tests for CIFuzz."""
15
+ import os
16
+ import unittest
17
+
18
+ import run_cifuzz
19
+ import test_helpers
20
+
21
+ CIFUZZ_DIR = os.path.dirname(os.path.abspath(__file__))
22
+ EXTERNAL_PROJECT_PATH = os.path.join(CIFUZZ_DIR, 'test_data',
23
+ 'external-project')
24
+
25
+
26
+ # This test will fail if not run as root because the fuzzer build process
27
+ # creates binaries that only root can write to.
28
+ # Use a seperate env var to keep this seperate from integration tests which
29
+ # don't have this annoying property.
30
+ @unittest.skipIf(not os.getenv('END_TO_END_TESTS'),
31
+ 'END_TO_END_TESTS=1 not set')
32
+ class EndToEndTest(unittest.TestCase):
33
+ """End-to-End tests for CIFuzz."""
34
+
35
+ def setUp(self):
36
+ test_helpers.patch_environ(self, runner=True)
37
+
38
+ def test_simple(self):
39
+ """Simple end-to-end test using run_cifuzz.main()."""
40
+ os.environ['REPOSITORY'] = 'external-project'
41
+ os.environ['PROJECT_SRC_PATH'] = EXTERNAL_PROJECT_PATH
42
+ os.environ['FILESTORE'] = 'no_filestore'
43
+ os.environ['NO_CLUSTERFUZZ_DEPLOYMENT'] = 'True'
44
+
45
+ with test_helpers.docker_temp_dir() as temp_dir:
46
+ os.environ['WORKSPACE'] = temp_dir
47
+ # TODO(metzman): Verify the crash, affected fuzzers, and other things.
48
+ self.assertEqual(run_cifuzz.main(), 1)
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/example_cifuzz.yml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CIFuzz
2
+ on: [pull_request]
3
+ permissions: {}
4
+ jobs:
5
+ Fuzzing:
6
+ runs-on: ubuntu-latest
7
+ permissions:
8
+ security-events: write
9
+ steps:
10
+ - name: Build Fuzzers
11
+ id: build
12
+ uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
13
+ with:
14
+ oss-fuzz-project-name: 'example'
15
+ - name: Run Fuzzers
16
+ uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
17
+ with:
18
+ oss-fuzz-project-name: 'example'
19
+ fuzz-seconds: 600
20
+ output-sarif: true
21
+ - name: Upload Crash
22
+ uses: actions/upload-artifact@v3
23
+ if: failure() && steps.build.outcome == 'success'
24
+ with:
25
+ name: artifacts
26
+ path: ./out/artifacts
27
+ - name: Upload Sarif
28
+ if: always() && steps.build.outcome == 'success'
29
+ uses: github/codeql-action/upload-sarif@v2
30
+ with:
31
+ # Path to SARIF file relative to the root of the repository
32
+ sarif_file: cifuzz-sarif/results.sarif
33
+ checkout_path: cifuzz-sarif
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore_utils_test.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for filestore_utils."""
15
+ import unittest
16
+ from unittest import mock
17
+
18
+ import parameterized
19
+
20
+ import platform_config
21
+ import filestore
22
+ from filestore import github_actions
23
+ import filestore_utils
24
+ import test_helpers
25
+
26
+
27
+ class GetFilestoreTest(unittest.TestCase):
28
+ """Tests for get_filestore."""
29
+
30
+ @parameterized.parameterized.expand([
31
+ ({
32
+ 'cfl_platform': 'github',
33
+ }, github_actions.GithubActionsFilestore),
34
+ ])
35
+ def test_get_filestore(self, config_kwargs, filestore_cls):
36
+ """Tests that get_filestore returns the right filestore given a certain
37
+ platform."""
38
+ run_config = test_helpers.create_run_config(**config_kwargs)
39
+ filestore_impl = filestore_utils.get_filestore(run_config)
40
+ self.assertIsInstance(filestore_impl, filestore_cls)
41
+
42
+ @mock.patch('config_utils.BaseConfig.platform', return_value='other')
43
+ @mock.patch('config_utils._get_platform_config',
44
+ return_value=platform_config.BasePlatformConfig())
45
+ def test_get_filestore_unsupported_platform(self, _, __):
46
+ """Tests that get_filestore exceptions given a platform it doesn't
47
+ support."""
48
+ run_config = test_helpers.create_run_config()
49
+ with self.assertRaises(filestore.FilestoreError):
50
+ filestore_utils.get_filestore(run_config)
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/generate_coverage_report.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for generating coverage reports."""
15
+ import os
16
+
17
+ import base_runner_utils
18
+ import fuzz_target
19
+ import utils
20
+
21
+
22
+ def run_coverage_command(config, workspace):
23
+ """Runs the coverage command in base-runner to generate a coverage report."""
24
+ env = base_runner_utils.get_env(config, workspace)
25
+ env['HTTP_PORT'] = ''
26
+ env['COVERAGE_EXTRA_ARGS'] = ''
27
+ env['CORPUS_DIR'] = workspace.corpora
28
+ env['COVERAGE_OUTPUT_DIR'] = workspace.coverage_report
29
+ command = 'coverage'
30
+ return utils.execute(command, env=env)
31
+
32
+
33
+ def download_corpora(fuzz_target_paths, clusterfuzz_deployment):
34
+ """Downloads corpora for fuzz targets in |fuzz_target_paths| using
35
+ |clusterfuzz_deployment| to download corpora from ClusterFuzz/OSS-Fuzz."""
36
+ for target_path in fuzz_target_paths:
37
+ target_name = os.path.basename(target_path)
38
+ corpus_dir = fuzz_target.get_fuzz_target_corpus_dir(
39
+ clusterfuzz_deployment.workspace, target_name)
40
+ clusterfuzz_deployment.download_corpus(target_name, corpus_dir)
41
+
42
+
43
+ def generate_coverage_report(fuzz_target_paths, workspace,
44
+ clusterfuzz_deployment, config):
45
+ """Generates a coverage report using Clang's source based coverage."""
46
+ download_corpora(fuzz_target_paths, clusterfuzz_deployment)
47
+ run_coverage_command(config, workspace)
48
+ clusterfuzz_deployment.upload_coverage()
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/get_coverage_test.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for get_coverage.py"""
15
+ import os
16
+ import json
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import parameterized
21
+ from pyfakefs import fake_filesystem_unittest
22
+ import pytest
23
+
24
+ import get_coverage
25
+
26
+ # pylint: disable=protected-access
27
+
28
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
29
+ 'test_data')
30
+
31
+ PROJECT_NAME = 'curl'
32
+ REPO_PATH = '/src/curl'
33
+ FUZZ_TARGET = 'curl_fuzzer'
34
+ PROJECT_COV_JSON_FILENAME = 'example_curl_cov.json'
35
+ FUZZ_TARGET_COV_JSON_FILENAME = 'example_curl_fuzzer_cov.json'
36
+ INVALID_TARGET = 'not-a-fuzz-target'
37
+
38
+ with open(os.path.join(TEST_DATA_PATH,
39
+ PROJECT_COV_JSON_FILENAME),) as cov_file_handle:
40
+ PROJECT_COV_INFO = json.loads(cov_file_handle.read())
41
+
42
+
43
+ class GetOssFuzzFuzzerStatsDirUrlTest(unittest.TestCase):
44
+ """Tests _get_oss_fuzz_fuzzer_stats_dir_url."""
45
+
46
+ @mock.patch('http_utils.get_json_from_url',
47
+ return_value={
48
+ 'fuzzer_stats_dir':
49
+ 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'
50
+ })
51
+ def test_get_valid_project(self, mock_get_json_from_url):
52
+ """Tests that a project's coverage report can be downloaded and parsed.
53
+
54
+ NOTE: This test relies on the PROJECT_NAME repo's coverage report.
55
+ The "example" project was not used because it has no coverage reports.
56
+ """
57
+ result = get_coverage._get_oss_fuzz_fuzzer_stats_dir_url(PROJECT_NAME)
58
+ (url,), _ = mock_get_json_from_url.call_args
59
+ self.assertEqual(
60
+ 'https://storage.googleapis.com/oss-fuzz-coverage/'
61
+ 'latest_report_info/curl.json', url)
62
+
63
+ expected_result = (
64
+ 'https://storage.googleapis.com/oss-fuzz-coverage/systemd/fuzzer_stats/'
65
+ '20210303')
66
+ self.assertEqual(result, expected_result)
67
+
68
+ def test_get_invalid_project(self):
69
+ """Tests that passing a bad project returns None."""
70
+ self.assertIsNone(
71
+ get_coverage._get_oss_fuzz_fuzzer_stats_dir_url('not-a-proj'))
72
+
73
+
74
+ class OSSFuzzCoverageGetTargetCoverageTest(unittest.TestCase):
75
+ """Tests OSSFuzzCoverage.get_target_coverage."""
76
+
77
+ def setUp(self):
78
+ with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
79
+ return_value=PROJECT_COV_INFO):
80
+ self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage(
81
+ REPO_PATH, PROJECT_NAME)
82
+
83
+ @mock.patch('http_utils.get_json_from_url', return_value={})
84
+ def test_valid_target(self, mock_get_json_from_url):
85
+ """Tests that a target's coverage report can be downloaded and parsed."""
86
+ self.oss_fuzz_coverage.get_target_coverage(FUZZ_TARGET)
87
+ (url,), _ = mock_get_json_from_url.call_args
88
+ self.assertEqual(
89
+ 'https://storage.googleapis.com/oss-fuzz-coverage/'
90
+ 'curl/fuzzer_stats/20200226/curl_fuzzer.json', url)
91
+
92
+ def test_invalid_target(self):
93
+ """Tests that passing an invalid target coverage report returns None."""
94
+ self.assertIsNone(
95
+ self.oss_fuzz_coverage.get_target_coverage(INVALID_TARGET))
96
+
97
+ @mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
98
+ return_value=None)
99
+ def test_invalid_project_json(self, _): # pylint: disable=no-self-use
100
+ """Tests an invalid project JSON results in None being returned."""
101
+ with pytest.raises(get_coverage.CoverageError):
102
+ get_coverage.OSSFuzzCoverage(REPO_PATH, PROJECT_NAME)
103
+
104
+
105
+ def _get_expected_curl_covered_file_list():
106
+ """Returns the expected covered file list for
107
+ FUZZ_TARGET_COV_JSON_FILENAME."""
108
+ curl_files_list_path = os.path.join(TEST_DATA_PATH,
109
+ 'example_curl_file_list.json')
110
+ with open(curl_files_list_path) as file_handle:
111
+ return json.loads(file_handle.read())
112
+
113
+
114
+ def _get_example_curl_coverage():
115
+ """Returns the contents of the fuzzer stats JSON file for
116
+ FUZZ_TARGET_COV_JSON_FILENAME."""
117
+ with open(os.path.join(TEST_DATA_PATH,
118
+ FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle:
119
+ return json.loads(file_handle.read())
120
+
121
+
122
+ class OSSFuzzCoverageGetFilesCoveredByTargetTest(unittest.TestCase):
123
+ """Tests OSSFuzzCoverage.get_files_covered_by_target."""
124
+
125
+ def setUp(self):
126
+ with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
127
+ return_value=PROJECT_COV_INFO):
128
+ self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage(
129
+ REPO_PATH, PROJECT_NAME)
130
+
131
+ @parameterized.parameterized.expand([({
132
+ 'data': []
133
+ },), ({
134
+ 'data': [[]]
135
+ },), ({
136
+ 'data': [{}]
137
+ },)])
138
+ def test_malformed_cov_data(self, coverage_data):
139
+ """Tests that covered files can be retrieved from a coverage report."""
140
+ with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage',
141
+ return_value=coverage_data):
142
+ self.oss_fuzz_coverage.get_files_covered_by_target(FUZZ_TARGET)
143
+
144
+ def test_valid_target(self):
145
+ """Tests that covered files can be retrieved from a coverage report."""
146
+ fuzzer_cov_data = _get_example_curl_coverage()
147
+ with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage',
148
+ return_value=fuzzer_cov_data):
149
+ file_list = self.oss_fuzz_coverage.get_files_covered_by_target(
150
+ FUZZ_TARGET)
151
+
152
+ expected_file_list = _get_expected_curl_covered_file_list()
153
+ self.assertCountEqual(file_list, expected_file_list)
154
+
155
+ def test_invalid_target(self):
156
+ """Tests passing invalid fuzz target returns None."""
157
+ self.assertIsNone(
158
+ self.oss_fuzz_coverage.get_files_covered_by_target(INVALID_TARGET))
159
+
160
+
161
+ class FilesystemCoverageGetFilesCoveredByTargetTest(
162
+ fake_filesystem_unittest.TestCase):
163
+ """Tests FilesystemCoverage.get_files_covered_by_target."""
164
+
165
+ def setUp(self):
166
+ _fuzzer_cov_data = _get_example_curl_coverage()
167
+ self._expected_file_list = _get_expected_curl_covered_file_list()
168
+ self.coverage_path = '/coverage'
169
+ self.filesystem_coverage = get_coverage.FilesystemCoverage(
170
+ REPO_PATH, self.coverage_path)
171
+ self.setUpPyfakefs()
172
+ self.fs.create_file(os.path.join(self.coverage_path, 'fuzzer_stats',
173
+ FUZZ_TARGET + '.json'),
174
+ contents=json.dumps(_fuzzer_cov_data))
175
+
176
+ def test_valid_target(self):
177
+ """Tests that covered files can be retrieved from a coverage report."""
178
+ file_list = self.filesystem_coverage.get_files_covered_by_target(
179
+ FUZZ_TARGET)
180
+ self.assertCountEqual(file_list, self._expected_file_list)
181
+
182
+ def test_invalid_target(self):
183
+ """Tests passing invalid fuzz target returns None."""
184
+ self.assertIsNone(
185
+ self.filesystem_coverage.get_files_covered_by_target(INVALID_TARGET))
186
+
187
+
188
+ class IsFileCoveredTest(unittest.TestCase):
189
+ """Tests for is_file_covered."""
190
+
191
+ def test_is_file_covered_covered(self):
192
+ """Tests that is_file_covered returns True for a covered file."""
193
+ file_coverage = {
194
+ 'filename': '/src/systemd/src/basic/locale-util.c',
195
+ 'summary': {
196
+ 'regions': {
197
+ 'count': 204,
198
+ 'covered': 200,
199
+ 'notcovered': 200,
200
+ 'percent': 98.03
201
+ }
202
+ }
203
+ }
204
+ self.assertTrue(get_coverage.is_file_covered(file_coverage))
205
+
206
+ def test_is_file_covered_not_covered(self):
207
+ """Tests that is_file_covered returns False for a not covered file."""
208
+ file_coverage = {
209
+ 'filename': '/src/systemd/src/basic/locale-util.c',
210
+ 'summary': {
211
+ 'regions': {
212
+ 'count': 204,
213
+ 'covered': 0,
214
+ 'notcovered': 0,
215
+ 'percent': 0
216
+ }
217
+ }
218
+ }
219
+ self.assertFalse(get_coverage.is_file_covered(file_coverage))
220
+
221
+
222
+ class GetOssFuzzLatestCovReportInfo(unittest.TestCase):
223
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as
224
+ intended."""
225
+
226
+ PROJECT = 'project'
227
+ LATEST_REPORT_INFO_URL = ('https://storage.googleapis.com/oss-fuzz-coverage/'
228
+ 'latest_report_info/project.json')
229
+
230
+ @mock.patch('logging.error')
231
+ @mock.patch('http_utils.get_json_from_url', return_value={'coverage': 1})
232
+ def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url,
233
+ mock_error):
234
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
235
+ result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT)
236
+ self.assertEqual(result, {'coverage': 1})
237
+ mock_error.assert_not_called()
238
+ mock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL)
239
+
240
+ @mock.patch('logging.error')
241
+ @mock.patch('http_utils.get_json_from_url', return_value=None)
242
+ def test_get_oss_fuzz_latest_cov_report_info_fail(self, _, mock_error):
243
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as intended when we
244
+ can't get latest report info."""
245
+ result = get_coverage._get_oss_fuzz_latest_cov_report_info('project')
246
+ self.assertIsNone(result)
247
+ mock_error.assert_called_with(
248
+ 'Could not get the coverage report json from url: %s.',
249
+ self.LATEST_REPORT_INFO_URL)
250
+
251
+
252
+ if __name__ == '__main__':
253
+ unittest.main()
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for running fuzzers."""
15
+ import enum
16
+ import logging
17
+ import os
18
+ import sys
19
+ import time
20
+
21
+ import clusterfuzz_deployment
22
+ import fuzz_target
23
+ import generate_coverage_report
24
+ import workspace_utils
25
+ import sarif_utils
26
+
27
+ # pylint: disable=wrong-import-position,import-error
28
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
29
+
30
+ import utils
31
+
32
+
33
+ class RunFuzzersResult(enum.Enum):
34
+ """Enum result from running fuzzers."""
35
+ ERROR = 0
36
+ BUG_FOUND = 1
37
+ NO_BUG_FOUND = 2
38
+
39
+
40
+ class BaseFuzzTargetRunner:
41
+ """Base class for fuzzer runners."""
42
+
43
+ def __init__(self, config):
44
+ self.config = config
45
+ self.workspace = workspace_utils.Workspace(config)
46
+ self.clusterfuzz_deployment = (
47
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
48
+ self.config, self.workspace))
49
+
50
+ # Set by the initialize method.
51
+ self.fuzz_target_paths = None
52
+
53
+ def get_fuzz_targets(self):
54
+ """Returns fuzz targets in out directory."""
55
+ return utils.get_fuzz_targets(self.workspace.out)
56
+
57
+ def initialize(self):
58
+ """Initialization method. Must be called before calling run_fuzz_targets.
59
+ Returns True on success."""
60
+ # Use a separate initialization function so we can return False on failure
61
+ # instead of exceptioning like we need to do if this were done in the
62
+ # __init__ method.
63
+
64
+ logging.info('Using %s sanitizer.', self.config.sanitizer)
65
+
66
+ # TODO(metzman) Add a check to ensure we aren't over time limit.
67
+ if not self.config.fuzz_seconds or self.config.fuzz_seconds < 1:
68
+ logging.error(
69
+ 'Fuzz_seconds argument must be greater than 1, but was: %s.',
70
+ self.config.fuzz_seconds)
71
+ return False
72
+
73
+ if not os.path.exists(self.workspace.out):
74
+ logging.error('Out directory: %s does not exist.', self.workspace.out)
75
+ return False
76
+
77
+ if not os.path.exists(self.workspace.artifacts):
78
+ os.makedirs(self.workspace.artifacts)
79
+ elif (not os.path.isdir(self.workspace.artifacts) or
80
+ os.listdir(self.workspace.artifacts)):
81
+ logging.error('Artifacts path: %s exists and is not an empty directory.',
82
+ self.workspace.artifacts)
83
+ return False
84
+
85
+ self.fuzz_target_paths = self.get_fuzz_targets()
86
+ logging.info('Fuzz targets: %s', self.fuzz_target_paths)
87
+ if not self.fuzz_target_paths:
88
+ logging.error('No fuzz targets were found in out directory: %s.',
89
+ self.workspace.out)
90
+ return False
91
+
92
+ return True
93
+
94
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
95
+ """Cleans up after running |fuzz_target_obj|."""
96
+ raise NotImplementedError('Child class must implement method.')
97
+
98
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
99
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
100
+ raise NotImplementedError('Child class must implement method.')
101
+
102
+ @property
103
+ def quit_on_bug_found(self):
104
+ """Property that is checked to determine if fuzzing should quit after first
105
+ bug is found."""
106
+ raise NotImplementedError('Child class must implement method.')
107
+
108
+ def create_fuzz_target_obj(self, target_path, run_seconds):
109
+ """Returns a fuzz target object."""
110
+ return fuzz_target.FuzzTarget(target_path, run_seconds, self.workspace,
111
+ self.clusterfuzz_deployment, self.config)
112
+
113
+ def run_fuzz_targets(self):
114
+ """Runs fuzz targets. Returns True if a bug was found."""
115
+ fuzzers_left_to_run = len(self.fuzz_target_paths)
116
+
117
+ # Make a copy since we will mutate it.
118
+ fuzz_seconds = self.config.fuzz_seconds
119
+
120
+ min_seconds_per_fuzzer = fuzz_seconds // fuzzers_left_to_run
121
+ bug_found = False
122
+ for target_path in self.fuzz_target_paths:
123
+ # By doing this, we can ensure that every fuzz target runs for at least
124
+ # min_seconds_per_fuzzer, but that other fuzzers will have longer to run
125
+ # if one ends early.
126
+ run_seconds = max(fuzz_seconds // fuzzers_left_to_run,
127
+ min_seconds_per_fuzzer)
128
+
129
+ target = self.create_fuzz_target_obj(target_path, run_seconds)
130
+ start_time = time.time()
131
+ result = self.run_fuzz_target(target)
132
+ self.cleanup_after_fuzz_target_run(target)
133
+
134
+ # It's OK if this goes negative since we take max when determining
135
+ # run_seconds.
136
+ fuzz_seconds -= time.time() - start_time
137
+
138
+ fuzzers_left_to_run -= 1
139
+ if not result.testcase or not result.stacktrace:
140
+ logging.info('Fuzzer %s finished running without reportable crashes.',
141
+ target.target_name)
142
+ continue
143
+
144
+ bug_found = True
145
+ if self.quit_on_bug_found:
146
+ logging.info('Bug found. Stopping fuzzing.')
147
+ break
148
+
149
+ # pylint: disable=undefined-loop-variable
150
+ if not target_path:
151
+ logging.error('Ran no fuzz targets.')
152
+ elif self.config.output_sarif:
153
+ # TODO(metzman): Handle multiple crashes.
154
+ write_fuzz_result_to_sarif(result, target_path, self.workspace)
155
+ self.clusterfuzz_deployment.upload_crashes()
156
+ return bug_found
157
+
158
+
159
+ def write_fuzz_result_to_sarif(fuzz_result, target_path, workspace):
160
+ """Write results of fuzzing to SARIF."""
161
+ logging.info('Writing sarif results.')
162
+ sarif_utils.write_stacktrace_to_sarif(fuzz_result.stacktrace, target_path,
163
+ workspace)
164
+
165
+
166
+ class PruneTargetRunner(BaseFuzzTargetRunner):
167
+ """Runner that prunes corpora."""
168
+
169
+ @property
170
+ def quit_on_bug_found(self):
171
+ return False
172
+
173
+ def run_fuzz_target(self, fuzz_target_obj):
174
+ """Prunes with |fuzz_target_obj| and returns the result."""
175
+ result = fuzz_target_obj.prune()
176
+ logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path))
177
+ self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name,
178
+ result.corpus_path,
179
+ replace=True)
180
+ return result
181
+
182
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
183
+ """Cleans up after pruning with |fuzz_target_obj|."""
184
+ fuzz_target_obj.free_disk_if_needed()
185
+
186
+
187
+ NON_FUZZ_TARGETS_FOR_COVERAGE = {
188
+ 'llvm-symbolizer',
189
+ 'jazzer_agent_deploy.jar',
190
+ 'jazzer_driver',
191
+ 'jazzer_driver_with_sanitizer',
192
+ }
193
+
194
+
195
+ def is_coverage_fuzz_target(file_path):
196
+ """Returns whether |file_path| is a fuzz target binary for the purposes of a
197
+ coverage report. Inspired by infra/base-images/base-runner/coverage."""
198
+ if not os.path.isfile(file_path):
199
+ return False
200
+ if not utils.is_executable(file_path):
201
+ return False
202
+ filename = os.path.basename(file_path)
203
+ return filename not in NON_FUZZ_TARGETS_FOR_COVERAGE
204
+
205
+
206
+ def get_coverage_fuzz_targets(out):
207
+ """Returns a list of fuzz targets in |out| for coverage."""
208
+ # We only want fuzz targets from the root because during the coverage build,
209
+ # a lot of the image's filesystem is copied into /out for the purpose of
210
+ # generating coverage reports.
211
+ fuzz_targets = []
212
+ for filename in os.listdir(out):
213
+ file_path = os.path.join(out, filename)
214
+ if is_coverage_fuzz_target(file_path):
215
+ fuzz_targets.append(file_path)
216
+ return fuzz_targets
217
+
218
+
219
+ class CoverageTargetRunner(BaseFuzzTargetRunner):
220
+ """Runner that runs the 'coverage' command."""
221
+
222
+ @property
223
+ def quit_on_bug_found(self):
224
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
225
+
226
+ def get_fuzz_targets(self):
227
+ """Returns fuzz targets in out directory."""
228
+ return get_coverage_fuzz_targets(self.workspace.out)
229
+
230
+ def run_fuzz_targets(self):
231
+ """Generates a coverage report. Always returns False since it never finds
232
+ any bugs."""
233
+ generate_coverage_report.generate_coverage_report(
234
+ self.fuzz_target_paths, self.workspace, self.clusterfuzz_deployment,
235
+ self.config)
236
+ return False
237
+
238
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
239
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
240
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
241
+
242
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
243
+ """Cleans up after running |fuzz_target_obj|."""
244
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
245
+
246
+
247
+ class CiFuzzTargetRunner(BaseFuzzTargetRunner):
248
+ """Runner for fuzz targets used in CI (patch-fuzzing) context."""
249
+
250
+ @property
251
+ def quit_on_bug_found(self):
252
+ return True
253
+
254
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
255
+ """Cleans up after running |fuzz_target_obj|."""
256
+ fuzz_target_obj.free_disk_if_needed()
257
+
258
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
259
+ return fuzz_target_obj.fuzz()
260
+
261
+
262
+ class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
263
+ """Runner for fuzz targets used in batch fuzzing context."""
264
+
265
+ @property
266
+ def quit_on_bug_found(self):
267
+ return False
268
+
269
+ def run_fuzz_target(self, fuzz_target_obj):
270
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
271
+ result = fuzz_target_obj.fuzz(batch=True)
272
+ logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path))
273
+ self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name,
274
+ result.corpus_path)
275
+ return result
276
+
277
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj):
278
+ """Cleans up after running |fuzz_target_obj|."""
279
+ # This must be done after we upload the corpus, otherwise it will be deleted
280
+ # before we get a chance to upload it. We can't delete the fuzz target
281
+ # because it is needed when we upload the build.
282
+ fuzz_target_obj.free_disk_if_needed(delete_fuzz_target=False)
283
+
284
+
285
+ _MODE_RUNNER_MAPPING = {
286
+ 'batch': BatchFuzzTargetRunner,
287
+ 'coverage': CoverageTargetRunner,
288
+ 'prune': PruneTargetRunner,
289
+ 'code-change': CiFuzzTargetRunner,
290
+ }
291
+
292
+
293
+ def get_fuzz_target_runner(config):
294
+ """Returns a fuzz target runner object based on the mode of
295
+ |config|."""
296
+ runner = _MODE_RUNNER_MAPPING[config.mode](config)
297
+ logging.info('run fuzzers MODE is: %s. Runner: %s.', config.mode, runner)
298
+ return runner
299
+
300
+
301
+ def run_fuzzers(config): # pylint: disable=too-many-locals
302
+ """Runs fuzzers for a specific OSS-Fuzz project.
303
+
304
+ Args:
305
+ config: A RunFuzzTargetsConfig.
306
+
307
+ Returns:
308
+ A RunFuzzersResult enum value indicating what happened during fuzzing.
309
+ """
310
+ fuzz_target_runner = get_fuzz_target_runner(config)
311
+ if not fuzz_target_runner.initialize():
312
+ # We didn't fuzz at all because of internal (CIFuzz) errors. And we didn't
313
+ # find any bugs.
314
+ return RunFuzzersResult.ERROR
315
+
316
+ if not fuzz_target_runner.run_fuzz_targets():
317
+ # We fuzzed successfully, but didn't find any bugs (in the fuzz target).
318
+ return RunFuzzersResult.NO_BUG_FOUND
319
+
320
+ # We fuzzed successfully and found bug(s) in the fuzz targets.
321
+ return RunFuzzersResult.BUG_FOUND
local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for running fuzzers."""
15
+ import json
16
+ import os
17
+ import shutil
18
+ import stat
19
+ import sys
20
+ import tempfile
21
+ import unittest
22
+ from unittest import mock
23
+
24
+ import parameterized
25
+ from pyfakefs import fake_filesystem_unittest
26
+
27
+ import build_fuzzers
28
+ import fuzz_target
29
+ import run_fuzzers
30
+
31
+ # pylint: disable=wrong-import-position
32
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33
+ sys.path.append(INFRA_DIR)
34
+
35
+ import helper
36
+ import test_helpers
37
+
38
+ # NOTE: This integration test relies on
39
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
40
+ EXAMPLE_PROJECT = 'example'
41
+
42
+ # Location of files used for testing.
43
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
44
+ 'test_data')
45
+
46
+ MEMORY_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'memory')
47
+ MEMORY_FUZZER = 'curl_fuzzer_memory'
48
+
49
+ UNDEFINED_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'undefined')
50
+ UNDEFINED_FUZZER = 'curl_fuzzer_undefined'
51
+
52
+ FUZZ_SECONDS = 10
53
+
54
+
55
+ class RunFuzzerIntegrationTestMixin: # pylint: disable=too-few-public-methods,invalid-name
56
+ """Mixin for integration test classes that runbuild_fuzzers on builds of a
57
+ specific sanitizer."""
58
+ # These must be defined by children.
59
+ FUZZER_DIR = None
60
+ FUZZER = None
61
+
62
+ def setUp(self):
63
+ """Patch the environ so that we can execute runner scripts."""
64
+ test_helpers.patch_environ(self, runner=True)
65
+
66
+ def _test_run_with_sanitizer(self, fuzzer_dir, sanitizer):
67
+ """Calls run_fuzzers on fuzzer_dir and |sanitizer| and asserts
68
+ the run succeeded and that no bug was found."""
69
+ with test_helpers.temp_dir_copy(fuzzer_dir) as fuzzer_dir_copy:
70
+ config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
71
+ workspace=fuzzer_dir_copy,
72
+ oss_fuzz_project_name='curl',
73
+ sanitizer=sanitizer)
74
+ result = run_fuzzers.run_fuzzers(config)
75
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
76
+
77
+
78
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
79
+ 'INTEGRATION_TESTS=1 not set')
80
+ class RunMemoryFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
81
+ unittest.TestCase):
82
+ """Integration test for build_fuzzers with an MSAN build."""
83
+ FUZZER_DIR = MEMORY_FUZZER_DIR
84
+ FUZZER = MEMORY_FUZZER
85
+
86
+ def test_run_with_memory_sanitizer(self):
87
+ """Tests run_fuzzers with a valid MSAN build."""
88
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'memory')
89
+
90
+
91
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
92
+ 'INTEGRATION_TESTS=1 not set')
93
+ class RunUndefinedFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
94
+ unittest.TestCase):
95
+ """Integration test for build_fuzzers with an UBSAN build."""
96
+ FUZZER_DIR = UNDEFINED_FUZZER_DIR
97
+ FUZZER = UNDEFINED_FUZZER
98
+
99
+ def test_run_with_undefined_sanitizer(self):
100
+ """Tests run_fuzzers with a valid UBSAN build."""
101
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'undefined')
102
+
103
+
104
+ class BaseFuzzTargetRunnerTest(unittest.TestCase):
105
+ """Tests BaseFuzzTargetRunner."""
106
+
107
+ def _create_runner(self, **kwargs): # pylint: disable=no-self-use
108
+ defaults = {
109
+ 'fuzz_seconds': FUZZ_SECONDS,
110
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT
111
+ }
112
+ for default_key, default_value in defaults.items():
113
+ if default_key not in kwargs:
114
+ kwargs[default_key] = default_value
115
+
116
+ config = test_helpers.create_run_config(**kwargs)
117
+ return run_fuzzers.BaseFuzzTargetRunner(config)
118
+
119
+ def _test_initialize_fail(self, expected_error_args, **create_runner_kwargs):
120
+ with mock.patch('logging.error') as mock_error:
121
+ runner = self._create_runner(**create_runner_kwargs)
122
+ self.assertFalse(runner.initialize())
123
+ mock_error.assert_called_with(*expected_error_args)
124
+
125
+ @parameterized.parameterized.expand([(0,), (None,), (-1,)])
126
+ def test_initialize_invalid_fuzz_seconds(self, fuzz_seconds):
127
+ """Tests initialize fails with an invalid fuzz seconds."""
128
+ expected_error_args = ('Fuzz_seconds argument must be greater than 1, '
129
+ 'but was: %s.', fuzz_seconds)
130
+ with tempfile.TemporaryDirectory() as tmp_dir:
131
+ out_path = os.path.join(tmp_dir, 'build-out')
132
+ os.mkdir(out_path)
133
+ with mock.patch('utils.get_fuzz_targets') as mock_get_fuzz_targets:
134
+ mock_get_fuzz_targets.return_value = [
135
+ os.path.join(out_path, 'fuzz_target')
136
+ ]
137
+ self._test_initialize_fail(expected_error_args,
138
+ fuzz_seconds=fuzz_seconds,
139
+ workspace=tmp_dir)
140
+
141
+ def test_initialize_no_out_dir(self):
142
+ """Tests initialize fails with no out dir."""
143
+ with tempfile.TemporaryDirectory() as tmp_dir:
144
+ out_path = os.path.join(tmp_dir, 'build-out')
145
+ expected_error_args = ('Out directory: %s does not exist.', out_path)
146
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
147
+
148
+ def test_initialize_nonempty_artifacts(self):
149
+ """Tests initialize with a file artifacts path."""
150
+ with tempfile.TemporaryDirectory() as tmp_dir:
151
+ out_path = os.path.join(tmp_dir, 'build-out')
152
+ os.mkdir(out_path)
153
+ os.makedirs(os.path.join(tmp_dir, 'out'))
154
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
155
+ with open(artifacts_path, 'w') as artifacts_handle:
156
+ artifacts_handle.write('fake')
157
+ expected_error_args = (
158
+ 'Artifacts path: %s exists and is not an empty directory.',
159
+ artifacts_path)
160
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
161
+
162
+ def test_initialize_bad_artifacts(self):
163
+ """Tests initialize with a non-empty artifacts path."""
164
+ with tempfile.TemporaryDirectory() as tmp_dir:
165
+ out_path = os.path.join(tmp_dir, 'build-out')
166
+ os.mkdir(out_path)
167
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
168
+ os.makedirs(artifacts_path)
169
+ artifact_path = os.path.join(artifacts_path, 'artifact')
170
+ with open(artifact_path, 'w') as artifact_handle:
171
+ artifact_handle.write('fake')
172
+ expected_error_args = (
173
+ 'Artifacts path: %s exists and is not an empty directory.',
174
+ artifacts_path)
175
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
176
+
177
+ @mock.patch('utils.get_fuzz_targets')
178
+ @mock.patch('logging.error')
179
+ def test_initialize_empty_artifacts(self, mock_log_error,
180
+ mock_get_fuzz_targets):
181
+ """Tests initialize with an empty artifacts dir."""
182
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
183
+ with tempfile.TemporaryDirectory() as tmp_dir:
184
+ out_path = os.path.join(tmp_dir, 'build-out')
185
+ os.mkdir(out_path)
186
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
187
+ os.makedirs(artifacts_path)
188
+ runner = self._create_runner(workspace=tmp_dir)
189
+ self.assertTrue(runner.initialize())
190
+ mock_log_error.assert_not_called()
191
+ self.assertTrue(os.path.isdir(artifacts_path))
192
+
193
+ @mock.patch('utils.get_fuzz_targets')
194
+ @mock.patch('logging.error')
195
+ def test_initialize_no_artifacts(self, mock_log_error, mock_get_fuzz_targets):
196
+ """Tests initialize with no artifacts dir (the expected setting)."""
197
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
198
+ with tempfile.TemporaryDirectory() as tmp_dir:
199
+ out_path = os.path.join(tmp_dir, 'build-out')
200
+ os.mkdir(out_path)
201
+ runner = self._create_runner(workspace=tmp_dir)
202
+ self.assertTrue(runner.initialize())
203
+ mock_log_error.assert_not_called()
204
+ self.assertTrue(os.path.isdir(os.path.join(tmp_dir, 'out', 'artifacts')))
205
+
206
+ def test_initialize_no_fuzz_targets(self):
207
+ """Tests initialize with no fuzz targets."""
208
+ with tempfile.TemporaryDirectory() as tmp_dir:
209
+ out_path = os.path.join(tmp_dir, 'build-out')
210
+ os.makedirs(out_path)
211
+ expected_error_args = ('No fuzz targets were found in out directory: %s.',
212
+ out_path)
213
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
214
+
215
+
216
+ class CiFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
217
+ """Tests that CiFuzzTargetRunner works as intended."""
218
+
219
+ def setUp(self):
220
+ self.setUpPyfakefs()
221
+
222
+ @mock.patch('clusterfuzz_deployment.OSSFuzz.upload_crashes')
223
+ @mock.patch('utils.get_fuzz_targets')
224
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.run_fuzz_target')
225
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.create_fuzz_target_obj')
226
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
227
+ mock_run_fuzz_target, mock_get_fuzz_targets,
228
+ mock_upload_crashes):
229
+ """Tests that run_fuzz_targets quits on the first crash it finds."""
230
+ workspace = 'workspace'
231
+ out_path = os.path.join(workspace, 'build-out')
232
+ self.fs.create_dir(out_path)
233
+ config = test_helpers.create_run_config(
234
+ fuzz_seconds=FUZZ_SECONDS,
235
+ workspace=workspace,
236
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
237
+ runner = run_fuzzers.CiFuzzTargetRunner(config)
238
+
239
+ mock_get_fuzz_targets.return_value = ['target1', 'target2']
240
+ runner.initialize()
241
+ testcase = os.path.join(workspace, 'testcase')
242
+ self.fs.create_file(testcase)
243
+ stacktrace = 'stacktrace'
244
+ corpus_dir = 'corpus'
245
+ self.fs.create_dir(corpus_dir)
246
+ mock_run_fuzz_target.return_value = fuzz_target.FuzzResult(
247
+ testcase, stacktrace, corpus_dir)
248
+ magic_mock = mock.MagicMock()
249
+ magic_mock.target_name = 'target1'
250
+ mock_create_fuzz_target_obj.return_value = magic_mock
251
+ self.assertTrue(runner.run_fuzz_targets())
252
+ self.assertEqual(mock_run_fuzz_target.call_count, 1)
253
+ self.assertEqual(mock_upload_crashes.call_count, 1)
254
+
255
+
256
+ class BatchFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
257
+ """Tests that BatchFuzzTargetRunnerTest works as intended."""
258
+ WORKSPACE = 'workspace'
259
+ STACKTRACE = 'stacktrace'
260
+ CORPUS_DIR = 'corpus'
261
+
262
+ def setUp(self):
263
+ self.setUpPyfakefs()
264
+ out_dir = os.path.join(self.WORKSPACE, 'build-out')
265
+ self.fs.create_dir(out_dir)
266
+ self.testcase1 = os.path.join(out_dir, 'testcase-aaa')
267
+ self.fs.create_file(self.testcase1)
268
+ self.testcase2 = os.path.join(out_dir, 'testcase-bbb')
269
+ self.fs.create_file(self.testcase2)
270
+ self.config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
271
+ workspace=self.WORKSPACE,
272
+ cfl_platform='github')
273
+
274
+ @mock.patch('utils.get_fuzz_targets', return_value=['target1', 'target2'])
275
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_crashes')
276
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.run_fuzz_target')
277
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.create_fuzz_target_obj')
278
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
279
+ mock_run_fuzz_target, mock_upload_crashes, _):
280
+ """Tests that run_fuzz_targets doesn't quit on the first crash it finds."""
281
+ runner = run_fuzzers.BatchFuzzTargetRunner(self.config)
282
+ runner.initialize()
283
+
284
+ call_count = 0
285
+
286
+ def mock_run_fuzz_target_impl(_):
287
+ nonlocal call_count
288
+ if call_count == 0:
289
+ testcase = self.testcase1
290
+ elif call_count == 1:
291
+ testcase = self.testcase2
292
+ assert call_count != 2
293
+ call_count += 1
294
+ if not os.path.exists(self.CORPUS_DIR):
295
+ self.fs.create_dir(self.CORPUS_DIR)
296
+ return fuzz_target.FuzzResult(testcase, self.STACKTRACE, self.CORPUS_DIR)
297
+
298
+ mock_run_fuzz_target.side_effect = mock_run_fuzz_target_impl
299
+ magic_mock = mock.MagicMock()
300
+ magic_mock.target_name = 'target1'
301
+ mock_create_fuzz_target_obj.return_value = magic_mock
302
+ self.assertTrue(runner.run_fuzz_targets())
303
+ self.assertEqual(mock_run_fuzz_target.call_count, 2)
304
+ self.assertEqual(mock_upload_crashes.call_count, 1)
305
+
306
+
307
+ class GetCoverageTargetsTest(unittest.TestCase):
308
+ """Tests for get_coverage_fuzz_targets."""
309
+
310
+ def test_get_fuzz_targets(self):
311
+ """Tests that get_coverage_fuzz_targets returns expected targets."""
312
+ with tempfile.TemporaryDirectory() as temp_dir:
313
+ # Setup.
314
+ fuzz_target_path = os.path.join(temp_dir, 'fuzz-target')
315
+ with open(fuzz_target_path, 'w') as file_handle:
316
+ file_handle.write('')
317
+ fuzz_target_st = os.stat(fuzz_target_path)
318
+ os.chmod(fuzz_target_path, fuzz_target_st.st_mode | stat.S_IEXEC)
319
+ non_fuzz_target1 = os.path.join(temp_dir, 'non-fuzz-target1')
320
+ with open(non_fuzz_target1, 'w') as file_handle:
321
+ file_handle.write('LLVMFuzzerTestOneInput')
322
+ subdir = os.path.join(temp_dir, 'subdir')
323
+ os.mkdir(subdir)
324
+ non_fuzz_target2 = os.path.join(subdir, 'non-fuzz-target1')
325
+ with open(non_fuzz_target2, 'w') as file_handle:
326
+ file_handle.write('LLVMFuzzerTestOneInput')
327
+
328
+ self.assertEqual(run_fuzzers.get_coverage_fuzz_targets(temp_dir),
329
+ [fuzz_target_path])
330
+
331
+
332
+ @unittest.skip('TODO(metzman): Fix this test')
333
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
334
+ 'INTEGRATION_TESTS=1 not set')
335
+ class CoverageReportIntegrationTest(unittest.TestCase):
336
+ """Integration tests for coverage reports."""
337
+ SANITIZER = 'coverage'
338
+
339
+ def setUp(self):
340
+ test_helpers.patch_environ(self, runner=True)
341
+
342
+ @mock.patch('filestore.github_actions._upload_artifact_with_upload_js')
343
+ def test_coverage_report(self, _):
344
+ """Tests generation of coverage reports end-to-end, from building to
345
+ generation."""
346
+
347
+ with test_helpers.docker_temp_dir() as temp_dir:
348
+ shared = os.path.join(temp_dir, 'shared')
349
+ os.mkdir(shared)
350
+ copy_command = ('cp -r /opt/code_coverage /shared && '
351
+ 'cp $(which llvm-profdata) /shared && '
352
+ 'cp $(which llvm-cov) /shared')
353
+ assert helper.docker_run([
354
+ '-v', f'{shared}:/shared', 'ghcr.io/aixcc-finals/base-runner', 'bash',
355
+ '-c', copy_command
356
+ ])
357
+
358
+ os.environ['CODE_COVERAGE_SRC'] = os.path.join(shared, 'code_coverage')
359
+ os.environ['PATH'] += os.pathsep + shared
360
+ # Do coverage build.
361
+ build_config = test_helpers.create_build_config(
362
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
363
+ project_repo_name='oss-fuzz',
364
+ workspace=temp_dir,
365
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
366
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
367
+ sanitizer=self.SANITIZER,
368
+ cfl_platform='github',
369
+ # Needed for test not to fail because of permissions issues.
370
+ bad_build_check=False)
371
+ self.assertTrue(build_fuzzers.build_fuzzers(build_config))
372
+
373
+ # TODO(metzman): Get rid of this here and make 'compile' do this.
374
+ chmod_command = ('chmod -R +r /out && '
375
+ 'find /out -type d -exec chmod +x {} +')
376
+
377
+ assert helper.docker_run([
378
+ '-v', f'{os.path.join(temp_dir, "build-out")}:/out',
379
+ 'ghcr.io/aixcc-finals/base-builder', 'bash', '-c', chmod_command
380
+ ])
381
+
382
+ # Generate report.
383
+ run_config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
384
+ workspace=temp_dir,
385
+ sanitizer=self.SANITIZER,
386
+ mode='coverage',
387
+ cfl_platform='github')
388
+ result = run_fuzzers.run_fuzzers(run_config)
389
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
390
+ expected_summary_path = os.path.join(
391
+ TEST_DATA_PATH, 'example_coverage_report_summary.json')
392
+ with open(expected_summary_path) as file_handle:
393
+ expected_summary = json.loads(file_handle.read())
394
+ actual_summary_path = os.path.join(temp_dir, 'cifuzz-coverage',
395
+ 'report', 'linux', 'summary.json')
396
+ with open(actual_summary_path) as file_handle:
397
+ actual_summary = json.loads(file_handle.read())
398
+ self.assertEqual(expected_summary, actual_summary)
399
+
400
+
401
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
402
+ 'INTEGRATION_TESTS=1 not set')
403
+ class RunAddressFuzzersIntegrationTest(RunFuzzerIntegrationTestMixin,
404
+ unittest.TestCase):
405
+ """Integration tests for build_fuzzers with an ASAN build."""
406
+
407
+ BUILD_DIR_NAME = 'cifuzz-latest-build'
408
+
409
+ def test_new_bug_found(self):
410
+ """Tests run_fuzzers with a valid ASAN build."""
411
+ # Set the first return value to True, then the second to False to
412
+ # emulate a bug existing in the current PR but not on the downloaded
413
+ # OSS-Fuzz build.
414
+ with mock.patch('fuzz_target.FuzzTarget.is_reproducible',
415
+ side_effect=[True, False]):
416
+ with tempfile.TemporaryDirectory() as tmp_dir:
417
+ workspace = os.path.join(tmp_dir, 'workspace')
418
+ shutil.copytree(TEST_DATA_PATH, workspace)
419
+ config = test_helpers.create_run_config(
420
+ fuzz_seconds=FUZZ_SECONDS,
421
+ workspace=workspace,
422
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
423
+ result = run_fuzzers.run_fuzzers(config)
424
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.BUG_FOUND)
425
+
426
+ @mock.patch('fuzz_target.FuzzTarget.is_reproducible',
427
+ side_effect=[True, True])
428
+ def test_old_bug_found(self, _):
429
+ """Tests run_fuzzers with a bug found in OSS-Fuzz before."""
430
+ with tempfile.TemporaryDirectory() as tmp_dir:
431
+ workspace = os.path.join(tmp_dir, 'workspace')
432
+ shutil.copytree(TEST_DATA_PATH, workspace)
433
+ config = test_helpers.create_run_config(
434
+ fuzz_seconds=FUZZ_SECONDS,
435
+ workspace=workspace,
436
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
437
+ result = run_fuzzers.run_fuzzers(config)
438
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
439
+
440
+ def test_invalid_build(self):
441
+ """Tests run_fuzzers with an invalid ASAN build."""
442
+ with tempfile.TemporaryDirectory() as tmp_dir:
443
+ out_path = os.path.join(tmp_dir, 'build-out')
444
+ os.mkdir(out_path)
445
+ config = test_helpers.create_run_config(
446
+ fuzz_seconds=FUZZ_SECONDS,
447
+ workspace=tmp_dir,
448
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
449
+ result = run_fuzzers.run_fuzzers(config)
450
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.ERROR)
451
+
452
+
453
+ class GetFuzzTargetRunnerTest(unittest.TestCase):
454
+ """Tests for get_fuzz_fuzz_target_runner."""
455
+
456
+ @parameterized.parameterized.expand([
457
+ ('batch', run_fuzzers.BatchFuzzTargetRunner),
458
+ ('code-change', run_fuzzers.CiFuzzTargetRunner),
459
+ ('coverage', run_fuzzers.CoverageTargetRunner)
460
+ ])
461
+ def test_get_fuzz_target_runner(self, mode, fuzz_target_runner_cls):
462
+ """Tests that get_fuzz_target_runner returns the correct runner based on the
463
+ specified mode."""
464
+ with tempfile.TemporaryDirectory() as tmp_dir:
465
+ run_config = test_helpers.create_run_config(
466
+ fuzz_seconds=FUZZ_SECONDS,
467
+ workspace=tmp_dir,
468
+ oss_fuzz_project_name='example',
469
+ mode=mode)
470
+ runner = run_fuzzers.get_fuzz_target_runner(run_config)
471
+ self.assertTrue(isinstance(runner, fuzz_target_runner_cls))
472
+
473
+
474
+ if __name__ == '__main__':
475
+ unittest.main()
local-test-tika-delta-02/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /* A detector that uses ptrace to identify shell injection vulnerabilities. */
17
+
18
+ /* C standard library */
19
+ #include <errno.h>
20
+ #include <signal.h>
21
+ #include <stdio.h>
22
+ #include <string.h>
23
+
24
+ /* POSIX */
25
+ #include <sys/stat.h>
26
+ #include <sys/user.h>
27
+ #include <sys/wait.h>
28
+ #include <unistd.h>
29
+
30
+ /* Linux */
31
+ #include <sys/ptrace.h>
32
+ #include <syscall.h>
33
+ #include <fcntl.h>
34
+
35
+ #include <fstream>
36
+ #include <iostream>
37
+ #include <map>
38
+ #include <set>
39
+ #include <sstream>
40
+ #include <string>
41
+ #include <vector>
42
+
43
+ #include "inspect_utils.h"
44
+ #include "inspect_dns.h"
45
+
46
+ #define DEBUG_LOGS 0
47
+
48
+ #if DEBUG_LOGS
49
+ #define debug_log(...) \
50
+ do { \
51
+ fprintf(stderr, __VA_ARGS__); \
52
+ fflush(stdout); \
53
+ fputc('\n', stderr); \
54
+ } while (0)
55
+ #else
56
+ #define debug_log(...)
57
+ #endif
58
+
59
+ #define fatal_log(...) \
60
+ do { \
61
+ fprintf(stderr, __VA_ARGS__); \
62
+ fputc('\n', stderr); \
63
+ exit(EXIT_FAILURE); \
64
+ } while (0)
65
+
66
+ // The magic string that we'll use to detect full control over the command
67
+ // executed.
68
+ const std::string kTripWire = "/tmp/tripwire";
69
+ // Shell injection bug confirmed with /tmp/tripwire.
70
+ const std::string kInjectionError = "Shell injection";
71
+ // Shell corruption bug detected based on syntax error.
72
+ const std::string kCorruptionError = "Shell corruption";
73
+ // The magic string that we'll use to detect arbitrary file open
74
+ const std::string kFzAbsoluteDirectory = "/fz/";
75
+ // Arbitrary file open in /fz/
76
+ const std::string kArbitraryFileOpenError = "Arbitrary file open";
77
+ // Assuming only shorter (than this constant) top dir are legitly used.
78
+ constexpr int kRootDirMaxLength = 16;
79
+
80
+ // The PID of the root process we're fuzzing.
81
+ pid_t g_root_pid;
82
+
83
+ // Map of a PID/TID its PID/TID creator and wether it ran exec.
84
+ std::map<pid_t, ThreadParent> root_pids;
85
+
86
+ // Assuming the longest pathname is "/bin/bash".
87
+ constexpr int kShellPathnameLength = 20;
88
+
89
+ // Syntax error messages of each shell.
90
+ const std::map<std::string, std::set<std::string>> kShellSyntaxErrors = {
91
+ {"bash",
92
+ {
93
+ ": command not found", // General
94
+ ": syntax error", // Unfinished " or ' or ` or if, leading | or ;
95
+ ": missing `]'", // Unfinished [
96
+ ": event not found", // ! leads large numbers
97
+ ": No such file or directory", // Leading < or /
98
+ }},
99
+ {"csh",
100
+ {
101
+ ": Command not found.", // General
102
+ ": Missing }.", // Unfinished {
103
+ "Too many ('s.", // Unfinished (
104
+ "Invalid null command.", // Leading | or < or >
105
+ "Missing name for redirect.", // Single < or >
106
+ ": No match.", // Leading ? or [ or *
107
+ "Modifier failed.", // Leading ^
108
+ "No previous left hand side.", // A ^
109
+ ": No such job.", // Leading %
110
+ ": No current job.", // A %
111
+ ": Undefined variable.", // Containing $
112
+ ": Event not found.", // ! leads large numbers
113
+ // TODO: Make this more specific.
114
+ "Unmatched", // Unfinished " or ' or `, leading ;
115
+ }},
116
+ {"dash",
117
+ {
118
+ "not found", // General
119
+ "Syntax error", // Unfinished " or ' or ` or if, leading | or ; or &
120
+ "missing ]", // Unfinished [
121
+ "No such file", // Leading <
122
+ }},
123
+ {"zsh",
124
+ {
125
+ ": command not found", // General
126
+ ": syntax error", // Unfinished " or ' or `
127
+ ": ']' expected", // Unfinished [
128
+ ": no such file or directory", // Leading < or /
129
+ ": parse error near", // Leading |, or &
130
+ ": no such user or named directory", // Leading ~
131
+ }},
132
+ };
133
+
134
+ // Shells used by Processes.
135
+ std::map<pid_t, std::string> g_shell_pids;
136
+
137
+ struct Tracee {
138
+ pid_t pid;
139
+ bool syscall_enter = true;
140
+
141
+ Tracee(pid_t pid) : pid(pid) {}
142
+ };
143
+
144
+ pid_t run_child(char **argv) {
145
+ // Run the program under test with its args as a child process
146
+ pid_t pid = fork();
147
+ switch (pid) {
148
+ case -1:
149
+ fatal_log("Fork failed: %s", strerror(errno));
150
+ case 0:
151
+ raise(SIGSTOP);
152
+ execvp(argv[0], argv);
153
+ fatal_log("execvp: %s", strerror(errno));
154
+ }
155
+ return pid;
156
+ }
157
+
158
+ // Construct a string with the memory specified in a register.
159
+ std::string read_string(pid_t pid, unsigned long reg, unsigned long length) {
160
+ auto memory = read_memory(pid, reg, length);
161
+ if (!memory.size()) {
162
+ return "";
163
+ }
164
+
165
+ std::string content(reinterpret_cast<char *>(memory.data()),
166
+ std::min(memory.size(), length));
167
+ return content;
168
+ }
169
+
170
+ void inspect_for_injection(pid_t pid, const user_regs_struct &regs) {
171
+ // Inspect a PID's registers for the sign of shell injection.
172
+ std::string path = read_string(pid, regs.rdi, kTripWire.length());
173
+ if (!path.length()) {
174
+ return;
175
+ }
176
+ debug_log("inspecting");
177
+ if (path == kTripWire) {
178
+ report_bug(kInjectionError, pid);
179
+ }
180
+ }
181
+
182
+ std::string get_pathname(pid_t pid, const user_regs_struct &regs) {
183
+ // Parse the pathname from the memory specified in the RDI register.
184
+ std::string pathname = read_string(pid, regs.rdi, kShellPathnameLength);
185
+ debug_log("Pathname is %s (len %lu)\n", pathname.c_str(), pathname.length());
186
+ return pathname;
187
+ }
188
+
189
+ std::string match_shell(std::string binary_pathname);
190
+
191
+ // Identify the exact shell behind sh
192
+ std::string identify_sh(std::string path) {
193
+ char shell_pathname[kShellPathnameLength];
194
+ auto written = readlink(path.c_str(), shell_pathname, kShellPathnameLength - 1);
195
+ if (written == -1) {
196
+ std::cerr << "Cannot query which shell is behind sh: readlink failed on "
197
+ << path << ": "
198
+ << strerror(errno) << "\n";
199
+ std::cerr << "Assuming the shell is dash\n";
200
+ return "dash";
201
+ }
202
+ shell_pathname[written] = '\0';
203
+
204
+ debug_log("sh links to %s\n", shell_pathname);
205
+ std::string shell_pathname_str(shell_pathname);
206
+
207
+ return match_shell(shell_pathname_str);
208
+ }
209
+
210
+ std::string match_shell(std::string binary_pathname) {
211
+ // Identify the name of the shell used in the pathname.
212
+ if (!binary_pathname.length()) {
213
+ return "";
214
+ }
215
+
216
+ // We use c_str() to accept only the null terminated string.
217
+ std::string binary_name = binary_pathname.substr(
218
+ binary_pathname.find_last_of("/") + 1).c_str();
219
+
220
+ debug_log("Binary is %s (%lu)\n", binary_name.c_str(),
221
+ binary_name.length());
222
+
223
+ for (const auto &item : kShellSyntaxErrors) {
224
+ std::string known_shell = item.first;
225
+ if (binary_name == "sh") {
226
+ debug_log("Matched sh: Needs to identify which specific shell it is.\n");
227
+ return identify_sh(binary_pathname);
228
+ }
229
+ if (binary_name == known_shell) {
230
+ debug_log("Matched %s\n", binary_name.c_str());
231
+ return known_shell;
232
+ }
233
+ }
234
+ return "";
235
+ }
236
+
237
+ std::string get_shell(pid_t pid, const user_regs_struct &regs) {
238
+ // Get shell name used in a process.
239
+ std::string binary_pathname = get_pathname(pid, regs);
240
+ return match_shell(binary_pathname);
241
+ }
242
+
243
+ void match_error_pattern(std::string buffer, std::string shell, pid_t pid) {
244
+ auto error_patterns = kShellSyntaxErrors.at(shell);
245
+ for (const auto &pattern : error_patterns) {
246
+ if (buffer.find(pattern) != std::string::npos) {
247
+ std::cerr << "--- Found a sign of shell corruption ---\n"
248
+ << buffer.c_str()
249
+ << "\n----------------------------------------\n";
250
+ // If a shell corruption error happens, kill its parent.
251
+ auto parent = root_pids[pid];
252
+ while (!parent.ran_exec) {
253
+ if (parent.parent_tid == g_root_pid) {
254
+ break;
255
+ }
256
+ parent = root_pids[parent.parent_tid];
257
+ }
258
+ report_bug(kCorruptionError, parent.parent_tid);
259
+ }
260
+ }
261
+ }
262
+
263
+ void inspect_for_corruption(pid_t pid, const user_regs_struct &regs) {
264
+ // Inspect a PID's registers for shell corruption.
265
+ std::string buffer = read_string(pid, regs.rsi, regs.rdx);
266
+ debug_log("Write buffer: %s\n", buffer.c_str());
267
+ match_error_pattern(buffer, g_shell_pids[pid], pid);
268
+ }
269
+
270
+ void log_file_open(std::string path, int flags, pid_t pid) {
271
+ report_bug(kArbitraryFileOpenError, pid);
272
+ std::cerr << "===File opened: " << path.c_str() << ", flags = " << flags << ",";
273
+ switch (flags & 3) {
274
+ case O_RDONLY:
275
+ std::cerr << "O_RDONLY";
276
+ break;
277
+ case O_WRONLY:
278
+ std::cerr << "O_WRONLY";
279
+ break;
280
+ case O_RDWR:
281
+ std::cerr << "O_RDWR";
282
+ break;
283
+ default:
284
+ std::cerr << "unknown";
285
+ }
286
+ std::cerr << "===\n";
287
+ }
288
+
289
+ bool has_unprintable(const std::string &value) {
290
+ for (size_t i = 0; i < value.length(); i++) {
291
+ if (value[i] & 0x80) {
292
+ return true;
293
+ }
294
+ }
295
+ return false;
296
+ }
297
+
298
+ void inspect_for_arbitrary_file_open(pid_t pid, const user_regs_struct &regs) {
299
+ // Inspect a PID's register for the sign of arbitrary file open.
300
+ std::string path = read_string(pid, regs.rsi, kRootDirMaxLength);
301
+ if (!path.length()) {
302
+ return;
303
+ }
304
+ if (path.substr(0, kFzAbsoluteDirectory.length()) == kFzAbsoluteDirectory) {
305
+ log_file_open(path, regs.rdx, pid);
306
+ return;
307
+ }
308
+ if (path[0] == '/' && path.length() > 1) {
309
+ std::string path_absolute_topdir = path;
310
+ size_t root_dir_end = path.find('/', 1);
311
+ if (root_dir_end != std::string::npos) {
312
+ path_absolute_topdir = path.substr(0, root_dir_end);
313
+ }
314
+ if (has_unprintable(path_absolute_topdir)) {
315
+ struct stat dirstat;
316
+ if (stat(path_absolute_topdir.c_str(), &dirstat) != 0) {
317
+ log_file_open(path, regs.rdx, pid);
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ int trace(std::map<pid_t, Tracee> pids) {
324
+ unsigned long exit_status = 0;
325
+ while (!pids.empty()) {
326
+ std::vector<pid_t> new_pids;
327
+
328
+ auto it = pids.begin();
329
+
330
+ while (it != pids.end()) {
331
+ auto pid = it->first;
332
+ auto &tracee = it->second;
333
+ int status = 0;
334
+
335
+ int result = waitpid(pid, &status, __WALL | WNOHANG);
336
+ if (result == -1) {
337
+ it = pids.erase(it);
338
+ continue;
339
+ }
340
+
341
+ if (result == 0) {
342
+ // Nothing to report yet.
343
+ ++it;
344
+ continue;
345
+ }
346
+
347
+ if (WIFEXITED(status) || WIFSIGNALED(status)) {
348
+ debug_log("%d exited", pid);
349
+ it = pids.erase(it);
350
+ // Remove pid from the watchlist when it exits
351
+ g_shell_pids.erase(pid);
352
+ root_pids.erase(pid);
353
+ continue;
354
+ }
355
+
356
+ // ptrace sets 0x80 for syscalls (with PTRACE_O_TRACESYSGOOD set).
357
+ bool is_syscall =
358
+ WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80);
359
+ int sig = 0;
360
+ if (!is_syscall) {
361
+ // Handle generic signal.
362
+ siginfo_t siginfo;
363
+ if (ptrace(PTRACE_GETSIGINFO, pid, nullptr, &siginfo) == -1) {
364
+ debug_log("ptrace(PTRACE_GETSIGINFO, %d): %s", pid, strerror(errno));
365
+ continue;
366
+ }
367
+ sig = siginfo.si_signo;
368
+ debug_log("forwarding signal %d to %d", sig, pid);
369
+ }
370
+
371
+ if ((status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8)))) {
372
+ debug_log("%d exiting", pid);
373
+ if (pid == g_root_pid) {
374
+ if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &exit_status) == -1) {
375
+ debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno));
376
+ }
377
+ debug_log("got exit status from root process: %lu", exit_status);
378
+ }
379
+
380
+ if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) {
381
+ debug_log("ptrace(PTRACE_DETACH, %d): %s", pid, strerror(errno));
382
+ }
383
+ continue;
384
+ }
385
+
386
+ if (WIFSTOPPED(status) &&
387
+ (status >> 8 == (SIGTRAP | (PTRACE_EVENT_CLONE << 8)) ||
388
+ status >> 8 == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
389
+ status >> 8 == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)))) {
390
+ long new_pid;
391
+ if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &new_pid) == -1) {
392
+ debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno));
393
+ continue;
394
+ }
395
+ debug_log("forked %ld", new_pid);
396
+ new_pids.push_back(new_pid);
397
+ root_pids.emplace(new_pid, ThreadParent(pid));
398
+ }
399
+
400
+ if (is_syscall) {
401
+ user_regs_struct regs;
402
+ if (ptrace(PTRACE_GETREGS, pid, 0, &regs) == -1) {
403
+ debug_log("ptrace(PTRACE_GETREGS, %d): %s", pid, strerror(errno));
404
+ continue;
405
+ }
406
+
407
+ if (tracee.syscall_enter) {
408
+ if (regs.orig_rax == __NR_execve) {
409
+ // This is a new process.
410
+ auto parent = root_pids[pid];
411
+ parent.ran_exec = true;
412
+ root_pids[pid] = parent;
413
+ inspect_for_injection(pid, regs);
414
+ std::string shell = get_shell(pid, regs);
415
+ if (shell != "") {
416
+ debug_log("Shell parsed: %s", shell.c_str());
417
+ g_shell_pids.insert(std::make_pair(pid, shell));
418
+ }
419
+ }
420
+
421
+ inspect_dns_syscalls(pid, regs);
422
+
423
+ if (regs.orig_rax == __NR_openat) {
424
+ // TODO(metzman): Re-enable this once we have config/flag support.
425
+ // inspect_for_arbitrary_file_open(pid, regs);
426
+ }
427
+
428
+ if (regs.orig_rax == __NR_write &&
429
+ g_shell_pids.find(pid) != g_shell_pids.end()) {
430
+ debug_log("Inspecting the `write` buffer of shell process %d.",
431
+ pid);
432
+ inspect_for_corruption(pid, regs);
433
+ }
434
+ }
435
+
436
+ // TODO: Check for commands with invalid syntax passed to /bin/sh and
437
+ // other shells.
438
+ // TODO: It's possible the process we're fuzzing can communicate with
439
+ // another process to execute code. Our check wouldn't catch this
440
+ // currently.
441
+ tracee.syscall_enter = !tracee.syscall_enter;
442
+ }
443
+
444
+ if (ptrace(PTRACE_SYSCALL, pid, nullptr, sig) == -1) {
445
+ debug_log("ptrace(PTRACE_SYSCALL, %d): %s", pid, strerror(errno));
446
+ continue;
447
+ }
448
+
449
+ ++it;
450
+ }
451
+
452
+ for (const auto &pid : new_pids) {
453
+ pids.emplace(pid, Tracee(pid));
454
+ }
455
+ }
456
+ return static_cast<int>(exit_status >> 8);
457
+ }
458
+
459
+ int main(int argc, char **argv) {
460
+ if (argc <= 1) {
461
+ fatal_log("Expecting at least one arguments, received %d", argc - 1);
462
+ }
463
+
464
+ // Create an executable tripwire file, as programs may check for existence
465
+ // before actually calling exec.
466
+ std::ofstream tripwire(kTripWire);
467
+ tripwire.close();
468
+ chmod(kTripWire.c_str(), 0755);
469
+
470
+ pid_t pid = run_child(argv + 1);
471
+
472
+ long options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK |
473
+ PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE |
474
+ PTRACE_O_TRACEEXIT;
475
+
476
+ if (ptrace(PTRACE_SEIZE, pid, nullptr, options) == -1) {
477
+ fatal_log("ptrace(PTRACE_SEIZE): %s", strerror(errno));
478
+ }
479
+
480
+ if (waitpid(pid, nullptr, __WALL) == -1) {
481
+ fatal_log("waitpid: %s", strerror(errno));
482
+ }
483
+
484
+ if (ptrace(PTRACE_SYSCALL, pid, 0, 0) == -1) {
485
+ fatal_log("ptrace(PTRACE_SYSCALL): %s", strerror(errno));
486
+ }
487
+
488
+ g_root_pid = pid;
489
+ std::map<pid_t, Tracee> pids;
490
+ pids.emplace(pid, Tracee(pid));
491
+ root_pids.emplace(pid, ThreadParent(pid));
492
+ return trace(pids);
493
+ }
local-test-tika-delta-02/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ #include <stdlib.h>
18
+ #include <stdio.h>
19
+ #include <string>
20
+ #include <iostream>
21
+
22
+ #include <string.h>
23
+ #include <sys/types.h>
24
+ #include <sys/socket.h>
25
+ #include <netdb.h>
26
+
27
+ extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) {
28
+ std::string str(data, size);
29
+ std::cout << "INPUT" << str << std::endl;
30
+
31
+ struct addrinfo *result = NULL;
32
+
33
+ getaddrinfo(str.c_str(), NULL, NULL, &result);
34
+ if (result) {
35
+ freeaddrinfo(result);
36
+ }
37
+
38
+ return 0;
39
+ }
local-test-tika-delta-02/fuzz-tooling/infra/experimental/SystemSan/vuln.dict ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ "/tmp/tripwire"
2
+ "/fz/"
3
+ "f.z"
local-test-tika-delta-02/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+ import {loadCoverageIntoWorkspace} from '../coverageHelper';
19
+ import {println} from '../logger';
20
+ import {getApi, FileDownloader} from '@microsoft/vscode-file-downloader-api';
21
+
22
+ /*
23
+ * Displays code coverage from OSS-Fuzz.
24
+ *
25
+ * Downloads a code coverage report from the OSS-Fuzz online storage, and then overlays
26
+ * the relevant source files with the coverage information.
27
+ */
28
+ export async function displayCodeCoverageFromOssFuzz(
29
+ context: vscode.ExtensionContext
30
+ ) {
31
+ const projectName = await vscode.window.showInputBox({
32
+ value: '',
33
+ placeHolder: "The project you'd like to get code coverage for.",
34
+ });
35
+ if (!projectName) {
36
+ return;
37
+ }
38
+ println('Getting code coverage for ' + projectName);
39
+
40
+ const fileDownloader: FileDownloader = await getApi();
41
+
42
+ const currentDate = new Date();
43
+ const yesterday = new Date(currentDate);
44
+ yesterday.setDate(yesterday.getDate() - 1);
45
+
46
+ const day = yesterday.getDate();
47
+ const month = yesterday.getMonth();
48
+ const year = yesterday.getFullYear();
49
+
50
+ try {
51
+ const codeCoverageFile: vscode.Uri = await fileDownloader.downloadFile(
52
+ vscode.Uri.parse(
53
+ 'https://storage.googleapis.com/oss-fuzz-coverage/' +
54
+ projectName +
55
+ '/textcov_reports/' +
56
+ year.toString() +
57
+ month.toString() +
58
+ day.toString() +
59
+ '/all_cov.json'
60
+ ),
61
+ 'all_cov.json',
62
+ context
63
+ );
64
+ await loadCoverageIntoWorkspace(context, codeCoverageFile);
65
+ } catch (err) {
66
+ println(
67
+ 'Could not get the URL. Currently, this feature is only supported for Python projects'
68
+ );
69
+ return;
70
+ }
71
+ }