Kitxuuu commited on
Commit
9391520
·
verified ·
1 Parent(s): 290e154

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-commons-compress-delta-02/fuzz-tooling/docs/.gitignore +5 -0
  2. local-test-commons-compress-delta-02/fuzz-tooling/docs/404.html +23 -0
  3. local-test-commons-compress-delta-02/fuzz-tooling/docs/Gemfile +4 -0
  4. local-test-commons-compress-delta-02/fuzz-tooling/docs/glossary.md +1 -0
  5. local-test-commons-compress-delta-02/fuzz-tooling/docs/ideal_integration.md +1 -0
  6. local-test-commons-compress-delta-02/fuzz-tooling/docs/reproducing.md +1 -0
  7. local-test-commons-compress-delta-02/fuzz-tooling/infra/README.md +23 -0
  8. local-test-commons-compress-delta-02/fuzz-tooling/infra/bisector_test.py +70 -0
  9. local-test-commons-compress-delta-02/fuzz-tooling/infra/build_fuzzers.Dockerfile +31 -0
  10. local-test-commons-compress-delta-02/fuzz-tooling/infra/build_specified_commit_test.py +126 -0
  11. local-test-commons-compress-delta-02/fuzz-tooling/infra/helper.py +1810 -0
  12. local-test-commons-compress-delta-02/fuzz-tooling/infra/helper_test.py +239 -0
  13. local-test-commons-compress-delta-02/fuzz-tooling/infra/manifest.py +61 -0
  14. local-test-commons-compress-delta-02/fuzz-tooling/infra/presubmit.py +549 -0
  15. local-test-commons-compress-delta-02/fuzz-tooling/infra/retry.py +106 -0
  16. local-test-commons-compress-delta-02/fuzz-tooling/infra/run_fuzzers.Dockerfile +31 -0
  17. local-test-commons-compress-delta-02/fuzz-tooling/infra/templates.py +119 -0
  18. local-test-commons-compress-delta-02/fuzz-tooling/infra/test +1 -0
  19. local-test-commons-compress-delta-02/fuzz-tooling/infra/test_repos.py +84 -0
  20. local-test-commons-compress-delta-02/fuzz-tooling/infra/utils.py +205 -0
