Kitxuuu commited on
Commit
e47e32e
·
verified ·
1 Parent(s): 3ac58ae

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc +0 -0
  2. local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc +0 -0
  3. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/README.md +6 -0
  4. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/aixcc_build_all.sh +59 -0
  5. local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/all.sh +28 -0
  6. local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build.py +292 -0
  7. local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build_test.py +124 -0
  8. local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/requirements.txt +9 -0
  9. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/CHANGELOG +3 -0
  10. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py +113 -0
  11. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py +113 -0
  12. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/base_runner_utils.py +33 -0
  13. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build-images.sh +34 -0
  14. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers.py +217 -0
  15. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py +60 -0
  16. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py +403 -0
  17. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py +40 -0
  18. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py +48 -0
  19. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cloudbuild.yaml +52 -0
  20. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py +385 -0
  21. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py +268 -0
  22. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils.py +283 -0
  23. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils_test.py +200 -0
  24. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration.py +375 -0
  25. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration_test.py +88 -0
  26. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker.py +127 -0
  27. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker_test.py +119 -0
  28. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/environment.py +51 -0
  29. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/example_cifuzz.yml +33 -0
  30. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils.py +48 -0
  31. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils_test.py +50 -0
  32. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target.py +408 -0
  33. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target_test.py +298 -0
  34. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report.py +48 -0
  35. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py +71 -0
  36. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage.py +208 -0
  37. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage_test.py +253 -0
  38. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils.py +118 -0
  39. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils_test.py +71 -0
  40. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/logs.py +25 -0
  41. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/requirements.txt +4 -0
  42. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_cifuzz.py +89 -0
  43. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers.py +321 -0
  44. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py +97 -0
  45. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py +475 -0
  46. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils.py +251 -0
  47. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils_test.py +128 -0
  48. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_helpers.py +117 -0
  49. local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/workspace_utils.py +85 -0
  50. local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/Makefile +41 -0
local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc ADDED
Binary file (802 Bytes). View file
 
local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc ADDED
Binary file (3.04 kB). View file
 
