Kitxuuu commited on
Commit
b4aa2e5
·
verified ·
1 Parent(s): 77c4d44

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. local-test-tika-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc +0 -0
  2. local-test-tika-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc +0 -0
  3. local-test-tika-delta-03/fuzz-tooling/infra/base-images/README.md +6 -0
  4. local-test-tika-delta-03/fuzz-tooling/infra/base-images/aixcc_build_all.sh +59 -0
  5. local-test-tika-delta-03/fuzz-tooling/infra/base-images/all.sh +28 -0
  6. local-test-tika-delta-03/fuzz-tooling/infra/ci/build.py +292 -0
  7. local-test-tika-delta-03/fuzz-tooling/infra/ci/build_test.py +124 -0
  8. local-test-tika-delta-03/fuzz-tooling/infra/ci/requirements.txt +9 -0
  9. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/CHANGELOG +3 -0
  10. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py +113 -0
  11. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/base_runner_utils.py +33 -0
  12. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/build-images.sh +34 -0
  13. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers.py +217 -0
  14. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py +60 -0
  15. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py +40 -0
  16. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py +385 -0
  17. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py +268 -0
  18. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration.py +375 -0
  19. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration_test.py +88 -0
  20. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/docker.py +127 -0
  21. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/docker_test.py +119 -0
  22. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/example_cifuzz.yml +33 -0
  23. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils.py +48 -0
  24. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target.py +408 -0
  25. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py +71 -0
  26. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/get_coverage_test.py +253 -0
  27. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/http_utils_test.py +71 -0
  28. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/logs.py +25 -0
  29. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/requirements.txt +4 -0
  30. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/run_cifuzz.py +89 -0
  31. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py +97 -0
  32. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py +475 -0
  33. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils.py +251 -0
  34. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/test_helpers.py +117 -0
  35. local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/workspace_utils.py +85 -0
  36. local-test-tika-delta-03/fuzz-tooling/infra/tools/hold_back_images.py +128 -0
  37. local-test-tika-delta-03/fuzz-tooling/infra/uploader/Dockerfile +7 -0
  38. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspace.ts +80 -0
  39. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts +49 -0
  40. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdCreateOSSFuzzSetup.ts +28 -0
  41. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDispatcherGenerateClusterfuzzLite.ts +38 -0
  42. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts +71 -0
  43. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdEndToEndCoverage.ts +192 -0
  44. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdReproduceTestcase.ts +167 -0
  45. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFI.ts +24 -0
  46. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupCIFuzz.ts +87 -0
  47. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupFI.ts +24 -0
  48. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTemplate.ts +357 -0
  49. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTestFuzzer.ts +90 -0
  50. local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/fuzzIntrospectorHelper.ts +117 -0
local-test-tika-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc ADDED
Binary file (802 Bytes). View file
 