local-test-commons-compress-delta-02/fuzz-tooling/docs/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ _site
2
+ .bundle
3
+ .sass-cache
4
+ .jekyll-metadata
5
+ vendor
local-test-commons-compress-delta-02/fuzz-tooling/docs/404.html ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ layout: default
3
+ ---
4
+
5
+ <style type="text/css" media="screen">
6
+ .container {
7
+ margin: 10px auto;
8
+ max-width: 600px;
9
+ text-align: center;
10
+ }
11
+ h1 {
12
+ margin: 30px 0;
13
+ font-size: 4em;
14
+ line-height: 1;
15
+ letter-spacing: -1px;
16
+ }
17
+ </style>
18
+
19
+ <div class="container">
20
+ <h1>404</h1>
21
+
22
+ <p><strong>Page not found :(</strong></p>
23
+ </div>
local-test-commons-compress-delta-02/fuzz-tooling/docs/Gemfile ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ source "https://rubygems.org"
2
+ gem 'github-pages', group: :jekyll_plugins
3
+
4
+ gem "webrick", "~> 1.8"
local-test-commons-compress-delta-02/fuzz-tooling/docs/glossary.md ADDED
@@ -0,0 +1 @@
 
 
1
+ This page has moved [here](https://google.github.io/oss-fuzz/reference/glossary/)
local-test-commons-compress-delta-02/fuzz-tooling/docs/ideal_integration.md ADDED
@@ -0,0 +1 @@
 
 
1
+ This page has moved [here](https://google.github.io/oss-fuzz/advanced-topics/ideal-integration)
local-test-commons-compress-delta-02/fuzz-tooling/docs/reproducing.md ADDED
@@ -0,0 +1 @@
 
 
1
+ This page has moved [here](https://google.github.io/oss-fuzz/advanced-topics/reproducing)
local-test-commons-compress-delta-02/fuzz-tooling/infra/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # infra
2
+ > OSS-Fuzz project infrastructure
3
+
4
+ Core infrastructure:
5
+ * [`base-images`](base-images/) - docker images for building fuzz targets & corresponding jenkins
6
+ pipeline.
7
+
8
+ Continuous Integration infrastructure:
9
+
10
+ * [`ci`](ci/) - script to build projects in CI.
11
+
12
+ ## helper.py
13
+ > script to automate common docker operations
14
+
15
+ | Command | Description |
16
+ |---------|-------------
17
+ | `generate` | Generates skeleton files for a new project |
18
+ | `build_image` | Builds a docker image for a given project |
19
+ | `build_fuzzers` | Builds fuzz targets for a given project |
20
+ | `run_fuzzer` | Runs a fuzz target in a docker container |
21
+ | `coverage` | Runs fuzz target(s) in a docker container and generates a code coverage report. See [Code Coverage doc](https://google.github.io/oss-fuzz/advanced-topics/code-coverage/) |
22
+ | `reproduce` | Runs a testcase to reproduce a crash |
23
+ | `shell` | Starts a shell inside the docker image for a project |
local-test-commons-compress-delta-02/fuzz-tooling/infra/bisector_test.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing perepo_managerissions and
13
+ # limitations under the License.
14
+ """Test the functionality of bisection module:
15
+ 1) Test a known case where an error appears in a regression range.
16
+ 2) Bisect can handle incorrect inputs.
17
+
18
+ IMPORTANT: This test needs to be run with root privileges.
19
+ """
20
+
21
+ import os
22
+ import unittest
23
+
24
+ import bisector
25
+ import build_specified_commit
26
+ import test_repos
27
+
28
+ # Necessary because __file__ changes with os.chdir
29
+ TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__))
30
+
31
+
32
+ @unittest.skip('Test is too long to be run with presubmit.')
33
+ class BisectIntegrationTests(unittest.TestCase):
34
+ """Class to test the functionality of bisection method."""
35
+
36
+ BISECT_TYPE = 'regressed'
37
+
38
+ def test_bisect_invalid_repo(self):
39
+ """Test the bisection method on a project that does not exist."""
40
+ test_repo = test_repos.INVALID_REPO
41
+ build_data = build_specified_commit.BuildData(
42
+ project_name=test_repo.project_name,
43
+ engine='libfuzzer',
44
+ sanitizer='address',
45
+ architecture='x86_64')
46
+ with self.assertRaises(ValueError):
47
+ bisector.bisect(self.BISECT_TYPE, test_repo.old_commit,
48
+ test_repo.new_commit, test_repo.testcase_path,
49
+ test_repo.fuzz_target, build_data)
50
+
51
+ def test_bisect(self):
52
+ """Test the bisect method on example projects."""
53
+ for test_repo in test_repos.TEST_REPOS:
54
+ if test_repo.new_commit:
55
+ build_data = build_specified_commit.BuildData(
56
+ project_name=test_repo.project_name,
57
+ engine='libfuzzer',
58
+ sanitizer='address',
59
+ architecture='x86_64')
60
+ result = bisector.bisect(self.BISECT_TYPE, test_repo.old_commit,
61
+ test_repo.new_commit, test_repo.testcase_path,
62
+ test_repo.fuzz_target, build_data)
63
+ self.assertEqual(result.commit, test_repo.intro_commit)
64
+
65
+
66
+ if __name__ == '__main__':
67
+ # Change to oss-fuzz main directory so helper.py runs correctly.
68
+ if os.getcwd() != os.path.dirname(TEST_DIR_PATH):
69
+ os.chdir(os.path.dirname(TEST_DIR_PATH))
70
+ unittest.main()
local-test-commons-compress-delta-02/fuzz-tooling/infra/build_fuzzers.Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+ # Docker image to run fuzzers for CIFuzz (the run_fuzzers action on GitHub
17
+ # actions).
18
+
19
+ FROM ghcr.io/aixcc-finals/cifuzz-base
20
+
21
+ # Python file to execute when the docker container starts up
22
+ # We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var,
23
+ # just expand to '/opt/oss-fuzz'.
24
+ ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/build_fuzzers_entrypoint.py"]
25
+
26
+ WORKDIR ${OSS_FUZZ_ROOT}/infra
27
+
28
+ # Update infra source code.
29
+ ADD . ${OSS_FUZZ_ROOT}/infra
30
+
31
+ RUN python3 -m pip install -r ${OSS_FUZZ_ROOT}/infra/cifuzz/requirements.txt
local-test-commons-compress-delta-02/fuzz-tooling/infra/build_specified_commit_test.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2019 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Test the functionality of the build image from commit module.
15
+ The will consist of the following functional tests:
16
+ 1. The inference of the main repo for a specific project.
17
+ 2. The building of a projects fuzzers from a specific commit.
18
+
19
+ """
20
+ import os
21
+ import tempfile
22
+ import unittest
23
+
24
+ import build_specified_commit
25
+ import helper
26
+ import repo_manager
27
+ import test_repos
28
+
29
+ # necessary because __file__ changes with os.chdir
30
+ TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__))
31
+
32
+
33
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
34
+ 'INTEGRATION_TESTS=1 not set')
35
+ class BuildImageIntegrationTest(unittest.TestCase):
36
+ """Tests if an image can be built from different states e.g. a commit."""
37
+
38
+ @unittest.skip('Test is failing (spuriously?).')
39
+ def test_build_fuzzers_from_commit(self):
40
+ """Tests if the fuzzers can build at a specified commit.
41
+
42
+ This is done by using a known regression range for a specific test case.
43
+ The old commit should show the error when its fuzzers run and the new one
44
+ should not.
45
+ """
46
+ with tempfile.TemporaryDirectory() as tmp_dir:
47
+ test_repo = test_repos.TEST_REPOS[1]
48
+ self.assertTrue(helper.build_image_impl(test_repo.project_name))
49
+ host_src_dir = build_specified_commit.copy_src_from_docker(
50
+ test_repo.project_name, tmp_dir)
51
+
52
+ test_repo_manager = repo_manager.clone_repo_and_get_manager(
53
+ test_repo.git_url, host_src_dir, test_repo.oss_repo_name)
54
+ build_data = build_specified_commit.BuildData(
55
+ sanitizer='address',
56
+ architecture='x86_64',
57
+ engine='libfuzzer',
58
+ project_name=test_repo.project_name)
59
+
60
+ build_specified_commit.build_fuzzers_from_commit(test_repo.old_commit,
61
+ test_repo_manager,
62
+ host_src_dir, build_data)
63
+ project = helper.Project(test_repo.project_name)
64
+ old_result = helper.reproduce_impl(project=project,
65
+ fuzzer_name=test_repo.fuzz_target,
66
+ valgrind=False,
67
+ env_to_add=[],
68
+ fuzzer_args=[],
69
+ testcase_path=test_repo.testcase_path)
70
+ build_specified_commit.build_fuzzers_from_commit(test_repo.project_name,
71
+ test_repo_manager,
72
+ host_src_dir, build_data)
73
+ new_result = helper.reproduce_impl(project=project,
74
+ fuzzer_name=test_repo.fuzz_target,
75
+ valgrind=False,
76
+ env_to_add=[],
77
+ fuzzer_args=[],
78
+ testcase_path=test_repo.testcase_path)
79
+ self.assertNotEqual(new_result, old_result)
80
+
81
+ def test_detect_main_repo_from_commit(self):
82
+ """Test the detect main repo function from build specific commit module."""
83
+ # TODO(metzman): Fix these tests so they don't randomly break because of
84
+ # changes in the outside world.
85
+ for example_repo in test_repos.TEST_REPOS:
86
+ if example_repo.new_commit:
87
+ # TODO(metzman): This function calls _build_image_with_retries which
88
+ # has a long delay (30 seconds). Figure out how to make this quicker.
89
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
90
+ example_repo.project_name, commit=example_repo.new_commit)
91
+ self.assertEqual(repo_origin, example_repo.git_url)
92
+ self.assertEqual(repo_name,
93
+ os.path.join('/src', example_repo.oss_repo_name))
94
+
95
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
96
+ test_repos.INVALID_REPO.project_name,
97
+ test_repos.INVALID_REPO.new_commit)
98
+ self.assertIsNone(repo_origin)
99
+ self.assertIsNone(repo_name)
100
+
101
+ def test_detect_main_repo_from_name(self):
102
+ """Test the detect main repo function from build specific commit module."""
103
+ for example_repo in test_repos.TEST_REPOS:
104
+ if example_repo.project_name == 'gonids':
105
+ # It's unclear how this test ever passed, but we can't infer the repo
106
+ # because gonids doesn't really check it out, it uses "go get".
107
+ continue
108
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
109
+ example_repo.project_name, repo_name=example_repo.git_repo_name)
110
+ self.assertEqual(repo_origin, example_repo.git_url)
111
+ self.assertEqual(
112
+ repo_name,
113
+ os.path.join(example_repo.image_location, example_repo.oss_repo_name))
114
+
115
+ repo_origin, repo_name = build_specified_commit.detect_main_repo(
116
+ test_repos.INVALID_REPO.project_name,
117
+ test_repos.INVALID_REPO.oss_repo_name)
118
+ self.assertIsNone(repo_origin)
119
+ self.assertIsNone(repo_name)
120
+
121
+
122
+ if __name__ == '__main__':
123
+ # Change to oss-fuzz main directory so helper.py runs correctly.
124
+ if os.getcwd() != os.path.dirname(TEST_DIR_PATH):
125
+ os.chdir(os.path.dirname(TEST_DIR_PATH))
126
+ unittest.main()
local-test-commons-compress-delta-02/fuzz-tooling/infra/helper.py ADDED
@@ -0,0 +1,1810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2016 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Helper script for OSS-Fuzz users. Can do common tasks like building
18
+ projects/fuzzers, running them etc."""
19
+
20
+ from __future__ import print_function
21
+ from multiprocessing.dummy import Pool as ThreadPool
22
+ import argparse
23
+ import datetime
24
+ import errno
25
+ import logging
26
+ import os
27
+ import re
28
+ import shlex
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+
34
+ import constants
35
+ import templates
36
+
37
+ OSS_FUZZ_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
38
+ BUILD_DIR = os.path.join(OSS_FUZZ_DIR, 'build')
39
+
40
+ BASE_IMAGE_TAG = ':v1.2.1' # no tag for latest
41
+
42
+ BASE_RUNNER_IMAGE = f'ghcr.io/aixcc-finals/base-runner{BASE_IMAGE_TAG}'
43
+
44
+ BASE_IMAGES = {
45
+ 'generic': [
46
+ f'ghcr.io/aixcc-finals/base-image{BASE_IMAGE_TAG}',
47
+ f'ghcr.io/aixcc-finals/base-clang{BASE_IMAGE_TAG}',
48
+ f'ghcr.io/aixcc-finals/base-builder{BASE_IMAGE_TAG}',
49
+ BASE_RUNNER_IMAGE,
50
+ f'ghcr.io/aixcc-finals/base-runner-debug{BASE_IMAGE_TAG}',
51
+ ],
52
+ 'go': [f'ghcr.io/aixcc-finals/base-builder-go{BASE_IMAGE_TAG}'],
53
+ 'javascript': [f'ghcr.io/aixcc-finals/base-builder-javascript{BASE_IMAGE_TAG}'],
54
+ 'jvm': [f'ghcr.io/aixcc-finals/base-builder-jvm{BASE_IMAGE_TAG}'],
55
+ 'python': [f'ghcr.io/aixcc-finals/base-builder-python{BASE_IMAGE_TAG}'],
56
+ 'rust': [f'ghcr.io/aixcc-finals/base-builder-rust{BASE_IMAGE_TAG}'],
57
+ 'ruby': [f'ghcr.io/aixcc-finals/base-builder-ruby{BASE_IMAGE_TAG}'],
58
+ 'swift': [f'ghcr.io/aixcc-finals/base-builder-swift{BASE_IMAGE_TAG}'],
59
+ }
60
+
61
+ VALID_PROJECT_NAME_REGEX = re.compile(r'^[a-zA-Z0-9_-]+$')
62
+ MAX_PROJECT_NAME_LENGTH = 26
63
+
64
+ CORPUS_URL_FORMAT = (
65
+ 'gs://{project_name}-corpus.clusterfuzz-external.appspot.com/libFuzzer/'
66
+ '{fuzz_target}/')
67
+ CORPUS_BACKUP_URL_FORMAT = (
68
+ 'gs://{project_name}-backup.clusterfuzz-external.appspot.com/corpus/'
69
+ 'libFuzzer/{fuzz_target}/')
70
+
71
+ HTTPS_CORPUS_BACKUP_URL_FORMAT = (
72
+ 'https://storage.googleapis.com/{project_name}-backup.clusterfuzz-external'
73
+ '.appspot.com/corpus/libFuzzer/{fuzz_target}/public.zip')
74
+
75
+ LANGUAGE_REGEX = re.compile(r'[^\s]+')
76
+ PROJECT_LANGUAGE_REGEX = re.compile(r'\s*language\s*:\s*([^\s]+)')
77
+
78
+ WORKDIR_REGEX = re.compile(r'\s*WORKDIR\s*([^\s]+)')
79
+
80
+ # Regex to match special chars in project name.
81
+ SPECIAL_CHARS_REGEX = re.compile('[^a-zA-Z0-9_-]')
82
+
83
+ LANGUAGE_TO_BASE_BUILDER_IMAGE = {
84
+ 'c': 'base-builder',
85
+ 'c++': 'base-builder',
86
+ 'go': 'base-builder-go',
87
+ 'javascript': 'base-builder-javascript',
88
+ 'jvm': 'base-builder-jvm',
89
+ 'python': 'base-builder-python',
90
+ 'ruby': 'base-builder-ruby',
91
+ 'rust': 'base-builder-rust',
92
+ 'swift': 'base-builder-swift'
93
+ }
94
+ ARM_BUILDER_NAME = 'oss-fuzz-buildx-builder'
95
+
96
+ CLUSTERFUZZLITE_ENGINE = 'libfuzzer'
97
+ CLUSTERFUZZLITE_ARCHITECTURE = 'x86_64'
98
+ CLUSTERFUZZLITE_FILESTORE_DIR = 'filestore'
99
+ CLUSTERFUZZLITE_DOCKER_IMAGE = 'ghcr.io/aixcc-finals/cifuzz-run-fuzzers'
100
+
101
+ logger = logging.getLogger(__name__)
102
+
103
+ if sys.version_info[0] >= 3:
104
+ raw_input = input # pylint: disable=invalid-name
105
+
106
+ # pylint: disable=too-many-lines
107
+
108
+
109
+ class Project:
110
+ """Class representing a project that is in OSS-Fuzz or an external project
111
+ (ClusterFuzzLite user)."""
112
+
113
+ def __init__(
114
+ self,
115
+ project_name_or_path,
116
+ is_external=False,
117
+ build_integration_path=constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH):
118
+ self.is_external = is_external
119
+ if self.is_external:
120
+ self.path = os.path.abspath(project_name_or_path)
121
+ self.name = os.path.basename(self.path)
122
+ self.build_integration_path = os.path.join(self.path,
123
+ build_integration_path)
124
+ else:
125
+ self.name = project_name_or_path
126
+ self.path = os.path.join(OSS_FUZZ_DIR, 'projects', self.name)
127
+ self.build_integration_path = self.path
128
+
129
+ @property
130
+ def dockerfile_path(self):
131
+ """Returns path to the project Dockerfile."""
132
+ return os.path.join(self.build_integration_path, 'Dockerfile')
133
+
134
+ @property
135
+ def language(self):
136
+ """Returns project language."""
137
+ project_yaml_path = os.path.join(self.build_integration_path,
138
+ 'project.yaml')
139
+ if not os.path.exists(project_yaml_path):
140
+ logger.warning('No project.yaml. Assuming c++.')
141
+ return constants.DEFAULT_LANGUAGE
142
+
143
+ with open(project_yaml_path) as file_handle:
144
+ content = file_handle.read()
145
+ for line in content.splitlines():
146
+ match = PROJECT_LANGUAGE_REGEX.match(line)
147
+ if match:
148
+ return match.group(1)
149
+
150
+ logger.warning('Language not specified in project.yaml. Assuming c++.')
151
+ return constants.DEFAULT_LANGUAGE
152
+
153
+ @property
154
+ def coverage_extra_args(self):
155
+ """Returns project coverage extra args."""
156
+ project_yaml_path = os.path.join(self.build_integration_path,
157
+ 'project.yaml')
158
+ if not os.path.exists(project_yaml_path):
159
+ logger.warning('project.yaml not found: %s.', project_yaml_path)
160
+ return ''
161
+
162
+ with open(project_yaml_path) as file_handle:
163
+ content = file_handle.read()
164
+
165
+ coverage_flags = ''
166
+ read_coverage_extra_args = False
167
+ # Pass the yaml file and extract the value of the coverage_extra_args key.
168
+ # This is naive yaml parsing and we do not handle comments at this point.
169
+ for line in content.splitlines():
170
+ if read_coverage_extra_args:
171
+ # Break reading coverage args if a new yaml key is defined.
172
+ if len(line) > 0 and line[0] != ' ':
173
+ break
174
+ coverage_flags += line
175
+ if 'coverage_extra_args' in line:
176
+ read_coverage_extra_args = True
177
+ # Include the first line only if it's not a multi-line value.
178
+ if 'coverage_extra_args: >' not in line:
179
+ coverage_flags += line.replace('coverage_extra_args: ', '')
180
+ return coverage_flags
181
+
182
+ @property
183
+ def out(self):
184
+ """Returns the out dir for the project. Creates it if needed."""
185
+ return _get_out_dir(self.name)
186
+
187
+ @property
188
+ def work(self):
189
+ """Returns the out dir for the project. Creates it if needed."""
190
+ return _get_project_build_subdir(self.name, 'work')
191
+
192
+ @property
193
+ def corpus(self):
194
+ """Returns the out dir for the project. Creates it if needed."""
195
+ return _get_project_build_subdir(self.name, 'corpus')
196
+
197
+
198
+ def main(): # pylint: disable=too-many-branches,too-many-return-statements
199
+ """Gets subcommand from program arguments and does it. Returns 0 on success 1
200
+ on error."""
201
+ logging.basicConfig(level=logging.INFO)
202
+ parser = get_parser()
203
+ args = parse_args(parser)
204
+
205
+ # Need to do this before chdir.
206
+ # TODO(https://github.com/google/oss-fuzz/issues/6758): Get rid of chdir.
207
+ if hasattr(args, 'testcase_path'):
208
+ args.testcase_path = _get_absolute_path(args.testcase_path)
209
+ # Note: this has to happen after parse_args above as parse_args needs to know
210
+ # the original CWD for external projects.
211
+ os.chdir(OSS_FUZZ_DIR)
212
+ if not os.path.exists(BUILD_DIR):
213
+ os.mkdir(BUILD_DIR)
214
+
215
+ # We have different default values for `sanitizer` depending on the `engine`.
216
+ # Some commands do not have `sanitizer` argument, so `hasattr` is necessary.
217
+ if hasattr(args, 'sanitizer') and not args.sanitizer:
218
+ if args.project.language == 'javascript':
219
+ args.sanitizer = 'none'
220
+ else:
221
+ args.sanitizer = constants.DEFAULT_SANITIZER
222
+
223
+ if args.command == 'generate':
224
+ result = generate(args)
225
+ elif args.command == 'build_image':
226
+ result = build_image(args)
227
+ elif args.command == 'build_fuzzers':
228
+ result = build_fuzzers(args)
229
+ elif args.command == 'fuzzbench_build_fuzzers':
230
+ result = fuzzbench_build_fuzzers(args)
231
+ elif args.command == 'fuzzbench_run_fuzzer':
232
+ result = fuzzbench_run_fuzzer(args)
233
+ elif args.command == 'fuzzbench_measure':
234
+ result = fuzzbench_measure(args)
235
+ elif args.command == 'check_build':
236
+ result = check_build(args)
237
+ elif args.command == 'download_corpora':
238
+ result = download_corpora(args)
239
+ elif args.command == 'run_fuzzer':
240
+ result = run_fuzzer(args)
241
+ elif args.command == 'coverage':
242
+ result = coverage(args)
243
+ elif args.command == 'introspector':
244
+ result = introspector(args)
245
+ elif args.command == 'reproduce':
246
+ result = reproduce(args)
247
+ if args.propagate_exit_codes:
248
+ return result
249
+ elif args.command == 'shell':
250
+ result = shell(args)
251
+ elif args.command == 'pull_images':
252
+ result = pull_images()
253
+ elif args.command == 'run_clusterfuzzlite':
254
+ result = run_clusterfuzzlite(args)
255
+ else:
256
+ # Print help string if no arguments provided.
257
+ parser.print_help()
258
+ result = False
259
+ return bool_to_retcode(result)
260
+
261
+
262
+ def bool_to_retcode(boolean):
263
+ """Returns 0 if |boolean| is Truthy, 0 is the standard return code for a
264
+ successful process execution. Returns 1 otherwise, indicating the process
265
+ failed."""
266
+ return 0 if boolean else 1
267
+
268
+
269
+ def parse_args(parser, args=None):
270
+ """Parses |args| using |parser| and returns parsed args. Also changes
271
+ |args.build_integration_path| to have correct default behavior."""
272
+ # Use default argument None for args so that in production, argparse does its
273
+ # normal behavior, but unittesting is easier.
274
+ parsed_args = parser.parse_args(args)
275
+ project = getattr(parsed_args, 'project', None)
276
+ if not project:
277
+ return parsed_args
278
+
279
+ # Use hacky method for extracting attributes so that ShellTest works.
280
+ # TODO(metzman): Fix this.
281
+ is_external = getattr(parsed_args, 'external', False)
282
+ parsed_args.project = Project(parsed_args.project, is_external)
283
+ return parsed_args
284
+
285
+
286
+ def _add_external_project_args(parser):
287
+ parser.add_argument(
288
+ '--external',
289
+ help='Is project external?',
290
+ default=False,
291
+ action='store_true',
292
+ )
293
+
294
+
295
+ def get_parser(): # pylint: disable=too-many-statements,too-many-locals
296
+ """Returns an argparse parser."""
297
+ parser = argparse.ArgumentParser('helper.py', description='oss-fuzz helpers')
298
+ subparsers = parser.add_subparsers(dest='command')
299
+
300
+ generate_parser = subparsers.add_parser(
301
+ 'generate', help='Generate files for new project.')
302
+ generate_parser.add_argument('project')
303
+ generate_parser.add_argument('--language',
304
+ default=constants.DEFAULT_LANGUAGE,
305
+ choices=LANGUAGE_TO_BASE_BUILDER_IMAGE.keys(),
306
+ help='Project language.')
307
+ _add_external_project_args(generate_parser)
308
+
309
+ build_image_parser = subparsers.add_parser('build_image',
310
+ help='Build an image.')
311
+ build_image_parser.add_argument('project')
312
+ build_image_parser.add_argument('--pull',
313
+ action='store_true',
314
+ help='Pull latest base image.')
315
+ _add_architecture_args(build_image_parser)
316
+ build_image_parser.add_argument('--cache',
317
+ action='store_true',
318
+ default=False,
319
+ help='Use docker cache when building image.')
320
+ build_image_parser.add_argument('--no-pull',
321
+ action='store_true',
322
+ help='Do not pull latest base image.')
323
+ build_image_parser.add_argument('--docker_image_tag',
324
+ dest='docker_image_tag',
325
+ default='latest',
326
+ help='docker image build tag'
327
+ 'default: latest')
328
+ _add_external_project_args(build_image_parser)
329
+
330
+ build_fuzzers_parser = subparsers.add_parser(
331
+ 'build_fuzzers', help='Build fuzzers for a project.')
332
+ _add_architecture_args(build_fuzzers_parser)
333
+ _add_engine_args(build_fuzzers_parser)
334
+ _add_sanitizer_args(build_fuzzers_parser)
335
+ _add_environment_args(build_fuzzers_parser)
336
+ _add_external_project_args(build_fuzzers_parser)
337
+ build_fuzzers_parser.add_argument('project')
338
+ build_fuzzers_parser.add_argument('source_path',
339
+ help='path of local source',
340
+ nargs='?')
341
+ build_fuzzers_parser.add_argument('--mount_path',
342
+ dest='mount_path',
343
+ help='path to mount local source in '
344
+ '(defaults to WORKDIR)')
345
+ build_fuzzers_parser.add_argument('--clean',
346
+ dest='clean',
347
+ action='store_true',
348
+ help='clean existing artifacts.')
349
+ build_fuzzers_parser.add_argument('--no-clean',
350
+ dest='clean',
351
+ action='store_false',
352
+ help='do not clean existing artifacts '
353
+ '(default).')
354
+ build_fuzzers_parser.add_argument('--docker_image_tag',
355
+ dest='docker_image_tag',
356
+ default='latest',
357
+ help='docker image build tag'
358
+ 'default: latest')
359
+ build_fuzzers_parser.set_defaults(clean=False)
360
+
361
+ fuzzbench_build_fuzzers_parser = subparsers.add_parser(
362
+ 'fuzzbench_build_fuzzers')
363
+ _add_architecture_args(fuzzbench_build_fuzzers_parser)
364
+ fuzzbench_build_fuzzers_parser.add_argument('--engine')
365
+ _add_sanitizer_args(fuzzbench_build_fuzzers_parser)
366
+ _add_environment_args(fuzzbench_build_fuzzers_parser)
367
+ _add_external_project_args(fuzzbench_build_fuzzers_parser)
368
+ fuzzbench_build_fuzzers_parser.add_argument('project')
369
+ check_build_parser = subparsers.add_parser(
370
+ 'check_build', help='Checks that fuzzers execute without errors.')
371
+ _add_architecture_args(check_build_parser)
372
+ _add_engine_args(check_build_parser, choices=constants.ENGINES)
373
+ _add_sanitizer_args(check_build_parser, choices=constants.SANITIZERS)
374
+ _add_environment_args(check_build_parser)
375
+ check_build_parser.add_argument('project',
376
+ help='name of the project or path (external)')
377
+ check_build_parser.add_argument('fuzzer_name',
378
+ help='name of the fuzzer',
379
+ nargs='?')
380
+ _add_external_project_args(check_build_parser)
381
+
382
+ run_fuzzer_parser = subparsers.add_parser(
383
+ 'run_fuzzer', help='Run a fuzzer in the emulated fuzzing environment.')
384
+ _add_architecture_args(run_fuzzer_parser)
385
+ _add_engine_args(run_fuzzer_parser)
386
+ _add_sanitizer_args(run_fuzzer_parser)
387
+ _add_environment_args(run_fuzzer_parser)
388
+ _add_external_project_args(run_fuzzer_parser)
389
+ run_fuzzer_parser.add_argument(
390
+ '--corpus-dir', help='directory to store corpus for the fuzz target')
391
+ run_fuzzer_parser.add_argument('project',
392
+ help='name of the project or path (external)')
393
+ run_fuzzer_parser.add_argument('fuzzer_name', help='name of the fuzzer')
394
+ run_fuzzer_parser.add_argument('fuzzer_args',
395
+ help='arguments to pass to the fuzzer',
396
+ nargs='*')
397
+
398
+ fuzzbench_run_fuzzer_parser = subparsers.add_parser('fuzzbench_run_fuzzer')
399
+ _add_architecture_args(fuzzbench_run_fuzzer_parser)
400
+ fuzzbench_run_fuzzer_parser.add_argument('--engine')
401
+ _add_sanitizer_args(fuzzbench_run_fuzzer_parser)
402
+ _add_environment_args(fuzzbench_run_fuzzer_parser)
403
+ _add_external_project_args(fuzzbench_run_fuzzer_parser)
404
+ fuzzbench_run_fuzzer_parser.add_argument(
405
+ '--corpus-dir', help='directory to store corpus for the fuzz target')
406
+ fuzzbench_run_fuzzer_parser.add_argument(
407
+ 'project', help='name of the project or path (external)')
408
+ fuzzbench_run_fuzzer_parser.add_argument('fuzzer_name',
409
+ help='name of the fuzzer')
410
+ fuzzbench_run_fuzzer_parser.add_argument(
411
+ 'fuzzer_args', help='arguments to pass to the fuzzer', nargs='*')
412
+
413
+ fuzzbench_measure_parser = subparsers.add_parser('fuzzbench_measure')
414
+ fuzzbench_measure_parser.add_argument(
415
+ 'project', help='name of the project or path (external)')
416
+ fuzzbench_measure_parser.add_argument('engine_name',
417
+ help='name of the fuzzer')
418
+ fuzzbench_measure_parser.add_argument('fuzz_target_name',
419
+ help='name of the fuzzer')
420
+
421
+ coverage_parser = subparsers.add_parser(
422
+ 'coverage', help='Generate code coverage report for the project.')
423
+ coverage_parser.add_argument('--no-corpus-download',
424
+ action='store_true',
425
+ help='do not download corpus backup from '
426
+ 'OSS-Fuzz; use corpus located in '
427
+ 'build/corpus/<project>/<fuzz_target>/')
428
+ coverage_parser.add_argument('--no-serve',
429
+ action='store_true',
430
+ help='do not serve a local HTTP server.')
431
+ coverage_parser.add_argument('--port',
432
+ default='8008',
433
+ help='specify port for'
434
+ ' a local HTTP server rendering coverage report')
435
+ coverage_parser.add_argument('--fuzz-target',
436
+ help='specify name of a fuzz '
437
+ 'target to be run for generating coverage '
438
+ 'report')
439
+ coverage_parser.add_argument('--corpus-dir',
440
+ help='specify location of corpus'
441
+ ' to be used (requires --fuzz-target argument)')
442
+ coverage_parser.add_argument('--public',
443
+ action='store_true',
444
+ help='if set, will download public '
445
+ 'corpus using wget')
446
+ coverage_parser.add_argument('project',
447
+ help='name of the project or path (external)')
448
+ coverage_parser.add_argument('extra_args',
449
+ help='additional arguments to '
450
+ 'pass to llvm-cov utility.',
451
+ nargs='*')
452
+ _add_external_project_args(coverage_parser)
453
+ _add_architecture_args(coverage_parser)
454
+
455
+ introspector_parser = subparsers.add_parser(
456
+ 'introspector',
457
+ help='Run a complete end-to-end run of '
458
+ 'fuzz introspector. This involves (1) '
459
+ 'building the fuzzers with ASAN; (2) '
460
+ 'running all fuzzers; (3) building '
461
+ 'fuzzers with coverge; (4) extracting '
462
+ 'coverage; (5) building fuzzers using '
463
+ 'introspector')
464
+ introspector_parser.add_argument('project', help='name of the project')
465
+ introspector_parser.add_argument('--seconds',
466
+ help='number of seconds to run fuzzers',
467
+ default=10)
468
+ introspector_parser.add_argument('source_path',
469
+ help='path of local source',
470
+ nargs='?')
471
+ introspector_parser.add_argument(
472
+ '--public-corpora',
473
+ help='if specified, will use public corpora for code coverage',
474
+ default=False,
475
+ action='store_true')
476
+ introspector_parser.add_argument(
477
+ '--private-corpora',
478
+ help='if specified, will use private corpora',
479
+ default=False,
480
+ action='store_true')
481
+
482
+ download_corpora_parser = subparsers.add_parser(
483
+ 'download_corpora', help='Download all corpora for a project.')
484
+ download_corpora_parser.add_argument('--fuzz-target',
485
+ nargs='+',
486
+ help='specify name of a fuzz target')
487
+ download_corpora_parser.add_argument('--public',
488
+ action='store_true',
489
+ help='if set, will download public '
490
+ 'corpus using wget')
491
+ download_corpora_parser.add_argument(
492
+ 'project', help='name of the project or path (external)')
493
+
494
+ reproduce_parser = subparsers.add_parser('reproduce',
495
+ help='Reproduce a crash.')
496
+ reproduce_parser.add_argument('--valgrind',
497
+ action='store_true',
498
+ help='run with valgrind')
499
+ reproduce_parser.add_argument('--propagate_exit_codes',
500
+ action='store_true',
501
+ default=False,
502
+ help='return underlying exit codes instead of True/False.')
503
+ reproduce_parser.add_argument('--not_privileged',
504
+ dest='privileged',
505
+ action='store_false',
506
+ default=True,
507
+ help='reproduce without running docker in privileged mode.')
508
+ reproduce_parser.add_argument('--err_result',
509
+ help='exit code override for missing harness / fuzz targets '
510
+ '(default err_result = 1).',
511
+ type=int)
512
+ reproduce_parser.add_argument('--timeout',
513
+ help='timeout for reproduce subprocess '
514
+ '(default: None).',
515
+ default=None,
516
+ type=int)
517
+ reproduce_parser.add_argument('project',
518
+ help='name of the project or path (external)')
519
+ reproduce_parser.add_argument('fuzzer_name', help='name of the fuzzer')
520
+ reproduce_parser.add_argument('testcase_path', help='path of local testcase')
521
+ reproduce_parser.add_argument('fuzzer_args',
522
+ help='arguments to pass to the fuzzer',
523
+ nargs='*')
524
+ _add_environment_args(reproduce_parser)
525
+ _add_external_project_args(reproduce_parser)
526
+ _add_architecture_args(reproduce_parser)
527
+
528
+ shell_parser = subparsers.add_parser(
529
+ 'shell', help='Run /bin/bash within the builder container.')
530
+ shell_parser.add_argument('project',
531
+ help='name of the project or path (external)')
532
+ shell_parser.add_argument('source_path',
533
+ help='path of local source',
534
+ nargs='?')
535
+ shell_parser.add_argument('--docker_image_tag',
536
+ dest='docker_image_tag',
537
+ default='latest',
538
+ help='docker image build tag'
539
+ 'default: latest')
540
+ _add_architecture_args(shell_parser)
541
+ _add_engine_args(shell_parser)
542
+ _add_sanitizer_args(shell_parser)
543
+ _add_environment_args(shell_parser)
544
+ _add_external_project_args(shell_parser)
545
+
546
+ run_clusterfuzzlite_parser = subparsers.add_parser(
547
+ 'run_clusterfuzzlite', help='Run ClusterFuzzLite on a project.')
548
+ _add_sanitizer_args(run_clusterfuzzlite_parser)
549
+ _add_environment_args(run_clusterfuzzlite_parser)
550
+ run_clusterfuzzlite_parser.add_argument('project')
551
+ run_clusterfuzzlite_parser.add_argument('--clean',
552
+ dest='clean',
553
+ action='store_true',
554
+ help='clean existing artifacts.')
555
+ run_clusterfuzzlite_parser.add_argument(
556
+ '--no-clean',
557
+ dest='clean',
558
+ action='store_false',
559
+ help='do not clean existing artifacts '
560
+ '(default).')
561
+ run_clusterfuzzlite_parser.add_argument('--branch',
562
+ default='master',
563
+ required=True)
564
+ _add_external_project_args(run_clusterfuzzlite_parser)
565
+ run_clusterfuzzlite_parser.set_defaults(clean=False)
566
+
567
+ subparsers.add_parser('pull_images', help='Pull base images.')
568
+ return parser
569
+
570
+
571
+ def is_base_image(image_name):
572
+ """Checks if the image name is a base image."""
573
+ return os.path.exists(os.path.join('infra', 'base-images', image_name))
574
+
575
+
576
+ def check_project_exists(project):
577
+ """Checks if a project exists."""
578
+ if os.path.exists(project.path):
579
+ return True
580
+
581
+ if project.is_external:
582
+ descriptive_project_name = project.path
583
+ else:
584
+ descriptive_project_name = project.name
585
+
586
+ logger.error('"%s" does not exist.', descriptive_project_name)
587
+ return False
588
+
589
+
590
+ def _check_fuzzer_exists(project, fuzzer_name, architecture='x86_64'):
591
+ """Checks if a fuzzer exists."""
592
+ platform = 'linux/arm64' if architecture == 'aarch64' else 'linux/amd64'
593
+ command = ['docker', 'run', '--rm', '--platform', platform]
594
+ command.extend(['-v', '%s:/out' % project.out])
595
+ command.append(BASE_RUNNER_IMAGE)
596
+
597
+ command.extend(['/bin/bash', '-c', 'test -f /out/%s' % fuzzer_name])
598
+
599
+ try:
600
+ subprocess.check_call(command)
601
+ except subprocess.CalledProcessError:
602
+ logger.error('%s does not seem to exist. Please run build_fuzzers first.',
603
+ fuzzer_name)
604
+ return False
605
+
606
+ return True
607
+
608
+
609
+ def _normalized_name(name):
610
+ """Return normalized name with special chars like slash, colon, etc normalized
611
+ to hyphen(-). This is important as otherwise these chars break local and cloud
612
+ storage paths."""
613
+ return SPECIAL_CHARS_REGEX.sub('-', name).strip('-')
614
+
615
+
616
+ def _get_absolute_path(path):
617
+ """Returns absolute path with user expansion."""
618
+ return os.path.abspath(os.path.expanduser(path))
619
+
620
+
621
+ def _get_command_string(command):
622
+ """Returns a shell escaped command string."""
623
+ return ' '.join(shlex.quote(part) for part in command)
624
+
625
+
626
+ def _get_project_build_subdir(project, subdir_name):
627
+ """Creates the |subdir_name| subdirectory of the |project| subdirectory in
628
+ |BUILD_DIR| and returns its path."""
629
+ directory = os.path.join(BUILD_DIR, subdir_name, project)
630
+ os.makedirs(directory, exist_ok=True)
631
+
632
+ return directory
633
+
634
+
635
+ def _get_out_dir(project=''):
636
+ """Creates and returns path to /out directory for the given project (if
637
+ specified)."""
638
+ return _get_project_build_subdir(project, 'out')
639
+
640
+
641
+ def _add_architecture_args(parser, choices=None):
642
+ """Adds common architecture args."""
643
+ if choices is None:
644
+ choices = constants.ARCHITECTURES
645
+ parser.add_argument('--architecture',
646
+ default=constants.DEFAULT_ARCHITECTURE,
647
+ choices=choices)
648
+
649
+
650
+ def _add_engine_args(parser, choices=None):
651
+ """Adds common engine args."""
652
+ if choices is None:
653
+ choices = constants.ENGINES
654
+ parser.add_argument('--engine',
655
+ default=constants.DEFAULT_ENGINE,
656
+ choices=choices)
657
+
658
+
659
+ def _add_sanitizer_args(parser, choices=None):
660
+ """Adds common sanitizer args."""
661
+ if choices is None:
662
+ choices = constants.SANITIZERS
663
+ parser.add_argument('--sanitizer',
664
+ default=None,
665
+ choices=choices,
666
+ help='the default is "address"')
667
+
668
+
669
+ def _add_environment_args(parser):
670
+ """Adds common environment args."""
671
+ parser.add_argument('-e',
672
+ action='append',
673
+ help="set environment variable e.g. VAR=value")
674
+
675
+
676
+ def build_image_impl(project, cache=True, pull=False,
677
+ architecture='x86_64',
678
+ docker_image_tag='latest'):
679
+ """Builds image."""
680
+ image_name = project.name
681
+
682
+ if is_base_image(image_name):
683
+ image_project = 'aixcc-finals'
684
+ docker_build_dir = os.path.join(OSS_FUZZ_DIR, 'infra', 'base-images',
685
+ image_name)
686
+ dockerfile_path = os.path.join(docker_build_dir, 'Dockerfile')
687
+ image_name = 'ghcr.io/%s/%s%s' % (image_project, image_name, BASE_IMAGE_TAG)
688
+ else:
689
+ if not check_project_exists(project):
690
+ return False
691
+ dockerfile_path = project.dockerfile_path
692
+ docker_build_dir = project.path
693
+ image_project = 'aixcc-afc'
694
+ image_name = '%s/%s:%s' % (image_project, image_name, docker_image_tag)
695
+
696
+ if pull and not pull_images(project.language):
697
+ return False
698
+
699
+ build_args = []
700
+ if architecture == 'aarch64':
701
+ build_args += [
702
+ 'buildx',
703
+ 'build',
704
+ '--platform',
705
+ 'linux/arm64',
706
+ '--progress',
707
+ 'plain',
708
+ '--load',
709
+ ]
710
+ if not cache:
711
+ build_args.append('--no-cache')
712
+
713
+ build_args += ['-t', image_name, '--file', dockerfile_path]
714
+ build_args.append(docker_build_dir)
715
+
716
+ if architecture == 'aarch64':
717
+ command = ['docker'] + build_args
718
+ subprocess.check_call(command)
719
+ return True
720
+ return docker_build(build_args)
721
+
722
+
723
+ def _env_to_docker_args(env_list):
724
+ """Turns envirnoment variable list into docker arguments."""
725
+ return sum([['-e', v] for v in env_list], [])
726
+
727
+
728
+ def workdir_from_lines(lines, default='/src'):
729
+ """Gets the WORKDIR from the given lines."""
730
+ for line in reversed(lines): # reversed to get last WORKDIR.
731
+ match = re.match(WORKDIR_REGEX, line)
732
+ if match:
733
+ workdir = match.group(1)
734
+ workdir = workdir.replace('$SRC', '/src')
735
+
736
+ if not os.path.isabs(workdir):
737
+ workdir = os.path.join('/src', workdir)
738
+
739
+ return os.path.normpath(workdir)
740
+
741
+ return default
742
+
743
+
744
+ def _workdir_from_dockerfile(project):
745
+ """Parses WORKDIR from the Dockerfile for the given project."""
746
+ with open(project.dockerfile_path) as file_handle:
747
+ lines = file_handle.readlines()
748
+
749
+ return workdir_from_lines(lines, default=os.path.join('/src', project.name))
750
+
751
+
752
+ def prepare_aarch64_emulation():
753
+ """Run some necessary commands to use buildx to build AArch64 targets using
754
+ QEMU emulation on an x86_64 host."""
755
+ subprocess.check_call(
756
+ ['docker', 'buildx', 'create', '--name', ARM_BUILDER_NAME])
757
+ subprocess.check_call(['docker', 'buildx', 'use', ARM_BUILDER_NAME])
758
+
759
+
760
+ def docker_run(run_args, print_output=True, architecture='x86_64', propagate_exit_codes=False, privileged=True, timeout=None):
761
+ """Calls `docker run`."""
762
+ platform = 'linux/arm64' if architecture == 'aarch64' else 'linux/amd64'
763
+
764
+ if privileged:
765
+ command = [
766
+ 'docker', 'run', '--privileged', '--shm-size=2g', '--platform', platform
767
+ ]
768
+ else:
769
+ command = [
770
+ 'docker', 'run', '--shm-size=2g', '--platform', platform
771
+ ]
772
+
773
+ if os.getenv('OSS_FUZZ_SAVE_CONTAINERS_NAME'):
774
+ command.append('--name')
775
+ command.append(os.getenv('OSS_FUZZ_SAVE_CONTAINERS_NAME'))
776
+ else:
777
+ command.append('--rm')
778
+
779
+ # Support environments with a TTY.
780
+ if sys.stdin.isatty():
781
+ command.append('-i')
782
+
783
+ command.extend(run_args)
784
+
785
+ logger.info('Running: %s.', _get_command_string(command))
786
+ stdout = None
787
+ if not print_output:
788
+ stdout = open(os.devnull, 'w')
789
+
790
+ exit_code = 0
791
+
792
+ try:
793
+ subprocess.check_call(command, stdout=stdout, stderr=subprocess.STDOUT,
794
+ timeout=timeout)
795
+ except subprocess.CalledProcessError as e:
796
+ print(f'subprocess command returned a non-zero exit status: {e.returncode}')
797
+ exit_code = e.returncode
798
+ except subprocess.TimeoutExpired:
799
+ print(f'subprocess command timed out: {timeout=}')
800
+ exit_code = 124
801
+
802
+ return exit_code if propagate_exit_codes else exit_code == 0
803
+
804
+
805
+ def docker_build(build_args):
806
+ """Calls `docker build`."""
807
+ command = ['docker', 'build']
808
+ command.extend(build_args)
809
+ logger.info('Running: %s.', _get_command_string(command))
810
+
811
+ try:
812
+ subprocess.check_call(command)
813
+ except subprocess.CalledProcessError:
814
+ logger.error('Docker build failed.')
815
+ return False
816
+
817
+ return True
818
+
819
+
820
+ def docker_pull(image):
821
+ """Call `docker pull`."""
822
+ command = ['docker', 'pull', image]
823
+ logger.info('Running: %s', _get_command_string(command))
824
+
825
+ try:
826
+ subprocess.check_call(command)
827
+ except subprocess.CalledProcessError:
828
+ logger.error('Docker pull failed.')
829
+ return False
830
+
831
+ return True
832
+
833
+
834
+ def build_image(args):
835
+ """Builds docker image."""
836
+ if args.pull and args.no_pull:
837
+ logger.error('Incompatible arguments --pull and --no-pull.')
838
+ return False
839
+
840
+ if args.pull:
841
+ pull = True
842
+ elif args.no_pull:
843
+ pull = False
844
+ else:
845
+ y_or_n = raw_input('Pull latest base images (compiler/runtime)? (y/N): ')
846
+ pull = y_or_n.lower() == 'y'
847
+
848
+ if pull:
849
+ logger.info('Pulling latest base images...')
850
+ else:
851
+ logger.info('Using cached base images...')
852
+
853
+ # If build_image is called explicitly, don't use cache.
854
+ if build_image_impl(args.project,
855
+ cache=args.cache,
856
+ pull=pull,
857
+ architecture=args.architecture,
858
+ docker_image_tag=args.docker_image_tag):
859
+ return True
860
+
861
+ return False
862
+
863
+
864
+ def build_fuzzers_impl( # pylint: disable=too-many-arguments,too-many-locals,too-many-branches
865
+ project,
866
+ clean,
867
+ engine,
868
+ sanitizer,
869
+ architecture,
870
+ env_to_add,
871
+ source_path,
872
+ mount_path=None,
873
+ child_dir='',
874
+ build_project_image=True,
875
+ docker_image_tag='latest'):
876
+ """Builds fuzzers."""
877
+ if build_project_image and not build_image_impl(project,
878
+ architecture=architecture,
879
+ docker_image_tag=docker_image_tag):
880
+ return False
881
+
882
+ docker_image = f'aixcc-afc/{project.name}:{docker_image_tag}'
883
+
884
+ project_out = os.path.join(project.out, child_dir)
885
+ if clean:
886
+ logger.info('Cleaning existing build artifacts.')
887
+
888
+ # Clean old and possibly conflicting artifacts in project's out directory.
889
+ docker_run([
890
+ '-v', f'{project_out}:/out', '-t', f'{docker_image}',
891
+ '/bin/bash', '-c', 'rm -rf /out/*'
892
+ ],
893
+ architecture=architecture)
894
+
895
+ docker_run([
896
+ '-v',
897
+ '%s:/work' % project.work, '-t',
898
+ f'{docker_image}', '/bin/bash', '-c', 'rm -rf /work/*'
899
+ ],
900
+ architecture=architecture)
901
+
902
+ else:
903
+ logger.info('Keeping existing build artifacts as-is (if any).')
904
+ env = [
905
+ 'FUZZING_ENGINE=' + engine,
906
+ 'SANITIZER=' + sanitizer,
907
+ 'ARCHITECTURE=' + architecture,
908
+ 'PROJECT_NAME=' + project.name,
909
+ 'HELPER=True',
910
+ ]
911
+
912
+ _add_oss_fuzz_ci_if_needed(env)
913
+
914
+ if project.language:
915
+ env.append('FUZZING_LANGUAGE=' + project.language)
916
+
917
+ if env_to_add:
918
+ env += env_to_add
919
+
920
+ command = _env_to_docker_args(env)
921
+ if source_path:
922
+ workdir = _workdir_from_dockerfile(project)
923
+ stateless_path = mount_path if mount_path else workdir
924
+
925
+ if stateless_path == '/src':
926
+ logger.error('Cannot mount local source targeting "/src".')
927
+ return False
928
+
929
+ command += [
930
+ '-v',
931
+ '%s:%s:ro' % (_get_absolute_path(source_path), '/local-source-mount'),
932
+ ]
933
+
934
+ command += [
935
+ '-v', f'{project_out}:/out', '-v', f'{project.work}:/work',
936
+ f'{docker_image}'
937
+ ]
938
+
939
+ if sys.stdin.isatty():
940
+ command.insert(-1, '-t')
941
+
942
+ if source_path:
943
+ default_cmd = 'compile'
944
+ command += [
945
+ '/bin/bash',
946
+ '-c',
947
+ f'pushd $SRC && rm -rf {stateless_path} && cp -r /local-source-mount {stateless_path} && popd && {default_cmd}'
948
+ ]
949
+
950
+ result = docker_run(command, architecture=architecture)
951
+ if not result:
952
+ logger.error('Building fuzzers failed.')
953
+ return False
954
+
955
+ return True
956
+
957
+
958
+ def run_clusterfuzzlite(args):
959
+ """Runs ClusterFuzzLite on a local repo."""
960
+ if not os.path.exists(CLUSTERFUZZLITE_FILESTORE_DIR):
961
+ os.mkdir(CLUSTERFUZZLITE_FILESTORE_DIR)
962
+
963
+ try:
964
+ with tempfile.TemporaryDirectory() as workspace:
965
+
966
+ if args.external:
967
+ project_src_path = os.path.join(workspace, args.project.name)
968
+ shutil.copytree(args.project.path, project_src_path)
969
+
970
+ build_command = [
971
+ '--tag', 'ghcr.io/aixcc-finals/cifuzz-run-fuzzers', '--file',
972
+ 'infra/run_fuzzers.Dockerfile', 'infra'
973
+ ]
974
+ if not docker_build(build_command):
975
+ return False
976
+ filestore_path = os.path.abspath(CLUSTERFUZZLITE_FILESTORE_DIR)
977
+ docker_run_command = []
978
+ if args.external:
979
+ docker_run_command += [
980
+ '-e',
981
+ f'PROJECT_SRC_PATH={project_src_path}',
982
+ ]
983
+ else:
984
+ docker_run_command += [
985
+ '-e',
986
+ f'OSS_FUZZ_PROJECT_NAME={args.project.name}',
987
+ ]
988
+ docker_run_command += [
989
+ '-v',
990
+ f'{filestore_path}:{filestore_path}',
991
+ '-v',
992
+ f'{workspace}:{workspace}',
993
+ '-e',
994
+ f'FILESTORE_ROOT_DIR={filestore_path}',
995
+ '-e',
996
+ f'WORKSPACE={workspace}',
997
+ '-e',
998
+ f'REPOSITORY={args.project.name}',
999
+ '-e',
1000
+ 'CFL_PLATFORM=standalone',
1001
+ '--entrypoint',
1002
+ '',
1003
+ '-v',
1004
+ '/var/run/docker.sock:/var/run/docker.sock',
1005
+ CLUSTERFUZZLITE_DOCKER_IMAGE,
1006
+ 'python3',
1007
+ '/opt/oss-fuzz/infra/cifuzz/cifuzz_combined_entrypoint.py',
1008
+ ]
1009
+ return docker_run(docker_run_command)
1010
+
1011
+ except PermissionError as error:
1012
+ logger.error('PermissionError: %s.', error)
1013
+ # Tempfile can't delete the workspace because of a permissions issue. This
1014
+ # is because docker creates files in the workspace that are owned by root
1015
+ # but this process is probably being run as another user. Use a docker image
1016
+ # to delete the temp directory (workspace) so that we have permission.
1017
+ docker_run([
1018
+ '-v', f'{workspace}:{workspace}', '--entrypoint', '',
1019
+ CLUSTERFUZZLITE_DOCKER_IMAGE, 'rm', '-rf',
1020
+ os.path.join(workspace, '*')
1021
+ ])
1022
+ return False
1023
+
1024
+
1025
+ def build_fuzzers(args):
1026
+ """Builds fuzzers."""
1027
+ if args.engine == 'centipede' and args.sanitizer != 'none':
1028
+ # Centipede always requires separate binaries for sanitizers:
1029
+ # An unsanitized binary, which Centipede requires for fuzzing.
1030
+ # A sanitized binary, placed in the child directory.
1031
+ sanitized_binary_directories = (
1032
+ ('none', ''),
1033
+ (args.sanitizer, f'__centipede_{args.sanitizer}'),
1034
+ )
1035
+ else:
1036
+ # Generally, a fuzzer only needs one sanitized binary in the default dir.
1037
+ sanitized_binary_directories = ((args.sanitizer, ''),)
1038
+ return all(
1039
+ build_fuzzers_impl(args.project,
1040
+ args.clean,
1041
+ args.engine,
1042
+ sanitizer,
1043
+ args.architecture,
1044
+ args.e,
1045
+ args.source_path,
1046
+ mount_path=args.mount_path,
1047
+ child_dir=child_dir,
1048
+ docker_image_tag=args.docker_image_tag)
1049
+ for sanitizer, child_dir in sanitized_binary_directories)
1050
+
1051
+
1052
+ def fuzzbench_build_fuzzers(args):
1053
+ """Builds fuzz targets with an arbitrary fuzzer from FuzzBench."""
1054
+ with tempfile.TemporaryDirectory() as tmp_dir:
1055
+ tmp_dir = os.path.abspath(tmp_dir)
1056
+ fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench')
1057
+ subprocess.run([
1058
+ 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1',
1059
+ fuzzbench_path
1060
+ ],
1061
+ check=True)
1062
+ env = [
1063
+ f'FUZZBENCH_PATH={fuzzbench_path}', 'OSS_FUZZ_ON_DEMAND=1',
1064
+ f'PROJECT={args.project.name}'
1065
+ ]
1066
+ tag = f'aixcc-afc/{args.project.name}'
1067
+ subprocess.run([
1068
+ 'docker', 'tag', 'ghcr.io/aixcc-finals/base-builder-fuzzbench',
1069
+ f'ghcr.io/aixcc-finals/base-builder{BASE_IMAGE_TAG}'
1070
+ ],
1071
+ check=True)
1072
+ build_image_impl(args.project)
1073
+ assert docker_build([
1074
+ '--tag', tag, '--build-arg', f'parent_image={tag}', '--file',
1075
+ os.path.join(fuzzbench_path, 'fuzzers', args.engine,
1076
+ 'builder.Dockerfile'),
1077
+ os.path.join(fuzzbench_path, 'fuzzers', args.engine)
1078
+ ])
1079
+
1080
+ return build_fuzzers_impl(args.project,
1081
+ False,
1082
+ args.engine,
1083
+ args.sanitizer,
1084
+ args.architecture,
1085
+ env,
1086
+ source_path=fuzzbench_path,
1087
+ mount_path=fuzzbench_path,
1088
+ build_project_image=False)
1089
+
1090
+
1091
+ def _add_oss_fuzz_ci_if_needed(env):
1092
+ """Adds value of |OSS_FUZZ_CI| environment variable to |env| if it is set."""
1093
+ oss_fuzz_ci = os.getenv('OSS_FUZZ_CI')
1094
+ if oss_fuzz_ci:
1095
+ env.append('OSS_FUZZ_CI=' + oss_fuzz_ci)
1096
+
1097
+
1098
+ def check_build(args):
1099
+ """Checks that fuzzers in the container execute without errors."""
1100
+ if not check_project_exists(args.project):
1101
+ return False
1102
+
1103
+ if (args.fuzzer_name and not _check_fuzzer_exists(
1104
+ args.project, args.fuzzer_name, args.architecture)):
1105
+ return False
1106
+
1107
+ env = [
1108
+ 'FUZZING_ENGINE=' + args.engine,
1109
+ 'SANITIZER=' + args.sanitizer,
1110
+ 'ARCHITECTURE=' + args.architecture,
1111
+ 'FUZZING_LANGUAGE=' + args.project.language,
1112
+ 'HELPER=True',
1113
+ ]
1114
+ _add_oss_fuzz_ci_if_needed(env)
1115
+ if args.e:
1116
+ env += args.e
1117
+
1118
+ run_args = _env_to_docker_args(env) + [
1119
+ '-v', f'{args.project.out}:/out', '-t', BASE_RUNNER_IMAGE
1120
+ ]
1121
+
1122
+ if args.fuzzer_name:
1123
+ run_args += ['test_one.py', args.fuzzer_name]
1124
+ else:
1125
+ run_args.append('test_all.py')
1126
+
1127
+ result = docker_run(run_args, architecture=args.architecture)
1128
+ if result:
1129
+ logger.info('Check build passed.')
1130
+ else:
1131
+ logger.error('Check build failed.')
1132
+
1133
+ return result
1134
+
1135
+
1136
+ def _get_fuzz_targets(project):
1137
+ """Returns names of fuzz targest build in the project's /out directory."""
1138
+ fuzz_targets = []
1139
+ for name in os.listdir(project.out):
1140
+ if name.startswith('afl-'):
1141
+ continue
1142
+ if name == 'centipede':
1143
+ continue
1144
+ if name.startswith('jazzer_'):
1145
+ continue
1146
+ if name == 'llvm-symbolizer':
1147
+ continue
1148
+
1149
+ path = os.path.join(project.out, name)
1150
+ # Python and JVM fuzz targets are only executable for the root user, so
1151
+ # we can't use os.access.
1152
+ if os.path.isfile(path) and (os.stat(path).st_mode & 0o111):
1153
+ fuzz_targets.append(name)
1154
+
1155
+ return fuzz_targets
1156
+
1157
+
1158
+ def _get_latest_corpus(project, fuzz_target, base_corpus_dir):
1159
+ """Downloads the latest corpus for the given fuzz target."""
1160
+ corpus_dir = os.path.join(base_corpus_dir, fuzz_target)
1161
+ os.makedirs(corpus_dir, exist_ok=True)
1162
+
1163
+ if not fuzz_target.startswith(project.name + '_'):
1164
+ fuzz_target = '%s_%s' % (project.name, fuzz_target)
1165
+
1166
+ # Normalise fuzz target name.
1167
+ fuzz_target = _normalized_name(fuzz_target)
1168
+
1169
+ corpus_backup_url = CORPUS_BACKUP_URL_FORMAT.format(project_name=project.name,
1170
+ fuzz_target=fuzz_target)
1171
+ command = ['gsutil', 'ls', corpus_backup_url]
1172
+
1173
+ # Don't capture stderr. We want it to print in real time, in case gsutil is
1174
+ # asking for two-factor authentication.
1175
+ corpus_listing = subprocess.Popen(command, stdout=subprocess.PIPE)
1176
+ output, _ = corpus_listing.communicate()
1177
+
1178
+ # Some fuzz targets (e.g. new ones) may not have corpus yet, just skip those.
1179
+ if corpus_listing.returncode:
1180
+ logger.warning('Corpus for %s not found:\n', fuzz_target)
1181
+ return
1182
+
1183
+ if output:
1184
+ latest_backup_url = output.splitlines()[-1]
1185
+ archive_path = corpus_dir + '.zip'
1186
+ command = ['gsutil', '-q', 'cp', latest_backup_url, archive_path]
1187
+ subprocess.check_call(command)
1188
+
1189
+ command = ['unzip', '-q', '-o', archive_path, '-d', corpus_dir]
1190
+ subprocess.check_call(command)
1191
+ os.remove(archive_path)
1192
+ else:
1193
+ # Sync the working corpus copy if a minimized backup is not available.
1194
+ corpus_url = CORPUS_URL_FORMAT.format(project_name=project.name,
1195
+ fuzz_target=fuzz_target)
1196
+ command = ['gsutil', '-m', '-q', 'rsync', '-R', corpus_url, corpus_dir]
1197
+ subprocess.check_call(command)
1198
+
1199
+
1200
+ def _get_latest_public_corpus(args, fuzzer):
1201
+ """Downloads the public corpus"""
1202
+ target_corpus_dir = "build/corpus/%s" % args.project.name
1203
+ if not os.path.isdir(target_corpus_dir):
1204
+ os.makedirs(target_corpus_dir)
1205
+
1206
+ target_zip = os.path.join(target_corpus_dir, fuzzer + ".zip")
1207
+
1208
+ project_qualified_fuzz_target_name = fuzzer
1209
+ qualified_name_prefix = args.project.name + '_'
1210
+ if not fuzzer.startswith(qualified_name_prefix):
1211
+ project_qualified_fuzz_target_name = qualified_name_prefix + fuzzer
1212
+
1213
+ download_url = HTTPS_CORPUS_BACKUP_URL_FORMAT.format(
1214
+ project_name=args.project.name,
1215
+ fuzz_target=project_qualified_fuzz_target_name)
1216
+
1217
+ cmd = ['wget', download_url, '-O', target_zip]
1218
+ try:
1219
+ with open(os.devnull, 'w') as stdout:
1220
+ subprocess.check_call(cmd, stdout=stdout)
1221
+ except OSError:
1222
+ logger.error('Failed to download corpus')
1223
+
1224
+ target_fuzzer_dir = os.path.join(target_corpus_dir, fuzzer)
1225
+ if not os.path.isdir(target_fuzzer_dir):
1226
+ os.mkdir(target_fuzzer_dir)
1227
+
1228
+ target_corpus_dir = os.path.join(target_corpus_dir, fuzzer)
1229
+ try:
1230
+ with open(os.devnull, 'w') as stdout:
1231
+ subprocess.check_call(
1232
+ ['unzip', '-q', '-o', target_zip, '-d', target_fuzzer_dir],
1233
+ stdout=stdout)
1234
+ except OSError:
1235
+ logger.error('Failed to unzip corpus')
1236
+
1237
+ # Remove the downloaded zip
1238
+ os.remove(target_zip)
1239
+ return True
1240
+
1241
+
1242
+ def download_corpora(args):
1243
+ """Downloads most recent corpora from GCS for the given project."""
1244
+ if not check_project_exists(args.project):
1245
+ return False
1246
+
1247
+ if args.public:
1248
+ logger.info("Downloading public corpus")
1249
+ try:
1250
+ with open(os.devnull, 'w') as stdout:
1251
+ subprocess.check_call(['wget', '--version'], stdout=stdout)
1252
+ except OSError:
1253
+ logger.error('wget not found')
1254
+ return False
1255
+ else:
1256
+ try:
1257
+ with open(os.devnull, 'w') as stdout:
1258
+ subprocess.check_call(['gsutil', '--version'], stdout=stdout)
1259
+ except OSError:
1260
+ logger.error('gsutil not found. Please install it from '
1261
+ 'https://cloud.google.com/storage/docs/gsutil_install')
1262
+ return False
1263
+
1264
+ if args.fuzz_target:
1265
+ fuzz_targets = args.fuzz_target
1266
+ else:
1267
+ fuzz_targets = _get_fuzz_targets(args.project)
1268
+
1269
+ if not fuzz_targets:
1270
+ logger.error(
1271
+ 'Fuzz targets not found. Please build project first '
1272
+ '(python3 infra/helper.py build_fuzzers %s) so that download_corpora '
1273
+ 'can automatically identify targets.', args.project.name)
1274
+ return False
1275
+
1276
+ corpus_dir = args.project.corpus
1277
+
1278
+ def _download_for_single_target(fuzz_target):
1279
+ try:
1280
+ if args.public:
1281
+ _get_latest_public_corpus(args, fuzz_target)
1282
+ else:
1283
+ _get_latest_corpus(args.project, fuzz_target, corpus_dir)
1284
+ return True
1285
+ except Exception as error: # pylint:disable=broad-except
1286
+ logger.error('Corpus download for %s failed: %s.', fuzz_target,
1287
+ str(error))
1288
+ return False
1289
+
1290
+ logger.info('Downloading corpora for %s project to %s.', args.project.name,
1291
+ corpus_dir)
1292
+ thread_pool = ThreadPool()
1293
+ return all(thread_pool.map(_download_for_single_target, fuzz_targets))
1294
+
1295
+
1296
+ def coverage(args): # pylint: disable=too-many-branches
1297
+ """Generates code coverage using clang source based code coverage."""
1298
+ if args.corpus_dir and not args.fuzz_target:
1299
+ logger.error(
1300
+ '--corpus-dir requires specifying a particular fuzz target using '
1301
+ '--fuzz-target')
1302
+ return False
1303
+
1304
+ if not check_project_exists(args.project):
1305
+ return False
1306
+
1307
+ if args.project.language not in constants.LANGUAGES_WITH_COVERAGE_SUPPORT:
1308
+ logger.error(
1309
+ 'Project is written in %s, coverage for it is not supported yet.',
1310
+ args.project.language)
1311
+ return False
1312
+
1313
+ if (not args.no_corpus_download and not args.corpus_dir and
1314
+ not args.project.is_external):
1315
+ if not download_corpora(args):
1316
+ return False
1317
+
1318
+ extra_cov_args = (
1319
+ f'{args.project.coverage_extra_args.strip()} {" ".join(args.extra_args)}')
1320
+ env = [
1321
+ 'FUZZING_ENGINE=libfuzzer',
1322
+ 'HELPER=True',
1323
+ 'FUZZING_LANGUAGE=%s' % args.project.language,
1324
+ 'PROJECT=%s' % args.project.name,
1325
+ 'SANITIZER=coverage',
1326
+ 'COVERAGE_EXTRA_ARGS=%s' % extra_cov_args,
1327
+ 'ARCHITECTURE=' + args.architecture,
1328
+ ]
1329
+
1330
+ if not args.no_serve:
1331
+ env.append(f'HTTP_PORT={args.port}')
1332
+
1333
+ run_args = _env_to_docker_args(env)
1334
+
1335
+ if args.port:
1336
+ run_args.extend([
1337
+ '-p',
1338
+ '%s:%s' % (args.port, args.port),
1339
+ ])
1340
+
1341
+ if args.corpus_dir:
1342
+ if not os.path.exists(args.corpus_dir):
1343
+ logger.error('The path provided in --corpus-dir argument does not '
1344
+ 'exist.')
1345
+ return False
1346
+ corpus_dir = os.path.realpath(args.corpus_dir)
1347
+ run_args.extend(['-v', '%s:/corpus/%s' % (corpus_dir, args.fuzz_target)])
1348
+ else:
1349
+ run_args.extend(['-v', '%s:/corpus' % args.project.corpus])
1350
+
1351
+ run_args.extend([
1352
+ '-v',
1353
+ '%s:/out' % args.project.out,
1354
+ '-t',
1355
+ BASE_RUNNER_IMAGE,
1356
+ ])
1357
+
1358
+ run_args.append('coverage')
1359
+ if args.fuzz_target:
1360
+ run_args.append(args.fuzz_target)
1361
+
1362
+ result = docker_run(run_args, architecture=args.architecture)
1363
+ if result:
1364
+ logger.info('Successfully generated clang code coverage report.')
1365
+ else:
1366
+ logger.error('Failed to generate clang code coverage report.')
1367
+
1368
+ return result
1369
+
1370
+
1371
+ def _introspector_prepare_corpus(args):
1372
+ """Helper function for introspector runs to generate corpora."""
1373
+ parser = get_parser()
1374
+ # Generate corpus, either by downloading or running fuzzers.
1375
+ if args.private_corpora or args.public_corpora:
1376
+ corpora_command = ['download_corpora']
1377
+ if args.public_corpora:
1378
+ corpora_command.append('--public')
1379
+ corpora_command.append(args.project.name)
1380
+ if not download_corpora(parse_args(parser, corpora_command)):
1381
+ logger.error('Failed to download corpora')
1382
+ return False
1383
+ else:
1384
+ fuzzer_targets = _get_fuzz_targets(args.project)
1385
+ for fuzzer_name in fuzzer_targets:
1386
+ # Make a corpus directory.
1387
+ fuzzer_corpus_dir = args.project.corpus + f'/{fuzzer_name}'
1388
+ if not os.path.isdir(fuzzer_corpus_dir):
1389
+ os.makedirs(fuzzer_corpus_dir)
1390
+ run_fuzzer_command = [
1391
+ 'run_fuzzer', '--sanitizer', 'address', '--corpus-dir',
1392
+ fuzzer_corpus_dir, args.project.name, fuzzer_name
1393
+ ]
1394
+
1395
+ parsed_args = parse_args(parser, run_fuzzer_command)
1396
+ parsed_args.fuzzer_args = [
1397
+ f'-max_total_time={args.seconds}', '-detect_leaks=0'
1398
+ ]
1399
+ # Continue even if run command fails, because we do not have 100%
1400
+ # accuracy in fuzz target detection, i.e. we might try to run something
1401
+ # that is not a target.
1402
+ run_fuzzer(parsed_args)
1403
+ return True
1404
+
1405
+
1406
+ def introspector(args):
1407
+ """Runs a complete end-to-end run of introspector."""
1408
+ parser = get_parser()
1409
+
1410
+ args_to_append = []
1411
+ if args.source_path:
1412
+ args_to_append.append(_get_absolute_path(args.source_path))
1413
+
1414
+ # Build fuzzers with ASAN.
1415
+ build_fuzzers_command = [
1416
+ 'build_fuzzers', '--sanitizer=address', args.project.name
1417
+ ] + args_to_append
1418
+ if not build_fuzzers(parse_args(parser, build_fuzzers_command)):
1419
+ logger.error('Failed to build project with ASAN')
1420
+ return False
1421
+
1422
+ if not _introspector_prepare_corpus(args):
1423
+ return False
1424
+
1425
+ # Build code coverage.
1426
+ build_fuzzers_command = [
1427
+ 'build_fuzzers', '--sanitizer=coverage', args.project.name
1428
+ ] + args_to_append
1429
+ if not build_fuzzers(parse_args(parser, build_fuzzers_command)):
1430
+ logger.error('Failed to build project with coverage instrumentation')
1431
+ return False
1432
+
1433
+ # Collect coverage.
1434
+ coverage_command = [
1435
+ 'coverage', '--no-corpus-download', '--port', '', args.project.name
1436
+ ]
1437
+ if not coverage(parse_args(parser, coverage_command)):
1438
+ logger.error('Failed to extract coverage')
1439
+ return False
1440
+
1441
+ # Build introspector.
1442
+ build_fuzzers_command = [
1443
+ 'build_fuzzers', '--sanitizer=introspector', args.project.name
1444
+ ] + args_to_append
1445
+ if not build_fuzzers(parse_args(parser, build_fuzzers_command)):
1446
+ logger.error('Failed to build project with introspector')
1447
+ return False
1448
+
1449
+ introspector_dst = os.path.join(args.project.out,
1450
+ "introspector-report/inspector")
1451
+ shutil.rmtree(introspector_dst, ignore_errors=True)
1452
+ shutil.copytree(os.path.join(args.project.out, "inspector"), introspector_dst)
1453
+
1454
+ # Copy the coverage reports into the introspector report.
1455
+ dst_cov_report = os.path.join(introspector_dst, "covreport")
1456
+ shutil.copytree(os.path.join(args.project.out, "report"), dst_cov_report)
1457
+
1458
+ # Copy per-target coverage reports
1459
+ src_target_cov_report = os.path.join(args.project.out, "report_target")
1460
+ for target_cov_dir in os.listdir(src_target_cov_report):
1461
+ dst_target_cov_report = os.path.join(dst_cov_report, target_cov_dir)
1462
+ shutil.copytree(os.path.join(src_target_cov_report, target_cov_dir),
1463
+ dst_target_cov_report)
1464
+
1465
+ logger.info('Introspector run complete. Report in %s', introspector_dst)
1466
+ logger.info(
1467
+ 'To browse the report, run: `python3 -m http.server 8008 --directory %s`'
1468
+ 'and navigate to localhost:8008/fuzz_report.html in your browser',
1469
+ introspector_dst)
1470
+ return True
1471
+
1472
+
1473
+ def run_fuzzer(args):
1474
+ """Runs a fuzzer in the container."""
1475
+ if not check_project_exists(args.project):
1476
+ return False
1477
+
1478
+ if not _check_fuzzer_exists(args.project, args.fuzzer_name,
1479
+ args.architecture):
1480
+ return False
1481
+
1482
+ env = [
1483
+ 'FUZZING_ENGINE=' + args.engine,
1484
+ 'SANITIZER=' + args.sanitizer,
1485
+ 'RUN_FUZZER_MODE=interactive',
1486
+ 'HELPER=True',
1487
+ ]
1488
+
1489
+ if args.e:
1490
+ env += args.e
1491
+
1492
+ run_args = _env_to_docker_args(env)
1493
+
1494
+ if args.corpus_dir:
1495
+ if not os.path.exists(args.corpus_dir):
1496
+ logger.error('The path provided in --corpus-dir argument does not exist')
1497
+ return False
1498
+ corpus_dir = os.path.realpath(args.corpus_dir)
1499
+ run_args.extend([
1500
+ '-v',
1501
+ '{corpus_dir}:/tmp/{fuzzer}_corpus'.format(corpus_dir=corpus_dir,
1502
+ fuzzer=args.fuzzer_name)
1503
+ ])
1504
+
1505
+ run_args.extend([
1506
+ '-v',
1507
+ '%s:/out' % args.project.out,
1508
+ '-t',
1509
+ BASE_RUNNER_IMAGE,
1510
+ 'run_fuzzer',
1511
+ args.fuzzer_name,
1512
+ ] + args.fuzzer_args)
1513
+
1514
+ return docker_run(run_args, architecture=args.architecture)
1515
+
1516
+
1517
+ def fuzzbench_run_fuzzer(args):
1518
+ """Runs a fuzz target built by fuzzbench in the container."""
1519
+ if not check_project_exists(args.project):
1520
+ return False
1521
+
1522
+ env = [
1523
+ 'FUZZING_ENGINE=' + args.engine,
1524
+ 'SANITIZER=' + args.sanitizer,
1525
+ 'RUN_FUZZER_MODE=interactive',
1526
+ 'HELPER=True',
1527
+ f'FUZZ_TARGET={args.fuzzer_name}',
1528
+ f'BENCHMARK={args.project.name}',
1529
+ 'TRIAL_ID=1',
1530
+ 'EXPERIMENT_TYPE=bug',
1531
+ ]
1532
+
1533
+ if args.e:
1534
+ env += args.e
1535
+
1536
+ run_args = _env_to_docker_args(env)
1537
+
1538
+ if args.corpus_dir:
1539
+ if not os.path.exists(args.corpus_dir):
1540
+ logger.error('The path provided in --corpus-dir argument does not exist')
1541
+ return False
1542
+ corpus_dir = os.path.realpath(args.corpus_dir)
1543
+ run_args.extend([
1544
+ '-v',
1545
+ '{corpus_dir}:/tmp/{fuzzer}_corpus'.format(corpus_dir=corpus_dir,
1546
+ fuzzer=args.fuzzer_name)
1547
+ ])
1548
+
1549
+ with tempfile.TemporaryDirectory() as tmp_dir:
1550
+ tmp_dir = os.path.abspath(tmp_dir)
1551
+ fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench')
1552
+ subprocess.run([
1553
+ 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1',
1554
+ fuzzbench_path
1555
+ ],
1556
+ check=True)
1557
+ run_args.extend([
1558
+ '-v',
1559
+ f'{args.project.out}:/out',
1560
+ '-v',
1561
+ f'{fuzzbench_path}:{fuzzbench_path}',
1562
+ '-e',
1563
+ f'FUZZBENCH_PATH={fuzzbench_path}',
1564
+ f'aixcc-afc/{args.project.name}',
1565
+ 'fuzzbench_run_fuzzer',
1566
+ args.fuzzer_name,
1567
+ ] + args.fuzzer_args)
1568
+
1569
+ return docker_run(run_args, architecture=args.architecture)
1570
+
1571
+
1572
+ def fuzzbench_measure(args):
1573
+ """Measure results from fuzzing with fuzzbench."""
1574
+ if not check_project_exists(args.project):
1575
+ return False
1576
+
1577
+ with tempfile.TemporaryDirectory() as tmp_dir:
1578
+ tmp_dir = os.path.abspath(tmp_dir)
1579
+ fuzzbench_path = os.path.join(tmp_dir, 'fuzzbench')
1580
+ subprocess.run([
1581
+ 'git', 'clone', 'https://github.com/google/fuzzbench', '--depth', '1',
1582
+ fuzzbench_path
1583
+ ],
1584
+ check=True)
1585
+ run_args = [
1586
+ '-v', f'{args.project.out}:/out', '-v',
1587
+ f'{fuzzbench_path}:{fuzzbench_path}', '-e',
1588
+ f'FUZZBENCH_PATH={fuzzbench_path}', '-e', 'EXPERIMENT_TYPE=bug', '-e',
1589
+ f'FUZZ_TARGET={args.fuzz_target_name}', '-e',
1590
+ f'FUZZER={args.engine_name}', '-e', f'BENCHMARK={args.project.name}',
1591
+ f'aixcc-afc/{args.project.name}', 'fuzzbench_measure'
1592
+ ]
1593
+
1594
+ return docker_run(run_args, 'x86_64')
1595
+
1596
+
1597
+ def reproduce(args):
1598
+ """Reproduces a specific test case from a specific project."""
1599
+ return reproduce_impl(args.project, args.fuzzer_name, args.valgrind, args.e,
1600
+ args.fuzzer_args, args.testcase_path, args.architecture,
1601
+ args.propagate_exit_codes, args.err_result,
1602
+ privileged=args.privileged, timeout=args.timeout)
1603
+
1604
+
1605
+ def reproduce_impl( # pylint: disable=too-many-arguments
1606
+ project,
1607
+ fuzzer_name,
1608
+ valgrind,
1609
+ env_to_add,
1610
+ fuzzer_args,
1611
+ testcase_path,
1612
+ architecture='x86_64',
1613
+ propagate_exit_codes=False,
1614
+ err_result=1,
1615
+ run_function=docker_run,
1616
+ privileged=True,
1617
+ timeout=None):
1618
+ """Reproduces a testcase in the container."""
1619
+
1620
+ if not check_project_exists(project):
1621
+ return err_result if propagate_exit_codes else False
1622
+
1623
+ if not _check_fuzzer_exists(project, fuzzer_name, architecture):
1624
+ return err_result if propagate_exit_codes else False
1625
+
1626
+ debugger = ''
1627
+ env = ['HELPER=True', 'ARCHITECTURE=' + architecture]
1628
+ image_name = 'base-runner'
1629
+
1630
+ if valgrind:
1631
+ debugger = 'valgrind --tool=memcheck --track-origins=yes --leak-check=full'
1632
+
1633
+ if debugger:
1634
+ image_name = 'base-runner-debug'
1635
+ env += ['DEBUGGER=' + debugger]
1636
+
1637
+ if env_to_add:
1638
+ env += env_to_add
1639
+
1640
+ run_args = _env_to_docker_args(env) + [
1641
+ '-v',
1642
+ '%s:/out' % project.out,
1643
+ '-v',
1644
+ '%s:/testcase' % _get_absolute_path(testcase_path),
1645
+ '-t',
1646
+ 'ghcr.io/aixcc-finals/%s%s' % (image_name, BASE_IMAGE_TAG),
1647
+ 'reproduce',
1648
+ fuzzer_name,
1649
+ '-runs=100',
1650
+ ] + fuzzer_args
1651
+
1652
+ return run_function(run_args, architecture=architecture, propagate_exit_codes=propagate_exit_codes, privileged=privileged, timeout=timeout)
1653
+
1654
+
1655
+ def _validate_project_name(project_name):
1656
+ """Validates |project_name| is a valid OSS-Fuzz project name."""
1657
+ if len(project_name) > MAX_PROJECT_NAME_LENGTH:
1658
+ logger.error(
1659
+ 'Project name needs to be less than or equal to %d characters.',
1660
+ MAX_PROJECT_NAME_LENGTH)
1661
+ return False
1662
+
1663
+ if not VALID_PROJECT_NAME_REGEX.match(project_name):
1664
+ logger.info('Invalid project name: %s.', project_name)
1665
+ return False
1666
+
1667
+ return True
1668
+
1669
+
1670
+ def _validate_language(language):
1671
+ if not LANGUAGE_REGEX.match(language):
1672
+ logger.error('Invalid project language %s.', language)
1673
+ return False
1674
+
1675
+ return True
1676
+
1677
+
1678
+ def _create_build_integration_directory(directory):
1679
+ """Returns True on successful creation of a build integration directory.
1680
+ Suitable for OSS-Fuzz and external projects."""
1681
+ try:
1682
+ os.makedirs(directory)
1683
+ except OSError as error:
1684
+ if error.errno != errno.EEXIST:
1685
+ raise
1686
+ logger.error('%s already exists.', directory)
1687
+ return False
1688
+ return True
1689
+
1690
+
1691
+ def _template_project_file(filename, template, template_args, directory):
1692
+ """Templates |template| using |template_args| and writes the result to
1693
+ |directory|/|filename|. Sets the file to executable if |filename| is
1694
+ build.sh."""
1695
+ file_path = os.path.join(directory, filename)
1696
+ with open(file_path, 'w') as file_handle:
1697
+ file_handle.write(template % template_args)
1698
+
1699
+ if filename == 'build.sh':
1700
+ os.chmod(file_path, 0o755)
1701
+
1702
+
1703
+ def generate(args):
1704
+ """Generates empty project files."""
1705
+ return _generate_impl(args.project, args.language)
1706
+
1707
+
1708
+ def _get_current_datetime():
1709
+ """Returns this year. Needed for mocking."""
1710
+ return datetime.datetime.now()
1711
+
1712
+
1713
+ def _base_builder_from_language(language):
1714
+ """Returns the base builder for the specified language."""
1715
+ return LANGUAGE_TO_BASE_BUILDER_IMAGE[language]
1716
+
1717
+
1718
+ def _generate_impl(project, language):
1719
+ """Implementation of generate(). Useful for testing."""
1720
+ if project.is_external:
1721
+ # External project.
1722
+ project_templates = templates.EXTERNAL_TEMPLATES
1723
+ else:
1724
+ # Internal project.
1725
+ if not _validate_project_name(project.name):
1726
+ return False
1727
+ project_templates = templates.TEMPLATES
1728
+
1729
+ if not _validate_language(language):
1730
+ return False
1731
+
1732
+ directory = project.build_integration_path
1733
+ if not _create_build_integration_directory(directory):
1734
+ return False
1735
+
1736
+ logger.info('Writing new files to: %s.', directory)
1737
+
1738
+ template_args = {
1739
+ 'project_name': project.name,
1740
+ 'base_builder': _base_builder_from_language(language),
1741
+ 'language': language,
1742
+ 'year': _get_current_datetime().year
1743
+ }
1744
+ for filename, template in project_templates.items():
1745
+ _template_project_file(filename, template, template_args, directory)
1746
+ return True
1747
+
1748
+
1749
+ def shell(args):
1750
+ """Runs a shell within a docker image."""
1751
+ if not build_image_impl(args.project):
1752
+ return False
1753
+
1754
+ env = [
1755
+ 'FUZZING_ENGINE=' + args.engine,
1756
+ 'SANITIZER=' + args.sanitizer,
1757
+ 'ARCHITECTURE=' + args.architecture,
1758
+ 'HELPER=True',
1759
+ ]
1760
+
1761
+ if args.project.name != 'base-runner-debug':
1762
+ env.append('FUZZING_LANGUAGE=' + args.project.language)
1763
+
1764
+ if args.e:
1765
+ env += args.e
1766
+
1767
+ if is_base_image(args.project.name):
1768
+ image_project = 'aixcc-finals'
1769
+ project_full = 'ghcr.io/%s/%s%s' % (image_project, args.project.name, BASE_IMAGE_TAG)
1770
+ out_dir = _get_out_dir()
1771
+ else:
1772
+ image_project = 'aixcc-afc'
1773
+ project_full = '%s/%s:%s' % (image_project, args.project.name, args.docker_image_tag)
1774
+ out_dir = args.project.out
1775
+
1776
+ run_args = _env_to_docker_args(env)
1777
+ if args.source_path:
1778
+ workdir = _workdir_from_dockerfile(args.project)
1779
+ run_args.extend([
1780
+ '-v',
1781
+ '%s:%s' % (_get_absolute_path(args.source_path), workdir),
1782
+ ])
1783
+
1784
+
1785
+ run_args.extend([
1786
+ '-v',
1787
+ '%s:/out' % out_dir, '-v',
1788
+ '%s:/work' % args.project.work, '-t',
1789
+ '%s' % (project_full), '/bin/bash'
1790
+ ])
1791
+
1792
+ docker_run(run_args, architecture=args.architecture)
1793
+ return True
1794
+
1795
+
1796
+ def pull_images(language=None):
1797
+ """Pulls base images used to build projects in language lang (or all if lang
1798
+ is None)."""
1799
+ for base_image_lang, base_images in BASE_IMAGES.items():
1800
+ if (language is None or base_image_lang == 'generic' or
1801
+ base_image_lang == language):
1802
+ for base_image in base_images:
1803
+ if not docker_pull(base_image):
1804
+ return False
1805
+
1806
+ return True
1807
+
1808
+
1809
+ if __name__ == '__main__':
1810
+ sys.exit(main())
local-test-commons-compress-delta-02/fuzz-tooling/infra/helper_test.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 helper.py"""
15
+
16
+ import datetime
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+ from unittest import mock
21
+
22
+ from pyfakefs import fake_filesystem_unittest
23
+
24
+ import constants
25
+ import helper
26
+ import templates
27
+
28
+ # pylint: disable=no-self-use,protected-access
29
+
30
+
31
+ class ShellTest(unittest.TestCase):
32
+ """Tests 'shell' command."""
33
+
34
+ @mock.patch('helper.docker_run')
35
+ @mock.patch('helper.build_image_impl')
36
+ def test_base_runner_debug(self, _, __):
37
+ """Tests that shell base-runner-debug works as intended."""
38
+ image_name = 'base-runner-debug'
39
+ unparsed_args = ['shell', image_name]
40
+ parser = helper.get_parser()
41
+ args = helper.parse_args(parser, unparsed_args)
42
+ args.sanitizer = 'address'
43
+ result = helper.shell(args)
44
+ self.assertTrue(result)
45
+
46
+
47
+ class BuildImageImplTest(unittest.TestCase):
48
+ """Tests for build_image_impl."""
49
+
50
+ @mock.patch('helper.docker_build')
51
+ def test_no_cache(self, mock_docker_build):
52
+ """Tests that cache=False is handled properly."""
53
+ image_name = 'base-image'
54
+ helper.build_image_impl(helper.Project(image_name), cache=False)
55
+ self.assertIn('--no-cache', mock_docker_build.call_args_list[0][0][0])
56
+
57
+ @mock.patch('helper.docker_build')
58
+ @mock.patch('helper.pull_images')
59
+ def test_pull(self, mock_pull_images, _):
60
+ """Tests that pull=True is handled properly."""
61
+ image_name = 'base-image'
62
+ project = helper.Project(image_name, is_external=True)
63
+ self.assertTrue(helper.build_image_impl(project, pull=True))
64
+ mock_pull_images.assert_called_with('c++')
65
+
66
+ @mock.patch('helper.docker_build')
67
+ def test_base_image(self, mock_docker_build):
68
+ """Tests that build_image_impl works as intended with a base-image."""
69
+ image_name = 'base-image'
70
+ self.assertTrue(helper.build_image_impl(helper.Project(image_name)))
71
+ build_dir = os.path.join(helper.OSS_FUZZ_DIR,
72
+ 'infra/base-images/base-image')
73
+ mock_docker_build.assert_called_with([
74
+ '-t', 'ghcr.io/aixcc-finals/base-image', '--file',
75
+ os.path.join(build_dir, 'Dockerfile'), build_dir
76
+ ])
77
+
78
+ @mock.patch('helper.docker_build')
79
+ def test_oss_fuzz_project(self, mock_docker_build):
80
+ """Tests that build_image_impl works as intended with an OSS-Fuzz
81
+ project."""
82
+ project_name = 'example'
83
+ self.assertTrue(helper.build_image_impl(helper.Project(project_name)))
84
+ build_dir = os.path.join(helper.OSS_FUZZ_DIR, 'projects', project_name)
85
+ mock_docker_build.assert_called_with([
86
+ '-t', 'gcr.io/oss-fuzz/example', '--file',
87
+ os.path.join(build_dir, 'Dockerfile'), build_dir
88
+ ])
89
+
90
+ @mock.patch('helper.docker_build')
91
+ def test_external_project(self, mock_docker_build):
92
+ """Tests that build_image_impl works as intended with a non-OSS-Fuzz
93
+ project."""
94
+ with tempfile.TemporaryDirectory() as temp_dir:
95
+ project_src_path = os.path.join(temp_dir, 'example')
96
+ os.mkdir(project_src_path)
97
+ build_integration_path = 'build-integration'
98
+ project = helper.Project(project_src_path,
99
+ is_external=True,
100
+ build_integration_path=build_integration_path)
101
+ self.assertTrue(helper.build_image_impl(project))
102
+ mock_docker_build.assert_called_with([
103
+ '-t', 'gcr.io/oss-fuzz/example', '--file',
104
+ os.path.join(project_src_path, build_integration_path, 'Dockerfile'),
105
+ project_src_path
106
+ ])
107
+
108
+
109
+ class GenerateImplTest(fake_filesystem_unittest.TestCase):
110
+ """Tests for _generate_impl."""
111
+ PROJECT_NAME = 'newfakeproject'
112
+ PROJECT_LANGUAGE = 'python'
113
+
114
+ def setUp(self):
115
+ self.maxDiff = None # pylint: disable=invalid-name
116
+ self.setUpPyfakefs()
117
+ self.fs.add_real_directory(helper.OSS_FUZZ_DIR)
118
+
119
+ def _verify_templated_files(self, template_dict, directory, language):
120
+ template_args = {
121
+ 'project_name': self.PROJECT_NAME,
122
+ 'year': 2021,
123
+ 'base_builder': helper._base_builder_from_language(language),
124
+ 'language': language,
125
+ }
126
+ for filename, template in template_dict.items():
127
+ file_path = os.path.join(directory, filename)
128
+ with open(file_path, 'r') as file_handle:
129
+ contents = file_handle.read()
130
+ self.assertEqual(contents, template % template_args)
131
+
132
+ @mock.patch('helper._get_current_datetime',
133
+ return_value=datetime.datetime(year=2021, month=1, day=1))
134
+ def test_generate_oss_fuzz_project(self, _):
135
+ """Tests that the correct files are generated for an OSS-Fuzz project."""
136
+ helper._generate_impl(helper.Project(self.PROJECT_NAME),
137
+ self.PROJECT_LANGUAGE)
138
+ self._verify_templated_files(
139
+ templates.TEMPLATES,
140
+ os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.PROJECT_NAME),
141
+ self.PROJECT_LANGUAGE)
142
+
143
+ def test_generate_external_project(self):
144
+ """Tests that the correct files are generated for a non-OSS-Fuzz project."""
145
+ build_integration_path = '/newfakeproject/build-integration'
146
+ helper._generate_impl(
147
+ helper.Project('/newfakeproject/',
148
+ is_external=True,
149
+ build_integration_path=build_integration_path),
150
+ self.PROJECT_LANGUAGE)
151
+ self._verify_templated_files(templates.EXTERNAL_TEMPLATES,
152
+ build_integration_path, self.PROJECT_LANGUAGE)
153
+
154
+ @mock.patch('helper._get_current_datetime',
155
+ return_value=datetime.datetime(year=2021, month=1, day=1))
156
+ def test_generate_swift_project(self, _):
157
+ """Tests that the swift project uses the correct base image."""
158
+ helper._generate_impl(helper.Project(self.PROJECT_NAME), 'swift')
159
+ self._verify_templated_files(
160
+ templates.TEMPLATES,
161
+ os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.PROJECT_NAME),
162
+ 'swift')
163
+
164
+
165
+ class ProjectTest(fake_filesystem_unittest.TestCase):
166
+ """Tests for Project class."""
167
+
168
+ def setUp(self):
169
+ self.project_name = 'project'
170
+ self.internal_project = helper.Project(self.project_name)
171
+ self.external_project_path = os.path.join('/path', 'to', self.project_name)
172
+ self.external_project = helper.Project(self.external_project_path,
173
+ is_external=True)
174
+ self.setUpPyfakefs()
175
+
176
+ def test_init_external_project(self):
177
+ """Tests __init__ method for external projects."""
178
+ self.assertEqual(self.external_project.name, self.project_name)
179
+ self.assertEqual(self.external_project.path, self.external_project_path)
180
+ self.assertEqual(
181
+ self.external_project.build_integration_path,
182
+ os.path.join(self.external_project_path,
183
+ constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH))
184
+
185
+ def test_init_internal_project(self):
186
+ """Tests __init__ method for internal projects."""
187
+ self.assertEqual(self.internal_project.name, self.project_name)
188
+ path = os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.project_name)
189
+ self.assertEqual(self.internal_project.path, path)
190
+ self.assertEqual(self.internal_project.build_integration_path, path)
191
+
192
+ def test_dockerfile_path_internal_project(self):
193
+ """Tests that dockerfile_path works as intended."""
194
+ self.assertEqual(
195
+ self.internal_project.dockerfile_path,
196
+ os.path.join(helper.OSS_FUZZ_DIR, 'projects', self.project_name,
197
+ 'Dockerfile'))
198
+
199
+ def test_dockerfile_path_external_project(self):
200
+ """Tests that dockerfile_path works as intended."""
201
+ self.assertEqual(
202
+ self.external_project.dockerfile_path,
203
+ os.path.join(self.external_project_path,
204
+ constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH,
205
+ 'Dockerfile'))
206
+
207
+ def test_out(self):
208
+ """Tests that out works as intended."""
209
+ out_dir = self.internal_project.out
210
+ self.assertEqual(
211
+ out_dir,
212
+ os.path.join(helper.OSS_FUZZ_DIR, 'build', 'out', self.project_name))
213
+ self.assertTrue(os.path.exists(out_dir))
214
+
215
+ def test_work(self):
216
+ """Tests that work works as intended."""
217
+ work_dir = self.internal_project.work
218
+ self.assertEqual(
219
+ work_dir,
220
+ os.path.join(helper.OSS_FUZZ_DIR, 'build', 'work', self.project_name))
221
+ self.assertTrue(os.path.exists(work_dir))
222
+
223
+ def test_corpus(self):
224
+ """Tests that corpus works as intended."""
225
+ corpus_dir = self.internal_project.corpus
226
+ self.assertEqual(
227
+ corpus_dir,
228
+ os.path.join(helper.OSS_FUZZ_DIR, 'build', 'corpus', self.project_name))
229
+ self.assertTrue(os.path.exists(corpus_dir))
230
+
231
+ def test_language_internal_project(self):
232
+ """Tests that language works as intended for an internal project."""
233
+ project_yaml_path = os.path.join(self.internal_project.path, 'project.yaml')
234
+ self.fs.create_file(project_yaml_path, contents='language: python')
235
+ self.assertEqual(self.internal_project.language, 'python')
236
+
237
+ def test_language_external_project(self):
238
+ """Tests that language works as intended for an external project."""
239
+ self.assertEqual(self.external_project.language, 'c++')
local-test-commons-compress-delta-02/fuzz-tooling/infra/manifest.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #! /usr/bin/env python3
2
+ # Copyright 2022 Google LLC
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ #
16
+ ################################################################################
17
+ """Script for pushing manifest files to docker that point to AMD64 and ARM
18
+ images."""
19
+ import logging
20
+ import subprocess
21
+ import sys
22
+
23
+
24
+ def push_manifest(image):
25
+ """Pushes a manifest file in place of |image| for ARM and AMD64 versions of
26
+ that image."""
27
+ subprocess.run(['docker', 'pull', image], check=True)
28
+ amd64_image = f'{image}:manifest-amd64'
29
+ subprocess.run(['docker', 'tag', image, amd64_image], check=True)
30
+ subprocess.run(['docker', 'push', amd64_image], check=True)
31
+
32
+ arm_version = f'{image}-testing-arm'
33
+ subprocess.run(['docker', 'pull', arm_version], check=True)
34
+ arm64_image = f'{image}:manifest-arm64v8'
35
+ subprocess.run(['docker', 'tag', arm_version, arm64_image], check=True)
36
+
37
+ subprocess.run([
38
+ 'docker', 'manifest', 'create', image, '--amend', arm64_image, '--amend',
39
+ amd64_image
40
+ ],
41
+ check=True)
42
+ subprocess.run(['docker', 'manifest', 'push', image], check=True)
43
+ return True
44
+
45
+
46
+ def main():
47
+ """Sets up manifests for base-builder and base-runner so they can be used for
48
+ ARM builds."""
49
+ logging.info('Doing simple gcloud command to ensure 2FA passes. '
50
+ 'Otherwise docker push fails.')
51
+ subprocess.run(['gcloud', 'projects', 'list', '--limit=1'], check=True)
52
+
53
+ images = [
54
+ 'ghcr.io/aixcc-finals/base-builder', 'ghcr.io/aixcc-finals/base-runner'
55
+ ]
56
+ results = [push_manifest(image) for image in images]
57
+ return 0 if all(results) else 1
58
+
59
+
60
+ if __name__ == '__main__':
61
+ sys.exit(main())
local-test-commons-compress-delta-02/fuzz-tooling/infra/presubmit.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2020 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
+ """Checks code for common issues before submitting."""
18
+
19
+ import argparse
20
+ import os
21
+ import re
22
+ import subprocess
23
+ import sys
24
+ import unittest
25
+ import yaml
26
+
27
+ import constants
28
+
29
+ _SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
+ VALID_PROJECT_REGEX_STR = '^[a-z0-9_-]+$'
31
+ VALID_PROJECT_REGEX = re.compile(VALID_PROJECT_REGEX_STR)
32
+
33
+
34
+ def _is_project_file(actual_path, expected_filename):
35
+ """Returns True if actual_path's name is |expected_filename| and is a file
36
+ that exists and is in in projects/."""
37
+ if os.path.basename(actual_path) != expected_filename:
38
+ return False
39
+
40
+ if os.path.basename(os.path.dirname(
41
+ os.path.dirname(actual_path))) != 'projects':
42
+ return False
43
+
44
+ return os.path.exists(actual_path)
45
+
46
+
47
+ # TODO: Check for -fsanitize=fuzzer in files as well.
48
+
49
+
50
+ def _check_one_lib_fuzzing_engine(build_sh_file):
51
+ """Returns False if |build_sh_file| contains -lFuzzingEngine.
52
+ This is deprecated behavior. $LIB_FUZZING_ENGINE should be used instead
53
+ so that -fsanitize=fuzzer is used."""
54
+ if not _is_project_file(build_sh_file, 'build.sh'):
55
+ return True
56
+
57
+ with open(build_sh_file) as build_sh:
58
+ build_sh_lines = build_sh.readlines()
59
+ for line_num, line in enumerate(build_sh_lines):
60
+ uncommented_code = line.split('#')[0]
61
+ if '-lFuzzingEngine' in uncommented_code:
62
+ print('Error: build.sh contains deprecated "-lFuzzingEngine" on line: '
63
+ f'{line_num}. Please use "$LIB_FUZZING_ENGINE" instead.')
64
+ return False
65
+ return True
66
+
67
+
68
+ def check_lib_fuzzing_engine(paths):
69
+ """Calls _check_one_lib_fuzzing_engine on each path in |paths|. Returns True
70
+ if the result of every call is True."""
71
+ return all(_check_one_lib_fuzzing_engine(path) for path in paths)
72
+
73
+
74
+ class ProjectYamlChecker:
75
+ """Checks for a project.yaml file."""
76
+
77
+ # Sections in a project.yaml and the constant values that they are allowed
78
+ # to have.
79
+ SECTIONS_AND_CONSTANTS = {
80
+ 'sanitizers': constants.SANITIZERS,
81
+ 'architectures': constants.ARCHITECTURES,
82
+ 'fuzzing_engines': constants.ENGINES,
83
+ }
84
+
85
+ # Note: this list must be updated when we allow new sections.
86
+ VALID_SECTION_NAMES = [
87
+ 'architectures',
88
+ 'auto_ccs',
89
+ 'blackbox',
90
+ 'builds_per_day',
91
+ 'coverage_extra_args',
92
+ 'disabled',
93
+ 'fuzzing_engines',
94
+ 'help_url',
95
+ 'homepage',
96
+ 'language',
97
+ 'labels', # For internal use only, hard to lint as it uses fuzzer names.
98
+ 'main_repo',
99
+ 'primary_contact',
100
+ 'run_tests',
101
+ 'sanitizers',
102
+ 'selective_unpack',
103
+ 'vendor_ccs',
104
+ 'view_restrictions',
105
+ 'file_github_issue',
106
+ ]
107
+
108
+ REQUIRED_SECTIONS = ['main_repo']
109
+
110
+ def __init__(self, filename):
111
+ self.filename = filename
112
+ with open(filename) as file_handle:
113
+ self.data = yaml.safe_load(file_handle)
114
+
115
+ self.success = True
116
+
117
+ def do_checks(self):
118
+ """Does all project.yaml checks. Returns True if they pass."""
119
+ if self.is_disabled():
120
+ return True
121
+
122
+ checks = [
123
+ self.check_project_yaml_constants,
124
+ self.check_required_sections,
125
+ self.check_valid_section_names,
126
+ self.check_valid_emails,
127
+ self.check_valid_language,
128
+ self.check_valid_project_name,
129
+ ]
130
+ for check_function in checks:
131
+ check_function()
132
+ return self.success
133
+
134
+ def is_disabled(self):
135
+ """Returns True if this project is disabled."""
136
+ return self.data.get('disabled', False)
137
+
138
+ def error(self, message):
139
+ """Prints an error message and sets self.success to False."""
140
+ self.success = False
141
+ print(f'Error in {self.filename}: {message}')
142
+
143
+ def check_valid_project_name(self):
144
+ """Checks that the project has a valid name."""
145
+ banned_names = ['google', 'g00gle']
146
+ project_name = os.path.basename(os.path.dirname(self.filename))
147
+ for banned_name in banned_names:
148
+ if banned_name in project_name:
149
+ self.error('Projects can\'t have \'google\' in the name.')
150
+ if not VALID_PROJECT_REGEX.match(project_name):
151
+ self.error(f'Projects must conform to regex {VALID_PROJECT_REGEX_STR}')
152
+
153
+ def check_project_yaml_constants(self):
154
+ """Returns True if certain sections only have certain constant values."""
155
+ for section, allowed_constants in self.SECTIONS_AND_CONSTANTS.items():
156
+ if section not in self.data:
157
+ continue
158
+ actual_constants = self.data[section]
159
+ allowed_constants_str = ', '.join(allowed_constants)
160
+ for constant in actual_constants:
161
+ if isinstance(constant, str):
162
+ if constant not in allowed_constants:
163
+ self.error(f'{constant} (in {section} section) is not a valid '
164
+ f'constant ({allowed_constants_str}).')
165
+ elif isinstance(constant, dict):
166
+ # The only alternative value allowed is the experimental flag, i.e.
167
+ # `constant == {'memory': {'experimental': True}}`. Do not check the
168
+ # experimental flag, but assert that the sanitizer is a valid one.
169
+ if (len(constant.keys()) > 1 or
170
+ list(constant.keys())[0] not in allowed_constants):
171
+ self.error(f'Not allowed value in the project.yaml: {constant}')
172
+ else:
173
+ self.error(f'Not allowed value in the project.yaml: {constant}')
174
+
175
+ def check_valid_section_names(self):
176
+ """Returns True if all section names are valid."""
177
+ for name in self.data:
178
+ if name not in self.VALID_SECTION_NAMES:
179
+ self.error(
180
+ f'{name} is not a valid section name ({self.VALID_SECTION_NAMES})')
181
+
182
+ def check_required_sections(self):
183
+ """Returns True if all required sections are in |self.data|."""
184
+ for section in self.REQUIRED_SECTIONS:
185
+ if section not in self.data:
186
+ self.error(f'{section} section is missing.')
187
+
188
+ def check_valid_emails(self):
189
+ """Returns True if emails are valid looking.."""
190
+ # Get email addresses.
191
+ email_addresses = []
192
+ primary_contact = self.data.get('primary_contact')
193
+ if primary_contact:
194
+ email_addresses.append(primary_contact)
195
+ auto_ccs = self.data.get('auto_ccs')
196
+ if auto_ccs:
197
+ email_addresses.extend(auto_ccs)
198
+
199
+ # Check that email addresses seem normal.
200
+ for email_address in email_addresses:
201
+ if '@' not in email_address or '.' not in email_address:
202
+ self.error(f'{email_address} is an invalid email address.')
203
+
204
+ def check_valid_language(self):
205
+ """Returns True if the language is specified and valid."""
206
+ language = self.data.get('language')
207
+ if not language:
208
+ self.error('Missing "language" attribute in project.yaml.')
209
+ elif language not in constants.LANGUAGES:
210
+ self.error(
211
+ f'"language: {language}" is not supported ({constants.LANGUAGES}).')
212
+
213
+
214
+ def _check_one_project_yaml(project_yaml_filename):
215
+ """Does checks on the project.yaml file. Returns True on success."""
216
+ if _is_project_file(project_yaml_filename, 'project.yml'):
217
+ print(project_yaml_filename, 'must be named project.yaml.')
218
+ return False
219
+
220
+ if not _is_project_file(project_yaml_filename, 'project.yaml'):
221
+ return True
222
+
223
+ checker = ProjectYamlChecker(project_yaml_filename)
224
+ return checker.do_checks()
225
+
226
+
227
+ def check_project_yaml(paths):
228
+ """Calls _check_one_project_yaml on each path in |paths|. Returns True if the
229
+ result of every call is True."""
230
+ return all([_check_one_project_yaml(path) for path in paths])
231
+
232
+
233
+ def _check_one_seed_corpus(path):
234
+ """Returns False and prints error if |path| is a seed corpus."""
235
+ if os.path.basename(os.path.dirname(os.path.dirname(path))) != 'projects':
236
+ return True
237
+
238
+ if os.path.splitext(path)[1] == '.zip':
239
+ print('Don\'t commit seed corpora into the ClusterFuzz repo,'
240
+ 'they bloat it forever.')
241
+ return False
242
+
243
+ return True
244
+
245
+
246
+ def check_seed_corpus(paths):
247
+ """Calls _check_one_seed_corpus on each path in |paths|. Returns True if the
248
+ result of every call is True."""
249
+ return all([_check_one_seed_corpus(path) for path in paths])
250
+
251
+
252
+ def _check_one_apt_update(path):
253
+ """Checks that a Dockerfile uses apt-update before apt-install"""
254
+ if os.path.basename(os.path.dirname(os.path.dirname(path))) != 'projects':
255
+ return True
256
+
257
+ if os.path.basename(path) != 'Dockerfile':
258
+ return True
259
+
260
+ with open(path, 'r') as file:
261
+ dockerfile = file.read()
262
+ if 'RUN apt install' in dockerfile or 'RUN apt-get install' in dockerfile:
263
+ print('Please add an "apt-get update" before "apt-get install". '
264
+ 'Otherwise, a cached and outdated RUN layer may lead to install '
265
+ 'failures in file %s.' % str(path))
266
+ return False
267
+
268
+ return True
269
+
270
+
271
+ def check_apt_update(paths):
272
+ """Checks that all Dockerfile use apt-update before apt-install"""
273
+ return all([_check_one_apt_update(path) for path in paths])
274
+
275
+
276
+ def do_checks(changed_files):
277
+ """Runs all presubmit checks. Returns False if any fails."""
278
+ checks = [
279
+ check_license,
280
+ yapf,
281
+ check_project_yaml,
282
+ check_lib_fuzzing_engine,
283
+ check_seed_corpus,
284
+ check_apt_update,
285
+ ]
286
+ # Use a list comprehension here and in other cases where we use all() so that
287
+ # we don't quit early on failure. This is more user-friendly since the more
288
+ # errors we spit out at once, the less frequently the less check-fix-check
289
+ # cycles they need to do.
290
+ return all([check(changed_files) for check in checks])
291
+
292
+
293
+ _CHECK_LICENSE_FILENAMES = ['Dockerfile']
294
+ _CHECK_LICENSE_EXTENSIONS = [
295
+ '.bash',
296
+ '.c',
297
+ '.cc',
298
+ '.cpp',
299
+ '.css',
300
+ '.Dockerfile',
301
+ '.go',
302
+ '.h',
303
+ '.htm',
304
+ '.html',
305
+ '.java',
306
+ '.js',
307
+ '.proto',
308
+ '.py',
309
+ '.rs',
310
+ '.sh',
311
+ '.ts',
312
+ ]
313
+ THIRD_PARTY_DIR_NAME = 'third_party'
314
+
315
+ _LICENSE_STRING = 'http://www.apache.org/licenses/LICENSE-2.0'
316
+
317
+
318
+ def check_license(paths):
319
+ """Validates license header."""
320
+ if not paths:
321
+ return True
322
+
323
+ success = True
324
+ for path in paths:
325
+ path_parts = str(path).split(os.sep)
326
+ if any(path_part == THIRD_PARTY_DIR_NAME for path_part in path_parts):
327
+ continue
328
+ filename = os.path.basename(path)
329
+ extension = os.path.splitext(path)[1]
330
+ if (filename not in _CHECK_LICENSE_FILENAMES and
331
+ extension not in _CHECK_LICENSE_EXTENSIONS):
332
+ continue
333
+
334
+ with open(path) as file_handle:
335
+ if _LICENSE_STRING not in file_handle.read():
336
+ print('Missing license header in file %s.' % str(path))
337
+ success = False
338
+
339
+ return success
340
+
341
+
342
+ def bool_to_returncode(success):
343
+ """Returns 0 if |success|. Otherwise returns 1."""
344
+ if success:
345
+ print('Success.')
346
+ return 0
347
+
348
+ print('Failed.')
349
+ return 1
350
+
351
+
352
+ def is_nonfuzzer_python(path):
353
+ """Returns True if |path| ends in .py."""
354
+ return os.path.splitext(path)[1] == '.py' and '/projects/' not in path
355
+
356
+
357
+ def lint(_=None):
358
+ """Runs python's linter on infra. Returns False if it fails linting."""
359
+
360
+ # Use --score no to make linting quieter.
361
+ command = ['python3', '-m', 'pylint', '--score', 'no', '-j', '0', 'infra']
362
+ returncode = subprocess.run(command, check=False).returncode
363
+ return returncode == 0
364
+
365
+
366
+ def yapf(paths, validate=True):
367
+ """Does yapf on |path| if it is Python file. Only validates format if
368
+ |validate|. Otherwise, formats the file. Returns False if validation or
369
+ formatting fails."""
370
+ paths = [path for path in paths if is_nonfuzzer_python(path)]
371
+ if not paths:
372
+ return True
373
+
374
+ validate_argument = '-d' if validate else '-i'
375
+ command = ['yapf', validate_argument, '-p']
376
+ command.extend(paths)
377
+
378
+ returncode = subprocess.run(command, check=False).returncode
379
+ return returncode == 0
380
+
381
+
382
+ def get_changed_files():
383
+ """Returns a list of absolute paths of files changed in this git branch."""
384
+ branch_commit_hash = subprocess.check_output(
385
+ ['git', 'merge-base', 'HEAD', 'origin/HEAD']).strip().decode()
386
+
387
+ diff_commands = [
388
+ # Return list of modified files in the commits on this branch.
389
+ ['git', 'diff', '--name-only', branch_commit_hash + '..'],
390
+ # Return list of modified files from uncommitted changes.
391
+ ['git', 'diff', '--name-only']
392
+ ]
393
+
394
+ changed_files = set()
395
+ for command in diff_commands:
396
+ file_paths = subprocess.check_output(command).decode().splitlines()
397
+ for file_path in file_paths:
398
+ if not os.path.isfile(file_path):
399
+ continue
400
+ changed_files.add(file_path)
401
+ print(f'Changed files: {" ".join(changed_files)}')
402
+ return [os.path.abspath(f) for f in changed_files]
403
+
404
+
405
+ def run_build_tests():
406
+ """Runs build tests because they can't be run in parallel."""
407
+ suite_list = [
408
+ unittest.TestLoader().discover(os.path.join(_SRC_ROOT, 'infra', 'build'),
409
+ pattern='*_test.py'),
410
+ ]
411
+ suite = unittest.TestSuite(suite_list)
412
+ print('Running build tests.')
413
+ result = unittest.TextTestRunner().run(suite)
414
+ return not result.failures and not result.errors
415
+
416
+
417
+ def run_nonbuild_tests(parallel):
418
+ """Runs all tests but build tests. Does them in parallel if |parallel|. The
419
+ reason why we exclude build tests is because they use an emulator that
420
+ prevents them from being used in parallel."""
421
+ # We look for all project directories because otherwise pytest won't run tests
422
+ # that are not in valid modules (e.g. "base-images").
423
+ relevant_dirs = set()
424
+ all_files = get_all_files()
425
+ for file_path in all_files:
426
+ directory = os.path.dirname(file_path)
427
+ relevant_dirs.add(directory)
428
+
429
+ # Use ignore-glob because ignore doesn't seem to work properly with the way we
430
+ # pass directories to pytest.
431
+ command = [
432
+ 'pytest',
433
+ '--ignore-glob=infra/build/*',
434
+ '--ignore-glob=projects/*',
435
+ ]
436
+ if parallel:
437
+ command.extend(['-n', 'auto'])
438
+ command += list(relevant_dirs)
439
+ print('Running non-build tests.')
440
+
441
+ # TODO(metzman): Get rid of this once config_utils stops using it.
442
+ env = os.environ.copy()
443
+ env['CIFUZZ_TEST'] = '1'
444
+
445
+ return subprocess.run(command, check=False, env=env).returncode == 0
446
+
447
+
448
+ def run_tests(_=None, parallel=False, build_tests=True, nonbuild_tests=True):
449
+ """Runs all unit tests."""
450
+ build_success = True
451
+ nonbuild_success = True
452
+ if nonbuild_tests:
453
+ nonbuild_success = run_nonbuild_tests(parallel)
454
+ else:
455
+ print('Skipping nonbuild tests as specified.')
456
+
457
+ if build_tests:
458
+ build_success = run_build_tests()
459
+ else:
460
+ print('Skipping build tests as specified.')
461
+
462
+ return nonbuild_success and build_success
463
+
464
+
465
+ def run_systemsan_tests(_=None):
466
+ """Runs SystemSan unit tests."""
467
+ command = ['make', 'test']
468
+ return subprocess.run(command,
469
+ cwd='infra/experimental/SystemSan',
470
+ check=False).returncode == 0
471
+
472
+
473
+ def get_all_files():
474
+ """Returns a list of absolute paths of files in this repo."""
475
+ get_all_files_command = ['git', 'ls-files']
476
+ output = subprocess.check_output(get_all_files_command).decode().splitlines()
477
+ return [os.path.abspath(path) for path in output if os.path.isfile(path)]
478
+
479
+
480
+ def main():
481
+ """Check changes on a branch for common issues before submitting."""
482
+ # Get program arguments.
483
+ parser = argparse.ArgumentParser(description='Presubmit script for oss-fuzz.')
484
+ parser.add_argument(
485
+ 'command',
486
+ choices=['format', 'lint', 'license', 'infra-tests', 'systemsan-tests'],
487
+ nargs='?')
488
+ parser.add_argument('-a',
489
+ '--all-files',
490
+ action='store_true',
491
+ help='Run presubmit check(s) on all files',
492
+ default=False)
493
+ parser.add_argument('-p',
494
+ '--parallel',
495
+ action='store_true',
496
+ help='Run tests in parallel.',
497
+ default=False)
498
+ parser.add_argument('-s',
499
+ '--skip-build-tests',
500
+ action='store_true',
501
+ help='Skip build tests which are slow and must run '
502
+ 'sequentially.',
503
+ default=False)
504
+ parser.add_argument('-n',
505
+ '--skip-nonbuild-tests',
506
+ action='store_true',
507
+ help='Only do build tests.',
508
+ default=False)
509
+ args = parser.parse_args()
510
+
511
+ if args.all_files:
512
+ relevant_files = get_all_files()
513
+ else:
514
+ relevant_files = get_changed_files()
515
+
516
+ os.chdir(_SRC_ROOT)
517
+
518
+ # Do one specific check if the user asked for it.
519
+ if args.command == 'format':
520
+ success = yapf(relevant_files, False)
521
+ return bool_to_returncode(success)
522
+
523
+ if args.command == 'lint':
524
+ success = lint()
525
+ return bool_to_returncode(success)
526
+
527
+ if args.command == 'license':
528
+ success = check_license(relevant_files)
529
+ return bool_to_returncode(success)
530
+
531
+ if args.command == 'infra-tests':
532
+ success = run_tests(relevant_files,
533
+ parallel=args.parallel,
534
+ build_tests=(not args.skip_build_tests),
535
+ nonbuild_tests=(not args.skip_nonbuild_tests))
536
+ return bool_to_returncode(success)
537
+
538
+ if args.command == 'systemsan-tests':
539
+ success = run_systemsan_tests(relevant_files)
540
+ return bool_to_returncode(success)
541
+
542
+ # Do all the checks (but no tests).
543
+ success = do_checks(relevant_files)
544
+
545
+ return bool_to_returncode(success)
546
+
547
+
548
+ if __name__ == '__main__':
549
+ sys.exit(main())
local-test-commons-compress-delta-02/fuzz-tooling/infra/retry.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Retry decorator. Copied from ClusterFuzz source."""
15
+
16
+ import functools
17
+ import inspect
18
+ import logging
19
+ import sys
20
+ import time
21
+
22
+ # pylint: disable=too-many-arguments,broad-except
23
+
24
+
25
+ def sleep(seconds):
26
+ """Invoke time.sleep. This is to avoid the flakiness of time.sleep. See:
27
+ crbug.com/770375"""
28
+ time.sleep(seconds)
29
+
30
+
31
+ def get_delay(num_try, delay, backoff):
32
+ """Compute backoff delay."""
33
+ return delay * (backoff**(num_try - 1))
34
+
35
+
36
+ def wrap(retries,
37
+ delay,
38
+ backoff=2,
39
+ exception_type=Exception,
40
+ retry_on_false=False):
41
+ """Retry decorator for a function."""
42
+
43
+ assert delay > 0
44
+ assert backoff >= 1
45
+ assert retries >= 0
46
+
47
+ def decorator(func):
48
+ """Decorator for the given function."""
49
+ tries = retries + 1
50
+ is_generator = inspect.isgeneratorfunction(func)
51
+ function_with_type = func.__qualname__
52
+ if is_generator:
53
+ function_with_type += ' (generator)'
54
+
55
+ def handle_retry(num_try, exception=None):
56
+ """Handle retry."""
57
+ if (exception is None or
58
+ isinstance(exception, exception_type)) and num_try < tries:
59
+ logging.info('Retrying on %s failed with %s. Retrying again.',
60
+ function_with_type,
61
+ sys.exc_info()[1])
62
+ sleep(get_delay(num_try, delay, backoff))
63
+ return True
64
+
65
+ logging.error('Retrying on %s failed with %s. Raise.', function_with_type,
66
+ sys.exc_info()[1])
67
+ return False
68
+
69
+ @functools.wraps(func)
70
+ def _wrapper(*args, **kwargs):
71
+ """Regular function wrapper."""
72
+ for num_try in range(1, tries + 1):
73
+ try:
74
+ result = func(*args, **kwargs)
75
+ if retry_on_false and not result:
76
+ if not handle_retry(num_try):
77
+ return result
78
+
79
+ continue
80
+ return result
81
+ except Exception as error:
82
+ if not handle_retry(num_try, exception=error):
83
+ raise
84
+
85
+ @functools.wraps(func)
86
+ def _generator_wrapper(*args, **kwargs):
87
+ """Generator function wrapper."""
88
+ # This argument is not applicable for generator functions.
89
+ assert not retry_on_false
90
+ already_yielded_element_count = 0
91
+ for num_try in range(1, tries + 1):
92
+ try:
93
+ for index, result in enumerate(func(*args, **kwargs)):
94
+ if index >= already_yielded_element_count:
95
+ yield result
96
+ already_yielded_element_count += 1
97
+ break
98
+ except Exception as error:
99
+ if not handle_retry(num_try, exception=error):
100
+ raise
101
+
102
+ if is_generator:
103
+ return _generator_wrapper
104
+ return _wrapper
105
+
106
+ return decorator
local-test-commons-compress-delta-02/fuzz-tooling/infra/run_fuzzers.Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+ # Docker image for running fuzzers on CIFuzz (the run_fuzzers action on GitHub
17
+ # actions).
18
+
19
+ FROM ghcr.io/aixcc-finals/cifuzz-base
20
+
21
+ # Python file to execute when the docker container starts up.
22
+ # We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var,
23
+ # just expand to '/opt/oss-fuzz'.
24
+ ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/run_fuzzers_entrypoint.py"]
25
+
26
+ WORKDIR ${OSS_FUZZ_ROOT}/infra
27
+
28
+ # Copy infra source code.
29
+ ADD . ${OSS_FUZZ_ROOT}/infra
30
+
31
+ RUN python3 -m pip install -r ${OSS_FUZZ_ROOT}/infra/cifuzz/requirements.txt
local-test-commons-compress-delta-02/fuzz-tooling/infra/templates.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2016 Google Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ ################################################################################
16
+ """Templates for OSS-Fuzz project files."""
17
+
18
+ PROJECT_YAML_TEMPLATE = """\
19
+ homepage: "<your_project_homepage>"
20
+ language: %(language)s
21
+ primary_contact: "<primary_contact_email>"
22
+ main_repo: "https://path/to/main/repo.git"
23
+ file_github_issue: true
24
+ """
25
+
26
+ DOCKER_TEMPLATE = """\
27
+ # Copyright %(year)d Google LLC
28
+ #
29
+ # Licensed under the Apache License, Version 2.0 (the "License");
30
+ # you may not use this file except in compliance with the License.
31
+ # You may obtain a copy of the License at
32
+ #
33
+ # http://www.apache.org/licenses/LICENSE-2.0
34
+ #
35
+ # Unless required by applicable law or agreed to in writing, software
36
+ # distributed under the License is distributed on an "AS IS" BASIS,
37
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
38
+ # See the License for the specific language governing permissions and
39
+ # limitations under the License.
40
+ #
41
+ ################################################################################
42
+
43
+ FROM ghcr.io/aixcc-finals/%(base_builder)s
44
+ RUN apt-get update && apt-get install -y make autoconf automake libtool
45
+ RUN git clone --depth 1 <git_url> %(project_name)s # or use other version control
46
+ WORKDIR %(project_name)s
47
+ COPY build.sh $SRC/
48
+ """
49
+
50
+ EXTERNAL_DOCKER_TEMPLATE = """\
51
+ FROM ghcr.io/aixcc-finals/%(base_builder)s:v1
52
+ RUN apt-get update && apt-get install -y make autoconf automake libtool
53
+ COPY . $SRC/%(project_name)s
54
+ WORKDIR %(project_name)s
55
+ COPY .clusterfuzzlite/build.sh $SRC/
56
+ """
57
+
58
+ BUILD_TEMPLATE = """\
59
+ #!/bin/bash -eu
60
+ # Copyright %(year)d Google LLC
61
+ #
62
+ # Licensed under the Apache License, Version 2.0 (the "License");
63
+ # you may not use this file except in compliance with the License.
64
+ # You may obtain a copy of the License at
65
+ #
66
+ # http://www.apache.org/licenses/LICENSE-2.0
67
+ #
68
+ # Unless required by applicable law or agreed to in writing, software
69
+ # distributed under the License is distributed on an "AS IS" BASIS,
70
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
71
+ # See the License for the specific language governing permissions and
72
+ # limitations under the License.
73
+ #
74
+ ################################################################################
75
+
76
+ # build project
77
+ # e.g.
78
+ # ./autogen.sh
79
+ # ./configure
80
+ # make -j$(nproc) all
81
+
82
+ # build fuzzers
83
+ # e.g.
84
+ # $CXX $CXXFLAGS -std=c++11 -Iinclude \\
85
+ # /path/to/name_of_fuzzer.cc -o $OUT/name_of_fuzzer \\
86
+ # $LIB_FUZZING_ENGINE /path/to/library.a
87
+ """
88
+
89
+ EXTERNAL_BUILD_TEMPLATE = """\
90
+ #!/bin/bash -eu
91
+
92
+ # build project
93
+ # e.g.
94
+ # ./autogen.sh
95
+ # ./configure
96
+ # make -j$(nproc) all
97
+
98
+ # build fuzzers
99
+ # e.g.
100
+ # $CXX $CXXFLAGS -std=c++11 -Iinclude \\
101
+ # /path/to/name_of_fuzzer.cc -o $OUT/name_of_fuzzer \\
102
+ # $LIB_FUZZING_ENGINE /path/to/library.a
103
+ """
104
+
105
+ EXTERNAL_PROJECT_YAML_TEMPLATE = """\
106
+ language: %(language)s
107
+ """
108
+
109
+ TEMPLATES = {
110
+ 'build.sh': BUILD_TEMPLATE,
111
+ 'Dockerfile': DOCKER_TEMPLATE,
112
+ 'project.yaml': PROJECT_YAML_TEMPLATE
113
+ }
114
+
115
+ EXTERNAL_TEMPLATES = {
116
+ 'build.sh': EXTERNAL_BUILD_TEMPLATE,
117
+ 'Dockerfile': EXTERNAL_DOCKER_TEMPLATE,
118
+ 'project.yaml': EXTERNAL_PROJECT_YAML_TEMPLATE
119
+ }
local-test-commons-compress-delta-02/fuzz-tooling/infra/test ADDED
@@ -0,0 +1 @@
 
 
1
+
local-test-commons-compress-delta-02/fuzz-tooling/infra/test_repos.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """This module contains a list of test repository's used in unit/integration
15
+ tests.
16
+
17
+ Note: If you notice tests failing for unexpected reasons, make sure the data
18
+ in the test repos are correct. This is because the test repos are dynamic and
19
+ may change.
20
+
21
+ Note: This should be removed when a better method of testing is established.
22
+ """
23
+
24
+ import collections
25
+ import os
26
+
27
+ ExampleRepo = collections.namedtuple('ExampleRepo', [
28
+ 'project_name', 'oss_repo_name', 'git_repo_name', 'image_location',
29
+ 'git_url', 'new_commit', 'old_commit', 'intro_commit', 'fuzz_target',
30
+ 'testcase_path'
31
+ ])
32
+
33
+ TEST_DIR_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
34
+ 'testcases')
35
+
36
+ # WARNING: Tests are dependent upon the following repos existing and the
37
+ # specified commits existing.
38
+ # TODO(metzman): Fix this problem.
39
+ # TODO(metzman): The testcases got deleted here because the test that used them
40
+ # was skipped. Probably worth deleting the test.
41
+ TEST_REPOS = [
42
+ ExampleRepo(project_name='curl',
43
+ oss_repo_name='curl',
44
+ git_repo_name='curl',
45
+ image_location='/src',
46
+ git_url='https://github.com/curl/curl.git',
47
+ old_commit='df26f5f9c36e19cd503c0e462e9f72ad37b84c82',
48
+ new_commit='dda418266c99ceab368d723facb52069cbb9c8d5',
49
+ intro_commit='df26f5f9c36e19cd503c0e462e9f72ad37b84c82',
50
+ fuzz_target='curl_fuzzer_ftp',
51
+ testcase_path=os.path.join(TEST_DIR_PATH, 'curl_test_data')),
52
+ ExampleRepo(project_name='libarchive',
53
+ oss_repo_name='libarchive',
54
+ git_repo_name='libarchive',
55
+ image_location='/src',
56
+ git_url='https://github.com/libarchive/libarchive.git',
57
+ old_commit='5bd2a9b6658a3a6efa20bb9ad75bd39a44d71da6',
58
+ new_commit='458e49358f17ec58d65ab1c45cf299baaf3c98d1',
59
+ intro_commit='840266712006de5e737f8052db920dfea2be4260',
60
+ fuzz_target='libarchive_fuzzer',
61
+ testcase_path=os.path.join(TEST_DIR_PATH,
62
+ 'libarchive_test_data')),
63
+ ExampleRepo(project_name='gonids',
64
+ oss_repo_name='gonids',
65
+ git_repo_name='gonids',
66
+ image_location='/root/go/src/github.com/google/',
67
+ git_url='https://github.com/google/gonids',
68
+ old_commit='',
69
+ new_commit='',
70
+ intro_commit='',
71
+ fuzz_target='',
72
+ testcase_path='')
73
+ ]
74
+
75
+ INVALID_REPO = ExampleRepo(project_name='notaproj',
76
+ oss_repo_name='notarepo',
77
+ git_repo_name='notarepo',
78
+ git_url='invalid.git',
79
+ image_location='/src',
80
+ old_commit='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
81
+ new_commit='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
82
+ intro_commit='aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
83
+ fuzz_target='NONEFUZZER',
84
+ testcase_path='not/a/path')
local-test-commons-compress-delta-02/fuzz-tooling/infra/utils.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Utilities for OSS-Fuzz infrastructure."""
15
+
16
+ import logging
17
+ import os
18
+ import posixpath
19
+ import re
20
+ import shlex
21
+ import stat
22
+ import subprocess
23
+ import sys
24
+
25
+ import helper
26
+
27
+ ALLOWED_FUZZ_TARGET_EXTENSIONS = ['', '.exe']
28
+ FUZZ_TARGET_SEARCH_STRING = 'LLVMFuzzerTestOneInput'
29
+ VALID_TARGET_NAME_REGEX = re.compile(r'^[a-zA-Z0-9_-]+$')
30
+ BLOCKLISTED_TARGET_NAME_REGEX = re.compile(r'^(jazzer_driver.*)$')
31
+
32
+ # Location of google cloud storage for latest OSS-Fuzz builds.
33
+ GCS_BASE_URL = 'https://storage.googleapis.com/'
34
+
35
+
36
+ def chdir_to_root():
37
+ """Changes cwd to OSS-Fuzz root directory."""
38
+ # Change to oss-fuzz main directory so helper.py runs correctly.
39
+ if os.getcwd() != helper.OSS_FUZZ_DIR:
40
+ os.chdir(helper.OSS_FUZZ_DIR)
41
+
42
+
43
+ def command_to_string(command):
44
+ """Returns the stringfied version of |command| a list representing a binary to
45
+ run and arguments to pass to it or a string representing a binary to run."""
46
+ if isinstance(command, str):
47
+ return command
48
+ return shlex.join(command)
49
+
50
+
51
+ def execute(command,
52
+ env=None,
53
+ location=None,
54
+ check_result=False,
55
+ log_command=True):
56
+ """Runs a shell command in the specified directory location.
57
+
58
+ Args:
59
+ command: The command as a list to be run.
60
+ env: (optional) an environment to pass to Popen to run the command in.
61
+ location (optional): The directory to run command in.
62
+ check_result (optional): Should an exception be thrown on failure.
63
+
64
+ Returns:
65
+ stdout, stderr, returncode.
66
+
67
+ Raises:
68
+ RuntimeError: running a command resulted in an error.
69
+ """
70
+
71
+ if not location:
72
+ location = os.getcwd()
73
+ process = subprocess.Popen(command,
74
+ stdout=subprocess.PIPE,
75
+ stderr=subprocess.PIPE,
76
+ cwd=location,
77
+ env=env)
78
+ out, err = process.communicate()
79
+ out = out.decode('utf-8', errors='ignore')
80
+ err = err.decode('utf-8', errors='ignore')
81
+
82
+ if log_command:
83
+ command_str = command_to_string(command)
84
+ display_err = err
85
+ else:
86
+ command_str = 'redacted'
87
+ display_err = 'redacted'
88
+
89
+ if err:
90
+ logging.debug('Stderr of command "%s" is: %s.', command_str, display_err)
91
+ if check_result and process.returncode:
92
+ raise RuntimeError('Executing command "{0}" failed with error: {1}.'.format(
93
+ command_str, display_err))
94
+ return out, err, process.returncode
95
+
96
+
97
+ def get_fuzz_targets(path):
98
+ """Gets fuzz targets in a directory.
99
+
100
+ Args:
101
+ path: A path to search for fuzz targets in.
102
+
103
+ Returns:
104
+ A list of paths to fuzzers or an empty list if None.
105
+ """
106
+ if not os.path.exists(path):
107
+ return []
108
+ fuzz_target_paths = []
109
+ for root, _, fuzzers in os.walk(path):
110
+ for fuzzer in fuzzers:
111
+ file_path = os.path.join(root, fuzzer)
112
+ if is_fuzz_target_local(file_path):
113
+ fuzz_target_paths.append(file_path)
114
+
115
+ return fuzz_target_paths
116
+
117
+
118
+ def get_container_name():
119
+ """Gets the name of the current docker container you are in.
120
+
121
+ Returns:
122
+ Container name or None if not in a container.
123
+ """
124
+ result = subprocess.run( # pylint: disable=subprocess-run-check
125
+ ['systemd-detect-virt', '-c'],
126
+ stdout=subprocess.PIPE).stdout
127
+ if b'docker' not in result:
128
+ return None
129
+ with open('/etc/hostname') as file_handle:
130
+ return file_handle.read().strip()
131
+
132
+
133
+ def is_executable(file_path):
134
+ """Returns True if |file_path| is an exectuable."""
135
+ return os.path.exists(file_path) and os.access(file_path, os.X_OK)
136
+
137
+
138
+ def is_fuzz_target_local(file_path):
139
+ """Returns whether |file_path| is a fuzz target binary (local path).
140
+ Copied from clusterfuzz src/python/bot/fuzzers/utils.py
141
+ with slight modifications.
142
+ """
143
+ # pylint: disable=too-many-return-statements
144
+ filename, file_extension = os.path.splitext(os.path.basename(file_path))
145
+ if not VALID_TARGET_NAME_REGEX.match(filename):
146
+ # Check fuzz target has a valid name (without any special chars).
147
+ return False
148
+
149
+ if BLOCKLISTED_TARGET_NAME_REGEX.match(filename):
150
+ # Check fuzz target an explicitly disallowed name (e.g. binaries used for
151
+ # jazzer-based targets).
152
+ return False
153
+
154
+ if file_extension not in ALLOWED_FUZZ_TARGET_EXTENSIONS:
155
+ # Ignore files with disallowed extensions (to prevent opening e.g. .zips).
156
+ return False
157
+
158
+ if not is_executable(file_path):
159
+ return False
160
+
161
+ if filename.endswith('_fuzzer'):
162
+ return True
163
+
164
+ if os.path.exists(file_path) and not stat.S_ISREG(os.stat(file_path).st_mode):
165
+ return False
166
+
167
+ with open(file_path, 'rb') as file_handle:
168
+ return file_handle.read().find(FUZZ_TARGET_SEARCH_STRING.encode()) != -1
169
+
170
+
171
+ def binary_print(string):
172
+ """Prints string. Can print a binary string."""
173
+ if isinstance(string, bytes):
174
+ string += b'\n'
175
+ else:
176
+ string += '\n'
177
+ sys.stdout.buffer.write(string)
178
+ sys.stdout.flush()
179
+
180
+
181
+ def url_join(*url_parts):
182
+ """Joins URLs together using the POSIX join method.
183
+
184
+ Args:
185
+ url_parts: Sections of a URL to be joined.
186
+
187
+ Returns:
188
+ Joined URL.
189
+ """
190
+ return posixpath.join(*url_parts)
191
+
192
+
193
+ def gs_url_to_https(url):
194
+ """Converts |url| from a GCS URL (beginning with 'gs://') to an HTTPS one."""
195
+ return url_join(GCS_BASE_URL, remove_prefix(url, 'gs://'))
196
+
197
+
198
+ def remove_prefix(string, prefix):
199
+ """Returns |string| without the leading substring |prefix|."""
200
+ # Match behavior of removeprefix from python3.9:
201
+ # https://www.python.org/dev/peps/pep-0616/
202
+ if string.startswith(prefix):
203
+ return string[len(prefix):]
204
+
205
+ return string