Kitxuuu commited on
Commit
8223302
·
verified ·
1 Parent(s): d1dbf5b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/base-images/README.md +6 -0
  2. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/base-images/all.sh +28 -0
  3. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/ci/build.py +292 -0
  4. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/ci/build_test.py +124 -0
  5. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/ci/requirements.txt +9 -0
  6. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py +113 -0
  7. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build-images.sh +34 -0
  8. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py +60 -0
  9. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py +385 -0
  10. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/fuzz_target.py +408 -0
  11. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py +71 -0
  12. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/http_utils.py +118 -0
  13. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/sarif_utils.py +251 -0
  14. local-test-tika-full-01-vuln_1/fuzz-tooling/infra/tools/hold_back_images.py +128 -0
  15. local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspace.ts +80 -0
  16. local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdDispatcherGenerateClusterfuzzLite.ts +38 -0
  17. local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts +71 -0
  18. local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdEndToEndCoverage.ts +192 -0
  19. local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFI.ts +24 -0
  20. local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts +59 -0
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/base-images/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Building all infra images:
2
+
3
+ ```bash
4
+ # run from project root
5
+ infra/base-images/all.sh
6
+ ```
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/base-images/all.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eux
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
+
18
+ docker build --pull -t ghcr.io/aixcc-finals/base-image "$@" infra/base-images/base-image
19
+ docker build -t ghcr.io/aixcc-finals/base-clang "$@" infra/base-images/base-clang
20
+ docker build -t ghcr.io/aixcc-finals/base-builder "$@" infra/base-images/base-builder
21
+ docker build -t ghcr.io/aixcc-finals/base-builder-go "$@" infra/base-images/base-builder-go
22
+ docker build -t ghcr.io/aixcc-finals/base-builder-jvm "$@" infra/base-images/base-builder-jvm
23
+ docker build -t ghcr.io/aixcc-finals/base-builder-python "$@" infra/base-images/base-builder-python
24
+ docker build -t ghcr.io/aixcc-finals/base-builder-rust "$@" infra/base-images/base-builder-rust
25
+ docker build -t ghcr.io/aixcc-finals/base-builder-ruby "$@" infra/base-images/base-builder-ruby
26
+ docker build -t ghcr.io/aixcc-finals/base-builder-swift "$@" infra/base-images/base-builder-swift
27
+ docker build -t ghcr.io/aixcc-finals/base-runner "$@" infra/base-images/base-runner
28
+ docker build -t ghcr.io/aixcc-finals/base-runner-debug "$@" infra/base-images/base-runner-debug
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/ci/build.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2019 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
+ """Build modified projects."""
18
+
19
+ from __future__ import print_function
20
+
21
+ import enum
22
+ import os
23
+ import re
24
+ import sys
25
+ import subprocess
26
+ import yaml
27
+
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
30
+
31
+ import constants
32
+
33
+ CANARY_PROJECT = 'skcms'
34
+
35
+ DEFAULT_ARCHITECTURES = ['x86_64']
36
+ DEFAULT_ENGINES = ['afl', 'honggfuzz', 'libfuzzer', 'centipede']
37
+ DEFAULT_SANITIZERS = ['address', 'undefined']
38
+
39
+
40
+ def get_changed_files_output():
41
+ """Returns the output of a git command that discovers changed files."""
42
+ branch_commit_hash = subprocess.check_output(
43
+ ['git', 'merge-base', 'HEAD', 'origin/HEAD']).strip().decode()
44
+
45
+ return subprocess.check_output(
46
+ ['git', 'diff', '--name-only', branch_commit_hash + '..']).decode()
47
+
48
+
49
+ def get_modified_buildable_projects():
50
+ """Returns a list of all the projects modified in this commit that have a
51
+ build.sh file."""
52
+ git_output = get_changed_files_output()
53
+ projects_regex = '.*projects/(?P<name>.*)/.*\n'
54
+ modified_projects = set(re.findall(projects_regex, git_output))
55
+ projects_dir = os.path.join(get_oss_fuzz_root(), 'projects')
56
+ # Filter out projects without Dockerfile files since new projects and reverted
57
+ # projects frequently don't have them. In these cases we don't want Travis's
58
+ # builds to fail.
59
+ modified_buildable_projects = []
60
+ for project in modified_projects:
61
+ if not os.path.exists(os.path.join(projects_dir, project, 'Dockerfile')):
62
+ print('Project {0} does not have Dockerfile. skipping build.'.format(
63
+ project))
64
+ continue
65
+ modified_buildable_projects.append(project)
66
+ return modified_buildable_projects
67
+
68
+
69
+ def get_oss_fuzz_root():
70
+ """Get the absolute path of the root of the oss-fuzz checkout."""
71
+ script_path = os.path.realpath(__file__)
72
+ return os.path.abspath(
73
+ os.path.dirname(os.path.dirname(os.path.dirname(script_path))))
74
+
75
+
76
+ def execute_helper_command(helper_command):
77
+ """Execute |helper_command| using helper.py."""
78
+ root = get_oss_fuzz_root()
79
+ script_path = os.path.join(root, 'infra', 'helper.py')
80
+ command = ['python', script_path] + helper_command
81
+ print('Running command: %s' % ' '.join(command))
82
+ subprocess.check_call(command)
83
+
84
+
85
+ def build_fuzzers(project, engine, sanitizer, architecture):
86
+ """Execute helper.py's build_fuzzers command on |project|. Build the fuzzers
87
+ with |engine| and |sanitizer| for |architecture|."""
88
+ execute_helper_command([
89
+ 'build_fuzzers', project, '--engine', engine, '--sanitizer', sanitizer,
90
+ '--architecture', architecture
91
+ ])
92
+
93
+
94
+ def check_build(project, engine, sanitizer, architecture):
95
+ """Execute helper.py's check_build command on |project|, assuming it was most
96
+ recently built with |engine| and |sanitizer| for |architecture|."""
97
+ execute_helper_command([
98
+ 'check_build', project, '--engine', engine, '--sanitizer', sanitizer,
99
+ '--architecture', architecture
100
+ ])
101
+
102
+
103
+ def should_build_coverage(project_yaml):
104
+ """Returns True if a coverage build should be done based on project.yaml
105
+ contents."""
106
+ # Enable coverage builds on projects that use engines. Those that don't use
107
+ # engines shouldn't get coverage builds.
108
+ engines = project_yaml.get('fuzzing_engines', DEFAULT_ENGINES)
109
+ engineless = 'none' in engines
110
+ if engineless:
111
+ assert_message = ('Forbidden to specify multiple engines for '
112
+ '"fuzzing_engines" if "none" is specified.')
113
+ assert len(engines) == 1, assert_message
114
+ return False
115
+ if 'wycheproof' in engines:
116
+ return False
117
+
118
+ language = project_yaml.get('language')
119
+ if language not in constants.LANGUAGES_WITH_COVERAGE_SUPPORT:
120
+ print(('Project is written in "{language}", '
121
+ 'coverage is not supported yet.').format(language=language))
122
+ return False
123
+
124
+ return True
125
+
126
+
127
+ def flatten_options(option_list):
128
+ """Generator that flattens |option_list| (a list of sanitizers, architectures
129
+ or fuzzing engines) by returning each element in the list that isn't a
130
+ dictionary. For elements that are dictionaries, the sole key is returned."""
131
+ result = []
132
+ for option in option_list:
133
+ if isinstance(option, dict):
134
+ keys = list(option.keys())
135
+ assert len(keys) == 1
136
+ result.append(keys[0])
137
+ continue
138
+ result.append(option)
139
+ print(result)
140
+ return result
141
+
142
+
143
+ def should_build(project_yaml):
144
+ """Returns True on if the build specified is enabled in the project.yaml."""
145
+
146
+ if os.getenv('SANITIZER') == 'coverage':
147
+ # This assumes we only do coverage builds with libFuzzer on x86_64.
148
+ return should_build_coverage(project_yaml)
149
+
150
+ def is_enabled(env_var, yaml_name, defaults):
151
+ """Is the value of |env_var| enabled in |project_yaml| (in the |yaml_name|
152
+ section)? Uses |defaults| if |yaml_name| section is unspecified."""
153
+ return os.getenv(env_var) in flatten_options(
154
+ project_yaml.get(yaml_name, defaults))
155
+
156
+ return (is_enabled('ENGINE', 'fuzzing_engines', DEFAULT_ENGINES) and
157
+ is_enabled('SANITIZER', 'sanitizers', DEFAULT_SANITIZERS) and
158
+ is_enabled('ARCHITECTURE', 'architectures', DEFAULT_ARCHITECTURES))
159
+
160
+
161
+ def build_project(project):
162
+ """Do the build of |project| that is specified by the environment variables -
163
+ SANITIZER, ENGINE, and ARCHITECTURE."""
164
+ root = get_oss_fuzz_root()
165
+ project_yaml_path = os.path.join(root, 'projects', project, 'project.yaml')
166
+ with open(project_yaml_path) as file_handle:
167
+ project_yaml = yaml.safe_load(file_handle)
168
+
169
+ if project_yaml.get('disabled', False):
170
+ print('Project {0} is disabled, skipping build.'.format(project))
171
+ return
172
+
173
+ engine = os.getenv('ENGINE')
174
+ sanitizer = os.getenv('SANITIZER')
175
+ architecture = os.getenv('ARCHITECTURE')
176
+
177
+ if not should_build(project_yaml):
178
+ print(('Specified build: engine: {0}, sanitizer: {1}, architecture: {2} '
179
+ 'not enabled for this project: {3}. Skipping build.').format(
180
+ engine, sanitizer, architecture, project))
181
+
182
+ return
183
+
184
+ print('Building project', project)
185
+ build_fuzzers(project, engine, sanitizer, architecture)
186
+
187
+ run_tests = project_yaml.get('run_tests', True)
188
+ if engine != 'none' and sanitizer != 'coverage' and run_tests:
189
+ check_build(project, engine, sanitizer, architecture)
190
+
191
+
192
+ class BuildModifiedProjectsResult(enum.Enum):
193
+ """Enum containing the return values of build_modified_projects()."""
194
+ NONE_BUILT = 0
195
+ BUILD_SUCCESS = 1
196
+ BUILD_FAIL = 2
197
+
198
+
199
+ def build_modified_projects():
200
+ """Build modified projects. Returns BuildModifiedProjectsResult.NONE_BUILT if
201
+ no builds were attempted. Returns BuildModifiedProjectsResult.BUILD_SUCCESS if
202
+ all attempts succeed, otherwise returns
203
+ BuildModifiedProjectsResult.BUILD_FAIL."""
204
+ projects = get_modified_buildable_projects()
205
+ if not projects:
206
+ return BuildModifiedProjectsResult.NONE_BUILT
207
+
208
+ failed_projects = []
209
+ for project in projects:
210
+ try:
211
+ build_project(project)
212
+ except subprocess.CalledProcessError:
213
+ failed_projects.append(project)
214
+
215
+ if failed_projects:
216
+ print('Failed projects:', ' '.join(failed_projects))
217
+ return BuildModifiedProjectsResult.BUILD_FAIL
218
+
219
+ return BuildModifiedProjectsResult.BUILD_SUCCESS
220
+
221
+
222
+ def is_infra_changed():
223
+ """Returns True if the infra directory was changed."""
224
+ git_output = get_changed_files_output()
225
+ infra_code_regex = '.*infra/.*\n'
226
+ return re.search(infra_code_regex, git_output) is not None
227
+
228
+
229
+ def build_base_images():
230
+ """Builds base images."""
231
+ # TODO(jonathanmetzman): Investigate why caching fails so often and
232
+ # when we improve it, build base-clang as well. Also, move this function
233
+ # to a helper command when we can support base-clang.
234
+ execute_helper_command(['pull_images'])
235
+ images = [
236
+ 'base-image',
237
+ 'base-builder',
238
+ 'base-builder-go',
239
+ 'base-builder-javascript',
240
+ 'base-builder-jvm',
241
+ 'base-builder-python',
242
+ 'base-builder-rust',
243
+ 'base-builder-swift',
244
+ 'base-builder-ruby',
245
+ 'base-runner',
246
+ ]
247
+ for image in images:
248
+ try:
249
+ execute_helper_command(['build_image', image, '--no-pull', '--cache'])
250
+ except subprocess.CalledProcessError:
251
+ return 1
252
+
253
+ return 0
254
+
255
+
256
+ def build_canary_project():
257
+ """Builds a specific project when infra/ is changed to verify that infra/
258
+ changes don't break things. Returns False if build was attempted but
259
+ failed."""
260
+
261
+ try:
262
+ build_project('skcms')
263
+ except subprocess.CalledProcessError:
264
+ return False
265
+
266
+ return True
267
+
268
+
269
+ def main():
270
+ """Build modified projects or canary project."""
271
+ os.environ['OSS_FUZZ_CI'] = '1'
272
+ infra_changed = is_infra_changed()
273
+ if infra_changed:
274
+ print('Pulling and building base images first.')
275
+ if build_base_images():
276
+ return 1
277
+
278
+ result = build_modified_projects()
279
+ if result == BuildModifiedProjectsResult.BUILD_FAIL:
280
+ return 1
281
+
282
+ # It's unnecessary to build the canary if we've built any projects already.
283
+ no_projects_built = result == BuildModifiedProjectsResult.NONE_BUILT
284
+ should_build_canary = no_projects_built and infra_changed
285
+ if should_build_canary and not build_canary_project():
286
+ return 1
287
+
288
+ return 0
289
+
290
+
291
+ if __name__ == '__main__':
292
+ sys.exit(main())
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/ci/build_test.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Tests for build.py"""
17
+
18
+ import os
19
+ import sys
20
+ import unittest
21
+ from unittest import mock
22
+
23
+ # pylint: disable=wrong-import-position
24
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
25
+ sys.path.append(INFRA_DIR)
26
+
27
+ from ci import build
28
+
29
+
30
+ def patch_environ(testcase_obj):
31
+ """Patch environment."""
32
+ env = {}
33
+ patcher = mock.patch.dict(os.environ, env)
34
+ testcase_obj.addCleanup(patcher.stop)
35
+ patcher.start()
36
+
37
+
38
+ def _set_coverage_build():
39
+ """Set the right environment variables for a coverage build."""
40
+ os.environ['SANITIZER'] = 'coverage'
41
+ os.environ['ENGINE'] = 'libfuzzer'
42
+ os.environ['ARCHITECTURE'] = 'x86_64'
43
+
44
+
45
+ class TestShouldBuild(unittest.TestCase):
46
+ """Tests that should_build() works as intended."""
47
+
48
+ def setUp(self):
49
+ patch_environ(self)
50
+
51
+ def test_none_engine_coverage_build(self):
52
+ """Tests that should_build returns False for a coverage build of a
53
+ project that specifies 'none' for fuzzing_engines."""
54
+ _set_coverage_build()
55
+ project_yaml = {
56
+ 'language': 'c++',
57
+ 'fuzzing_engines': ['none'],
58
+ 'sanitizers': ['address']
59
+ }
60
+ self.assertFalse(build.should_build(project_yaml))
61
+
62
+ def test_unspecified_engines_coverage_build(self):
63
+ """Tests that should_build returns True for a coverage build of a
64
+ project that doesn't specify fuzzing_engines."""
65
+ _set_coverage_build()
66
+ project_yaml = {'language': 'c++'}
67
+ self.assertTrue(build.should_build(project_yaml))
68
+
69
+ def test_libfuzzer_coverage_build(self):
70
+ """Tests that should_build returns True for coverage build of a project
71
+ specifying 'libfuzzer' for fuzzing_engines."""
72
+ _set_coverage_build()
73
+ project_yaml = {
74
+ 'language': 'c++',
75
+ 'fuzzing_engines': ['libfuzzer'],
76
+ 'sanitizers': ['address']
77
+ }
78
+ self.assertTrue(build.should_build(project_yaml))
79
+
80
+ def test_go_coverage_build(self):
81
+ """Tests that should_build returns True for coverage build of a project
82
+ specifying 'libfuzzer' for fuzzing_engines."""
83
+ _set_coverage_build()
84
+ project_yaml = {'language': 'go'}
85
+ self.assertTrue(build.should_build(project_yaml))
86
+
87
+ def test_engine_project_none_build(self):
88
+ """Tests that should_build returns False for an engine: 'none' build when
89
+ the project doesn't specify engines."""
90
+ os.environ['SANITIZER'] = 'address'
91
+ os.environ['ENGINE'] = 'none'
92
+ os.environ['ARCHITECTURE'] = 'x86_64'
93
+ project_yaml = {
94
+ 'language': 'c++',
95
+ 'fuzzing_engines': ['libfuzzer'],
96
+ 'sanitizers': ['address']
97
+ }
98
+ self.assertFalse(build.should_build(project_yaml))
99
+
100
+ def test_centipede_none_build(self):
101
+ """Tests that should_build returns True for none sanitizer build of a
102
+ project specifying 'centipede' for fuzzing_engines."""
103
+ os.environ['SANITIZER'] = 'none'
104
+ os.environ['ENGINE'] = 'centipede'
105
+ os.environ['ARCHITECTURE'] = 'x86_64'
106
+ project_yaml = {
107
+ 'language': 'c++',
108
+ 'fuzzing_engines': ['centipede'],
109
+ 'sanitizers': ['none']
110
+ }
111
+ self.assertTrue(build.should_build(project_yaml))
112
+
113
+ def test_centipede_address_build(self):
114
+ """Tests that should_build returns True for address sanitizer build of a
115
+ project specifying 'centipede' for fuzzing_engines."""
116
+ os.environ['SANITIZER'] = 'address'
117
+ os.environ['ENGINE'] = 'centipede'
118
+ os.environ['ARCHITECTURE'] = 'x86_64'
119
+ project_yaml = {
120
+ 'language': 'c++',
121
+ 'fuzzing_engines': ['centipede'],
122
+ 'sanitizers': ['address']
123
+ }
124
+ self.assertTrue(build.should_build(project_yaml))
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/ci/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Requirements for submitting code changes to infra/ (needed by presubmit.py).
2
+ parameterized==0.7.4
3
+ pyfakefs==4.5.6
4
+ pylint==2.5.3
5
+ pytest==7.1.2
6
+ pytest-xdist==2.5.0
7
+ PyYAML==6.0
8
+ requests==2.31.0
9
+ yapf==0.32.0
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fuzz targets affected by the change-under-test
15
+ (CUT)."""
16
+ import logging
17
+ import os
18
+ import sys
19
+
20
+ # pylint: disable=wrong-import-position,import-error
21
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+ import utils
23
+
24
+
25
+ def remove_unaffected_fuzz_targets(clusterfuzz_deployment, out_dir,
26
+ files_changed, repo_path):
27
+ """Removes all non affected fuzz targets in the out directory.
28
+
29
+ Args:
30
+ clusterfuzz_deployment: The ClusterFuzz deployment object.
31
+ out_dir: The location of the fuzz target binaries.
32
+ files_changed: A list of files changed compared to HEAD.
33
+ repo_path: The location of the OSS-Fuzz repo in the docker image.
34
+
35
+ This function will not delete fuzz targets unless it knows that the fuzz
36
+ targets are unaffected. For example, this means that fuzz targets which don't
37
+ have coverage data on will not be deleted.
38
+ """
39
+ if not files_changed:
40
+ # Don't remove any fuzz targets if there is no difference from HEAD.
41
+ logging.info('No files changed compared to HEAD.')
42
+ return
43
+
44
+ logging.info('Files changed in PR: %s', files_changed)
45
+
46
+ fuzz_target_paths = utils.get_fuzz_targets(out_dir)
47
+ if not fuzz_target_paths:
48
+ # Nothing to remove.
49
+ logging.error('No fuzz targets found in out dir.')
50
+ return
51
+
52
+ coverage = clusterfuzz_deployment.get_coverage(repo_path)
53
+ if not coverage:
54
+ # Don't remove any fuzz targets unless we have data.
55
+ logging.error('Could not find latest coverage report.')
56
+ return
57
+
58
+ affected_fuzz_targets = get_affected_fuzz_targets(coverage, fuzz_target_paths,
59
+ files_changed)
60
+
61
+ if not affected_fuzz_targets:
62
+ logging.info('No affected fuzz targets detected, keeping all as fallback.')
63
+ return
64
+
65
+ logging.info('Using affected fuzz targets: %s.', affected_fuzz_targets)
66
+ unaffected_fuzz_targets = set(fuzz_target_paths) - affected_fuzz_targets
67
+ logging.info('Removing unaffected fuzz targets: %s.', unaffected_fuzz_targets)
68
+
69
+ # Remove all the targets that are not affected.
70
+ for fuzz_target_path in unaffected_fuzz_targets:
71
+ try:
72
+ os.remove(fuzz_target_path)
73
+ except OSError as error:
74
+ logging.error('%s occurred while removing file %s', error,
75
+ fuzz_target_path)
76
+
77
+
78
+ def is_fuzz_target_affected(coverage, fuzz_target_path, files_changed):
79
+ """Returns True if a fuzz target (|fuzz_target_path|) is affected by
80
+ |files_changed|."""
81
+ fuzz_target = os.path.basename(fuzz_target_path)
82
+ covered_files = coverage.get_files_covered_by_target(fuzz_target)
83
+ if not covered_files:
84
+ # Assume a fuzz target is affected if we can't get its coverage from
85
+ # OSS-Fuzz.
86
+ # TODO(metzman): Figure out what we should do if covered_files is [].
87
+ # Should we act as if we couldn't get the coverage?
88
+ logging.info('Could not get coverage for %s. Treating as affected.',
89
+ fuzz_target)
90
+ return True
91
+
92
+ covered_files = [
93
+ os.path.normpath(covered_file) for covered_file in covered_files
94
+ ]
95
+ logging.info('Fuzz target %s is affected by: %s', fuzz_target, covered_files)
96
+ for filename in files_changed:
97
+ if filename in covered_files:
98
+ logging.info('Fuzz target %s is affected by changed file: %s',
99
+ fuzz_target, filename)
100
+ return True
101
+
102
+ logging.info('Fuzz target %s is not affected.', fuzz_target)
103
+ return False
104
+
105
+
106
+ def get_affected_fuzz_targets(coverage, fuzz_target_paths, files_changed):
107
+ """Returns a list of paths of affected targets."""
108
+ affected_fuzz_targets = set()
109
+ for fuzz_target_path in fuzz_target_paths:
110
+ if is_fuzz_target_affected(coverage, fuzz_target_path, files_changed):
111
+ affected_fuzz_targets.add(fuzz_target_path)
112
+
113
+ return affected_fuzz_targets
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build-images.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /bin/bash -eux
2
+ # Copyright 2021 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
+ # Script for building the docker images for cifuzz.
17
+
18
+ CIFUZZ_DIR=$(dirname "$0")
19
+ CIFUZZ_DIR=$(realpath $CIFUZZ_DIR)
20
+ INFRA_DIR=$(realpath $CIFUZZ_DIR/..)
21
+ OSS_FUZZ_ROOT=$(realpath $INFRA_DIR/..)
22
+
23
+ # Build cifuzz-base.
24
+ docker build --tag ghcr.io/aixcc-finals/cifuzz-base --file $CIFUZZ_DIR/cifuzz-base/Dockerfile $OSS_FUZZ_ROOT
25
+
26
+ # Build run-fuzzers and build-fuzzers images.
27
+ docker build \
28
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers-test:v1 \
29
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 \
30
+ --file $INFRA_DIR/build_fuzzers.Dockerfile $INFRA_DIR
31
+ docker build \
32
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 \
33
+ --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers-test:v1 \
34
+ --file $INFRA_DIR/run_fuzzers.Dockerfile $INFRA_DIR
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Builds a specific OSS-Fuzz project's fuzzers for CI tools."""
15
+ import logging
16
+ import sys
17
+
18
+ import build_fuzzers
19
+ import logs
20
+ import config_utils
21
+
22
+ # pylint: disable=c-extension-no-member
23
+ # pylint gets confused because of the relative import of cifuzz.
24
+
25
+ logs.init()
26
+
27
+
28
+ def build_fuzzers_entrypoint():
29
+ """Builds OSS-Fuzz project's fuzzers for CI tools."""
30
+ config = config_utils.BuildFuzzersConfig()
31
+
32
+ if config.dry_run:
33
+ # Sets the default return code on error to success.
34
+ returncode = 0
35
+ else:
36
+ # The default return code when an error occurs.
37
+ returncode = 1
38
+
39
+ if not build_fuzzers.build_fuzzers(config):
40
+ logging.error('Error building fuzzers for (commit: %s, pr_ref: %s).',
41
+ config.git_sha, config.pr_ref)
42
+ return returncode
43
+
44
+ return 0
45
+
46
+
47
+ def main():
48
+ """Builds OSS-Fuzz project's fuzzers for CI tools.
49
+
50
+ Note: The resulting fuzz target binaries of this build are placed in
51
+ the directory: ${GITHUB_WORKSPACE}/out
52
+
53
+ Returns:
54
+ 0 on success or nonzero on failure.
55
+ """
56
+ return build_fuzzers_entrypoint()
57
+
58
+
59
+ if __name__ == '__main__':
60
+ sys.exit(main())
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 interacting with the ClusterFuzz deployment."""
15
+ import logging
16
+ import os
17
+ import sys
18
+ import urllib.error
19
+ import urllib.request
20
+
21
+ import config_utils
22
+ import continuous_integration
23
+ import filestore_utils
24
+ import http_utils
25
+ import get_coverage
26
+ import repo_manager
27
+
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
30
+ import utils
31
+
32
+
33
+ class BaseClusterFuzzDeployment:
34
+ """Base class for ClusterFuzz deployments."""
35
+
36
+ def __init__(self, config, workspace):
37
+ self.config = config
38
+ self.workspace = workspace
39
+ self.ci_system = continuous_integration.get_ci(config)
40
+
41
+ def download_latest_build(self):
42
+ """Downloads the latest build from ClusterFuzz.
43
+
44
+ Returns:
45
+ A path to where the OSS-Fuzz build was stored, or None if it wasn't.
46
+ """
47
+ raise NotImplementedError('Child class must implement method.')
48
+
49
+ def upload_build(self, commit):
50
+ """Uploads the build with the given commit sha to the filestore."""
51
+ raise NotImplementedError('Child class must implement method.')
52
+
53
+ def download_corpus(self, target_name, corpus_dir):
54
+ """Downloads the corpus for |target_name| from ClusterFuzz to |corpus_dir|.
55
+
56
+ Returns:
57
+ A path to where the OSS-Fuzz build was stored, or None if it wasn't.
58
+ """
59
+ raise NotImplementedError('Child class must implement method.')
60
+
61
+ def upload_crashes(self):
62
+ """Uploads crashes in |crashes_dir| to filestore."""
63
+ raise NotImplementedError('Child class must implement method.')
64
+
65
+ def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument
66
+ """Uploads the corpus for |target_name| to filestore."""
67
+ raise NotImplementedError('Child class must implement method.')
68
+
69
+ def upload_coverage(self):
70
+ """Uploads the coverage report to the filestore."""
71
+ raise NotImplementedError('Child class must implement method.')
72
+
73
+ def get_coverage(self, repo_path):
74
+ """Returns the project coverage object for the project."""
75
+ raise NotImplementedError('Child class must implement method.')
76
+
77
+
78
+ def _make_empty_dir_if_nonexistent(path):
79
+ """Makes an empty directory at |path| if it does not exist."""
80
+ os.makedirs(path, exist_ok=True)
81
+
82
+
83
+ class ClusterFuzzLite(BaseClusterFuzzDeployment):
84
+ """Class representing a deployment of ClusterFuzzLite."""
85
+
86
+ COVERAGE_NAME = 'latest'
87
+ LATEST_BUILD_WINDOW = 3
88
+
89
+ def __init__(self, config, workspace):
90
+ super().__init__(config, workspace)
91
+ self.filestore = filestore_utils.get_filestore(self.config)
92
+
93
+ def download_latest_build(self):
94
+ if os.path.exists(self.workspace.clusterfuzz_build):
95
+ # This path is necessary because download_latest_build can be called
96
+ # multiple times.That is the case because it is called only when we need
97
+ # to see if a bug is novel, i.e. until we want to check a bug is novel we
98
+ # don't want to waste time calling this, but therefore this method can be
99
+ # called if multiple bugs are found.
100
+ return self.workspace.clusterfuzz_build
101
+
102
+ repo_dir = self.ci_system.repo_dir
103
+ if not repo_dir:
104
+ raise RuntimeError('Repo checkout does not exist.')
105
+
106
+ _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build)
107
+ repo = repo_manager.RepoManager(repo_dir)
108
+
109
+ diff_base = self.ci_system.get_diff_base()
110
+ if not diff_base:
111
+ diff_base = 'HEAD^'
112
+
113
+ # Builds are stored by commit, so try the latest |LATEST_BUILD_WINDOW|
114
+ # commits before the current diff base.
115
+ # TODO(ochang): If API usage becomes an issue, this can be optimized by the
116
+ # filestore accepting a list of filenames to try.
117
+ try:
118
+ # TODO(metzman): Why do we default to 'origin', we should avoid going down
119
+ # this path entirely and not need to catch an exception.
120
+ commit_list = repo.get_commit_list(diff_base,
121
+ limit=self.LATEST_BUILD_WINDOW)
122
+ except ValueError as error:
123
+ logging.error('Can\'t get commit list: %s', error)
124
+ return None
125
+
126
+ for old_commit in commit_list:
127
+ logging.info('Trying to downloading previous build %s.', old_commit)
128
+ build_name = self._get_build_name(old_commit)
129
+ try:
130
+ if self.filestore.download_build(build_name,
131
+ self.workspace.clusterfuzz_build):
132
+ logging.info('Done downloading previous build.')
133
+ return self.workspace.clusterfuzz_build
134
+
135
+ logging.info('Build for %s does not exist.', old_commit)
136
+ except Exception as err: # pylint: disable=broad-except
137
+ logging.error('Could not download build for %s because of: %s',
138
+ old_commit, err)
139
+
140
+ return None
141
+
142
+ def download_corpus(self, target_name, corpus_dir):
143
+ _make_empty_dir_if_nonexistent(corpus_dir)
144
+ logging.info('Downloading corpus for %s to %s.', target_name, corpus_dir)
145
+ corpus_name = self._get_corpus_name(target_name)
146
+ try:
147
+ self.filestore.download_corpus(corpus_name, corpus_dir)
148
+ logging.info('Done downloading corpus. Contains %d elements.',
149
+ len(os.listdir(corpus_dir)))
150
+ except Exception as err: # pylint: disable=broad-except
151
+ logging.error('Failed to download corpus for target: %s. Error: %s',
152
+ target_name, str(err))
153
+ return corpus_dir
154
+
155
+ def _get_build_name(self, name):
156
+ return f'{self.config.sanitizer}-{name}'
157
+
158
+ def _get_corpus_name(self, target_name): # pylint: disable=no-self-use
159
+ """Returns the name of the corpus artifact."""
160
+ return target_name
161
+
162
+ def upload_corpus(self, target_name, corpus_dir, replace=False):
163
+ """Upload the corpus produced by |target_name|."""
164
+ logging.info('Uploading corpus in %s for %s.', corpus_dir, target_name)
165
+ name = self._get_corpus_name(target_name)
166
+ try:
167
+ self.filestore.upload_corpus(name, corpus_dir, replace=replace)
168
+ logging.info('Done uploading corpus.')
169
+ except Exception as err: # pylint: disable=broad-except
170
+ logging.error('Failed to upload corpus for target: %s. Error: %s.',
171
+ target_name, err)
172
+
173
+ def upload_build(self, commit):
174
+ """Upload the build produced by CIFuzz as the latest build."""
175
+ logging.info('Uploading latest build in %s.', self.workspace.out)
176
+ build_name = self._get_build_name(commit)
177
+ try:
178
+ result = self.filestore.upload_build(build_name, self.workspace.out)
179
+ logging.info('Done uploading latest build.')
180
+ return result
181
+ except Exception as err: # pylint: disable=broad-except
182
+ logging.error('Failed to upload latest build: %s. Error: %s',
183
+ self.workspace.out, err)
184
+
185
+ def upload_crashes(self):
186
+ """Uploads crashes."""
187
+ artifact_dirs = os.listdir(self.workspace.artifacts)
188
+ if not artifact_dirs:
189
+ logging.info('No crashes in %s. Not uploading.', self.workspace.artifacts)
190
+ return
191
+
192
+ for crash_target in artifact_dirs:
193
+ artifact_dir = os.path.join(self.workspace.artifacts, crash_target)
194
+ if not os.path.isdir(artifact_dir):
195
+ logging.warning('%s is not an expected artifact directory, skipping.',
196
+ crash_target)
197
+ continue
198
+
199
+ logging.info('Uploading crashes in %s.', artifact_dir)
200
+ try:
201
+ self.filestore.upload_crashes(crash_target, artifact_dir)
202
+ logging.info('Done uploading crashes.')
203
+ except Exception as err: # pylint: disable=broad-except
204
+ logging.error('Failed to upload crashes. Error: %s', err)
205
+
206
+ def upload_coverage(self):
207
+ """Uploads the coverage report to the filestore."""
208
+ self.filestore.upload_coverage(self.COVERAGE_NAME,
209
+ self.workspace.coverage_report)
210
+
211
+ def get_coverage(self, repo_path):
212
+ """Returns the project coverage object for the project."""
213
+ _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_coverage)
214
+ try:
215
+ if not self.filestore.download_coverage(
216
+ self.COVERAGE_NAME, self.workspace.clusterfuzz_coverage):
217
+ logging.error('Could not download coverage.')
218
+ return None
219
+ return get_coverage.FilesystemCoverage(
220
+ repo_path, self.workspace.clusterfuzz_coverage)
221
+ except Exception as err: # pylint: disable=broad-except
222
+ logging.error('Could not get coverage: %s.', err)
223
+ return None
224
+
225
+
226
+ class OSSFuzz(BaseClusterFuzzDeployment):
227
+ """The OSS-Fuzz ClusterFuzz deployment."""
228
+
229
+ # Location of clusterfuzz builds on GCS.
230
+ CLUSTERFUZZ_BUILDS = 'clusterfuzz-builds'
231
+
232
+ # Zip file name containing the corpus.
233
+ CORPUS_ZIP_NAME = 'public.zip'
234
+
235
+ def get_latest_build_name(self):
236
+ """Gets the name of the latest OSS-Fuzz build of a project.
237
+
238
+ Returns:
239
+ A string with the latest build version or None.
240
+ """
241
+ version_file = (
242
+ f'{self.config.oss_fuzz_project_name}-{self.config.sanitizer}'
243
+ '-latest.version')
244
+ version_url = utils.url_join(utils.GCS_BASE_URL, self.CLUSTERFUZZ_BUILDS,
245
+ self.config.oss_fuzz_project_name,
246
+ version_file)
247
+ try:
248
+ response = urllib.request.urlopen(version_url)
249
+ except urllib.error.HTTPError:
250
+ logging.error('Error getting latest build version for %s from: %s.',
251
+ self.config.oss_fuzz_project_name, version_url)
252
+ return None
253
+ return response.read().decode()
254
+
255
+ def download_latest_build(self):
256
+ """Downloads the latest OSS-Fuzz build from GCS.
257
+
258
+ Returns:
259
+ A path to where the OSS-Fuzz build was stored, or None if it wasn't.
260
+ """
261
+ if os.path.exists(self.workspace.clusterfuzz_build):
262
+ # This function can be called multiple times, don't download the build
263
+ # again.
264
+ return self.workspace.clusterfuzz_build
265
+
266
+ _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build)
267
+
268
+ latest_build_name = self.get_latest_build_name()
269
+ if not latest_build_name:
270
+ return None
271
+
272
+ logging.info('Downloading latest build.')
273
+ oss_fuzz_build_url = utils.url_join(utils.GCS_BASE_URL,
274
+ self.CLUSTERFUZZ_BUILDS,
275
+ self.config.oss_fuzz_project_name,
276
+ latest_build_name)
277
+ if http_utils.download_and_unpack_zip(oss_fuzz_build_url,
278
+ self.workspace.clusterfuzz_build):
279
+ logging.info('Done downloading latest build.')
280
+ return self.workspace.clusterfuzz_build
281
+
282
+ return None
283
+
284
+ def upload_build(self, commit): # pylint: disable=no-self-use
285
+ """Noop Implementation of upload_build."""
286
+ logging.info('Not uploading latest build because on OSS-Fuzz.')
287
+
288
+ def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument
289
+ """Noop Implementation of upload_corpus."""
290
+ logging.info('Not uploading corpus because on OSS-Fuzz.')
291
+
292
+ def upload_crashes(self): # pylint: disable=no-self-use
293
+ """Noop Implementation of upload_crashes."""
294
+ logging.info('Not uploading crashes because on OSS-Fuzz.')
295
+
296
+ def download_corpus(self, target_name, corpus_dir):
297
+ """Downloads the latest OSS-Fuzz corpus for the target.
298
+
299
+ Returns:
300
+ The local path to to corpus or None if download failed.
301
+ """
302
+ _make_empty_dir_if_nonexistent(corpus_dir)
303
+ project_qualified_fuzz_target_name = target_name
304
+ qualified_name_prefix = self.config.oss_fuzz_project_name + '_'
305
+ if not target_name.startswith(qualified_name_prefix):
306
+ project_qualified_fuzz_target_name = qualified_name_prefix + target_name
307
+
308
+ corpus_url = (f'{utils.GCS_BASE_URL}{self.config.oss_fuzz_project_name}'
309
+ '-backup.clusterfuzz-external.appspot.com/corpus/'
310
+ f'libFuzzer/{project_qualified_fuzz_target_name}/'
311
+ f'{self.CORPUS_ZIP_NAME}')
312
+ logging.info('Downloading corpus from OSS-Fuzz: %s', corpus_url)
313
+
314
+ if not http_utils.download_and_unpack_zip(corpus_url, corpus_dir):
315
+ logging.warning('Failed to download corpus for %s.', target_name)
316
+ return corpus_dir
317
+
318
+ def upload_coverage(self):
319
+ """Noop Implementation of upload_coverage_report."""
320
+ logging.info('Not uploading coverage report because on OSS-Fuzz.')
321
+
322
+ def get_coverage(self, repo_path):
323
+ """Returns the project coverage object for the project."""
324
+ try:
325
+ return get_coverage.OSSFuzzCoverage(repo_path,
326
+ self.config.oss_fuzz_project_name)
327
+ except get_coverage.CoverageError:
328
+ return None
329
+
330
+
331
+ class NoClusterFuzzDeployment(BaseClusterFuzzDeployment):
332
+ """ClusterFuzzDeployment implementation used when there is no deployment of
333
+ ClusterFuzz to use."""
334
+
335
+ def upload_build(self, commit): # pylint: disable=no-self-use
336
+ """Noop Implementation of upload_build."""
337
+ logging.info('Not uploading latest build because no ClusterFuzz '
338
+ 'deployment.')
339
+
340
+ def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument
341
+ """Noop Implementation of upload_corpus."""
342
+ logging.info('Not uploading corpus because no ClusterFuzz deployment.')
343
+
344
+ def upload_crashes(self): # pylint: disable=no-self-use
345
+ """Noop Implementation of upload_crashes."""
346
+ logging.info('Not uploading crashes because no ClusterFuzz deployment.')
347
+
348
+ def download_corpus(self, target_name, corpus_dir):
349
+ """Noop Implementation of download_corpus."""
350
+ logging.info('Not downloading corpus because no ClusterFuzz deployment.')
351
+ return _make_empty_dir_if_nonexistent(corpus_dir)
352
+
353
+ def download_latest_build(self): # pylint: disable=no-self-use
354
+ """Noop Implementation of download_latest_build."""
355
+ logging.info(
356
+ 'Not downloading latest build because no ClusterFuzz deployment.')
357
+
358
+ def upload_coverage(self):
359
+ """Noop Implementation of upload_coverage."""
360
+ logging.info(
361
+ 'Not uploading coverage report because no ClusterFuzz deployment.')
362
+
363
+ def get_coverage(self, repo_path):
364
+ """Noop Implementation of get_coverage."""
365
+ logging.info(
366
+ 'Not getting project coverage because no ClusterFuzz deployment.')
367
+
368
+
369
+ _PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING = {
370
+ config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI: OSSFuzz,
371
+ config_utils.BaseConfig.Platform.INTERNAL_GITHUB: OSSFuzz,
372
+ config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI: ClusterFuzzLite,
373
+ config_utils.BaseConfig.Platform.EXTERNAL_GITHUB: ClusterFuzzLite,
374
+ }
375
+
376
+
377
+ def get_clusterfuzz_deployment(config, workspace):
378
+ """Returns object reprsenting deployment of ClusterFuzz used by |config|."""
379
+ deployment_cls = _PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING[config.platform]
380
+ if config.no_clusterfuzz_deployment:
381
+ logging.info('Overriding ClusterFuzzDeployment. Using None.')
382
+ deployment_cls = NoClusterFuzzDeployment
383
+ result = deployment_cls(config, workspace)
384
+ logging.info('ClusterFuzzDeployment: %s.', result)
385
+ return result
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/fuzz_target.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """A module to handle running a fuzz target for a specified amount of time."""
15
+ import collections
16
+ import logging
17
+ import multiprocessing
18
+ import os
19
+ import shutil
20
+ import stat
21
+ import tempfile
22
+ from typing import Optional
23
+
24
+ import clusterfuzz.environment
25
+ import clusterfuzz.fuzz
26
+
27
+ import config_utils
28
+ import logs
29
+
30
+ logs.init()
31
+
32
+ # Use len_control=0 since we don't have enough time fuzzing for len_control to
33
+ # make sense (probably).
34
+ LIBFUZZER_OPTIONS_BATCH = ['-len_control=0']
35
+ # Use a fixed seed for determinism for code change fuzzing.
36
+ LIBFUZZER_OPTIONS_CODE_CHANGE = LIBFUZZER_OPTIONS_BATCH + ['-seed=1337']
37
+ LIBFUZZER_OPTIONS_NO_REPORT_OOM = ['-rss_limit_mb=0']
38
+
39
+ # The number of reproduce attempts for a crash.
40
+ REPRODUCE_ATTEMPTS = 10
41
+
42
+ DEFAULT_REPRODUCE_TIME_SECONDS = 30
43
+ PER_LANGUAGE_REPRODUCE_TIMEOUTS = {
44
+ 'python': 30 * 4 # Python takes a bit longer on startup.
45
+ }
46
+ MINIMIZE_TIME_SECONDS = 60 * 4
47
+
48
+ # Seconds on top of duration until a timeout error is raised.
49
+ BUFFER_TIME = 10
50
+
51
+ # Log message if we can't check if crash reproduces on an recent build.
52
+ COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE = (
53
+ 'Could not run previous build of target to determine if this code change '
54
+ '(pr/commit) introduced crash. Assuming crash was newly introduced.')
55
+
56
+ FuzzResult = collections.namedtuple('FuzzResult',
57
+ ['testcase', 'stacktrace', 'corpus_path'])
58
+
59
+
60
+ def get_libfuzzer_parallel_options():
61
+ """Returns a list containing options to pass to libFuzzer to fuzz using all
62
+ available cores."""
63
+ return ['-jobs=' + str(multiprocessing.cpu_count())]
64
+
65
+
66
+ class ReproduceError(Exception):
67
+ """Error for when we can't attempt to reproduce a crash."""
68
+
69
+
70
+ def get_fuzz_target_corpus_dir(workspace, target_name):
71
+ """Returns the directory for storing |target_name|'s corpus in |workspace|."""
72
+ return os.path.join(workspace.corpora, target_name)
73
+
74
+
75
+ def get_fuzz_target_pruned_corpus_dir(workspace, target_name):
76
+ """Returns the directory for storing |target_name|'s puned corpus in
77
+ |workspace|."""
78
+ return os.path.join(workspace.pruned_corpora, target_name)
79
+
80
+
81
+ class FuzzTarget: # pylint: disable=too-many-instance-attributes
82
+ """A class to manage a single fuzz target.
83
+
84
+ Attributes:
85
+ target_name: The name of the fuzz target.
86
+ duration: The length of time in seconds that the target should run.
87
+ target_path: The location of the fuzz target binary.
88
+ workspace: The workspace for storing things related to fuzzing.
89
+ """
90
+
91
+ # pylint: disable=too-many-arguments
92
+ def __init__(self, target_path, duration, workspace, clusterfuzz_deployment,
93
+ config):
94
+ """Represents a single fuzz target.
95
+
96
+ Args:
97
+ target_path: The location of the fuzz target binary.
98
+ duration: The length of time in seconds the target should run.
99
+ workspace: The path used for storing things needed for fuzzing.
100
+ clusterfuzz_deployment: The object representing the ClusterFuzz
101
+ deployment.
102
+ config: The config of this project.
103
+ """
104
+ self.target_path = target_path
105
+ self.target_name = os.path.basename(self.target_path)
106
+ self.duration = int(duration)
107
+ self.workspace = workspace
108
+ self.clusterfuzz_deployment = clusterfuzz_deployment
109
+ self.config = config
110
+ self.latest_corpus_path = get_fuzz_target_corpus_dir(
111
+ self.workspace, self.target_name)
112
+ os.makedirs(self.latest_corpus_path, exist_ok=True)
113
+ self.pruned_corpus_path = get_fuzz_target_pruned_corpus_dir(
114
+ self.workspace, self.target_name)
115
+ os.makedirs(self.pruned_corpus_path, exist_ok=True)
116
+
117
+ def _download_corpus(self):
118
+ """Downloads the corpus for the target from ClusterFuzz and returns the path
119
+ to the corpus. An empty directory is provided if the corpus can't be
120
+ downloaded or is empty."""
121
+ self.clusterfuzz_deployment.download_corpus(self.target_name,
122
+ self.latest_corpus_path)
123
+ return self.latest_corpus_path
124
+
125
+ def _target_artifact_path(self):
126
+ """Target artifact path."""
127
+ artifact_path = os.path.join(self.workspace.artifacts, self.target_name,
128
+ self.config.sanitizer)
129
+ os.makedirs(artifact_path, exist_ok=True)
130
+ return artifact_path
131
+
132
+ def _save_crash(self, crash):
133
+ """Add stacktraces to crashes."""
134
+ target_reproducer_path = os.path.join(self._target_artifact_path(),
135
+ os.path.basename(crash.input_path))
136
+ shutil.copy(crash.input_path, target_reproducer_path)
137
+ bug_summary_artifact_path = target_reproducer_path + '.summary'
138
+ with open(bug_summary_artifact_path, 'w') as handle:
139
+ handle.write(crash.stacktrace)
140
+
141
+ # Set permissions of testcase to be the same as summary so that we're sure
142
+ # it can be read by necessary users.
143
+ permissions_mode = os.stat(bug_summary_artifact_path).st_mode
144
+ os.chmod(target_reproducer_path, permissions_mode & 0o777)
145
+ return target_reproducer_path
146
+
147
+ def prune(self):
148
+ """Prunes the corpus and returns the result."""
149
+ self._download_corpus()
150
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
151
+ self.config.sanitizer,
152
+ self.target_path):
153
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
154
+ result = engine_impl.minimize_corpus(self.target_path, [],
155
+ [self.latest_corpus_path],
156
+ self.pruned_corpus_path,
157
+ self._target_artifact_path(),
158
+ self.duration)
159
+
160
+ print(result.logs)
161
+ return FuzzResult(None, result.logs, self.pruned_corpus_path)
162
+
163
+ def fuzz(self, batch=False) -> Optional[FuzzResult]:
164
+ """Starts the fuzz target run for the length of time specified by duration.
165
+
166
+ Returns:
167
+ FuzzResult namedtuple with stacktrace and testcase if applicable.
168
+ """
169
+ logging.info('Running fuzzer: %s.', self.target_name)
170
+
171
+ self._download_corpus()
172
+ corpus_path = self.latest_corpus_path
173
+
174
+ logging.info('Starting fuzzing')
175
+ with tempfile.TemporaryDirectory() as artifacts_dir:
176
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
177
+ self.config.sanitizer,
178
+ self.target_path) as env:
179
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
180
+ options = engine_impl.prepare(corpus_path, env.target_path,
181
+ env.build_dir)
182
+ options.merge_back_new_testcases = False
183
+ options.analyze_dictionary = False
184
+ if batch:
185
+ options.arguments.extend(LIBFUZZER_OPTIONS_BATCH)
186
+ else:
187
+ options.arguments.extend(LIBFUZZER_OPTIONS_CODE_CHANGE)
188
+
189
+ if not self.config.report_ooms:
190
+ options.arguments.extend(LIBFUZZER_OPTIONS_NO_REPORT_OOM)
191
+
192
+ if self.config.parallel_fuzzing:
193
+ if self.config.sanitizer == 'memory':
194
+ # TODO(https://github.com/google/oss-fuzz/issues/11915): Don't gate
195
+ # this after jobs is fixed for MSAN.
196
+ logging.info('Not using jobs because it breaks MSAN.')
197
+ else:
198
+ options.arguments.extend(get_libfuzzer_parallel_options())
199
+
200
+ result = engine_impl.fuzz(self.target_path, options, artifacts_dir,
201
+ self.duration)
202
+ print(f'Fuzzing logs:\n{result.logs}')
203
+
204
+ if not result.crashes:
205
+ # Libfuzzer max time was reached.
206
+ logging.info('Fuzzer %s finished with no crashes discovered.',
207
+ self.target_name)
208
+ return FuzzResult(None, None, self.latest_corpus_path)
209
+
210
+ if result.timed_out:
211
+ logging.info('Not reporting crash in %s because process timed out.',
212
+ self.target_name)
213
+ return FuzzResult(None, None, self.latest_corpus_path)
214
+
215
+ # Only report first crash.
216
+ crash = result.crashes[0]
217
+ logging.info('Fuzzer: %s. Detected bug.', self.target_name)
218
+
219
+ is_reportable = self.is_crash_reportable(crash.input_path,
220
+ crash.reproduce_args,
221
+ batch=batch)
222
+ if is_reportable or self.config.upload_all_crashes:
223
+ logging.info('SAVING CRASH')
224
+ fuzzer_logs = result.logs
225
+ testcase_path = self._save_crash(crash)
226
+ if is_reportable and self.config.minimize_crashes:
227
+ # TODO(metzman): We don't want to minimize unreproducible crashes.
228
+ # Use is_reportable to decide this even though reportable crashes
229
+ # are a subset of reproducible ones.
230
+ self.minimize_testcase(testcase_path)
231
+ else:
232
+ logging.info('NOT MINIMIZED')
233
+ else:
234
+ fuzzer_logs = None
235
+ testcase_path = None
236
+
237
+ return FuzzResult(testcase_path, fuzzer_logs, self.latest_corpus_path)
238
+
239
+ def minimize_testcase(self, testcase_path):
240
+ """Minimizes the testcase located at |testcase_path|."""
241
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
242
+ self.config.sanitizer,
243
+ self.target_path):
244
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
245
+ minimized_testcase_path = testcase_path + '-minimized'
246
+ return engine_impl.minimize_testcase(self.target_path, [],
247
+ testcase_path,
248
+ minimized_testcase_path,
249
+ max_time=MINIMIZE_TIME_SECONDS)
250
+
251
+ def free_disk_if_needed(self, delete_fuzz_target=True):
252
+ """Deletes things that are no longer needed from fuzzing this fuzz target to
253
+ save disk space if needed."""
254
+ if not self.config.low_disk_space:
255
+ logging.info('Not freeing disk space after running fuzz target.')
256
+ return
257
+ logging.info('Deleting corpus and seed corpus of %s to save disk.',
258
+ self.target_name)
259
+
260
+ # Delete the seed corpus, corpus, and fuzz target.
261
+ for corpus_path in [self.latest_corpus_path, self.pruned_corpus_path]:
262
+ # Use ignore_errors=True to fix
263
+ # https://github.com/google/oss-fuzz/issues/5383.
264
+ shutil.rmtree(corpus_path, ignore_errors=True)
265
+
266
+ target_seed_corpus_path = self.target_path + '_seed_corpus.zip'
267
+ if os.path.exists(target_seed_corpus_path):
268
+ os.remove(target_seed_corpus_path)
269
+
270
+ if delete_fuzz_target:
271
+ logging.info('Deleting fuzz target: %s.', self.target_name)
272
+ os.remove(self.target_path)
273
+ logging.info('Done deleting.')
274
+
275
+ def is_reproducible(self, testcase, target_path, reproduce_args):
276
+ """Checks if the testcase reproduces.
277
+
278
+ Args:
279
+ testcase: The path to the testcase to be tested.
280
+ target_path: The path to the fuzz target to be tested
281
+ reproduce_args: The arguments to pass to the target to reproduce the
282
+ crash.
283
+
284
+ Returns:
285
+ True if crash is reproducible and we were able to run the
286
+ binary.
287
+
288
+ Raises:
289
+ ReproduceError if we can't attempt to reproduce the crash.
290
+ """
291
+ if not os.path.exists(target_path):
292
+ logging.info('Target: %s does not exist.', target_path)
293
+ raise ReproduceError(f'Target {target_path} not found.')
294
+
295
+ os.chmod(target_path, stat.S_IRWXO)
296
+
297
+ logging.info('Trying to reproduce crash using: %s.', testcase)
298
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
299
+ self.config.sanitizer,
300
+ target_path):
301
+ reproduce_time_seconds = PER_LANGUAGE_REPRODUCE_TIMEOUTS.get(
302
+ self.config.language, DEFAULT_REPRODUCE_TIME_SECONDS)
303
+ for _ in range(REPRODUCE_ATTEMPTS):
304
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
305
+ try:
306
+ result = engine_impl.reproduce(target_path,
307
+ testcase,
308
+ arguments=reproduce_args,
309
+ max_time=reproduce_time_seconds)
310
+ except TimeoutError as error:
311
+ logging.error('%s.', error)
312
+ return False
313
+
314
+ if result.return_code != 0:
315
+ logging.info('Reproduce command returned: %s. Reproducible on %s.',
316
+ result.return_code, target_path)
317
+
318
+ return True
319
+
320
+ logging.info('Reproduce command returned: 0. Not reproducible on %s.',
321
+ target_path)
322
+ return False
323
+
324
+ def is_crash_reportable(self, testcase, reproduce_args, batch=False):
325
+ """Returns True if a crash is reportable. This means the crash is
326
+ reproducible but not reproducible on a build from the ClusterFuzz deployment
327
+ (meaning the crash was introduced by this PR/commit/code change).
328
+
329
+ Args:
330
+ testcase: The path to the testcase that triggered the crash.
331
+ reproduce_args: The arguments to pass to the target to reproduce the
332
+ crash.
333
+
334
+ Returns:
335
+ True if the crash was introduced by the current pull request.
336
+
337
+ Raises:
338
+ ReproduceError if we can't attempt to reproduce the crash on the PR build.
339
+ """
340
+
341
+ if not self.is_crash_type_reportable(testcase):
342
+ return False
343
+
344
+ if not os.path.exists(testcase):
345
+ raise ReproduceError(f'Testcase {testcase} not found.')
346
+
347
+ try:
348
+ reproducible_on_code_change = self.is_reproducible(
349
+ testcase, self.target_path, reproduce_args)
350
+ except ReproduceError as error:
351
+ logging.error('Could not check for crash reproducibility.'
352
+ 'Please file an issue:'
353
+ 'https://github.com/google/oss-fuzz/issues/new.')
354
+ raise error
355
+
356
+ if not reproducible_on_code_change:
357
+ logging.info('Crash is not reproducible.')
358
+ return self.config.report_unreproducible_crashes
359
+
360
+ logging.info('Crash is reproducible.')
361
+ if batch:
362
+ # We don't need to check if the crash is novel for batch fuzzing.
363
+ return True
364
+
365
+ return self.is_crash_novel(testcase, reproduce_args)
366
+
367
+ def is_crash_type_reportable(self, testcase):
368
+ """Returns True if |testcase| is an actual crash. If crash is a timeout or
369
+ OOM then returns True if config says we should report those."""
370
+ # TODO(metzman): Use a less hacky method.
371
+ testcase = os.path.basename(testcase)
372
+ if testcase.startswith('oom-'):
373
+ return self.config.report_ooms
374
+ if testcase.startswith('timeout-'):
375
+ return self.config.report_timeouts
376
+ return True
377
+
378
+ def is_crash_novel(self, testcase, reproduce_args):
379
+ """Returns whether or not the crash is new. A crash is considered new if it
380
+ can't be reproduced on an older ClusterFuzz build of the target."""
381
+ if not os.path.exists(testcase):
382
+ raise ReproduceError('Testcase %s not found.' % testcase)
383
+ clusterfuzz_build_dir = self.clusterfuzz_deployment.download_latest_build()
384
+ if not clusterfuzz_build_dir:
385
+ # Crash is reproducible on PR build and we can't test on a recent
386
+ # ClusterFuzz/OSS-Fuzz build.
387
+ logging.info(COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE)
388
+ return True
389
+
390
+ clusterfuzz_target_path = os.path.join(clusterfuzz_build_dir,
391
+ self.target_name)
392
+
393
+ try:
394
+ reproducible_on_clusterfuzz_build = self.is_reproducible(
395
+ testcase, clusterfuzz_target_path, reproduce_args)
396
+ except ReproduceError:
397
+ # This happens if the project has ClusterFuzz builds, but the fuzz target
398
+ # is not in it (e.g. because the fuzz target is new).
399
+ logging.info(COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE)
400
+ return True
401
+
402
+ if reproducible_on_clusterfuzz_build:
403
+ logging.info('The crash is reproducible on previous build. '
404
+ 'Code change (pr/commit) did not introduce crash.')
405
+ return False
406
+ logging.info('The crash is not reproducible on previous build. '
407
+ 'Code change (pr/commit) introduced crash.')
408
+ return True
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 generate_coverage_report."""
15
+
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import generate_coverage_report
20
+ import test_helpers
21
+
22
+ OUT_DIR = '/outdir'
23
+ PROJECT = 'example-project'
24
+ SANITIZER = 'coverage'
25
+
26
+
27
+ class TestRunCoverageCommand(unittest.TestCase):
28
+ """Tests run_coverage_command"""
29
+
30
+ def setUp(self):
31
+ test_helpers.patch_environ(self, empty=True)
32
+
33
+ @mock.patch('utils.execute')
34
+ def test_run_coverage_command(self, mock_execute): # pylint: disable=no-self-use
35
+ """Tests that run_coverage_command works as intended."""
36
+ config = test_helpers.create_run_config(oss_fuzz_project_name=PROJECT,
37
+ sanitizer=SANITIZER)
38
+ workspace = test_helpers.create_workspace()
39
+ generate_coverage_report.run_coverage_command(config, workspace)
40
+ expected_command = 'coverage'
41
+ expected_env = {
42
+ 'SANITIZER': config.sanitizer,
43
+ 'FUZZING_LANGUAGE': config.language,
44
+ 'OUT': workspace.out,
45
+ 'CIFUZZ': 'True',
46
+ 'FUZZING_ENGINE': 'libfuzzer',
47
+ 'ARCHITECTURE': 'x86_64',
48
+ 'FUZZER_ARGS': '-rss_limit_mb=2560 -timeout=25',
49
+ 'HTTP_PORT': '',
50
+ 'COVERAGE_EXTRA_ARGS': '',
51
+ 'CORPUS_DIR': workspace.corpora,
52
+ 'COVERAGE_OUTPUT_DIR': workspace.coverage_report
53
+ }
54
+ mock_execute.assert_called_with(expected_command, env=expected_env)
55
+
56
+
57
+ class DownloadCorporaTest(unittest.TestCase):
58
+ """Tests for download_corpora."""
59
+
60
+ def test_download_corpora(self): # pylint: disable=no-self-use
61
+ """Tests that download_corpora works as intended."""
62
+ clusterfuzz_deployment = mock.Mock()
63
+ clusterfuzz_deployment.workspace = test_helpers.create_workspace()
64
+ fuzz_target_paths = ['/path/to/fuzzer1', '/path/to/fuzzer2']
65
+ expected_calls = [
66
+ mock.call('fuzzer1', '/workspace/cifuzz-corpus/fuzzer1'),
67
+ mock.call('fuzzer2', '/workspace/cifuzz-corpus/fuzzer2')
68
+ ]
69
+ generate_coverage_report.download_corpora(fuzz_target_paths,
70
+ clusterfuzz_deployment)
71
+ clusterfuzz_deployment.download_corpus.assert_has_calls(expected_calls)
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/http_utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Utility module for HTTP."""
15
+ import json
16
+ import logging
17
+ import os
18
+ import sys
19
+ import tempfile
20
+ import zipfile
21
+
22
+ import requests
23
+
24
+ # pylint: disable=wrong-import-position,import-error
25
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
26
+ import retry
27
+
28
+ _DOWNLOAD_URL_RETRIES = 3
29
+ _DOWNLOAD_URL_BACKOFF = 1
30
+ _HTTP_REQUEST_TIMEOUT = 10
31
+
32
+
33
+ def download_and_unpack_zip(url, extract_directory, headers=None):
34
+ """Downloads and unpacks a zip file from an HTTP URL.
35
+
36
+ Args:
37
+ url: A url to the zip file to be downloaded and unpacked.
38
+ extract_directory: The path where the zip file should be extracted to.
39
+ headers: (Optional) HTTP headers to send with the download request.
40
+
41
+ Returns:
42
+ True on success.
43
+ """
44
+ if headers is None:
45
+ headers = {}
46
+
47
+ if not os.path.exists(extract_directory):
48
+ logging.error('Extract directory: %s does not exist.', extract_directory)
49
+ return False
50
+
51
+ # Gives the temporary zip file a unique identifier in the case that
52
+ # that download_and_unpack_zip is done in parallel.
53
+ with tempfile.NamedTemporaryFile(suffix='.zip') as tmp_file:
54
+ if not download_url(url, tmp_file.name, headers=headers):
55
+ return False
56
+
57
+ try:
58
+ with zipfile.ZipFile(tmp_file.name, 'r') as zip_file:
59
+ zip_file.extractall(extract_directory)
60
+ except zipfile.BadZipFile:
61
+ logging.error('Error unpacking zip from %s. Bad Zipfile.', url)
62
+ return False
63
+
64
+ return True
65
+
66
+
67
+ def download_url(*args, **kwargs):
68
+ """Wrapper around _download_url that returns False if _download_url
69
+ exceptions."""
70
+ try:
71
+ return _download_url(*args, **kwargs)
72
+ except Exception: # pylint: disable=broad-except
73
+ return False
74
+
75
+
76
+ def get_json_from_url(url):
77
+ """Gets a json object from a specified HTTP URL.
78
+
79
+ Args:
80
+ url: The url of the json to be downloaded.
81
+
82
+ Returns:
83
+ A dictionary deserialized from JSON or None on failure.
84
+ """
85
+ try:
86
+ return requests.get(url, timeout=_HTTP_REQUEST_TIMEOUT).json()
87
+ except (ValueError, TypeError, json.JSONDecodeError,
88
+ requests.exceptions.ReadTimeout) as err:
89
+ logging.error('Loading json from url %s failed with: %s.', url, str(err))
90
+ return None
91
+
92
+
93
+ @retry.wrap(_DOWNLOAD_URL_RETRIES, _DOWNLOAD_URL_BACKOFF)
94
+ def _download_url(url, filename, headers=None):
95
+ """Downloads the file located at |url|, using HTTP to |filename|.
96
+
97
+ Args:
98
+ url: A url to a file to download.
99
+ filename: The path the file should be downloaded to.
100
+ headers: (Optional) HTTP headers to send with the download request.
101
+
102
+ Returns:
103
+ True on success.
104
+ """
105
+ if headers is None:
106
+ headers = {}
107
+
108
+ response = requests.get(url, headers=headers)
109
+
110
+ if response.status_code != 200:
111
+ logging.error('Unable to download from: %s. Code: %d. Content: %s.', url,
112
+ response.status_code, response.content)
113
+ return False
114
+
115
+ with open(filename, 'wb') as file_handle:
116
+ file_handle.write(response.content)
117
+
118
+ return True
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/cifuzz/sarif_utils.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Module for outputting SARIF data."""
15
+ import copy
16
+ import json
17
+ import logging
18
+ import os
19
+
20
+ from clusterfuzz import stacktraces
21
+
22
+ SARIF_RULES = [
23
+ {
24
+ 'id': 'no-crashes',
25
+ 'shortDescription': {
26
+ 'text': 'Don\'t crash'
27
+ },
28
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/416.html',
29
+ 'properties': {
30
+ 'category': 'Crashes'
31
+ }
32
+ },
33
+ {
34
+ 'id': 'heap-use-after-free',
35
+ 'shortDescription': {
36
+ 'text': 'Use of a heap-object after it has been freed.'
37
+ },
38
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/416.html',
39
+ 'properties': {
40
+ 'category': 'Crashes'
41
+ }
42
+ },
43
+ {
44
+ 'id': 'heap-buffer-overflow',
45
+ 'shortDescription': {
46
+ 'text': 'A read or write past the end of a heap buffer.'
47
+ },
48
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/122.html',
49
+ 'properties': {
50
+ 'category': 'Crashes'
51
+ }
52
+ },
53
+ {
54
+ 'id': 'stack-buffer-overflow',
55
+ 'shortDescription': {
56
+ 'text': 'A read or write past the end of a stack buffer.'
57
+ },
58
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/121.html',
59
+ 'properties': {
60
+ 'category': 'Crashes'
61
+ }
62
+ },
63
+ {
64
+ 'id': 'global-buffer-overflow',
65
+ 'shortDescription': {
66
+ 'text': 'A read or write past the end of a global buffer.'
67
+ },
68
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/121.html',
69
+ 'properties': {
70
+ 'category': 'Crashes'
71
+ }
72
+ },
73
+ {
74
+ 'id': 'stack-use-after-return',
75
+ 'shortDescription': {
76
+ 'text':
77
+ 'A stack-based variable has been used after the function returned.'
78
+ },
79
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/562.html',
80
+ 'properties': {
81
+ 'category': 'Crashes'
82
+ }
83
+ },
84
+ {
85
+ 'id': 'stack-use-after-scope',
86
+ 'shortDescription': {
87
+ 'text':
88
+ 'A stack-based variable has been used outside of the scope in which it exists.'
89
+ },
90
+ 'helpUri': 'https://cwe.mitre.org/data/definitions/562.html',
91
+ 'properties': {
92
+ 'category': 'Crashes'
93
+ }
94
+ },
95
+ {
96
+ 'id': 'initialization-order-fiasco',
97
+ 'shortDescription': {
98
+ 'text': 'Problem with order of initialization of global objects.'
99
+ },
100
+ 'helpUri': 'https://isocpp.org/wiki/faq/ctors#static-init-order',
101
+ 'properties': {
102
+ 'category': 'Crashes'
103
+ }
104
+ },
105
+ {
106
+ 'id':
107
+ 'direct-leak',
108
+ 'shortDescription': {
109
+ 'text': 'Memory is leaked.'
110
+ },
111
+ 'helpUri':
112
+ 'https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer',
113
+ 'properties': {
114
+ 'category': 'Crashes'
115
+ }
116
+ },
117
+ {
118
+ 'id':
119
+ 'indirect-leak',
120
+ 'shortDescription': {
121
+ 'text': 'Memory is leaked.'
122
+ },
123
+ 'helpUri':
124
+ 'https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer',
125
+ 'properties': {
126
+ 'category': 'Crashes'
127
+ }
128
+ },
129
+ ]
130
+ SARIF_DATA = {
131
+ 'version':
132
+ '2.1.0',
133
+ '$schema':
134
+ 'http://json.schemastore.org/sarif-2.1.0-rtm.4',
135
+ 'runs': [{
136
+ 'tool': {
137
+ 'driver': {
138
+ 'name': 'ClusterFuzzLite/CIFuzz',
139
+ 'informationUri': 'https://google.github.io/clusterfuzzlite/',
140
+ 'rules': SARIF_RULES,
141
+ }
142
+ },
143
+ 'results': []
144
+ }]
145
+ }
146
+
147
+ SRC_ROOT = '/src/'
148
+
149
+
150
+ def redact_src_path(src_path):
151
+ """Redact the src path so that it can be reported to users."""
152
+ src_path = os.path.normpath(src_path)
153
+ if src_path.startswith(SRC_ROOT):
154
+ src_path = src_path[len(SRC_ROOT):]
155
+
156
+ src_path = os.sep.join(src_path.split(os.sep)[1:])
157
+ return src_path
158
+
159
+
160
+ def get_error_frame(crash_info):
161
+ """Returns the stackframe where the error occurred."""
162
+ if not crash_info.crash_state:
163
+ return None
164
+ state = crash_info.crash_state.split('\n')[0]
165
+ logging.info('state: %s frames %s, %s', state, crash_info.frames,
166
+ [f.function_name for f in crash_info.frames[0]])
167
+
168
+ for crash_frames in crash_info.frames:
169
+ for frame in crash_frames:
170
+ # TODO(metzman): Do something less fragile here.
171
+ if frame.function_name is None:
172
+ continue
173
+ if state in frame.function_name:
174
+ return frame
175
+ return None
176
+
177
+
178
+ def get_error_source_info(crash_info):
179
+ """Returns the filename and the line where the bug occurred."""
180
+ frame = get_error_frame(crash_info)
181
+ if not frame:
182
+ return (None, 1)
183
+ try:
184
+ return redact_src_path(frame.filename), int(frame.fileline or 1)
185
+ except TypeError:
186
+ return (None, 1)
187
+
188
+
189
+ def get_rule_index(crash_type):
190
+ """Returns the rule index describe the rule that |crash_type| ran afoul of."""
191
+ # Don't include "READ" or "WRITE" or number of bytes.
192
+ crash_type = crash_type.replace('\n', ' ').split(' ')[0].lower()
193
+ logging.info('crash_type: %s.', crash_type)
194
+ for idx, rule in enumerate(SARIF_RULES):
195
+ if rule['id'] == crash_type:
196
+ logging.info('Rule index: %d.', idx)
197
+ return idx
198
+
199
+ return get_rule_index('no-crashes')
200
+
201
+
202
+ def get_sarif_data(stacktrace, target_path):
203
+ """Returns a description of the crash in SARIF."""
204
+ data = copy.deepcopy(SARIF_DATA)
205
+ if stacktrace is None:
206
+ return data
207
+
208
+ fuzz_target = os.path.basename(target_path)
209
+ stack_parser = stacktraces.StackParser(fuzz_target=fuzz_target,
210
+ symbolized=True,
211
+ detect_ooms_and_hangs=True,
212
+ include_ubsan=True)
213
+ crash_info = stack_parser.parse(stacktrace)
214
+ error_source_info = get_error_source_info(crash_info)
215
+ rule_idx = get_rule_index(crash_info.crash_type)
216
+ rule_id = SARIF_RULES[rule_idx]['id']
217
+ uri = error_source_info[0]
218
+
219
+ result = {
220
+ 'level': 'error',
221
+ 'message': {
222
+ 'text': crash_info.crash_type
223
+ },
224
+ 'locations': [{
225
+ 'physicalLocation': {
226
+ 'artifactLocation': {
227
+ 'uri': uri,
228
+ 'index': 0
229
+ },
230
+ 'region': {
231
+ 'startLine': error_source_info[1],
232
+ # We don't have this granualarity fuzzing.
233
+ 'startColumn': 1,
234
+ }
235
+ }
236
+ }],
237
+ 'ruleId': rule_id,
238
+ 'ruleIndex': rule_idx
239
+ }
240
+ if uri:
241
+ data['runs'][0]['results'].append(result)
242
+ return data
243
+
244
+
245
+ def write_stacktrace_to_sarif(stacktrace, target_path, workspace):
246
+ """Writes a description of the crash in stacktrace to a SARIF file."""
247
+ data = get_sarif_data(stacktrace, target_path)
248
+ if not os.path.exists(workspace.sarif):
249
+ os.makedirs(workspace.sarif)
250
+ with open(os.path.join(workspace.sarif, 'results.sarif'), 'w') as file_handle:
251
+ file_handle.write(json.dumps(data))
local-test-tika-full-01-vuln_1/fuzz-tooling/infra/tools/hold_back_images.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
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 pinning builder images for projects that break on upgrades. Works
18
+ with projects that use language builders."""
19
+ import argparse
20
+ import logging
21
+ import os
22
+ import re
23
+ import sys
24
+ import subprocess
25
+
26
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
27
+ PROJECTS_DIR = os.path.join(ROOT_DIR, 'projects')
28
+
29
+ IMAGE_DIGEST_REGEX = re.compile(r'\[(.+)\]\n')
30
+ FROM_LINE_REGEX = re.compile(
31
+ r'FROM (ghcr.io\/aixcc-finals\/base-builder[\-a-z0-9]*)(\@?.*)')
32
+
33
+
34
+ def get_latest_docker_image_digest(image):
35
+ """Returns a pinnable version of the latest |image|. This version will have a
36
+ SHA."""
37
+ subprocess.run(['docker', 'pull', image], check=True)
38
+ subprocess.run(['docker', 'pull', image], stdout=subprocess.PIPE, check=True)
39
+
40
+ command = [
41
+ 'docker', 'image', 'inspect', '--format', '{{.RepoDigests}}', image
42
+ ]
43
+ output = subprocess.run(command, check=True,
44
+ stdout=subprocess.PIPE).stdout.decode('utf-8')
45
+ return IMAGE_DIGEST_REGEX.match(output).groups(1)[0]
46
+
47
+
48
+ def get_args():
49
+ """Returns parsed arguments."""
50
+ parser = argparse.ArgumentParser(sys.argv[0],
51
+ description='Hold back builder images.')
52
+ parser.add_argument('projects', help='Projects.', nargs='+')
53
+
54
+ parser.add_argument('--hold-image-digest',
55
+ required=False,
56
+ nargs='?',
57
+ default=None,
58
+ help='Image to hold on to.')
59
+
60
+ parser.add_argument('--update-held',
61
+ action='store_true',
62
+ default=False,
63
+ help='Update held images.')
64
+
65
+ parser.add_argument('--issue-number',
66
+ required=False,
67
+ nargs='?',
68
+ default=None,
69
+ help='Issue to reference.')
70
+
71
+ args = parser.parse_args()
72
+ return args
73
+
74
+
75
+ def get_hold_image_digest(line, hold_image_digest, update_held):
76
+ """Returns the image digest for the |line| we want to pin. If the image is
77
+ already pinned then it is only updated if |update_held. If |hold_image_digest
78
+ is specified then it is returned, otherwise the latest pinnable version is
79
+ returned."""
80
+ matches = FROM_LINE_REGEX.match(line).groups()
81
+ if matches[1] and not update_held:
82
+ return None, False
83
+ initial_image = matches[0]
84
+ if hold_image_digest:
85
+ return hold_image_digest, True
86
+ return get_latest_docker_image_digest(initial_image), True
87
+
88
+
89
+ def hold_image(project, hold_image_digest, update_held, issue_number):
90
+ """Rewrites the Dockerfile of |project| to pin the base-builder image on
91
+ upgrade."""
92
+ dockerfile_path = os.path.join(PROJECTS_DIR, project, 'Dockerfile')
93
+ with open(dockerfile_path, 'r') as dockerfile_handle:
94
+ dockerfile = dockerfile_handle.readlines()
95
+ for idx, line in enumerate(dockerfile[:]):
96
+ if not line.startswith('FROM ghcr.io/aixcc-finals/base-builder'):
97
+ continue
98
+
99
+ hold_image_digest, should_hold = get_hold_image_digest(
100
+ line.strip(), hold_image_digest, update_held)
101
+ if not should_hold:
102
+ logging.error('Not holding back %s.', project)
103
+ break
104
+ dockerfile[idx] = f'FROM {hold_image_digest}\n'
105
+ if issue_number:
106
+ comment = ('# Held back because of github.com/google/oss-fuzz/pull/'
107
+ f'{issue_number}\n# Please fix failure and upgrade.\n')
108
+ dockerfile.insert(idx, comment)
109
+ break
110
+ else:
111
+ # This path is taken when we don't break out of the loop.
112
+ assert None, f'Could not find FROM line in {project}'
113
+ dockerfile = ''.join(dockerfile)
114
+ with open(dockerfile_path, 'w') as dockerfile_handle:
115
+ dockerfile_handle.write(dockerfile)
116
+
117
+
118
+ def main():
119
+ """Script for pinning builder images for projects that break on upgrades."""
120
+ args = get_args()
121
+ for project in args.projects:
122
+ hold_image(project, args.hold_image_digest, args.update_held,
123
+ args.issue_number)
124
+ return 0
125
+
126
+
127
+ if __name__ == '__main__':
128
+ sys.exit(main())
local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspace.ts ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+ import {println} from '../logger';
19
+ import {commandHistory} from '../commandUtils';
20
+ import {
21
+ hasOssFuzzInWorkspace,
22
+ getOssFuzzWorkspaceProjectName,
23
+ setStatusText,
24
+ } from '../utils';
25
+ import {buildFuzzersFromWorkspace} from '../ossfuzzWrappers';
26
+
27
+ export async function cmdInputCollectorBuildFuzzersFromWorkspace() {
28
+ let ossFuzzProjectName = '';
29
+ // First determine if we have a name in the workspace
30
+ if (await hasOssFuzzInWorkspace()) {
31
+ /**
32
+ * The fuzzers are in the workspace, as opposed to e.g. the oss-fuzz dirctory.
33
+ */
34
+ ossFuzzProjectName = await getOssFuzzWorkspaceProjectName();
35
+ } else {
36
+ // If we did not have that, ask the user.
37
+
38
+ const ossFuzzProjectNameInput = await vscode.window.showInputBox({
39
+ value: '',
40
+ placeHolder: 'The OSS-Fuzz project name',
41
+ });
42
+ if (!ossFuzzProjectNameInput) {
43
+ println('Did not get a ossFuzzTargetProject');
44
+ return false;
45
+ }
46
+ ossFuzzProjectName = ossFuzzProjectNameInput.toString();
47
+ }
48
+
49
+ // Create an history object
50
+ const args = new Object({
51
+ projectName: ossFuzzProjectName,
52
+ sanitizer: '',
53
+ toClean: false,
54
+ });
55
+
56
+ const commandObject = new Object({
57
+ commandType: 'oss-fuzz.WSBuildFuzzers',
58
+ Arguments: args,
59
+ dispatcherFunc: cmdDispatchBuildFuzzersFromWorkspace,
60
+ });
61
+ console.log('L1: ' + commandHistory.length);
62
+ commandHistory.push(commandObject);
63
+
64
+ await cmdDispatchBuildFuzzersFromWorkspace(args);
65
+ return true;
66
+ }
67
+
68
+ async function cmdDispatchBuildFuzzersFromWorkspace(args: any) {
69
+ await setStatusText('Building fuzzers: starting');
70
+ const res = await buildFuzzersFromWorkspace(
71
+ args.projectName,
72
+ args.sanitizer,
73
+ args.toClean
74
+ );
75
+ if (res) {
76
+ await setStatusText('Building fuzzers: finished');
77
+ } else {
78
+ await setStatusText('Building fuzzers: failed');
79
+ }
80
+ }
local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdDispatcherGenerateClusterfuzzLite.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ /**
18
+ * Command for generating template fuzzers. This is a short-cut for rapid
19
+ * prototyping as well as an archive for inspiration.
20
+ */
21
+ import * as vscode from 'vscode';
22
+ import {setStatusText} from '../utils';
23
+
24
+ import {setupProjectInitialFiles} from '../projectIntegrationHelper';
25
+
26
+ export async function cmdDispatcherGenerateClusterfuzzLite(
27
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
28
+ _context: vscode.ExtensionContext
29
+ ) {
30
+ await setStatusText('Creating OSS-Fuzz setup: starting');
31
+ const res = await setupProjectInitialFiles(true);
32
+ if (res) {
33
+ await setStatusText('Creating OSS-Fuzz setup: finished');
34
+ } else {
35
+ await setStatusText('Creating OSS-Fuzz setup: failed');
36
+ }
37
+ return;
38
+ }
local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+ import {loadCoverageIntoWorkspace} from '../coverageHelper';
19
+ import {println} from '../logger';
20
+ import {getApi, FileDownloader} from '@microsoft/vscode-file-downloader-api';
21
+
22
+ /*
23
+ * Displays code coverage from OSS-Fuzz.
24
+ *
25
+ * Downloads a code coverage report from the OSS-Fuzz online storage, and then overlays
26
+ * the relevant source files with the coverage information.
27
+ */
28
+ export async function displayCodeCoverageFromOssFuzz(
29
+ context: vscode.ExtensionContext
30
+ ) {
31
+ const projectName = await vscode.window.showInputBox({
32
+ value: '',
33
+ placeHolder: "The project you'd like to get code coverage for.",
34
+ });
35
+ if (!projectName) {
36
+ return;
37
+ }
38
+ println('Getting code coverage for ' + projectName);
39
+
40
+ const fileDownloader: FileDownloader = await getApi();
41
+
42
+ const currentDate = new Date();
43
+ const yesterday = new Date(currentDate);
44
+ yesterday.setDate(yesterday.getDate() - 1);
45
+
46
+ const day = yesterday.getDate();
47
+ const month = yesterday.getMonth();
48
+ const year = yesterday.getFullYear();
49
+
50
+ try {
51
+ const codeCoverageFile: vscode.Uri = await fileDownloader.downloadFile(
52
+ vscode.Uri.parse(
53
+ 'https://storage.googleapis.com/oss-fuzz-coverage/' +
54
+ projectName +
55
+ '/textcov_reports/' +
56
+ year.toString() +
57
+ month.toString() +
58
+ day.toString() +
59
+ '/all_cov.json'
60
+ ),
61
+ 'all_cov.json',
62
+ context
63
+ );
64
+ await loadCoverageIntoWorkspace(context, codeCoverageFile);
65
+ } catch (err) {
66
+ println(
67
+ 'Could not get the URL. Currently, this feature is only supported for Python projects'
68
+ );
69
+ return;
70
+ }
71
+ }
local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdEndToEndCoverage.ts ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+ const fs = require('fs');
19
+ import {println} from '../logger';
20
+ import {commandHistory} from '../commandUtils';
21
+ import {buildFuzzersFromWorkspace, runFuzzerHandler} from '../ossfuzzWrappers';
22
+ import {listFuzzersForProject, systemSync, setStatusText} from '../utils';
23
+ import {
24
+ compareLocalToRemoteCoverage,
25
+ loadCoverageIntoWorkspace,
26
+ } from '../coverageHelper';
27
+ import {extensionConfig} from '../config';
28
+
29
+ /**
30
+ * Performs the activities:
31
+ * 1) Build a project using address sanitizer
32
+ * 2) Run each fuzzer of the project, saving corpus
33
+ * 3) Build project using coverage sanitizer
34
+ * 4) Collect coverage
35
+ * @param context
36
+ * @returns
37
+ */
38
+ export async function runEndToEndAndGetCoverage(
39
+ context: vscode.ExtensionContext
40
+ ) {
41
+ println('Getting code coverage');
42
+ await setStatusText('end-to-end coverage: getting input');
43
+ const ossFuzzProjectNameInput = await vscode.window.showInputBox({
44
+ value: '',
45
+ placeHolder: 'The OSS-Fuzz project name',
46
+ });
47
+ if (!ossFuzzProjectNameInput) {
48
+ println('Did not get a ossFuzzTargetProject');
49
+ return;
50
+ }
51
+ const secondsToRunEachFuzzer = await vscode.window.showInputBox({
52
+ value: '',
53
+ placeHolder: 'Seconds to run each fuzzer',
54
+ });
55
+ if (!secondsToRunEachFuzzer) {
56
+ println('Did not get number of seconds to run each fuzzer');
57
+ return;
58
+ }
59
+
60
+ // Create an history object
61
+ const args = new Object({
62
+ projectName: ossFuzzProjectNameInput.toString(),
63
+ secondsToRun: secondsToRunEachFuzzer.toString(),
64
+ vsContext: context,
65
+ });
66
+
67
+ const commandObject = new Object({
68
+ commandType: 'oss-fuzz.cmdDispatchEndToEndRun',
69
+ Arguments: args,
70
+ dispatcherFunc: cmdDispatchEndToEndRun,
71
+ });
72
+ console.log('L1: ' + commandHistory.length);
73
+ commandHistory.push(commandObject);
74
+
75
+ await cmdDispatchEndToEndRun(args);
76
+ return;
77
+ }
78
+
79
+ async function cmdDispatchEndToEndRun(args: any) {
80
+ await setStatusText('end-to-end coverage: starting');
81
+ const res = await endToEndRun(
82
+ args.projectName,
83
+ args.secondsToRun,
84
+ args.vsContext
85
+ );
86
+ if (res) {
87
+ await setStatusText('end-to-end coverage: finished succesfully');
88
+ } else {
89
+ await setStatusText('end-to-end coverage: failed');
90
+ }
91
+ return;
92
+ }
93
+
94
+ async function endToEndRun(
95
+ ossFuzzProjectNameInput: string,
96
+ secondsToRunEachFuzzer: string,
97
+ context: vscode.ExtensionContext
98
+ ) {
99
+ await setStatusText('end-to-end coverage: build with ASAN');
100
+ vscode.window.showInformationMessage(
101
+ 'Building project: ' + ossFuzzProjectNameInput.toString()
102
+ );
103
+ if (
104
+ (await buildFuzzersFromWorkspace(
105
+ ossFuzzProjectNameInput.toString(),
106
+ '',
107
+ true
108
+ )) === false
109
+ ) {
110
+ println('Failed to build project');
111
+ return false;
112
+ }
113
+ println('Build projects');
114
+
115
+ // List all of the fuzzers in the project
116
+ const fuzzersInProject = await listFuzzersForProject(
117
+ ossFuzzProjectNameInput,
118
+ extensionConfig.ossFuzzPepositoryWorkPath
119
+ );
120
+
121
+ // Run all of the fuzzers in the project
122
+ await setStatusText('end-to-end coverage: collecting corpus');
123
+ println('Fuzzers found in project: ' + fuzzersInProject.toString());
124
+ println('Running each of the fuzzers to collect a corpus');
125
+ for (const fuzzName of fuzzersInProject) {
126
+ println('Running fuzzer: ' + fuzzName);
127
+ await setStatusText('end-to-end coverage: collecting corpus: ' + fuzzName);
128
+ // Corpus directory
129
+ const fuzzerCorpusPath =
130
+ extensionConfig.ossFuzzPepositoryWorkPath +
131
+ '/build/corpus/' +
132
+ ossFuzzProjectNameInput +
133
+ '/' +
134
+ fuzzName;
135
+
136
+ await systemSync('mkdir', ['-p', fuzzerCorpusPath]);
137
+
138
+ await runFuzzerHandler(
139
+ ossFuzzProjectNameInput,
140
+ fuzzName,
141
+ secondsToRunEachFuzzer.toString(),
142
+ fuzzerCorpusPath
143
+ );
144
+ }
145
+
146
+ // Build with code coverage
147
+ println('Building project with coverage sanitizer');
148
+ await setStatusText('end-to-end coverage: building with coverage');
149
+ await buildFuzzersFromWorkspace(
150
+ ossFuzzProjectNameInput.toString(),
151
+ 'coverage',
152
+ true
153
+ );
154
+
155
+ // Run coverage command
156
+ println('Collecting code coverage');
157
+ await setStatusText('end-to-end coverage: collecting coverage');
158
+ const args: Array<string> = [
159
+ extensionConfig.ossFuzzPepositoryWorkPath + '/infra/helper.py',
160
+ 'coverage',
161
+ '--port',
162
+ '',
163
+ '--no-corpus-download',
164
+ ossFuzzProjectNameInput.toString(),
165
+ ];
166
+ await systemSync('python3', args);
167
+ await setStatusText('end-to-end coverage: finished collecting coverage');
168
+ println('Load coverage report with the command:');
169
+ println(
170
+ 'python3 -m http.server 8008 --directory /tmp/oss-fuzz/build/out/' +
171
+ ossFuzzProjectNameInput.toString() +
172
+ '/report/'
173
+ );
174
+
175
+ println('Trying to load code coverage in IDE');
176
+ const allCovPath =
177
+ extensionConfig.ossFuzzPepositoryWorkPath +
178
+ '/build/out/' +
179
+ ossFuzzProjectNameInput.toString() +
180
+ '/textcov_reports/all_cov.json';
181
+ if (fs.existsSync(allCovPath)) {
182
+ const generatedCodeCoverageFile = vscode.Uri.file(allCovPath);
183
+ await loadCoverageIntoWorkspace(context, generatedCodeCoverageFile);
184
+ }
185
+
186
+ await compareLocalToRemoteCoverage(
187
+ context,
188
+ ossFuzzProjectNameInput.toString()
189
+ );
190
+
191
+ return true;
192
+ }
local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFI.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2024 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import {runFuzzIntrospector} from '../fuzzIntrospectorHelper';
18
+
19
+ /**
20
+ * Function for setting up Fuzz Introspector by way of a Python virtual env.
21
+ */
22
+ export async function runFuzzIntrospectorHandler() {
23
+ runFuzzIntrospector();
24
+ }
local-test-tika-full-01-vuln_1/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2023 Google LLC
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ ////////////////////////////////////////////////////////////////////////////////
16
+
17
+ import * as vscode from 'vscode';
18
+
19
+ import {println} from '../logger';
20
+ import {extensionConfig} from '../config';
21
+
22
+ // Set the oss-fuzz path.
23
+ export async function setOssFuzzPath() {
24
+ println('Setting path');
25
+ const newOssFuzzPath = await vscode.window.showInputBox({
26
+ value: '',
27
+ placeHolder: 'Type path',
28
+ });
29
+ if (!newOssFuzzPath) {
30
+ println('Failed getting path');
31
+ return;
32
+ }
33
+
34
+ const fpathh = vscode.Uri.file(newOssFuzzPath);
35
+ let isValid = false;
36
+ try {
37
+ if (await vscode.workspace.fs.readDirectory(fpathh)) {
38
+ println('Is a directory');
39
+ const helperPathURI = vscode.Uri.file(
40
+ newOssFuzzPath + '/infra/helper.py'
41
+ );
42
+ if (await vscode.workspace.fs.readFile(helperPathURI)) {
43
+ println('Found helper file');
44
+ isValid = true;
45
+ }
46
+ isValid = true;
47
+ } else {
48
+ isValid = false;
49
+ }
50
+ } catch {
51
+ isValid = false;
52
+ }
53
+
54
+ if (isValid) {
55
+ extensionConfig.ossFuzzPepositoryWorkPath = newOssFuzzPath;
56
+ } else {
57
+ println('Not setting OSS-Fuzz path');
58
+ }
59
+ }