Kitxuuu commited on
Commit
247f9d3
·
verified ·
1 Parent(s): 5cdcc87

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/MAINTAINERS.csv +7 -0
  2. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/README.md +23 -0
  3. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/bisector.py +318 -0
  4. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/build_specified_commit_test.py +126 -0
  5. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/base_runner_utils.py +33 -0
  6. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py +403 -0
  7. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py +48 -0
  8. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/cloudbuild.yaml +52 -0
  9. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/config_utils_test.py +200 -0
  10. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/environment.py +51 -0
  11. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/sarif_utils_test.py +128 -0
  12. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/test_helpers.py +117 -0
  13. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/workspace_utils.py +85 -0
  14. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/helper.py +1810 -0
  15. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/manifest.py +61 -0
  16. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/pr_helper.py +300 -0
  17. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/retry.py +106 -0
  18. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/run_fuzzers.Dockerfile +31 -0
  19. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/templates.py +119 -0
  20. local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/test +1 -0
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/MAINTAINERS.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Name,Email,Github Username
2
+ Adam Korcz,adam@adalogics.com,AdamKorcz
3
+ David Korczynski,david@adalogics.com,DavidKorczynski
4
+ Dongge Liu,donggeliu@google.com,Alan32Liu
5
+ Holly Gong,gongh@google.com,hogo6002
6
+ Jonathan Metzman,metzman@google.com,jonathanmetzman
7
+ Oliver Chang,ochang@google.com,oliverchang
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # infra
2
+ > OSS-Fuzz project infrastructure
3
+
4
+ Core infrastructure:
5
+ * [`base-images`](base-images/) - docker images for building fuzz targets & corresponding jenkins
6
+ pipeline.
7
+
8
+ Continuous Integration infrastructure:
9
+
10
+ * [`ci`](ci/) - script to build projects in CI.
11
+
12
+ ## helper.py
13
+ > script to automate common docker operations
14
+
15
+ | Command | Description |
16
+ |---------|-------------
17
+ | `generate` | Generates skeleton files for a new project |
18
+ | `build_image` | Builds a docker image for a given project |
19
+ | `build_fuzzers` | Builds fuzz targets for a given project |
20
+ | `run_fuzzer` | Runs a fuzz target in a docker container |
21
+ | `coverage` | Runs fuzz target(s) in a docker container and generates a code coverage report. See [Code Coverage doc](https://google.github.io/oss-fuzz/advanced-topics/code-coverage/) |
22
+ | `reproduce` | Runs a testcase to reproduce a crash |
23
+ | `shell` | Starts a shell inside the docker image for a project |
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/bisector.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 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
+ """Uses bisection to determine which commit a bug was introduced and fixed.
15
+ This module takes a high and a low commit SHA, a repo name, and a bug.
16
+ The module bisects the high and low commit SHA searching for the location
17
+ where the bug was introduced. It also looks for where the bug was fixed.
18
+ This is done with the following steps:
19
+
20
+
21
+ NOTE: Needs to be run from root of the OSS-Fuzz source checkout.
22
+
23
+ Typical usage example:
24
+ python3 infra/bisector.py
25
+ --old_commit 1e403e9259a1abedf108ab86f711ba52c907226d
26
+ --new_commit f79be4f2330f4b89ea2f42e1c44ca998c59a0c0f
27
+ --fuzz_target rules_fuzzer
28
+ --project_name yara
29
+ --testcase infra/yara_testcase
30
+ --sanitizer address
31
+ """
32
+
33
+ import argparse
34
+ import collections
35
+ import logging
36
+ import os
37
+ import sys
38
+ import tempfile
39
+
40
+ import build_specified_commit
41
+ import helper
42
+ import repo_manager
43
+ import utils
44
+
45
+ Result = collections.namedtuple('Result', ['repo_url', 'commit'])
46
+
47
+ START_MARKERS = [
48
+ '==ERROR',
49
+ '==WARNING',
50
+ ]
51
+
52
+ END_MARKERS = [
53
+ 'SUMMARY:',
54
+ ]
55
+
56
+ DEDUP_TOKEN_MARKER = 'DEDUP_TOKEN:'
57
+
58
+
59
+ class BisectError(Exception):
60
+ """Bisection error."""
61
+
62
+ def __init__(self, message, repo_url):
63
+ super().__init__(message)
64
+ self.repo_url = repo_url
65
+
66
+
67
+ def main():
68
+ """Finds the commit SHA where an error was initally introduced."""
69
+ logging.getLogger().setLevel(logging.INFO)
70
+ utils.chdir_to_root()
71
+ parser = argparse.ArgumentParser(
72
+ description='git bisection for finding introduction of bugs')
73
+
74
+ parser.add_argument('--project_name',
75
+ help='The name of the project where the bug occurred.',
76
+ required=True)
77
+ parser.add_argument('--new_commit',
78
+ help='The newest commit SHA to be bisected.',
79
+ required=True)
80
+ parser.add_argument('--old_commit',
81
+ help='The oldest commit SHA to be bisected.',
82
+ required=True)
83
+ parser.add_argument('--fuzz_target',
84
+ help='The name of the fuzzer to be built.',
85
+ required=True)
86
+ parser.add_argument('--test_case_path',
87
+ help='The path to test case.',
88
+ required=True)
89
+ parser.add_argument('--engine',
90
+ help='The default is "libfuzzer".',
91
+ default='libfuzzer')
92
+ parser.add_argument('--sanitizer',
93
+ default='address',
94
+ help='The default is "address".')
95
+ parser.add_argument('--type',
96
+ choices=['regressed', 'fixed'],
97
+ help='The bisection type.',
98
+ required=True)
99
+ parser.add_argument('--architecture', default='x86_64')
100
+ args = parser.parse_args()
101
+
102
+ build_data = build_specified_commit.BuildData(project_name=args.project_name,
103
+ engine=args.engine,
104
+ sanitizer=args.sanitizer,
105
+ architecture=args.architecture)
106
+
107
+ result = bisect(args.type, args.old_commit, args.new_commit,
108
+ args.test_case_path, args.fuzz_target, build_data)
109
+ if not result.commit:
110
+ logging.error('No error was found in commit range %s:%s', args.old_commit,
111
+ args.new_commit)
112
+ return 1
113
+ if result.commit == args.old_commit:
114
+ logging.error(
115
+ 'Bisection Error: Both the first and the last commits in'
116
+ 'the given range have the same behavior, bisection is not possible. ')
117
+ return 1
118
+ if args.type == 'regressed':
119
+ print('Error was introduced at commit %s' % result.commit)
120
+ elif args.type == 'fixed':
121
+ print('Error was fixed at commit %s' % result.commit)
122
+ return 0
123
+
124
+
125
+ def _get_dedup_token(output):
126
+ """Get dedup token."""
127
+ for line in output.splitlines():
128
+ token_location = line.find(DEDUP_TOKEN_MARKER)
129
+ if token_location == -1:
130
+ continue
131
+
132
+ return line[token_location + len(DEDUP_TOKEN_MARKER):].strip()
133
+
134
+ return None
135
+
136
+
137
+ def _check_for_crash(project_name, fuzz_target, testcase_path):
138
+ """Check for crash."""
139
+
140
+ def docker_run(args, **kwargs):
141
+ del kwargs
142
+ command = ['docker', 'run', '--rm', '--privileged']
143
+ if sys.stdin.isatty():
144
+ command.append('-i')
145
+
146
+ return utils.execute(command + args)
147
+
148
+ logging.info('Checking for crash')
149
+ out, err, return_code = helper.reproduce_impl(
150
+ project=helper.Project(project_name),
151
+ fuzzer_name=fuzz_target,
152
+ valgrind=False,
153
+ env_to_add=[],
154
+ fuzzer_args=[],
155
+ testcase_path=testcase_path,
156
+ run_function=docker_run,
157
+ err_result=(None, None, None))
158
+ if return_code is None:
159
+ return None
160
+
161
+ logging.info('stdout =\n%s', out)
162
+ logging.info('stderr =\n%s', err)
163
+
164
+ # pylint: disable=unsupported-membership-test
165
+ has_start_marker = any(
166
+ marker in out or marker in err for marker in START_MARKERS)
167
+ has_end_marker = any(marker in out or marker in err for marker in END_MARKERS)
168
+ if not has_start_marker or not has_end_marker:
169
+ return None
170
+
171
+ return _get_dedup_token(out + err)
172
+
173
+
174
+ # pylint: disable=too-many-locals
175
+ # pylint: disable=too-many-arguments
176
+ # pylint: disable=too-many-statements
177
+ def _bisect(bisect_type, old_commit, new_commit, testcase_path, fuzz_target,
178
+ build_data):
179
+ """Perform the bisect."""
180
+ # pylint: disable=too-many-branches
181
+ base_builder_repo = build_specified_commit.load_base_builder_repo()
182
+
183
+ with tempfile.TemporaryDirectory() as tmp_dir:
184
+ repo_url, repo_path = build_specified_commit.detect_main_repo(
185
+ build_data.project_name, commit=new_commit)
186
+ if not repo_url or not repo_path:
187
+ raise ValueError('Main git repo can not be determined.')
188
+
189
+ if old_commit == new_commit:
190
+ raise BisectError('old_commit is the same as new_commit', repo_url)
191
+
192
+ # Copy /src from the built Docker container to ensure all dependencies
193
+ # exist. This will be mounted when running them.
194
+ host_src_dir = build_specified_commit.copy_src_from_docker(
195
+ build_data.project_name, tmp_dir)
196
+
197
+ bisect_repo_manager = repo_manager.RepoManager(
198
+ os.path.join(host_src_dir, os.path.basename(repo_path)))
199
+ bisect_repo_manager.fetch_all_remotes()
200
+
201
+ commit_list = bisect_repo_manager.get_commit_list(new_commit, old_commit)
202
+
203
+ old_idx = len(commit_list) - 1
204
+ new_idx = 0
205
+ logging.info('Testing against new_commit (%s)', commit_list[new_idx])
206
+ if not build_specified_commit.build_fuzzers_from_commit(
207
+ commit_list[new_idx],
208
+ bisect_repo_manager,
209
+ host_src_dir,
210
+ build_data,
211
+ base_builder_repo=base_builder_repo):
212
+ raise BisectError('Failed to build new_commit', repo_url)
213
+
214
+ if bisect_type == 'fixed':
215
+ should_crash = False
216
+ elif bisect_type == 'regressed':
217
+ should_crash = True
218
+ else:
219
+ raise BisectError('Invalid bisect type ' + bisect_type, repo_url)
220
+
221
+ expected_error = _check_for_crash(build_data.project_name, fuzz_target,
222
+ testcase_path)
223
+ logging.info('new_commit result = %s', expected_error)
224
+
225
+ if not should_crash and expected_error:
226
+ logging.warning('new_commit crashed but not shouldn\'t. '
227
+ 'Continuing to see if stack changes.')
228
+
229
+ range_valid = False
230
+ for _ in range(2):
231
+ logging.info('Testing against old_commit (%s)', commit_list[old_idx])
232
+ if not build_specified_commit.build_fuzzers_from_commit(
233
+ commit_list[old_idx],
234
+ bisect_repo_manager,
235
+ host_src_dir,
236
+ build_data,
237
+ base_builder_repo=base_builder_repo):
238
+ raise BisectError('Failed to build old_commit', repo_url)
239
+
240
+ if _check_for_crash(build_data.project_name, fuzz_target,
241
+ testcase_path) == expected_error:
242
+ logging.warning('old_commit %s had same result as new_commit %s',
243
+ old_commit, new_commit)
244
+ # Try again on an slightly older commit.
245
+ old_commit = bisect_repo_manager.get_parent(old_commit, 64)
246
+ if not old_commit:
247
+ break
248
+
249
+ commit_list = bisect_repo_manager.get_commit_list(
250
+ new_commit, old_commit)
251
+ old_idx = len(commit_list) - 1
252
+ continue
253
+
254
+ range_valid = True
255
+ break
256
+
257
+ if not range_valid:
258
+ raise BisectError('old_commit had same result as new_commit', repo_url)
259
+
260
+ while old_idx - new_idx > 1:
261
+ curr_idx = (old_idx + new_idx) // 2
262
+ logging.info('Testing against %s (idx=%d)', commit_list[curr_idx],
263
+ curr_idx)
264
+ if not build_specified_commit.build_fuzzers_from_commit(
265
+ commit_list[curr_idx],
266
+ bisect_repo_manager,
267
+ host_src_dir,
268
+ build_data,
269
+ base_builder_repo=base_builder_repo):
270
+ # Treat build failures as if we couldn't repo.
271
+ # TODO(ochang): retry nearby commits?
272
+ old_idx = curr_idx
273
+ continue
274
+
275
+ current_error = _check_for_crash(build_data.project_name, fuzz_target,
276
+ testcase_path)
277
+ logging.info('Current result = %s', current_error)
278
+ if expected_error == current_error:
279
+ new_idx = curr_idx
280
+ else:
281
+ old_idx = curr_idx
282
+ return Result(repo_url, commit_list[new_idx])
283
+
284
+
285
+ # pylint: disable=too-many-locals
286
+ # pylint: disable=too-many-arguments
287
+ def bisect(bisect_type, old_commit, new_commit, testcase_path, fuzz_target,
288
+ build_data):
289
+ """From a commit range, this function caluclates which introduced a
290
+ specific error from a fuzz testcase_path.
291
+
292
+ Args:
293
+ bisect_type: The type of the bisect ('regressed' or 'fixed').
294
+ old_commit: The oldest commit in the error regression range.
295
+ new_commit: The newest commit in the error regression range.
296
+ testcase_path: The file path of the test case that triggers the error
297
+ fuzz_target: The name of the fuzzer to be tested.
298
+ build_data: a class holding all of the input parameters for bisection.
299
+
300
+ Returns:
301
+ The commit SHA that introduced the error or None.
302
+
303
+ Raises:
304
+ ValueError: when a repo url can't be determine from the project.
305
+ """
306
+ try:
307
+ return _bisect(bisect_type, old_commit, new_commit, testcase_path,
308
+ fuzz_target, build_data)
309
+ finally:
310
+ # Clean up projects/ as _bisect may have modified it.
311
+ oss_fuzz_repo_manager = repo_manager.RepoManager(helper.OSS_FUZZ_DIR)
312
+ oss_fuzz_repo_manager.git(['reset', 'projects'])
313
+ oss_fuzz_repo_manager.git(['checkout', 'projects'])
314
+ oss_fuzz_repo_manager.git(['clean', '-fxd', 'projects'])
315
+
316
+
317
+ if __name__ == '__main__':
318
+ main()
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/build_specified_commit_test.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 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
+ """Test the functionality of the build image from commit module.
15
+ The will consist of the following functional tests:
16
+ 1. The inference of the main repo for a specific project.
17
+ 2. The building of a projects fuzzers from a specific commit.
18
+
19
+ """
20
+ import os
21
+ import tempfile
22
+ import unittest
23
+
24
+ import build_specified_commit
25
+ import helper
26
+ import repo_manager
27
+ import test_repos
28
+
29
+ # necessary because __file__ changes with os.chdir
30
+ TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__))
31
+
32
+
33
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
34
+ 'INTEGRATION_TESTS=1 not set')
35
+ class BuildImageIntegrationTest(unittest.TestCase):
36
+ """Tests if an image can be built from different states e.g. a commit."""
37
+
38
+ @unittest.skip('Test is failing (spuriously?).')
39
+ def test_build_fuzzers_from_commit(self):
40
+ """Tests if the fuzzers can build at a specified commit.
41
+
42
+ This is done by using a known regression range for a specific test case.
43
+ The old commit should show the error when its fuzzers run and the new one
44
+ should not.
45
+ """
46
+ with tempfile.TemporaryDirectory() as tmp_dir:
47
+ test_repo = test_repos.TEST_REPOS[1]
48
+ self.assertTrue(helper.build_image_impl(test_repo.project_name))
49
+ host_src_dir = build_specified_commit.copy_src_from_docker(
50
+ test_repo.project_name, tmp_dir)
51
+
52
+ test_repo_manager = repo_manager.clone_repo_and_get_manager(
53
+ test_repo.git_url, host_src_dir, test_repo.oss_repo_name)
54
+ build_data = build_specified_commit.BuildData(
55
+ sanitizer='address',
56
+ architecture='x86_64',
57
+ engine='libfuzzer',
58
+ project_name=test_repo.project_name)
59
+
60
+ build_specified_commit.build_fuzzers_from_commit(test_repo.old_commit,
61
+ test_repo_manager,
62
+ host_src_dir, build_data)
63
+ project = helper.Project(test_repo.project_name)
64
+ old_result = helper.reproduce_impl(project=project,
65
+ fuzzer_name=test_repo.fuzz_target,
66
+ valgrind=False,
67
+ env_to_add=[],
68
+ fuzzer_args=[],
69
+ testcase_path=test_repo.testcase_path)
70
+ build_specified_commit.build_fuzzers_from_commit(test_repo.project_name,
71
+ test_repo_manager,
72
+ host_src_dir, build_data)
73
+ new_result = helper.reproduce_impl(project=project,
74
+ fuzzer_name=test_repo.fuzz_target,
75
+ valgrind=False,
76
+ env_to_add=[],
77
+ fuzzer_args=[],
78
+ testcase_path=test_repo.testcase_path)
79
+ self.assertNotEqual(new_result, old_result)
80
+
81
+ def test_detect_main_repo_from_commit(self):
82
+ """Test the detect main repo function from build specific commit module."""
83
+ # TODO(metzman): Fix these tests so they don't randomly break because of
84
+ # changes in the outside world.
85
+ for example_repo in test_repos.TEST_REPOS:
86
+ if example_repo.new_commit:
87
+ # TODO(metzman): This function calls _build_image_with_retries which
88
+ # has a long delay (30 seconds). Figure out how to make this quicker.
89
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
90
+ example_repo.project_name, commit=example_repo.new_commit)
91
+ self.assertEqual(repo_origin, example_repo.git_url)
92
+ self.assertEqual(repo_name,
93
+ os.path.join('/src', example_repo.oss_repo_name))
94
+
95
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
96
+ test_repos.INVALID_REPO.project_name,
97
+ test_repos.INVALID_REPO.new_commit)
98
+ self.assertIsNone(repo_origin)
99
+ self.assertIsNone(repo_name)
100
+
101
+ def test_detect_main_repo_from_name(self):
102
+ """Test the detect main repo function from build specific commit module."""
103
+ for example_repo in test_repos.TEST_REPOS:
104
+ if example_repo.project_name == 'gonids':
105
+ # It's unclear how this test ever passed, but we can't infer the repo
106
+ # because gonids doesn't really check it out, it uses "go get".
107
+ continue
108
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
109
+ example_repo.project_name, repo_name=example_repo.git_repo_name)
110
+ self.assertEqual(repo_origin, example_repo.git_url)
111
+ self.assertEqual(
112
+ repo_name,
113
+ os.path.join(example_repo.image_location, example_repo.oss_repo_name))
114
+
115
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
116
+ test_repos.INVALID_REPO.project_name,
117
+ test_repos.INVALID_REPO.oss_repo_name)
118
+ self.assertIsNone(repo_origin)
119
+ self.assertIsNone(repo_name)
120
+
121
+
122
+ if __name__ == '__main__':
123
+ # Change to oss-fuzz main directory so helper.py runs correctly.
124
+ if os.getcwd() != os.path.dirname(TEST_DIR_PATH):
125
+ os.chdir(os.path.dirname(TEST_DIR_PATH))
126
+ unittest.main()
local-test-commons-compress-full-01-vuln_5/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-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tests the functionality of the cifuzz module."""
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ import unittest
20
+ from unittest import mock
21
+
22
+ import parameterized
23
+
24
+ # pylint: disable=wrong-import-position
25
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.append(INFRA_DIR)
27
+
28
+ OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR)
29
+
30
+ import build_fuzzers
31
+ import continuous_integration
32
+ import repo_manager
33
+ import test_helpers
34
+
35
+ # NOTE: This integration test relies on
36
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
37
+ EXAMPLE_PROJECT = 'example'
38
+
39
+ # Location of data used for testing.
40
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
41
+ 'test_data')
42
+
43
+ # An example fuzzer that triggers an crash.
44
+ # Binary is a copy of the example project's do_stuff_fuzzer and can be
45
+ # generated by running "python3 infra/helper.py build_fuzzers example".
46
+ EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer'
47
+
48
+ # An example fuzzer that does not trigger a crash.
49
+ # Binary is a modified version of example project's do_stuff_fuzzer. It is
50
+ # created by removing the bug in my_api.cpp.
51
+ EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer'
52
+
53
+ # A fuzzer to be built in build_fuzzers integration tests.
54
+ EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer'
55
+
56
+ # pylint: disable=no-self-use,protected-access,too-few-public-methods,unused-argument
57
+
58
+
59
+ def docker_command_has_env_var_arg(command, env_var_arg):
60
+ """Returns True if a docker command has a specific env var argument."""
61
+ for idx, element in enumerate(command):
62
+ if idx == 0:
63
+ # We're looking for the variable which can't be the first argument.
64
+ continue
65
+
66
+ if element == env_var_arg and command[idx - 1] == '-e':
67
+ return True
68
+ return False
69
+
70
+
71
+ class BuildFuzzersTest(unittest.TestCase):
72
+ """Unit tests for build_fuzzers."""
73
+
74
+ @mock.patch('build_specified_commit.detect_main_repo',
75
+ return_value=('example.com', '/path'))
76
+ @mock.patch('repo_manager._clone', return_value=None)
77
+ @mock.patch('continuous_integration.checkout_specified_commit')
78
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
79
+ def test_cifuzz_env_var(self, mock_docker_run, _, __, ___):
80
+ """Tests that the CIFUZZ env var is set."""
81
+
82
+ with tempfile.TemporaryDirectory() as tmp_dir:
83
+ build_fuzzers.build_fuzzers(
84
+ test_helpers.create_build_config(
85
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
86
+ project_repo_name=EXAMPLE_PROJECT,
87
+ workspace=tmp_dir,
88
+ pr_ref='refs/pull/1757/merge'))
89
+
90
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
91
+
92
+ self.assertTrue(
93
+ docker_command_has_env_var_arg(docker_run_command, 'CIFUZZ=True'))
94
+
95
+ @mock.patch('build_specified_commit.detect_main_repo',
96
+ return_value=('example.com', '/path'))
97
+ @mock.patch('repo_manager._clone', return_value=None)
98
+ @mock.patch('continuous_integration.checkout_specified_commit')
99
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
100
+ def test_extra_env_var(self, mock_docker_run, _, __, ___):
101
+ """Tests that the CIFUZZ env var is set."""
102
+
103
+ extra_env_var = 'CFL_EXTRA_TOKEN'
104
+ with tempfile.TemporaryDirectory() as tmp_dir:
105
+ with mock.patch.dict(os.environ, {extra_env_var: 'BLAH'}):
106
+ build_fuzzers.build_fuzzers(
107
+ test_helpers.create_build_config(
108
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
109
+ project_repo_name=EXAMPLE_PROJECT,
110
+ workspace=tmp_dir,
111
+ pr_ref='refs/pull/1757/merge'))
112
+
113
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
114
+ self.assertTrue(
115
+ docker_command_has_env_var_arg(docker_run_command, extra_env_var))
116
+
117
+
118
+ class InternalGithubBuildTest(unittest.TestCase):
119
+ """Tests for building OSS-Fuzz projects on GitHub actions."""
120
+ PROJECT_REPO_NAME = 'myproject'
121
+ SANITIZER = 'address'
122
+ GIT_SHA = 'fake'
123
+ PR_REF = 'fake'
124
+
125
+ def _create_builder(self, tmp_dir, oss_fuzz_project_name='myproject'):
126
+ """Creates an InternalGithubBuilder and returns it."""
127
+ config = test_helpers.create_build_config(
128
+ oss_fuzz_project_name=oss_fuzz_project_name,
129
+ project_repo_name=self.PROJECT_REPO_NAME,
130
+ workspace=tmp_dir,
131
+ sanitizer=self.SANITIZER,
132
+ git_sha=self.GIT_SHA,
133
+ pr_ref=self.PR_REF,
134
+ cfl_platform='github')
135
+ cfl_platform = continuous_integration.get_ci(config)
136
+ builder = build_fuzzers.Builder(config, cfl_platform)
137
+ builder.repo_manager = repo_manager.RepoManager('/fake')
138
+ return builder
139
+
140
+ @mock.patch('helper.docker_run', return_value=True)
141
+ @mock.patch('continuous_integration.checkout_specified_commit',
142
+ side_effect=None)
143
+ def test_correct_host_repo_path(self, _, __):
144
+ """Tests that the correct self.host_repo_path is set by
145
+ build_image_and_checkout_src. Specifically, we want the name of the
146
+ directory the repo is in to match the name used in the docker
147
+ image/container, so that it will replace the host's copy properly."""
148
+ image_repo_path = '/src/repo_dir'
149
+ with tempfile.TemporaryDirectory() as tmp_dir, mock.patch(
150
+ 'build_specified_commit.detect_main_repo',
151
+ return_value=('inferred_url', image_repo_path)):
152
+ builder = self._create_builder(tmp_dir)
153
+ builder.build_image_and_checkout_src()
154
+
155
+ self.assertEqual(os.path.basename(builder.host_repo_path),
156
+ os.path.basename(image_repo_path))
157
+
158
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
159
+ return_value=True)
160
+ def test_upload_build_disabled(self, mock_upload_build):
161
+ """Test upload build (disabled)."""
162
+ with tempfile.TemporaryDirectory() as tmp_dir:
163
+ builder = self._create_builder(tmp_dir)
164
+ builder.upload_build()
165
+
166
+ mock_upload_build.assert_not_called()
167
+
168
+ @mock.patch('repo_manager.RepoManager.get_current_commit',
169
+ return_value='commit')
170
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
171
+ return_value=True)
172
+ def test_upload_build(self, mock_upload_build, mock_get_current_commit):
173
+ """Test upload build."""
174
+ with tempfile.TemporaryDirectory() as tmp_dir:
175
+ builder = self._create_builder(tmp_dir, oss_fuzz_project_name='')
176
+ builder.config.upload_build = True
177
+ builder.upload_build()
178
+
179
+ mock_upload_build.assert_called_with('commit')
180
+
181
+
182
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
183
+ 'INTEGRATION_TESTS=1 not set')
184
+ class BuildFuzzersIntegrationTest(unittest.TestCase):
185
+ """Integration tests for build_fuzzers."""
186
+
187
+ def setUp(self):
188
+ self.temp_dir_ctx_manager = test_helpers.docker_temp_dir()
189
+ self.workspace = self.temp_dir_ctx_manager.__enter__()
190
+ self.out_dir = os.path.join(self.workspace, 'build-out')
191
+ test_helpers.patch_environ(self)
192
+
193
+ base_runner_path = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
194
+ os.environ['PATH'] = os.environ['PATH'] + os.pathsep + base_runner_path
195
+
196
+ def tearDown(self):
197
+ self.temp_dir_ctx_manager.__exit__(None, None, None)
198
+
199
+ def test_external_github_project(self):
200
+ """Tests building fuzzers from an external project on Github."""
201
+ project_repo_name = 'external-project'
202
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
203
+ # This test is dependant on the state of
204
+ # github.com/jonathanmetzman/cifuzz-external-example.
205
+ config = test_helpers.create_build_config(
206
+ project_repo_name=project_repo_name,
207
+ workspace=self.workspace,
208
+ git_url=git_url,
209
+ git_sha='HEAD',
210
+ cfl_platform='github',
211
+ base_commit='HEAD^1')
212
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
213
+ self.assertTrue(
214
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
215
+
216
+ def test_external_generic_project(self):
217
+ """Tests building fuzzers from an external project not on Github."""
218
+ project_repo_name = 'cifuzz-external-example'
219
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
220
+ # This test is dependant on the state of
221
+ # github.com/jonathanmetzman/cifuzz-external-example.
222
+ manager = repo_manager.clone_repo_and_get_manager(
223
+ 'https://github.com/jonathanmetzman/cifuzz-external-example',
224
+ self.workspace)
225
+ project_src_path = manager.repo_dir
226
+ config = test_helpers.create_build_config(
227
+ project_repo_name=project_repo_name,
228
+ workspace=self.workspace,
229
+ git_url=git_url,
230
+ filestore='no_filestore',
231
+ git_sha='HEAD',
232
+ project_src_path=project_src_path,
233
+ base_commit='HEAD^1')
234
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
235
+ self.assertTrue(
236
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
237
+
238
+ def test_valid_commit(self):
239
+ """Tests building fuzzers with valid inputs."""
240
+ config = test_helpers.create_build_config(
241
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
242
+ project_repo_name='oss-fuzz',
243
+ workspace=self.workspace,
244
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
245
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
246
+ cfl_platform='github')
247
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
248
+ self.assertTrue(
249
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
250
+
251
+ def test_valid_pull_request(self):
252
+ """Tests building fuzzers with valid pull request."""
253
+ config = test_helpers.create_build_config(
254
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
255
+ project_repo_name='oss-fuzz',
256
+ workspace=self.workspace,
257
+ pr_ref='refs/pull/1757/merge',
258
+ base_ref='master',
259
+ cfl_platform='github')
260
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
261
+ self.assertTrue(
262
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
263
+
264
+ def test_invalid_pull_request(self):
265
+ """Tests building fuzzers with invalid pull request."""
266
+ config = test_helpers.create_build_config(
267
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
268
+ project_repo_name='oss-fuzz',
269
+ workspace=self.workspace,
270
+ pr_ref='ref-1/merge',
271
+ base_ref='master',
272
+ cfl_platform='github')
273
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
274
+
275
+ def test_invalid_oss_fuzz_project_name(self):
276
+ """Tests building fuzzers with invalid project name."""
277
+ config = test_helpers.create_build_config(
278
+ oss_fuzz_project_name='not_a_valid_project',
279
+ project_repo_name='oss-fuzz',
280
+ workspace=self.workspace,
281
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
282
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
283
+
284
+ def test_invalid_repo_name(self):
285
+ """Tests building fuzzers with invalid repo name."""
286
+ config = test_helpers.create_build_config(
287
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
288
+ project_repo_name='not-real-repo',
289
+ workspace=self.workspace,
290
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
291
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
292
+
293
+ def test_invalid_git_sha(self):
294
+ """Tests building fuzzers with invalid commit SHA."""
295
+ config = test_helpers.create_build_config(
296
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
297
+ project_repo_name='oss-fuzz',
298
+ workspace=self.workspace,
299
+ git_sha='',
300
+ cfl_platform='github')
301
+ with self.assertRaises(AssertionError):
302
+ build_fuzzers.build_fuzzers(config)
303
+
304
+ def test_invalid_workspace(self):
305
+ """Tests building fuzzers with invalid workspace."""
306
+ config = test_helpers.create_build_config(
307
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
308
+ project_repo_name='oss-fuzz',
309
+ workspace=os.path.join(self.workspace, 'not', 'a', 'dir'),
310
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
311
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
312
+
313
+
314
+ class CheckFuzzerBuildTest(unittest.TestCase):
315
+ """Tests the check_fuzzer_build function in the cifuzz module."""
316
+
317
+ SANITIZER = 'address'
318
+ LANGUAGE = 'c++'
319
+
320
+ def setUp(self):
321
+ self.temp_dir_obj = tempfile.TemporaryDirectory()
322
+ workspace_path = os.path.join(self.temp_dir_obj.name, 'workspace')
323
+ self.config = test_helpers.create_build_config(
324
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
325
+ sanitizer=self.SANITIZER,
326
+ language=self.LANGUAGE,
327
+ workspace=workspace_path,
328
+ pr_ref='refs/pull/1757/merge')
329
+ self.workspace = test_helpers.create_workspace(workspace_path)
330
+ shutil.copytree(TEST_DATA_PATH, workspace_path)
331
+ test_helpers.patch_environ(self, runner=True)
332
+
333
+ def tearDown(self):
334
+ self.temp_dir_obj.cleanup()
335
+
336
+ def test_correct_fuzzer_build(self):
337
+ """Checks check_fuzzer_build function returns True for valid fuzzers."""
338
+ self.assertTrue(build_fuzzers.check_fuzzer_build(self.config))
339
+
340
+ def test_not_a_valid_path(self):
341
+ """Tests that False is returned when a nonexistent path is given."""
342
+ self.config.workspace = 'not/a/valid/path'
343
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
344
+
345
+ def test_no_valid_fuzzers(self):
346
+ """Tests that False is returned when an empty directory is given."""
347
+ with tempfile.TemporaryDirectory() as tmp_dir:
348
+ self.config.workspace = tmp_dir
349
+ os.mkdir(os.path.join(self.config.workspace, 'build-out'))
350
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
351
+
352
+ @mock.patch('utils.execute', return_value=(None, None, 0))
353
+ def test_allow_broken_fuzz_targets_percentage(self, mock_execute):
354
+ """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running
355
+ docker if passed to check_fuzzer_build."""
356
+ percentage = '0'
357
+ self.config.allowed_broken_targets_percentage = percentage
358
+ build_fuzzers.check_fuzzer_build(self.config)
359
+ self.assertEqual(
360
+ mock_execute.call_args[1]['env']['ALLOWED_BROKEN_TARGETS_PERCENTAGE'],
361
+ percentage)
362
+
363
+
364
+ @unittest.skip('Test is too long to be run with presubmit.')
365
+ class BuildSantizerIntegrationTest(unittest.TestCase):
366
+ """Integration tests for the build_fuzzers.
367
+ Note: This test relies on "curl" being an OSS-Fuzz project."""
368
+ PROJECT_NAME = 'curl'
369
+ PR_REF = 'fake_pr'
370
+
371
+ @classmethod
372
+ def _create_config(cls, tmp_dir, sanitizer):
373
+ return test_helpers.create_build_config(
374
+ oss_fuzz_project_name=cls.PROJECT_NAME,
375
+ project_repo_name=cls.PROJECT_NAME,
376
+ workspace=tmp_dir,
377
+ pr_ref=cls.PR_REF,
378
+ sanitizer=sanitizer)
379
+
380
+ @parameterized.parameterized.expand([('memory',), ('undefined',)])
381
+ def test_valid_project_curl(self, sanitizer):
382
+ """Tests that MSAN can be detected from project.yaml"""
383
+ with tempfile.TemporaryDirectory() as tmp_dir:
384
+ self.assertTrue(
385
+ build_fuzzers.build_fuzzers(self._create_config(tmp_dir, sanitizer)))
386
+
387
+
388
+ class GetDockerBuildFuzzersArgsNotContainerTest(unittest.TestCase):
389
+ """Tests that _get_docker_build_fuzzers_args_not_container works as
390
+ intended."""
391
+
392
+ def test_get_docker_build_fuzzers_args_no_container(self):
393
+ """Tests that _get_docker_build_fuzzers_args_not_container works
394
+ as intended."""
395
+ host_repo_path = '/host/repo'
396
+ result = build_fuzzers._get_docker_build_fuzzers_args_not_container(
397
+ host_repo_path)
398
+ expected_result = ['-v', '/host/repo:/host/repo']
399
+ self.assertEqual(result, expected_result)
400
+
401
+
402
+ if __name__ == '__main__':
403
+ unittest.main()
local-test-commons-compress-full-01-vuln_5/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-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/cloudbuild.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO(metzman): Get rid of cifuzz-build-fuzzers and cifuzz-run-fuzzers.
2
+ steps:
3
+ - name: 'gcr.io/cloud-builders/docker'
4
+ args:
5
+ - build
6
+ - '-t'
7
+ - ghcr.io/aixcc-finals/cifuzz-base
8
+ - '-t'
9
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
10
+ - '-f'
11
+ - infra/cifuzz/cifuzz-base/Dockerfile
12
+ - .
13
+ - name: 'gcr.io/cloud-builders/docker'
14
+ args:
15
+ - build
16
+ - '-t'
17
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
18
+ - '-t'
19
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
20
+ - '-t'
21
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
22
+ - '-t'
23
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
24
+ - '-f'
25
+ - infra/build_fuzzers.Dockerfile
26
+ - infra
27
+ - name: 'gcr.io/cloud-builders/docker'
28
+ args:
29
+ - build
30
+ - '-t'
31
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
32
+ - '-t'
33
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
34
+ - '-t'
35
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
36
+ - '-t'
37
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
38
+ - '-f'
39
+ - infra/run_fuzzers.Dockerfile
40
+ - infra
41
+ images:
42
+ - ghcr.io/aixcc-finals/cifuzz-base
43
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
44
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
45
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
46
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
47
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
48
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
49
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
50
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
51
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
52
+ timeout: 1800s
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/config_utils_test.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 config_utils."""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import config_utils
20
+ import constants
21
+ import test_helpers
22
+
23
+ # pylint: disable=no-self-use,protected-access
24
+
25
+
26
+ class BaseConfigTest(unittest.TestCase):
27
+ """Tests for BaseConfig."""
28
+
29
+ def setUp(self):
30
+ test_helpers.patch_environ(self)
31
+
32
+ def _create_config(self):
33
+ return config_utils.BuildFuzzersConfig()
34
+
35
+ def test_language_default(self):
36
+ """Tests that the correct default language is set."""
37
+ config = self._create_config()
38
+ self.assertEqual(config.language, 'c++')
39
+
40
+ def test_language(self):
41
+ """Tests that the correct language is set."""
42
+ language = 'python'
43
+ os.environ['LANGUAGE'] = language
44
+ config = self._create_config()
45
+ self.assertEqual(config.language, language)
46
+
47
+ def test_is_coverage(self):
48
+ """Tests that is_coverage is set correctly."""
49
+ # Test it is set when it is supposed to be.
50
+ os.environ['SANITIZER'] = 'coverage'
51
+ config = self._create_config()
52
+ self.assertTrue(config.is_coverage)
53
+
54
+ # Test it is not set when it is not supposed to be.
55
+ os.environ['SANITIZER'] = 'address'
56
+ config = self._create_config()
57
+ self.assertFalse(config.is_coverage)
58
+
59
+ @mock.patch('logging.error')
60
+ def test_validate_no_workspace(self, mock_error):
61
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
62
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
63
+ config = self._create_config()
64
+ self.assertFalse(config.validate())
65
+ mock_error.assert_called_with('Must set WORKSPACE.')
66
+
67
+ @mock.patch('logging.error')
68
+ def test_validate_invalid_language(self, mock_error):
69
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
70
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
71
+ os.environ['WORKSPACE'] = '/workspace'
72
+ os.environ['LANGUAGE'] = 'invalid-language'
73
+ config = self._create_config()
74
+ self.assertFalse(config.validate())
75
+ mock_error.assert_called_with('Invalid LANGUAGE: %s. Must be one of: %s.',
76
+ os.environ['LANGUAGE'], constants.LANGUAGES)
77
+
78
+ @mock.patch('logging.error')
79
+ def test_validate_invalid_sanitizer(self, mock_error):
80
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
81
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
82
+ os.environ['WORKSPACE'] = '/workspace'
83
+ os.environ['SANITIZER'] = 'invalid-sanitizer'
84
+ config = self._create_config()
85
+ self.assertFalse(config.validate())
86
+ mock_error.assert_called_with('Invalid SANITIZER: %s. Must be one of: %s.',
87
+ os.environ['SANITIZER'],
88
+ config_utils.SANITIZERS)
89
+
90
+ def test_validate(self):
91
+ """Tests that validate returns True if config is valid."""
92
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
93
+ os.environ['WORKSPACE'] = '/workspace'
94
+ os.environ['REPOSITORY'] = 'repo'
95
+ config = self._create_config()
96
+ self.assertTrue(config.validate())
97
+
98
+
99
+ class BuildFuzzersConfigTest(unittest.TestCase):
100
+ """Tests for BuildFuzzersConfig."""
101
+
102
+ def setUp(self):
103
+ test_helpers.patch_environ(self)
104
+
105
+ def _create_config(self):
106
+ return config_utils.BuildFuzzersConfig()
107
+
108
+ @mock.patch('platform_config.github._get_event_data', return_value={})
109
+ def test_github_base_ref(self, _):
110
+ """Tests that base_ref is set properly."""
111
+ expected_base_ref = 'expected_base_ref'
112
+ os.environ['GITHUB_BASE_REF'] = expected_base_ref
113
+ os.environ['CFL_PLATFORM'] = 'github'
114
+ os.environ['GITHUB_REPOSITORY'] = 'owner/repo'
115
+ config = self._create_config()
116
+ self.assertEqual(config.base_ref, expected_base_ref)
117
+
118
+ def test_base_ref(self):
119
+ """Tests that base_ref is set properly."""
120
+ expected_base_ref = 'expected_base_ref'
121
+ os.environ['GIT_BASE_REF'] = expected_base_ref
122
+ config = self._create_config()
123
+ self.assertEqual(config.base_ref, expected_base_ref)
124
+
125
+ def test_keep_unaffected_defaults_to_true(self):
126
+ """Tests that keep_unaffected_fuzz_targets defaults to true."""
127
+ config = self._create_config()
128
+ self.assertTrue(config.keep_unaffected_fuzz_targets)
129
+
130
+ def test_keep_unaffected_defaults_to_false_when_pr(self):
131
+ """Tests that keep_unaffected_fuzz_targets defaults to false when from a
132
+ pr."""
133
+ os.environ['GIT_BASE_REF'] = 'base-ref'
134
+ config = self._create_config()
135
+ self.assertFalse(config.keep_unaffected_fuzz_targets)
136
+
137
+
138
+ class RunFuzzersConfigTest(unittest.TestCase):
139
+ """Tests for RunFuzzersConfig."""
140
+
141
+ def setUp(self):
142
+ test_helpers.patch_environ(self)
143
+
144
+ def _create_config(self):
145
+ return config_utils.RunFuzzersConfig()
146
+
147
+ def test_coverage(self):
148
+ """Tests that mode is overriden properly based on is_coverage."""
149
+ # Test that it is overriden when it is supposed to be.
150
+ os.environ['SANITIZER'] = 'coverage'
151
+ os.environ['MODE'] = 'code-change'
152
+ config = self._create_config()
153
+ self.assertEqual(config.mode, 'coverage')
154
+
155
+ # Test that it isn't overriden when it isn't supposed to be.
156
+ os.environ['SANITIZER'] = 'address'
157
+ mode = 'code-change'
158
+ os.environ['MODE'] = mode
159
+ config = self._create_config()
160
+ self.assertEqual(config.mode, mode)
161
+
162
+ def test_run_config_validate(self):
163
+ """Tests that _run_config_validate returns True when the config is valid."""
164
+ self.assertTrue(self._create_config()._run_config_validate())
165
+
166
+ @mock.patch('logging.error')
167
+ def test_run_config_invalid_mode(self, mock_error):
168
+ """Tests that _run_config_validate returns False when mode is invalid."""
169
+ fake_mode = 'fake-mode'
170
+ os.environ['MODE'] = fake_mode
171
+ self.assertFalse(self._create_config()._run_config_validate())
172
+ mock_error.assert_called_with('Invalid MODE: %s. Must be one of %s.',
173
+ fake_mode,
174
+ config_utils.RunFuzzersConfig.MODES)
175
+
176
+
177
+ class GetSanitizerTest(unittest.TestCase):
178
+ """Tests for _get_sanitizer."""
179
+
180
+ def setUp(self):
181
+ test_helpers.patch_environ(self)
182
+ self.sanitizer = 'memory'
183
+
184
+ def test_default_value(self):
185
+ """Tests that the default value returned by _get_sanitizer is correct."""
186
+ self.assertEqual(config_utils._get_sanitizer(), 'address')
187
+
188
+ def test_normal_case(self):
189
+ """Tests that _get_sanitizer returns the correct value in normal cases."""
190
+ os.environ['SANITIZER'] = self.sanitizer
191
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
192
+
193
+ def test_capitalization(self):
194
+ """Tests that that _get_sanitizer handles capitalization properly."""
195
+ os.environ['SANITIZER'] = self.sanitizer.upper()
196
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
197
+
198
+
199
+ if __name__ == '__main__':
200
+ unittest.main()
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/environment.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dealing with env vars."""
15
+
16
+ import ast
17
+ import os
18
+
19
+
20
+ def _eval_value(value_string):
21
+ """Returns evaluated value."""
22
+ try:
23
+ return ast.literal_eval(value_string)
24
+ except: # pylint: disable=bare-except
25
+ # String fallback.
26
+ return value_string
27
+
28
+
29
+ def get(env_var, default_value=None):
30
+ """Returns an environment variable value."""
31
+ value_string = os.getenv(env_var)
32
+ if value_string is None:
33
+ return default_value
34
+
35
+ return _eval_value(value_string)
36
+
37
+
38
+ def get_bool(env_var, default_value=None):
39
+ """Returns a boolean environment variable value. This is needed because a lot
40
+ of CIFuzz users specified 'false' for dry-run. So we need to special case
41
+ this."""
42
+ value = get(env_var, default_value)
43
+ if not isinstance(value, str):
44
+ return bool(value)
45
+
46
+ lower_value = value.lower()
47
+ allowed_values = {'true', 'false'}
48
+ if lower_value not in allowed_values:
49
+ raise Exception(f'Bool env var {env_var} value {value} is invalid. '
50
+ f'Must be one of {allowed_values}.')
51
+ return lower_value == 'true'
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/sarif_utils_test.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tests for sarif_utils.py"""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import sarif_utils
20
+
21
+ CRASH_INFO_FILELINE = 403
22
+
23
+ TEST_DATA = os.path.join(os.path.dirname(__file__), 'test_data')
24
+
25
+
26
+ class GetSarifDataTest(unittest.TestCase):
27
+ """Tests for get_sarif_data."""
28
+
29
+ def setUp(self):
30
+ self.maxDiff = None # pylint: disable=invalid-name
31
+
32
+ def test_get_sarif_data_none(self):
33
+ """Tests get_sarif_data when there was no crash."""
34
+ self.assertEqual(sarif_utils.get_sarif_data(None, '/root/target'),
35
+ sarif_utils.SARIF_DATA)
36
+
37
+ def test_ordinary_case(self):
38
+ stacktrace_filename = os.path.join(TEST_DATA,
39
+ 'sarif_utils_systemd_stack.txt')
40
+ with open(stacktrace_filename, 'r') as fp:
41
+ stacktrace = fp.read()
42
+ expected_result = {
43
+ 'level': 'error',
44
+ 'message': {
45
+ 'text': 'Heap-buffer-overflow\nREAD 4'
46
+ },
47
+ 'locations': [{
48
+ 'physicalLocation': {
49
+ 'artifactLocation': {
50
+ 'uri': 'src/core/fuzz-unit-file.c',
51
+ 'index': 0
52
+ },
53
+ 'region': {
54
+ 'startLine': 30,
55
+ # We don't have this granualarity fuzzing.
56
+ 'startColumn': 1,
57
+ }
58
+ }
59
+ }],
60
+ 'ruleId': 'heap-buffer-overflow',
61
+ 'ruleIndex': 2
62
+ }
63
+ actual_result = sarif_utils.get_sarif_data(
64
+ stacktrace, '/root/target')['runs'][0]['results'][0]
65
+ self.assertEqual(actual_result, expected_result)
66
+
67
+ def test_llvmfuzzertestoneinput_case(self):
68
+ stacktrace_filename = os.path.join(TEST_DATA,
69
+ 'sarif_utils_only_llvmfuzzer_stack.txt')
70
+ with open(stacktrace_filename, 'r') as fp:
71
+ stacktrace = fp.read()
72
+ actual_result = sarif_utils.get_sarif_data(
73
+ stacktrace, '/root/target')['runs'][0]['results']
74
+ self.assertEqual(actual_result, [])
75
+
76
+ def test_msan(self):
77
+ """Tests that MSAN stacktraces don't exception."""
78
+ stacktrace_filename = os.path.join(TEST_DATA, 'sarif_utils_msan_stack.txt')
79
+ with open(stacktrace_filename, 'r') as fp:
80
+ stacktrace = fp.read()
81
+
82
+ actual_result = sarif_utils.get_sarif_data(stacktrace, '/root/target')
83
+
84
+
85
+ class RedactSrcPathTest(unittest.TestCase):
86
+ """Tests for redact_src_path."""
87
+
88
+ def test_redact_src_path(self):
89
+ """Tests redact_src_path."""
90
+ path = '/src/src-repo/subdir/file'
91
+ self.assertEqual(sarif_utils.redact_src_path(path), 'subdir/file')
92
+
93
+
94
+ def _get_mock_crash_info():
95
+ """Returns a mock crash_info to be used in tests."""
96
+ stack_frame = mock.MagicMock()
97
+ stack_frame.filename = '/src/repo-dir/sub/vuln.cc'
98
+ stack_frame.function_name = 'vuln_func'
99
+ stack_frame.fileline = CRASH_INFO_FILELINE
100
+ crash1_frames = [stack_frame, stack_frame]
101
+ frames = [crash1_frames]
102
+ crash_info = mock.MagicMock()
103
+ crash_info.frames = frames
104
+ crash_info.crash_state = 'vuln_func\nvuln_func0\nvuln_func1'
105
+ return crash_info
106
+
107
+
108
+ class GetErrorSourceInfoTest(unittest.TestCase):
109
+ """Tests for get_error_source_info."""
110
+
111
+ def test_redact_src_path(self):
112
+ """Tests that get_error_source_info finds the right source info."""
113
+ crash_info = _get_mock_crash_info()
114
+ source_info = sarif_utils.get_error_source_info(crash_info)
115
+ expected_source_info = ('sub/vuln.cc', CRASH_INFO_FILELINE)
116
+ self.assertEqual(source_info, expected_source_info)
117
+
118
+
119
+ class GetRuleIndexTest(unittest.TestCase):
120
+ """Tests for get_rule_index."""
121
+ CRASH_INFO_CRASH_TYPE = 'Heap-use-after-free READ 8'
122
+
123
+ def test_get_rule_index(self):
124
+ """Tests that get_rule_index finds the right rule index."""
125
+ index = sarif_utils.get_rule_index(self.CRASH_INFO_CRASH_TYPE)
126
+ self.assertEqual(sarif_utils.SARIF_RULES[index]['id'],
127
+ 'heap-use-after-free')
128
+ self.assertEqual(sarif_utils.get_rule_index('no-crashes'), 0)
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/test_helpers.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Contains convenient helpers for writing tests."""
15
+
16
+ import contextlib
17
+ import os
18
+ import sys
19
+ import shutil
20
+ import tempfile
21
+ from unittest import mock
22
+
23
+ import config_utils
24
+ import docker
25
+ import workspace_utils
26
+
27
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(INFRA_DIR)
30
+
31
+ import helper
32
+
33
+
34
+ # TODO(metzman): Get rid of these decorators.
35
+ @mock.patch('config_utils._is_dry_run', return_value=True)
36
+ @mock.patch('platform_config.BasePlatformConfig.project_src_path',
37
+ return_value=None)
38
+ @mock.patch('os.path.basename', return_value=None)
39
+ def _create_config(config_cls, _, __, ___, **kwargs):
40
+ """Creates a config object from |config_cls| and then sets every attribute
41
+ that is a key in |kwargs| to the corresponding value. Asserts that each key in
42
+ |kwargs| is an attribute of config."""
43
+ with mock.patch('config_utils.BaseConfig.validate', return_value=True):
44
+ config = config_cls()
45
+ for key, value in kwargs.items():
46
+ assert hasattr(config, key), 'Config doesn\'t have attribute: ' + key
47
+ setattr(config, key, value)
48
+
49
+ return config
50
+
51
+
52
+ def create_build_config(**kwargs):
53
+ """Wrapper around _create_config for build configs."""
54
+ return _create_config(config_utils.BuildFuzzersConfig, **kwargs)
55
+
56
+
57
+ def create_run_config(**kwargs):
58
+ """Wrapper around _create_config for run configs."""
59
+ return _create_config(config_utils.RunFuzzersConfig, **kwargs)
60
+
61
+
62
+ def create_workspace(workspace_path='/workspace'):
63
+ """Returns a workspace located at |workspace_path| ('/workspace' by
64
+ default)."""
65
+ config = create_run_config(workspace=workspace_path)
66
+ return workspace_utils.Workspace(config)
67
+
68
+
69
+ def patch_environ(testcase_obj, env=None, empty=False, runner=False):
70
+ """Patch environment. |testcase_obj| is the unittest.TestCase that contains
71
+ tests. |env|, if specified, is a dictionary of environment variables to start
72
+ from. If |empty| is True then the new patched environment will be empty. If
73
+ |runner| is True then the necessary environment variables will be set to run
74
+ the scripts from base-runner."""
75
+ if env is None:
76
+ env = {}
77
+
78
+ patcher = mock.patch.dict(os.environ, env)
79
+ testcase_obj.addCleanup(patcher.stop)
80
+ patcher.start()
81
+ if empty:
82
+ for key in os.environ.copy():
83
+ del os.environ[key]
84
+
85
+ if runner:
86
+ # Add the scripts for base-runner to the path since the wont be in
87
+ # /usr/local/bin on host machines during testing.
88
+ base_runner_dir = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
89
+ os.environ['PATH'] = (os.environ.get('PATH', '') + os.pathsep +
90
+ base_runner_dir)
91
+ if 'GOPATH' not in os.environ:
92
+ # A GOPATH must be set or else the coverage script fails, even for getting
93
+ # the coverage of non-Go programs.
94
+ os.environ['GOPATH'] = '/root/go'
95
+
96
+
97
+ @contextlib.contextmanager
98
+ def temp_dir_copy(directory):
99
+ """Context manager that yields a temporary copy of |directory|."""
100
+ with tempfile.TemporaryDirectory() as temp_dir:
101
+ temp_copy_path = os.path.join(temp_dir, os.path.basename(directory))
102
+ shutil.copytree(directory, temp_copy_path)
103
+ yield temp_copy_path
104
+
105
+
106
+ @contextlib.contextmanager
107
+ def docker_temp_dir():
108
+ """Returns a temporary a directory that is useful for use with docker. On
109
+ cleanup this contextmanager uses docker to delete the directory's contents so
110
+ that if anything is owned by root it can be deleted (which
111
+ tempfile.TemporaryDirectory() cannot do) by non-root users."""
112
+ with tempfile.TemporaryDirectory() as temp_dir:
113
+ yield temp_dir
114
+ helper.docker_run([
115
+ '-v', f'{temp_dir}:/temp_dir', '-t', docker.BASE_BUILDER_TAG,
116
+ '/bin/bash', '-c', 'rm -rf /temp_dir/*'
117
+ ])
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/cifuzz/workspace_utils.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 representing the workspace directory which CIFuzz uses."""
15
+
16
+ import os
17
+ import shutil
18
+
19
+
20
+ class Workspace:
21
+ """Class representing the workspace directory."""
22
+
23
+ def __init__(self, config):
24
+ self.workspace = config.workspace
25
+
26
+ def initialize_dir(self, directory): # pylint: disable=no-self-use
27
+ """Creates directory if it doesn't already exist, otherwise does nothing."""
28
+ os.makedirs(directory, exist_ok=True)
29
+
30
+ @property
31
+ def repo_storage(self):
32
+ """The parent directory for repo storage."""
33
+ return os.path.join(self.workspace, 'storage')
34
+
35
+ @property
36
+ def out(self):
37
+ """The out directory used for storing the fuzzer build built by
38
+ build_fuzzers."""
39
+ # Don't use 'out' because it needs to be used by artifacts.
40
+ return os.path.join(self.workspace, 'build-out')
41
+
42
+ @property
43
+ def work(self):
44
+ """The directory used as the work directory for the fuzzer build/run."""
45
+ return os.path.join(self.workspace, 'work')
46
+
47
+ @property
48
+ def artifacts(self):
49
+ """The directory used to store artifacts for download by CI-system users."""
50
+ # This is hardcoded by a lot of clients, so we need to use this.
51
+ return os.path.join(self.workspace, 'out', 'artifacts')
52
+
53
+ @property
54
+ def clusterfuzz_build(self):
55
+ """The directory where builds from ClusterFuzz are stored."""
56
+ return os.path.join(self.workspace, 'cifuzz-prev-build')
57
+
58
+ @property
59
+ def clusterfuzz_coverage(self):
60
+ """The directory where builds from ClusterFuzz are stored."""
61
+ return os.path.join(self.workspace, 'cifuzz-prev-coverage')
62
+
63
+ @property
64
+ def coverage_report(self):
65
+ """The directory where coverage reports generated by cifuzz are put."""
66
+ return os.path.join(self.workspace, 'cifuzz-coverage')
67
+
68
+ @property
69
+ def corpora(self):
70
+ """The directory where corpora from ClusterFuzz are stored."""
71
+ return os.path.join(self.workspace, 'cifuzz-corpus')
72
+
73
+ @property
74
+ def pruned_corpora(self):
75
+ """The directory where pruned corpora are stored."""
76
+ return os.path.join(self.workspace, 'cifuzz-pruned-corpus')
77
+
78
+ @property
79
+ def sarif(self):
80
+ """The directory where sarif files are stored."""
81
+ return os.path.join(self.workspace, 'cifuzz-sarif')
82
+
83
+ def make_repo_for_sarif(self, repo_manager):
84
+ """Copies the repo over for the sarif upload GitHub action."""
85
+ return shutil.copytree(repo_manager.repo_dir, self.sarif, symlinks=True)
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/helper.py ADDED
@@ -0,0 +1,1810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2016 Google Inc.
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
+ """Helper script for OSS-Fuzz users. Can do common tasks like building
18
+ projects/fuzzers, running them etc."""
19
+
20
+ from __future__ import print_function
21
+ from multiprocessing.dummy import Pool as ThreadPool
22
+ import argparse
23
+ import datetime
24
+ import errno
25
+ import logging
26
+ import os
27
+ import re
28
+ import shlex
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+
34
+ import constants
35
+ import templates
36
+
37
+ OSS_FUZZ_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
38
+ BUILD_DIR = os.path.join(OSS_FUZZ_DIR, 'build')
39
+
40
+ BASE_IMAGE_TAG = ':v1.2.1' # no tag for latest
41
+
42
+ BASE_RUNNER_IMAGE = f'ghcr.io/aixcc-finals/base-runner{BASE_IMAGE_TAG}'
43
+
44
+ BASE_IMAGES = {
45
+ 'generic': [
46
+ f'ghcr.io/aixcc-finals/base-image{BASE_IMAGE_TAG}',
47
+ f'ghcr.io/aixcc-finals/base-clang{BASE_IMAGE_TAG}',
48
+ f'ghcr.io/aixcc-finals/base-builder{BASE_IMAGE_TAG}',
49
+ BASE_RUNNER_IMAGE,
50
+ f'ghcr.io/aixcc-finals/base-runner-debug{BASE_IMAGE_TAG}',
51
+ ],
52
+ 'go': [f'ghcr.io/aixcc-finals/base-builder-go{BASE_IMAGE_TAG}'],
53
+ 'javascript': [f'ghcr.io/aixcc-finals/base-builder-javascript{BASE_IMAGE_TAG}'],
54
+ 'jvm': [f'ghcr.io/aixcc-finals/base-builder-jvm{BASE_IMAGE_TAG}'],
55
+ 'python': [f'ghcr.io/aixcc-finals/base-builder-python{BASE_IMAGE_TAG}'],
56
+ 'rust': [f'ghcr.io/aixcc-finals/base-builder-rust{BASE_IMAGE_TAG}'],
57
+ 'ruby': [f'ghcr.io/aixcc-finals/base-builder-ruby{BASE_IMAGE_TAG}'],
58
+ 'swift': [f'ghcr.io/aixcc-finals/base-builder-swift{BASE_IMAGE_TAG}'],
59
+ }
60
+
61
+ VALID_PROJECT_NAME_REGEX = re.compile(r'^[a-zA-Z0-9_-]+$')
62
+ MAX_PROJECT_NAME_LENGTH = 26
63
+
64
+ CORPUS_URL_FORMAT = (
65
+ 'gs://{project_name}-corpus.clusterfuzz-external.appspot.com/libFuzzer/'
66
+ '{fuzz_target}/')
67
+ CORPUS_BACKUP_URL_FORMAT = (
68
+ 'gs://{project_name}-backup.clusterfuzz-external.appspot.com/corpus/'
69
+ 'libFuzzer/{fuzz_target}/')
70
+
71
+ HTTPS_CORPUS_BACKUP_URL_FORMAT = (
72
+ 'https://storage.googleapis.com/{project_name}-backup.clusterfuzz-external'
73
+ '.appspot.com/corpus/libFuzzer/{fuzz_target}/public.zip')
74
+
75
+ LANGUAGE_REGEX = re.compile(r'[^\s]+')
76
+ PROJECT_LANGUAGE_REGEX = re.compile(r'\s*language\s*:\s*([^\s]+)')
77
+
78
+ WORKDIR_REGEX = re.compile(r'\s*WORKDIR\s*([^\s]+)')
79
+
80
+ # Regex to match special chars in project name.
81
+ SPECIAL_CHARS_REGEX = re.compile('[^a-zA-Z0-9_-]')
82
+
83
+ LANGUAGE_TO_BASE_BUILDER_IMAGE = {
84
+ 'c': 'base-builder',
85
+ 'c++': 'base-builder',
86
+ 'go': 'base-builder-go',
87
+ 'javascript': 'base-builder-javascript',
88
+ 'jvm': 'base-builder-jvm',
89
+ 'python': 'base-builder-python',
90
+ 'ruby': 'base-builder-ruby',
91
+ 'rust': 'base-builder-rust',
92
+ 'swift': 'base-builder-swift'
93
+ }
94
+ ARM_BUILDER_NAME = 'oss-fuzz-buildx-builder'
95
+
96
+ CLUSTERFUZZLITE_ENGINE = 'libfuzzer'
97
+ CLUSTERFUZZLITE_ARCHITECTURE = 'x86_64'
98
+ CLUSTERFUZZLITE_FILESTORE_DIR = 'filestore'
99
+ CLUSTERFUZZLITE_DOCKER_IMAGE = 'ghcr.io/aixcc-finals/cifuzz-run-fuzzers'
100
+
101
+ logger = logging.getLogger(__name__)
102
+
103
+ if sys.version_info[0] >= 3:
104
+ raw_input = input # pylint: disable=invalid-name
105
+
106
+ # pylint: disable=too-many-lines
107
+
108
+
109
+ class Project:
110
+ """Class representing a project that is in OSS-Fuzz or an external project
111
+ (ClusterFuzzLite user)."""
112
+
113
+ def __init__(
114
+ self,
115
+ project_name_or_path,
116
+ is_external=False,
117
+ build_integration_path=constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH):
118
+ self.is_external = is_external
119
+ if self.is_external:
120
+ self.path = os.path.abspath(project_name_or_path)
121
+ self.name = os.path.basename(self.path)
122
+ self.build_integration_path = os.path.join(self.path,
123
+ build_integration_path)
124
+ else:
125
+ self.name = project_name_or_path
126
+ self.path = os.path.join(OSS_FUZZ_DIR, 'projects', self.name)
127
+ self.build_integration_path = self.path
128
+
129
+ @property
130
+ def dockerfile_path(self):
131
+ """Returns path to the project Dockerfile."""
132
+ return os.path.join(self.build_integration_path, 'Dockerfile')
133
+
134
+ @property
135
+ def language(self):
136
+ """Returns project language."""
137
+ project_yaml_path = os.path.join(self.build_integration_path,
138
+ 'project.yaml')
139
+ if not os.path.exists(project_yaml_path):
140
+ logger.warning('No project.yaml. Assuming c++.')
141
+ return constants.DEFAULT_LANGUAGE
142
+
143
+ with open(project_yaml_path) as file_handle:
144
+ content = file_handle.read()
145
+ for line in content.splitlines():
146
+ match = PROJECT_LANGUAGE_REGEX.match(line)
147
+ if match:
148
+ return match.group(1)
149
+
150
+ logger.warning('Language not specified in project.yaml. Assuming c++.')
151
+ return constants.DEFAULT_LANGUAGE
152
+
153
+ @property
154
+ def coverage_extra_args(self):
155
+ """Returns project coverage extra args."""
156
+ project_yaml_path = os.path.join(self.build_integration_path,
157
+ 'project.yaml')
158
+ if not os.path.exists(project_yaml_path):
159
+ logger.warning('project.yaml not found: %s.', project_yaml_path)
160
+ return ''
161
+
162
+ with open(project_yaml_path) as file_handle:
163
+ content = file_handle.read()
164
+
165
+ coverage_flags = ''
166
+ read_coverage_extra_args = False
167
+ # Pass the yaml file and extract the value of the coverage_extra_args key.
168
+ # This is naive yaml parsing and we do not handle comments at this point.
169
+ for line in content.splitlines():
170
+ if read_coverage_extra_args:
171
+ # Break reading coverage args if a new yaml key is defined.
172
+ if len(line) > 0 and line[0] != ' ':
173
+ break
174
+ coverage_flags += line
175
+ if 'coverage_extra_args' in line:
176
+ read_coverage_extra_args = True
177
+ # Include the first line only if it's not a multi-line value.
178
+ if 'coverage_extra_args: >' not in line:
179
+ coverage_flags += line.replace('coverage_extra_args: ', '')
180
+ return coverage_flags
181
+
182
+ @property
183
+ def out(self):
184
+ """Returns the out dir for the project. Creates it if needed."""
185
+ return _get_out_dir(self.name)
186
+
187
+ @property
188
+ def work(self):
189
+ """Returns the out dir for the project. Creates it if needed."""
190
+ return _get_project_build_subdir(self.name, 'work')
191
+
192
+ @property
193
+ def corpus(self):
194
+ """Returns the out dir for the project. Creates it if needed."""
195
+ return _get_project_build_subdir(self.name, 'corpus')
196
+
197
+
198
+ def main(): # pylint: disable=too-many-branches,too-many-return-statements
199
+ """Gets subcommand from program arguments and does it. Returns 0 on success 1
200
+ on error."""
201
+ logging.basicConfig(level=logging.INFO)
202
+ parser = get_parser()
203
+ args = parse_args(parser)
204
+
205
+ # Need to do this before chdir.
206
+ # TODO(https://github.com/google/oss-fuzz/issues/6758): Get rid of chdir.
207
+ if hasattr(args, 'testcase_path'):
208
+ args.testcase_path = _get_absolute_path(args.testcase_path)
209
+ # Note: this has to happen after parse_args above as parse_args needs to know
210
+ # the original CWD for external projects.
211
+ os.chdir(OSS_FUZZ_DIR)
212
+ if not os.path.exists(BUILD_DIR):
213
+ os.mkdir(BUILD_DIR)
214
+
215
+ # We have different default values for `sanitizer` depending on the `engine`.
216
+ # Some commands do not have `sanitizer` argument, so `hasattr` is necessary.
217
+ if hasattr(args, 'sanitizer') and not args.sanitizer:
218
+ if args.project.language == 'javascript':
219
+ args.sanitizer = 'none'
220
+ else:
221
+ args.sanitizer = constants.DEFAULT_SANITIZER
222
+
223
+ if args.command == 'generate':
224
+ result = generate(args)
225
+ elif args.command == 'build_image':
226
+ result = build_image(args)
227
+ elif args.command == 'build_fuzzers':
228
+ result = build_fuzzers(args)
229
+ elif args.command == 'fuzzbench_build_fuzzers':
230
+ result = fuzzbench_build_fuzzers(args)
231
+ elif args.command == 'fuzzbench_run_fuzzer':
232
+ result = fuzzbench_run_fuzzer(args)
233
+ elif args.command == 'fuzzbench_measure':
234
+ result = fuzzbench_measure(args)
235
+ elif args.command == 'check_build':
236
+ result = check_build(args)
237
+ elif args.command == 'download_corpora':
238
+ result = download_corpora(args)
239
+ elif args.command == 'run_fuzzer':
240
+ result = run_fuzzer(args)
241
+ elif args.command == 'coverage':
242
+ result = coverage(args)
243
+ elif args.command == 'introspector':
244
+ result = introspector(args)
245
+ elif args.command == 'reproduce':
246
+ result = reproduce(args)
247
+ if args.propagate_exit_codes:
248
+ return result
249
+ elif args.command == 'shell':
250
+ result = shell(args)
251
+ elif args.command == 'pull_images':
252
+ result = pull_images()
253
+ elif args.command == 'run_clusterfuzzlite':
254
+ result = run_clusterfuzzlite(args)
255
+ else:
256
+ # Print help string if no arguments provided.
257
+ parser.print_help()
258
+ result = False
259
+ return bool_to_retcode(result)
260
+
261
+
262
+ def bool_to_retcode(boolean):
263
+ """Returns 0 if |boolean| is Truthy, 0 is the standard return code for a
264
+ successful process execution. Returns 1 otherwise, indicating the process
265
+ failed."""
266
+ return 0 if boolean else 1
267
+
268
+
269
+ def parse_args(parser, args=None):
270
+ """Parses |args| using |parser| and returns parsed args. Also changes
271
+ |args.build_integration_path| to have correct default behavior."""
272
+ # Use default argument None for args so that in production, argparse does its
273
+ # normal behavior, but unittesting is easier.
274
+ parsed_args = parser.parse_args(args)
275
+ project = getattr(parsed_args, 'project', None)
276
+ if not project:
277
+ return parsed_args
278
+
279
+ # Use hacky method for extracting attributes so that ShellTest works.
280
+ # TODO(metzman): Fix this.
281
+ is_external = getattr(parsed_args, 'external', False)
282
+ parsed_args.project = Project(parsed_args.project, is_external)
283
+ return parsed_args
284
+
285
+
286
+ def _add_external_project_args(parser):
287
+ parser.add_argument(
288
+ '--external',
289
+ help='Is project external?',
290
+ default=False,
291
+ action='store_true',
292
+ )
293
+
294
+
295
+ def get_parser(): # pylint: disable=too-many-statements,too-many-locals
296
+ """Returns an argparse parser."""
297
+ parser = argparse.ArgumentParser('helper.py', description='oss-fuzz helpers')
298
+ subparsers = parser.add_subparsers(dest='command')
299
+
300
+ generate_parser = subparsers.add_parser(
301
+ 'generate', help='Generate files for new project.')
302
+ generate_parser.add_argument('project')
303
+ generate_parser.add_argument('--language',
304
+ default=constants.DEFAULT_LANGUAGE,
305
+ choices=LANGUAGE_TO_BASE_BUILDER_IMAGE.keys(),
306
+ help='Project language.')
307
+ _add_external_project_args(generate_parser)
308
+
309
+ build_image_parser = subparsers.add_parser('build_image',
310
+ help='Build an image.')
311
+ build_image_parser.add_argument('project')
312
+ build_image_parser.add_argument('--pull',
313
+ action='store_true',
314
+ help='Pull latest base image.')
315
+ _add_architecture_args(build_image_parser)
316
+ build_image_parser.add_argument('--cache',
317
+ action='store_true',
318
+ default=False,
319
+ help='Use docker cache when building image.')
320
+ build_image_parser.add_argument('--no-pull',
321
+ action='store_true',
322
+ help='Do not pull latest base image.')
323
+ build_image_parser.add_argument('--docker_image_tag',
324
+ dest='docker_image_tag',
325
+ default='latest',
326
+ help='docker image build tag'
327
+ 'default: latest')
328
+ _add_external_project_args(build_image_parser)
329
+
330
+ build_fuzzers_parser = subparsers.add_parser(
331
+ 'build_fuzzers', help='Build fuzzers for a project.')
332
+ _add_architecture_args(build_fuzzers_parser)
333
+ _add_engine_args(build_fuzzers_parser)
334
+ _add_sanitizer_args(build_fuzzers_parser)
335
+ _add_environment_args(build_fuzzers_parser)
336
+ _add_external_project_args(build_fuzzers_parser)
337
+ build_fuzzers_parser.add_argument('project')
338
+ build_fuzzers_parser.add_argument('source_path',
339
+ help='path of local source',
340
+ nargs='?')
341
+ build_fuzzers_parser.add_argument('--mount_path',
342
+ dest='mount_path',
343
+ help='path to mount local source in '
344
+ '(defaults to WORKDIR)')
345
+ build_fuzzers_parser.add_argument('--clean',
346
+ dest='clean',
347
+ action='store_true',
348
+ help='clean existing artifacts.')
349
+ build_fuzzers_parser.add_argument('--no-clean',
350
+ dest='clean',
351
+ action='store_false',
352
+ help='do not clean existing artifacts '
353
+ '(default).')
354
+ build_fuzzers_parser.add_argument('--docker_image_tag',
355
+ dest='docker_image_tag',
356
+ default='latest',
357
+ help='docker image build tag'
358
+ 'default: latest')
359
+ build_fuzzers_parser.set_defaults(clean=False)
360
+
361
+ fuzzbench_build_fuzzers_parser = subparsers.add_parser(
362
+ 'fuzzbench_build_fuzzers')
363
+ _add_architecture_args(fuzzbench_build_fuzzers_parser)
364
+ fuzzbench_build_fuzzers_parser.add_argument('--engine')
365
+ _add_sanitizer_args(fuzzbench_build_fuzzers_parser)
366
+ _add_environment_args(fuzzbench_build_fuzzers_parser)
367
+ _add_external_project_args(fuzzbench_build_fuzzers_parser)
368
+ fuzzbench_build_fuzzers_parser.add_argument('project')
369
+ check_build_parser = subparsers.add_parser(
370
+ 'check_build', help='Checks that fuzzers execute without errors.')
371
+ _add_architecture_args(check_build_parser)
372
+ _add_engine_args(check_build_parser, choices=constants.ENGINES)
373
+ _add_sanitizer_args(check_build_parser, choices=constants.SANITIZERS)
374
+ _add_environment_args(check_build_parser)
375
+ check_build_parser.add_argument('project',
376
+ help='name of the project or path (external)')
377
+ check_build_parser.add_argument('fuzzer_name',
378
+ help='name of the fuzzer',
379
+ nargs='?')
380
+ _add_external_project_args(check_build_parser)
381
+
382
+ run_fuzzer_parser = subparsers.add_parser(
383
+ 'run_fuzzer', help='Run a fuzzer in the emulated fuzzing environment.')
384
+ _add_architecture_args(run_fuzzer_parser)
385
+ _add_engine_args(run_fuzzer_parser)
386
+ _add_sanitizer_args(run_fuzzer_parser)
387
+ _add_environment_args(run_fuzzer_parser)
388
+ _add_external_project_args(run_fuzzer_parser)
389
+ run_fuzzer_parser.add_argument(
390
+ '--corpus-dir', help='directory to store corpus for the fuzz target')
391
+ run_fuzzer_parser.add_argument('project',
392
+ help='name of the project or path (external)')
393
+ run_fuzzer_parser.add_argument('fuzzer_name', help='name of the fuzzer')
394
+ run_fuzzer_parser.add_argument('fuzzer_args',
395
+ help='arguments to pass to the fuzzer',
396
+ nargs='*')
397
+
398
+ fuzzbench_run_fuzzer_parser = subparsers.add_parser('fuzzbench_run_fuzzer')
399
+ _add_architecture_args(fuzzbench_run_fuzzer_parser)
400
+ fuzzbench_run_fuzzer_parser.add_argument('--engine')
401
+ _add_sanitizer_args(fuzzbench_run_fuzzer_parser)
402
+ _add_environment_args(fuzzbench_run_fuzzer_parser)
403
+ _add_external_project_args(fuzzbench_run_fuzzer_parser)
404
+ fuzzbench_run_fuzzer_parser.add_argument(
405
+ '--corpus-dir', help='directory to store corpus for the fuzz target')
406
+ fuzzbench_run_fuzzer_parser.add_argument(
407
+ 'project', help='name of the project or path (external)')
408
+ fuzzbench_run_fuzzer_parser.add_argument('fuzzer_name',
409
+ help='name of the fuzzer')
410
+ fuzzbench_run_fuzzer_parser.add_argument(
411
+ 'fuzzer_args', help='arguments to pass to the fuzzer', nargs='*')
412
+
413
+ fuzzbench_measure_parser = subparsers.add_parser('fuzzbench_measure')
414
+ fuzzbench_measure_parser.add_argument(
415
+ 'project', help='name of the project or path (external)')
416
+ fuzzbench_measure_parser.add_argument('engine_name',
417
+ help='name of the fuzzer')
418
+ fuzzbench_measure_parser.add_argument('fuzz_target_name',
419
+ help='name of the fuzzer')
420
+
421
+ coverage_parser = subparsers.add_parser(
422
+ 'coverage', help='Generate code coverage report for the project.')
423
+ coverage_parser.add_argument('--no-corpus-download',
424
+ action='store_true',
425
+ help='do not download corpus backup from '
426
+ 'OSS-Fuzz; use corpus located in '
427
+ 'build/corpus/<project>/<fuzz_target>/')
428
+ coverage_parser.add_argument('--no-serve',
429
+ action='store_true',
430
+ help='do not serve a local HTTP server.')
431
+ coverage_parser.add_argument('--port',
432
+ default='8008',
433
+ help='specify port for'
434
+ ' a local HTTP server rendering coverage report')
435
+ coverage_parser.add_argument('--fuzz-target',
436
+ help='specify name of a fuzz '
437
+ 'target to be run for generating coverage '
438
+ 'report')
439
+ coverage_parser.add_argument('--corpus-dir',
440
+ help='specify location of corpus'
441
+ ' to be used (requires --fuzz-target argument)')
442
+ coverage_parser.add_argument('--public',
443
+ action='store_true',
444
+ help='if set, will download public '
445
+ 'corpus using wget')
446
+ coverage_parser.add_argument('project',
447
+ help='name of the project or path (external)')
448
+ coverage_parser.add_argument('extra_args',
449
+ help='additional arguments to '
450
+ 'pass to llvm-cov utility.',
451
+ nargs='*')
452
+ _add_external_project_args(coverage_parser)
453
+ _add_architecture_args(coverage_parser)
454
+
455
+ introspector_parser = subparsers.add_parser(
456
+ 'introspector',
457
+ help='Run a complete end-to-end run of '
458
+ 'fuzz introspector. This involves (1) '
459
+ 'building the fuzzers with ASAN; (2) '
460
+ 'running all fuzzers; (3) building '
461
+ 'fuzzers with coverge; (4) extracting '
462
+ 'coverage; (5) building fuzzers using '
463
+ 'introspector')
464
+ introspector_parser.add_argument('project', help='name of the project')
465
+ introspector_parser.add_argument('--seconds',
466
+ help='number of seconds to run fuzzers',
467
+ default=10)
468
+ introspector_parser.add_argument('source_path',
469
+ help='path of local source',
470
+ nargs='?')
471
+ introspector_parser.add_argument(
472
+ '--public-corpora',
473
+ help='if specified, will use public corpora for code coverage',
474
+ default=False,
475
+ action='store_true')
476
+ introspector_parser.add_argument(
477
+ '--private-corpora',
478
+ help='if specified, will use private corpora',
479
+ default=False,
480
+ action='store_true')
481
+
482
+ download_corpora_parser = subparsers.add_parser(
483
+ 'download_corpora', help='Download all corpora for a project.')
484
+ download_corpora_parser.add_argument('--fuzz-target',
485
+ nargs='+',
486
+ help='specify name of a fuzz target')
487
+ download_corpora_parser.add_argument('--public',
488
+ action='store_true',
489
+ help='if set, will download public '
490
+ 'corpus using wget')
491
+ download_corpora_parser.add_argument(
492
+ 'project', help='name of the project or path (external)')
493
+
494
+ reproduce_parser = subparsers.add_parser('reproduce',
495
+ help='Reproduce a crash.')
496
+ reproduce_parser.add_argument('--valgrind',
497
+ action='store_true',
498
+ help='run with valgrind')
499
+ reproduce_parser.add_argument('--propagate_exit_codes',
500
+ action='store_true',
501
+ default=False,
502
+ help='return underlying exit codes instead of True/False.')
503
+ reproduce_parser.add_argument('--not_privileged',
504
+ dest='privileged',
505
+ action='store_false',
506
+ default=True,
507
+ help='reproduce without running docker in privileged mode.')
508
+ reproduce_parser.add_argument('--err_result',
509
+ help='exit code override for missing harness / fuzz targets '
510
+ '(default err_result = 1).',
511
+ type=int)
512
+ reproduce_parser.add_argument('--timeout',
513
+ help='timeout for reproduce subprocess '
514
+ '(default: None).',
515
+ default=None,
516
+ type=int)
517
+ reproduce_parser.add_argument('project',
518
+ help='name of the project or path (external)')
519
+ reproduce_parser.add_argument('fuzzer_name', help='name of the fuzzer')
520
+ reproduce_parser.add_argument('testcase_path', help='path of local testcase')
521
+ reproduce_parser.add_argument('fuzzer_args',
522
+ help='arguments to pass to the fuzzer',
523
+ nargs='*')
524
+ _add_environment_args(reproduce_parser)
525
+ _add_external_project_args(reproduce_parser)
526
+ _add_architecture_args(reproduce_parser)
527
+
528
+ shell_parser = subparsers.add_parser(
529
+ 'shell', help='Run /bin/bash within the builder container.')
530
+ shell_parser.add_argument('project',
531
+ help='name of the project or path (external)')
532
+ shell_parser.add_argument('source_path',
533
+ help='path of local source',
534
+ nargs='?')
535
+ shell_parser.add_argument('--docker_image_tag',
536
+ dest='docker_image_tag',
537
+ default='latest',
538
+ help='docker image build tag'
539
+ 'default: latest')
540
+ _add_architecture_args(shell_parser)
541
+ _add_engine_args(shell_parser)
542
+ _add_sanitizer_args(shell_parser)
543
+ _add_environment_args(shell_parser)
544
+ _add_external_project_args(shell_parser)
545
+
546
+ run_clusterfuzzlite_parser = subparsers.add_parser(
547
+ 'run_clusterfuzzlite', help='Run ClusterFuzzLite on a project.')
548
+ _add_sanitizer_args(run_clusterfuzzlite_parser)
549
+ _add_environment_args(run_clusterfuzzlite_parser)
550
+ run_clusterfuzzlite_parser.add_argument('project')
551
+ run_clusterfuzzlite_parser.add_argument('--clean',
552
+ dest='clean',
553
+ action='store_true',
554
+ help='clean existing artifacts.')
555
+ run_clusterfuzzlite_parser.add_argument(
556
+ '--no-clean',
557
+ dest='clean',
558
+ action='store_false',
559
+ help='do not clean existing artifacts '
560
+ '(default).')
561
+ run_clusterfuzzlite_parser.add_argument('--branch',
562
+ default='master',
563
+ required=True)
564
+ _add_external_project_args(run_clusterfuzzlite_parser)
565
+ run_clusterfuzzlite_parser.set_defaults(clean=False)
566
+
567
+ subparsers.add_parser('pull_images', help='Pull base images.')
568
+ return parser
569
+
570
+
571
+ def is_base_image(image_name):
572
+ """Checks if the image name is a base image."""
573
+ return os.path.exists(os.path.join('infra', 'base-images', image_name))
574
+
575
+
576
+ def check_project_exists(project):
577
+ """Checks if a project exists."""
578
+ if os.path.exists(project.path):
579
+ return True
580
+
581
+ if project.is_external:
582
+ descriptive_project_name = project.path
583
+ else:
584
+ descriptive_project_name = project.name
585
+
586
+ logger.error('"%s" does not exist.', descriptive_project_name)
587
+ return False
588
+
589
+
590
+ def _check_fuzzer_exists(project, fuzzer_name, architecture='x86_64'):
591
+ """Checks if a fuzzer exists."""
592
+ platform = 'linux/arm64' if architecture == 'aarch64' else 'linux/amd64'
593
+ command = ['docker', 'run', '--rm', '--platform', platform]
594
+ command.extend(['-v', '%s:/out' % project.out])
595
+ command.append(BASE_RUNNER_IMAGE)
596
+
597
+ command.extend(['/bin/bash', '-c', 'test -f /out/%s' % fuzzer_name])
598
+
599
+ try:
600
+ subprocess.check_call(command)
601
+ except subprocess.CalledProcessError:
602
+ logger.error('%s does not seem to exist. Please run build_fuzzers first.',
603
+ fuzzer_name)
604
+ return False
605
+
606
+ return True
607
+
608
+
609
+ def _normalized_name(name):
610
+ """Return normalized name with special chars like slash, colon, etc normalized
611
+ to hyphen(-). This is important as otherwise these chars break local and cloud
612
+ storage paths."""
613
+ return SPECIAL_CHARS_REGEX.sub('-', name).strip('-')
614
+
615
+
616
+ def _get_absolute_path(path):
617
+ """Returns absolute path with user expansion."""
618
+ return os.path.abspath(os.path.expanduser(path))
619
+
620
+
621
+ def _get_command_string(command):
622
+ """Returns a shell escaped command string."""
623
+ return ' '.join(shlex.quote(part) for part in command)
624
+
625
+
626
+ def _get_project_build_subdir(project, subdir_name):
627
+ """Creates the |subdir_name| subdirectory of the |project| subdirectory in
628
+ |BUILD_DIR| and returns its path."""
629
+ directory = os.path.join(BUILD_DIR, subdir_name, project)
630
+ os.makedirs(directory, exist_ok=True)
631
+
632
+ return directory
633
+
634
+
635
+ def _get_out_dir(project=''):
636
+ """Creates and returns path to /out directory for the given project (if
637
+ specified)."""
638
+ return _get_project_build_subdir(project, 'out')
639
+
640
+
641
+ def _add_architecture_args(parser, choices=None):
642
+ """Adds common architecture args."""
643
+ if choices is None:
644
+ choices = constants.ARCHITECTURES
645
+ parser.add_argument('--architecture',
646
+ default=constants.DEFAULT_ARCHITECTURE,
647
+ choices=choices)
648
+
649
+
650
+ def _add_engine_args(parser, choices=None):
651
+ """Adds common engine args."""
652
+ if choices is None:
653
+ choices = constants.ENGINES
654
+ parser.add_argument('--engine',
655
+ default=constants.DEFAULT_ENGINE,
656
+ choices=choices)
657
+
658
+
659
+ def _add_sanitizer_args(parser, choices=None):
660
+ """Adds common sanitizer args."""
661
+ if choices is None:
662
+ choices = constants.SANITIZERS
663
+ parser.add_argument('--sanitizer',
664
+ default=None,
665
+ choices=choices,
666
+ help='the default is "address"')
667
+
668
+
669
+ def _add_environment_args(parser):
670
+ """Adds common environment args."""
671
+ parser.add_argument('-e',
672
+ action='append',
673
+ help="set environment variable e.g. VAR=value")
674
+
675
+
676
+ def build_image_impl(project, cache=True, pull=False,
677
+ architecture='x86_64',
678
+ docker_image_tag='latest'):
679
+ """Builds image."""
680
+ image_name = project.name
681
+
682
+ if is_base_image(image_name):
683
+ image_project = 'aixcc-finals'
684
+ docker_build_dir = os.path.join(OSS_FUZZ_DIR, 'infra', 'base-images',
685
+ image_name)
686
+ dockerfile_path = os.path.join(docker_build_dir, 'Dockerfile')
687
+ image_name = 'ghcr.io/%s/%s%s' % (image_project, image_name, BASE_IMAGE_TAG)
688
+ else:
689
+ if not check_project_exists(project):
690
+ return False
691
+ dockerfile_path = project.dockerfile_path
692
+ docker_build_dir = project.path
693
+ image_project = 'aixcc-afc'
694
+ image_name = '%s/%s:%s' % (image_project, image_name, docker_image_tag)
695
+
696
+ if pull and not pull_images(project.language):
697
+ return False
698
+
699
+ build_args = []
700
+ if architecture == 'aarch64':
701
+ build_args += [
702
+ 'buildx',
703
+ 'build',
704
+ '--platform',
705
+ 'linux/arm64',
706
+ '--progress',
707
+ 'plain',
708
+ '--load',
709
+ ]
710
+ if not cache:
711
+ build_args.append('--no-cache')
712
+
713
+ build_args += ['-t', image_name, '--file', dockerfile_path]
714
+ build_args.append(docker_build_dir)
715
+
716
+ if architecture == 'aarch64':
717
+ command = ['docker'] + build_args
718
+ subprocess.check_call(command)
719
+ return True
720
+ return docker_build(build_args)
721
+
722
+
723
+ def _env_to_docker_args(env_list):
724
+ """Turns envirnoment variable list into docker arguments."""
725
+ return sum([['-e', v] for v in env_list], [])
726
+
727
+
728
+ def workdir_from_lines(lines, default='/src'):
729
+ """Gets the WORKDIR from the given lines."""
730
+ for line in reversed(lines): # reversed to get last WORKDIR.
731
+ match = re.match(WORKDIR_REGEX, line)
732
+ if match:
733
+ workdir = match.group(1)
734
+ workdir = workdir.replace('$SRC', '/src')
735
+
736
+ if not os.path.isabs(workdir):
737
+ workdir = os.path.join('/src', workdir)
738
+
739
+ return os.path.normpath(workdir)
740
+
741
+ return default
742
+
743
+
744
+ def _workdir_from_dockerfile(project):
745
+ """Parses WORKDIR from the Dockerfile for the given project."""
746
+ with open(project.dockerfile_path) as file_handle:
747
+ lines = file_handle.readlines()
748
+
749
+ return workdir_from_lines(lines, default=os.path.join('/src', project.name))
750
+
751
+
752
+ def prepare_aarch64_emulation():
753
+ """Run some necessary commands to use buildx to build AArch64 targets using
754
+ QEMU emulation on an x86_64 host."""
755
+ subprocess.check_call(
756
+ ['docker', 'buildx', 'create', '--name', ARM_BUILDER_NAME])
757
+ subprocess.check_call(['docker', 'buildx', 'use', ARM_BUILDER_NAME])
758
+
759
+
760
+ def docker_run(run_args, print_output=True, architecture='x86_64', propagate_exit_codes=False, privileged=True, timeout=None):
761
+ """Calls `docker run`."""
762
+ platform = 'linux/arm64' if architecture == 'aarch64' else 'linux/amd64'
763
+
764
+ if privileged:
765
+ command = [
766
+ 'docker', 'run', '--privileged', '--shm-size=2g', '--platform', platform
767
+ ]
768
+ else:
769
+ command = [
770
+ 'docker', 'run', '--shm-size=2g', '--platform', platform
771
+ ]
772
+
773
+ if os.getenv('OSS_FUZZ_SAVE_CONTAINERS_NAME'):
774
+ command.append('--name')
775
+ command.append(os.getenv('OSS_FUZZ_SAVE_CONTAINERS_NAME'))
776
+ else:
777
+ command.append('--rm')
778
+
779
+ # Support environments with a TTY.
780
+ if sys.stdin.isatty():
781
+ command.append('-i')
782
+
783
+ command.extend(run_args)
784
+
785
+ logger.info('Running: %s.', _get_command_string(command))
786
+ stdout = None
787
+ if not print_output:
788
+ stdout = open(os.devnull, 'w')
789
+
790
+ exit_code = 0
791
+
792
+ try:
793
+ subprocess.check_call(command, stdout=stdout, stderr=subprocess.STDOUT,
794
+ timeout=timeout)
795
+ except subprocess.CalledProcessError as e:
796
+ print(f'subprocess command returned a non-zero exit status: {e.returncode}')
797
+ exit_code = e.returncode
798
+ except subprocess.TimeoutExpired:
799
+ print(f'subprocess command timed out: {timeout=}')
800
+ exit_code = 124
801
+
802
+ return exit_code if propagate_exit_codes else exit_code == 0
803
+
804
+
805
+ def docker_build(build_args):
806
+ """Calls `docker build`."""
807
+ command = ['docker', 'build']
808
+ command.extend(build_args)
809
+ logger.info('Running: %s.', _get_command_string(command))
810
+
811
+ try:
812
+ subprocess.check_call(command)
813
+ except subprocess.CalledProcessError:
814
+ logger.error('Docker build failed.')
815
+ return False
816
+
817
+ return True
818
+
819
+
820
+ def docker_pull(image):
821
+ """Call `docker pull`."""
822
+ command = ['docker', 'pull', image]
823
+ logger.info('Running: %s', _get_command_string(command))
824
+
825
+ try:
826
+ subprocess.check_call(command)
827
+ except subprocess.CalledProcessError:
828
+ logger.error('Docker pull failed.')
829
+ return False
830
+
831
+ return True
832
+
833
+
834
+ def build_image(args):
835
+ """Builds docker image."""
836
+ if args.pull and args.no_pull:
837
+ logger.error('Incompatible arguments --pull and --no-pull.')
838
+ return False
839
+
840
+ if args.pull:
841
+ pull = True
842
+ elif args.no_pull:
843
+ pull = False
844
+ else:
845
+ y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ')
846
+ pull = y_or_n.lower() == 'y'
847
+
848
+ if pull:
849
+ logger.info('Pulling latest base images...')
850
+ else:
851
+ logger.info('Using cached base images...')
852
+
853
+ # If build_image is called explicitly, don't use cache.
854
+ if build_image_impl(args.project,
855
+ cache=args.cache,
856
+ pull=pull,
857
+ architecture=args.architecture,
858
+ docker_image_tag=args.docker_image_tag):
859
+ return True
860
+
861
+ return False
862
+
863
+
864
+ def build_fuzzers_impl( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
865
+ project,
866
+ clean,
867
+ engine,
868
+ sanitizer,
869
+ architecture,
870
+ env_to_add,
871
+ source_path,
872
+ mount_path=None,
873
+ child_dir='',
874
+ build_project_image=True,
875
+ docker_image_tag='latest'):
876
+ """Builds fuzzers."""
877
+ if build_project_image and not build_image_impl(project,
878
+ architecture=architecture,
879
+ docker_image_tag=docker_image_tag):
880
+ return False
881
+
882
+ docker_image = f'aixcc-afc/{project.name}:{docker_image_tag}'
883
+
884
+ project_out = os.path.join(project.out, child_dir)
885
+ if clean:
886
+ logger.info('Cleaning existing build artifacts.')
887
+
888
+ # Clean old and possibly conflicting artifacts in project's out directory.
889
+ docker_run([
890
+ '-v', f'{project_out}:/out', '-t', f'{docker_image}',
891
+ '/bin/bash', '-c', 'rm -rf /out/*'
892
+ ],
893
+ architecture=architecture)
894
+
895
+ docker_run([
896
+ '-v',
897
+ '%s:/work' % project.work, '-t',
898
+ f'{docker_image}', '/bin/bash', '-c', 'rm -rf /work/*'
899
+ ],
900
+ architecture=architecture)
901
+
902
+ else:
903
+ logger.info('Keeping existing build artifacts as-is (if any).')
904
+ env = [
905
+ 'FUZZING_ENGINE=' + engine,
906
+ 'SANITIZER=' + sanitizer,
907
+ 'ARCHITECTURE=' + architecture,
908
+ 'PROJECT_NAME=' + project.name,
909
+ 'HELPER=True',
910
+ ]
911
+
912
+ _add_oss_fuzz_ci_if_needed(env)
913
+
914
+ if project.language:
915
+ env.append('FUZZING_LANGUAGE=' + project.language)
916
+
917
+ if env_to_add:
918
+ env += env_to_add
919
+
920
+ command = _env_to_docker_args(env)
921
+ if source_path:
922
+ workdir = _workdir_from_dockerfile(project)
923
+ stateless_path = mount_path if mount_path else workdir
924
+
925
+ if stateless_path == '/src':
926
+ logger.error('Cannot mount local source targeting "/src".')
927
+ return False
928
+
929
+ command += [
930
+ '-v',
931
+ '%s:%s:ro' % (_get_absolute_path(source_path), '/local-source-mount'),
932
+ ]
933
+
934
+ command += [
935
+ '-v', f'{project_out}:/out', '-v', f'{project.work}:/work',
936
+ f'{docker_image}'
937
+ ]
938
+
939
+ if sys.stdin.isatty():
940
+ command.insert(-1, '-t')
941
+
942
+ if source_path:
943
+ default_cmd = 'compile'
944
+ command += [
945
+ '/bin/bash',
946
+ '-c',
947
+ f'pushd $SRC && rm -rf {stateless_path} && cp -r /local-source-mount {stateless_path} && popd && {default_cmd}'
948
+ ]
949
+
950
+ result = docker_run(command, architecture=architecture)
951
+ if not result:
952
+ logger.error('Building fuzzers failed.')
953
+ return False
954
+
955
+ return True
956
+
957
+
958
+ def run_clusterfuzzlite(args):
959
+ """Runs ClusterFuzzLite on a local repo."""
960
+ if not os.path.exists(CLUSTERFUZZLITE_FILESTORE_DIR):
961
+ os.mkdir(CLUSTERFUZZLITE_FILESTORE_DIR)
962
+
963
+ try:
964
+ with tempfile.TemporaryDirectory() as workspace:
965
+
966
+ if args.external:
967
+ project_src_path = os.path.join(workspace, args.project.name)
968
+ shutil.copytree(args.project.path, project_src_path)
969
+
970
+ build_command = [
971
+ '--tag', 'ghcr.io/aixcc-finals/cifuzz-run-fuzzers', '--file',
972
+ 'infra/run_fuzzers.Dockerfile', 'infra'
973
+ ]
974
+ if not docker_build(build_command):
975
+ return False
976
+ filestore_path = os.path.abspath(CLUSTERFUZZLITE_FILESTORE_DIR)
977
+ docker_run_command = []
978
+ if args.external:
979
+ docker_run_command += [
980
+ '-e',
981
+ f'PROJECT_SRC_PATH={project_src_path}',
982
+ ]
983
+ else:
984
+ docker_run_command += [
985
+ '-e',
986
+ f'OSS_FUZZ_PROJECT_NAME={args.project.name}',
987
+ ]
988
+ docker_run_command += [
989
+ '-v',
990
+ f'{filestore_path}:{filestore_path}',
991
+ '-v',
992
+ f'{workspace}:{workspace}',
993
+ '-e',
994
+ f'FILESTORE_ROOT_DIR={filestore_path}',
995
+ '-e',
996
+ f'WORKSPACE={workspace}',
997
+ '-e',
998
+ f'REPOSITORY={args.project.name}',
999
+ '-e',
1000
+ 'CFL_PLATFORM=standalone',
1001
+ '--entrypoint',
1002
+ '',
1003
+ '-v',
1004
+ '/var/run/docker.sock:/var/run/docker.sock',
1005
+ CLUSTERFUZZLITE_DOCKER_IMAGE,
1006
+ 'python3',
1007
+ '/opt/oss-fuzz/infra/cifuzz/cifuzz_combined_entrypoint.py',
1008
+ ]
1009
+ return docker_run(docker_run_command)
1010
+
1011
+ except PermissionError as error:
1012
+ logger.error('PermissionError: %s.', error)
1013
+ # Tempfile can't delete the workspace because of a permissions issue. This
1014
+ # is because docker creates files in the workspace that are owned by root
1015
+ # but this process is probably being run as another user. Use a docker image
1016
+ # to delete the temp directory (workspace) so that we have permission.
1017
+ docker_run([
1018
+ '-v', f'{workspace}:{workspace}', '--entrypoint', '',
1019
+ CLUSTERFUZZLITE_DOCKER_IMAGE, 'rm', '-rf',
1020
+ os.path.join(workspace, '*')
1021
+ ])
1022
+ return False
1023
+
1024
+
1025
+ def build_fuzzers(args):
1026
+ """Builds fuzzers."""
1027
+ if args.engine == 'centipede' and args.sanitizer != 'none':
1028
+ # Centipede always requires separate binaries for sanitizers:
1029
+ # An unsanitized binary, which Centipede requires for fuzzing.
1030
+ # A sanitized binary, placed in the child directory.
1031
+ sanitized_binary_directories = (
1032
+ ('none', ''),
1033
+ (args.sanitizer, f'__centipede_{args.sanitizer}'),
1034
+ )
1035
+ else:
1036
+ # Generally, a fuzzer only needs one sanitized binary in the default dir.
1037
+ sanitized_binary_directories = ((args.sanitizer, ''),)
1038
+ return all(
1039
+ build_fuzzers_impl(args.project,
1040
+ args.clean,
1041
+ args.engine,
1042
+ sanitizer,
1043
+ args.architecture,
1044
+ args.e,
1045
+ args.source_path,
1046
+ mount_path=args.mount_path,
1047
+ child_dir=child_dir,
1048
+ docker_image_tag=args.docker_image_tag)
1049
+ for sanitizer, child_dir in sanitized_binary_directories)
1050
+
1051
+
1052
+ def fuzzbench_build_fuzzers(args):
1053
+ """Builds fuzz targets with an arbitrary fuzzer from FuzzBench."""
1054
+ with tempfile.TemporaryDirectory() as tmp_dir:
1055
+ tmp_dir = os.path.abspath(tmp_dir)
1056
+ fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench')
1057
+ subprocess.run([
1058
+ 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1',
1059
+ fuzzbench_path
1060
+ ],
1061
+ check=True)
1062
+ env = [
1063
+ f'FUZZBENCH_PATH={fuzzbench_path}', 'OSS_FUZZ_ON_DEMAND=1',
1064
+ f'PROJECT={args.project.name}'
1065
+ ]
1066
+ tag = f'aixcc-afc/{args.project.name}'
1067
+ subprocess.run([
1068
+ 'docker', 'tag', 'ghcr.io/aixcc-finals/base-builder-fuzzbench',
1069
+ f'ghcr.io/aixcc-finals/base-builder{BASE_IMAGE_TAG}'
1070
+ ],
1071
+ check=True)
1072
+ build_image_impl(args.project)
1073
+ assert docker_build([
1074
+ '--tag', tag, '--build-arg', f'parent_image={tag}', '--file',
1075
+ os.path.join(fuzzbench_path, 'fuzzers', args.engine,
1076
+ 'builder.Dockerfile'),
1077
+ os.path.join(fuzzbench_path, 'fuzzers', args.engine)
1078
+ ])
1079
+
1080
+ return build_fuzzers_impl(args.project,
1081
+ False,
1082
+ args.engine,
1083
+ args.sanitizer,
1084
+ args.architecture,
1085
+ env,
1086
+ source_path=fuzzbench_path,
1087
+ mount_path=fuzzbench_path,
1088
+ build_project_image=False)
1089
+
1090
+
1091
+ def _add_oss_fuzz_ci_if_needed(env):
1092
+ """Adds value of |OSS_FUZZ_CI| environment variable to |env| if it is set."""
1093
+ oss_fuzz_ci = os.getenv('OSS_FUZZ_CI')
1094
+ if oss_fuzz_ci:
1095
+ env.append('OSS_FUZZ_CI=' + oss_fuzz_ci)
1096
+
1097
+
1098
+ def check_build(args):
1099
+ """Checks that fuzzers in the container execute without errors."""
1100
+ if not check_project_exists(args.project):
1101
+ return False
1102
+
1103
+ if (args.fuzzer_name and not _check_fuzzer_exists(
1104
+ args.project, args.fuzzer_name, args.architecture)):
1105
+ return False
1106
+
1107
+ env = [
1108
+ 'FUZZING_ENGINE=' + args.engine,
1109
+ 'SANITIZER=' + args.sanitizer,
1110
+ 'ARCHITECTURE=' + args.architecture,
1111
+ 'FUZZING_LANGUAGE=' + args.project.language,
1112
+ 'HELPER=True',
1113
+ ]
1114
+ _add_oss_fuzz_ci_if_needed(env)
1115
+ if args.e:
1116
+ env += args.e
1117
+
1118
+ run_args = _env_to_docker_args(env) + [
1119
+ '-v', f'{args.project.out}:/out', '-t', BASE_RUNNER_IMAGE
1120
+ ]
1121
+
1122
+ if args.fuzzer_name:
1123
+ run_args += ['test_one.py', args.fuzzer_name]
1124
+ else:
1125
+ run_args.append('test_all.py')
1126
+
1127
+ result = docker_run(run_args, architecture=args.architecture)
1128
+ if result:
1129
+ logger.info('Check build passed.')
1130
+ else:
1131
+ logger.error('Check build failed.')
1132
+
1133
+ return result
1134
+
1135
+
1136
+ def _get_fuzz_targets(project):
1137
+ """Returns names of fuzz targest build in the project's /out directory."""
1138
+ fuzz_targets = []
1139
+ for name in os.listdir(project.out):
1140
+ if name.startswith('afl-'):
1141
+ continue
1142
+ if name == 'centipede':
1143
+ continue
1144
+ if name.startswith('jazzer_'):
1145
+ continue
1146
+ if name == 'llvm-symbolizer':
1147
+ continue
1148
+
1149
+ path = os.path.join(project.out, name)
1150
+ # Python and JVM fuzz targets are only executable for the root user, so
1151
+ # we can't use os.access.
1152
+ if os.path.isfile(path) and (os.stat(path).st_mode & 0o111):
1153
+ fuzz_targets.append(name)
1154
+
1155
+ return fuzz_targets
1156
+
1157
+
1158
+ def _get_latest_corpus(project, fuzz_target, base_corpus_dir):
1159
+ """Downloads the latest corpus for the given fuzz target."""
1160
+ corpus_dir = os.path.join(base_corpus_dir, fuzz_target)
1161
+ os.makedirs(corpus_dir, exist_ok=True)
1162
+
1163
+ if not fuzz_target.startswith(project.name + '_'):
1164
+ fuzz_target = '%s_%s' % (project.name, fuzz_target)
1165
+
1166
+ # Normalise fuzz target name.
1167
+ fuzz_target = _normalized_name(fuzz_target)
1168
+
1169
+ corpus_backup_url = CORPUS_BACKUP_URL_FORMAT.format(project_name=project.name,
1170
+ fuzz_target=fuzz_target)
1171
+ command = ['gsutil', 'ls', corpus_backup_url]
1172
+
1173
+ # Don't capture stderr. We want it to print in real time, in case gsutil is
1174
+ # asking for two-factor authentication.
1175
+ corpus_listing = subprocess.Popen(command, stdout=subprocess.PIPE)
1176
+ output, _ = corpus_listing.communicate()
1177
+
1178
+ # Some fuzz targets (e.g. new ones) may not have corpus yet, just skip those.
1179
+ if corpus_listing.returncode:
1180
+ logger.warning('Corpus for %s not found:\n', fuzz_target)
1181
+ return
1182
+
1183
+ if output:
1184
+ latest_backup_url = output.splitlines()[-1]
1185
+ archive_path = corpus_dir + '.zip'
1186
+ command = ['gsutil', '-q', 'cp', latest_backup_url, archive_path]
1187
+ subprocess.check_call(command)
1188
+
1189
+ command = ['unzip', '-q', '-o', archive_path, '-d', corpus_dir]
1190
+ subprocess.check_call(command)
1191
+ os.remove(archive_path)
1192
+ else:
1193
+ # Sync the working corpus copy if a minimized backup is not available.
1194
+ corpus_url = CORPUS_URL_FORMAT.format(project_name=project.name,
1195
+ fuzz_target=fuzz_target)
1196
+ command = ['gsutil', '-m', '-q', 'rsync', '-R', corpus_url, corpus_dir]
1197
+ subprocess.check_call(command)
1198
+
1199
+
1200
+ def _get_latest_public_corpus(args, fuzzer):
1201
+ """Downloads the public corpus"""
1202
+ target_corpus_dir = "build/corpus/%s" % args.project.name
1203
+ if not os.path.isdir(target_corpus_dir):
1204
+ os.makedirs(target_corpus_dir)
1205
+
1206
+ target_zip = os.path.join(target_corpus_dir, fuzzer + ".zip")
1207
+
1208
+ project_qualified_fuzz_target_name = fuzzer
1209
+ qualified_name_prefix = args.project.name + '_'
1210
+ if not fuzzer.startswith(qualified_name_prefix):
1211
+ project_qualified_fuzz_target_name = qualified_name_prefix + fuzzer
1212
+
1213
+ download_url = HTTPS_CORPUS_BACKUP_URL_FORMAT.format(
1214
+ project_name=args.project.name,
1215
+ fuzz_target=project_qualified_fuzz_target_name)
1216
+
1217
+ cmd = ['wget', download_url, '-O', target_zip]
1218
+ try:
1219
+ with open(os.devnull, 'w') as stdout:
1220
+ subprocess.check_call(cmd, stdout=stdout)
1221
+ except OSError:
1222
+ logger.error('Failed to download corpus')
1223
+
1224
+ target_fuzzer_dir = os.path.join(target_corpus_dir, fuzzer)
1225
+ if not os.path.isdir(target_fuzzer_dir):
1226
+ os.mkdir(target_fuzzer_dir)
1227
+
1228
+ target_corpus_dir = os.path.join(target_corpus_dir, fuzzer)
1229
+ try:
1230
+ with open(os.devnull, 'w') as stdout:
1231
+ subprocess.check_call(
1232
+ ['unzip', '-q', '-o', target_zip, '-d', target_fuzzer_dir],
1233
+ stdout=stdout)
1234
+ except OSError:
1235
+ logger.error('Failed to unzip corpus')
1236
+
1237
+ # Remove the downloaded zip
1238
+ os.remove(target_zip)
1239
+ return True
1240
+
1241
+
1242
+ def download_corpora(args):
1243
+ """Downloads most recent corpora from GCS for the given project."""
1244
+ if not check_project_exists(args.project):
1245
+ return False
1246
+
1247
+ if args.public:
1248
+ logger.info("Downloading public corpus")
1249
+ try:
1250
+ with open(os.devnull, 'w') as stdout:
1251
+ subprocess.check_call(['wget', '--version'], stdout=stdout)
1252
+ except OSError:
1253
+ logger.error('wget not found')
1254
+ return False
1255
+ else:
1256
+ try:
1257
+ with open(os.devnull, 'w') as stdout:
1258
+ subprocess.check_call(['gsutil', '--version'], stdout=stdout)
1259
+ except OSError:
1260
+ logger.error('gsutil not found. Please install it from '
1261
+ 'https://cloud.google.com/storage/docs/gsutil_install')
1262
+ return False
1263
+
1264
+ if args.fuzz_target:
1265
+ fuzz_targets = args.fuzz_target
1266
+ else:
1267
+ fuzz_targets = _get_fuzz_targets(args.project)
1268
+
1269
+ if not fuzz_targets:
1270
+ logger.error(
1271
+ 'Fuzz targets not found. Please build project first '
1272
+ '(python3 infra/helper.py build_fuzzers %s) so that download_corpora '
1273
+ 'can automatically identify targets.', args.project.name)
1274
+ return False
1275
+
1276
+ corpus_dir = args.project.corpus
1277
+
1278
+ def _download_for_single_target(fuzz_target):
1279
+ try:
1280
+ if args.public:
1281
+ _get_latest_public_corpus(args, fuzz_target)
1282
+ else:
1283
+ _get_latest_corpus(args.project, fuzz_target, corpus_dir)
1284
+ return True
1285
+ except Exception as error: # pylint:disable=broad-except
1286
+ logger.error('Corpus download for %s failed: %s.', fuzz_target,
1287
+ str(error))
1288
+ return False
1289
+
1290
+ logger.info('Downloading corpora for %s project to %s.', args.project.name,
1291
+ corpus_dir)
1292
+ thread_pool = ThreadPool()
1293
+ return all(thread_pool.map(_download_for_single_target, fuzz_targets))
1294
+
1295
+
1296
+ def coverage(args): # pylint: disable=too-many-branches
1297
+ """Generates code coverage using clang source based code coverage."""
1298
+ if args.corpus_dir and not args.fuzz_target:
1299
+ logger.error(
1300
+ '--corpus-dir requires specifying a particular fuzz target using '
1301
+ '--fuzz-target')
1302
+ return False
1303
+
1304
+ if not check_project_exists(args.project):
1305
+ return False
1306
+
1307
+ if args.project.language not in constants.LANGUAGES_WITH_COVERAGE_SUPPORT:
1308
+ logger.error(
1309
+ 'Project is written in %s, coverage for it is not supported yet.',
1310
+ args.project.language)
1311
+ return False
1312
+
1313
+ if (not args.no_corpus_download and not args.corpus_dir and
1314
+ not args.project.is_external):
1315
+ if not download_corpora(args):
1316
+ return False
1317
+
1318
+ extra_cov_args = (
1319
+ f'{args.project.coverage_extra_args.strip()} {" ".join(args.extra_args)}')
1320
+ env = [
1321
+ 'FUZZING_ENGINE=libfuzzer',
1322
+ 'HELPER=True',
1323
+ 'FUZZING_LANGUAGE=%s' % args.project.language,
1324
+ 'PROJECT=%s' % args.project.name,
1325
+ 'SANITIZER=coverage',
1326
+ 'COVERAGE_EXTRA_ARGS=%s' % extra_cov_args,
1327
+ 'ARCHITECTURE=' + args.architecture,
1328
+ ]
1329
+
1330
+ if not args.no_serve:
1331
+ env.append(f'HTTP_PORT={args.port}')
1332
+
1333
+ run_args = _env_to_docker_args(env)
1334
+
1335
+ if args.port:
1336
+ run_args.extend([
1337
+ '-p',
1338
+ '%s:%s' % (args.port, args.port),
1339
+ ])
1340
+
1341
+ if args.corpus_dir:
1342
+ if not os.path.exists(args.corpus_dir):
1343
+ logger.error('The path provided in --corpus-dir argument does not '
1344
+ 'exist.')
1345
+ return False
1346
+ corpus_dir = os.path.realpath(args.corpus_dir)
1347
+ run_args.extend(['-v', '%s:/corpus/%s' % (corpus_dir, args.fuzz_target)])
1348
+ else:
1349
+ run_args.extend(['-v', '%s:/corpus' % args.project.corpus])
1350
+
1351
+ run_args.extend([
1352
+ '-v',
1353
+ '%s:/out' % args.project.out,
1354
+ '-t',
1355
+ BASE_RUNNER_IMAGE,
1356
+ ])
1357
+
1358
+ run_args.append('coverage')
1359
+ if args.fuzz_target:
1360
+ run_args.append(args.fuzz_target)
1361
+
1362
+ result = docker_run(run_args, architecture=args.architecture)
1363
+ if result:
1364
+ logger.info('Successfully generated clang code coverage report.')
1365
+ else:
1366
+ logger.error('Failed to generate clang code coverage report.')
1367
+
1368
+ return result
1369
+
1370
+
1371
+ def _introspector_prepare_corpus(args):
1372
+ """Helper function for introspector runs to generate corpora."""
1373
+ parser = get_parser()
1374
+ # Generate corpus, either by downloading or running fuzzers.
1375
+ if args.private_corpora or args.public_corpora:
1376
+ corpora_command = ['download_corpora']
1377
+ if args.public_corpora:
1378
+ corpora_command.append('--public')
1379
+ corpora_command.append(args.project.name)
1380
+ if not download_corpora(parse_args(parser, corpora_command)):
1381
+ logger.error('Failed to download corpora')
1382
+ return False
1383
+ else:
1384
+ fuzzer_targets = _get_fuzz_targets(args.project)
1385
+ for fuzzer_name in fuzzer_targets:
1386
+ # Make a corpus directory.
1387
+ fuzzer_corpus_dir = args.project.corpus + f'/{fuzzer_name}'
1388
+ if not os.path.isdir(fuzzer_corpus_dir):
1389
+ os.makedirs(fuzzer_corpus_dir)
1390
+ run_fuzzer_command = [
1391
+ 'run_fuzzer', '--sanitizer', 'address', '--corpus-dir',
1392
+ fuzzer_corpus_dir, args.project.name, fuzzer_name
1393
+ ]
1394
+
1395
+ parsed_args = parse_args(parser, run_fuzzer_command)
1396
+ parsed_args.fuzzer_args = [
1397
+ f'-max_total_time={args.seconds}', '-detect_leaks=0'
1398
+ ]
1399
+ # Continue even if run command fails, because we do not have 100%
1400
+ # accuracy in fuzz target detection, i.e. we might try to run something
1401
+ # that is not a target.
1402
+ run_fuzzer(parsed_args)
1403
+ return True
1404
+
1405
+
1406
+ def introspector(args):
1407
+ """Runs a complete end-to-end run of introspector."""
1408
+ parser = get_parser()
1409
+
1410
+ args_to_append = []
1411
+ if args.source_path:
1412
+ args_to_append.append(_get_absolute_path(args.source_path))
1413
+
1414
+ # Build fuzzers with ASAN.
1415
+ build_fuzzers_command = [
1416
+ 'build_fuzzers', '--sanitizer=address', args.project.name
1417
+ ] + args_to_append
1418
+ if not build_fuzzers(parse_args(parser, build_fuzzers_command)):
1419
+ logger.error('Failed to build project with ASAN')
1420
+ return False
1421
+
1422
+ if not _introspector_prepare_corpus(args):
1423
+ return False
1424
+
1425
+ # Build code coverage.
1426
+ build_fuzzers_command = [
1427
+ 'build_fuzzers', '--sanitizer=coverage', args.project.name
1428
+ ] + args_to_append
1429
+ if not build_fuzzers(parse_args(parser, build_fuzzers_command)):
1430
+ logger.error('Failed to build project with coverage instrumentation')
1431
+ return False
1432
+
1433
+ # Collect coverage.
1434
+ coverage_command = [
1435
+ 'coverage', '--no-corpus-download', '--port', '', args.project.name
1436
+ ]
1437
+ if not coverage(parse_args(parser, coverage_command)):
1438
+ logger.error('Failed to extract coverage')
1439
+ return False
1440
+
1441
+ # Build introspector.
1442
+ build_fuzzers_command = [
1443
+ 'build_fuzzers', '--sanitizer=introspector', args.project.name
1444
+ ] + args_to_append
1445
+ if not build_fuzzers(parse_args(parser, build_fuzzers_command)):
1446
+ logger.error('Failed to build project with introspector')
1447
+ return False
1448
+
1449
+ introspector_dst = os.path.join(args.project.out,
1450
+ "introspector-report/inspector")
1451
+ shutil.rmtree(introspector_dst, ignore_errors=True)
1452
+ shutil.copytree(os.path.join(args.project.out, "inspector"), introspector_dst)
1453
+
1454
+ # Copy the coverage reports into the introspector report.
1455
+ dst_cov_report = os.path.join(introspector_dst, "covreport")
1456
+ shutil.copytree(os.path.join(args.project.out, "report"), dst_cov_report)
1457
+
1458
+ # Copy per-target coverage reports
1459
+ src_target_cov_report = os.path.join(args.project.out, "report_target")
1460
+ for target_cov_dir in os.listdir(src_target_cov_report):
1461
+ dst_target_cov_report = os.path.join(dst_cov_report, target_cov_dir)
1462
+ shutil.copytree(os.path.join(src_target_cov_report, target_cov_dir),
1463
+ dst_target_cov_report)
1464
+
1465
+ logger.info('Introspector run complete. Report in %s', introspector_dst)
1466
+ logger.info(
1467
+ 'To browse the report, run: `python3 -m http.server 8008 --directory %s`'
1468
+ 'and navigate to localhost:8008/fuzz_report.html in your browser',
1469
+ introspector_dst)
1470
+ return True
1471
+
1472
+
1473
+ def run_fuzzer(args):
1474
+ """Runs a fuzzer in the container."""
1475
+ if not check_project_exists(args.project):
1476
+ return False
1477
+
1478
+ if not _check_fuzzer_exists(args.project, args.fuzzer_name,
1479
+ args.architecture):
1480
+ return False
1481
+
1482
+ env = [
1483
+ 'FUZZING_ENGINE=' + args.engine,
1484
+ 'SANITIZER=' + args.sanitizer,
1485
+ 'RUN_FUZZER_MODE=interactive',
1486
+ 'HELPER=True',
1487
+ ]
1488
+
1489
+ if args.e:
1490
+ env += args.e
1491
+
1492
+ run_args = _env_to_docker_args(env)
1493
+
1494
+ if args.corpus_dir:
1495
+ if not os.path.exists(args.corpus_dir):
1496
+ logger.error('The path provided in --corpus-dir argument does not exist')
1497
+ return False
1498
+ corpus_dir = os.path.realpath(args.corpus_dir)
1499
+ run_args.extend([
1500
+ '-v',
1501
+ '{corpus_dir}:/tmp/{fuzzer}_corpus'.format(corpus_dir=corpus_dir,
1502
+ fuzzer=args.fuzzer_name)
1503
+ ])
1504
+
1505
+ run_args.extend([
1506
+ '-v',
1507
+ '%s:/out' % args.project.out,
1508
+ '-t',
1509
+ BASE_RUNNER_IMAGE,
1510
+ 'run_fuzzer',
1511
+ args.fuzzer_name,
1512
+ ] + args.fuzzer_args)
1513
+
1514
+ return docker_run(run_args, architecture=args.architecture)
1515
+
1516
+
1517
+ def fuzzbench_run_fuzzer(args):
1518
+ """Runs a fuzz target built by fuzzbench in the container."""
1519
+ if not check_project_exists(args.project):
1520
+ return False
1521
+
1522
+ env = [
1523
+ 'FUZZING_ENGINE=' + args.engine,
1524
+ 'SANITIZER=' + args.sanitizer,
1525
+ 'RUN_FUZZER_MODE=interactive',
1526
+ 'HELPER=True',
1527
+ f'FUZZ_TARGET={args.fuzzer_name}',
1528
+ f'BENCHMARK={args.project.name}',
1529
+ 'TRIAL_ID=1',
1530
+ 'EXPERIMENT_TYPE=bug',
1531
+ ]
1532
+
1533
+ if args.e:
1534
+ env += args.e
1535
+
1536
+ run_args = _env_to_docker_args(env)
1537
+
1538
+ if args.corpus_dir:
1539
+ if not os.path.exists(args.corpus_dir):
1540
+ logger.error('The path provided in --corpus-dir argument does not exist')
1541
+ return False
1542
+ corpus_dir = os.path.realpath(args.corpus_dir)
1543
+ run_args.extend([
1544
+ '-v',
1545
+ '{corpus_dir}:/tmp/{fuzzer}_corpus'.format(corpus_dir=corpus_dir,
1546
+ fuzzer=args.fuzzer_name)
1547
+ ])
1548
+
1549
+ with tempfile.TemporaryDirectory() as tmp_dir:
1550
+ tmp_dir = os.path.abspath(tmp_dir)
1551
+ fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench')
1552
+ subprocess.run([
1553
+ 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1',
1554
+ fuzzbench_path
1555
+ ],
1556
+ check=True)
1557
+ run_args.extend([
1558
+ '-v',
1559
+ f'{args.project.out}:/out',
1560
+ '-v',
1561
+ f'{fuzzbench_path}:{fuzzbench_path}',
1562
+ '-e',
1563
+ f'FUZZBENCH_PATH={fuzzbench_path}',
1564
+ f'aixcc-afc/{args.project.name}',
1565
+ 'fuzzbench_run_fuzzer',
1566
+ args.fuzzer_name,
1567
+ ] + args.fuzzer_args)
1568
+
1569
+ return docker_run(run_args, architecture=args.architecture)
1570
+
1571
+
1572
+ def fuzzbench_measure(args):
1573
+ """Measure results from fuzzing with fuzzbench."""
1574
+ if not check_project_exists(args.project):
1575
+ return False
1576
+
1577
+ with tempfile.TemporaryDirectory() as tmp_dir:
1578
+ tmp_dir = os.path.abspath(tmp_dir)
1579
+ fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench')
1580
+ subprocess.run([
1581
+ 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1',
1582
+ fuzzbench_path
1583
+ ],
1584
+ check=True)
1585
+ run_args = [
1586
+ '-v', f'{args.project.out}:/out', '-v',
1587
+ f'{fuzzbench_path}:{fuzzbench_path}', '-e',
1588
+ f'FUZZBENCH_PATH={fuzzbench_path}', '-e', 'EXPERIMENT_TYPE=bug', '-e',
1589
+ f'FUZZ_TARGET={args.fuzz_target_name}', '-e',
1590
+ f'FUZZER={args.engine_name}', '-e', f'BENCHMARK={args.project.name}',
1591
+ f'aixcc-afc/{args.project.name}', 'fuzzbench_measure'
1592
+ ]
1593
+
1594
+ return docker_run(run_args, 'x86_64')
1595
+
1596
+
1597
+ def reproduce(args):
1598
+ """Reproduces a specific test case from a specific project."""
1599
+ return reproduce_impl(args.project, args.fuzzer_name, args.valgrind, args.e,
1600
+ args.fuzzer_args, args.testcase_path, args.architecture,
1601
+ args.propagate_exit_codes, args.err_result,
1602
+ privileged=args.privileged, timeout=args.timeout)
1603
+
1604
+
1605
+ def reproduce_impl( # pylint: disable=too-many-arguments
1606
+ project,
1607
+ fuzzer_name,
1608
+ valgrind,
1609
+ env_to_add,
1610
+ fuzzer_args,
1611
+ testcase_path,
1612
+ architecture='x86_64',
1613
+ propagate_exit_codes=False,
1614
+ err_result=1,
1615
+ run_function=docker_run,
1616
+ privileged=True,
1617
+ timeout=None):
1618
+ """Reproduces a testcase in the container."""
1619
+
1620
+ if not check_project_exists(project):
1621
+ return err_result if propagate_exit_codes else False
1622
+
1623
+ if not _check_fuzzer_exists(project, fuzzer_name, architecture):
1624
+ return err_result if propagate_exit_codes else False
1625
+
1626
+ debugger = ''
1627
+ env = ['HELPER=True', 'ARCHITECTURE=' + architecture]
1628
+ image_name = 'base-runner'
1629
+
1630
+ if valgrind:
1631
+ debugger = 'valgrind --tool=memcheck --track-origins=yes --leak-check=full'
1632
+
1633
+ if debugger:
1634
+ image_name = 'base-runner-debug'
1635
+ env += ['DEBUGGER=' + debugger]
1636
+
1637
+ if env_to_add:
1638
+ env += env_to_add
1639
+
1640
+ run_args = _env_to_docker_args(env) + [
1641
+ '-v',
1642
+ '%s:/out' % project.out,
1643
+ '-v',
1644
+ '%s:/testcase' % _get_absolute_path(testcase_path),
1645
+ '-t',
1646
+ 'ghcr.io/aixcc-finals/%s%s' % (image_name, BASE_IMAGE_TAG),
1647
+ 'reproduce',
1648
+ fuzzer_name,
1649
+ '-runs=100',
1650
+ ] + fuzzer_args
1651
+
1652
+ return run_function(run_args, architecture=architecture, propagate_exit_codes=propagate_exit_codes, privileged=privileged, timeout=timeout)
1653
+
1654
+
1655
+ def _validate_project_name(project_name):
1656
+ """Validates |project_name| is a valid OSS-Fuzz project name."""
1657
+ if len(project_name) > MAX_PROJECT_NAME_LENGTH:
1658
+ logger.error(
1659
+ 'Project name needs to be less than or equal to %d characters.',
1660
+ MAX_PROJECT_NAME_LENGTH)
1661
+ return False
1662
+
1663
+ if not VALID_PROJECT_NAME_REGEX.match(project_name):
1664
+ logger.info('Invalid project name: %s.', project_name)
1665
+ return False
1666
+
1667
+ return True
1668
+
1669
+
1670
+ def _validate_language(language):
1671
+ if not LANGUAGE_REGEX.match(language):
1672
+ logger.error('Invalid project language %s.', language)
1673
+ return False
1674
+
1675
+ return True
1676
+
1677
+
1678
+ def _create_build_integration_directory(directory):
1679
+ """Returns True on successful creation of a build integration directory.
1680
+ Suitable for OSS-Fuzz and external projects."""
1681
+ try:
1682
+ os.makedirs(directory)
1683
+ except OSError as error:
1684
+ if error.errno != errno.EEXIST:
1685
+ raise
1686
+ logger.error('%s already exists.', directory)
1687
+ return False
1688
+ return True
1689
+
1690
+
1691
+ def _template_project_file(filename, template, template_args, directory):
1692
+ """Templates |template| using |template_args| and writes the result to
1693
+ |directory|/|filename|. Sets the file to executable if |filename| is
1694
+ build.sh."""
1695
+ file_path = os.path.join(directory, filename)
1696
+ with open(file_path, 'w') as file_handle:
1697
+ file_handle.write(template % template_args)
1698
+
1699
+ if filename == 'build.sh':
1700
+ os.chmod(file_path, 0o755)
1701
+
1702
+
1703
+ def generate(args):
1704
+ """Generates empty project files."""
1705
+ return _generate_impl(args.project, args.language)
1706
+
1707
+
1708
+ def _get_current_datetime():
1709
+ """Returns this year. Needed for mocking."""
1710
+ return datetime.datetime.now()
1711
+
1712
+
1713
+ def _base_builder_from_language(language):
1714
+ """Returns the base builder for the specified language."""
1715
+ return LANGUAGE_TO_BASE_BUILDER_IMAGE[language]
1716
+
1717
+
1718
+ def _generate_impl(project, language):
1719
+ """Implementation of generate(). Useful for testing."""
1720
+ if project.is_external:
1721
+ # External project.
1722
+ project_templates = templates.EXTERNAL_TEMPLATES
1723
+ else:
1724
+ # Internal project.
1725
+ if not _validate_project_name(project.name):
1726
+ return False
1727
+ project_templates = templates.TEMPLATES
1728
+
1729
+ if not _validate_language(language):
1730
+ return False
1731
+
1732
+ directory = project.build_integration_path
1733
+ if not _create_build_integration_directory(directory):
1734
+ return False
1735
+
1736
+ logger.info('Writing new files to: %s.', directory)
1737
+
1738
+ template_args = {
1739
+ 'project_name': project.name,
1740
+ 'base_builder': _base_builder_from_language(language),
1741
+ 'language': language,
1742
+ 'year': _get_current_datetime().year
1743
+ }
1744
+ for filename, template in project_templates.items():
1745
+ _template_project_file(filename, template, template_args, directory)
1746
+ return True
1747
+
1748
+
1749
+ def shell(args):
1750
+ """Runs a shell within a docker image."""
1751
+ if not build_image_impl(args.project):
1752
+ return False
1753
+
1754
+ env = [
1755
+ 'FUZZING_ENGINE=' + args.engine,
1756
+ 'SANITIZER=' + args.sanitizer,
1757
+ 'ARCHITECTURE=' + args.architecture,
1758
+ 'HELPER=True',
1759
+ ]
1760
+
1761
+ if args.project.name != 'base-runner-debug':
1762
+ env.append('FUZZING_LANGUAGE=' + args.project.language)
1763
+
1764
+ if args.e:
1765
+ env += args.e
1766
+
1767
+ if is_base_image(args.project.name):
1768
+ image_project = 'aixcc-finals'
1769
+ project_full = 'ghcr.io/%s/%s%s' % (image_project, args.project.name, BASE_IMAGE_TAG)
1770
+ out_dir = _get_out_dir()
1771
+ else:
1772
+ image_project = 'aixcc-afc'
1773
+ project_full = '%s/%s:%s' % (image_project, args.project.name, args.docker_image_tag)
1774
+ out_dir = args.project.out
1775
+
1776
+ run_args = _env_to_docker_args(env)
1777
+ if args.source_path:
1778
+ workdir = _workdir_from_dockerfile(args.project)
1779
+ run_args.extend([
1780
+ '-v',
1781
+ '%s:%s' % (_get_absolute_path(args.source_path), workdir),
1782
+ ])
1783
+
1784
+
1785
+ run_args.extend([
1786
+ '-v',
1787
+ '%s:/out' % out_dir, '-v',
1788
+ '%s:/work' % args.project.work, '-t',
1789
+ '%s' % (project_full), '/bin/bash'
1790
+ ])
1791
+
1792
+ docker_run(run_args, architecture=args.architecture)
1793
+ return True
1794
+
1795
+
1796
+ def pull_images(language=None):
1797
+ """Pulls base images used to build projects in language lang (or all if lang
1798
+ is None)."""
1799
+ for base_image_lang, base_images in BASE_IMAGES.items():
1800
+ if (language is None or base_image_lang == 'generic' or
1801
+ base_image_lang == language):
1802
+ for base_image in base_images:
1803
+ if not docker_pull(base_image):
1804
+ return False
1805
+
1806
+ return True
1807
+
1808
+
1809
+ if __name__ == '__main__':
1810
+ sys.exit(main())
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/manifest.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env 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
+ #
16
+ ################################################################################
17
+ """Script for pushing manifest files to docker that point to AMD64 and ARM
18
+ images."""
19
+ import logging
20
+ import subprocess
21
+ import sys
22
+
23
+
24
+ def push_manifest(image):
25
+ """Pushes a manifest file in place of |image| for ARM and AMD64 versions of
26
+ that image."""
27
+ subprocess.run(['docker', 'pull', image], check=True)
28
+ amd64_image = f'{image}:manifest-amd64'
29
+ subprocess.run(['docker', 'tag', image, amd64_image], check=True)
30
+ subprocess.run(['docker', 'push', amd64_image], check=True)
31
+
32
+ arm_version = f'{image}-testing-arm'
33
+ subprocess.run(['docker', 'pull', arm_version], check=True)
34
+ arm64_image = f'{image}:manifest-arm64v8'
35
+ subprocess.run(['docker', 'tag', arm_version, arm64_image], check=True)
36
+
37
+ subprocess.run([
38
+ 'docker', 'manifest', 'create', image, '--amend', arm64_image, '--amend',
39
+ amd64_image
40
+ ],
41
+ check=True)
42
+ subprocess.run(['docker', 'manifest', 'push', image], check=True)
43
+ return True
44
+
45
+
46
+ def main():
47
+ """Sets up manifests for base-builder and base-runner so they can be used for
48
+ ARM builds."""
49
+ logging.info('Doing simple gcloud command to ensure 2FA passes. '
50
+ 'Otherwise docker push fails.')
51
+ subprocess.run(['gcloud', 'projects', 'list', '--limit=1'], check=True)
52
+
53
+ images = [
54
+ 'ghcr.io/aixcc-finals/base-builder', 'ghcr.io/aixcc-finals/base-runner'
55
+ ]
56
+ results = [push_manifest(image) for image in images]
57
+ return 0 if all(results) else 1
58
+
59
+
60
+ if __name__ == '__main__':
61
+ sys.exit(main())
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/pr_helper.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2023 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
+ """Adds comments for PR to provide more information for approvers."""
18
+ import base64
19
+ import json
20
+ import os
21
+ import subprocess
22
+
23
+ import requests
24
+ import yaml
25
+
26
+ OWNER = 'google'
27
+ REPO = 'oss-fuzz'
28
+ GITHUB_URL = 'https://github.com/'
29
+ GITHUB_NONREF_URL = f'https://www.github.com/{OWNER}/{REPO}' # Github URL that doesn't send emails on linked issues.
30
+ API_URL = 'https://api.github.com'
31
+ BASE_URL = f'{API_URL}/repos/{OWNER}/{REPO}'
32
+ BRANCH = 'master'
33
+ CRITICALITY_SCORE_PATH = '/home/runner/go/bin/criticality_score'
34
+ COMMITS_LIMIT = 50 # Only process the most recent 50 commits.
35
+
36
+
37
+ def get_criticality_score(repo_url):
38
+ """Gets the criticality score of the project."""
39
+ # Criticality score does not support repo url ends with '.git'
40
+ if repo_url.endswith('.git'):
41
+ repo_url = repo_url[:-4]
42
+ report = subprocess.run([
43
+ CRITICALITY_SCORE_PATH, '--format', 'json',
44
+ '-gcp-project-id=clusterfuzz-external', '-depsdev-disable', repo_url
45
+ ],
46
+ capture_output=True,
47
+ text=True)
48
+
49
+ try:
50
+ report_dict = json.loads(report.stdout)
51
+ except:
52
+ print(f'Criticality score failed with stdout: {report.stdout}')
53
+ print(f'Criticality score failed with stderr: {report.stderr}')
54
+ return 'N/A'
55
+ return report_dict.get('default_score', 'N/A')
56
+
57
+
58
+ def is_known_contributor(content, email):
59
+ """Checks if the author is in the contact list."""
60
+ return (email == content.get('primary_contact') or
61
+ email in content.get('vendor_ccs', []) or
62
+ email in content.get('auto_ccs', []))
63
+
64
+
65
+ def save_env(message, is_ready_for_merge, is_internal=False):
66
+ """Saves the outputs as environment variables."""
67
+ with open(os.environ['GITHUB_ENV'], 'a') as github_env:
68
+ github_env.write(f'MESSAGE={message}\n')
69
+ github_env.write(f'IS_READY_FOR_MERGE={is_ready_for_merge}\n')
70
+ github_env.write(f'IS_INTERNAL={is_internal}')
71
+
72
+
73
+ def main():
74
+ """Verifies if a PR is ready to merge."""
75
+ github = GithubHandler()
76
+
77
+ # Bypasses PRs of the internal members.
78
+ if github.is_author_internal_member():
79
+ save_env(None, None, True)
80
+ return
81
+
82
+ message = ''
83
+ is_ready_for_merge = True
84
+ pr_author = github.get_pr_author()
85
+ # Gets all modified projects path.
86
+ projects_path = github.get_projects_path()
87
+ verified, email = github.get_author_email()
88
+
89
+ for project_path in projects_path:
90
+ project_url = f'{GITHUB_URL}/{OWNER}/{REPO}/tree/{BRANCH}/{project_path}'
91
+ content_dict = github.get_project_yaml(project_path)
92
+
93
+ # Gets information for the new integrating project.
94
+ if not content_dict:
95
+ is_ready_for_merge = False
96
+ new_project = github.get_integrated_project_info()
97
+ repo_url = new_project.get('main_repo')
98
+ if repo_url is None:
99
+ message += (f'{pr_author} is integrating a new project, '
100
+ 'but the `main_repo` is missing. '
101
+ 'The criticality score cannot be computed.<br/>')
102
+ else:
103
+ message += (f'{pr_author} is integrating a new project:<br/>'
104
+ f'- Main repo: {repo_url}<br/> - Criticality score: '
105
+ f'{get_criticality_score(repo_url)}<br/>')
106
+ continue
107
+
108
+ # Checks if the author is in the contact list.
109
+ if email:
110
+ if is_known_contributor(content_dict, email):
111
+ # Checks if the email is verified.
112
+ verified_marker = ' (verified)' if verified else ''
113
+ message += (
114
+ f'{pr_author}{verified_marker} is either the primary contact or '
115
+ f'is in the CCs list of [{project_path}]({project_url}).<br/>')
116
+ if verified:
117
+ continue
118
+
119
+ # Checks the previous commits.
120
+ commit_sha = github.has_author_modified_project(project_path)
121
+ if commit_sha is None:
122
+ history_message = ''
123
+ contributors = github.get_past_contributors(project_path)
124
+ if contributors:
125
+ history_message = 'The past contributors are: '
126
+ history_message += ', '.join(contributors)
127
+ message += (
128
+ f'{pr_author} is a new contributor to '
129
+ f'[{project_path}]({project_url}). The PR must be approved by known '
130
+ f'contributors before it can be merged. {history_message}<br/>')
131
+ is_ready_for_merge = False
132
+ continue
133
+
134
+ # If the previous commit is not associated with a pull request.
135
+ pr_message = (f'{pr_author} has previously contributed to '
136
+ f'[{project_path}]({project_url}). The previous commit was '
137
+ f'{GITHUB_NONREF_URL}/commit/{commit_sha}<br/>')
138
+
139
+ previous_pr_number = github.get_pull_request_number(commit_sha)
140
+ if previous_pr_number is not None:
141
+ pr_message = (f'{pr_author} has previously contributed to '
142
+ f'[{project_path}]({project_url}). '
143
+ f'The previous PR was [#{previous_pr_number}]'
144
+ f'({GITHUB_NONREF_URL}/pull/{previous_pr_number})<br/>')
145
+ message += pr_message
146
+
147
+ save_env(message, is_ready_for_merge, False)
148
+
149
+
150
+ class GithubHandler:
151
+ """Github requests handler."""
152
+
153
+ def __init__(self):
154
+ self._pr_author = os.environ['PRAUTHOR']
155
+ self._token = os.environ['GITHUBTOKEN']
156
+ self._pr_number = os.environ['PRNUMBER']
157
+ self._headers = {
158
+ 'Authorization': f'Bearer {self._token}',
159
+ 'X-GitHub-Api-Version': '2022-11-28'
160
+ }
161
+ self._maintainers = set()
162
+ os.environ['GITHUB_AUTH_TOKEN'] = self._token
163
+
164
+ def get_pr_author(self):
165
+ """Gets the pr author user name."""
166
+ return self._pr_author
167
+
168
+ def get_projects_path(self):
169
+ """Gets the current project path."""
170
+ response = requests.get(f'{BASE_URL}/pulls/{self._pr_number}/files',
171
+ headers=self._headers)
172
+ if not response.ok:
173
+ return []
174
+
175
+ projects_path = set()
176
+ for file in response.json():
177
+ file_path = file['filename']
178
+ dir_path = file_path.split(os.sep)
179
+ if len(dir_path) > 1 and dir_path[0] == 'projects':
180
+ projects_path.add(os.sep.join(dir_path[0:2]))
181
+ return list(projects_path)
182
+
183
+ def get_author_email(self):
184
+ """Retrieves the author's email address for a pull request,
185
+ including non-public emails."""
186
+ user_response = requests.get(f'{API_URL}/users/{self._pr_author}')
187
+ if user_response.ok:
188
+ email = user_response.json()['email']
189
+ if email:
190
+ return True, email
191
+
192
+ commits_response = requests.get(
193
+ f'{BASE_URL}/pulls/{self._pr_number}/commits', headers=self._headers)
194
+ if not commits_response.ok:
195
+ return False, None
196
+ email = commits_response.json()[0]['commit']['author']['email']
197
+ verified = commits_response.json()[0]['commit']['verification']['verified']
198
+ return verified, email
199
+
200
+ def get_project_yaml(self, project_path):
201
+ """Gets the project yaml file."""
202
+ contents_url = f'{BASE_URL}/contents/{project_path}/project.yaml'
203
+ return self.get_yaml_file_content(contents_url)
204
+
205
+ def get_yaml_file_content(self, contents_url):
206
+ """Gets yaml file content."""
207
+ response = requests.get(contents_url, headers=self._headers)
208
+ if not response.ok:
209
+ return {}
210
+ content = base64.b64decode(response.json()['content']).decode('UTF-8')
211
+ return yaml.safe_load(content)
212
+
213
+ def get_integrated_project_info(self):
214
+ """Gets the new integrated project."""
215
+ response = requests.get(f'{BASE_URL}/pulls/{self._pr_number}/files',
216
+ headers=self._headers)
217
+
218
+ for file in response.json():
219
+ file_path = file['filename']
220
+ if 'project.yaml' in file_path:
221
+ return self.get_yaml_file_content(file['contents_url'])
222
+
223
+ return {}
224
+
225
+ def get_pull_request_number(self, commit):
226
+ """Gets the pull request number."""
227
+ pr_response = requests.get(f'{BASE_URL}/commits/{commit}/pulls',
228
+ headers=self._headers)
229
+ if not pr_response.ok:
230
+ return None
231
+ return pr_response.json()[0]['number']
232
+
233
+ def get_past_contributors(self, project_path):
234
+ """Returns a list of past contributors of a certain project."""
235
+ commits_response = requests.get(f'{BASE_URL}/commits?path={project_path}',
236
+ headers=self._headers)
237
+
238
+ if not commits_response.ok:
239
+ return []
240
+ commits = commits_response.json()
241
+ contributors: dict[str, bool] = {}
242
+ for i, commit in enumerate(commits):
243
+ if i >= COMMITS_LIMIT:
244
+ break
245
+
246
+ if not commit['author'] or not commit['commit']:
247
+ continue
248
+
249
+ login = commit['author']['login']
250
+ verified = commit['commit']['verification']['verified']
251
+ if login in self._maintainers:
252
+ continue
253
+ if login not in contributors:
254
+ contributors[login] = verified
255
+ if verified:
256
+ # Override previous verification bit.
257
+ contributors[login] = True
258
+
259
+ all_contributors = []
260
+ for login, verified in contributors.items():
261
+ login_verify = login if verified else f'{login} (unverified)'
262
+ all_contributors.append(login_verify)
263
+
264
+ return all_contributors
265
+
266
+ def get_maintainers(self):
267
+ """Get a list of internal members."""
268
+ if self._maintainers:
269
+ return self._maintainers
270
+
271
+ response = requests.get(f'{BASE_URL}/contents/infra/MAINTAINERS.csv',
272
+ headers=self._headers)
273
+ if not response.ok:
274
+ return self._maintainers
275
+
276
+ maintainers_file = base64.b64decode(
277
+ response.json()['content']).decode('UTF-8')
278
+ for line in maintainers_file.split(os.linesep):
279
+ self._maintainers.add(line.split(',')[2])
280
+ return self._maintainers
281
+
282
+ def is_author_internal_member(self):
283
+ """Returns if the author is an internal member."""
284
+ return self._pr_author in self.get_maintainers()
285
+
286
+ def has_author_modified_project(self, project_path):
287
+ """Checks if the author has modified this project before."""
288
+ commits_response = requests.get(
289
+ f'{BASE_URL}/commits?path={project_path}&author={self._pr_author}',
290
+ headers=self._headers)
291
+
292
+ if not commits_response.ok or not commits_response.json():
293
+ return None
294
+
295
+ commit = commits_response.json()[0]
296
+ return commit['sha']
297
+
298
+
299
+ if __name__ == '__main__':
300
+ main()
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/retry.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Retry decorator. Copied from ClusterFuzz source."""
15
+
16
+ import functools
17
+ import inspect
18
+ import logging
19
+ import sys
20
+ import time
21
+
22
+ # pylint: disable=too-many-arguments,broad-except
23
+
24
+
25
+ def sleep(seconds):
26
+ """Invoke time.sleep. This is to avoid the flakiness of time.sleep. See:
27
+ crbug.com/770375"""
28
+ time.sleep(seconds)
29
+
30
+
31
+ def get_delay(num_try, delay, backoff):
32
+ """Compute backoff delay."""
33
+ return delay * (backoff**(num_try - 1))
34
+
35
+
36
+ def wrap(retries,
37
+ delay,
38
+ backoff=2,
39
+ exception_type=Exception,
40
+ retry_on_false=False):
41
+ """Retry decorator for a function."""
42
+
43
+ assert delay > 0
44
+ assert backoff >= 1
45
+ assert retries >= 0
46
+
47
+ def decorator(func):
48
+ """Decorator for the given function."""
49
+ tries = retries + 1
50
+ is_generator = inspect.isgeneratorfunction(func)
51
+ function_with_type = func.__qualname__
52
+ if is_generator:
53
+ function_with_type += ' (generator)'
54
+
55
+ def handle_retry(num_try, exception=None):
56
+ """Handle retry."""
57
+ if (exception is None or
58
+ isinstance(exception, exception_type)) and num_try < tries:
59
+ logging.info('Retrying on %s failed with %s. Retrying again.',
60
+ function_with_type,
61
+ sys.exc_info()[1])
62
+ sleep(get_delay(num_try, delay, backoff))
63
+ return True
64
+
65
+ logging.error('Retrying on %s failed with %s. Raise.', function_with_type,
66
+ sys.exc_info()[1])
67
+ return False
68
+
69
+ @functools.wraps(func)
70
+ def _wrapper(*args, **kwargs):
71
+ """Regular function wrapper."""
72
+ for num_try in range(1, tries + 1):
73
+ try:
74
+ result = func(*args, **kwargs)
75
+ if retry_on_false and not result:
76
+ if not handle_retry(num_try):
77
+ return result
78
+
79
+ continue
80
+ return result
81
+ except Exception as error:
82
+ if not handle_retry(num_try, exception=error):
83
+ raise
84
+
85
+ @functools.wraps(func)
86
+ def _generator_wrapper(*args, **kwargs):
87
+ """Generator function wrapper."""
88
+ # This argument is not applicable for generator functions.
89
+ assert not retry_on_false
90
+ already_yielded_element_count = 0
91
+ for num_try in range(1, tries + 1):
92
+ try:
93
+ for index, result in enumerate(func(*args, **kwargs)):
94
+ if index >= already_yielded_element_count:
95
+ yield result
96
+ already_yielded_element_count += 1
97
+ break
98
+ except Exception as error:
99
+ if not handle_retry(num_try, exception=error):
100
+ raise
101
+
102
+ if is_generator:
103
+ return _generator_wrapper
104
+ return _wrapper
105
+
106
+ return decorator
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/run_fuzzers.Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #
15
+ ################################################################################
16
+ # Docker image for running fuzzers on CIFuzz (the run_fuzzers action on GitHub
17
+ # actions).
18
+
19
+ FROM ghcr.io/aixcc-finals/cifuzz-base
20
+
21
+ # Python file to execute when the docker container starts up.
22
+ # We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var,
23
+ # just expand to '/opt/oss-fuzz'.
24
+ ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/run_fuzzers_entrypoint.py"]
25
+
26
+ WORKDIR ${OSS_FUZZ_ROOT}/infra
27
+
28
+ # Copy infra source code.
29
+ ADD . ${OSS_FUZZ_ROOT}/infra
30
+
31
+ RUN python3 -m pip install -r ${OSS_FUZZ_ROOT}/infra/cifuzz/requirements.txt
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/templates.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc.
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
+ """Templates for OSS-Fuzz project files."""
17
+
18
+ PROJECT_YAML_TEMPLATE = """\
19
+ homepage: "<your_project_homepage>"
20
+ language: %(language)s
21
+ primary_contact: "<primary_contact_email>"
22
+ main_repo: "https://path/to/main/repo.git"
23
+ file_github_issue: true
24
+ """
25
+
26
+ DOCKER_TEMPLATE = """\
27
+ # Copyright %(year)d Google LLC
28
+ #
29
+ # Licensed under the Apache License, Version 2.0 (the "License");
30
+ # you may not use this file except in compliance with the License.
31
+ # You may obtain a copy of the License at
32
+ #
33
+ # http://www.apache.org/licenses/LICENSE-2.0
34
+ #
35
+ # Unless required by applicable law or agreed to in writing, software
36
+ # distributed under the License is distributed on an "AS IS" BASIS,
37
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
38
+ # See the License for the specific language governing permissions and
39
+ # limitations under the License.
40
+ #
41
+ ################################################################################
42
+
43
+ FROM ghcr.io/aixcc-finals/%(base_builder)s
44
+ RUN apt-get update && apt-get install -y make autoconf automake libtool
45
+ RUN git clone --depth 1 <git_url> %(project_name)s # or use other version control
46
+ WORKDIR %(project_name)s
47
+ COPY build.sh $SRC/
48
+ """
49
+
50
+ EXTERNAL_DOCKER_TEMPLATE = """\
51
+ FROM ghcr.io/aixcc-finals/%(base_builder)s:v1
52
+ RUN apt-get update && apt-get install -y make autoconf automake libtool
53
+ COPY . $SRC/%(project_name)s
54
+ WORKDIR %(project_name)s
55
+ COPY .clusterfuzzlite/build.sh $SRC/
56
+ """
57
+
58
+ BUILD_TEMPLATE = """\
59
+ #!/bin/bash -eu
60
+ # Copyright %(year)d Google LLC
61
+ #
62
+ # Licensed under the Apache License, Version 2.0 (the "License");
63
+ # you may not use this file except in compliance with the License.
64
+ # You may obtain a copy of the License at
65
+ #
66
+ # http://www.apache.org/licenses/LICENSE-2.0
67
+ #
68
+ # Unless required by applicable law or agreed to in writing, software
69
+ # distributed under the License is distributed on an "AS IS" BASIS,
70
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
71
+ # See the License for the specific language governing permissions and
72
+ # limitations under the License.
73
+ #
74
+ ################################################################################
75
+
76
+ # build project
77
+ # e.g.
78
+ # ./autogen.sh
79
+ # ./configure
80
+ # make -j$(nproc) all
81
+
82
+ # build fuzzers
83
+ # e.g.
84
+ # $CXX $CXXFLAGS -std=c++11 -Iinclude \\
85
+ # /path/to/name_of_fuzzer.cc -o $OUT/name_of_fuzzer \\
86
+ # $LIB_FUZZING_ENGINE /path/to/library.a
87
+ """
88
+
89
+ EXTERNAL_BUILD_TEMPLATE = """\
90
+ #!/bin/bash -eu
91
+
92
+ # build project
93
+ # e.g.
94
+ # ./autogen.sh
95
+ # ./configure
96
+ # make -j$(nproc) all
97
+
98
+ # build fuzzers
99
+ # e.g.
100
+ # $CXX $CXXFLAGS -std=c++11 -Iinclude \\
101
+ # /path/to/name_of_fuzzer.cc -o $OUT/name_of_fuzzer \\
102
+ # $LIB_FUZZING_ENGINE /path/to/library.a
103
+ """
104
+
105
+ EXTERNAL_PROJECT_YAML_TEMPLATE = """\
106
+ language: %(language)s
107
+ """
108
+
109
+ TEMPLATES = {
110
+ 'build.sh': BUILD_TEMPLATE,
111
+ 'Dockerfile': DOCKER_TEMPLATE,
112
+ 'project.yaml': PROJECT_YAML_TEMPLATE
113
+ }
114
+
115
+ EXTERNAL_TEMPLATES = {
116
+ 'build.sh': EXTERNAL_BUILD_TEMPLATE,
117
+ 'Dockerfile': EXTERNAL_DOCKER_TEMPLATE,
118
+ 'project.yaml': EXTERNAL_PROJECT_YAML_TEMPLATE
119
+ }
local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/test ADDED
@@ -0,0 +1 @@
 
 
1
+