local-test-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.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
+ """Tests for affected_fuzz_targets.py"""
15
+ import os
16
+ import shutil
17
+ import tempfile
18
+ import unittest
19
+ from unittest import mock
20
+
21
+ import parameterized
22
+
23
+ import affected_fuzz_targets
24
+ import clusterfuzz_deployment
25
+ import get_coverage
26
+ import test_helpers
27
+ import workspace_utils
28
+
29
+ # pylint: disable=protected-access
30
+
31
+ # NOTE: This integration test relies on
32
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
33
+ EXAMPLE_PROJECT = 'example'
34
+
35
+ EXAMPLE_FILE_CHANGED = 'test.txt'
36
+
37
+ TEST_DATA_OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
38
+ 'test_data', 'build-out')
39
+
40
+
41
+ class RemoveUnaffectedFuzzTargetsTest(unittest.TestCase):
42
+ """Tests remove_unaffected_fuzzers."""
43
+
44
+ TEST_FUZZER_1 = os.path.join(TEST_DATA_OUT_PATH, 'example_crash_fuzzer')
45
+ TEST_FUZZER_2 = os.path.join(TEST_DATA_OUT_PATH, 'example_nocrash_fuzzer')
46
+
47
+ # yapf: disable
48
+ @parameterized.parameterized.expand([
49
+ # Tests specific affected fuzzers are kept.
50
+ ([[EXAMPLE_FILE_CHANGED], None], 2,),
51
+
52
+ # Tests specific affected fuzzer is kept.
53
+ ([[EXAMPLE_FILE_CHANGED], ['not/a/real/file']], 1),
54
+
55
+ # Tests all fuzzers are kept if none are deemed affected.
56
+ ([None, None], 2),
57
+
58
+ # Tests that multiple fuzzers are kept if multiple fuzzers are affected.
59
+ ([[EXAMPLE_FILE_CHANGED], [EXAMPLE_FILE_CHANGED]], 2),
60
+ ])
61
+ # yapf: enable
62
+ def test_remove_unaffected_fuzz_targets(self, side_effect, expected_dir_len):
63
+ """Tests that remove_unaffected_fuzzers has the intended effect."""
64
+ config = test_helpers.create_run_config(
65
+ cfl_platform='github',
66
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
67
+ workspace='/workspace')
68
+ workspace = workspace_utils.Workspace(config)
69
+ deployment = clusterfuzz_deployment.get_clusterfuzz_deployment(
70
+ config, workspace)
71
+ # We can't use fakefs in this test because this test executes
72
+ # utils.is_fuzz_target_local. This function relies on the executable bit
73
+ # being set, which doesn't work properly in fakefs.
74
+ with tempfile.TemporaryDirectory() as tmp_dir, mock.patch(
75
+ 'get_coverage.OSSFuzzCoverage.get_files_covered_by_target'
76
+ ) as mock_get_files:
77
+ with mock.patch('get_coverage._get_oss_fuzz_fuzzer_stats_dir_url',
78
+ return_value=1):
79
+ mock_get_files.side_effect = side_effect
80
+ shutil.copy(self.TEST_FUZZER_1, tmp_dir)
81
+ shutil.copy(self.TEST_FUZZER_2, tmp_dir)
82
+
83
+ affected_fuzz_targets.remove_unaffected_fuzz_targets(
84
+ deployment, tmp_dir, [EXAMPLE_FILE_CHANGED], '')
85
+ self.assertEqual(expected_dir_len, len(os.listdir(tmp_dir)))
86
+
87
+
88
+ class IsFuzzTargetAffectedTest(unittest.TestCase):
89
+ """Tests for is_fuzz_target_affected."""
90
+
91
+ def setUp(self):
92
+ self.fuzz_target_path = '/fuzz_target'
93
+
94
+ def test_relative_paths(self):
95
+ """Tests that is_fuzz_target_affected works as intended when the covered
96
+ files are relative paths."""
97
+ with mock.patch.object(
98
+ get_coverage.FilesystemCoverage,
99
+ 'get_files_covered_by_target',
100
+ ) as get_files_covered_by_target:
101
+ get_files_covered_by_target.return_value = [
102
+ '/work/build/../../src/systemd/src/basic/alloc-util.c'
103
+ ]
104
+ coverage = get_coverage.FilesystemCoverage('/', '/')
105
+
106
+ self.assertTrue(
107
+ affected_fuzz_targets.is_fuzz_target_affected(
108
+ coverage, self.fuzz_target_path,
109
+ ['/src/systemd/src/basic/alloc-util.c']))
110
+
111
+
112
+ if __name__ == '__main__':
113
+ unittest.main()
local-test-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests the functionality of the cifuzz module."""
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ import unittest
20
+ from unittest import mock
21
+
22
+ import parameterized
23
+
24
+ # pylint: disable=wrong-import-position
25
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.append(INFRA_DIR)
27
+
28
+ OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR)
29
+
30
+ import build_fuzzers
31
+ import continuous_integration
32
+ import repo_manager
33
+ import test_helpers
34
+
35
+ # NOTE: This integration test relies on
36
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
37
+ EXAMPLE_PROJECT = 'example'
38
+
39
+ # Location of data used for testing.
40
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
41
+ 'test_data')
42
+
43
+ # An example fuzzer that triggers an crash.
44
+ # Binary is a copy of the example project's do_stuff_fuzzer and can be
45
+ # generated by running "python3 infra/helper.py build_fuzzers example".
46
+ EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer'
47
+
48
+ # An example fuzzer that does not trigger a crash.
49
+ # Binary is a modified version of example project's do_stuff_fuzzer. It is
50
+ # created by removing the bug in my_api.cpp.
51
+ EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer'
52
+
53
+ # A fuzzer to be built in build_fuzzers integration tests.
54
+ EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer'
55
+
56
+ # pylint: disable=no-self-use,protected-access,too-few-public-methods,unused-argument
57
+
58
+
59
+ def docker_command_has_env_var_arg(command, env_var_arg):
60
+ """Returns True if a docker command has a specific env var argument."""
61
+ for idx, element in enumerate(command):
62
+ if idx == 0:
63
+ # We're looking for the variable which can't be the first argument.
64
+ continue
65
+
66
+ if element == env_var_arg and command[idx - 1] == '-e':
67
+ return True
68
+ return False
69
+
70
+
71
+ class BuildFuzzersTest(unittest.TestCase):
72
+ """Unit tests for build_fuzzers."""
73
+
74
+ @mock.patch('build_specified_commit.detect_main_repo',
75
+ return_value=('example.com', '/path'))
76
+ @mock.patch('repo_manager._clone', return_value=None)
77
+ @mock.patch('continuous_integration.checkout_specified_commit')
78
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
79
+ def test_cifuzz_env_var(self, mock_docker_run, _, __, ___):
80
+ """Tests that the CIFUZZ env var is set."""
81
+
82
+ with tempfile.TemporaryDirectory() as tmp_dir:
83
+ build_fuzzers.build_fuzzers(
84
+ test_helpers.create_build_config(
85
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
86
+ project_repo_name=EXAMPLE_PROJECT,
87
+ workspace=tmp_dir,
88
+ pr_ref='refs/pull/1757/merge'))
89
+
90
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
91
+
92
+ self.assertTrue(
93
+ docker_command_has_env_var_arg(docker_run_command, 'CIFUZZ=True'))
94
+
95
+ @mock.patch('build_specified_commit.detect_main_repo',
96
+ return_value=('example.com', '/path'))
97
+ @mock.patch('repo_manager._clone', return_value=None)
98
+ @mock.patch('continuous_integration.checkout_specified_commit')
99
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
100
+ def test_extra_env_var(self, mock_docker_run, _, __, ___):
101
+ """Tests that the CIFUZZ env var is set."""
102
+
103
+ extra_env_var = 'CFL_EXTRA_TOKEN'
104
+ with tempfile.TemporaryDirectory() as tmp_dir:
105
+ with mock.patch.dict(os.environ, {extra_env_var: 'BLAH'}):
106
+ build_fuzzers.build_fuzzers(
107
+ test_helpers.create_build_config(
108
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
109
+ project_repo_name=EXAMPLE_PROJECT,
110
+ workspace=tmp_dir,
111
+ pr_ref='refs/pull/1757/merge'))
112
+
113
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
114
+ self.assertTrue(
115
+ docker_command_has_env_var_arg(docker_run_command, extra_env_var))
116
+
117
+
118
+ class InternalGithubBuildTest(unittest.TestCase):
119
+ """Tests for building OSS-Fuzz projects on GitHub actions."""
120
+ PROJECT_REPO_NAME = 'myproject'
121
+ SANITIZER = 'address'
122
+ GIT_SHA = 'fake'
123
+ PR_REF = 'fake'
124
+
125
+ def _create_builder(self, tmp_dir, oss_fuzz_project_name='myproject'):
126
+ """Creates an InternalGithubBuilder and returns it."""
127
+ config = test_helpers.create_build_config(
128
+ oss_fuzz_project_name=oss_fuzz_project_name,
129
+ project_repo_name=self.PROJECT_REPO_NAME,
130
+ workspace=tmp_dir,
131
+ sanitizer=self.SANITIZER,
132
+ git_sha=self.GIT_SHA,
133
+ pr_ref=self.PR_REF,
134
+ cfl_platform='github')
135
+ cfl_platform = continuous_integration.get_ci(config)
136
+ builder = build_fuzzers.Builder(config, cfl_platform)
137
+ builder.repo_manager = repo_manager.RepoManager('/fake')
138
+ return builder
139
+
140
+ @mock.patch('helper.docker_run', return_value=True)
141
+ @mock.patch('continuous_integration.checkout_specified_commit',
142
+ side_effect=None)
143
+ def test_correct_host_repo_path(self, _, __):
144
+ """Tests that the correct self.host_repo_path is set by
145
+ build_image_and_checkout_src. Specifically, we want the name of the
146
+ directory the repo is in to match the name used in the docker
147
+ image/container, so that it will replace the host's copy properly."""
148
+ image_repo_path = '/src/repo_dir'
149
+ with tempfile.TemporaryDirectory() as tmp_dir, mock.patch(
150
+ 'build_specified_commit.detect_main_repo',
151
+ return_value=('inferred_url', image_repo_path)):
152
+ builder = self._create_builder(tmp_dir)
153
+ builder.build_image_and_checkout_src()
154
+
155
+ self.assertEqual(os.path.basename(builder.host_repo_path),
156
+ os.path.basename(image_repo_path))
157
+
158
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
159
+ return_value=True)
160
+ def test_upload_build_disabled(self, mock_upload_build):
161
+ """Test upload build (disabled)."""
162
+ with tempfile.TemporaryDirectory() as tmp_dir:
163
+ builder = self._create_builder(tmp_dir)
164
+ builder.upload_build()
165
+
166
+ mock_upload_build.assert_not_called()
167
+
168
+ @mock.patch('repo_manager.RepoManager.get_current_commit',
169
+ return_value='commit')
170
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
171
+ return_value=True)
172
+ def test_upload_build(self, mock_upload_build, mock_get_current_commit):
173
+ """Test upload build."""
174
+ with tempfile.TemporaryDirectory() as tmp_dir:
175
+ builder = self._create_builder(tmp_dir, oss_fuzz_project_name='')
176
+ builder.config.upload_build = True
177
+ builder.upload_build()
178
+
179
+ mock_upload_build.assert_called_with('commit')
180
+
181
+
182
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
183
+ 'INTEGRATION_TESTS=1 not set')
184
+ class BuildFuzzersIntegrationTest(unittest.TestCase):
185
+ """Integration tests for build_fuzzers."""
186
+
187
+ def setUp(self):
188
+ self.temp_dir_ctx_manager = test_helpers.docker_temp_dir()
189
+ self.workspace = self.temp_dir_ctx_manager.__enter__()
190
+ self.out_dir = os.path.join(self.workspace, 'build-out')
191
+ test_helpers.patch_environ(self)
192
+
193
+ base_runner_path = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
194
+ os.environ['PATH'] = os.environ['PATH'] + os.pathsep + base_runner_path
195
+
196
+ def tearDown(self):
197
+ self.temp_dir_ctx_manager.__exit__(None, None, None)
198
+
199
+ def test_external_github_project(self):
200
+ """Tests building fuzzers from an external project on Github."""
201
+ project_repo_name = 'external-project'
202
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
203
+ # This test is dependant on the state of
204
+ # github.com/jonathanmetzman/cifuzz-external-example.
205
+ config = test_helpers.create_build_config(
206
+ project_repo_name=project_repo_name,
207
+ workspace=self.workspace,
208
+ git_url=git_url,
209
+ git_sha='HEAD',
210
+ cfl_platform='github',
211
+ base_commit='HEAD^1')
212
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
213
+ self.assertTrue(
214
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
215
+
216
+ def test_external_generic_project(self):
217
+ """Tests building fuzzers from an external project not on Github."""
218
+ project_repo_name = 'cifuzz-external-example'
219
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
220
+ # This test is dependant on the state of
221
+ # github.com/jonathanmetzman/cifuzz-external-example.
222
+ manager = repo_manager.clone_repo_and_get_manager(
223
+ 'https://github.com/jonathanmetzman/cifuzz-external-example',
224
+ self.workspace)
225
+ project_src_path = manager.repo_dir
226
+ config = test_helpers.create_build_config(
227
+ project_repo_name=project_repo_name,
228
+ workspace=self.workspace,
229
+ git_url=git_url,
230
+ filestore='no_filestore',
231
+ git_sha='HEAD',
232
+ project_src_path=project_src_path,
233
+ base_commit='HEAD^1')
234
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
235
+ self.assertTrue(
236
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
237
+
238
+ def test_valid_commit(self):
239
+ """Tests building fuzzers with valid inputs."""
240
+ config = test_helpers.create_build_config(
241
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
242
+ project_repo_name='oss-fuzz',
243
+ workspace=self.workspace,
244
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
245
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
246
+ cfl_platform='github')
247
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
248
+ self.assertTrue(
249
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
250
+
251
+ def test_valid_pull_request(self):
252
+ """Tests building fuzzers with valid pull request."""
253
+ config = test_helpers.create_build_config(
254
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
255
+ project_repo_name='oss-fuzz',
256
+ workspace=self.workspace,
257
+ pr_ref='refs/pull/1757/merge',
258
+ base_ref='master',
259
+ cfl_platform='github')
260
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
261
+ self.assertTrue(
262
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
263
+
264
+ def test_invalid_pull_request(self):
265
+ """Tests building fuzzers with invalid pull request."""
266
+ config = test_helpers.create_build_config(
267
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
268
+ project_repo_name='oss-fuzz',
269
+ workspace=self.workspace,
270
+ pr_ref='ref-1/merge',
271
+ base_ref='master',
272
+ cfl_platform='github')
273
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
274
+
275
+ def test_invalid_oss_fuzz_project_name(self):
276
+ """Tests building fuzzers with invalid project name."""
277
+ config = test_helpers.create_build_config(
278
+ oss_fuzz_project_name='not_a_valid_project',
279
+ project_repo_name='oss-fuzz',
280
+ workspace=self.workspace,
281
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
282
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
283
+
284
+ def test_invalid_repo_name(self):
285
+ """Tests building fuzzers with invalid repo name."""
286
+ config = test_helpers.create_build_config(
287
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
288
+ project_repo_name='not-real-repo',
289
+ workspace=self.workspace,
290
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
291
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
292
+
293
+ def test_invalid_git_sha(self):
294
+ """Tests building fuzzers with invalid commit SHA."""
295
+ config = test_helpers.create_build_config(
296
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
297
+ project_repo_name='oss-fuzz',
298
+ workspace=self.workspace,
299
+ git_sha='',
300
+ cfl_platform='github')
301
+ with self.assertRaises(AssertionError):
302
+ build_fuzzers.build_fuzzers(config)
303
+
304
+ def test_invalid_workspace(self):
305
+ """Tests building fuzzers with invalid workspace."""
306
+ config = test_helpers.create_build_config(
307
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
308
+ project_repo_name='oss-fuzz',
309
+ workspace=os.path.join(self.workspace, 'not', 'a', 'dir'),
310
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
311
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
312
+
313
+
314
+ class CheckFuzzerBuildTest(unittest.TestCase):
315
+ """Tests the check_fuzzer_build function in the cifuzz module."""
316
+
317
+ SANITIZER = 'address'
318
+ LANGUAGE = 'c++'
319
+
320
+ def setUp(self):
321
+ self.temp_dir_obj = tempfile.TemporaryDirectory()
322
+ workspace_path = os.path.join(self.temp_dir_obj.name, 'workspace')
323
+ self.config = test_helpers.create_build_config(
324
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
325
+ sanitizer=self.SANITIZER,
326
+ language=self.LANGUAGE,
327
+ workspace=workspace_path,
328
+ pr_ref='refs/pull/1757/merge')
329
+ self.workspace = test_helpers.create_workspace(workspace_path)
330
+ shutil.copytree(TEST_DATA_PATH, workspace_path)
331
+ test_helpers.patch_environ(self, runner=True)
332
+
333
+ def tearDown(self):
334
+ self.temp_dir_obj.cleanup()
335
+
336
+ def test_correct_fuzzer_build(self):
337
+ """Checks check_fuzzer_build function returns True for valid fuzzers."""
338
+ self.assertTrue(build_fuzzers.check_fuzzer_build(self.config))
339
+
340
+ def test_not_a_valid_path(self):
341
+ """Tests that False is returned when a nonexistent path is given."""
342
+ self.config.workspace = 'not/a/valid/path'
343
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
344
+
345
+ def test_no_valid_fuzzers(self):
346
+ """Tests that False is returned when an empty directory is given."""
347
+ with tempfile.TemporaryDirectory() as tmp_dir:
348
+ self.config.workspace = tmp_dir
349
+ os.mkdir(os.path.join(self.config.workspace, 'build-out'))
350
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
351
+
352
+ @mock.patch('utils.execute', return_value=(None, None, 0))
353
+ def test_allow_broken_fuzz_targets_percentage(self, mock_execute):
354
+ """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running
355
+ docker if passed to check_fuzzer_build."""
356
+ percentage = '0'
357
+ self.config.allowed_broken_targets_percentage = percentage
358
+ build_fuzzers.check_fuzzer_build(self.config)
359
+ self.assertEqual(
360
+ mock_execute.call_args[1]['env']['ALLOWED_BROKEN_TARGETS_PERCENTAGE'],
361
+ percentage)
362
+
363
+
364
+ @unittest.skip('Test is too long to be run with presubmit.')
365
+ class BuildSantizerIntegrationTest(unittest.TestCase):
366
+ """Integration tests for the build_fuzzers.
367
+ Note: This test relies on "curl" being an OSS-Fuzz project."""
368
+ PROJECT_NAME = 'curl'
369
+ PR_REF = 'fake_pr'
370
+
371
+ @classmethod
372
+ def _create_config(cls, tmp_dir, sanitizer):
373
+ return test_helpers.create_build_config(
374
+ oss_fuzz_project_name=cls.PROJECT_NAME,
375
+ project_repo_name=cls.PROJECT_NAME,
376
+ workspace=tmp_dir,
377
+ pr_ref=cls.PR_REF,
378
+ sanitizer=sanitizer)
379
+
380
+ @parameterized.parameterized.expand([('memory',), ('undefined',)])
381
+ def test_valid_project_curl(self, sanitizer):
382
+ """Tests that MSAN can be detected from project.yaml"""
383
+ with tempfile.TemporaryDirectory() as tmp_dir:
384
+ self.assertTrue(
385
+ build_fuzzers.build_fuzzers(self._create_config(tmp_dir, sanitizer)))
386
+
387
+
388
+ class GetDockerBuildFuzzersArgsNotContainerTest(unittest.TestCase):
389
+ """Tests that _get_docker_build_fuzzers_args_not_container works as
390
+ intended."""
391
+
392
+ def test_get_docker_build_fuzzers_args_no_container(self):
393
+ """Tests that _get_docker_build_fuzzers_args_not_container works
394
+ as intended."""
395
+ host_repo_path = '/host/repo'
396
+ result = build_fuzzers._get_docker_build_fuzzers_args_not_container(
397
+ host_repo_path)
398
+ expected_result = ['-v', '/host/repo:/host/repo']
399
+ self.assertEqual(result, expected_result)
400
+
401
+
402
+ if __name__ == '__main__':
403
+ unittest.main()
local-test-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """End-to-End tests for CIFuzz."""
15
+ import os
16
+ import unittest
17
+
18
+ import run_cifuzz
19
+ import test_helpers
20
+
21
+ CIFUZZ_DIR = os.path.dirname(os.path.abspath(__file__))
22
+ EXTERNAL_PROJECT_PATH = os.path.join(CIFUZZ_DIR, 'test_data',
23
+ 'external-project')
24
+
25
+
26
+ # This test will fail if not run as root because the fuzzer build process
27
+ # creates binaries that only root can write to.
28
+ # Use a seperate env var to keep this seperate from integration tests which
29
+ # don't have this annoying property.
30
+ @unittest.skipIf(not os.getenv('END_TO_END_TESTS'),
31
+ 'END_TO_END_TESTS=1 not set')
32
+ class EndToEndTest(unittest.TestCase):
33
+ """End-to-End tests for CIFuzz."""
34
+
35
+ def setUp(self):
36
+ test_helpers.patch_environ(self, runner=True)
37
+
38
+ def test_simple(self):
39
+ """Simple end-to-end test using run_cifuzz.main()."""
40
+ os.environ['REPOSITORY'] = 'external-project'
41
+ os.environ['PROJECT_SRC_PATH'] = EXTERNAL_PROJECT_PATH
42
+ os.environ['FILESTORE'] = 'no_filestore'
43
+ os.environ['NO_CLUSTERFUZZ_DEPLOYMENT'] = 'True'
44
+
45
+ with test_helpers.docker_temp_dir() as temp_dir:
46
+ os.environ['WORKSPACE'] = temp_dir
47
+ # TODO(metzman): Verify the crash, affected fuzzers, and other things.
48
+ self.assertEqual(run_cifuzz.main(), 1)
local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cloudbuild.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO(metzman): Get rid of cifuzz-build-fuzzers and cifuzz-run-fuzzers.
2
+ steps:
3
+ - name: 'gcr.io/cloud-builders/docker'
4
+ args:
5
+ - build
6
+ - '-t'
7
+ - ghcr.io/aixcc-finals/cifuzz-base
8
+ - '-t'
9
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
10
+ - '-f'
11
+ - infra/cifuzz/cifuzz-base/Dockerfile
12
+ - .
13
+ - name: 'gcr.io/cloud-builders/docker'
14
+ args:
15
+ - build
16
+ - '-t'
17
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
18
+ - '-t'
19
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
20
+ - '-t'
21
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
22
+ - '-t'
23
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
24
+ - '-f'
25
+ - infra/build_fuzzers.Dockerfile
26
+ - infra
27
+ - name: 'gcr.io/cloud-builders/docker'
28
+ args:
29
+ - build
30
+ - '-t'
31
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
32
+ - '-t'
33
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
34
+ - '-t'
35
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
36
+ - '-t'
37
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
38
+ - '-f'
39
+ - infra/run_fuzzers.Dockerfile
40
+ - infra
41
+ images:
42
+ - ghcr.io/aixcc-finals/cifuzz-base
43
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
44
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
45
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
46
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
47
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
48
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
49
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
50
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
51
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
52
+ timeout: 1800s
local-test-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 getting the configuration CIFuzz needs to run."""
15
+
16
+ import enum
17
+ import importlib
18
+ import logging
19
+ import os
20
+ import sys
21
+
22
+ import environment
23
+
24
+ # pylint: disable=wrong-import-position,import-error
25
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
26
+
27
+ import platform_config
28
+ import constants
29
+
30
+ SANITIZERS = ['address', 'memory', 'undefined', 'coverage']
31
+
32
+ # TODO(metzman): Set these on config objects so there's one source of truth.
33
+ DEFAULT_ENGINE = 'libfuzzer'
34
+
35
+ # This module deals a lot with env variables. Many of these will be set by users
36
+ # and others beyond CIFuzz's control. Thus, you should be careful about using
37
+ # the environment.py helpers for getting env vars, since it can cause values
38
+ # that should be interpreted as strings to be returned as other types (bools or
39
+ # ints for example). The environment.py helpers should not be used for values
40
+ # that are supposed to be strings.
41
+
42
+
43
+ def _get_sanitizer():
44
+ return os.getenv('SANITIZER', constants.DEFAULT_SANITIZER).lower()
45
+
46
+
47
+ def _get_architecture():
48
+ return os.getenv('ARCHITECTURE', constants.DEFAULT_ARCHITECTURE).lower()
49
+
50
+
51
+ def _is_dry_run():
52
+ """Returns True if configured to do a dry run."""
53
+ return environment.get_bool('DRY_RUN', False)
54
+
55
+
56
+ def _get_language():
57
+ """Returns the project language."""
58
+ # Get language from environment. We took this approach because the convenience
59
+ # given to OSS-Fuzz users by not making them specify the language again (and
60
+ # getting it from the project.yaml) is outweighed by the complexity in
61
+ # implementing this. A lot of the complexity comes from our unittests not
62
+ # setting a proper projet at this point.
63
+ return os.getenv('LANGUAGE', constants.DEFAULT_LANGUAGE)
64
+
65
+
66
+ def _get_extra_environment_variables():
67
+ """Gets extra environment variables specified by the user with
68
+ CFL_EXTRA_$NAME=$VALUE."""
69
+ return [key for key in os.environ if key.startswith('CFL_EXTRA_')]
70
+
71
+
72
+ # pylint: disable=too-many-instance-attributes
73
+
74
+
75
+ class ConfigError(Exception):
76
+ """Error for invalid configuration."""
77
+
78
+
79
+ class BaseConfig:
80
+ """Object containing constant configuration for CIFuzz."""
81
+
82
+ class Platform(enum.Enum):
83
+ """Enum representing the different platforms CIFuzz runs on."""
84
+ EXTERNAL_GITHUB = 0 # Non-OSS-Fuzz on GitHub actions.
85
+ INTERNAL_GITHUB = 1 # OSS-Fuzz on GitHub actions.
86
+ INTERNAL_GENERIC_CI = 2 # OSS-Fuzz on any CI.
87
+ EXTERNAL_GENERIC_CI = 3 # Non-OSS-Fuzz on any CI.
88
+
89
+ @property
90
+ def is_github(self):
91
+ """Returns True if running on GitHub."""
92
+ return self.cfl_platform == 'github'
93
+
94
+ def __init__(self):
95
+ # Need to set these before calling self.platform.
96
+ self.oss_fuzz_project_name = os.getenv('OSS_FUZZ_PROJECT_NAME')
97
+ self.cfl_platform = os.getenv('CFL_PLATFORM')
98
+ logging.debug('Is github: %s.', self.is_github)
99
+
100
+ self.platform_conf = _get_platform_config(self.cfl_platform)
101
+ self.base_commit = self.platform_conf.base_commit
102
+ self.base_ref = self.platform_conf.base_ref
103
+ self.pr_ref = self.platform_conf.pr_ref
104
+ self.workspace = self.platform_conf.workspace
105
+ self.project_src_path = self.platform_conf.project_src_path
106
+ self.actor = self.platform_conf.actor
107
+ self.token = self.platform_conf.token
108
+ self.project_repo_owner = self.platform_conf.project_repo_owner
109
+ self.project_repo_name = self.platform_conf.project_repo_name
110
+ self.filestore = self.platform_conf.filestore
111
+
112
+ # This determines if builds are done using docker in docker
113
+ # rather than the normal method which is sibling containers.
114
+ self.docker_in_docker = self.platform_conf.docker_in_docker
115
+
116
+ self.dry_run = _is_dry_run() # Check if failures should not be reported.
117
+ self.sanitizer = _get_sanitizer()
118
+ self.architecture = _get_architecture()
119
+ self.language = _get_language()
120
+ self.low_disk_space = environment.get_bool('LOW_DISK_SPACE', False)
121
+
122
+ self.git_store_repo = os.environ.get('GIT_STORE_REPO')
123
+ self.git_store_branch = os.environ.get('GIT_STORE_BRANCH')
124
+ self.git_store_branch_coverage = os.environ.get('GIT_STORE_BRANCH_COVERAGE',
125
+ self.git_store_branch)
126
+ self.cloud_bucket = os.environ.get('CLOUD_BUCKET')
127
+ self.no_clusterfuzz_deployment = environment.get_bool(
128
+ 'NO_CLUSTERFUZZ_DEPLOYMENT', False)
129
+ self.build_integration_path = (
130
+ constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH)
131
+
132
+ self.parallel_fuzzing = environment.get_bool('PARALLEL_FUZZING', False)
133
+ self.extra_environment_variables = _get_extra_environment_variables()
134
+ self.output_sarif = environment.get_bool('OUTPUT_SARIF', False)
135
+
136
+ # TODO(metzman): Fix tests to create valid configurations and get rid of
137
+ # CIFUZZ_TEST here and in presubmit.py.
138
+ if not os.getenv('CIFUZZ_TEST') and not self.validate():
139
+ raise ConfigError('Invalid Configuration.')
140
+
141
+ def validate(self):
142
+ """Returns False if the configuration is invalid."""
143
+ # Do validation here so that unittests don't need to make a fully-valid
144
+ # config.
145
+ # pylint: disable=too-many-return-statements
146
+ if not self.workspace:
147
+ logging.error('Must set WORKSPACE.')
148
+ return False
149
+
150
+ if self.sanitizer not in SANITIZERS:
151
+ logging.error('Invalid SANITIZER: %s. Must be one of: %s.',
152
+ self.sanitizer, SANITIZERS)
153
+ return False
154
+
155
+ if self.architecture not in constants.ARCHITECTURES:
156
+ logging.error('Invalid ARCHITECTURE: %s. Must be one of: %s.',
157
+ self.architecture, constants.ARCHITECTURES)
158
+ return False
159
+
160
+ if self.architecture == 'i386' and self.sanitizer != 'address':
161
+ logging.error(
162
+ 'ARCHITECTURE=i386 can be used with SANITIZER=address only.')
163
+ return False
164
+
165
+ if self.language not in constants.LANGUAGES:
166
+ logging.error('Invalid LANGUAGE: %s. Must be one of: %s.', self.language,
167
+ constants.LANGUAGES)
168
+ return False
169
+
170
+ if not self.project_repo_name:
171
+ logging.error('Must set REPOSITORY.')
172
+ return False
173
+
174
+ return True
175
+
176
+ @property
177
+ def is_internal(self):
178
+ """Returns True if this is an OSS-Fuzz project."""
179
+ return bool(self.oss_fuzz_project_name)
180
+
181
+ @property
182
+ def platform(self):
183
+ """Returns the platform CIFuzz is runnning on."""
184
+ if not self.is_internal:
185
+ if not self.is_github:
186
+ return self.Platform.EXTERNAL_GENERIC_CI
187
+ return self.Platform.EXTERNAL_GITHUB
188
+
189
+ if self.is_github:
190
+ return self.Platform.INTERNAL_GITHUB
191
+ return self.Platform.INTERNAL_GENERIC_CI
192
+
193
+ @property
194
+ def is_coverage(self):
195
+ """Returns True if this CIFuzz run (building fuzzers and running them) for
196
+ generating a coverage report."""
197
+ return self.sanitizer == 'coverage'
198
+
199
+
200
+ def _get_platform_config(cfl_platform):
201
+ """Returns the CI environment object for |cfl_platform|."""
202
+ module_name = f'platform_config.{cfl_platform}'
203
+ try:
204
+ cls = importlib.import_module(module_name).PlatformConfig
205
+ except ImportError:
206
+ cls = platform_config.BasePlatformConfig
207
+ return cls()
208
+
209
+
210
+ class RunFuzzersConfig(BaseConfig):
211
+ """Class containing constant configuration for running fuzzers in CIFuzz."""
212
+
213
+ MODES = ['batch', 'code-change', 'coverage', 'prune']
214
+
215
+ def __init__(self):
216
+ super().__init__()
217
+ # TODO(metzman): Pick a better default for pruning.
218
+ self.fuzz_seconds = int(os.environ.get('FUZZ_SECONDS', 600))
219
+ self.mode = os.environ.get('MODE', 'code-change').lower()
220
+ if self.is_coverage:
221
+ self.mode = 'coverage'
222
+
223
+ self.report_unreproducible_crashes = environment.get_bool(
224
+ 'REPORT_UNREPRODUCIBLE_CRASHES', False)
225
+
226
+ self.minimize_crashes = environment.get_bool('MINIMIZE_CRASHES', False)
227
+ if self.mode == 'batch':
228
+ logging.warning(
229
+ 'Minimizing crashes reduces fuzzing time in batch fuzzing.')
230
+ self.report_timeouts = environment.get_bool('REPORT_TIMEOUTS', False)
231
+ self.report_ooms = environment.get_bool('REPORT_OOMS', True)
232
+ self.upload_all_crashes = environment.get_bool('UPLOAD_ALL_CRASHES', False)
233
+
234
+ # TODO(metzman): Fix tests to create valid configurations and get rid of
235
+ # CIFUZZ_TEST here and in presubmit.py.
236
+ if not os.getenv('CIFUZZ_TEST') and not self._run_config_validate():
237
+ raise ConfigError('Invalid Run Configuration.')
238
+
239
+ def _run_config_validate(self):
240
+ """Do extra validation on RunFuzzersConfig.__init__(). Do not name this
241
+ validate or else it will be called when using the parent's __init__ and will
242
+ fail. Returns True if valid."""
243
+ if self.mode not in self.MODES:
244
+ logging.error('Invalid MODE: %s. Must be one of %s.', self.mode,
245
+ self.MODES)
246
+ return False
247
+
248
+ return True
249
+
250
+
251
+ class BuildFuzzersConfig(BaseConfig):
252
+ """Class containing constant configuration for building fuzzers in CIFuzz."""
253
+
254
+ def __init__(self):
255
+ """Get the configuration from CIFuzz from the environment. These variables
256
+ are set by GitHub or the user."""
257
+ super().__init__()
258
+ self.git_sha = self.platform_conf.git_sha
259
+ self.git_url = self.platform_conf.git_url
260
+
261
+ self.allowed_broken_targets_percentage = os.getenv(
262
+ 'ALLOWED_BROKEN_TARGETS_PERCENTAGE')
263
+ self.bad_build_check = environment.get_bool('BAD_BUILD_CHECK', True)
264
+
265
+ self.keep_unaffected_fuzz_targets = environment.get_bool(
266
+ 'KEEP_UNAFFECTED_FUZZ_TARGETS')
267
+
268
+ self.upload_build = environment.get_bool('UPLOAD_BUILD', False)
269
+ if not self.keep_unaffected_fuzz_targets:
270
+ has_base_for_diff = (self.base_ref or self.base_commit)
271
+ if not has_base_for_diff:
272
+ logging.info(
273
+ 'Keeping all fuzzers because there is nothing to diff against.')
274
+ self.keep_unaffected_fuzz_targets = True
275
+ elif self.upload_build:
276
+ logging.info('Keeping all fuzzers because we are uploading build.')
277
+ self.keep_unaffected_fuzz_targets = True
278
+ elif self.sanitizer == 'coverage':
279
+ logging.info('Keeping all fuzzers because we are doing coverage.')
280
+ self.keep_unaffected_fuzz_targets = True
281
+
282
+ if self.sanitizer == 'coverage':
283
+ self.bad_build_check = False
local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils_test.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for config_utils."""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import config_utils
20
+ import constants
21
+ import test_helpers
22
+
23
+ # pylint: disable=no-self-use,protected-access
24
+
25
+
26
+ class BaseConfigTest(unittest.TestCase):
27
+ """Tests for BaseConfig."""
28
+
29
+ def setUp(self):
30
+ test_helpers.patch_environ(self)
31
+
32
+ def _create_config(self):
33
+ return config_utils.BuildFuzzersConfig()
34
+
35
+ def test_language_default(self):
36
+ """Tests that the correct default language is set."""
37
+ config = self._create_config()
38
+ self.assertEqual(config.language, 'c++')
39
+
40
+ def test_language(self):
41
+ """Tests that the correct language is set."""
42
+ language = 'python'
43
+ os.environ['LANGUAGE'] = language
44
+ config = self._create_config()
45
+ self.assertEqual(config.language, language)
46
+
47
+ def test_is_coverage(self):
48
+ """Tests that is_coverage is set correctly."""
49
+ # Test it is set when it is supposed to be.
50
+ os.environ['SANITIZER'] = 'coverage'
51
+ config = self._create_config()
52
+ self.assertTrue(config.is_coverage)
53
+
54
+ # Test it is not set when it is not supposed to be.
55
+ os.environ['SANITIZER'] = 'address'
56
+ config = self._create_config()
57
+ self.assertFalse(config.is_coverage)
58
+
59
+ @mock.patch('logging.error')
60
+ def test_validate_no_workspace(self, mock_error):
61
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
62
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
63
+ config = self._create_config()
64
+ self.assertFalse(config.validate())
65
+ mock_error.assert_called_with('Must set WORKSPACE.')
66
+
67
+ @mock.patch('logging.error')
68
+ def test_validate_invalid_language(self, mock_error):
69
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
70
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
71
+ os.environ['WORKSPACE'] = '/workspace'
72
+ os.environ['LANGUAGE'] = 'invalid-language'
73
+ config = self._create_config()
74
+ self.assertFalse(config.validate())
75
+ mock_error.assert_called_with('Invalid LANGUAGE: %s. Must be one of: %s.',
76
+ os.environ['LANGUAGE'], constants.LANGUAGES)
77
+
78
+ @mock.patch('logging.error')
79
+ def test_validate_invalid_sanitizer(self, mock_error):
80
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
81
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
82
+ os.environ['WORKSPACE'] = '/workspace'
83
+ os.environ['SANITIZER'] = 'invalid-sanitizer'
84
+ config = self._create_config()
85
+ self.assertFalse(config.validate())
86
+ mock_error.assert_called_with('Invalid SANITIZER: %s. Must be one of: %s.',
87
+ os.environ['SANITIZER'],
88
+ config_utils.SANITIZERS)
89
+
90
+ def test_validate(self):
91
+ """Tests that validate returns True if config is valid."""
92
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
93
+ os.environ['WORKSPACE'] = '/workspace'
94
+ os.environ['REPOSITORY'] = 'repo'
95
+ config = self._create_config()
96
+ self.assertTrue(config.validate())
97
+
98
+
99
+ class BuildFuzzersConfigTest(unittest.TestCase):
100
+ """Tests for BuildFuzzersConfig."""
101
+
102
+ def setUp(self):
103
+ test_helpers.patch_environ(self)
104
+
105
+ def _create_config(self):
106
+ return config_utils.BuildFuzzersConfig()
107
+
108
+ @mock.patch('platform_config.github._get_event_data', return_value={})
109
+ def test_github_base_ref(self, _):
110
+ """Tests that base_ref is set properly."""
111
+ expected_base_ref = 'expected_base_ref'
112
+ os.environ['GITHUB_BASE_REF'] = expected_base_ref
113
+ os.environ['CFL_PLATFORM'] = 'github'
114
+ os.environ['GITHUB_REPOSITORY'] = 'owner/repo'
115
+ config = self._create_config()
116
+ self.assertEqual(config.base_ref, expected_base_ref)
117
+
118
+ def test_base_ref(self):
119
+ """Tests that base_ref is set properly."""
120
+ expected_base_ref = 'expected_base_ref'
121
+ os.environ['GIT_BASE_REF'] = expected_base_ref
122
+ config = self._create_config()
123
+ self.assertEqual(config.base_ref, expected_base_ref)
124
+
125
+ def test_keep_unaffected_defaults_to_true(self):
126
+ """Tests that keep_unaffected_fuzz_targets defaults to true."""
127
+ config = self._create_config()
128
+ self.assertTrue(config.keep_unaffected_fuzz_targets)
129
+
130
+ def test_keep_unaffected_defaults_to_false_when_pr(self):
131
+ """Tests that keep_unaffected_fuzz_targets defaults to false when from a
132
+ pr."""
133
+ os.environ['GIT_BASE_REF'] = 'base-ref'
134
+ config = self._create_config()
135
+ self.assertFalse(config.keep_unaffected_fuzz_targets)
136
+
137
+
138
+ class RunFuzzersConfigTest(unittest.TestCase):
139
+ """Tests for RunFuzzersConfig."""
140
+
141
+ def setUp(self):
142
+ test_helpers.patch_environ(self)
143
+
144
+ def _create_config(self):
145
+ return config_utils.RunFuzzersConfig()
146
+
147
+ def test_coverage(self):
148
+ """Tests that mode is overriden properly based on is_coverage."""
149
+ # Test that it is overriden when it is supposed to be.
150
+ os.environ['SANITIZER'] = 'coverage'
151
+ os.environ['MODE'] = 'code-change'
152
+ config = self._create_config()
153
+ self.assertEqual(config.mode, 'coverage')
154
+
155
+ # Test that it isn't overriden when it isn't supposed to be.
156
+ os.environ['SANITIZER'] = 'address'
157
+ mode = 'code-change'
158
+ os.environ['MODE'] = mode
159
+ config = self._create_config()
160
+ self.assertEqual(config.mode, mode)
161
+
162
+ def test_run_config_validate(self):
163
+ """Tests that _run_config_validate returns True when the config is valid."""
164
+ self.assertTrue(self._create_config()._run_config_validate())
165
+
166
+ @mock.patch('logging.error')
167
+ def test_run_config_invalid_mode(self, mock_error):
168
+ """Tests that _run_config_validate returns False when mode is invalid."""
169
+ fake_mode = 'fake-mode'
170
+ os.environ['MODE'] = fake_mode
171
+ self.assertFalse(self._create_config()._run_config_validate())
172
+ mock_error.assert_called_with('Invalid MODE: %s. Must be one of %s.',
173
+ fake_mode,
174
+ config_utils.RunFuzzersConfig.MODES)
175
+
176
+
177
+ class GetSanitizerTest(unittest.TestCase):
178
+ """Tests for _get_sanitizer."""
179
+
180
+ def setUp(self):
181
+ test_helpers.patch_environ(self)
182
+ self.sanitizer = 'memory'
183
+
184
+ def test_default_value(self):
185
+ """Tests that the default value returned by _get_sanitizer is correct."""
186
+ self.assertEqual(config_utils._get_sanitizer(), 'address')
187
+
188
+ def test_normal_case(self):
189
+ """Tests that _get_sanitizer returns the correct value in normal cases."""
190
+ os.environ['SANITIZER'] = self.sanitizer
191
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
192
+
193
+ def test_capitalization(self):
194
+ """Tests that that _get_sanitizer handles capitalization properly."""
195
+ os.environ['SANITIZER'] = self.sanitizer.upper()
196
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
197
+
198
+
199
+ if __name__ == '__main__':
200
+ unittest.main()
local-test-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/environment.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for dealing with env vars."""
15
+
16
+ import ast
17
+ import os
18
+
19
+
20
+ def _eval_value(value_string):
21
+ """Returns evaluated value."""
22
+ try:
23
+ return ast.literal_eval(value_string)
24
+ except: # pylint: disable=bare-except
25
+ # String fallback.
26
+ return value_string
27
+
28
+
29
+ def get(env_var, default_value=None):
30
+ """Returns an environment variable value."""
31
+ value_string = os.getenv(env_var)
32
+ if value_string is None:
33
+ return default_value
34
+
35
+ return _eval_value(value_string)
36
+
37
+
38
+ def get_bool(env_var, default_value=None):
39
+ """Returns a boolean environment variable value. This is needed because a lot
40
+ of CIFuzz users specified 'false' for dry-run. So we need to special case
41
+ this."""
42
+ value = get(env_var, default_value)
43
+ if not isinstance(value, str):
44
+ return bool(value)
45
+
46
+ lower_value = value.lower()
47
+ allowed_values = {'true', 'false'}
48
+ if lower_value not in allowed_values:
49
+ raise Exception(f'Bool env var {env_var} value {value} is invalid. '
50
+ f'Must be one of {allowed_values}.')
51
+ return lower_value == 'true'
local-test-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils_test.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for filestore_utils."""
15
+ import unittest
16
+ from unittest import mock
17
+
18
+ import parameterized
19
+
20
+ import platform_config
21
+ import filestore
22
+ from filestore import github_actions
23
+ import filestore_utils
24
+ import test_helpers
25
+
26
+
27
+ class GetFilestoreTest(unittest.TestCase):
28
+ """Tests for get_filestore."""
29
+
30
+ @parameterized.parameterized.expand([
31
+ ({
32
+ 'cfl_platform': 'github',
33
+ }, github_actions.GithubActionsFilestore),
34
+ ])
35
+ def test_get_filestore(self, config_kwargs, filestore_cls):
36
+ """Tests that get_filestore returns the right filestore given a certain
37
+ platform."""
38
+ run_config = test_helpers.create_run_config(**config_kwargs)
39
+ filestore_impl = filestore_utils.get_filestore(run_config)
40
+ self.assertIsInstance(filestore_impl, filestore_cls)
41
+
42
+ @mock.patch('config_utils.BaseConfig.platform', return_value='other')
43
+ @mock.patch('config_utils._get_platform_config',
44
+ return_value=platform_config.BasePlatformConfig())
45
+ def test_get_filestore_unsupported_platform(self, _, __):
46
+ """Tests that get_filestore exceptions given a platform it doesn't
47
+ support."""
48
+ run_config = test_helpers.create_run_config()
49
+ with self.assertRaises(filestore.FilestoreError):
50
+ filestore_utils.get_filestore(run_config)
local-test-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target_test.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests the functionality of the fuzz_target module."""
15
+
16
+ import os
17
+ import shutil
18
+ import tempfile
19
+ import unittest
20
+ from unittest import mock
21
+
22
+ import certifi
23
+ # Importing this later causes import failures with pytest for some reason.
24
+ # TODO(ochang): Figure out why.
25
+ import parameterized
26
+ import google.cloud.ndb # pylint: disable=unused-import
27
+ from pyfakefs import fake_filesystem_unittest
28
+ from clusterfuzz.fuzz import engine
29
+
30
+ import clusterfuzz_deployment
31
+ import fuzz_target
32
+ import test_helpers
33
+ import workspace_utils
34
+
35
+ # NOTE: This integration test relies on
36
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
37
+ EXAMPLE_PROJECT = 'example'
38
+
39
+ # An example fuzzer that triggers an error.
40
+ EXAMPLE_FUZZER = 'example_crash_fuzzer'
41
+
42
+ # Mock return values for engine_impl.reproduce.
43
+ EXECUTE_SUCCESS_RESULT = engine.ReproduceResult([], 0, 0, '')
44
+ EXECUTE_FAILURE_RESULT = engine.ReproduceResult([], 1, 0, '')
45
+
46
+ TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'test_data')
47
+
48
+
49
+ def _create_config(**kwargs):
50
+ """Creates a config object and then sets every attribute that is a key in
51
+ |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an
52
+ attribute of Config."""
53
+ defaults = {
54
+ 'cfl_platform': 'github',
55
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT,
56
+ 'workspace': '/workspace'
57
+ }
58
+ for default_key, default_value in defaults.items():
59
+ if default_key not in kwargs:
60
+ kwargs[default_key] = default_value
61
+
62
+ return test_helpers.create_run_config(**kwargs)
63
+
64
+
65
+ def _create_deployment(**kwargs):
66
+ config = _create_config(**kwargs)
67
+ workspace = workspace_utils.Workspace(config)
68
+ return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace)
69
+
70
+
71
+ @mock.patch('utils.get_container_name', return_value='container')
72
+ class IsReproducibleTest(fake_filesystem_unittest.TestCase):
73
+ """Tests the is_reproducible method in the fuzz_target.FuzzTarget class."""
74
+
75
+ def setUp(self):
76
+ """Sets up example fuzz target to test is_reproducible method."""
77
+ self.fuzz_target_name = 'fuzz-target'
78
+ deployment = _create_deployment()
79
+ self.config = deployment.config
80
+ self.workspace = deployment.workspace
81
+ self.fuzz_target_path = os.path.join(self.workspace.out,
82
+ self.fuzz_target_name)
83
+ self.setUpPyfakefs()
84
+ self.fs.create_file(self.fuzz_target_path)
85
+ self.testcase_path = '/testcase'
86
+ self.fs.create_file(self.testcase_path)
87
+
88
+ self.target = fuzz_target.FuzzTarget(self.fuzz_target_path,
89
+ fuzz_target.REPRODUCE_ATTEMPTS,
90
+ self.workspace, deployment,
91
+ deployment.config)
92
+
93
+ # ClusterFuzz requires ROOT_DIR.
94
+ root_dir = os.environ['ROOT_DIR']
95
+ test_helpers.patch_environ(self, empty=True)
96
+ os.environ['ROOT_DIR'] = root_dir
97
+
98
+ # There's an extremely bad issue that happens if this test is run: Other tests
99
+ # in this file fail in CI with stacktraces using referencing fakefs even if
100
+ # the tests do not use fakefs.
101
+ # TODO(metzman): Stop using fakefs.
102
+ @mock.patch('os.chmod')
103
+ @unittest.skip('Skip because of weird failures.')
104
+ def test_repro_timed_out(self, mock_chmod, mock_get_container_name):
105
+ """Tests that is_reproducible behaves correctly when reproduction times
106
+ out."""
107
+ del mock_get_container_name
108
+ del mock_chmod
109
+
110
+ with mock.patch(
111
+ 'clusterfuzz._internal.bot.fuzzers.libFuzzer.engine.LibFuzzerEngine.'
112
+ 'reproduce',
113
+ side_effect=TimeoutError):
114
+ self.assertFalse(
115
+ self.target.is_reproducible('/testcase', self.target.target_path, []))
116
+
117
+ def test_reproducible(self, _):
118
+ """Tests that is_reproducible returns True if crash is detected and that
119
+ is_reproducible uses the correct command to reproduce a crash."""
120
+ all_repro = [EXECUTE_FAILURE_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS
121
+ with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine:
122
+ mock_get_engine().reproduce.side_effect = all_repro
123
+
124
+ result = self.target.is_reproducible(self.testcase_path,
125
+ self.fuzz_target_path, [])
126
+ mock_get_engine().reproduce.assert_called_once_with(
127
+ '/workspace/build-out/fuzz-target',
128
+ '/testcase',
129
+ arguments=[],
130
+ max_time=30)
131
+ self.assertTrue(result)
132
+ self.assertEqual(1, mock_get_engine().reproduce.call_count)
133
+
134
+ def test_flaky(self, _):
135
+ """Tests that is_reproducible returns True if crash is detected on the last
136
+ attempt."""
137
+ last_time_repro = [EXECUTE_SUCCESS_RESULT] * 9 + [EXECUTE_FAILURE_RESULT]
138
+ with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine:
139
+ mock_get_engine().reproduce.side_effect = last_time_repro
140
+ self.assertTrue(
141
+ self.target.is_reproducible(self.testcase_path, self.fuzz_target_path,
142
+ []))
143
+ self.assertEqual(fuzz_target.REPRODUCE_ATTEMPTS,
144
+ mock_get_engine().reproduce.call_count)
145
+
146
+ def test_nonexistent_fuzzer(self, _):
147
+ """Tests that is_reproducible raises an error if it could not attempt
148
+ reproduction because the fuzzer doesn't exist."""
149
+ with self.assertRaises(fuzz_target.ReproduceError):
150
+ self.target.is_reproducible(self.testcase_path, '/non-existent-path', [])
151
+
152
+ def test_unreproducible(self, _):
153
+ """Tests that is_reproducible returns False for a crash that did not
154
+ reproduce."""
155
+ all_unrepro = [EXECUTE_SUCCESS_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS
156
+ with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine:
157
+ mock_get_engine().reproduce.side_effect = all_unrepro
158
+ result = self.target.is_reproducible(self.testcase_path,
159
+ self.fuzz_target_path, [])
160
+ self.assertFalse(result)
161
+
162
+
163
+ class IsCrashReportableTest(fake_filesystem_unittest.TestCase):
164
+ """Tests the is_crash_reportable method of FuzzTarget."""
165
+
166
+ def setUp(self):
167
+ """Sets up example fuzz target to test is_crash_reportable method."""
168
+ self.setUpPyfakefs()
169
+ self.fuzz_target_path = '/example/do_stuff_fuzzer'
170
+ deployment = _create_deployment()
171
+ self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, 100,
172
+ deployment.workspace, deployment,
173
+ deployment.config)
174
+ self.oss_fuzz_build_path = '/oss-fuzz-build'
175
+ self.fs.create_file(self.fuzz_target_path)
176
+ self.oss_fuzz_target_path = os.path.join(
177
+ self.oss_fuzz_build_path, os.path.basename(self.fuzz_target_path))
178
+ self.fs.create_file(self.oss_fuzz_target_path)
179
+ self.testcase_path = '/testcase'
180
+ self.fs.create_file(self.testcase_path, contents='')
181
+
182
+ # Do this to prevent pyfakefs from messing with requests.
183
+ self.fs.add_real_directory(os.path.dirname(certifi.__file__))
184
+
185
+ @mock.patch('fuzz_target.FuzzTarget.is_reproducible',
186
+ side_effect=[True, False])
187
+ @mock.patch('logging.info')
188
+ def test_new_reproducible_crash(self, mock_info, _):
189
+ """Tests that a new reproducible crash returns True."""
190
+ with tempfile.TemporaryDirectory() as tmp_dir:
191
+ self.target.out_dir = tmp_dir
192
+ self.assertTrue(self.target.is_crash_reportable(self.testcase_path, []))
193
+ mock_info.assert_called_with(
194
+ 'The crash is not reproducible on previous build. '
195
+ 'Code change (pr/commit) introduced crash.')
196
+
197
+ # yapf: disable
198
+ @parameterized.parameterized.expand([
199
+ # Reproducible on PR build, but also reproducible on OSS-Fuzz.
200
+ ([True, True],),
201
+
202
+ # Not reproducible on PR build, but somehow reproducible on OSS-Fuzz.
203
+ # Unlikely to happen in real world except if test is flaky.
204
+ ([False, True],),
205
+
206
+ # Not reproducible on PR build, and not reproducible on OSS-Fuzz.
207
+ ([False, False],),
208
+ ])
209
+ # yapf: enable
210
+ def test_invalid_crash(self, is_reproducible_retvals):
211
+ """Tests that a nonreportable crash causes the method to return False."""
212
+ with mock.patch('fuzz_target.FuzzTarget.is_reproducible',
213
+ side_effect=is_reproducible_retvals):
214
+ with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build',
215
+ return_value=self.oss_fuzz_build_path):
216
+ self.assertFalse(self.target.is_crash_reportable(
217
+ self.testcase_path, []))
218
+
219
+ @mock.patch('logging.info')
220
+ @mock.patch('fuzz_target.FuzzTarget.is_reproducible', return_value=[True])
221
+ def test_reproducible_no_oss_fuzz_target(self, _, mock_info):
222
+ """Tests that is_crash_reportable returns True when a crash reproduces on
223
+ the PR build but the target is not in the OSS-Fuzz build (usually because it
224
+ is new)."""
225
+ os.remove(self.oss_fuzz_target_path)
226
+
227
+ def is_reproducible_side_effect(testcase, target_path, reproduce_arguments):
228
+ del testcase
229
+ del reproduce_arguments
230
+ if os.path.dirname(target_path) == self.oss_fuzz_build_path:
231
+ raise fuzz_target.ReproduceError()
232
+ return True
233
+
234
+ with mock.patch(
235
+ 'fuzz_target.FuzzTarget.is_reproducible',
236
+ side_effect=is_reproducible_side_effect) as mock_is_reproducible:
237
+ with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build',
238
+ return_value=self.oss_fuzz_build_path):
239
+ self.assertTrue(self.target.is_crash_reportable(self.testcase_path, []))
240
+ mock_is_reproducible.assert_any_call(self.testcase_path,
241
+ self.oss_fuzz_target_path, [])
242
+ mock_info.assert_called_with(
243
+ 'Could not run previous build of target to determine if this code '
244
+ 'change (pr/commit) introduced crash. Assuming crash was newly '
245
+ 'introduced.')
246
+
247
+
248
+ class FuzzTest(fake_filesystem_unittest.TestCase):
249
+ """Fuzz test."""
250
+
251
+ def setUp(self):
252
+ """Sets up example fuzz target."""
253
+ self.setUpPyfakefs()
254
+ deployment = _create_deployment()
255
+ config = deployment.config
256
+ workspace = deployment.workspace
257
+ self.fuzz_target = fuzz_target.FuzzTarget('/path/fuzz-target', 10,
258
+ workspace, deployment, config)
259
+
260
+ def test_get_fuzz_target_artifact(self):
261
+ """Tests that get_fuzz_target_artifact works as intended."""
262
+ # pylint: disable=protected-access
263
+ fuzz_target_artifact = self.fuzz_target._target_artifact_path()
264
+ self.assertEqual('/workspace/out/artifacts/fuzz-target/address',
265
+ fuzz_target_artifact)
266
+
267
+
268
+ class TimeoutIntegrationTest(unittest.TestCase):
269
+ """Tests handling of fuzzer timeout (timeout crashes reported by
270
+ libFuzzer)."""
271
+ TIMEOUT_FUZZER_NAME = 'timeout_fuzzer'
272
+
273
+ @parameterized.parameterized.expand([(True, True), (False, False)])
274
+ def test_timeout_reported(self, report_timeouts, expect_crash):
275
+ """Tests that timeouts are not reported."""
276
+ with test_helpers.temp_dir_copy(TEST_DATA_PATH) as temp_dir:
277
+ fuzz_target_path = os.path.join(temp_dir, 'build-out',
278
+ self.TIMEOUT_FUZZER_NAME)
279
+ shutil.copy(os.path.join(temp_dir, self.TIMEOUT_FUZZER_NAME),
280
+ fuzz_target_path)
281
+ deployment = _create_deployment(workspace=temp_dir,
282
+ report_timeouts=report_timeouts)
283
+ config = deployment.config
284
+ fuzz_target_obj = fuzz_target.FuzzTarget(fuzz_target_path,
285
+ fuzz_target.REPRODUCE_ATTEMPTS,
286
+ deployment.workspace, deployment,
287
+ config)
288
+ with mock.patch('clusterfuzz._internal.bot.fuzzers.libfuzzer.'
289
+ 'fix_timeout_argument_for_reproduction') as _:
290
+ with mock.patch(
291
+ 'clusterfuzz._internal.bot.fuzzers.libFuzzer.fuzzer.get_arguments',
292
+ return_value=['-timeout=1', '-rss_limit_mb=2560']):
293
+ fuzz_result = fuzz_target_obj.fuzz()
294
+ self.assertEqual(bool(fuzz_result.testcase), expect_crash)
295
+
296
+
297
+ if __name__ == '__main__':
298
+ unittest.main()
local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for generating coverage reports."""
15
+ import os
16
+
17
+ import base_runner_utils
18
+ import fuzz_target
19
+ import utils
20
+
21
+
22
+ def run_coverage_command(config, workspace):
23
+ """Runs the coverage command in base-runner to generate a coverage report."""
24
+ env = base_runner_utils.get_env(config, workspace)
25
+ env['HTTP_PORT'] = ''
26
+ env['COVERAGE_EXTRA_ARGS'] = ''
27
+ env['CORPUS_DIR'] = workspace.corpora
28
+ env['COVERAGE_OUTPUT_DIR'] = workspace.coverage_report
29
+ command = 'coverage'
30
+ return utils.execute(command, env=env)
31
+
32
+
33
+ def download_corpora(fuzz_target_paths, clusterfuzz_deployment):
34
+ """Downloads corpora for fuzz targets in |fuzz_target_paths| using
35
+ |clusterfuzz_deployment| to download corpora from ClusterFuzz/OSS-Fuzz."""
36
+ for target_path in fuzz_target_paths:
37
+ target_name = os.path.basename(target_path)
38
+ corpus_dir = fuzz_target.get_fuzz_target_corpus_dir(
39
+ clusterfuzz_deployment.workspace, target_name)
40
+ clusterfuzz_deployment.download_corpus(target_name, corpus_dir)
41
+
42
+
43
+ def generate_coverage_report(fuzz_target_paths, workspace,
44
+ clusterfuzz_deployment, config):
45
+ """Generates a coverage report using Clang's source based coverage."""
46
+ download_corpora(fuzz_target_paths, clusterfuzz_deployment)
47
+ run_coverage_command(config, workspace)
48
+ clusterfuzz_deployment.upload_coverage()
local-test-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 determining coverage of fuzz targets."""
15
+ import json
16
+ import logging
17
+ import os
18
+ import sys
19
+
20
+ import http_utils
21
+
22
+ # pylint: disable=wrong-import-position,import-error
23
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
24
+ import utils
25
+
26
+ # The path to get OSS-Fuzz project's latest report json file.`
27
+ OSS_FUZZ_LATEST_COVERAGE_INFO_PATH = 'oss-fuzz-coverage/latest_report_info/'
28
+
29
+
30
+ # pylint: disable=too-few-public-methods
31
+ class CoverageError(Exception):
32
+ """Exceptions for project coverage."""
33
+
34
+
35
+ class BaseCoverage:
36
+ """Gets coverage data for a project."""
37
+
38
+ def __init__(self, repo_path):
39
+ self.repo_path = _normalize_repo_path(repo_path)
40
+
41
+ def get_files_covered_by_target(self, target):
42
+ """Returns a list of source files covered by the specific fuzz target.
43
+
44
+ Args:
45
+ target: The name of the fuzz target whose coverage is requested.
46
+
47
+ Returns:
48
+ A list of files that the fuzz target covers or None.
49
+ """
50
+ target_cov = self.get_target_coverage(target)
51
+ if not target_cov:
52
+ logging.info('No coverage available for %s.', target)
53
+ return None
54
+
55
+ coverage_per_file = get_coverage_per_file(target_cov)
56
+ if not coverage_per_file:
57
+ logging.info('No files found in coverage report.')
58
+ return None
59
+
60
+ affected_file_list = []
61
+ for file_cov in coverage_per_file:
62
+ norm_file_path = os.path.normpath(file_cov['filename'])
63
+ if not norm_file_path.startswith(self.repo_path):
64
+ # Exclude files outside of the main repo.
65
+ continue
66
+
67
+ if not is_file_covered(file_cov):
68
+ # Don't consider a file affected if code in it is never executed.
69
+ continue
70
+
71
+ # TODO(metzman): It's weird to me that we access file_cov['filename']
72
+ # again and not norm_file_path, figure out if this makes sense.
73
+ relative_path = utils.remove_prefix(file_cov['filename'], self.repo_path)
74
+ affected_file_list.append(relative_path)
75
+
76
+ return affected_file_list
77
+
78
+ def get_target_coverage(self, target):
79
+ """Get the coverage report for a specific fuzz target.
80
+
81
+ Args:
82
+ target: The name of the fuzz target whose coverage is requested.
83
+
84
+ Returns:
85
+ The target's coverage json dict or None on failure.
86
+ """
87
+ raise NotImplementedError('Child class must implement method.')
88
+
89
+
90
+ class OSSFuzzCoverage(BaseCoverage):
91
+ """Gets coverage data for a project from OSS-Fuzz."""
92
+
93
+ def __init__(self, repo_path, oss_fuzz_project_name):
94
+ """Constructor for OSSFuzzCoverage."""
95
+ super().__init__(repo_path)
96
+ self.oss_fuzz_project_name = oss_fuzz_project_name
97
+ self.fuzzer_stats_url = _get_oss_fuzz_fuzzer_stats_dir_url(
98
+ self.oss_fuzz_project_name)
99
+ if self.fuzzer_stats_url is None:
100
+ raise CoverageError('Could not get latest coverage.')
101
+
102
+ def get_target_coverage(self, target):
103
+ """Get the coverage report for a specific fuzz target.
104
+
105
+ Args:
106
+ target: The name of the fuzz target whose coverage is requested.
107
+
108
+ Returns:
109
+ The target's coverage json dict or None on failure.
110
+ """
111
+ if not self.fuzzer_stats_url:
112
+ return None
113
+
114
+ target_url = utils.url_join(self.fuzzer_stats_url, target + '.json')
115
+ return http_utils.get_json_from_url(target_url)
116
+
117
+
118
+ def _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name):
119
+ """Gets and returns a dictionary containing the latest coverage report info
120
+ for |project|."""
121
+ latest_report_info_url = utils.url_join(utils.GCS_BASE_URL,
122
+ OSS_FUZZ_LATEST_COVERAGE_INFO_PATH,
123
+ oss_fuzz_project_name + '.json')
124
+ latest_cov_info = http_utils.get_json_from_url(latest_report_info_url)
125
+ if latest_cov_info is None:
126
+ logging.error('Could not get the coverage report json from url: %s.',
127
+ latest_report_info_url)
128
+ return None
129
+ return latest_cov_info
130
+
131
+
132
+ def _get_oss_fuzz_fuzzer_stats_dir_url(oss_fuzz_project_name):
133
+ """Gets latest coverage report info for a specific OSS-Fuzz project from
134
+ GCS.
135
+
136
+ Args:
137
+ oss_fuzz_project_name: The name of the project.
138
+
139
+ Returns:
140
+ The projects coverage report info in json dict or None on failure.
141
+ """
142
+ latest_cov_info = _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name)
143
+
144
+ if not latest_cov_info:
145
+ return None
146
+
147
+ if 'fuzzer_stats_dir' not in latest_cov_info:
148
+ logging.error('fuzzer_stats_dir not in latest coverage info.')
149
+ return None
150
+
151
+ fuzzer_stats_dir_gs_url = latest_cov_info['fuzzer_stats_dir']
152
+ fuzzer_stats_dir_url = utils.gs_url_to_https(fuzzer_stats_dir_gs_url)
153
+ return fuzzer_stats_dir_url
154
+
155
+
156
+ class FilesystemCoverage(BaseCoverage):
157
+ """Class that gets a project's coverage from the filesystem."""
158
+
159
+ def __init__(self, repo_path, project_coverage_dir):
160
+ super().__init__(repo_path)
161
+ self.project_coverage_dir = project_coverage_dir
162
+
163
+ def get_target_coverage(self, target):
164
+ """Get the coverage report for a specific fuzz target.
165
+
166
+ Args:
167
+ target: The name of the fuzz target whose coverage is requested.
168
+
169
+ Returns:
170
+ The target's coverage json dict or None on failure.
171
+ """
172
+ logging.info('Getting coverage for %s from filesystem.', target)
173
+ fuzzer_stats_json_path = os.path.join(self.project_coverage_dir,
174
+ 'fuzzer_stats', target + '.json')
175
+ if not os.path.exists(fuzzer_stats_json_path):
176
+ logging.warning('%s does not exist.', fuzzer_stats_json_path)
177
+ return None
178
+
179
+ with open(fuzzer_stats_json_path) as fuzzer_stats_json_file_handle:
180
+ try:
181
+ return json.load(fuzzer_stats_json_file_handle)
182
+ except json.decoder.JSONDecodeError as err:
183
+ logging.error('Could not decode: %s. Error: %s.',
184
+ fuzzer_stats_json_path, err)
185
+ return None
186
+
187
+
188
+ def is_file_covered(file_cov):
189
+ """Returns whether the file is covered."""
190
+ return file_cov['summary']['regions']['covered']
191
+
192
+
193
+ def get_coverage_per_file(target_cov):
194
+ """Returns the coverage per file within |target_cov|."""
195
+ try:
196
+ return target_cov['data'][0]['files']
197
+ except (IndexError, TypeError, KeyError):
198
+ logging.error('target_cov: %s is malformed.', target_cov)
199
+ return None
200
+
201
+
202
+ def _normalize_repo_path(repo_path):
203
+ """Normalizes and returns |repo_path| to make sure cases like /src/curl and
204
+ /src/curl/ are both handled."""
205
+ repo_path = os.path.normpath(repo_path)
206
+ if not repo_path.endswith('/'):
207
+ repo_path += '/'
208
+ return repo_path
local-test-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utility module for HTTP."""
15
+ import json
16
+ import logging
17
+ import os
18
+ import sys
19
+ import tempfile
20
+ import zipfile
21
+
22
+ import requests
23
+
24
+ # pylint: disable=wrong-import-position,import-error
25
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
26
+ import retry
27
+
28
+ _DOWNLOAD_URL_RETRIES = 3
29
+ _DOWNLOAD_URL_BACKOFF = 1
30
+ _HTTP_REQUEST_TIMEOUT = 10
31
+
32
+
33
+ def download_and_unpack_zip(url, extract_directory, headers=None):
34
+ """Downloads and unpacks a zip file from an HTTP URL.
35
+
36
+ Args:
37
+ url: A url to the zip file to be downloaded and unpacked.
38
+ extract_directory: The path where the zip file should be extracted to.
39
+ headers: (Optional) HTTP headers to send with the download request.
40
+
41
+ Returns:
42
+ True on success.
43
+ """
44
+ if headers is None:
45
+ headers = {}
46
+
47
+ if not os.path.exists(extract_directory):
48
+ logging.error('Extract directory: %s does not exist.', extract_directory)
49
+ return False
50
+
51
+ # Gives the temporary zip file a unique identifier in the case that
52
+ # that download_and_unpack_zip is done in parallel.
53
+ with tempfile.NamedTemporaryFile(suffix='.zip') as tmp_file:
54
+ if not download_url(url, tmp_file.name, headers=headers):
55
+ return False
56
+
57
+ try:
58
+ with zipfile.ZipFile(tmp_file.name, 'r') as zip_file:
59
+ zip_file.extractall(extract_directory)
60
+ except zipfile.BadZipFile:
61
+ logging.error('Error unpacking zip from %s. Bad Zipfile.', url)
62
+ return False
63
+
64
+ return True
65
+
66
+
67
+ def download_url(*args, **kwargs):
68
+ """Wrapper around _download_url that returns False if _download_url
69
+ exceptions."""
70
+ try:
71
+ return _download_url(*args, **kwargs)
72
+ except Exception: # pylint: disable=broad-except
73
+ return False
74
+
75
+
76
+ def get_json_from_url(url):
77
+ """Gets a json object from a specified HTTP URL.
78
+
79
+ Args:
80
+ url: The url of the json to be downloaded.
81
+
82
+ Returns:
83
+ A dictionary deserialized from JSON or None on failure.
84
+ """
85
+ try:
86
+ return requests.get(url, timeout=_HTTP_REQUEST_TIMEOUT).json()
87
+ except (ValueError, TypeError, json.JSONDecodeError,
88
+ requests.exceptions.ReadTimeout) as err:
89
+ logging.error('Loading json from url %s failed with: %s.', url, str(err))
90
+ return None
91
+
92
+
93
+ @retry.wrap(_DOWNLOAD_URL_RETRIES, _DOWNLOAD_URL_BACKOFF)
94
+ def _download_url(url, filename, headers=None):
95
+ """Downloads the file located at |url|, using HTTP to |filename|.
96
+
97
+ Args:
98
+ url: A url to a file to download.
99
+ filename: The path the file should be downloaded to.
100
+ headers: (Optional) HTTP headers to send with the download request.
101
+
102
+ Returns:
103
+ True on success.
104
+ """
105
+ if headers is None:
106
+ headers = {}
107
+
108
+ response = requests.get(url, headers=headers)
109
+
110
+ if response.status_code != 200:
111
+ logging.error('Unable to download from: %s. Code: %d. Content: %s.', url,
112
+ response.status_code, response.content)
113
+ return False
114
+
115
+ with open(filename, 'wb') as file_handle:
116
+ file_handle.write(response.content)
117
+
118
+ return True
local-test-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for running fuzzers."""
15
+ import enum
16
+ import logging
17
+ import os
18
+ import sys
19
+ import time
20
+
21
+ import clusterfuzz_deployment
22
+ import fuzz_target
23
+ import generate_coverage_report
24
+ import workspace_utils
25
+ import sarif_utils
26
+
27
+ # pylint: disable=wrong-import-position,import-error
28
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
29
+
30
+ import utils
31
+
32
+
33
+ class RunFuzzersResult(enum.Enum):
34
+ """Enum result from running fuzzers."""
35
+ ERROR = 0
36
+ BUG_FOUND = 1
37
+ NO_BUG_FOUND = 2
38
+
39
+
40
+ class BaseFuzzTargetRunner:
41
+ """Base class for fuzzer runners."""
42
+
43
+ def __init__(self, config):
44
+ self.config = config
45
+ self.workspace = workspace_utils.Workspace(config)
46
+ self.clusterfuzz_deployment = (
47
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
48
+ self.config, self.workspace))
49
+
50
+ # Set by the initialize method.
51
+ self.fuzz_target_paths = None
52
+
53
+ def get_fuzz_targets(self):
54
+ """Returns fuzz targets in out directory."""
55
+ return utils.get_fuzz_targets(self.workspace.out)
56
+
57
+ def initialize(self):
58
+ """Initialization method. Must be called before calling run_fuzz_targets.
59
+ Returns True on success."""
60
+ # Use a separate initialization function so we can return False on failure
61
+ # instead of exceptioning like we need to do if this were done in the
62
+ # __init__ method.
63
+
64
+ logging.info('Using %s sanitizer.', self.config.sanitizer)
65
+
66
+ # TODO(metzman) Add a check to ensure we aren't over time limit.
67
+ if not self.config.fuzz_seconds or self.config.fuzz_seconds < 1:
68
+ logging.error(
69
+ 'Fuzz_seconds argument must be greater than 1, but was: %s.',
70
+ self.config.fuzz_seconds)
71
+ return False
72
+
73
+ if not os.path.exists(self.workspace.out):
74
+ logging.error('Out directory: %s does not exist.', self.workspace.out)
75
+ return False
76
+
77
+ if not os.path.exists(self.workspace.artifacts):
78
+ os.makedirs(self.workspace.artifacts)
79
+ elif (not os.path.isdir(self.workspace.artifacts) or
80
+ os.listdir(self.workspace.artifacts)):
81
+ logging.error('Artifacts path: %s exists and is not an empty directory.',
82
+ self.workspace.artifacts)
83
+ return False
84
+
85
+ self.fuzz_target_paths = self.get_fuzz_targets()
86
+ logging.info('Fuzz targets: %s', self.fuzz_target_paths)
87
+ if not self.fuzz_target_paths:
88
+ logging.error('No fuzz targets were found in out directory: %s.',
89
+ self.workspace.out)
90
+ return False
91
+
92
+ return True
93
+
94
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
95
+ """Cleans up after running |fuzz_target_obj|."""
96
+ raise NotImplementedError('Child class must implement method.')
97
+
98
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
99
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
100
+ raise NotImplementedError('Child class must implement method.')
101
+
102
+ @property
103
+ def quit_on_bug_found(self):
104
+ """Property that is checked to determine if fuzzing should quit after first
105
+ bug is found."""
106
+ raise NotImplementedError('Child class must implement method.')
107
+
108
+ def create_fuzz_target_obj(self, target_path, run_seconds):
109
+ """Returns a fuzz target object."""
110
+ return fuzz_target.FuzzTarget(target_path, run_seconds, self.workspace,
111
+ self.clusterfuzz_deployment, self.config)
112
+
113
+ def run_fuzz_targets(self):
114
+ """Runs fuzz targets. Returns True if a bug was found."""
115
+ fuzzers_left_to_run = len(self.fuzz_target_paths)
116
+
117
+ # Make a copy since we will mutate it.
118
+ fuzz_seconds = self.config.fuzz_seconds
119
+
120
+ min_seconds_per_fuzzer = fuzz_seconds // fuzzers_left_to_run
121
+ bug_found = False
122
+ for target_path in self.fuzz_target_paths:
123
+ # By doing this, we can ensure that every fuzz target runs for at least
124
+ # min_seconds_per_fuzzer, but that other fuzzers will have longer to run
125
+ # if one ends early.
126
+ run_seconds = max(fuzz_seconds // fuzzers_left_to_run,
127
+ min_seconds_per_fuzzer)
128
+
129
+ target = self.create_fuzz_target_obj(target_path, run_seconds)
130
+ start_time = time.time()
131
+ result = self.run_fuzz_target(target)
132
+ self.cleanup_after_fuzz_target_run(target)
133
+
134
+ # It's OK if this goes negative since we take max when determining
135
+ # run_seconds.
136
+ fuzz_seconds -= time.time() - start_time
137
+
138
+ fuzzers_left_to_run -= 1
139
+ if not result.testcase or not result.stacktrace:
140
+ logging.info('Fuzzer %s finished running without reportable crashes.',
141
+ target.target_name)
142
+ continue
143
+
144
+ bug_found = True
145
+ if self.quit_on_bug_found:
146
+ logging.info('Bug found. Stopping fuzzing.')
147
+ break
148
+
149
+ # pylint: disable=undefined-loop-variable
150
+ if not target_path:
151
+ logging.error('Ran no fuzz targets.')
152
+ elif self.config.output_sarif:
153
+ # TODO(metzman): Handle multiple crashes.
154
+ write_fuzz_result_to_sarif(result, target_path, self.workspace)
155
+ self.clusterfuzz_deployment.upload_crashes()
156
+ return bug_found
157
+
158
+
159
+ def write_fuzz_result_to_sarif(fuzz_result, target_path, workspace):
160
+ """Write results of fuzzing to SARIF."""
161
+ logging.info('Writing sarif results.')
162
+ sarif_utils.write_stacktrace_to_sarif(fuzz_result.stacktrace, target_path,
163
+ workspace)
164
+
165
+
166
+ class PruneTargetRunner(BaseFuzzTargetRunner):
167
+ """Runner that prunes corpora."""
168
+
169
+ @property
170
+ def quit_on_bug_found(self):
171
+ return False
172
+
173
+ def run_fuzz_target(self, fuzz_target_obj):
174
+ """Prunes with |fuzz_target_obj| and returns the result."""
175
+ result = fuzz_target_obj.prune()
176
+ logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path))
177
+ self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name,
178
+ result.corpus_path,
179
+ replace=True)
180
+ return result
181
+
182
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
183
+ """Cleans up after pruning with |fuzz_target_obj|."""
184
+ fuzz_target_obj.free_disk_if_needed()
185
+
186
+
187
+ NON_FUZZ_TARGETS_FOR_COVERAGE = {
188
+ 'llvm-symbolizer',
189
+ 'jazzer_agent_deploy.jar',
190
+ 'jazzer_driver',
191
+ 'jazzer_driver_with_sanitizer',
192
+ }
193
+
194
+
195
+ def is_coverage_fuzz_target(file_path):
196
+ """Returns whether |file_path| is a fuzz target binary for the purposes of a
197
+ coverage report. Inspired by infra/base-images/base-runner/coverage."""
198
+ if not os.path.isfile(file_path):
199
+ return False
200
+ if not utils.is_executable(file_path):
201
+ return False
202
+ filename = os.path.basename(file_path)
203
+ return filename not in NON_FUZZ_TARGETS_FOR_COVERAGE
204
+
205
+
206
+ def get_coverage_fuzz_targets(out):
207
+ """Returns a list of fuzz targets in |out| for coverage."""
208
+ # We only want fuzz targets from the root because during the coverage build,
209
+ # a lot of the image's filesystem is copied into /out for the purpose of
210
+ # generating coverage reports.
211
+ fuzz_targets = []
212
+ for filename in os.listdir(out):
213
+ file_path = os.path.join(out, filename)
214
+ if is_coverage_fuzz_target(file_path):
215
+ fuzz_targets.append(file_path)
216
+ return fuzz_targets
217
+
218
+
219
+ class CoverageTargetRunner(BaseFuzzTargetRunner):
220
+ """Runner that runs the 'coverage' command."""
221
+
222
+ @property
223
+ def quit_on_bug_found(self):
224
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
225
+
226
+ def get_fuzz_targets(self):
227
+ """Returns fuzz targets in out directory."""
228
+ return get_coverage_fuzz_targets(self.workspace.out)
229
+
230
+ def run_fuzz_targets(self):
231
+ """Generates a coverage report. Always returns False since it never finds
232
+ any bugs."""
233
+ generate_coverage_report.generate_coverage_report(
234
+ self.fuzz_target_paths, self.workspace, self.clusterfuzz_deployment,
235
+ self.config)
236
+ return False
237
+
238
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
239
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
240
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
241
+
242
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
243
+ """Cleans up after running |fuzz_target_obj|."""
244
+ raise NotImplementedError('Not implemented for CoverageTargetRunner.')
245
+
246
+
247
+ class CiFuzzTargetRunner(BaseFuzzTargetRunner):
248
+ """Runner for fuzz targets used in CI (patch-fuzzing) context."""
249
+
250
+ @property
251
+ def quit_on_bug_found(self):
252
+ return True
253
+
254
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use
255
+ """Cleans up after running |fuzz_target_obj|."""
256
+ fuzz_target_obj.free_disk_if_needed()
257
+
258
+ def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use
259
+ return fuzz_target_obj.fuzz()
260
+
261
+
262
+ class BatchFuzzTargetRunner(BaseFuzzTargetRunner):
263
+ """Runner for fuzz targets used in batch fuzzing context."""
264
+
265
+ @property
266
+ def quit_on_bug_found(self):
267
+ return False
268
+
269
+ def run_fuzz_target(self, fuzz_target_obj):
270
+ """Fuzzes with |fuzz_target_obj| and returns the result."""
271
+ result = fuzz_target_obj.fuzz(batch=True)
272
+ logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path))
273
+ self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name,
274
+ result.corpus_path)
275
+ return result
276
+
277
+ def cleanup_after_fuzz_target_run(self, fuzz_target_obj):
278
+ """Cleans up after running |fuzz_target_obj|."""
279
+ # This must be done after we upload the corpus, otherwise it will be deleted
280
+ # before we get a chance to upload it. We can't delete the fuzz target
281
+ # because it is needed when we upload the build.
282
+ fuzz_target_obj.free_disk_if_needed(delete_fuzz_target=False)
283
+
284
+
285
+ _MODE_RUNNER_MAPPING = {
286
+ 'batch': BatchFuzzTargetRunner,
287
+ 'coverage': CoverageTargetRunner,
288
+ 'prune': PruneTargetRunner,
289
+ 'code-change': CiFuzzTargetRunner,
290
+ }
291
+
292
+
293
+ def get_fuzz_target_runner(config):
294
+ """Returns a fuzz target runner object based on the mode of
295
+ |config|."""
296
+ runner = _MODE_RUNNER_MAPPING[config.mode](config)
297
+ logging.info('run fuzzers MODE is: %s. Runner: %s.', config.mode, runner)
298
+ return runner
299
+
300
+
301
+ def run_fuzzers(config): # pylint: disable=too-many-locals
302
+ """Runs fuzzers for a specific OSS-Fuzz project.
303
+
304
+ Args:
305
+ config: A RunFuzzTargetsConfig.
306
+
307
+ Returns:
308
+ A RunFuzzersResult enum value indicating what happened during fuzzing.
309
+ """
310
+ fuzz_target_runner = get_fuzz_target_runner(config)
311
+ if not fuzz_target_runner.initialize():
312
+ # We didn't fuzz at all because of internal (CIFuzz) errors. And we didn't
313
+ # find any bugs.
314
+ return RunFuzzersResult.ERROR
315
+
316
+ if not fuzz_target_runner.run_fuzz_targets():
317
+ # We fuzzed successfully, but didn't find any bugs (in the fuzz target).
318
+ return RunFuzzersResult.NO_BUG_FOUND
319
+
320
+ # We fuzzed successfully and found bug(s) in the fuzz targets.
321
+ return RunFuzzersResult.BUG_FOUND
local-test-commons-compress-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-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils_test.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for sarif_utils.py"""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import sarif_utils
20
+
21
+ CRASH_INFO_FILELINE = 403
22
+
23
+ TEST_DATA = os.path.join(os.path.dirname(__file__), 'test_data')
24
+
25
+
26
+ class GetSarifDataTest(unittest.TestCase):
27
+ """Tests for get_sarif_data."""
28
+
29
+ def setUp(self):
30
+ self.maxDiff = None # pylint: disable=invalid-name
31
+
32
+ def test_get_sarif_data_none(self):
33
+ """Tests get_sarif_data when there was no crash."""
34
+ self.assertEqual(sarif_utils.get_sarif_data(None, '/root/target'),
35
+ sarif_utils.SARIF_DATA)
36
+
37
+ def test_ordinary_case(self):
38
+ stacktrace_filename = os.path.join(TEST_DATA,
39
+ 'sarif_utils_systemd_stack.txt')
40
+ with open(stacktrace_filename, 'r') as fp:
41
+ stacktrace = fp.read()
42
+ expected_result = {
43
+ 'level': 'error',
44
+ 'message': {
45
+ 'text': 'Heap-buffer-overflow\nREAD 4'
46
+ },
47
+ 'locations': [{
48
+ 'physicalLocation': {
49
+ 'artifactLocation': {
50
+ 'uri': 'src/core/fuzz-unit-file.c',
51
+ 'index': 0
52
+ },
53
+ 'region': {
54
+ 'startLine': 30,
55
+ # We don't have this granualarity fuzzing.
56
+ 'startColumn': 1,
57
+ }
58
+ }
59
+ }],
60
+ 'ruleId': 'heap-buffer-overflow',
61
+ 'ruleIndex': 2
62
+ }
63
+ actual_result = sarif_utils.get_sarif_data(
64
+ stacktrace, '/root/target')['runs'][0]['results'][0]
65
+ self.assertEqual(actual_result, expected_result)
66
+
67
+ def test_llvmfuzzertestoneinput_case(self):
68
+ stacktrace_filename = os.path.join(TEST_DATA,
69
+ 'sarif_utils_only_llvmfuzzer_stack.txt')
70
+ with open(stacktrace_filename, 'r') as fp:
71
+ stacktrace = fp.read()
72
+ actual_result = sarif_utils.get_sarif_data(
73
+ stacktrace, '/root/target')['runs'][0]['results']
74
+ self.assertEqual(actual_result, [])
75
+
76
+ def test_msan(self):
77
+ """Tests that MSAN stacktraces don't exception."""
78
+ stacktrace_filename = os.path.join(TEST_DATA, 'sarif_utils_msan_stack.txt')
79
+ with open(stacktrace_filename, 'r') as fp:
80
+ stacktrace = fp.read()
81
+
82
+ actual_result = sarif_utils.get_sarif_data(stacktrace, '/root/target')
83
+
84
+
85
+ class RedactSrcPathTest(unittest.TestCase):
86
+ """Tests for redact_src_path."""
87
+
88
+ def test_redact_src_path(self):
89
+ """Tests redact_src_path."""
90
+ path = '/src/src-repo/subdir/file'
91
+ self.assertEqual(sarif_utils.redact_src_path(path), 'subdir/file')
92
+
93
+
94
+ def _get_mock_crash_info():
95
+ """Returns a mock crash_info to be used in tests."""
96
+ stack_frame = mock.MagicMock()
97
+ stack_frame.filename = '/src/repo-dir/sub/vuln.cc'
98
+ stack_frame.function_name = 'vuln_func'
99
+ stack_frame.fileline = CRASH_INFO_FILELINE
100
+ crash1_frames = [stack_frame, stack_frame]
101
+ frames = [crash1_frames]
102
+ crash_info = mock.MagicMock()
103
+ crash_info.frames = frames
104
+ crash_info.crash_state = 'vuln_func\nvuln_func0\nvuln_func1'
105
+ return crash_info
106
+
107
+
108
+ class GetErrorSourceInfoTest(unittest.TestCase):
109
+ """Tests for get_error_source_info."""
110
+
111
+ def test_redact_src_path(self):
112
+ """Tests that get_error_source_info finds the right source info."""
113
+ crash_info = _get_mock_crash_info()
114
+ source_info = sarif_utils.get_error_source_info(crash_info)
115
+ expected_source_info = ('sub/vuln.cc', CRASH_INFO_FILELINE)
116
+ self.assertEqual(source_info, expected_source_info)
117
+
118
+
119
+ class GetRuleIndexTest(unittest.TestCase):
120
+ """Tests for get_rule_index."""
121
+ CRASH_INFO_CRASH_TYPE = 'Heap-use-after-free READ 8'
122
+
123
+ def test_get_rule_index(self):
124
+ """Tests that get_rule_index finds the right rule index."""
125
+ index = sarif_utils.get_rule_index(self.CRASH_INFO_CRASH_TYPE)
126
+ self.assertEqual(sarif_utils.SARIF_RULES[index]['id'],
127
+ 'heap-use-after-free')
128
+ self.assertEqual(sarif_utils.get_rule_index('no-crashes'), 0)
local-test-commons-compress-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-commons-compress-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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/Makefile ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .POSIX:
2
+ CXX = clang++
3
+ CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 -Werror
4
+
5
+ all: SystemSan target target_file target_dns
6
+
7
+ SystemSan: SystemSan.cpp inspect_dns.cpp inspect_utils.cpp
8
+ $(CXX) $(CFLAGS) -lpthread -o $@ $^
9
+
10
+ # Needs atheris.
11
+ python-test: all
12
+ ./SystemSan python shell_injection_poc_fuzzer.py
13
+
14
+ target: target.cpp
15
+ $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^
16
+
17
+ target_file: target_file.cpp
18
+ $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^
19
+
20
+ target_dns: target_dns.cpp
21
+ $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^
22
+
23
+ test: all vuln.dict
24
+ ./SystemSan ./target -dict=vuln.dict
25
+ ./SystemSan ./target_file -dict=vuln.dict
26
+ ./SystemSan ./target_dns -dict=vuln.dict
27
+
28
+ pytorch-lightning-1.5.10:
29
+ cp SystemSan.cpp PoEs/pytorch-lightning-1.5.10/; \
30
+ cd PoEs/pytorch-lightning-1.5.10/; \
31
+ docker build . --tag syssan_pytorch-lightning; \
32
+ docker run -t systemsan_pytorch-lightning:latest;
33
+
34
+ node-shell-quote-v1.7.3:
35
+ cp SystemSan.cpp PoEs/node-shell-quote-v1.7.3/; \
36
+ cd PoEs/node-shell-quote-v1.7.3/; \
37
+ docker build . --tag systemsan_node-shell-quote; \
38
+ docker run -t systemsan_node-shell-quote:latest;
39
+
40
+ clean:
41
+ rm -f SystemSan /tmp/tripwire target target_file target_dns