Kitxuuu commited on
Commit
f87209a
·
verified ·
1 Parent(s): 316148b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py +113 -0
  2. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/base_runner_utils.py +33 -0
  3. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py +403 -0
  4. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/cloudbuild.yaml +52 -0
  5. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/filestore_utils.py +48 -0
  6. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/fuzz_target_test.py +298 -0
  7. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/generate_coverage_report.py +48 -0
  8. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/http_utils.py +118 -0
  9. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/sarif_utils.py +251 -0
  10. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/sarif_utils_test.py +128 -0
  11. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/Makefile +41 -0
  12. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp +493 -0
  13. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h +26 -0
  14. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/target.cpp +28 -0
  15. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp +39 -0
  16. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp +32 -0
  17. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/chronos/Dockerfile +18 -0
  18. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/chronos/README.md +49 -0
  19. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh +35 -0
  20. local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/tools/hold_back_images.py +128 -0
local-test-commons-compress-full-01-vuln_2/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-full-01-vuln_2/fuzz-tooling/infra/cifuzz/base_runner_utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Utilities for scripts from ghcr.io/aixcc-finals/base-runner."""
15
+
16
+ import os
17
+
18
+ import config_utils
19
+
20
+
21
+ def get_env(config, workspace):
22
+ """Returns a dictionary containing the current environment with additional env
23
+ vars set to values needed to run a fuzzer."""
24
+ env = os.environ.copy()
25
+ env['SANITIZER'] = config.sanitizer
26
+ env['FUZZING_LANGUAGE'] = config.language
27
+ env['OUT'] = workspace.out
28
+ env['CIFUZZ'] = 'True'
29
+ env['FUZZING_ENGINE'] = config_utils.DEFAULT_ENGINE
30
+ env['ARCHITECTURE'] = config.architecture
31
+ # Do this so we don't fail in tests.
32
+ env['FUZZER_ARGS'] = '-rss_limit_mb=2560 -timeout=25'
33
+ return env
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests the functionality of the cifuzz module."""
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ import unittest
20
+ from unittest import mock
21
+
22
+ import parameterized
23
+
24
+ # pylint: disable=wrong-import-position
25
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ sys.path.append(INFRA_DIR)
27
+
28
+ OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR)
29
+
30
+ import build_fuzzers
31
+ import continuous_integration
32
+ import repo_manager
33
+ import test_helpers
34
+
35
+ # NOTE: This integration test relies on
36
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
37
+ EXAMPLE_PROJECT = 'example'
38
+
39
+ # Location of data used for testing.
40
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
41
+ 'test_data')
42
+
43
+ # An example fuzzer that triggers an crash.
44
+ # Binary is a copy of the example project's do_stuff_fuzzer and can be
45
+ # generated by running "python3 infra/helper.py build_fuzzers example".
46
+ EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer'
47
+
48
+ # An example fuzzer that does not trigger a crash.
49
+ # Binary is a modified version of example project's do_stuff_fuzzer. It is
50
+ # created by removing the bug in my_api.cpp.
51
+ EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer'
52
+
53
+ # A fuzzer to be built in build_fuzzers integration tests.
54
+ EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer'
55
+
56
+ # pylint: disable=no-self-use,protected-access,too-few-public-methods,unused-argument
57
+
58
+
59
+ def docker_command_has_env_var_arg(command, env_var_arg):
60
+ """Returns True if a docker command has a specific env var argument."""
61
+ for idx, element in enumerate(command):
62
+ if idx == 0:
63
+ # We're looking for the variable which can't be the first argument.
64
+ continue
65
+
66
+ if element == env_var_arg and command[idx - 1] == '-e':
67
+ return True
68
+ return False
69
+
70
+
71
+ class BuildFuzzersTest(unittest.TestCase):
72
+ """Unit tests for build_fuzzers."""
73
+
74
+ @mock.patch('build_specified_commit.detect_main_repo',
75
+ return_value=('example.com', '/path'))
76
+ @mock.patch('repo_manager._clone', return_value=None)
77
+ @mock.patch('continuous_integration.checkout_specified_commit')
78
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
79
+ def test_cifuzz_env_var(self, mock_docker_run, _, __, ___):
80
+ """Tests that the CIFUZZ env var is set."""
81
+
82
+ with tempfile.TemporaryDirectory() as tmp_dir:
83
+ build_fuzzers.build_fuzzers(
84
+ test_helpers.create_build_config(
85
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
86
+ project_repo_name=EXAMPLE_PROJECT,
87
+ workspace=tmp_dir,
88
+ pr_ref='refs/pull/1757/merge'))
89
+
90
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
91
+
92
+ self.assertTrue(
93
+ docker_command_has_env_var_arg(docker_run_command, 'CIFUZZ=True'))
94
+
95
+ @mock.patch('build_specified_commit.detect_main_repo',
96
+ return_value=('example.com', '/path'))
97
+ @mock.patch('repo_manager._clone', return_value=None)
98
+ @mock.patch('continuous_integration.checkout_specified_commit')
99
+ @mock.patch('helper.docker_run', return_value=False) # We want to quit early.
100
+ def test_extra_env_var(self, mock_docker_run, _, __, ___):
101
+ """Tests that the CIFUZZ env var is set."""
102
+
103
+ extra_env_var = 'CFL_EXTRA_TOKEN'
104
+ with tempfile.TemporaryDirectory() as tmp_dir:
105
+ with mock.patch.dict(os.environ, {extra_env_var: 'BLAH'}):
106
+ build_fuzzers.build_fuzzers(
107
+ test_helpers.create_build_config(
108
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
109
+ project_repo_name=EXAMPLE_PROJECT,
110
+ workspace=tmp_dir,
111
+ pr_ref='refs/pull/1757/merge'))
112
+
113
+ docker_run_command = mock_docker_run.call_args_list[0][0][0]
114
+ self.assertTrue(
115
+ docker_command_has_env_var_arg(docker_run_command, extra_env_var))
116
+
117
+
118
+ class InternalGithubBuildTest(unittest.TestCase):
119
+ """Tests for building OSS-Fuzz projects on GitHub actions."""
120
+ PROJECT_REPO_NAME = 'myproject'
121
+ SANITIZER = 'address'
122
+ GIT_SHA = 'fake'
123
+ PR_REF = 'fake'
124
+
125
+ def _create_builder(self, tmp_dir, oss_fuzz_project_name='myproject'):
126
+ """Creates an InternalGithubBuilder and returns it."""
127
+ config = test_helpers.create_build_config(
128
+ oss_fuzz_project_name=oss_fuzz_project_name,
129
+ project_repo_name=self.PROJECT_REPO_NAME,
130
+ workspace=tmp_dir,
131
+ sanitizer=self.SANITIZER,
132
+ git_sha=self.GIT_SHA,
133
+ pr_ref=self.PR_REF,
134
+ cfl_platform='github')
135
+ cfl_platform = continuous_integration.get_ci(config)
136
+ builder = build_fuzzers.Builder(config, cfl_platform)
137
+ builder.repo_manager = repo_manager.RepoManager('/fake')
138
+ return builder
139
+
140
+ @mock.patch('helper.docker_run', return_value=True)
141
+ @mock.patch('continuous_integration.checkout_specified_commit',
142
+ side_effect=None)
143
+ def test_correct_host_repo_path(self, _, __):
144
+ """Tests that the correct self.host_repo_path is set by
145
+ build_image_and_checkout_src. Specifically, we want the name of the
146
+ directory the repo is in to match the name used in the docker
147
+ image/container, so that it will replace the host's copy properly."""
148
+ image_repo_path = '/src/repo_dir'
149
+ with tempfile.TemporaryDirectory() as tmp_dir, mock.patch(
150
+ 'build_specified_commit.detect_main_repo',
151
+ return_value=('inferred_url', image_repo_path)):
152
+ builder = self._create_builder(tmp_dir)
153
+ builder.build_image_and_checkout_src()
154
+
155
+ self.assertEqual(os.path.basename(builder.host_repo_path),
156
+ os.path.basename(image_repo_path))
157
+
158
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
159
+ return_value=True)
160
+ def test_upload_build_disabled(self, mock_upload_build):
161
+ """Test upload build (disabled)."""
162
+ with tempfile.TemporaryDirectory() as tmp_dir:
163
+ builder = self._create_builder(tmp_dir)
164
+ builder.upload_build()
165
+
166
+ mock_upload_build.assert_not_called()
167
+
168
+ @mock.patch('repo_manager.RepoManager.get_current_commit',
169
+ return_value='commit')
170
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build',
171
+ return_value=True)
172
+ def test_upload_build(self, mock_upload_build, mock_get_current_commit):
173
+ """Test upload build."""
174
+ with tempfile.TemporaryDirectory() as tmp_dir:
175
+ builder = self._create_builder(tmp_dir, oss_fuzz_project_name='')
176
+ builder.config.upload_build = True
177
+ builder.upload_build()
178
+
179
+ mock_upload_build.assert_called_with('commit')
180
+
181
+
182
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
183
+ 'INTEGRATION_TESTS=1 not set')
184
+ class BuildFuzzersIntegrationTest(unittest.TestCase):
185
+ """Integration tests for build_fuzzers."""
186
+
187
+ def setUp(self):
188
+ self.temp_dir_ctx_manager = test_helpers.docker_temp_dir()
189
+ self.workspace = self.temp_dir_ctx_manager.__enter__()
190
+ self.out_dir = os.path.join(self.workspace, 'build-out')
191
+ test_helpers.patch_environ(self)
192
+
193
+ base_runner_path = os.path.join(INFRA_DIR, 'base-images', 'base-runner')
194
+ os.environ['PATH'] = os.environ['PATH'] + os.pathsep + base_runner_path
195
+
196
+ def tearDown(self):
197
+ self.temp_dir_ctx_manager.__exit__(None, None, None)
198
+
199
+ def test_external_github_project(self):
200
+ """Tests building fuzzers from an external project on Github."""
201
+ project_repo_name = 'external-project'
202
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
203
+ # This test is dependant on the state of
204
+ # github.com/jonathanmetzman/cifuzz-external-example.
205
+ config = test_helpers.create_build_config(
206
+ project_repo_name=project_repo_name,
207
+ workspace=self.workspace,
208
+ git_url=git_url,
209
+ git_sha='HEAD',
210
+ cfl_platform='github',
211
+ base_commit='HEAD^1')
212
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
213
+ self.assertTrue(
214
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
215
+
216
+ def test_external_generic_project(self):
217
+ """Tests building fuzzers from an external project not on Github."""
218
+ project_repo_name = 'cifuzz-external-example'
219
+ git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git'
220
+ # This test is dependant on the state of
221
+ # github.com/jonathanmetzman/cifuzz-external-example.
222
+ manager = repo_manager.clone_repo_and_get_manager(
223
+ 'https://github.com/jonathanmetzman/cifuzz-external-example',
224
+ self.workspace)
225
+ project_src_path = manager.repo_dir
226
+ config = test_helpers.create_build_config(
227
+ project_repo_name=project_repo_name,
228
+ workspace=self.workspace,
229
+ git_url=git_url,
230
+ filestore='no_filestore',
231
+ git_sha='HEAD',
232
+ project_src_path=project_src_path,
233
+ base_commit='HEAD^1')
234
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
235
+ self.assertTrue(
236
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
237
+
238
+ def test_valid_commit(self):
239
+ """Tests building fuzzers with valid inputs."""
240
+ config = test_helpers.create_build_config(
241
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
242
+ project_repo_name='oss-fuzz',
243
+ workspace=self.workspace,
244
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
245
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
246
+ cfl_platform='github')
247
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
248
+ self.assertTrue(
249
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
250
+
251
+ def test_valid_pull_request(self):
252
+ """Tests building fuzzers with valid pull request."""
253
+ config = test_helpers.create_build_config(
254
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
255
+ project_repo_name='oss-fuzz',
256
+ workspace=self.workspace,
257
+ pr_ref='refs/pull/1757/merge',
258
+ base_ref='master',
259
+ cfl_platform='github')
260
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
261
+ self.assertTrue(
262
+ os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER)))
263
+
264
+ def test_invalid_pull_request(self):
265
+ """Tests building fuzzers with invalid pull request."""
266
+ config = test_helpers.create_build_config(
267
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
268
+ project_repo_name='oss-fuzz',
269
+ workspace=self.workspace,
270
+ pr_ref='ref-1/merge',
271
+ base_ref='master',
272
+ cfl_platform='github')
273
+ self.assertTrue(build_fuzzers.build_fuzzers(config))
274
+
275
+ def test_invalid_oss_fuzz_project_name(self):
276
+ """Tests building fuzzers with invalid project name."""
277
+ config = test_helpers.create_build_config(
278
+ oss_fuzz_project_name='not_a_valid_project',
279
+ project_repo_name='oss-fuzz',
280
+ workspace=self.workspace,
281
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
282
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
283
+
284
+ def test_invalid_repo_name(self):
285
+ """Tests building fuzzers with invalid repo name."""
286
+ config = test_helpers.create_build_config(
287
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
288
+ project_repo_name='not-real-repo',
289
+ workspace=self.workspace,
290
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
291
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
292
+
293
+ def test_invalid_git_sha(self):
294
+ """Tests building fuzzers with invalid commit SHA."""
295
+ config = test_helpers.create_build_config(
296
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
297
+ project_repo_name='oss-fuzz',
298
+ workspace=self.workspace,
299
+ git_sha='',
300
+ cfl_platform='github')
301
+ with self.assertRaises(AssertionError):
302
+ build_fuzzers.build_fuzzers(config)
303
+
304
+ def test_invalid_workspace(self):
305
+ """Tests building fuzzers with invalid workspace."""
306
+ config = test_helpers.create_build_config(
307
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
308
+ project_repo_name='oss-fuzz',
309
+ workspace=os.path.join(self.workspace, 'not', 'a', 'dir'),
310
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523')
311
+ self.assertFalse(build_fuzzers.build_fuzzers(config))
312
+
313
+
314
+ class CheckFuzzerBuildTest(unittest.TestCase):
315
+ """Tests the check_fuzzer_build function in the cifuzz module."""
316
+
317
+ SANITIZER = 'address'
318
+ LANGUAGE = 'c++'
319
+
320
+ def setUp(self):
321
+ self.temp_dir_obj = tempfile.TemporaryDirectory()
322
+ workspace_path = os.path.join(self.temp_dir_obj.name, 'workspace')
323
+ self.config = test_helpers.create_build_config(
324
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
325
+ sanitizer=self.SANITIZER,
326
+ language=self.LANGUAGE,
327
+ workspace=workspace_path,
328
+ pr_ref='refs/pull/1757/merge')
329
+ self.workspace = test_helpers.create_workspace(workspace_path)
330
+ shutil.copytree(TEST_DATA_PATH, workspace_path)
331
+ test_helpers.patch_environ(self, runner=True)
332
+
333
+ def tearDown(self):
334
+ self.temp_dir_obj.cleanup()
335
+
336
+ def test_correct_fuzzer_build(self):
337
+ """Checks check_fuzzer_build function returns True for valid fuzzers."""
338
+ self.assertTrue(build_fuzzers.check_fuzzer_build(self.config))
339
+
340
+ def test_not_a_valid_path(self):
341
+ """Tests that False is returned when a nonexistent path is given."""
342
+ self.config.workspace = 'not/a/valid/path'
343
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
344
+
345
+ def test_no_valid_fuzzers(self):
346
+ """Tests that False is returned when an empty directory is given."""
347
+ with tempfile.TemporaryDirectory() as tmp_dir:
348
+ self.config.workspace = tmp_dir
349
+ os.mkdir(os.path.join(self.config.workspace, 'build-out'))
350
+ self.assertFalse(build_fuzzers.check_fuzzer_build(self.config))
351
+
352
+ @mock.patch('utils.execute', return_value=(None, None, 0))
353
+ def test_allow_broken_fuzz_targets_percentage(self, mock_execute):
354
+ """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running
355
+ docker if passed to check_fuzzer_build."""
356
+ percentage = '0'
357
+ self.config.allowed_broken_targets_percentage = percentage
358
+ build_fuzzers.check_fuzzer_build(self.config)
359
+ self.assertEqual(
360
+ mock_execute.call_args[1]['env']['ALLOWED_BROKEN_TARGETS_PERCENTAGE'],
361
+ percentage)
362
+
363
+
364
+ @unittest.skip('Test is too long to be run with presubmit.')
365
+ class BuildSantizerIntegrationTest(unittest.TestCase):
366
+ """Integration tests for the build_fuzzers.
367
+ Note: This test relies on "curl" being an OSS-Fuzz project."""
368
+ PROJECT_NAME = 'curl'
369
+ PR_REF = 'fake_pr'
370
+
371
+ @classmethod
372
+ def _create_config(cls, tmp_dir, sanitizer):
373
+ return test_helpers.create_build_config(
374
+ oss_fuzz_project_name=cls.PROJECT_NAME,
375
+ project_repo_name=cls.PROJECT_NAME,
376
+ workspace=tmp_dir,
377
+ pr_ref=cls.PR_REF,
378
+ sanitizer=sanitizer)
379
+
380
+ @parameterized.parameterized.expand([('memory',), ('undefined',)])
381
+ def test_valid_project_curl(self, sanitizer):
382
+ """Tests that MSAN can be detected from project.yaml"""
383
+ with tempfile.TemporaryDirectory() as tmp_dir:
384
+ self.assertTrue(
385
+ build_fuzzers.build_fuzzers(self._create_config(tmp_dir, sanitizer)))
386
+
387
+
388
+ class GetDockerBuildFuzzersArgsNotContainerTest(unittest.TestCase):
389
+ """Tests that _get_docker_build_fuzzers_args_not_container works as
390
+ intended."""
391
+
392
+ def test_get_docker_build_fuzzers_args_no_container(self):
393
+ """Tests that _get_docker_build_fuzzers_args_not_container works
394
+ as intended."""
395
+ host_repo_path = '/host/repo'
396
+ result = build_fuzzers._get_docker_build_fuzzers_args_not_container(
397
+ host_repo_path)
398
+ expected_result = ['-v', '/host/repo:/host/repo']
399
+ self.assertEqual(result, expected_result)
400
+
401
+
402
+ if __name__ == '__main__':
403
+ unittest.main()
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/cifuzz/cloudbuild.yaml ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TODO(metzman): Get rid of cifuzz-build-fuzzers and cifuzz-run-fuzzers.
2
+ steps:
3
+ - name: 'gcr.io/cloud-builders/docker'
4
+ args:
5
+ - build
6
+ - '-t'
7
+ - ghcr.io/aixcc-finals/cifuzz-base
8
+ - '-t'
9
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
10
+ - '-f'
11
+ - infra/cifuzz/cifuzz-base/Dockerfile
12
+ - .
13
+ - name: 'gcr.io/cloud-builders/docker'
14
+ args:
15
+ - build
16
+ - '-t'
17
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
18
+ - '-t'
19
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
20
+ - '-t'
21
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
22
+ - '-t'
23
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
24
+ - '-f'
25
+ - infra/build_fuzzers.Dockerfile
26
+ - infra
27
+ - name: 'gcr.io/cloud-builders/docker'
28
+ args:
29
+ - build
30
+ - '-t'
31
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
32
+ - '-t'
33
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
34
+ - '-t'
35
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
36
+ - '-t'
37
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
38
+ - '-f'
39
+ - infra/run_fuzzers.Dockerfile
40
+ - infra
41
+ images:
42
+ - ghcr.io/aixcc-finals/cifuzz-base
43
+ - ghcr.io/aixcc-finals/cifuzz-base:v1
44
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers
45
+ - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1
46
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers
47
+ - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1
48
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers
49
+ - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1
50
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers
51
+ - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1
52
+ timeout: 1800s
local-test-commons-compress-full-01-vuln_2/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-full-01-vuln_2/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-full-01-vuln_2/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-full-01-vuln_2/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-full-01-vuln_2/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-full-01-vuln_2/fuzz-tooling/infra/cifuzz/sarif_utils_test.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for sarif_utils.py"""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import sarif_utils
20
+
21
+ CRASH_INFO_FILELINE = 403
22
+
23
+ TEST_DATA = os.path.join(os.path.dirname(__file__), 'test_data')
24
+
25
+
26
+ class GetSarifDataTest(unittest.TestCase):
27
+ """Tests for get_sarif_data."""
28
+
29
+ def setUp(self):
30
+ self.maxDiff = None # pylint: disable=invalid-name
31
+
32
+ def test_get_sarif_data_none(self):
33
+ """Tests get_sarif_data when there was no crash."""
34
+ self.assertEqual(sarif_utils.get_sarif_data(None, '/root/target'),
35
+ sarif_utils.SARIF_DATA)
36
+
37
+ def test_ordinary_case(self):
38
+ stacktrace_filename = os.path.join(TEST_DATA,
39
+ 'sarif_utils_systemd_stack.txt')
40
+ with open(stacktrace_filename, 'r') as fp:
41
+ stacktrace = fp.read()
42
+ expected_result = {
43
+ 'level': 'error',
44
+ 'message': {
45
+ 'text': 'Heap-buffer-overflow\nREAD 4'
46
+ },
47
+ 'locations': [{
48
+ 'physicalLocation': {
49
+ 'artifactLocation': {
50
+ 'uri': 'src/core/fuzz-unit-file.c',
51
+ 'index': 0
52
+ },
53
+ 'region': {
54
+ 'startLine': 30,
55
+ # We don't have this granualarity fuzzing.
56
+ 'startColumn': 1,
57
+ }
58
+ }
59
+ }],
60
+ 'ruleId': 'heap-buffer-overflow',
61
+ 'ruleIndex': 2
62
+ }
63
+ actual_result = sarif_utils.get_sarif_data(
64
+ stacktrace, '/root/target')['runs'][0]['results'][0]
65
+ self.assertEqual(actual_result, expected_result)
66
+
67
+ def test_llvmfuzzertestoneinput_case(self):
68
+ stacktrace_filename = os.path.join(TEST_DATA,
69
+ 'sarif_utils_only_llvmfuzzer_stack.txt')
70
+ with open(stacktrace_filename, 'r') as fp:
71
+ stacktrace = fp.read()
72
+ actual_result = sarif_utils.get_sarif_data(
73
+ stacktrace, '/root/target')['runs'][0]['results']
74
+ self.assertEqual(actual_result, [])
75
+
76
+ def test_msan(self):
77
+ """Tests that MSAN stacktraces don't exception."""
78
+ stacktrace_filename = os.path.join(TEST_DATA, 'sarif_utils_msan_stack.txt')
79
+ with open(stacktrace_filename, 'r') as fp:
80
+ stacktrace = fp.read()
81
+
82
+ actual_result = sarif_utils.get_sarif_data(stacktrace, '/root/target')
83
+
84
+
85
+ class RedactSrcPathTest(unittest.TestCase):
86
+ """Tests for redact_src_path."""
87
+
88
+ def test_redact_src_path(self):
89
+ """Tests redact_src_path."""
90
+ path = '/src/src-repo/subdir/file'
91
+ self.assertEqual(sarif_utils.redact_src_path(path), 'subdir/file')
92
+
93
+
94
+ def _get_mock_crash_info():
95
+ """Returns a mock crash_info to be used in tests."""
96
+ stack_frame = mock.MagicMock()
97
+ stack_frame.filename = '/src/repo-dir/sub/vuln.cc'
98
+ stack_frame.function_name = 'vuln_func'
99
+ stack_frame.fileline = CRASH_INFO_FILELINE
100
+ crash1_frames = [stack_frame, stack_frame]
101
+ frames = [crash1_frames]
102
+ crash_info = mock.MagicMock()
103
+ crash_info.frames = frames
104
+ crash_info.crash_state = 'vuln_func\nvuln_func0\nvuln_func1'
105
+ return crash_info
106
+
107
+
108
+ class GetErrorSourceInfoTest(unittest.TestCase):
109
+ """Tests for get_error_source_info."""
110
+
111
+ def test_redact_src_path(self):
112
+ """Tests that get_error_source_info finds the right source info."""
113
+ crash_info = _get_mock_crash_info()
114
+ source_info = sarif_utils.get_error_source_info(crash_info)
115
+ expected_source_info = ('sub/vuln.cc', CRASH_INFO_FILELINE)
116
+ self.assertEqual(source_info, expected_source_info)
117
+
118
+
119
+ class GetRuleIndexTest(unittest.TestCase):
120
+ """Tests for get_rule_index."""
121
+ CRASH_INFO_CRASH_TYPE = 'Heap-use-after-free READ 8'
122
+
123
+ def test_get_rule_index(self):
124
+ """Tests that get_rule_index finds the right rule index."""
125
+ index = sarif_utils.get_rule_index(self.CRASH_INFO_CRASH_TYPE)
126
+ self.assertEqual(sarif_utils.SARIF_RULES[index]['id'],
127
+ 'heap-use-after-free')
128
+ self.assertEqual(sarif_utils.get_rule_index('no-crashes'), 0)
local-test-commons-compress-full-01-vuln_2/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
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp ADDED
@@ -0,0 +1,493 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /* A detector that uses ptrace to identify shell injection vulnerabilities. */
17
+
18
+ /* C standard library */
19
+ #include <errno.h>
20
+ #include <signal.h>
21
+ #include <stdio.h>
22
+ #include <string.h>
23
+
24
+ /* POSIX */
25
+ #include <sys/stat.h>
26
+ #include <sys/user.h>
27
+ #include <sys/wait.h>
28
+ #include <unistd.h>
29
+
30
+ /* Linux */
31
+ #include <sys/ptrace.h>
32
+ #include <syscall.h>
33
+ #include <fcntl.h>
34
+
35
+ #include <fstream>
36
+ #include <iostream>
37
+ #include <map>
38
+ #include <set>
39
+ #include <sstream>
40
+ #include <string>
41
+ #include <vector>
42
+
43
+ #include "inspect_utils.h"
44
+ #include "inspect_dns.h"
45
+
46
+ #define DEBUG_LOGS 0
47
+
48
+ #if DEBUG_LOGS
49
+ #define debug_log(...) \
50
+ do { \
51
+ fprintf(stderr, __VA_ARGS__); \
52
+ fflush(stdout); \
53
+ fputc('\n', stderr); \
54
+ } while (0)
55
+ #else
56
+ #define debug_log(...)
57
+ #endif
58
+
59
+ #define fatal_log(...) \
60
+ do { \
61
+ fprintf(stderr, __VA_ARGS__); \
62
+ fputc('\n', stderr); \
63
+ exit(EXIT_FAILURE); \
64
+ } while (0)
65
+
66
+ // The magic string that we'll use to detect full control over the command
67
+ // executed.
68
+ const std::string kTripWire = "/tmp/tripwire";
69
+ // Shell injection bug confirmed with /tmp/tripwire.
70
+ const std::string kInjectionError = "Shell injection";
71
+ // Shell corruption bug detected based on syntax error.
72
+ const std::string kCorruptionError = "Shell corruption";
73
+ // The magic string that we'll use to detect arbitrary file open
74
+ const std::string kFzAbsoluteDirectory = "/fz/";
75
+ // Arbitrary file open in /fz/
76
+ const std::string kArbitraryFileOpenError = "Arbitrary file open";
77
+ // Assuming only shorter (than this constant) top dir are legitly used.
78
+ constexpr int kRootDirMaxLength = 16;
79
+
80
+ // The PID of the root process we're fuzzing.
81
+ pid_t g_root_pid;
82
+
83
+ // Map of a PID/TID its PID/TID creator and wether it ran exec.
84
+ std::map<pid_t, ThreadParent> root_pids;
85
+
86
+ // Assuming the longest pathname is "/bin/bash".
87
+ constexpr int kShellPathnameLength = 20;
88
+
89
+ // Syntax error messages of each shell.
90
+ const std::map<std::string, std::set<std::string>> kShellSyntaxErrors = {
91
+ {"bash",
92
+ {
93
+ ": command not found", // General
94
+ ": syntax error", // Unfinished " or ' or ` or if, leading | or ;
95
+ ": missing `]'", // Unfinished [
96
+ ": event not found", // ! leads large numbers
97
+ ": No such file or directory", // Leading < or /
98
+ }},
99
+ {"csh",
100
+ {
101
+ ": Command not found.", // General
102
+ ": Missing }.", // Unfinished {
103
+ "Too many ('s.", // Unfinished (
104
+ "Invalid null command.", // Leading | or < or >
105
+ "Missing name for redirect.", // Single < or >
106
+ ": No match.", // Leading ? or [ or *
107
+ "Modifier failed.", // Leading ^
108
+ "No previous left hand side.", // A ^
109
+ ": No such job.", // Leading %
110
+ ": No current job.", // A %
111
+ ": Undefined variable.", // Containing $
112
+ ": Event not found.", // ! leads large numbers
113
+ // TODO: Make this more specific.
114
+ "Unmatched", // Unfinished " or ' or `, leading ;
115
+ }},
116
+ {"dash",
117
+ {
118
+ "not found", // General
119
+ "Syntax error", // Unfinished " or ' or ` or if, leading | or ; or &
120
+ "missing ]", // Unfinished [
121
+ "No such file", // Leading <
122
+ }},
123
+ {"zsh",
124
+ {
125
+ ": command not found", // General
126
+ ": syntax error", // Unfinished " or ' or `
127
+ ": ']' expected", // Unfinished [
128
+ ": no such file or directory", // Leading < or /
129
+ ": parse error near", // Leading |, or &
130
+ ": no such user or named directory", // Leading ~
131
+ }},
132
+ };
133
+
134
+ // Shells used by Processes.
135
+ std::map<pid_t, std::string> g_shell_pids;
136
+
137
+ struct Tracee {
138
+ pid_t pid;
139
+ bool syscall_enter = true;
140
+
141
+ Tracee(pid_t pid) : pid(pid) {}
142
+ };
143
+
144
+ pid_t run_child(char **argv) {
145
+ // Run the program under test with its args as a child process
146
+ pid_t pid = fork();
147
+ switch (pid) {
148
+ case -1:
149
+ fatal_log("Fork failed: %s", strerror(errno));
150
+ case 0:
151
+ raise(SIGSTOP);
152
+ execvp(argv[0], argv);
153
+ fatal_log("execvp: %s", strerror(errno));
154
+ }
155
+ return pid;
156
+ }
157
+
158
+ // Construct a string with the memory specified in a register.
159
+ std::string read_string(pid_t pid, unsigned long reg, unsigned long length) {
160
+ auto memory = read_memory(pid, reg, length);
161
+ if (!memory.size()) {
162
+ return "";
163
+ }
164
+
165
+ std::string content(reinterpret_cast<char *>(memory.data()),
166
+ std::min(memory.size(), length));
167
+ return content;
168
+ }
169
+
170
+ void inspect_for_injection(pid_t pid, const user_regs_struct &regs) {
171
+ // Inspect a PID's registers for the sign of shell injection.
172
+ std::string path = read_string(pid, regs.rdi, kTripWire.length());
173
+ if (!path.length()) {
174
+ return;
175
+ }
176
+ debug_log("inspecting");
177
+ if (path == kTripWire) {
178
+ report_bug(kInjectionError, pid);
179
+ }
180
+ }
181
+
182
+ std::string get_pathname(pid_t pid, const user_regs_struct &regs) {
183
+ // Parse the pathname from the memory specified in the RDI register.
184
+ std::string pathname = read_string(pid, regs.rdi, kShellPathnameLength);
185
+ debug_log("Pathname is %s (len %lu)\n", pathname.c_str(), pathname.length());
186
+ return pathname;
187
+ }
188
+
189
+ std::string match_shell(std::string binary_pathname);
190
+
191
+ // Identify the exact shell behind sh
192
+ std::string identify_sh(std::string path) {
193
+ char shell_pathname[kShellPathnameLength];
194
+ auto written = readlink(path.c_str(), shell_pathname, kShellPathnameLength - 1);
195
+ if (written == -1) {
196
+ std::cerr << "Cannot query which shell is behind sh: readlink failed on "
197
+ << path << ": "
198
+ << strerror(errno) << "\n";
199
+ std::cerr << "Assuming the shell is dash\n";
200
+ return "dash";
201
+ }
202
+ shell_pathname[written] = '\0';
203
+
204
+ debug_log("sh links to %s\n", shell_pathname);
205
+ std::string shell_pathname_str(shell_pathname);
206
+
207
+ return match_shell(shell_pathname_str);
208
+ }
209
+
210
+ std::string match_shell(std::string binary_pathname) {
211
+ // Identify the name of the shell used in the pathname.
212
+ if (!binary_pathname.length()) {
213
+ return "";
214
+ }
215
+
216
+ // We use c_str() to accept only the null terminated string.
217
+ std::string binary_name = binary_pathname.substr(
218
+ binary_pathname.find_last_of("/") + 1).c_str();
219
+
220
+ debug_log("Binary is %s (%lu)\n", binary_name.c_str(),
221
+ binary_name.length());
222
+
223
+ for (const auto &item : kShellSyntaxErrors) {
224
+ std::string known_shell = item.first;
225
+ if (binary_name == "sh") {
226
+ debug_log("Matched sh: Needs to identify which specific shell it is.\n");
227
+ return identify_sh(binary_pathname);
228
+ }
229
+ if (binary_name == known_shell) {
230
+ debug_log("Matched %s\n", binary_name.c_str());
231
+ return known_shell;
232
+ }
233
+ }
234
+ return "";
235
+ }
236
+
237
+ std::string get_shell(pid_t pid, const user_regs_struct &regs) {
238
+ // Get shell name used in a process.
239
+ std::string binary_pathname = get_pathname(pid, regs);
240
+ return match_shell(binary_pathname);
241
+ }
242
+
243
+ void match_error_pattern(std::string buffer, std::string shell, pid_t pid) {
244
+ auto error_patterns = kShellSyntaxErrors.at(shell);
245
+ for (const auto &pattern : error_patterns) {
246
+ if (buffer.find(pattern) != std::string::npos) {
247
+ std::cerr << "--- Found a sign of shell corruption ---\n"
248
+ << buffer.c_str()
249
+ << "\n----------------------------------------\n";
250
+ // If a shell corruption error happens, kill its parent.
251
+ auto parent = root_pids[pid];
252
+ while (!parent.ran_exec) {
253
+ if (parent.parent_tid == g_root_pid) {
254
+ break;
255
+ }
256
+ parent = root_pids[parent.parent_tid];
257
+ }
258
+ report_bug(kCorruptionError, parent.parent_tid);
259
+ }
260
+ }
261
+ }
262
+
263
+ void inspect_for_corruption(pid_t pid, const user_regs_struct &regs) {
264
+ // Inspect a PID's registers for shell corruption.
265
+ std::string buffer = read_string(pid, regs.rsi, regs.rdx);
266
+ debug_log("Write buffer: %s\n", buffer.c_str());
267
+ match_error_pattern(buffer, g_shell_pids[pid], pid);
268
+ }
269
+
270
+ void log_file_open(std::string path, int flags, pid_t pid) {
271
+ report_bug(kArbitraryFileOpenError, pid);
272
+ std::cerr << "===File opened: " << path.c_str() << ", flags = " << flags << ",";
273
+ switch (flags & 3) {
274
+ case O_RDONLY:
275
+ std::cerr << "O_RDONLY";
276
+ break;
277
+ case O_WRONLY:
278
+ std::cerr << "O_WRONLY";
279
+ break;
280
+ case O_RDWR:
281
+ std::cerr << "O_RDWR";
282
+ break;
283
+ default:
284
+ std::cerr << "unknown";
285
+ }
286
+ std::cerr << "===\n";
287
+ }
288
+
289
+ bool has_unprintable(const std::string &value) {
290
+ for (size_t i = 0; i < value.length(); i++) {
291
+ if (value[i] & 0x80) {
292
+ return true;
293
+ }
294
+ }
295
+ return false;
296
+ }
297
+
298
+ void inspect_for_arbitrary_file_open(pid_t pid, const user_regs_struct &regs) {
299
+ // Inspect a PID's register for the sign of arbitrary file open.
300
+ std::string path = read_string(pid, regs.rsi, kRootDirMaxLength);
301
+ if (!path.length()) {
302
+ return;
303
+ }
304
+ if (path.substr(0, kFzAbsoluteDirectory.length()) == kFzAbsoluteDirectory) {
305
+ log_file_open(path, regs.rdx, pid);
306
+ return;
307
+ }
308
+ if (path[0] == '/' && path.length() > 1) {
309
+ std::string path_absolute_topdir = path;
310
+ size_t root_dir_end = path.find('/', 1);
311
+ if (root_dir_end != std::string::npos) {
312
+ path_absolute_topdir = path.substr(0, root_dir_end);
313
+ }
314
+ if (has_unprintable(path_absolute_topdir)) {
315
+ struct stat dirstat;
316
+ if (stat(path_absolute_topdir.c_str(), &dirstat) != 0) {
317
+ log_file_open(path, regs.rdx, pid);
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ int trace(std::map<pid_t, Tracee> pids) {
324
+ unsigned long exit_status = 0;
325
+ while (!pids.empty()) {
326
+ std::vector<pid_t> new_pids;
327
+
328
+ auto it = pids.begin();
329
+
330
+ while (it != pids.end()) {
331
+ auto pid = it->first;
332
+ auto &tracee = it->second;
333
+ int status = 0;
334
+
335
+ int result = waitpid(pid, &status, __WALL | WNOHANG);
336
+ if (result == -1) {
337
+ it = pids.erase(it);
338
+ continue;
339
+ }
340
+
341
+ if (result == 0) {
342
+ // Nothing to report yet.
343
+ ++it;
344
+ continue;
345
+ }
346
+
347
+ if (WIFEXITED(status) || WIFSIGNALED(status)) {
348
+ debug_log("%d exited", pid);
349
+ it = pids.erase(it);
350
+ // Remove pid from the watchlist when it exits
351
+ g_shell_pids.erase(pid);
352
+ root_pids.erase(pid);
353
+ continue;
354
+ }
355
+
356
+ // ptrace sets 0x80 for syscalls (with PTRACE_O_TRACESYSGOOD set).
357
+ bool is_syscall =
358
+ WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80);
359
+ int sig = 0;
360
+ if (!is_syscall) {
361
+ // Handle generic signal.
362
+ siginfo_t siginfo;
363
+ if (ptrace(PTRACE_GETSIGINFO, pid, nullptr, &siginfo) == -1) {
364
+ debug_log("ptrace(PTRACE_GETSIGINFO, %d): %s", pid, strerror(errno));
365
+ continue;
366
+ }
367
+ sig = siginfo.si_signo;
368
+ debug_log("forwarding signal %d to %d", sig, pid);
369
+ }
370
+
371
+ if ((status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8)))) {
372
+ debug_log("%d exiting", pid);
373
+ if (pid == g_root_pid) {
374
+ if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &exit_status) == -1) {
375
+ debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno));
376
+ }
377
+ debug_log("got exit status from root process: %lu", exit_status);
378
+ }
379
+
380
+ if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) {
381
+ debug_log("ptrace(PTRACE_DETACH, %d): %s", pid, strerror(errno));
382
+ }
383
+ continue;
384
+ }
385
+
386
+ if (WIFSTOPPED(status) &&
387
+ (status >> 8 == (SIGTRAP | (PTRACE_EVENT_CLONE << 8)) ||
388
+ status >> 8 == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) ||
389
+ status >> 8 == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)))) {
390
+ long new_pid;
391
+ if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &new_pid) == -1) {
392
+ debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno));
393
+ continue;
394
+ }
395
+ debug_log("forked %ld", new_pid);
396
+ new_pids.push_back(new_pid);
397
+ root_pids.emplace(new_pid, ThreadParent(pid));
398
+ }
399
+
400
+ if (is_syscall) {
401
+ user_regs_struct regs;
402
+ if (ptrace(PTRACE_GETREGS, pid, 0, &regs) == -1) {
403
+ debug_log("ptrace(PTRACE_GETREGS, %d): %s", pid, strerror(errno));
404
+ continue;
405
+ }
406
+
407
+ if (tracee.syscall_enter) {
408
+ if (regs.orig_rax == __NR_execve) {
409
+ // This is a new process.
410
+ auto parent = root_pids[pid];
411
+ parent.ran_exec = true;
412
+ root_pids[pid] = parent;
413
+ inspect_for_injection(pid, regs);
414
+ std::string shell = get_shell(pid, regs);
415
+ if (shell != "") {
416
+ debug_log("Shell parsed: %s", shell.c_str());
417
+ g_shell_pids.insert(std::make_pair(pid, shell));
418
+ }
419
+ }
420
+
421
+ inspect_dns_syscalls(pid, regs);
422
+
423
+ if (regs.orig_rax == __NR_openat) {
424
+ // TODO(metzman): Re-enable this once we have config/flag support.
425
+ // inspect_for_arbitrary_file_open(pid, regs);
426
+ }
427
+
428
+ if (regs.orig_rax == __NR_write &&
429
+ g_shell_pids.find(pid) != g_shell_pids.end()) {
430
+ debug_log("Inspecting the `write` buffer of shell process %d.",
431
+ pid);
432
+ inspect_for_corruption(pid, regs);
433
+ }
434
+ }
435
+
436
+ // TODO: Check for commands with invalid syntax passed to /bin/sh and
437
+ // other shells.
438
+ // TODO: It's possible the process we're fuzzing can communicate with
439
+ // another process to execute code. Our check wouldn't catch this
440
+ // currently.
441
+ tracee.syscall_enter = !tracee.syscall_enter;
442
+ }
443
+
444
+ if (ptrace(PTRACE_SYSCALL, pid, nullptr, sig) == -1) {
445
+ debug_log("ptrace(PTRACE_SYSCALL, %d): %s", pid, strerror(errno));
446
+ continue;
447
+ }
448
+
449
+ ++it;
450
+ }
451
+
452
+ for (const auto &pid : new_pids) {
453
+ pids.emplace(pid, Tracee(pid));
454
+ }
455
+ }
456
+ return static_cast<int>(exit_status >> 8);
457
+ }
458
+
459
+ int main(int argc, char **argv) {
460
+ if (argc <= 1) {
461
+ fatal_log("Expecting at least one arguments, received %d", argc - 1);
462
+ }
463
+
464
+ // Create an executable tripwire file, as programs may check for existence
465
+ // before actually calling exec.
466
+ std::ofstream tripwire(kTripWire);
467
+ tripwire.close();
468
+ chmod(kTripWire.c_str(), 0755);
469
+
470
+ pid_t pid = run_child(argv + 1);
471
+
472
+ long options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK |
473
+ PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE |
474
+ PTRACE_O_TRACEEXIT;
475
+
476
+ if (ptrace(PTRACE_SEIZE, pid, nullptr, options) == -1) {
477
+ fatal_log("ptrace(PTRACE_SEIZE): %s", strerror(errno));
478
+ }
479
+
480
+ if (waitpid(pid, nullptr, __WALL) == -1) {
481
+ fatal_log("waitpid: %s", strerror(errno));
482
+ }
483
+
484
+ if (ptrace(PTRACE_SYSCALL, pid, 0, 0) == -1) {
485
+ fatal_log("ptrace(PTRACE_SYSCALL): %s", strerror(errno));
486
+ }
487
+
488
+ g_root_pid = pid;
489
+ std::map<pid_t, Tracee> pids;
490
+ pids.emplace(pid, Tracee(pid));
491
+ root_pids.emplace(pid, ThreadParent(pid));
492
+ return trace(pids);
493
+ }
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /* A detector that uses ptrace to identify DNS arbitrary resolutions. */
17
+
18
+
19
+ /* POSIX */
20
+ #include <unistd.h>
21
+
22
+ /* Linux */
23
+ #include <sys/ptrace.h>
24
+
25
+
26
+ void inspect_dns_syscalls(pid_t pid, const user_regs_struct &regs);
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/target.cpp ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /* A sample target program under test,
17
+ * /tmp/tripwire or other commands will be injected into its shell command */
18
+
19
+ #include <stdlib.h>
20
+ #include <string>
21
+ #include <iostream>
22
+
23
+ extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) {
24
+ std::string str(data, size);
25
+ std::cout << "INPUT" << str << std::endl;
26
+ system(str.c_str());
27
+ return 0;
28
+ }
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ #include <stdlib.h>
18
+ #include <stdio.h>
19
+ #include <string>
20
+ #include <iostream>
21
+
22
+ #include <string.h>
23
+ #include <sys/types.h>
24
+ #include <sys/socket.h>
25
+ #include <netdb.h>
26
+
27
+ extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) {
28
+ std::string str(data, size);
29
+ std::cout << "INPUT" << str << std::endl;
30
+
31
+ struct addrinfo *result = NULL;
32
+
33
+ getaddrinfo(str.c_str(), NULL, NULL, &result);
34
+ if (result) {
35
+ freeaddrinfo(result);
36
+ }
37
+
38
+ return 0;
39
+ }
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright 2022 Google LLC
3
+
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /* A sample target program under test,
17
+ * /tmp/tripwire or other commands will be injected into its shell command */
18
+
19
+ #include <stdlib.h>
20
+ #include <stdio.h>
21
+ #include <string>
22
+ #include <iostream>
23
+
24
+ extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) {
25
+ std::string str(data, size);
26
+ std::cout << "INPUT" << str << std::endl;
27
+ FILE *fp = fopen(str.c_str(), "r");
28
+ if (fp) {
29
+ fclose(fp);
30
+ }
31
+ return 0;
32
+ }
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/chronos/Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+ FROM gcr.io/cloud-builders/gcloud
17
+
18
+ RUN apt-get update && apt-get install -y jq
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/chronos/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Chronos: rebuilding OSS-Fuzz harnesses using cached builds
2
+
3
+ ## Pre-built images.
4
+
5
+ Daily pre-built images are available at:
6
+
7
+ - `us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/<PROJECT>-ofg-cached-address`
8
+ - `us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/<PROJECT>-ofg-cached-coverage`
9
+
10
+ They can be used as drop-in replacements for the usual `gcr.io/oss-fuzz/<PROJECT>` images.
11
+
12
+ These images are generated in 2 ways:
13
+ - (Preferred) [Generate](https://github.com/google/oss-fuzz/blob/master/infra/base-images/base-builder/bash_parser.py)
14
+ a replay build script that can be re-run alongside existing build artifacts,
15
+ leveraging existing build system mechanisms to avoid rebuilding (e.g. running
16
+ `make` twice should not actually rebuild everything). This is error-prone, so
17
+ we validate the script works by running it.
18
+ - (Fallback, if the replay build script didn't work). We leverage
19
+ [ccache](https://ccache.dev/), to provide a compiler cache. This is often not
20
+ as fast as the replay build script, because some project builds spend
21
+ significant time doing non-compiler tasks (e.g. checking out submodules,
22
+ running configure scripts).
23
+
24
+ Note: this mechanism does not work for every single OSS-Fuzz project today. The
25
+ resulting image may either:
26
+ - Not provide much performance improvement compared with a normal image, or
27
+ - Not exist at all (if neither approach worked).
28
+
29
+ Stats from a recent run: <https://gist.github.com/oliverchang/abaf3a1106a2b923c0ac3a577410aaaa>
30
+ (Feb 3 2025).
31
+
32
+ ## Usage locally
33
+
34
+ **Example 1: htslib**
35
+
36
+ From the OSS-Fuzz root
37
+
38
+ ```sh
39
+ $ RUN_ALL=1 ./infra/experimental/chronos/build_cache_local.sh htslib c address
40
+ ...
41
+ ...
42
+ Vanilla compile time:
43
+ 17
44
+ Replay worked
45
+ Replay compile time:
46
+ 2
47
+ Ccache compile time:
48
+ 9
49
+ ```
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/bash -eux
2
+ # Copyright 2024 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+
18
+ CMP1=$1
19
+ CMP2=$2
20
+
21
+ for exec1 in $(find $CMP1/ -type f -executable); do
22
+ base=$(basename $exec1)
23
+
24
+ exec2=$CMP2/${base}
25
+ if [ ! -f ${exec2} ]; then
26
+ exit 1
27
+ fi
28
+
29
+ comparison=$(cmp --silent $exec1 $exec2; echo $?)
30
+ if [[ $comparison -ne 0 ]]; then
31
+ exit 1
32
+ fi
33
+ done
34
+
35
+ exit 0
local-test-commons-compress-full-01-vuln_2/fuzz-tooling/infra/tools/hold_back_images.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Script for pinning builder images for projects that break on upgrades. Works
18
+ with projects that use language builders."""
19
+ import argparse
20
+ import logging
21
+ import os
22
+ import re
23
+ import sys
24
+ import subprocess
25
+
26
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
27
+ PROJECTS_DIR = os.path.join(ROOT_DIR, 'projects')
28
+
29
+ IMAGE_DIGEST_REGEX = re.compile(r'\[(.+)\]\n')
30
+ FROM_LINE_REGEX = re.compile(
31
+ r'FROM (ghcr.io\/aixcc-finals\/base-builder[\-a-z0-9]*)(\@?.*)')
32
+
33
+
34
+ def get_latest_docker_image_digest(image):
35
+ """Returns a pinnable version of the latest |image|. This version will have a
36
+ SHA."""
37
+ subprocess.run(['docker', 'pull', image], check=True)
38
+ subprocess.run(['docker', 'pull', image], stdout=subprocess.PIPE, check=True)
39
+
40
+ command = [
41
+ 'docker', 'image', 'inspect', '--format', '{{.RepoDigests}}', image
42
+ ]
43
+ output = subprocess.run(command, check=True,
44
+ stdout=subprocess.PIPE).stdout.decode('utf-8')
45
+ return IMAGE_DIGEST_REGEX.match(output).groups(1)[0]
46
+
47
+
48
+ def get_args():
49
+ """Returns parsed arguments."""
50
+ parser = argparse.ArgumentParser(sys.argv[0],
51
+ description='Hold back builder images.')
52
+ parser.add_argument('projects', help='Projects.', nargs='+')
53
+
54
+ parser.add_argument('--hold-image-digest',
55
+ required=False,
56
+ nargs='?',
57
+ default=None,
58
+ help='Image to hold on to.')
59
+
60
+ parser.add_argument('--update-held',
61
+ action='store_true',
62
+ default=False,
63
+ help='Update held images.')
64
+
65
+ parser.add_argument('--issue-number',
66
+ required=False,
67
+ nargs='?',
68
+ default=None,
69
+ help='Issue to reference.')
70
+
71
+ args = parser.parse_args()
72
+ return args
73
+
74
+
75
+ def get_hold_image_digest(line, hold_image_digest, update_held):
76
+ """Returns the image digest for the |line| we want to pin. If the image is
77
+ already pinned then it is only updated if |update_held. If |hold_image_digest
78
+ is specified then it is returned, otherwise the latest pinnable version is
79
+ returned."""
80
+ matches = FROM_LINE_REGEX.match(line).groups()
81
+ if matches[1] and not update_held:
82
+ return None, False
83
+ initial_image = matches[0]
84
+ if hold_image_digest:
85
+ return hold_image_digest, True
86
+ return get_latest_docker_image_digest(initial_image), True
87
+
88
+
89
+ def hold_image(project, hold_image_digest, update_held, issue_number):
90
+ """Rewrites the Dockerfile of |project| to pin the base-builder image on
91
+ upgrade."""
92
+ dockerfile_path = os.path.join(PROJECTS_DIR, project, 'Dockerfile')
93
+ with open(dockerfile_path, 'r') as dockerfile_handle:
94
+ dockerfile = dockerfile_handle.readlines()
95
+ for idx, line in enumerate(dockerfile[:]):
96
+ if not line.startswith('FROM ghcr.io/aixcc-finals/base-builder'):
97
+ continue
98
+
99
+ hold_image_digest, should_hold = get_hold_image_digest(
100
+ line.strip(), hold_image_digest, update_held)
101
+ if not should_hold:
102
+ logging.error('Not holding back %s.', project)
103
+ break
104
+ dockerfile[idx] = f'FROM {hold_image_digest}\n'
105
+ if issue_number:
106
+ comment = ('# Held back because of github.com/google/oss-fuzz/pull/'
107
+ f'{issue_number}\n# Please fix failure and upgrade.\n')
108
+ dockerfile.insert(idx, comment)
109
+ break
110
+ else:
111
+ # This path is taken when we don't break out of the loop.
112
+ assert None, f'Could not find FROM line in {project}'
113
+ dockerfile = ''.join(dockerfile)
114
+ with open(dockerfile_path, 'w') as dockerfile_handle:
115
+ dockerfile_handle.write(dockerfile)
116
+
117
+
118
+ def main():
119
+ """Script for pinning builder images for projects that break on upgrades."""
120
+ args = get_args()
121
+ for project in args.projects:
122
+ hold_image(project, args.hold_image_digest, args.update_held,
123
+ args.issue_number)
124
+ return 0
125
+
126
+
127
+ if __name__ == '__main__':
128
+ sys.exit(main())