local-test-tika-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc ADDED
Binary file (3.04 kB). View file
 
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/base-images/aixcc_build_all.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -eux
2
+
3
+ if [ "$1" = "--cache-from" ]; then
4
+ PULL_CACHE=1
5
+ shift
6
+ CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes
7
+ shift
8
+ elif [ "$1" = "--cache-to" ]; then
9
+ PUSH_CACHE=1
10
+ shift
11
+ CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes
12
+ shift
13
+ fi
14
+
15
+ ARG_TAG="$1"
16
+ shift
17
+
18
+ BASE_IMAGES=(
19
+ "ghcr.io/aixcc-finals/base-image infra/base-images/base-image"
20
+ "ghcr.io/aixcc-finals/base-clang infra/base-images/base-clang"
21
+ "ghcr.io/aixcc-finals/base-builder infra/base-images/base-builder"
22
+ "ghcr.io/aixcc-finals/base-builder-go infra/base-images/base-builder-go"
23
+ "ghcr.io/aixcc-finals/base-builder-jvm infra/base-images/base-builder-jvm"
24
+ "ghcr.io/aixcc-finals/base-builder-python infra/base-images/base-builder-python"
25
+ "ghcr.io/aixcc-finals/base-builder-rust infra/base-images/base-builder-rust"
26
+ "ghcr.io/aixcc-finals/base-builder-ruby infra/base-images/base-builder-ruby"
27
+ "ghcr.io/aixcc-finals/base-builder-swift infra/base-images/base-builder-swift"
28
+ "ghcr.io/aixcc-finals/base-runner infra/base-images/base-runner"
29
+ "ghcr.io/aixcc-finals/base-runner-debug infra/base-images/base-runner-debug"
30
+ )
31
+
32
+ for tuple in "${BASE_IMAGES[@]}"; do
33
+ read -r image path <<< "$tuple"
34
+
35
+ if [ "${PULL_CACHE+x}" ]; then
36
+
37
+ docker buildx build \
38
+ --build-arg IMG_TAG="${ARG_TAG}" \
39
+ --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \
40
+ --tag "${image}:${ARG_TAG}" --push "$@" "${path}"
41
+
42
+ elif [ "${PUSH_CACHE+x}" ]; then
43
+
44
+ docker buildx build \
45
+ --build-arg IMG_TAG="${ARG_TAG}" \
46
+ --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \
47
+ --cache-to=type=registry,ref="${image}:${CACHE_TAG}",mode=max \
48
+ --tag "${image}:${ARG_TAG}" --push "$@" "${path}"
49
+
50
+ else
51
+
52
+ docker buildx build \
53
+ --build-arg IMG_TAG="${ARG_TAG}" \
54
+ --tag "${image}:${ARG_TAG}" --push "$@" "${path}"
55
+
56
+ fi
57
+
58
+ done
59
+
local-test-tika-delta-03/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-delta-03/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-delta-03/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-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/CHANGELOG ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Next Release:
2
+
3
+ Improve detection of changed files better by fixing https://github.com/google/oss-fuzz/issues/7011
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/base_runner_utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utilities for scripts from ghcr.io/aixcc-finals/base-runner."""
15
+
16
+ import os
17
+
18
+ import config_utils
19
+
20
+
21
+ def get_env(config, workspace):
22
+ """Returns a dictionary containing the current environment with additional env
23
+ vars set to values needed to run a fuzzer."""
24
+ env = os.environ.copy()
25
+ env['SANITIZER'] = config.sanitizer
26
+ env['FUZZING_LANGUAGE'] = config.language
27
+ env['OUT'] = workspace.out
28
+ env['CIFUZZ'] = 'True'
29
+ env['FUZZING_ENGINE'] = config_utils.DEFAULT_ENGINE
30
+ env['ARCHITECTURE'] = config.architecture
31
+ # Do this so we don't fail in tests.
32
+ env['FUZZER_ARGS'] = '-rss_limit_mb=2560 -timeout=25'
33
+ return env
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module used by CI tools in order to interact with fuzzers. This module helps
15
+ CI tools to build fuzzers."""
16
+
17
+ import logging
18
+ import os
19
+ import sys
20
+
21
+ import affected_fuzz_targets
22
+ import base_runner_utils
23
+ import clusterfuzz_deployment
24
+ import continuous_integration
25
+ import docker
26
+ import logs
27
+ import workspace_utils
28
+
29
+ # pylint: disable=wrong-import-position,import-error
30
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
31
+ import helper
32
+ import utils
33
+
34
+ logs.init()
35
+
36
+
37
+ def check_project_src_path(project_src_path):
38
+ """Returns True if |project_src_path| exists."""
39
+ if not os.path.exists(project_src_path):
40
+ logging.error(
41
+ 'PROJECT_SRC_PATH: %s does not exist. '
42
+ 'Are you mounting it correctly?', project_src_path)
43
+ return False
44
+ return True
45
+
46
+
47
+ # pylint: disable=too-many-arguments
48
+
49
+
50
+ class Builder: # pylint: disable=too-many-instance-attributes
51
+ """Class for fuzzer builders."""
52
+
53
+ def __init__(self, config, ci_system):
54
+ self.config = config
55
+ self.ci_system = ci_system
56
+ self.workspace = workspace_utils.Workspace(config)
57
+ self.workspace.initialize_dir(self.workspace.out)
58
+ self.workspace.initialize_dir(self.workspace.work)
59
+ self.clusterfuzz_deployment = (
60
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
61
+ self.config, self.workspace))
62
+ self.image_repo_path = None
63
+ self.host_repo_path = None
64
+ self.repo_manager = None
65
+
66
+ def build_image_and_checkout_src(self):
67
+ """Builds the project builder image and checkout source code for the patch
68
+ we want to fuzz (if necessary). Returns True on success."""
69
+ result = self.ci_system.prepare_for_fuzzer_build()
70
+ if not result.success:
71
+ return False
72
+ self.image_repo_path = result.image_repo_path
73
+ self.repo_manager = result.repo_manager
74
+ if self.config.output_sarif:
75
+ self.workspace.make_repo_for_sarif(self.repo_manager)
76
+ logging.info('repo_dir: %s.', self.repo_manager.repo_dir)
77
+ self.host_repo_path = self.repo_manager.repo_dir
78
+ return True
79
+
80
+ def build_fuzzers(self):
81
+ """Moves the source code we want to fuzz into the project builder and builds
82
+ the fuzzers from that source code. Returns True on success."""
83
+ docker_args, docker_container = docker.get_base_docker_run_args(
84
+ self.workspace, self.config.sanitizer, self.config.language,
85
+ self.config.architecture, self.config.docker_in_docker)
86
+ if not docker_container:
87
+ docker_args.extend(
88
+ _get_docker_build_fuzzers_args_not_container(self.host_repo_path))
89
+
90
+ build_command = self.ci_system.get_build_command(self.host_repo_path,
91
+ self.image_repo_path)
92
+
93
+ # Set extra environment variables so that they are visible to the build.
94
+ for key in self.config.extra_environment_variables:
95
+ # Don't specify their value in case they get echoed.
96
+ docker_args.extend(['-e', key])
97
+
98
+ docker_args.extend([
99
+ docker.get_project_image_name(self.config.oss_fuzz_project_name),
100
+ '/bin/bash',
101
+ '-c',
102
+ build_command,
103
+ ])
104
+ logging.info('Building with %s sanitizer.', self.config.sanitizer)
105
+
106
+ # TODO(metzman): Stop using helper.docker_run so we can get rid of
107
+ # docker.get_base_docker_run_args and merge its contents into
108
+ # docker.get_base_docker_run_command.
109
+ if not helper.docker_run(docker_args):
110
+ logging.error('Building fuzzers failed.')
111
+ return False
112
+
113
+ return True
114
+
115
+ def upload_build(self):
116
+ """Upload build."""
117
+ if self.config.upload_build:
118
+ self.clusterfuzz_deployment.upload_build(
119
+ self.repo_manager.get_current_commit())
120
+
121
+ return True
122
+
123
+ def check_fuzzer_build(self):
124
+ """Checks the fuzzer build. Returns True on success or if config specifies
125
+ to skip check."""
126
+ if not self.config.bad_build_check:
127
+ return True
128
+
129
+ return check_fuzzer_build(self.config)
130
+
131
+ def build(self):
132
+ """Builds the image, checkouts the source (if needed), builds the fuzzers
133
+ and then removes the unaffectted fuzzers. Returns True on success."""
134
+ methods = [
135
+ self.build_image_and_checkout_src,
136
+ self.build_fuzzers,
137
+ self.remove_unaffected_fuzz_targets,
138
+ self.upload_build,
139
+ self.check_fuzzer_build,
140
+ ]
141
+ for method in methods:
142
+ if not method():
143
+ return False
144
+ return True
145
+
146
+ def remove_unaffected_fuzz_targets(self):
147
+ """Removes the fuzzers unaffected by the patch."""
148
+ if self.config.keep_unaffected_fuzz_targets:
149
+ logging.info('Not removing unaffected fuzz targets.')
150
+ return True
151
+
152
+ logging.info('Removing unaffected fuzz targets.')
153
+ changed_files = self.ci_system.get_changed_code_under_test(
154
+ self.repo_manager)
155
+ affected_fuzz_targets.remove_unaffected_fuzz_targets(
156
+ self.clusterfuzz_deployment, self.workspace.out, changed_files,
157
+ self.image_repo_path)
158
+ return True
159
+
160
+
161
+ def build_fuzzers(config):
162
+ """Builds all of the fuzzers for a specific OSS-Fuzz project.
163
+
164
+ Args:
165
+ config: The configuration object for building fuzzers.
166
+
167
+ Returns:
168
+ True if build succeeded.
169
+ """
170
+ # Do some quick validation.
171
+ if config.project_src_path and not check_project_src_path(
172
+ config.project_src_path):
173
+ return False
174
+
175
+ # Get the builder and then build the fuzzers.
176
+ ci_system = continuous_integration.get_ci(config)
177
+ logging.info('ci_system: %s.', ci_system)
178
+ builder = Builder(config, ci_system)
179
+ return builder.build()
180
+
181
+
182
+ def check_fuzzer_build(config):
183
+ """Checks the integrity of the built fuzzers.
184
+
185
+ Args:
186
+ config: The config object.
187
+
188
+ Returns:
189
+ True if fuzzers pass OSS-Fuzz's build check.
190
+ """
191
+ workspace = workspace_utils.Workspace(config)
192
+ if not os.path.exists(workspace.out):
193
+ logging.error('Invalid out directory: %s.', workspace.out)
194
+ return False
195
+ if not os.listdir(workspace.out):
196
+ logging.error('No fuzzers found in out directory: %s.', workspace.out)
197
+ return False
198
+
199
+ env = base_runner_utils.get_env(config, workspace)
200
+ if config.allowed_broken_targets_percentage is not None:
201
+ env['ALLOWED_BROKEN_TARGETS_PERCENTAGE'] = (
202
+ config.allowed_broken_targets_percentage)
203
+
204
+ stdout, stderr, retcode = utils.execute('test_all.py', env=env)
205
+ print(f'Build check: stdout: {stdout}\nstderr: {stderr}')
206
+ if retcode == 0:
207
+ logging.info('Build check passed.')
208
+ return True
209
+ logging.error('Build check failed.')
210
+ return False
211
+
212
+
213
+ def _get_docker_build_fuzzers_args_not_container(host_repo_path):
214
+ """Returns arguments to the docker build arguments that are needed to use
215
+ |host_repo_path| when the host of the OSS-Fuzz builder container is not
216
+ another container."""
217
+ return ['-v', f'{host_repo_path}:{host_repo_path}']
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Builds fuzzers and runs fuzzers. Entrypoint used for external users"""
15
+ import logging
16
+ import sys
17
+
18
+ import build_fuzzers_entrypoint
19
+ import run_fuzzers_entrypoint
20
+
21
+
22
+ def main():
23
+ """Builds and runs fuzzers for CI tools.
24
+
25
+ NOTE: Any crash report will be in the filepath: $WORKSPACE/out/testcase
26
+ This can be used with GitHub's upload-artifact action to surface the logs.
27
+
28
+ Required environment variables:
29
+ Returns:
30
+ 0 on success or 1 on failure.
31
+ """
32
+ logging.debug("Using cifuzz_combined_entrypoint.")
33
+ result = build_fuzzers_entrypoint.build_fuzzers_entrypoint()
34
+ if result != 0:
35
+ return result
36
+ return run_fuzzers_entrypoint.run_fuzzers_entrypoint()
37
+
38
+
39
+ if __name__ == '__main__':
40
+ sys.exit(main())
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 clusterfuzz_deployment.py"""
15
+
16
+ import os
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import parameterized
21
+ from pyfakefs import fake_filesystem_unittest
22
+
23
+ import clusterfuzz_deployment
24
+ import config_utils
25
+ import test_helpers
26
+ import workspace_utils
27
+
28
+ # NOTE: This integration test relies on
29
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
30
+ EXAMPLE_PROJECT = 'example'
31
+
32
+ # An example fuzzer that triggers an error.
33
+ EXAMPLE_FUZZER = 'example_crash_fuzzer'
34
+
35
+ WORKSPACE = '/workspace'
36
+ EXPECTED_LATEST_BUILD_PATH = os.path.join(WORKSPACE, 'cifuzz-prev-build')
37
+
38
+ # pylint: disable=unused-argument
39
+
40
+
41
+ def _create_config(**kwargs):
42
+ """Creates a config object and then sets every attribute that is a key in
43
+ |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an
44
+ attribute of Config."""
45
+ defaults = {
46
+ 'cfl_platform': 'github',
47
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT,
48
+ 'workspace': WORKSPACE,
49
+ }
50
+ for default_key, default_value in defaults.items():
51
+ if default_key not in kwargs:
52
+ kwargs[default_key] = default_value
53
+
54
+ return test_helpers.create_run_config(**kwargs)
55
+
56
+
57
+ def _create_deployment(**kwargs):
58
+ config = _create_config(**kwargs)
59
+ workspace = workspace_utils.Workspace(config)
60
+ return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace)
61
+
62
+
63
+ class OSSFuzzTest(fake_filesystem_unittest.TestCase):
64
+ """Tests OSSFuzz."""
65
+
66
+ def setUp(self):
67
+ self.setUpPyfakefs()
68
+ self.deployment = _create_deployment()
69
+ self.corpus_dir = os.path.join(self.deployment.workspace.corpora,
70
+ EXAMPLE_FUZZER)
71
+
72
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=True)
73
+ def test_download_corpus(self, mock_download_and_unpack_zip):
74
+ """Tests that we can download a corpus for a valid project."""
75
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
76
+ expected_url = ('https://storage.googleapis.com/example-backup.'
77
+ 'clusterfuzz-external.appspot.com/corpus/libFuzzer/'
78
+ 'example_crash_fuzzer/public.zip')
79
+ call_args, _ = mock_download_and_unpack_zip.call_args
80
+ self.assertEqual(call_args, (expected_url, self.corpus_dir))
81
+ self.assertTrue(os.path.exists(self.corpus_dir))
82
+
83
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=False)
84
+ def test_download_corpus_fail(self, _):
85
+ """Tests that when downloading fails, an empty corpus directory is still
86
+ returned."""
87
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
88
+ self.assertEqual(os.listdir(self.corpus_dir), [])
89
+
90
+ def test_get_latest_build_name(self):
91
+ """Tests that the latest build name can be retrieved from GCS."""
92
+ latest_build_name = self.deployment.get_latest_build_name()
93
+ self.assertTrue(latest_build_name.endswith('.zip'))
94
+ self.assertTrue('address' in latest_build_name)
95
+
96
+ @parameterized.parameterized.expand([
97
+ ('upload_build', ('commit',),
98
+ 'Not uploading latest build because on OSS-Fuzz.'),
99
+ ('upload_corpus', ('target', 'corpus-dir'),
100
+ 'Not uploading corpus because on OSS-Fuzz.'),
101
+ ('upload_crashes', tuple(), 'Not uploading crashes because on OSS-Fuzz.'),
102
+ ])
103
+ def test_noop_methods(self, method, method_args, expected_message):
104
+ """Tests that certain methods are noops for OSS-Fuzz."""
105
+ with mock.patch('logging.info') as mock_info:
106
+ method = getattr(self.deployment, method)
107
+ self.assertIsNone(method(*method_args))
108
+ mock_info.assert_called_with(expected_message)
109
+
110
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=True)
111
+ def test_download_latest_build(self, mock_download_and_unpack_zip):
112
+ """Tests that downloading the latest build works as intended under normal
113
+ circumstances."""
114
+ self.assertEqual(self.deployment.download_latest_build(),
115
+ EXPECTED_LATEST_BUILD_PATH)
116
+ expected_url = ('https://storage.googleapis.com/clusterfuzz-builds/example/'
117
+ 'example-address-202008030600.zip')
118
+ mock_download_and_unpack_zip.assert_called_with(expected_url,
119
+ EXPECTED_LATEST_BUILD_PATH)
120
+
121
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=False)
122
+ def test_download_latest_build_fail(self, _):
123
+ """Tests that download_latest_build returns None when it fails to download a
124
+ build."""
125
+ self.assertIsNone(self.deployment.download_latest_build())
126
+
127
+
128
+ class ClusterFuzzLiteTest(fake_filesystem_unittest.TestCase):
129
+ """Tests for ClusterFuzzLite."""
130
+
131
+ def setUp(self):
132
+ self.setUpPyfakefs()
133
+ self.deployment = _create_deployment(mode='batch',
134
+ oss_fuzz_project_name='',
135
+ cloud_bucket='gs://bucket')
136
+ self.corpus_dir = os.path.join(self.deployment.workspace.corpora,
137
+ EXAMPLE_FUZZER)
138
+
139
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus',
140
+ return_value=True)
141
+ def test_download_corpus(self, mock_download_corpus):
142
+ """Tests that download_corpus works for a valid project."""
143
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
144
+ mock_download_corpus.assert_called_with('example_crash_fuzzer',
145
+ self.corpus_dir)
146
+ self.assertTrue(os.path.exists(self.corpus_dir))
147
+
148
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus',
149
+ side_effect=Exception)
150
+ def test_download_corpus_fail(self, _):
151
+ """Tests that when downloading fails, an empty corpus directory is still
152
+ returned."""
153
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
154
+ self.assertEqual(os.listdir(self.corpus_dir), [])
155
+
156
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build',
157
+ side_effect=[False, True])
158
+ @mock.patch('repo_manager.RepoManager.get_commit_list',
159
+ return_value=['commit1', 'commit2'])
160
+ @mock.patch('continuous_integration.GithubCiMixin.repo_dir',
161
+ return_value='/path/to/repo')
162
+ def test_download_latest_build(self, mock_repo_dir, mock_get_commit_list,
163
+ mock_download_build):
164
+ """Tests that downloading the latest build works as intended under normal
165
+ circumstances."""
166
+ self.assertEqual(self.deployment.download_latest_build(),
167
+ EXPECTED_LATEST_BUILD_PATH)
168
+ expected_artifact_name = 'address-commit2'
169
+ mock_download_build.assert_called_with(expected_artifact_name,
170
+ EXPECTED_LATEST_BUILD_PATH)
171
+
172
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build',
173
+ side_effect=Exception)
174
+ @mock.patch('repo_manager.RepoManager.get_commit_list',
175
+ return_value=['commit1', 'commit2'])
176
+ @mock.patch('continuous_integration.GithubCiMixin.repo_dir',
177
+ return_value='/path/to/repo')
178
+ def test_download_latest_build_fail(self, mock_repo_dir, mock_get_commit_list,
179
+ _):
180
+ """Tests that download_latest_build returns None when it fails to download a
181
+ build."""
182
+ self.assertIsNone(self.deployment.download_latest_build())
183
+
184
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.upload_build')
185
+ def test_upload_build(self, mock_upload_build):
186
+ """Tests that upload_build works as intended."""
187
+ self.deployment.upload_build('commit')
188
+ mock_upload_build.assert_called_with('address-commit',
189
+ '/workspace/build-out')
190
+
191
+
192
+ class NoClusterFuzzDeploymentTest(fake_filesystem_unittest.TestCase):
193
+ """Tests for NoClusterFuzzDeployment."""
194
+
195
+ def setUp(self):
196
+ self.setUpPyfakefs()
197
+ config = test_helpers.create_run_config(workspace=WORKSPACE,
198
+ cfl_platform='other',
199
+ filestore='no_filestore',
200
+ no_clusterfuzz_deployment=True)
201
+ workspace = workspace_utils.Workspace(config)
202
+ self.deployment = clusterfuzz_deployment.get_clusterfuzz_deployment(
203
+ config, workspace)
204
+
205
+ self.corpus_dir = os.path.join(workspace.corpora, EXAMPLE_FUZZER)
206
+
207
+ @mock.patch('logging.info')
208
+ def test_download_corpus(self, mock_info):
209
+ """Tests that download corpus returns the path to the empty corpus
210
+ directory."""
211
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
212
+ mock_info.assert_called_with(
213
+ 'Not downloading corpus because no ClusterFuzz deployment.')
214
+ self.assertTrue(os.path.exists(self.corpus_dir))
215
+
216
+ @parameterized.parameterized.expand([
217
+ ('upload_build', ('commit',),
218
+ 'Not uploading latest build because no ClusterFuzz deployment.'),
219
+ ('upload_corpus', ('target', 'corpus-dir'),
220
+ 'Not uploading corpus because no ClusterFuzz deployment.'),
221
+ ('upload_crashes', tuple(),
222
+ 'Not uploading crashes because no ClusterFuzz deployment.'),
223
+ ('download_latest_build', tuple(),
224
+ 'Not downloading latest build because no ClusterFuzz deployment.')
225
+ ])
226
+ def test_noop_methods(self, method, method_args, expected_message):
227
+ """Tests that certain methods are noops for NoClusterFuzzDeployment."""
228
+ with mock.patch('logging.info') as mock_info:
229
+ method = getattr(self.deployment, method)
230
+ self.assertIsNone(method(*method_args))
231
+ mock_info.assert_called_with(expected_message)
232
+
233
+
234
+ class GetClusterFuzzDeploymentTest(unittest.TestCase):
235
+ """Tests for get_clusterfuzz_deployment."""
236
+
237
+ def setUp(self):
238
+ test_helpers.patch_environ(self)
239
+ os.environ['GITHUB_REPOSITORY'] = 'owner/myproject'
240
+
241
+ @parameterized.parameterized.expand([
242
+ (config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI,
243
+ clusterfuzz_deployment.OSSFuzz),
244
+ (config_utils.BaseConfig.Platform.INTERNAL_GITHUB,
245
+ clusterfuzz_deployment.OSSFuzz),
246
+ (config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI,
247
+ clusterfuzz_deployment.ClusterFuzzLite),
248
+ (config_utils.BaseConfig.Platform.EXTERNAL_GITHUB,
249
+ clusterfuzz_deployment.ClusterFuzzLite),
250
+ ])
251
+ def test_get_clusterfuzz_deployment(self, platform, expected_deployment_cls):
252
+ """Tests that get_clusterfuzz_deployment returns the correct value."""
253
+ with mock.patch('config_utils.BaseConfig.platform',
254
+ return_value=platform,
255
+ new_callable=mock.PropertyMock):
256
+ with mock.patch('filestore_utils.get_filestore', return_value=None):
257
+ with mock.patch('platform_config.github._get_event_data',
258
+ return_value={}):
259
+ config = _create_config()
260
+ workspace = workspace_utils.Workspace(config)
261
+
262
+ self.assertIsInstance(
263
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
264
+ config, workspace), expected_deployment_cls)
265
+
266
+
267
+ if __name__ == '__main__':
268
+ unittest.main()
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Implementations for various CI systems."""
15
+
16
+ import os
17
+ import collections
18
+ import sys
19
+ import logging
20
+
21
+ # pylint: disable=wrong-import-position,import-error
22
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
23
+ import build_specified_commit
24
+ import docker
25
+ import helper
26
+ import repo_manager
27
+ import retry
28
+ import utils
29
+ import workspace_utils
30
+
31
+ # pylint: disable=too-few-public-methods
32
+
33
+ BuildPreparationResult = collections.namedtuple(
34
+ 'BuildPreparationResult', ['success', 'image_repo_path', 'repo_manager'])
35
+
36
+ _IMAGE_BUILD_TRIES = 3
37
+ _IMAGE_BUILD_BACKOFF = 2
38
+
39
+
40
+ def fix_git_repo_for_diff(repo_manager_obj):
41
+ """Fixes git repos cloned by the "checkout" action so that diffing works on
42
+ them."""
43
+ command = [
44
+ 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD',
45
+ 'refs/remotes/origin/master'
46
+ ]
47
+ return utils.execute(command, location=repo_manager_obj.repo_dir)
48
+
49
+
50
+ class BaseCi:
51
+ """Class representing common CI functionality."""
52
+
53
+ def __init__(self, config):
54
+ self.config = config
55
+ self.workspace = workspace_utils.Workspace(config)
56
+ self._repo_dir = None
57
+
58
+ @property
59
+ def repo_dir(self):
60
+ """Returns the source repo path, if it has been checked out. None is
61
+ returned otherwise."""
62
+ raise NotImplementedError('Child class must implement method.')
63
+
64
+ def prepare_for_fuzzer_build(self):
65
+ """Builds the fuzzer builder image and gets the source code we need to
66
+ fuzz."""
67
+ raise NotImplementedError('Child class must implement method.')
68
+
69
+ def get_diff_base(self):
70
+ """Returns the base to diff against with git to get the change under
71
+ test."""
72
+ if self.config.base_ref:
73
+ logging.debug('Diffing against base_ref: %s.', self.config.base_ref)
74
+ return self.config.base_ref
75
+ if self.config.base_commit:
76
+ logging.debug('Diffing against base_commit: %s.', self.config.base_commit)
77
+ return self.config.base_commit
78
+ # TODO(metzman): Do we want this at all? What purpose does it serve? I guess
79
+ # it is a decent fallback when there is no base_commit or base_ref.
80
+ logging.debug('Diffing against origin.')
81
+ return 'origin'
82
+
83
+ def get_changed_code_under_test(self, repo_manager_obj):
84
+ """Returns the changed files that need to be tested."""
85
+ if self.config.base_ref:
86
+ repo_manager_obj.fetch_branch(self.config.base_ref)
87
+ fix_git_repo_for_diff(repo_manager_obj)
88
+ base = self.get_diff_base()
89
+ logging.info('Diffing against %s.', base)
90
+ # git diff <commit>... is equivalent to
91
+ # git diff $(git merge-base <commit> HEAD)
92
+ return repo_manager_obj.get_git_diff(base + '...')
93
+
94
+ def get_build_command(self, host_repo_path, image_repo_path):
95
+ """Returns the command for building the project that is run inside the
96
+ project builder container."""
97
+ raise NotImplementedError('Child class must implement method.')
98
+
99
+ def _build_external_project_docker_image(self, manager):
100
+ """Helper for child classes that builds an external project's docker image.
101
+ Returns a BuildPreparationResult indicating failure or success."""
102
+ build_integration_abs_path = os.path.join(
103
+ manager.repo_dir, self.config.build_integration_path)
104
+ if not build_external_project_docker_image(manager.repo_dir,
105
+ build_integration_abs_path):
106
+ logging.error('Failed to build external project.')
107
+ return get_build_preparation_failure()
108
+ image_repo_path = os.path.join('/src', self.config.project_repo_name)
109
+ return BuildPreparationResult(success=True,
110
+ image_repo_path=image_repo_path,
111
+ repo_manager=manager)
112
+
113
+ def _make_repo_storage_dir(self):
114
+ os.makedirs(self.workspace.repo_storage, exist_ok=True)
115
+
116
+ def _clone_repo_and_checkout(self, repo_url, repo_name):
117
+ """Helper for child classes that clones the git repo specified by |repo_url|
118
+ to |repo_name|, checks out the specified commit, and returns the
119
+ |manager|."""
120
+ self._make_repo_storage_dir()
121
+ # Checkout project's repo in the shared volume.
122
+ manager = repo_manager.clone_repo_and_get_manager(
123
+ repo_url,
124
+ self.workspace.repo_storage,
125
+ repo_name=repo_name,
126
+ username=self.config.actor,
127
+ password=self.config.token)
128
+ self._checkout_specified_commit(manager)
129
+ return manager
130
+
131
+ def _checkout_specified_commit(self, manager):
132
+ checkout_specified_commit(manager, self.config.pr_ref, self.config.git_sha)
133
+
134
+ def _detect_main_repo(self):
135
+ """Helper for child classes that detects the main repo and returns a tuple
136
+ containing the inffered url and path to the repo in the image."""
137
+ inferred_url, image_repo_path = build_specified_commit.detect_main_repo(
138
+ self.config.oss_fuzz_project_name,
139
+ repo_name=self.config.project_repo_name)
140
+ if not inferred_url or not image_repo_path:
141
+ logging.error('Could not detect repo.')
142
+ return inferred_url, image_repo_path
143
+
144
+ def _create_repo_manager_for_project_src_path(self):
145
+ """Returns a repo manager for |project_src_path|."""
146
+ return repo_manager.RepoManager(self.config.project_src_path)
147
+
148
+
149
+ def get_build_command():
150
+ """Returns the command to build the project inside the project builder
151
+ container."""
152
+ return 'compile'
153
+
154
+
155
+ def get_replace_repo_and_build_command(host_repo_path, image_repo_path):
156
+ """Returns the command to replace the repo located at |image_repo_path| with
157
+ |host_repo_path| and build the project inside the project builder
158
+ container."""
159
+ rm_path = os.path.join(image_repo_path, '*')
160
+ image_src_path = os.path.dirname(image_repo_path)
161
+ build_command = get_build_command()
162
+ command = (f'cd / && rm -rf {rm_path} && cp -r {host_repo_path} '
163
+ f'{image_src_path} && cd - && {build_command}')
164
+ return command
165
+
166
+
167
+ def get_ci(config):
168
+ """Determines what kind of CI is being used and returns the object
169
+ representing that system."""
170
+
171
+ if config.platform == config.Platform.EXTERNAL_GENERIC_CI:
172
+ # Non-OSS-Fuzz projects must bring their own source and their own build
173
+ # integration (which is relative to that source).
174
+ return ExternalGeneric(config)
175
+ if config.platform == config.Platform.EXTERNAL_GITHUB:
176
+ # Non-OSS-Fuzz projects must bring their own source and their own build
177
+ # integration (which is relative to that source).
178
+ return ExternalGithub(config)
179
+
180
+ if config.platform == config.Platform.INTERNAL_GENERIC_CI:
181
+ # Builds of OSS-Fuzz projects not hosted on Github must bring their own
182
+ # source since the checkout logic CIFuzz implements is github-specific.
183
+ # TODO(metzman): Consider moving Github-actions builds of OSS-Fuzz projects
184
+ # to this system to reduce implementation complexity.
185
+ return InternalGeneric(config)
186
+
187
+ return InternalGithub(config)
188
+
189
+
190
+ def checkout_specified_commit(repo_manager_obj, pr_ref, git_sha):
191
+ """Checks out the specified commit or pull request using
192
+ |repo_manager_obj|."""
193
+ try:
194
+ if pr_ref:
195
+ repo_manager_obj.checkout_pr(pr_ref)
196
+ else:
197
+ repo_manager_obj.checkout_commit(git_sha)
198
+ except (RuntimeError, ValueError):
199
+ logging.error(
200
+ 'Can not check out requested state %s. '
201
+ 'Using current repo state.', pr_ref or git_sha)
202
+
203
+
204
+ class GithubCiMixin:
205
+ """Mixin for Github based CI systems."""
206
+
207
+ def __init__(self, config):
208
+ super().__init__(config)
209
+ # Unlike in other classes, here _repo_dir is the parent directory of the
210
+ # repo, not its actual directory.
211
+ self._repo_dir = self.workspace.repo_storage
212
+
213
+ @property
214
+ def repo_dir(self):
215
+ """Returns the source repo path, if it has been checked out. None is
216
+ returned otherwise."""
217
+ if not os.path.exists(self._repo_dir):
218
+ logging.warning('Repo dir: %s does not exist.', self._repo_dir)
219
+ return None
220
+
221
+ # Note: this assumes there is only one repo checked out here.
222
+ listing = os.listdir(self._repo_dir)
223
+ if len(listing) != 1:
224
+ raise RuntimeError('Invalid repo directory.')
225
+
226
+ repo_path = os.path.join(self._repo_dir, listing[0])
227
+ if not os.path.isdir(repo_path):
228
+ raise RuntimeError('Repo is not a directory.')
229
+
230
+ return repo_path
231
+
232
+
233
+ class InternalGithub(GithubCiMixin, BaseCi):
234
+ """Class representing CI for an OSS-Fuzz project on Github Actions."""
235
+
236
+ def _copy_repo_from_image(self, image_repo_path):
237
+ self._make_repo_storage_dir()
238
+ repo_name = os.path.basename(image_repo_path)
239
+ host_repo_path = os.path.join(self._repo_dir, repo_name)
240
+ bash_command = f'cp -r {image_repo_path} {host_repo_path}'
241
+ docker_args, _ = docker.get_base_docker_run_args(
242
+ self.workspace, self.config.sanitizer, self.config.language,
243
+ self.config.architecture, self.config.docker_in_docker)
244
+ docker_args.extend([
245
+ docker.get_project_image_name(self.config.oss_fuzz_project_name),
246
+ '/bin/bash', '-c', bash_command
247
+ ])
248
+ if not helper.docker_run(docker_args):
249
+ raise RuntimeError('Failed to copy repo.')
250
+ return repo_manager.RepoManager(host_repo_path)
251
+
252
+ def prepare_for_fuzzer_build(self):
253
+ """Builds the fuzzer builder image, checks out the pull request/commit and
254
+ returns the BuildPreparationResult."""
255
+ logging.info('InternalGithub: preparing for fuzzer build.')
256
+ assert self.config.pr_ref or self.config.git_sha
257
+ # _detect_main_repo builds the image as a side effect.
258
+ _, image_repo_path = self._detect_main_repo()
259
+ if not image_repo_path:
260
+ return get_build_preparation_failure()
261
+
262
+ # Use the same name used in the docker image so we can overwrite it.
263
+ manager = self._copy_repo_from_image(image_repo_path)
264
+ self._checkout_specified_commit(manager)
265
+ return BuildPreparationResult(success=True,
266
+ image_repo_path=image_repo_path,
267
+ repo_manager=manager)
268
+
269
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
270
+ """Returns the command for building the project that is run inside the
271
+ project builder container. Command also replaces |image_repo_path| with
272
+ |host_repo_path|."""
273
+ return get_replace_repo_and_build_command(host_repo_path, image_repo_path)
274
+
275
+
276
+ def get_build_preparation_failure():
277
+ """Returns a BuildPreparationResult indicating failure."""
278
+ return BuildPreparationResult(success=False,
279
+ image_repo_path=None,
280
+ repo_manager=None)
281
+
282
+
283
+ class InternalGeneric(BaseCi):
284
+ """Class representing CI for an OSS-Fuzz project on a CI other than Github
285
+ actions."""
286
+
287
+ def __init__(self, config):
288
+ super().__init__(config)
289
+ self._repo_dir = config.project_src_path
290
+
291
+ @property
292
+ def repo_dir(self):
293
+ """Returns the source repo path, if it has been checked out. None is
294
+ returned otherwise."""
295
+ return self._repo_dir
296
+
297
+ def prepare_for_fuzzer_build(self):
298
+ """Builds the project builder image for an OSS-Fuzz project outside of
299
+ GitHub actions. Returns the repo_manager. Does not checkout source code
300
+ since external projects are expected to bring their own source code to
301
+ CIFuzz."""
302
+ logging.info('InternalGeneric: preparing for fuzzer build.')
303
+ # detect_main_repo builds the image as a side effect.
304
+ _, image_repo_path = self._detect_main_repo()
305
+
306
+ if not image_repo_path:
307
+ return get_build_preparation_failure()
308
+
309
+ manager = self._create_repo_manager_for_project_src_path()
310
+ return BuildPreparationResult(success=True,
311
+ image_repo_path=image_repo_path,
312
+ repo_manager=manager)
313
+
314
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
315
+ """Returns the command for building the project that is run inside the
316
+ project builder container. Command also replaces |image_repo_path| with
317
+ |host_repo_path|."""
318
+ return get_replace_repo_and_build_command(host_repo_path, image_repo_path)
319
+
320
+
321
+ @retry.wrap(_IMAGE_BUILD_TRIES, _IMAGE_BUILD_BACKOFF)
322
+ def build_external_project_docker_image(project_src, build_integration_path):
323
+ """Builds the project builder image for an external (non-OSS-Fuzz) project.
324
+ Returns True on success."""
325
+ dockerfile_path = os.path.join(build_integration_path, 'Dockerfile')
326
+ command = [
327
+ '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f', dockerfile_path, project_src
328
+ ]
329
+ return helper.docker_build(command)
330
+
331
+
332
+ class ExternalGeneric(BaseCi):
333
+ """CI implementation for generic CI for external (non-OSS-Fuzz) projects."""
334
+
335
+ def __init__(self, config):
336
+ super().__init__(config)
337
+ self._repo_dir = config.project_src_path
338
+
339
+ @property
340
+ def repo_dir(self):
341
+ """Returns the source repo path, if it has been checked out. None is
342
+ returned otherwise."""
343
+ return self._repo_dir
344
+
345
+ def prepare_for_fuzzer_build(self):
346
+ logging.info('ExternalGeneric: preparing for fuzzer build.')
347
+ manager = self._create_repo_manager_for_project_src_path()
348
+ return self._build_external_project_docker_image(manager)
349
+
350
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
351
+ """Returns the command for building the project that is run inside the
352
+ project builder container."""
353
+ return get_build_command()
354
+
355
+
356
+ class ExternalGithub(GithubCiMixin, BaseCi):
357
+ """Class representing CI for a non-OSS-Fuzz project on Github Actions."""
358
+
359
+ def prepare_for_fuzzer_build(self):
360
+ """Builds the project builder image for a non-OSS-Fuzz project on GitHub
361
+ actions. Sets the repo manager. Does not checkout source code since external
362
+ projects are expected to bring their own source code to CIFuzz. Returns True
363
+ on success."""
364
+ logging.info('ExternalGithub: preparing for fuzzer build.')
365
+ # Checkout before building, so we don't need to rely on copying the source
366
+ # from the image.
367
+ # TODO(metzman): Figure out if we want second copy at all.
368
+ manager = self._clone_repo_and_checkout(self.config.git_url,
369
+ self.config.project_repo_name)
370
+ return self._build_external_project_docker_image(manager)
371
+
372
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
373
+ """Returns the command for building the project that is run inside the
374
+ project builder container."""
375
+ return get_build_command()
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration_test.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 continuous_integration_module."""
15
+ import os
16
+ import sys
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import continuous_integration
21
+ import docker
22
+
23
+ # pylint: disable=wrong-import-position,import-error
24
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
25
+
26
+ import repo_manager
27
+
28
+ # pylint: disable=no-self-use
29
+
30
+
31
+ class FixGitRepoForDiffTest(unittest.TestCase):
32
+ """Tests for fix_git_repo_for_diff."""
33
+
34
+ @mock.patch('utils.execute')
35
+ def test_fix_git_repo_for_diff(self, mock_execute):
36
+ """Tests that fix_git_repo_for_diff works as intended."""
37
+ repo_dir = '/dir'
38
+ repo_manager_obj = repo_manager.RepoManager(repo_dir)
39
+ continuous_integration.fix_git_repo_for_diff(repo_manager_obj)
40
+ expected_command = [
41
+ 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD',
42
+ 'refs/remotes/origin/master'
43
+ ]
44
+
45
+ mock_execute.assert_called_with(expected_command, location=repo_dir)
46
+
47
+
48
+ class GetBuildCommand(unittest.TestCase):
49
+ """Tests for get_build_command."""
50
+
51
+ def test_build_command(self):
52
+ """Tests that get_build_command works as intended."""
53
+ self.assertEqual(continuous_integration.get_build_command(), 'compile')
54
+
55
+
56
+ class GetReplaceRepoAndBuildCommand(unittest.TestCase):
57
+ """Tests for get_replace_repo_and_build_command."""
58
+
59
+ def test_get_replace_repo_and_build_command(self):
60
+ """Tests that get_replace_repo_and_build_command works as intended."""
61
+ host_repo_path = '/path/on/host/to/repo'
62
+ image_repo_path = '/src/repo'
63
+ command = continuous_integration.get_replace_repo_and_build_command(
64
+ host_repo_path, image_repo_path)
65
+ expected_command = ('cd / && rm -rf /src/repo/* && '
66
+ 'cp -r /path/on/host/to/repo /src && cd - '
67
+ '&& compile')
68
+ self.assertEqual(command, expected_command)
69
+
70
+
71
+ class BuildExternalProjetDockerImage(unittest.TestCase):
72
+ """Tests for build_external_project_docker_image."""
73
+
74
+ @mock.patch('helper.docker_build')
75
+ def test_build_external_project_docker_image(self, mock_docker_build):
76
+ """Tests that build_external_project_docker_image works as intended."""
77
+ build_integration_path = '.clusterfuzzlite'
78
+ project_src = '/path/to/project/src'
79
+ continuous_integration.build_external_project_docker_image(
80
+ project_src, build_integration_path)
81
+
82
+ mock_docker_build.assert_called_with([
83
+ '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f',
84
+ os.path.join('.clusterfuzzlite', 'Dockerfile'), project_src
85
+ ])
86
+
87
+
88
+ # TODO(metzman): Write tests for the rest of continuous_integration.py.
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/docker.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 docker."""
15
+ import logging
16
+ import os
17
+ import sys
18
+ import uuid
19
+
20
+ # pylint: disable=wrong-import-position,import-error
21
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+
23
+ import constants
24
+ import utils
25
+ import environment
26
+
27
+ BASE_BUILDER_TAG = 'ghcr.io/aixcc-finals/base-builder'
28
+ PROJECT_TAG_PREFIX = 'gcr.io/oss-fuzz/'
29
+
30
+ # Default fuzz configuration.
31
+ _DEFAULT_DOCKER_RUN_ARGS = [
32
+ '-e', 'FUZZING_ENGINE=' + constants.DEFAULT_ENGINE, '-e', 'CIFUZZ=True'
33
+ ]
34
+
35
+ UNIQUE_ID_SUFFIX = '-' + uuid.uuid4().hex
36
+
37
+ # TODO(metzman): Make run_fuzzers able to delete this image.
38
+ EXTERNAL_PROJECT_IMAGE = 'external-cfl-project' + UNIQUE_ID_SUFFIX
39
+
40
+ _DEFAULT_DOCKER_RUN_COMMAND = [
41
+ 'docker',
42
+ 'run',
43
+ '--rm',
44
+ '--privileged',
45
+ ]
46
+
47
+
48
+ def get_docker_env_vars(env_mapping):
49
+ """Returns a list of docker arguments that sets each key in |env_mapping| as
50
+ an env var and the value of that key in |env_mapping| as the value."""
51
+ env_var_args = []
52
+ for env_var, env_var_val in env_mapping.items():
53
+ env_var_args.extend(['-e', f'{env_var}={env_var_val}'])
54
+ return env_var_args
55
+
56
+
57
+ def get_project_image_name(project):
58
+ """Returns the name of the project builder image for |project_name|."""
59
+ # TODO(jonathanmetzman): We may need unique names to support parallel fuzzing
60
+ # for CIFuzz (like CFL supports). Don't do this for now because no one has
61
+ # asked for it and build_specified_commit would need to be modified to support
62
+ # this.
63
+ if project:
64
+ return PROJECT_TAG_PREFIX + project
65
+
66
+ return EXTERNAL_PROJECT_IMAGE
67
+
68
+
69
+ def delete_images(images):
70
+ """Deletes |images|."""
71
+ command = ['docker', 'rmi', '-f'] + images
72
+ utils.execute(command)
73
+ utils.execute(['docker', 'builder', 'prune', '-f'])
74
+
75
+
76
+ def get_base_docker_run_args(workspace,
77
+ sanitizer=constants.DEFAULT_SANITIZER,
78
+ language=constants.DEFAULT_LANGUAGE,
79
+ architecture=constants.DEFAULT_ARCHITECTURE,
80
+ docker_in_docker=False):
81
+ """Returns arguments that should be passed to every invocation of 'docker
82
+ run'."""
83
+ docker_args = _DEFAULT_DOCKER_RUN_ARGS.copy()
84
+ env_mapping = {
85
+ 'SANITIZER': sanitizer,
86
+ 'ARCHITECTURE': architecture,
87
+ 'FUZZING_LANGUAGE': language,
88
+ 'OUT': workspace.out
89
+ }
90
+ docker_args += get_docker_env_vars(env_mapping)
91
+ docker_container = environment.get('CFL_CONTAINER_ID',
92
+ utils.get_container_name())
93
+ logging.info('Docker container: %s.', docker_container)
94
+ if docker_container and not docker_in_docker:
95
+ # Don't map specific volumes if in a docker container, it breaks when
96
+ # running a sibling container.
97
+ docker_args += ['--volumes-from', docker_container]
98
+ else:
99
+ docker_args += _get_args_mapping_host_path_to_container(workspace.workspace)
100
+ return docker_args, docker_container
101
+
102
+
103
+ def get_base_docker_run_command(workspace,
104
+ sanitizer=constants.DEFAULT_SANITIZER,
105
+ language=constants.DEFAULT_LANGUAGE,
106
+ architecture=constants.DEFAULT_ARCHITECTURE,
107
+ docker_in_docker=False):
108
+ """Returns part of the command that should be used everytime 'docker run' is
109
+ invoked."""
110
+ docker_args, docker_container = get_base_docker_run_args(
111
+ workspace,
112
+ sanitizer,
113
+ language,
114
+ architecture,
115
+ docker_in_docker=docker_in_docker)
116
+ command = _DEFAULT_DOCKER_RUN_COMMAND.copy() + docker_args
117
+ return command, docker_container
118
+
119
+
120
+ def _get_args_mapping_host_path_to_container(host_path, container_path=None):
121
+ """Get arguments to docker run that will map |host_path| a path on the host to
122
+ a path in the container. If |container_path| is specified, that path is mapped
123
+ to. If not, then |host_path| is mapped to itself in the container."""
124
+ # WARNING: Do not use this function when running in production (and
125
+ # --volumes-from) is used for mapping volumes. It will break production.
126
+ container_path = host_path if container_path is None else container_path
127
+ return ['-v', f'{host_path}:{container_path}']
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/docker_test.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 the functionality of the docker module."""
15
+ import unittest
16
+ from unittest import mock
17
+
18
+ import docker
19
+ import test_helpers
20
+ import workspace_utils
21
+
22
+ CONTAINER_NAME = 'example-container'
23
+ config = test_helpers.create_run_config(oss_fuzz_project_name='project',
24
+ workspace='/workspace')
25
+ config.workspace = '/workspace'
26
+ WORKSPACE = workspace_utils.Workspace(config)
27
+ SANITIZER = 'example-sanitizer'
28
+ LANGUAGE = 'example-language'
29
+
30
+
31
+ class GetProjectImageTest(unittest.TestCase):
32
+ """Tests for get_project_image."""
33
+
34
+ def test_get_project_image(self):
35
+ """Tests that get_project_image_name works as intended."""
36
+ project = 'my-project'
37
+ self.assertEqual(docker.get_project_image_name(project),
38
+ 'gcr.io/oss-fuzz/my-project')
39
+
40
+
41
+ class GetDeleteImagesTest(unittest.TestCase):
42
+ """Tests for delete_images."""
43
+
44
+ @mock.patch('utils.execute')
45
+ def test_delete_images(self, mock_execute): # pylint: disable=no-self-use
46
+ """Tests that get_project_image_name works as intended."""
47
+ images = ['image']
48
+ docker.delete_images(images)
49
+ expected_calls = [
50
+ mock.call(['docker', 'rmi', '-f'] + images),
51
+ mock.call(['docker', 'builder', 'prune', '-f'])
52
+ ]
53
+
54
+ mock_execute.assert_has_calls(expected_calls)
55
+
56
+
57
+ class GetBaseDockerRunArgsTest(unittest.TestCase):
58
+ """Tests get_base_docker_run_args."""
59
+
60
+ @mock.patch('utils.get_container_name', return_value=CONTAINER_NAME)
61
+ def test_get_base_docker_run_args_container(self, _):
62
+ """Tests that get_base_docker_run_args works as intended when inside a
63
+ container."""
64
+ docker_args, docker_container = docker.get_base_docker_run_args(
65
+ WORKSPACE, SANITIZER, LANGUAGE)
66
+ self.assertEqual(docker_container, CONTAINER_NAME)
67
+ expected_docker_args = []
68
+ expected_docker_args = [
69
+ '-e',
70
+ 'FUZZING_ENGINE=libfuzzer',
71
+ '-e',
72
+ 'CIFUZZ=True',
73
+ '-e',
74
+ f'SANITIZER={SANITIZER}',
75
+ '-e',
76
+ 'ARCHITECTURE=x86_64',
77
+ '-e',
78
+ f'FUZZING_LANGUAGE={LANGUAGE}',
79
+ '-e',
80
+ f'OUT={WORKSPACE.out}',
81
+ '--volumes-from',
82
+ CONTAINER_NAME,
83
+ ]
84
+ self.assertEqual(docker_args, expected_docker_args)
85
+
86
+ @mock.patch('utils.get_container_name', return_value=None)
87
+ def test_get_base_docker_run_args_no_container(self, _):
88
+ """Tests that get_base_docker_run_args works as intended when not inside a
89
+ container."""
90
+ docker_args, docker_container = docker.get_base_docker_run_args(
91
+ WORKSPACE, SANITIZER, LANGUAGE)
92
+ self.assertEqual(docker_container, None)
93
+ expected_docker_args = [
94
+ '-e', 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e',
95
+ f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e',
96
+ f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v',
97
+ f'{WORKSPACE.workspace}:{WORKSPACE.workspace}'
98
+ ]
99
+ self.assertEqual(docker_args, expected_docker_args)
100
+
101
+
102
+ class GetBaseDockerRunCommandTest(unittest.TestCase):
103
+ """Tests get_base_docker_run_args."""
104
+
105
+ @mock.patch('utils.get_container_name', return_value=None)
106
+ def test_get_base_docker_run_command_no_container(self, _):
107
+ """Tests that get_base_docker_run_args works as intended when not inside a
108
+ container."""
109
+ docker_args, docker_container = docker.get_base_docker_run_command(
110
+ WORKSPACE, SANITIZER, LANGUAGE)
111
+ self.assertEqual(docker_container, None)
112
+ expected_docker_command = [
113
+ 'docker', 'run', '--rm', '--privileged', '-e',
114
+ 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e',
115
+ f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e',
116
+ f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v',
117
+ f'{WORKSPACE.workspace}:{WORKSPACE.workspace}'
118
+ ]
119
+ self.assertEqual(docker_args, expected_docker_command)
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/example_cifuzz.yml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CIFuzz
2
+ on: [pull_request]
3
+ permissions: {}
4
+ jobs:
5
+ Fuzzing:
6
+ runs-on: ubuntu-latest
7
+ permissions:
8
+ security-events: write
9
+ steps:
10
+ - name: Build Fuzzers
11
+ id: build
12
+ uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master
13
+ with:
14
+ oss-fuzz-project-name: 'example'
15
+ - name: Run Fuzzers
16
+ uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master
17
+ with:
18
+ oss-fuzz-project-name: 'example'
19
+ fuzz-seconds: 600
20
+ output-sarif: true
21
+ - name: Upload Crash
22
+ uses: actions/upload-artifact@v3
23
+ if: failure() && steps.build.outcome == 'success'
24
+ with:
25
+ name: artifacts
26
+ path: ./out/artifacts
27
+ - name: Upload Sarif
28
+ if: always() && steps.build.outcome == 'success'
29
+ uses: github/codeql-action/upload-sarif@v2
30
+ with:
31
+ # Path to SARIF file relative to the root of the repository
32
+ sarif_file: cifuzz-sarif/results.sarif
33
+ checkout_path: cifuzz-sarif
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """External filestore interface. Cannot be depended on by filestore code."""
15
+ import filestore
16
+ import filestore.filesystem
17
+ import filestore.git
18
+ import filestore.github_actions
19
+ import filestore.gsutil
20
+ import filestore.no_filestore
21
+ import filestore.gitlab
22
+
23
+ FILESTORE_MAPPING = {
24
+ 'filesystem': filestore.filesystem.FilesystemFilestore,
25
+ 'gsutil': filestore.gsutil.GSUtilFilestore,
26
+ 'github-actions': filestore.github_actions.GithubActionsFilestore,
27
+ 'git': filestore.git.GitFilestore,
28
+ # TODO(metzman): Change to "no-filestore"
29
+ 'no_filestore': filestore.no_filestore.NoFilestore,
30
+ 'gitlab': filestore.gitlab.GitlabFilestore,
31
+ }
32
+
33
+
34
+ def get_filestore(config):
35
+ """Returns the correct filestore object based on the platform in |config|.
36
+ Raises an exception if there is no correct filestore for the platform."""
37
+ if config.platform == config.Platform.EXTERNAL_GITHUB:
38
+ ci_filestore = filestore.github_actions.GithubActionsFilestore(config)
39
+ if not config.git_store_repo:
40
+ return ci_filestore
41
+
42
+ return filestore.git.GitFilestore(config, ci_filestore)
43
+
44
+ filestore_cls = FILESTORE_MAPPING.get(config.filestore)
45
+ if filestore_cls is None:
46
+ raise filestore.FilestoreError(
47
+ f'Filestore: {config.filestore} doesn\'t exist.')
48
+ return filestore_cls(config)
local-test-tika-delta-03/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-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/get_coverage_test.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for get_coverage.py"""
15
+ import os
16
+ import json
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import parameterized
21
+ from pyfakefs import fake_filesystem_unittest
22
+ import pytest
23
+
24
+ import get_coverage
25
+
26
+ # pylint: disable=protected-access
27
+
28
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
29
+ 'test_data')
30
+
31
+ PROJECT_NAME = 'curl'
32
+ REPO_PATH = '/src/curl'
33
+ FUZZ_TARGET = 'curl_fuzzer'
34
+ PROJECT_COV_JSON_FILENAME = 'example_curl_cov.json'
35
+ FUZZ_TARGET_COV_JSON_FILENAME = 'example_curl_fuzzer_cov.json'
36
+ INVALID_TARGET = 'not-a-fuzz-target'
37
+
38
+ with open(os.path.join(TEST_DATA_PATH,
39
+ PROJECT_COV_JSON_FILENAME),) as cov_file_handle:
40
+ PROJECT_COV_INFO = json.loads(cov_file_handle.read())
41
+
42
+
43
+ class GetOssFuzzFuzzerStatsDirUrlTest(unittest.TestCase):
44
+ """Tests _get_oss_fuzz_fuzzer_stats_dir_url."""
45
+
46
+ @mock.patch('http_utils.get_json_from_url',
47
+ return_value={
48
+ 'fuzzer_stats_dir':
49
+ 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303'
50
+ })
51
+ def test_get_valid_project(self, mock_get_json_from_url):
52
+ """Tests that a project's coverage report can be downloaded and parsed.
53
+
54
+ NOTE: This test relies on the PROJECT_NAME repo's coverage report.
55
+ The "example" project was not used because it has no coverage reports.
56
+ """
57
+ result = get_coverage._get_oss_fuzz_fuzzer_stats_dir_url(PROJECT_NAME)
58
+ (url,), _ = mock_get_json_from_url.call_args
59
+ self.assertEqual(
60
+ 'https://storage.googleapis.com/oss-fuzz-coverage/'
61
+ 'latest_report_info/curl.json', url)
62
+
63
+ expected_result = (
64
+ 'https://storage.googleapis.com/oss-fuzz-coverage/systemd/fuzzer_stats/'
65
+ '20210303')
66
+ self.assertEqual(result, expected_result)
67
+
68
+ def test_get_invalid_project(self):
69
+ """Tests that passing a bad project returns None."""
70
+ self.assertIsNone(
71
+ get_coverage._get_oss_fuzz_fuzzer_stats_dir_url('not-a-proj'))
72
+
73
+
74
+ class OSSFuzzCoverageGetTargetCoverageTest(unittest.TestCase):
75
+ """Tests OSSFuzzCoverage.get_target_coverage."""
76
+
77
+ def setUp(self):
78
+ with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
79
+ return_value=PROJECT_COV_INFO):
80
+ self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage(
81
+ REPO_PATH, PROJECT_NAME)
82
+
83
+ @mock.patch('http_utils.get_json_from_url', return_value={})
84
+ def test_valid_target(self, mock_get_json_from_url):
85
+ """Tests that a target's coverage report can be downloaded and parsed."""
86
+ self.oss_fuzz_coverage.get_target_coverage(FUZZ_TARGET)
87
+ (url,), _ = mock_get_json_from_url.call_args
88
+ self.assertEqual(
89
+ 'https://storage.googleapis.com/oss-fuzz-coverage/'
90
+ 'curl/fuzzer_stats/20200226/curl_fuzzer.json', url)
91
+
92
+ def test_invalid_target(self):
93
+ """Tests that passing an invalid target coverage report returns None."""
94
+ self.assertIsNone(
95
+ self.oss_fuzz_coverage.get_target_coverage(INVALID_TARGET))
96
+
97
+ @mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
98
+ return_value=None)
99
+ def test_invalid_project_json(self, _): # pylint: disable=no-self-use
100
+ """Tests an invalid project JSON results in None being returned."""
101
+ with pytest.raises(get_coverage.CoverageError):
102
+ get_coverage.OSSFuzzCoverage(REPO_PATH, PROJECT_NAME)
103
+
104
+
105
+ def _get_expected_curl_covered_file_list():
106
+ """Returns the expected covered file list for
107
+ FUZZ_TARGET_COV_JSON_FILENAME."""
108
+ curl_files_list_path = os.path.join(TEST_DATA_PATH,
109
+ 'example_curl_file_list.json')
110
+ with open(curl_files_list_path) as file_handle:
111
+ return json.loads(file_handle.read())
112
+
113
+
114
+ def _get_example_curl_coverage():
115
+ """Returns the contents of the fuzzer stats JSON file for
116
+ FUZZ_TARGET_COV_JSON_FILENAME."""
117
+ with open(os.path.join(TEST_DATA_PATH,
118
+ FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle:
119
+ return json.loads(file_handle.read())
120
+
121
+
122
+ class OSSFuzzCoverageGetFilesCoveredByTargetTest(unittest.TestCase):
123
+ """Tests OSSFuzzCoverage.get_files_covered_by_target."""
124
+
125
+ def setUp(self):
126
+ with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info',
127
+ return_value=PROJECT_COV_INFO):
128
+ self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage(
129
+ REPO_PATH, PROJECT_NAME)
130
+
131
+ @parameterized.parameterized.expand([({
132
+ 'data': []
133
+ },), ({
134
+ 'data': [[]]
135
+ },), ({
136
+ 'data': [{}]
137
+ },)])
138
+ def test_malformed_cov_data(self, coverage_data):
139
+ """Tests that covered files can be retrieved from a coverage report."""
140
+ with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage',
141
+ return_value=coverage_data):
142
+ self.oss_fuzz_coverage.get_files_covered_by_target(FUZZ_TARGET)
143
+
144
+ def test_valid_target(self):
145
+ """Tests that covered files can be retrieved from a coverage report."""
146
+ fuzzer_cov_data = _get_example_curl_coverage()
147
+ with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage',
148
+ return_value=fuzzer_cov_data):
149
+ file_list = self.oss_fuzz_coverage.get_files_covered_by_target(
150
+ FUZZ_TARGET)
151
+
152
+ expected_file_list = _get_expected_curl_covered_file_list()
153
+ self.assertCountEqual(file_list, expected_file_list)
154
+
155
+ def test_invalid_target(self):
156
+ """Tests passing invalid fuzz target returns None."""
157
+ self.assertIsNone(
158
+ self.oss_fuzz_coverage.get_files_covered_by_target(INVALID_TARGET))
159
+
160
+
161
+ class FilesystemCoverageGetFilesCoveredByTargetTest(
162
+ fake_filesystem_unittest.TestCase):
163
+ """Tests FilesystemCoverage.get_files_covered_by_target."""
164
+
165
+ def setUp(self):
166
+ _fuzzer_cov_data = _get_example_curl_coverage()
167
+ self._expected_file_list = _get_expected_curl_covered_file_list()
168
+ self.coverage_path = '/coverage'
169
+ self.filesystem_coverage = get_coverage.FilesystemCoverage(
170
+ REPO_PATH, self.coverage_path)
171
+ self.setUpPyfakefs()
172
+ self.fs.create_file(os.path.join(self.coverage_path, 'fuzzer_stats',
173
+ FUZZ_TARGET + '.json'),
174
+ contents=json.dumps(_fuzzer_cov_data))
175
+
176
+ def test_valid_target(self):
177
+ """Tests that covered files can be retrieved from a coverage report."""
178
+ file_list = self.filesystem_coverage.get_files_covered_by_target(
179
+ FUZZ_TARGET)
180
+ self.assertCountEqual(file_list, self._expected_file_list)
181
+
182
+ def test_invalid_target(self):
183
+ """Tests passing invalid fuzz target returns None."""
184
+ self.assertIsNone(
185
+ self.filesystem_coverage.get_files_covered_by_target(INVALID_TARGET))
186
+
187
+
188
+ class IsFileCoveredTest(unittest.TestCase):
189
+ """Tests for is_file_covered."""
190
+
191
+ def test_is_file_covered_covered(self):
192
+ """Tests that is_file_covered returns True for a covered file."""
193
+ file_coverage = {
194
+ 'filename': '/src/systemd/src/basic/locale-util.c',
195
+ 'summary': {
196
+ 'regions': {
197
+ 'count': 204,
198
+ 'covered': 200,
199
+ 'notcovered': 200,
200
+ 'percent': 98.03
201
+ }
202
+ }
203
+ }
204
+ self.assertTrue(get_coverage.is_file_covered(file_coverage))
205
+
206
+ def test_is_file_covered_not_covered(self):
207
+ """Tests that is_file_covered returns False for a not covered file."""
208
+ file_coverage = {
209
+ 'filename': '/src/systemd/src/basic/locale-util.c',
210
+ 'summary': {
211
+ 'regions': {
212
+ 'count': 204,
213
+ 'covered': 0,
214
+ 'notcovered': 0,
215
+ 'percent': 0
216
+ }
217
+ }
218
+ }
219
+ self.assertFalse(get_coverage.is_file_covered(file_coverage))
220
+
221
+
222
+ class GetOssFuzzLatestCovReportInfo(unittest.TestCase):
223
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as
224
+ intended."""
225
+
226
+ PROJECT = 'project'
227
+ LATEST_REPORT_INFO_URL = ('https://storage.googleapis.com/oss-fuzz-coverage/'
228
+ 'latest_report_info/project.json')
229
+
230
+ @mock.patch('logging.error')
231
+ @mock.patch('http_utils.get_json_from_url', return_value={'coverage': 1})
232
+ def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url,
233
+ mock_error):
234
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as intended."""
235
+ result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT)
236
+ self.assertEqual(result, {'coverage': 1})
237
+ mock_error.assert_not_called()
238
+ mock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL)
239
+
240
+ @mock.patch('logging.error')
241
+ @mock.patch('http_utils.get_json_from_url', return_value=None)
242
+ def test_get_oss_fuzz_latest_cov_report_info_fail(self, _, mock_error):
243
+ """Tests that _get_oss_fuzz_latest_cov_report_info works as intended when we
244
+ can't get latest report info."""
245
+ result = get_coverage._get_oss_fuzz_latest_cov_report_info('project')
246
+ self.assertIsNone(result)
247
+ mock_error.assert_called_with(
248
+ 'Could not get the coverage report json from url: %s.',
249
+ self.LATEST_REPORT_INFO_URL)
250
+
251
+
252
+ if __name__ == '__main__':
253
+ unittest.main()
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/http_utils_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 http_utils.py"""
15
+
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ from pyfakefs import fake_filesystem_unittest
20
+
21
+ import http_utils
22
+
23
+ mock_get_response = mock.MagicMock(status_code=200, content=b'')
24
+
25
+
26
+ class DownloadUrlTest(unittest.TestCase):
27
+ """Tests that download_url works."""
28
+ URL = 'https://example.com/file'
29
+ FILE_PATH = '/tmp/file'
30
+
31
+ @mock.patch('time.sleep')
32
+ @mock.patch('requests.get', return_value=mock_get_response)
33
+ def test_download_url_no_error(self, mock_urlretrieve, _):
34
+ """Tests that download_url works when there is no error."""
35
+ self.assertTrue(http_utils.download_url(self.URL, self.FILE_PATH))
36
+ self.assertEqual(1, mock_urlretrieve.call_count)
37
+
38
+ @mock.patch('time.sleep')
39
+ @mock.patch('logging.error')
40
+ @mock.patch('requests.get',
41
+ return_value=mock.MagicMock(status_code=404, content=b''))
42
+ def test_download_url_http_error(self, mock_get, mock_error, _):
43
+ """Tests that download_url doesn't retry when there is an HTTP error."""
44
+ self.assertFalse(http_utils.download_url(self.URL, self.FILE_PATH))
45
+ mock_error.assert_called_with(
46
+ 'Unable to download from: %s. Code: %d. Content: %s.', self.URL, 404,
47
+ b'')
48
+ self.assertEqual(1, mock_get.call_count)
49
+
50
+ @mock.patch('time.sleep')
51
+ @mock.patch('requests.get', side_effect=ConnectionResetError)
52
+ def test_download_url_connection_error(self, mock_get, mock_sleep):
53
+ """Tests that download_url doesn't retry when there is an HTTP error."""
54
+ self.assertFalse(http_utils.download_url(self.URL, self.FILE_PATH))
55
+ self.assertEqual(4, mock_get.call_count)
56
+ self.assertEqual(3, mock_sleep.call_count)
57
+
58
+
59
+ class DownloadAndUnpackZipTest(fake_filesystem_unittest.TestCase):
60
+ """Tests download_and_unpack_zip."""
61
+
62
+ def setUp(self):
63
+ self.setUpPyfakefs()
64
+
65
+ @mock.patch('requests.get', return_value=mock_get_response)
66
+ def test_bad_zip_download(self, _):
67
+ """Tests download_and_unpack_zip returns none when a bad zip is passed."""
68
+ self.fs.create_file('/url_tmp.zip', contents='Test file.')
69
+ self.assertFalse(
70
+ http_utils.download_and_unpack_zip('/not/a/real/url',
71
+ '/extract-directory'))
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/logs.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Log helpers."""
15
+
16
+ import logging
17
+ import os
18
+
19
+
20
+ def init():
21
+ """Initialize logging."""
22
+ log_level = logging.DEBUG if os.getenv('CIFUZZ_DEBUG') else logging.INFO
23
+ logging.basicConfig(
24
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25
+ level=log_level)
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ clusterfuzz==2.5.9
2
+ requests==2.28.0
3
+ protobuf==3.20.2
4
+ gsutil==5.20
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/run_cifuzz.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Script for running CIFuzz end-to-end. This is meant to work outside any
15
+ docker image. This cannot depend on any CIFuzz code or third party packages."""
16
+ import os
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ import logging
21
+
22
+ INFRA_DIR = os.path.dirname(os.path.dirname(__file__))
23
+ DEFAULT_ENVS = [('DRY_RUN', '0'), ('SANITIZER', 'address')]
24
+ BASE_CIFUZZ_DOCKER_TAG = 'ghcr.io/aixcc-finals'
25
+
26
+
27
+ def set_default_env_var_if_unset(env_var, default_value):
28
+ """Sets the value of |env_var| in the environment to |default_value| if it was
29
+ not already set."""
30
+ if env_var not in os.environ:
31
+ os.environ[env_var] = default_value
32
+
33
+
34
+ def docker_run(name, workspace, project_src_path):
35
+ """Runs a CIFuzz docker container with |name|."""
36
+ command = [
37
+ 'docker', 'run', '--name', name, '--rm', '-e', 'PROJECT_SRC_PATH', '-e',
38
+ 'OSS_FUZZ_PROJECT_NAME', '-e', 'WORKSPACE', '-e', 'REPOSITORY', '-e',
39
+ 'DRY_RUN', '-e', 'CI', '-e', 'SANITIZER', '-e', 'GIT_SHA', '-e',
40
+ 'FILESTORE', '-e', 'NO_CLUSTERFUZZ_DEPLOYMENT'
41
+ ]
42
+ if project_src_path:
43
+ command += ['-v', f'{project_src_path}:{project_src_path}']
44
+ command += [
45
+ '-v', '/var/run/docker.sock:/var/run/docker.sock', '-v',
46
+ f'{workspace}:{workspace}', f'{BASE_CIFUZZ_DOCKER_TAG}/{name}'
47
+ ]
48
+ print('Running docker command:', command)
49
+ subprocess.run(command, check=True)
50
+
51
+
52
+ def docker_build(image):
53
+ """Builds the CIFuzz |image|. Only suitable for building CIFuzz images."""
54
+ command = [
55
+ 'docker', 'build', '-t', f'{BASE_CIFUZZ_DOCKER_TAG}/{image}', '--file',
56
+ f'{image}.Dockerfile', '.'
57
+ ]
58
+ subprocess.run(command, check=True, cwd=INFRA_DIR)
59
+
60
+
61
+ def main():
62
+ """Builds and runs fuzzers using CIFuzz."""
63
+ for env_var, default_value in DEFAULT_ENVS:
64
+ set_default_env_var_if_unset(env_var, default_value)
65
+
66
+ repository = os.getenv('REPOSITORY')
67
+ assert repository
68
+
69
+ project_src_path = os.getenv('PROJECT_SRC_PATH')
70
+
71
+ with tempfile.TemporaryDirectory() as temp_dir:
72
+ if 'WORKSPACE' not in os.environ:
73
+ os.environ['WORKSPACE'] = temp_dir
74
+
75
+ workspace = os.environ['WORKSPACE']
76
+
77
+ docker_build('build_fuzzers')
78
+ docker_run('build_fuzzers', workspace, project_src_path)
79
+ docker_build('run_fuzzers')
80
+ try:
81
+ docker_run('run_fuzzers', workspace, project_src_path)
82
+ except subprocess.CalledProcessError:
83
+ logging.error('run_fuzzers failed.')
84
+ return 1
85
+ return 0
86
+
87
+
88
+ if __name__ == '__main__':
89
+ sys.exit(main())
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Runs a specific OSS-Fuzz project's fuzzers for CI tools."""
15
+ import logging
16
+ import sys
17
+
18
+ import config_utils
19
+ import docker
20
+ import logs
21
+ import run_fuzzers
22
+
23
+ # pylint: disable=c-extension-no-member
24
+ # pylint gets confused because of the relative import of cifuzz.
25
+
26
+ logs.init()
27
+
28
+
29
+ def delete_unneeded_docker_images(config):
30
+ """Deletes unneeded docker images if running in an environment with low
31
+ disk space."""
32
+ if not config.low_disk_space:
33
+ return
34
+ logging.info('Deleting builder docker images to save disk space.')
35
+ project_image = docker.get_project_image_name(config.oss_fuzz_project_name)
36
+ images = [
37
+ project_image,
38
+ docker.BASE_BUILDER_TAG,
39
+ docker.BASE_BUILDER_TAG + '-go',
40
+ docker.BASE_BUILDER_TAG + '-javascript',
41
+ docker.BASE_BUILDER_TAG + '-jvm',
42
+ docker.BASE_BUILDER_TAG + '-python',
43
+ docker.BASE_BUILDER_TAG + '-rust',
44
+ docker.BASE_BUILDER_TAG + '-ruby',
45
+ docker.BASE_BUILDER_TAG + '-swift',
46
+ ]
47
+ docker.delete_images(images)
48
+
49
+
50
+ def run_fuzzers_entrypoint():
51
+ """This is the entrypoint for the run_fuzzers github action.
52
+ This action can be added to any OSS-Fuzz project's workflow that uses
53
+ Github."""
54
+ config = config_utils.RunFuzzersConfig()
55
+ # The default return code when an error occurs.
56
+ returncode = 1
57
+ if config.dry_run:
58
+ # Sets the default return code on error to success.
59
+ returncode = 0
60
+
61
+ delete_unneeded_docker_images(config)
62
+ # Run the specified project's fuzzers from the build.
63
+ result = run_fuzzers.run_fuzzers(config)
64
+ if result == run_fuzzers.RunFuzzersResult.ERROR:
65
+ logging.error('Error occurred while running in workspace %s.',
66
+ config.workspace)
67
+ return returncode
68
+ if result == run_fuzzers.RunFuzzersResult.BUG_FOUND:
69
+ logging.info('Bug found.')
70
+ if not config.dry_run:
71
+ # Return 2 when a bug was found by a fuzzer causing the CI to fail.
72
+ return 2
73
+ return 0
74
+
75
+
76
+ def main():
77
+ """Runs project's fuzzers for CI tools.
78
+ This is the entrypoint for the run_fuzzers github action.
79
+
80
+ NOTE: libFuzzer binaries must be located in the $WORKSPACE/build-out
81
+ directory in order for this action to be used. This action will only fuzz the
82
+ binaries that are located in that directory. It is recommended that you add
83
+ the build_fuzzers action preceding this one.
84
+
85
+ NOTE: Any crash report will be in the filepath:
86
+ ${GITHUB_WORKSPACE}/out/testcase
87
+ This can be used in parallel with the upload-artifact action to surface the
88
+ logs.
89
+
90
+ Returns:
91
+ 0 on success or nonzero on failure.
92
+ """
93
+ return run_fuzzers_entrypoint()
94
+
95
+
96
+ if __name__ == '__main__':
97
+ sys.exit(main())
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for running fuzzers."""
15
+ import json
16
+ import os
17
+ import shutil
18
+ import stat
19
+ import sys
20
+ import tempfile
21
+ import unittest
22
+ from unittest import mock
23
+
24
+ import parameterized
25
+ from pyfakefs import fake_filesystem_unittest
26
+
27
+ import build_fuzzers
28
+ import fuzz_target
29
+ import run_fuzzers
30
+
31
+ # pylint: disable=wrong-import-position
32
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33
+ sys.path.append(INFRA_DIR)
34
+
35
+ import helper
36
+ import test_helpers
37
+
38
+ # NOTE: This integration test relies on
39
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
40
+ EXAMPLE_PROJECT = 'example'
41
+
42
+ # Location of files used for testing.
43
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
44
+ 'test_data')
45
+
46
+ MEMORY_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'memory')
47
+ MEMORY_FUZZER = 'curl_fuzzer_memory'
48
+
49
+ UNDEFINED_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'undefined')
50
+ UNDEFINED_FUZZER = 'curl_fuzzer_undefined'
51
+
52
+ FUZZ_SECONDS = 10
53
+
54
+
55
+ class RunFuzzerIntegrationTestMixin: # pylint: disable=too-few-public-methods,invalid-name
56
+ """Mixin for integration test classes that runbuild_fuzzers on builds of a
57
+ specific sanitizer."""
58
+ # These must be defined by children.
59
+ FUZZER_DIR = None
60
+ FUZZER = None
61
+
62
+ def setUp(self):
63
+ """Patch the environ so that we can execute runner scripts."""
64
+ test_helpers.patch_environ(self, runner=True)
65
+
66
+ def _test_run_with_sanitizer(self, fuzzer_dir, sanitizer):
67
+ """Calls run_fuzzers on fuzzer_dir and |sanitizer| and asserts
68
+ the run succeeded and that no bug was found."""
69
+ with test_helpers.temp_dir_copy(fuzzer_dir) as fuzzer_dir_copy:
70
+ config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
71
+ workspace=fuzzer_dir_copy,
72
+ oss_fuzz_project_name='curl',
73
+ sanitizer=sanitizer)
74
+ result = run_fuzzers.run_fuzzers(config)
75
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
76
+
77
+
78
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
79
+ 'INTEGRATION_TESTS=1 not set')
80
+ class RunMemoryFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
81
+ unittest.TestCase):
82
+ """Integration test for build_fuzzers with an MSAN build."""
83
+ FUZZER_DIR = MEMORY_FUZZER_DIR
84
+ FUZZER = MEMORY_FUZZER
85
+
86
+ def test_run_with_memory_sanitizer(self):
87
+ """Tests run_fuzzers with a valid MSAN build."""
88
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'memory')
89
+
90
+
91
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
92
+ 'INTEGRATION_TESTS=1 not set')
93
+ class RunUndefinedFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
94
+ unittest.TestCase):
95
+ """Integration test for build_fuzzers with an UBSAN build."""
96
+ FUZZER_DIR = UNDEFINED_FUZZER_DIR
97
+ FUZZER = UNDEFINED_FUZZER
98
+
99
+ def test_run_with_undefined_sanitizer(self):
100
+ """Tests run_fuzzers with a valid UBSAN build."""
101
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'undefined')
102
+
103
+
104
+ class BaseFuzzTargetRunnerTest(unittest.TestCase):
105
+ """Tests BaseFuzzTargetRunner."""
106
+
107
+ def _create_runner(self, **kwargs): # pylint: disable=no-self-use
108
+ defaults = {
109
+ 'fuzz_seconds': FUZZ_SECONDS,
110
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT
111
+ }
112
+ for default_key, default_value in defaults.items():
113
+ if default_key not in kwargs:
114
+ kwargs[default_key] = default_value
115
+
116
+ config = test_helpers.create_run_config(**kwargs)
117
+ return run_fuzzers.BaseFuzzTargetRunner(config)
118
+
119
+ def _test_initialize_fail(self, expected_error_args, **create_runner_kwargs):
120
+ with mock.patch('logging.error') as mock_error:
121
+ runner = self._create_runner(**create_runner_kwargs)
122
+ self.assertFalse(runner.initialize())
123
+ mock_error.assert_called_with(*expected_error_args)
124
+
125
+ @parameterized.parameterized.expand([(0,), (None,), (-1,)])
126
+ def test_initialize_invalid_fuzz_seconds(self, fuzz_seconds):
127
+ """Tests initialize fails with an invalid fuzz seconds."""
128
+ expected_error_args = ('Fuzz_seconds argument must be greater than 1, '
129
+ 'but was: %s.', fuzz_seconds)
130
+ with tempfile.TemporaryDirectory() as tmp_dir:
131
+ out_path = os.path.join(tmp_dir, 'build-out')
132
+ os.mkdir(out_path)
133
+ with mock.patch('utils.get_fuzz_targets') as mock_get_fuzz_targets:
134
+ mock_get_fuzz_targets.return_value = [
135
+ os.path.join(out_path, 'fuzz_target')
136
+ ]
137
+ self._test_initialize_fail(expected_error_args,
138
+ fuzz_seconds=fuzz_seconds,
139
+ workspace=tmp_dir)
140
+
141
+ def test_initialize_no_out_dir(self):
142
+ """Tests initialize fails with no out dir."""
143
+ with tempfile.TemporaryDirectory() as tmp_dir:
144
+ out_path = os.path.join(tmp_dir, 'build-out')
145
+ expected_error_args = ('Out directory: %s does not exist.', out_path)
146
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
147
+
148
+ def test_initialize_nonempty_artifacts(self):
149
+ """Tests initialize with a file artifacts path."""
150
+ with tempfile.TemporaryDirectory() as tmp_dir:
151
+ out_path = os.path.join(tmp_dir, 'build-out')
152
+ os.mkdir(out_path)
153
+ os.makedirs(os.path.join(tmp_dir, 'out'))
154
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
155
+ with open(artifacts_path, 'w') as artifacts_handle:
156
+ artifacts_handle.write('fake')
157
+ expected_error_args = (
158
+ 'Artifacts path: %s exists and is not an empty directory.',
159
+ artifacts_path)
160
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
161
+
162
+ def test_initialize_bad_artifacts(self):
163
+ """Tests initialize with a non-empty artifacts path."""
164
+ with tempfile.TemporaryDirectory() as tmp_dir:
165
+ out_path = os.path.join(tmp_dir, 'build-out')
166
+ os.mkdir(out_path)
167
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
168
+ os.makedirs(artifacts_path)
169
+ artifact_path = os.path.join(artifacts_path, 'artifact')
170
+ with open(artifact_path, 'w') as artifact_handle:
171
+ artifact_handle.write('fake')
172
+ expected_error_args = (
173
+ 'Artifacts path: %s exists and is not an empty directory.',
174
+ artifacts_path)
175
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
176
+
177
+ @mock.patch('utils.get_fuzz_targets')
178
+ @mock.patch('logging.error')
179
+ def test_initialize_empty_artifacts(self, mock_log_error,
180
+ mock_get_fuzz_targets):
181
+ """Tests initialize with an empty artifacts dir."""
182
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
183
+ with tempfile.TemporaryDirectory() as tmp_dir:
184
+ out_path = os.path.join(tmp_dir, 'build-out')
185
+ os.mkdir(out_path)
186
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
187
+ os.makedirs(artifacts_path)
188
+ runner = self._create_runner(workspace=tmp_dir)
189
+ self.assertTrue(runner.initialize())
190
+ mock_log_error.assert_not_called()
191
+ self.assertTrue(os.path.isdir(artifacts_path))
192
+
193
+ @mock.patch('utils.get_fuzz_targets')
194
+ @mock.patch('logging.error')
195
+ def test_initialize_no_artifacts(self, mock_log_error, mock_get_fuzz_targets):
196
+ """Tests initialize with no artifacts dir (the expected setting)."""
197
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
198
+ with tempfile.TemporaryDirectory() as tmp_dir:
199
+ out_path = os.path.join(tmp_dir, 'build-out')
200
+ os.mkdir(out_path)
201
+ runner = self._create_runner(workspace=tmp_dir)
202
+ self.assertTrue(runner.initialize())
203
+ mock_log_error.assert_not_called()
204
+ self.assertTrue(os.path.isdir(os.path.join(tmp_dir, 'out', 'artifacts')))
205
+
206
+ def test_initialize_no_fuzz_targets(self):
207
+ """Tests initialize with no fuzz targets."""
208
+ with tempfile.TemporaryDirectory() as tmp_dir:
209
+ out_path = os.path.join(tmp_dir, 'build-out')
210
+ os.makedirs(out_path)
211
+ expected_error_args = ('No fuzz targets were found in out directory: %s.',
212
+ out_path)
213
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
214
+
215
+
216
+ class CiFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
217
+ """Tests that CiFuzzTargetRunner works as intended."""
218
+
219
+ def setUp(self):
220
+ self.setUpPyfakefs()
221
+
222
+ @mock.patch('clusterfuzz_deployment.OSSFuzz.upload_crashes')
223
+ @mock.patch('utils.get_fuzz_targets')
224
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.run_fuzz_target')
225
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.create_fuzz_target_obj')
226
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
227
+ mock_run_fuzz_target, mock_get_fuzz_targets,
228
+ mock_upload_crashes):
229
+ """Tests that run_fuzz_targets quits on the first crash it finds."""
230
+ workspace = 'workspace'
231
+ out_path = os.path.join(workspace, 'build-out')
232
+ self.fs.create_dir(out_path)
233
+ config = test_helpers.create_run_config(
234
+ fuzz_seconds=FUZZ_SECONDS,
235
+ workspace=workspace,
236
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
237
+ runner = run_fuzzers.CiFuzzTargetRunner(config)
238
+
239
+ mock_get_fuzz_targets.return_value = ['target1', 'target2']
240
+ runner.initialize()
241
+ testcase = os.path.join(workspace, 'testcase')
242
+ self.fs.create_file(testcase)
243
+ stacktrace = 'stacktrace'
244
+ corpus_dir = 'corpus'
245
+ self.fs.create_dir(corpus_dir)
246
+ mock_run_fuzz_target.return_value = fuzz_target.FuzzResult(
247
+ testcase, stacktrace, corpus_dir)
248
+ magic_mock = mock.MagicMock()
249
+ magic_mock.target_name = 'target1'
250
+ mock_create_fuzz_target_obj.return_value = magic_mock
251
+ self.assertTrue(runner.run_fuzz_targets())
252
+ self.assertEqual(mock_run_fuzz_target.call_count, 1)
253
+ self.assertEqual(mock_upload_crashes.call_count, 1)
254
+
255
+
256
+ class BatchFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
257
+ """Tests that BatchFuzzTargetRunnerTest works as intended."""
258
+ WORKSPACE = 'workspace'
259
+ STACKTRACE = 'stacktrace'
260
+ CORPUS_DIR = 'corpus'
261
+
262
+ def setUp(self):
263
+ self.setUpPyfakefs()
264
+ out_dir = os.path.join(self.WORKSPACE, 'build-out')
265
+ self.fs.create_dir(out_dir)
266
+ self.testcase1 = os.path.join(out_dir, 'testcase-aaa')
267
+ self.fs.create_file(self.testcase1)
268
+ self.testcase2 = os.path.join(out_dir, 'testcase-bbb')
269
+ self.fs.create_file(self.testcase2)
270
+ self.config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
271
+ workspace=self.WORKSPACE,
272
+ cfl_platform='github')
273
+
274
+ @mock.patch('utils.get_fuzz_targets', return_value=['target1', 'target2'])
275
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_crashes')
276
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.run_fuzz_target')
277
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.create_fuzz_target_obj')
278
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
279
+ mock_run_fuzz_target, mock_upload_crashes, _):
280
+ """Tests that run_fuzz_targets doesn't quit on the first crash it finds."""
281
+ runner = run_fuzzers.BatchFuzzTargetRunner(self.config)
282
+ runner.initialize()
283
+
284
+ call_count = 0
285
+
286
+ def mock_run_fuzz_target_impl(_):
287
+ nonlocal call_count
288
+ if call_count == 0:
289
+ testcase = self.testcase1
290
+ elif call_count == 1:
291
+ testcase = self.testcase2
292
+ assert call_count != 2
293
+ call_count += 1
294
+ if not os.path.exists(self.CORPUS_DIR):
295
+ self.fs.create_dir(self.CORPUS_DIR)
296
+ return fuzz_target.FuzzResult(testcase, self.STACKTRACE, self.CORPUS_DIR)
297
+
298
+ mock_run_fuzz_target.side_effect = mock_run_fuzz_target_impl
299
+ magic_mock = mock.MagicMock()
300
+ magic_mock.target_name = 'target1'
301
+ mock_create_fuzz_target_obj.return_value = magic_mock
302
+ self.assertTrue(runner.run_fuzz_targets())
303
+ self.assertEqual(mock_run_fuzz_target.call_count, 2)
304
+ self.assertEqual(mock_upload_crashes.call_count, 1)
305
+
306
+
307
+ class GetCoverageTargetsTest(unittest.TestCase):
308
+ """Tests for get_coverage_fuzz_targets."""
309
+
310
+ def test_get_fuzz_targets(self):
311
+ """Tests that get_coverage_fuzz_targets returns expected targets."""
312
+ with tempfile.TemporaryDirectory() as temp_dir:
313
+ # Setup.
314
+ fuzz_target_path = os.path.join(temp_dir, 'fuzz-target')
315
+ with open(fuzz_target_path, 'w') as file_handle:
316
+ file_handle.write('')
317
+ fuzz_target_st = os.stat(fuzz_target_path)
318
+ os.chmod(fuzz_target_path, fuzz_target_st.st_mode | stat.S_IEXEC)
319
+ non_fuzz_target1 = os.path.join(temp_dir, 'non-fuzz-target1')
320
+ with open(non_fuzz_target1, 'w') as file_handle:
321
+ file_handle.write('LLVMFuzzerTestOneInput')
322
+ subdir = os.path.join(temp_dir, 'subdir')
323
+ os.mkdir(subdir)
324
+ non_fuzz_target2 = os.path.join(subdir, 'non-fuzz-target1')
325
+ with open(non_fuzz_target2, 'w') as file_handle:
326
+ file_handle.write('LLVMFuzzerTestOneInput')
327
+
328
+ self.assertEqual(run_fuzzers.get_coverage_fuzz_targets(temp_dir),
329
+ [fuzz_target_path])
330
+
331
+
332
+ @unittest.skip('TODO(metzman): Fix this test')
333
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
334
+ 'INTEGRATION_TESTS=1 not set')
335
+ class CoverageReportIntegrationTest(unittest.TestCase):
336
+ """Integration tests for coverage reports."""
337
+ SANITIZER = 'coverage'
338
+
339
+ def setUp(self):
340
+ test_helpers.patch_environ(self, runner=True)
341
+
342
+ @mock.patch('filestore.github_actions._upload_artifact_with_upload_js')
343
+ def test_coverage_report(self, _):
344
+ """Tests generation of coverage reports end-to-end, from building to
345
+ generation."""
346
+
347
+ with test_helpers.docker_temp_dir() as temp_dir:
348
+ shared = os.path.join(temp_dir, 'shared')
349
+ os.mkdir(shared)
350
+ copy_command = ('cp -r /opt/code_coverage /shared && '
351
+ 'cp $(which llvm-profdata) /shared && '
352
+ 'cp $(which llvm-cov) /shared')
353
+ assert helper.docker_run([
354
+ '-v', f'{shared}:/shared', 'ghcr.io/aixcc-finals/base-runner', 'bash',
355
+ '-c', copy_command
356
+ ])
357
+
358
+ os.environ['CODE_COVERAGE_SRC'] = os.path.join(shared, 'code_coverage')
359
+ os.environ['PATH'] += os.pathsep + shared
360
+ # Do coverage build.
361
+ build_config = test_helpers.create_build_config(
362
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
363
+ project_repo_name='oss-fuzz',
364
+ workspace=temp_dir,
365
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
366
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
367
+ sanitizer=self.SANITIZER,
368
+ cfl_platform='github',
369
+ # Needed for test not to fail because of permissions issues.
370
+ bad_build_check=False)
371
+ self.assertTrue(build_fuzzers.build_fuzzers(build_config))
372
+
373
+ # TODO(metzman): Get rid of this here and make 'compile' do this.
374
+ chmod_command = ('chmod -R +r /out && '
375
+ 'find /out -type d -exec chmod +x {} +')
376
+
377
+ assert helper.docker_run([
378
+ '-v', f'{os.path.join(temp_dir, "build-out")}:/out',
379
+ 'ghcr.io/aixcc-finals/base-builder', 'bash', '-c', chmod_command
380
+ ])
381
+
382
+ # Generate report.
383
+ run_config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
384
+ workspace=temp_dir,
385
+ sanitizer=self.SANITIZER,
386
+ mode='coverage',
387
+ cfl_platform='github')
388
+ result = run_fuzzers.run_fuzzers(run_config)
389
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
390
+ expected_summary_path = os.path.join(
391
+ TEST_DATA_PATH, 'example_coverage_report_summary.json')
392
+ with open(expected_summary_path) as file_handle:
393
+ expected_summary = json.loads(file_handle.read())
394
+ actual_summary_path = os.path.join(temp_dir, 'cifuzz-coverage',
395
+ 'report', 'linux', 'summary.json')
396
+ with open(actual_summary_path) as file_handle:
397
+ actual_summary = json.loads(file_handle.read())
398
+ self.assertEqual(expected_summary, actual_summary)
399
+
400
+
401
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
402
+ 'INTEGRATION_TESTS=1 not set')
403
+ class RunAddressFuzzersIntegrationTest(RunFuzzerIntegrationTestMixin,
404
+ unittest.TestCase):
405
+ """Integration tests for build_fuzzers with an ASAN build."""
406
+
407
+ BUILD_DIR_NAME = 'cifuzz-latest-build'
408
+
409
+ def test_new_bug_found(self):
410
+ """Tests run_fuzzers with a valid ASAN build."""
411
+ # Set the first return value to True, then the second to False to
412
+ # emulate a bug existing in the current PR but not on the downloaded
413
+ # OSS-Fuzz build.
414
+ with mock.patch('fuzz_target.FuzzTarget.is_reproducible',
415
+ side_effect=[True, False]):
416
+ with tempfile.TemporaryDirectory() as tmp_dir:
417
+ workspace = os.path.join(tmp_dir, 'workspace')
418
+ shutil.copytree(TEST_DATA_PATH, workspace)
419
+ config = test_helpers.create_run_config(
420
+ fuzz_seconds=FUZZ_SECONDS,
421
+ workspace=workspace,
422
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
423
+ result = run_fuzzers.run_fuzzers(config)
424
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.BUG_FOUND)
425
+
426
+ @mock.patch('fuzz_target.FuzzTarget.is_reproducible',
427
+ side_effect=[True, True])
428
+ def test_old_bug_found(self, _):
429
+ """Tests run_fuzzers with a bug found in OSS-Fuzz before."""
430
+ with tempfile.TemporaryDirectory() as tmp_dir:
431
+ workspace = os.path.join(tmp_dir, 'workspace')
432
+ shutil.copytree(TEST_DATA_PATH, workspace)
433
+ config = test_helpers.create_run_config(
434
+ fuzz_seconds=FUZZ_SECONDS,
435
+ workspace=workspace,
436
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
437
+ result = run_fuzzers.run_fuzzers(config)
438
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
439
+
440
+ def test_invalid_build(self):
441
+ """Tests run_fuzzers with an invalid ASAN build."""
442
+ with tempfile.TemporaryDirectory() as tmp_dir:
443
+ out_path = os.path.join(tmp_dir, 'build-out')
444
+ os.mkdir(out_path)
445
+ config = test_helpers.create_run_config(
446
+ fuzz_seconds=FUZZ_SECONDS,
447
+ workspace=tmp_dir,
448
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
449
+ result = run_fuzzers.run_fuzzers(config)
450
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.ERROR)
451
+
452
+
453
+ class GetFuzzTargetRunnerTest(unittest.TestCase):
454
+ """Tests for get_fuzz_fuzz_target_runner."""
455
+
456
+ @parameterized.parameterized.expand([
457
+ ('batch', run_fuzzers.BatchFuzzTargetRunner),
458
+ ('code-change', run_fuzzers.CiFuzzTargetRunner),
459
+ ('coverage', run_fuzzers.CoverageTargetRunner)
460
+ ])
461
+ def test_get_fuzz_target_runner(self, mode, fuzz_target_runner_cls):
462
+ """Tests that get_fuzz_target_runner returns the correct runner based on the
463
+ specified mode."""
464
+ with tempfile.TemporaryDirectory() as tmp_dir:
465
+ run_config = test_helpers.create_run_config(
466
+ fuzz_seconds=FUZZ_SECONDS,
467
+ workspace=tmp_dir,
468
+ oss_fuzz_project_name='example',
469
+ mode=mode)
470
+ runner = run_fuzzers.get_fuzz_target_runner(run_config)
471
+ self.assertTrue(isinstance(runner, fuzz_target_runner_cls))
472
+
473
+
474
+ if __name__ == '__main__':
475
+ unittest.main()
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/cifuzz/test_helpers.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains convenient helpers for writing tests."""
15
+
16
+ import contextlib
17
+ import os
18
+ import sys
19
+ import shutil
20
+ import tempfile
21
+ from unittest import mock
22
+
23
+ import config_utils
24
+ import docker
25
+ import workspace_utils
26
+
27
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28
+ # pylint: disable=wrong-import-position,import-error
29
+ sys.path.append(INFRA_DIR)
30
+
31
+ import helper
32
+
33
+
34
+ # TODO(metzman): Get rid of these decorators.
35
+ @mock.patch('config_utils._is_dry_run', return_value=True)
36
+ @mock.patch('platform_config.BasePlatformConfig.project_src_path',
37
+ return_value=None)
38
+ @mock.patch('os.path.basename', return_value=None)
39
+ def _create_config(config_cls, _, __, ___, **kwargs):
40
+ """Creates a config object from |config_cls| and then sets every attribute
41
+ that is a key in |kwargs| to the corresponding value. Asserts that each key in
42
+ |kwargs| is an attribute of config."""
43
+ with mock.patch('config_utils.BaseConfig.validate', return_value=True):
44
+ config = config_cls()
45
+ for key, value in kwargs.items():
46
+ assert hasattr(config, key), 'Config doesn\'t have attribute: ' + key
47
+ setattr(config, key, value)
48
+
49
+ return config
50
+
51
+
52
+ def create_build_config(**kwargs):
53
+ """Wrapper around _create_config for build configs."""
54
+ return _create_config(config_utils.BuildFuzzersConfig, **kwargs)
55
+
56
+
57
+ def create_run_config(**kwargs):
58
+ """Wrapper around _create_config for run configs."""
59
+ return _create_config(config_utils.RunFuzzersConfig, **kwargs)
60
+
61
+
62
+ def create_workspace(workspace_path='/workspace'):
63
+ """Returns a workspace located at |workspace_path| ('/workspace' by
64
+ default)."""
65
+ config = create_run_config(workspace=workspace_path)
66
+ return workspace_utils.Workspace(config)
67
+
68
+
69
+ def patch_environ(testcase_obj, env=None, empty=False, runner=False):
70
+ """Patch environment. |testcase_obj| is the unittest.TestCase that contains
71
+ tests. |env|, if specified, is a dictionary of environment variables to start
72
+ from. If |empty| is True then the new patched environment will be empty. If
73
+ |runner| is True then the necessary environment variables will be set to run
74
+ the scripts from base-runner."""
75
+ if env is None:
76
+ env = {}
77
+
78
+ patcher = mock.patch.dict(os.environ, env)
79
+ testcase_obj.addCleanup(patcher.stop)
80
+ patcher.start()
81
+ if empty:
82
+ for key in os.environ.copy():
83
+ del os.environ[key]
84
+
85
+ if runner:
86
+ # Add the scripts for base-runner to the path since the wont be in
87
+ # /usr/local/bin on host machines during testing.
88
+ base_runner_dir = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
89
+ os.environ['PATH'] = (os.environ.get('PATH', '') + os.pathsep +
90
+ base_runner_dir)
91
+ if 'GOPATH' not in os.environ:
92
+ # A GOPATH must be set or else the coverage script fails, even for getting
93
+ # the coverage of non-Go programs.
94
+ os.environ['GOPATH'] = '/root/go'
95
+
96
+
97
+ @contextlib.contextmanager
98
+ def temp_dir_copy(directory):
99
+ """Context manager that yields a temporary copy of |directory|."""
100
+ with tempfile.TemporaryDirectory() as temp_dir:
101
+ temp_copy_path = os.path.join(temp_dir, os.path.basename(directory))
102
+ shutil.copytree(directory, temp_copy_path)
103
+ yield temp_copy_path
104
+
105
+
106
+ @contextlib.contextmanager
107
+ def docker_temp_dir():
108
+ """Returns a temporary a directory that is useful for use with docker. On
109
+ cleanup this contextmanager uses docker to delete the directory's contents so
110
+ that if anything is owned by root it can be deleted (which
111
+ tempfile.TemporaryDirectory() cannot do) by non-root users."""
112
+ with tempfile.TemporaryDirectory() as temp_dir:
113
+ yield temp_dir
114
+ helper.docker_run([
115
+ '-v', f'{temp_dir}:/temp_dir', '-t', docker.BASE_BUILDER_TAG,
116
+ '/bin/bash', '-c', 'rm -rf /temp_dir/*'
117
+ ])
local-test-tika-delta-03/fuzz-tooling/infra/cifuzz/workspace_utils.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for representing the workspace directory which CIFuzz uses."""
15
+
16
+ import os
17
+ import shutil
18
+
19
+
20
+ class Workspace:
21
+ """Class representing the workspace directory."""
22
+
23
+ def __init__(self, config):
24
+ self.workspace = config.workspace
25
+
26
+ def initialize_dir(self, directory): # pylint: disable=no-self-use
27
+ """Creates directory if it doesn't already exist, otherwise does nothing."""
28
+ os.makedirs(directory, exist_ok=True)
29
+
30
+ @property
31
+ def repo_storage(self):
32
+ """The parent directory for repo storage."""
33
+ return os.path.join(self.workspace, 'storage')
34
+
35
+ @property
36
+ def out(self):
37
+ """The out directory used for storing the fuzzer build built by
38
+ build_fuzzers."""
39
+ # Don't use 'out' because it needs to be used by artifacts.
40
+ return os.path.join(self.workspace, 'build-out')
41
+
42
+ @property
43
+ def work(self):
44
+ """The directory used as the work directory for the fuzzer build/run."""
45
+ return os.path.join(self.workspace, 'work')
46
+
47
+ @property
48
+ def artifacts(self):
49
+ """The directory used to store artifacts for download by CI-system users."""
50
+ # This is hardcoded by a lot of clients, so we need to use this.
51
+ return os.path.join(self.workspace, 'out', 'artifacts')
52
+
53
+ @property
54
+ def clusterfuzz_build(self):
55
+ """The directory where builds from ClusterFuzz are stored."""
56
+ return os.path.join(self.workspace, 'cifuzz-prev-build')
57
+
58
+ @property
59
+ def clusterfuzz_coverage(self):
60
+ """The directory where builds from ClusterFuzz are stored."""
61
+ return os.path.join(self.workspace, 'cifuzz-prev-coverage')
62
+
63
+ @property
64
+ def coverage_report(self):
65
+ """The directory where coverage reports generated by cifuzz are put."""
66
+ return os.path.join(self.workspace, 'cifuzz-coverage')
67
+
68
+ @property
69
+ def corpora(self):
70
+ """The directory where corpora from ClusterFuzz are stored."""
71
+ return os.path.join(self.workspace, 'cifuzz-corpus')
72
+
73
+ @property
74
+ def pruned_corpora(self):
75
+ """The directory where pruned corpora are stored."""
76
+ return os.path.join(self.workspace, 'cifuzz-pruned-corpus')
77
+
78
+ @property
79
+ def sarif(self):
80
+ """The directory where sarif files are stored."""
81
+ return os.path.join(self.workspace, 'cifuzz-sarif')
82
+
83
+ def make_repo_for_sarif(self, repo_manager):
84
+ """Copies the repo over for the sarif upload GitHub action."""
85
+ return shutil.copytree(repo_manager.repo_dir, self.sarif, symlinks=True)
local-test-tika-delta-03/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-delta-03/fuzz-tooling/infra/uploader/Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from ubuntu:16.04
2
+
3
+ RUN apt-get update && apt-get upgrade -y
4
+ RUN apt-get install -y curl
5
+
6
+ ENTRYPOINT ["curl", "--retry", "5", "-X", "PUT", "-T"]
7
+
local-test-tika-delta-03/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-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ // Copyright 2023 Google LLC
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ //
16
+ ////////////////////////////////////////////////////////////////////////////////
17
+
18
+ import {commandHistory} from '../commandUtils';
19
+ import {setStatusText} from '../utils';
20
+ import {buildFuzzersFromWorkspaceClusterfuzzLite} from '../ossfuzzWrappers';
21
+
22
+ export async function cmdInputCollectorBuildFuzzersFromWorkspaceCFLite() {
23
+ // Create an history object
24
+ const args = new Object({
25
+ toClean: false,
26
+ });
27
+
28
+ const commandObject = new Object({
29
+ commandType: 'oss-fuzz.WSBuildFuzzers',
30
+ Arguments: args,
31
+ dispatcherFunc: cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite,
32
+ });
33
+ console.log('L1: ' + commandHistory.length);
34
+ commandHistory.push(commandObject);
35
+
36
+ await cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite(args);
37
+ return true;
38
+ }
39
+
40
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
41
+ async function cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite(_args: any) {
42
+ await setStatusText('[CFLite] Building fuzzers: starting');
43
+ const res = await buildFuzzersFromWorkspaceClusterfuzzLite();
44
+ if (res) {
45
+ await setStatusText('[CFLite] Building fuzzers: finished');
46
+ } else {
47
+ await setStatusText('[CFLite] Building fuzzers: failed');
48
+ }
49
+ }
local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdCreateOSSFuzzSetup.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {setupProjectInitialFiles} from '../projectIntegrationHelper';
18
+ import {setStatusText} from '../utils';
19
+
20
+ export async function createOssFuzzSetup() {
21
+ await setStatusText('Creating OSS-Fuzz setup: starting');
22
+ const res = await setupProjectInitialFiles(false);
23
+ if (res) {
24
+ await setStatusText('Creating OSS-Fuzz setup: finished');
25
+ } else {
26
+ await setStatusText('Creating OSS-Fuzz setup: failed');
27
+ }
28
+ }
local-test-tika-delta-03/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-delta-03/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-delta-03/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-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdReproduceTestcase.ts ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {systemSyncLogIfFailure} from '../utils';
22
+ import {buildFuzzersFromWorkspace} from '../ossfuzzWrappers';
23
+ import {extensionConfig} from '../config';
24
+ const readline = require('readline');
25
+
26
+ export async function cmdInputCollectorReproduceTestcase() {
27
+ // Runs a fuzzer from a given project.
28
+ const crashFileInput = await vscode.window.showInputBox({
29
+ value: '',
30
+ placeHolder: 'The ID of the testcase.',
31
+ });
32
+ if (!crashFileInput) {
33
+ return;
34
+ }
35
+ // Create an history object and append it to the command history.
36
+ const args = new Object({
37
+ crashFile: crashFileInput.toString(),
38
+ });
39
+
40
+ const commandObject = new Object({
41
+ commandType: 'oss-fuzz.ReproduceFuzzer',
42
+ Arguments: args,
43
+ dispatcherFunc: cmdDispatchReproduceTestcase,
44
+ });
45
+ commandHistory.push(commandObject);
46
+
47
+ await cmdDispatchReproduceTestcase(args);
48
+ return true;
49
+ }
50
+
51
+ async function cmdDispatchReproduceTestcase(args: any) {
52
+ await reproduceTestcase(args.crashFile);
53
+ }
54
+
55
+ export async function reproduceTestcase(crashInfoFileInput: string) {
56
+ println('Reproducing testcase for ' + crashInfoFileInput);
57
+ println('Checking directory: ' + extensionConfig.crashesDirectory);
58
+
59
+ const crashInfoFile =
60
+ extensionConfig.crashesDirectory + '/' + crashInfoFileInput + '.info';
61
+ println(crashInfoFile);
62
+ try {
63
+ if (fs.existsSync(crashInfoFile)) {
64
+ println('File exists');
65
+ } else {
66
+ println('Crash file does not exist');
67
+ return;
68
+ }
69
+ } catch (err) {
70
+ console.error(err);
71
+ return;
72
+ }
73
+
74
+ // At this point the file exists
75
+ const r = readline.createInterface({
76
+ input: fs.createReadStream(crashInfoFile),
77
+ });
78
+
79
+ let targetProject = 'N/A';
80
+ let targetFuzzer = 'N/A';
81
+ // Logic for passing the file. This is based off of clusterfuzz monorail reports,
82
+ // and the intention is the file needs to be a copy of:
83
+ //
84
+ // Project: project-name
85
+ // Fuzzing Engine: libFuzzer
86
+ // Fuzz Target: fuzzer-name
87
+ //
88
+ // Example:
89
+ // The following URL: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=59747
90
+ // has the bug information:
91
+ // """
92
+ // Project: my-fuzzing-project
93
+ // Fuzzing Engine: libFuzzer
94
+ // Fuzz Target: the-fuzzer-name-fuzz-parseXX
95
+ // Job Type: libfuzzer_asan_my-fuzzing-project
96
+ // Platform Id: linux
97
+ // """
98
+ // and a link to a reproducer test case:
99
+ // https://oss-fuzz.com/download?testcase_id=5009071179431936
100
+ // which, when accessed will download the file
101
+ // clusterfuzz-testcase-minimized-flb-it-fuzz-config_map_fuzzer_OSSFUZZ-5009071179431936
102
+ //
103
+ // To enable reproducing of this issue we need to:
104
+ // - 1) Download the crash file and place it in the directory given in config.ts
105
+ // and "crashesDirectory" variable.
106
+ // - 2) create a file "5009071179431936.info" and paste the information above
107
+ // (Project:... Fuzz Target: ...) into the file. This information is
108
+ // needed because we need to know project name and fuzzer name in order
109
+ // to reproduce the crash.
110
+ // - 3) the reproducer can now be reproduced using the reproduce command
111
+ // with argument "5009071179431936" as argument.
112
+ r.on('line', (text: string) => {
113
+ println(text);
114
+ if (text.startsWith('Project: ')) {
115
+ println('Starts with project');
116
+ println(text.split('Project: ').toString());
117
+ targetProject = text.split('Project: ')[1];
118
+ } else if (text.startsWith('Fuzzing Engine: ')) {
119
+ println('Starts with fuzzing engine');
120
+ } else if (text.startsWith('Fuzz Target:')) {
121
+ println('Starts with Fuzz Target');
122
+ targetFuzzer = text.split('Fuzz Target: ')[1];
123
+ } else if (text.startsWith('Job Type:')) {
124
+ println('Starts with Job Type');
125
+ }
126
+ });
127
+
128
+ r.on('close', async () => {
129
+ println('Target project: ' + targetProject);
130
+ println('Target fuzzer: ' + targetFuzzer);
131
+
132
+ // Build a fresh version of the project.
133
+ const buildResult: boolean = await buildFuzzersFromWorkspace(
134
+ targetProject,
135
+ '',
136
+ true
137
+ );
138
+ if (!buildResult) {
139
+ println('Failed to build fuzzers');
140
+ return false;
141
+ }
142
+
143
+ // We have a fresh build of the project, proceed to reproduce the testcase.
144
+ const crashInputTestCase =
145
+ extensionConfig.crashesDirectory +
146
+ '/' +
147
+ 'clusterfuzz-testcase-minimized-' +
148
+ targetFuzzer +
149
+ '-' +
150
+ crashInfoFileInput;
151
+ // Run reproduce command against the target file
152
+ // Build the fuzzers using OSS-Fuzz infrastructure.
153
+ const cmdToExec = 'python3';
154
+ const args = [
155
+ extensionConfig.ossFuzzPepositoryWorkPath + '/infra/helper.py',
156
+ 'reproduce',
157
+ targetProject,
158
+ targetFuzzer,
159
+ crashInputTestCase,
160
+ ];
161
+ if (!(await systemSyncLogIfFailure(cmdToExec, args))) {
162
+ println('Failed to reproduce testcase');
163
+ }
164
+
165
+ return true;
166
+ });
167
+ }
local-test-tika-delta-03/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-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupCIFuzz.ts ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {determineWorkspaceLanguage} from '../utils';
20
+ import {cifuzzGenerator} from '../cifuzz';
21
+
22
+ export async function setupCIFuzzHandler() {
23
+ const workspaceFolder = vscode.workspace.workspaceFolders;
24
+ if (!workspaceFolder) {
25
+ return false;
26
+ }
27
+
28
+ const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder
29
+
30
+ /**
31
+ * Go through GitHub workflows to find potential traces of CIFuzz
32
+ */
33
+ const githubWorkflowsPath = vscode.Uri.file(wsPath + '/.github/workflows');
34
+ try {
35
+ await vscode.workspace.fs.readDirectory(githubWorkflowsPath);
36
+ } catch {
37
+ println('Did not find a workflows path.');
38
+ return false;
39
+ }
40
+
41
+ for (const [name, type] of await vscode.workspace.fs.readDirectory(
42
+ githubWorkflowsPath
43
+ )) {
44
+ // Skip directories.
45
+ if (type === 2) {
46
+ continue;
47
+ }
48
+
49
+ // Read the files.
50
+ println('Is a file');
51
+ const workflowFile = vscode.Uri.file(wsPath + '/.github/workflows/' + name);
52
+ const doc = await vscode.workspace.openTextDocument(workflowFile);
53
+ if (doc.getText().includes('cifuzz')) {
54
+ println('Found existing CIFuzz, will not continue.');
55
+ return false;
56
+ }
57
+ }
58
+
59
+ println('Did not find CIFuzz, creating one.');
60
+ const projectName = await vscode.window.showInputBox({
61
+ value: '',
62
+ placeHolder: 'OSS-Fuzz project name',
63
+ });
64
+ if (!projectName) {
65
+ println('Failed to get project name');
66
+ return false;
67
+ }
68
+
69
+ /*
70
+ * There is no CIFuzz found, so we create one.
71
+ */
72
+ // Determine the language of the workspace.
73
+ const targetLanguage = await determineWorkspaceLanguage();
74
+ println('Target language: ' + targetLanguage);
75
+
76
+ // Generate a CIFuzz workflow text.
77
+ const cifuzzWorkflowText = cifuzzGenerator(targetLanguage, projectName, 30);
78
+
79
+ // Create the CIFuzz .yml file and write the contents to it to path
80
+ // .github/workflows/cifuzz.yml
81
+ const cifuzzYml = vscode.Uri.file(wsPath + '/.github/workflows/cifuzz.yml');
82
+ const wsedit = new vscode.WorkspaceEdit();
83
+ wsedit.createFile(cifuzzYml, {ignoreIfExists: true});
84
+ wsedit.insert(cifuzzYml, new vscode.Position(0, 0), cifuzzWorkflowText);
85
+ vscode.workspace.applyEdit(wsedit);
86
+ return true;
87
+ }
local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupFI.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 {setUpFuzzIntrospector} from '../fuzzIntrospectorHelper';
18
+
19
+ /**
20
+ * Function for setting up Fuzz Introspector by way of a Python virtual env.
21
+ */
22
+ export async function setUpFuzzIntrospectorHandler() {
23
+ setUpFuzzIntrospector();
24
+ }
local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTemplate.ts ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {println} from '../logger';
23
+
24
+ export const cLangSimpleStringFuzzer = `#include <stdint.h>
25
+ #include <string.h>
26
+ #include <stdlib.h>
27
+
28
+ int
29
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
30
+ {
31
+ char *new_str = (char *)malloc(size+1);
32
+ if (new_str == NULL){
33
+ return 0;
34
+ }
35
+ memcpy(new_str, data, size);
36
+ new_str[size] = '\\0';
37
+
38
+ // Insert fuzzer contents here
39
+ // fuzz data in new_str
40
+
41
+ // end of fuzzer contents
42
+
43
+ free(new_str);
44
+ return 0;
45
+ }`;
46
+
47
+ const cLangFileInputFuzzer = `int
48
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
49
+ {
50
+ char filename[256];
51
+ sprintf(filename, "/tmp/libfuzzer.%d", getpid());
52
+
53
+ // Create a file on the filesystem with fuzzer data in it
54
+ FILE *fp = fopen(filename, "wb");
55
+ if (!fp) {
56
+ return 0;
57
+ }
58
+ fwrite(data, size, 1, fp);
59
+ fclose(fp);
60
+
61
+ // Fuzzer logic here. Use the file as a source of data.
62
+
63
+ // Fuzzer logic end
64
+
65
+ // Clean up the file.
66
+ unlink(filename);
67
+
68
+ return 0;
69
+ }`;
70
+
71
+ const cLangBareTemplateFuzzer = `int
72
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
73
+ {
74
+ return 0;
75
+ }`;
76
+
77
+ const cppLangBareTemplateFuzzer = `extern "C" int
78
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
79
+ {
80
+ return 0;
81
+ }`;
82
+
83
+ const cppLangStdStringTemplateFuzzer = `extern "C" int
84
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
85
+ {
86
+ std::string input(reinterpret_cast<const char*>(data), size);
87
+
88
+ return 0;
89
+ }`;
90
+
91
+ export const cppLangFDPTemplateFuzzer = `#include <fuzzer/FuzzedDataProvider.h>
92
+
93
+ #include <string>
94
+
95
+ extern "C" int
96
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
97
+ {
98
+ FuzzedDataProvider fdp(data, size);
99
+
100
+ // Extract higher level data types used for fuzzing, e.g.
101
+ // int ran_int = fdp.ConsumeIntegralInRange<int>(1, 1024);
102
+ // std::string s = fdp.ConsumeRandomLengthString();
103
+
104
+ return 0;
105
+ }`;
106
+
107
+ const cppLangFileInputFuzzer = `extern "C" int
108
+ LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
109
+ {
110
+ char filename[256];
111
+ sprintf(filename, "/tmp/libfuzzer.%d", getpid());
112
+
113
+ FILE *fp = fopen(filename, "wb");
114
+ if (!fp) {
115
+ return 0;
116
+ }
117
+ fwrite(data, size, 1, fp);
118
+ fclose(fp);
119
+
120
+ // Fuzzer logic here
121
+
122
+ // Fuzzer logic end
123
+
124
+ unlink(filename);
125
+ }`;
126
+
127
+ const pythonLangBareTemplate = `import sys
128
+ import atheris
129
+
130
+
131
+ def TestOneInput(fuzz_bytes):
132
+ return
133
+
134
+
135
+ def main():
136
+ atheris.Setup(sys.argv, TestOneInput)
137
+ atheris.Fuzz()
138
+
139
+
140
+ if __name__ == "__main__":
141
+ main()`;
142
+
143
+ export const pythonLangFileInputFuzzer = `import sys
144
+ import atheris
145
+
146
+ @atheris.instrument_func
147
+ def TestOneInput(data):
148
+ # Write fuzz data to a file
149
+ with open('/tmp/fuzz_input.b') as f:
150
+ f.write(data)
151
+
152
+ # Use '/tmp/fuzz_input.b' as input to file handling logic.
153
+
154
+
155
+ def main():
156
+ atheris.instrument_all()
157
+ atheris.Setup(sys.argv, TestOneInput)
158
+ atheris.Fuzz()
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()`;
163
+
164
+ const pythonLongFdpTemplate = `import sys
165
+ import atheris
166
+
167
+ def TestOneInput(fuzz_bytes):
168
+ fdp = atheris.FuzzedDataProvider(fuzz_bytes)
169
+ return
170
+
171
+ def main():
172
+ atheris.Setup(sys.argv, TestOneInput)
173
+ atheris.Fuzz()
174
+
175
+ if __name__ == "__main__":
176
+ main()`;
177
+
178
+ export const javaLangBareTemplate = `import com.code_intelligence.jazzer.api.FuzzedDataProvider;
179
+ public class SampleFuzzer {
180
+ public static void fuzzerTestOneInput(FuzzedDataProvider fdp) {
181
+ // Use fdp to create arbitrary types seeded with fuzz data
182
+ }
183
+ }
184
+ `;
185
+
186
+ /**
187
+ * C templates
188
+ */
189
+ async function cTemplates() {
190
+ let template = '';
191
+ const result = await vscode.window.showQuickPick(
192
+ ['Bare template', 'Null-terminated string input', 'File input'],
193
+ {
194
+ placeHolder: 'Pick which template',
195
+ }
196
+ );
197
+ vscode.window.showInformationMessage(`Got: ${result}`);
198
+
199
+ if (result === 'Null-terminated string input') {
200
+ template = cLangSimpleStringFuzzer;
201
+ } else if (result === 'File input') {
202
+ template = cLangFileInputFuzzer;
203
+ } else if (result === 'Bare template') {
204
+ template = cLangBareTemplateFuzzer;
205
+ } else {
206
+ template = 'empty';
207
+ }
208
+ const workspaceFolder = vscode.workspace.workspaceFolders;
209
+ if (!workspaceFolder) {
210
+ return;
211
+ }
212
+
213
+ const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder
214
+
215
+ const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.c');
216
+ const wsedit = new vscode.WorkspaceEdit();
217
+ wsedit.createFile(cifuzzYml, {ignoreIfExists: true});
218
+ wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template);
219
+ vscode.workspace.applyEdit(wsedit);
220
+ return;
221
+ }
222
+
223
+ /**
224
+ * CPP templates
225
+ */
226
+ async function cppTemplates() {
227
+ let template = '';
228
+ const result = await vscode.window.showQuickPick(
229
+ [
230
+ 'Bare template',
231
+ 'Simple CPP string',
232
+ 'File input fuzzer',
233
+ 'Fuzzed data provider',
234
+ ],
235
+ {
236
+ placeHolder: 'Pick which template',
237
+ }
238
+ );
239
+ vscode.window.showInformationMessage(`Got: ${result}`);
240
+
241
+ if (result === 'Bare template') {
242
+ template = cppLangBareTemplateFuzzer;
243
+ } else if (result === 'Simple CPP string') {
244
+ template = cppLangStdStringTemplateFuzzer;
245
+ } else if (result === 'File input fuzzer') {
246
+ template = cppLangFileInputFuzzer;
247
+ } else if (result === 'Fuzzed data provider') {
248
+ template = cppLangFDPTemplateFuzzer;
249
+ } else {
250
+ template = 'empty';
251
+ }
252
+ const workspaceFolder = vscode.workspace.workspaceFolders;
253
+ if (!workspaceFolder) {
254
+ return;
255
+ }
256
+
257
+ const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder
258
+
259
+ const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.cpp');
260
+ const wsedit = new vscode.WorkspaceEdit();
261
+ wsedit.createFile(cifuzzYml, {ignoreIfExists: true});
262
+ wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template);
263
+ vscode.workspace.applyEdit(wsedit);
264
+ return;
265
+ }
266
+
267
+ /**
268
+ * Python templates
269
+ */
270
+ async function pythonTepmlates() {
271
+ let template = '';
272
+ const result = await vscode.window.showQuickPick(
273
+ ['Bare template', 'Fuzzed Data Provider', 'File input fuzzer'],
274
+ {
275
+ placeHolder: 'Pick which template',
276
+ }
277
+ );
278
+ vscode.window.showInformationMessage(`Got: ${result}`);
279
+
280
+ if (result === 'Fuzzed Data Provider') {
281
+ template = pythonLongFdpTemplate;
282
+ } else if (result === 'Bare template') {
283
+ template = pythonLangBareTemplate;
284
+ } else if (result === 'File input fuzzer') {
285
+ template = pythonLangFileInputFuzzer;
286
+ } else {
287
+ template = 'empty';
288
+ }
289
+ const workspaceFolder = vscode.workspace.workspaceFolders;
290
+ if (!workspaceFolder) {
291
+ return;
292
+ }
293
+
294
+ const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder
295
+
296
+ const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.py');
297
+ const wsedit = new vscode.WorkspaceEdit();
298
+ wsedit.createFile(cifuzzYml, {ignoreIfExists: true});
299
+ wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template);
300
+ vscode.workspace.applyEdit(wsedit);
301
+ return;
302
+ }
303
+
304
+ /**
305
+ * Java templates
306
+ */
307
+ async function javaTemplates() {
308
+ let template = '';
309
+ const result = await vscode.window.showQuickPick(['Bare template'], {
310
+ placeHolder: 'Pick which template',
311
+ });
312
+ vscode.window.showInformationMessage(`Got: ${result}`);
313
+
314
+ if (result === 'Bare template') {
315
+ template = javaLangBareTemplate;
316
+ } else {
317
+ template = 'empty';
318
+ }
319
+ const workspaceFolder = vscode.workspace.workspaceFolders;
320
+ if (!workspaceFolder) {
321
+ return;
322
+ }
323
+
324
+ const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder
325
+
326
+ const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.java');
327
+ const wsedit = new vscode.WorkspaceEdit();
328
+ wsedit.createFile(cifuzzYml, {ignoreIfExists: true});
329
+ wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template);
330
+ vscode.workspace.applyEdit(wsedit);
331
+ return;
332
+ }
333
+
334
+ export async function cmdDispatcherTemplate(context: vscode.ExtensionContext) {
335
+ println('Creating template');
336
+ const options: {
337
+ [key: string]: (context: vscode.ExtensionContext) => Promise<void>;
338
+ } = {
339
+ C: cTemplates,
340
+ CPP: cppTemplates,
341
+ Python: pythonTepmlates,
342
+ Java: javaTemplates,
343
+ };
344
+
345
+ const quickPick = vscode.window.createQuickPick();
346
+ quickPick.items = Object.keys(options).map(label => ({label}));
347
+ quickPick.onDidChangeSelection(selection => {
348
+ if (selection[0]) {
349
+ options[selection[0].label](context).catch(console.error);
350
+ }
351
+ });
352
+ quickPick.onDidHide(() => quickPick.dispose());
353
+ quickPick.placeholder = 'Pick language';
354
+ quickPick.show();
355
+
356
+ return;
357
+ }
local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTestFuzzer.ts ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {runFuzzerHandler, buildFuzzersFromWorkspace} from '../ossfuzzWrappers';
20
+ import {setStatusText} from '../utils';
21
+ import {commandHistory} from '../commandUtils';
22
+ import {extensionConfig} from '../config';
23
+
24
+ /**
25
+ * Does an end-to-end test of a project/fuzzer. This is done by
26
+ * first building the project and then running the fuzzer.
27
+ * @param context
28
+ * @returns
29
+ */
30
+
31
+ export async function cmdInputCollectorTestFuzzer() {
32
+ setStatusText('Testing specific fuzzer: getting input');
33
+ // Get the project name and fuzzer name to test.
34
+ const ossFuzzProjectNameInput = await vscode.window.showInputBox({
35
+ value: '',
36
+ placeHolder: 'The OSS-Fuzz project name',
37
+ });
38
+ if (!ossFuzzProjectNameInput) {
39
+ println('Did not get a ossFuzzTargetProject');
40
+ return;
41
+ }
42
+ println('Project name: ' + ossFuzzProjectNameInput);
43
+
44
+ // Get the fuzzer to run
45
+ const fuzzerNameInput = await vscode.window.showInputBox({
46
+ value: '',
47
+ placeHolder: 'Type a fuzzer name',
48
+ });
49
+ if (!fuzzerNameInput) {
50
+ println('Failed to get fuzzer name');
51
+ return;
52
+ }
53
+
54
+ // Create the args object for the dispatcher
55
+ const args = new Object({
56
+ projectName: ossFuzzProjectNameInput.toString(),
57
+ fuzzerName: fuzzerNameInput.toString(),
58
+ });
59
+
60
+ // Create a dispatcher object.
61
+ const commandObject = new Object({
62
+ commandType: 'oss-fuzz.TestFuzzer',
63
+ Arguments: args,
64
+ dispatcherFunc: cmdDispatchTestFuzzerHandler,
65
+ });
66
+ commandHistory.push(commandObject);
67
+
68
+ await cmdDispatchTestFuzzerHandler(args);
69
+ }
70
+
71
+ async function cmdDispatchTestFuzzerHandler(args: any) {
72
+ // Build the project
73
+ setStatusText('Test specific fuzzer: building fuzzers in workspace');
74
+ if (!(await buildFuzzersFromWorkspace(args.projectName, '', false))) {
75
+ println('Build projects');
76
+ return;
77
+ }
78
+
79
+ // Run the fuzzer for 10 seconds
80
+ println('Running fuzzer');
81
+ setStatusText('Test specific fuzzer: running fuzzer ' + args.fuzzerName);
82
+ await runFuzzerHandler(
83
+ args.projectName,
84
+ args.fuzzerName,
85
+ extensionConfig.numberOfSecondsForTestRuns.toString(),
86
+ ''
87
+ );
88
+ setStatusText('Test specific fuzzer: test completed of ' + args.fuzzerName);
89
+ return;
90
+ }
local-test-tika-delta-03/fuzz-tooling/tools/vscode-extension/src/fuzzIntrospectorHelper.ts ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright 2025 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
+ import {isPathValidOssFuzzPath} from './ossfuzzWrappers';
22
+ import {systemSync} from './utils';
23
+
24
+ const fs = require('fs');
25
+
26
+ export async function setUpFuzzIntrospector() {
27
+ println('Setting up oss-fuzz in /tmp/');
28
+
29
+ // First check if we already have Fuzz Introspector installed.
30
+ const tmpOssFuzzRepositoryPath = '/tmp/fi-tmp-env';
31
+
32
+ if ((await isPathValidOssFuzzPath(tmpOssFuzzRepositoryPath)) === true) {
33
+ println('Fuzz Introspector virtual env already exists in /tmp/fi-tmp-env');
34
+ extensionConfig.ossFuzzPepositoryWorkPath = tmpOssFuzzRepositoryPath;
35
+ return;
36
+ }
37
+
38
+ const cmdToExec = 'python3.11';
39
+ const args: Array<string> = ['-m', 'virtualenv', tmpOssFuzzRepositoryPath];
40
+ const [res, output] = await systemSync(cmdToExec, args);
41
+ if (res === false) {
42
+ println('Failed to create virtual environment');
43
+ println(output);
44
+ return;
45
+ }
46
+
47
+ const cmdToExec2 = '/tmp/fi-tmp-env/bin/python3.11';
48
+ const args2: Array<string> = [
49
+ '-m',
50
+ 'pip',
51
+ 'install',
52
+ 'fuzz-introspector==0.1.6',
53
+ ];
54
+ const [res2, output2] = await systemSync(cmdToExec2, args2);
55
+ if (res2 === false) {
56
+ println('Failed to create virtual environment');
57
+ println(output2);
58
+ return;
59
+ }
60
+ }
61
+
62
+ export async function runFuzzIntrospector() {
63
+ println('Setting up oss-fuzz in /tmp/');
64
+
65
+ const workspaceFolder = vscode.workspace.workspaceFolders;
66
+ if (!workspaceFolder) {
67
+ return;
68
+ }
69
+ const pathOfLocal = workspaceFolder[0].uri.fsPath;
70
+ println('path of local: ' + pathOfLocal);
71
+
72
+ // First check if we already have Fuzz Introspector installed.
73
+ const tmpOssFuzzRepositoryPath = '/tmp/fi-tmp-env';
74
+
75
+ if ((await isPathValidOssFuzzPath(tmpOssFuzzRepositoryPath)) === true) {
76
+ println('Fuzz Introspector virtual env already exists in /tmp/fi-tmp-env');
77
+ extensionConfig.ossFuzzPepositoryWorkPath = tmpOssFuzzRepositoryPath;
78
+ return;
79
+ }
80
+
81
+ await systemSync('mkdir', ['-p', '/tmp/out-fi/']);
82
+
83
+ const cmdToExec = '/tmp/fi-tmp-env/bin/fuzz-introspector';
84
+ const args: Array<string> = [
85
+ 'full',
86
+ '--target_dir=' + pathOfLocal,
87
+ '--out-dir=/tmp/out-fi',
88
+ ];
89
+ const [res, output] = await systemSync(cmdToExec, args);
90
+ if (res === false) {
91
+ println('Failed run FI');
92
+ println(output);
93
+ return;
94
+ }
95
+ }
96
+
97
+ export async function getOptimalTargetsFromIntrospector() {
98
+ if (!fs.existsSync('/tmp/out-fi/summary.json')) {
99
+ println('There are no introspector reports. Please run introspector first');
100
+ }
101
+ const json_data = fs.readFileSync('/tmp/out-fi/summary.json');
102
+ // println(json_data);
103
+
104
+ const jsonCodeCoverage = JSON.parse(json_data);
105
+
106
+ println('Optimal targets');
107
+ Object.entries(jsonCodeCoverage['analyses']['OptimalTargets']).forEach(
108
+ entry => {
109
+ const [key, value] = entry;
110
+ const objectDictionary: any = value as any;
111
+ println(JSON.stringify(objectDictionary, null, 2));
112
+ }
113
+ );
114
+ println('--------------------------');
115
+
116
+ return;
117
+ }