Kitxuuu commited on
Commit
2fadd3e
·
verified ·
1 Parent(s): e1fab32

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-libxml2-delta-02/fuzz-tooling/docs/404.html +23 -0
  2. local-test-libxml2-delta-02/fuzz-tooling/docs/faq.md +237 -0
  3. local-test-libxml2-delta-02/fuzz-tooling/docs/ideal_integration.md +1 -0
  4. local-test-libxml2-delta-02/fuzz-tooling/docs/reproducing.md +1 -0
  5. local-test-libxml2-delta-02/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc +0 -0
  6. local-test-libxml2-delta-02/fuzz-tooling/infra/base-images/README.md +6 -0
  7. local-test-libxml2-delta-02/fuzz-tooling/infra/ci/requirements.txt +9 -0
  8. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/CHANGELOG +3 -0
  9. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py +60 -0
  10. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py +268 -0
  11. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/config_utils_test.py +200 -0
  12. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/continuous_integration.py +375 -0
  13. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/docker_test.py +119 -0
  14. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/filestore_utils.py +48 -0
  15. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/fuzz_target.py +408 -0
  16. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/logs.py +25 -0
  17. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/run_cifuzz.py +89 -0
  18. local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py +475 -0
  19. local-test-libxml2-delta-02/fuzz-tooling/infra/templates.py +119 -0
  20. local-test-libxml2-delta-02/fuzz-tooling/infra/uploader/Dockerfile +7 -0
local-test-libxml2-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-libxml2-delta-02/fuzz-tooling/docs/faq.md ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ layout: default
3
+ title: FAQ
4
+ nav_order: 7
5
+ permalink: /faq/
6
+ ---
7
+
8
+ # Frequently Asked Questions
9
+
10
+ - TOC
11
+ {:toc}
12
+ ---
13
+
14
+ ## Where can I learn more about fuzzing?
15
+
16
+ We recommend reading [libFuzzer tutorial] and the other docs in [google/fuzzing]
17
+ repository. These and some other resources are listed on the
18
+ [useful links]({{ site.baseurl }}/reference/useful-links/#tutorials) page.
19
+
20
+ [google/fuzzing]: https://github.com/google/fuzzing/tree/master/docs
21
+ [libFuzzer tutorial]: https://github.com/google/fuzzing/blob/master/tutorial/libFuzzerTutorial.md
22
+
23
+ ## What kind of projects are you accepting?
24
+
25
+ We accept established projects that have a critical impact on infrastructure and
26
+ user security. We will consider each request on a case-by-case basis, but some
27
+ things we keep in mind are:
28
+
29
+ - Exposure to remote attacks (e.g. libraries that are used to process
30
+ untrusted input).
31
+ - Number of users/other projects depending on this project.
32
+
33
+ We hope to relax this requirement in the future though, so keep an eye out even
34
+ if we are not able to accept your project at this time!
35
+
36
+ ## How can I find potential fuzz targets in my open source project?
37
+
38
+ You should look for places in your code that:
39
+
40
+ - consume un-trusted data from users or from the network.
41
+ - consume complex input data even if it's 'trusted'.
42
+ - use an algorithm that has two or more implementations
43
+ (to verify their equivalence).
44
+ - look for existing fuzz target [examples](https://github.com/google/oss-fuzz/tree/master/projects)
45
+ and find similarities.
46
+
47
+ ## Where can I store fuzz target sources and the build script if it's not yet accepted upstream?
48
+
49
+ Fuzz target sources as well as the build script may temporarily live inside the
50
+ `projects/<your_project>` directory in the OSS-Fuzz repository. Note that we do
51
+ not accept integrations that rely on forked repositories. Refer to the
52
+ [ideal integration guide] for the preferred long term solution.
53
+
54
+ ## My project is not open source. Can I use OSS-Fuzz?
55
+
56
+ You cannot use OSS-Fuzz, but you can use [ClusterFuzz] which OSS-Fuzz is based
57
+ on. ClusterFuzz is an open-source fuzzing infrastructure that you can deploy in
58
+ your own environment and run continuously at scale.
59
+
60
+ OSS-Fuzz is a production instance of ClusterFuzz, plus the code living in
61
+ [OSS-Fuzz repository]: build scripts, `project.yaml` files with contacts, etc.
62
+
63
+ [OSS-Fuzz repository]: https://github.com/google/oss-fuzz
64
+
65
+ ## Why do you use a [different issue tracker](https://bugs.chromium.org/p/oss-fuzz/issues/list) for reporting bugs in OSS projects?
66
+
67
+ Security access control is important for the kind of issues that OSS-Fuzz detects,
68
+ hence why by default issues are only opened on the OSS-Fuzz tracker.
69
+ You can opt-in to have them on Github as well by adding the `file_github_issue`
70
+ attribute to your `project.yaml` file. Note that this is only for visibility's
71
+ purpose, and that the actual details can be found by following the link to the
72
+ OSS-Fuzz tracker.
73
+
74
+ ## Why do you require a Google account for authentication?
75
+
76
+ Our [ClusterFuzz]({{ site.baseurl }}/further-reading/clusterfuzz) fuzzing
77
+ infrastructure and [issue tracker](https://bugs.chromium.org/p/oss-fuzz/issues/list)
78
+ require a Google account for authentication. Note that an alternate email
79
+ address associated with a Google account does not work due to appengine api
80
+ limitations.
81
+
82
+ ## Why do you use Docker?
83
+
84
+ Building fuzzers requires building your project with a fresh Clang compiler and
85
+ special compiler flags. An easy-to-use Docker image is provided to simplify
86
+ toolchain distribution. This also simplifies our support for a variety of Linux
87
+ distributions and provides a reproducible environment for fuzzer
88
+ building and execution.
89
+
90
+ ## How do you handle timeouts and OOMs?
91
+
92
+ If a single input to a [fuzz target]({{ site.baseurl }}/reference/glossary/#fuzz-target)
93
+ requires more than **~25 seconds** or more than **2.5GB RAM** to process, we
94
+ report this as a timeout or an OOM (out-of-memory) bug
95
+ (examples: [timeouts](https://bugs.chromium.org/p/oss-fuzz/issues/list?can=1&q=%22Crash+Type%3A+Timeout%22),
96
+ [OOMs](https://bugs.chromium.org/p/oss-fuzz/issues/list?can=1&q="Crash+Type%3A+Out-of-memory")).
97
+ This may or may not be considered as a real bug by the project owners,
98
+ but nevertheless we treat all timeouts and OOMs as bugs
99
+ since they significantly reduce the efficiency of fuzzing.
100
+
101
+ Remember that fuzzing is executed with AddressSanitizer or other
102
+ sanitizers which introduces a certain overhead in RAM and CPU.
103
+
104
+ We currently do not have a good way to deduplicate timeout or OOM bugs.
105
+ So, we report only one timeout and only one OOM bug per fuzz target.
106
+ Once that bug is fixed, we will file another one, and so on.
107
+
108
+ Currently we do not offer ways to change the memory and time limits.
109
+
110
+ ## Can I launch an additional process (e.g. a daemon) from my fuzz target?
111
+
112
+ No. In order to get all the benefits of in-process, coverage-guided fuzz testing,
113
+ it is required to run everything inside a single process. Any child processes
114
+ created outside the main process introduces heavy launch overhead and is not
115
+ monitored for code coverage.
116
+
117
+ Another rule of thumb is: "the smaller fuzz target is, the better it is". It is
118
+ expected that your project will have many fuzz targets to test different
119
+ components, instead of a single fuzz target trying to cover everything.
120
+ Think of fuzz target as a unit test, though it is much more powerful since it
121
+ helps to test millions of data permutations rather than just one.
122
+
123
+ ## What if my fuzz target finds a bug in another project (dependency) ?
124
+
125
+ Every bug report has a crash stack-trace that shows where the crash happened.
126
+ Using that, you can debug the root cause and see which category the bug falls in:
127
+
128
+ - If this is a bug is due to an incorrect usage of the dependent project's API
129
+ in your project, then you need to fix your usage to call the API correctly.
130
+ - If this is a real bug in the dependent project, then you should CC the
131
+ maintainers of that project on the bug. Once CCed, they will get automatic
132
+ access to all the information necessary to reproduce the issue. If this project
133
+ is maintained in OSS-Fuzz, you can search for contacts in the respective
134
+ project.yaml file.
135
+
136
+ ## What if my fuzzer does not find anything?
137
+
138
+ If your fuzz target is running for many days and does not find bugs or new
139
+ coverage, it may mean several things:
140
+ - We've covered all reachable code. In order to cover more code we need more
141
+ fuzz targets.
142
+ - The [seed corpus]({{ site.baseurl }}/getting-started/new-project-guide#seed-corpus) is not good enough and the
143
+ fuzzing engine(s) are not able to go deeper based on the existing seeds.
144
+ Need to add more seeds.
145
+ - There is some crypto/crc stuff in the code that will prevent any fuzzing
146
+ engine from going deeper, in which case the crypto should be disabled in
147
+ [fuzzing mode](https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode).
148
+ Examples: [openssl](https://github.com/openssl/openssl/tree/master/fuzz#reproducing-issues),
149
+ [boringssl](https://boringssl.googlesource.com/boringssl/+/HEAD/FUZZING.md#Fuzzer-mode)
150
+ - It is also possible that the fuzzer is running too slow
151
+ (you may check the speed of your targets at https://oss-fuzz.com/)
152
+
153
+ In either case, look at the
154
+ [coverage reports]({{ site.baseurl }}/further-reading/clusterfuzz#coverage-reports)
155
+ for your target(s) and figure out why some parts of the code are not covered.
156
+
157
+ ## What if my fuzzer does not find new coverage or bugs after a while?
158
+
159
+ It is common for fuzzers to plateau and stop finding new coverage or bugs.
160
+ [Fuzz Introspector](https://github.com/ossf/fuzz-introspector) helps you
161
+ evaluate your fuzzers' performance.
162
+ It can help you identify bottlenecks causing your fuzzers to plateau.
163
+ It provides aggregated and individual fuzzer reachability and coverage reports.
164
+ Developers can either introduce a new fuzz target or modify an existing one to
165
+ reach previously unreachable code.
166
+ Here are
167
+ [case studies](https://github.com/ossf/fuzz-introspector/blob/main/doc/CaseStudies.md)
168
+ where Fuzz Introspector helped developers improve fuzzing of a project.
169
+ Fuzz Introspector reports are available on the [OSS-Fuzz homepage](https://oss-fuzz.com/)
170
+ or through this [index](http://oss-fuzz-introspector.storage.googleapis.com/index.html).
171
+
172
+ Developers can also use Fuzz Introspector on their local machines.
173
+ Detailed instructions are available
174
+ [here](https://github.com/ossf/fuzz-introspector/tree/main/oss_fuzz_integration#build-fuzz-introspector-with-oss-fuzz).
175
+
176
+ ## Why are code coverage reports public?
177
+
178
+ We work with open source projects and try to keep as much information public as
179
+ possible. We believe that public code coverage reports do not put users at risk,
180
+ as they do not indicate the presence of bugs or lack thereof.
181
+
182
+ ## Why is the coverage command complaining about format compatibility issues?
183
+
184
+ This may happen if the Docker images fetched locally become out of sync. Make
185
+ sure you run the following command to pull the most recent images:
186
+
187
+ ```bash
188
+ $ python infra/helper.py pull_images
189
+ ```
190
+
191
+ Please refer to
192
+ [code coverage]({{ site.baseurl }}/advanced-topics/code-coverage/) for detailed
193
+ information on code coverage generation.
194
+
195
+ ## What happens when I rename a fuzz target ?
196
+
197
+ If you rename your fuzz targets, the existing bugs for those targets will get
198
+ closed and fuzzing will start from scratch from a fresh corpora
199
+ (seed corpus only). Similar corpora will get accumulated over time depending on
200
+ the number of cpu cycles that original fuzz target has run. If this is not
201
+ desirable, make sure to copy the accumulated corpora from the original fuzz
202
+ target (instructions to download
203
+ [here]({{ site.baseurl }}/advanced-topics/corpora/#downloading-the-corpus)) and
204
+ restore it to the new GCS location later (instruction to find the
205
+ new location [here]({{ site.baseurl }}/advanced-topics/corpora/#viewing-the-corpus-for-a-fuzz-target)).
206
+
207
+ ## Does OSS-Fuzz support AFL or honggfuzz or Centipede?
208
+
209
+ OSS-Fuzz *uses* the following
210
+ [fuzzing engines]({{ site.baseurl }}/reference/glossary/#fuzzing-engine):
211
+
212
+ 1. [libFuzzer](https://llvm.org/docs/LibFuzzer.html).
213
+ 1. [AFL++](https://github.com/AFLplusplus/AFLplusplus), an improved and
214
+ well-maintained version of [AFL](https://lcamtuf.coredump.cx/afl/).
215
+ 1. [Honggfuzz](https://github.com/google/honggfuzz).
216
+ 1. [Centipede (Experimental)](https://github.com/google/centipede).
217
+
218
+ Follow the [new project guide] and OSS-Fuzz will use all its fuzzing engines
219
+ on your code.
220
+
221
+ ## What are the specs on your machines?
222
+
223
+ OSS-Fuzz builders have 32CPU/28.8GB RAM.
224
+
225
+ Fuzzing machines only have a single core and fuzz targets should not use more
226
+ than 2.5GB of RAM.
227
+
228
+ ## Are there any restrictions on using test cases / corpora generated by OSS-Fuzz?
229
+
230
+ No, you can freely use (i.e. share, add to your repo, etc.) the test cases and
231
+ corpora generated by OSS-Fuzz. OSS-Fuzz infrastructure is fully open source
232
+ (including [ClusterFuzz], various fuzzing engines, and other dependencies). We
233
+ have no intent to restrict the use of the artifacts produced by OSS-Fuzz.
234
+
235
+ [ClusterFuzz]: https://github.com/google/clusterfuzz
236
+ [new project guide]: {{ site.baseurl }}/getting-started/new-project-guide/
237
+ [ideal integration guide]: {{ site.baseurl }}/getting-started/new-project-guide/
local-test-libxml2-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-libxml2-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-libxml2-delta-02/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc ADDED
Binary file (3.04 kB). View file
 
local-test-libxml2-delta-02/fuzz-tooling/infra/base-images/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Building all infra images:
2
+
3
+ ```bash
4
+ # run from project root
5
+ infra/base-images/all.sh
6
+ ```
local-test-libxml2-delta-02/fuzz-tooling/infra/ci/requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Requirements for submitting code changes to infra/ (needed by presubmit.py).
2
+ parameterized==0.7.4
3
+ pyfakefs==4.5.6
4
+ pylint==2.5.3
5
+ pytest==7.1.2
6
+ pytest-xdist==2.5.0
7
+ PyYAML==6.0
8
+ requests==2.31.0
9
+ yapf==0.32.0
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/CHANGELOG ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Next Release:
2
+
3
+ Improve detection of changed files better by fixing https://github.com/google/oss-fuzz/issues/7011
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Builds a specific OSS-Fuzz project's fuzzers for CI tools."""
15
+ import logging
16
+ import sys
17
+
18
+ import build_fuzzers
19
+ import logs
20
+ import config_utils
21
+
22
+ # pylint: disable=c-extension-no-member
23
+ # pylint gets confused because of the relative import of cifuzz.
24
+
25
+ logs.init()
26
+
27
+
28
+ def build_fuzzers_entrypoint():
29
+ """Builds OSS-Fuzz project's fuzzers for CI tools."""
30
+ config = config_utils.BuildFuzzersConfig()
31
+
32
+ if config.dry_run:
33
+ # Sets the default return code on error to success.
34
+ returncode = 0
35
+ else:
36
+ # The default return code when an error occurs.
37
+ returncode = 1
38
+
39
+ if not build_fuzzers.build_fuzzers(config):
40
+ logging.error('Error building fuzzers for (commit: %s, pr_ref: %s).',
41
+ config.git_sha, config.pr_ref)
42
+ return returncode
43
+
44
+ return 0
45
+
46
+
47
+ def main():
48
+ """Builds OSS-Fuzz project's fuzzers for CI tools.
49
+
50
+ Note: The resulting fuzz target binaries of this build are placed in
51
+ the directory: ${GITHUB_WORKSPACE}/out
52
+
53
+ Returns:
54
+ 0 on success or nonzero on failure.
55
+ """
56
+ return build_fuzzers_entrypoint()
57
+
58
+
59
+ if __name__ == '__main__':
60
+ sys.exit(main())
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for clusterfuzz_deployment.py"""
15
+
16
+ import os
17
+ import unittest
18
+ from unittest import mock
19
+
20
+ import parameterized
21
+ from pyfakefs import fake_filesystem_unittest
22
+
23
+ import clusterfuzz_deployment
24
+ import config_utils
25
+ import test_helpers
26
+ import workspace_utils
27
+
28
+ # NOTE: This integration test relies on
29
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
30
+ EXAMPLE_PROJECT = 'example'
31
+
32
+ # An example fuzzer that triggers an error.
33
+ EXAMPLE_FUZZER = 'example_crash_fuzzer'
34
+
35
+ WORKSPACE = '/workspace'
36
+ EXPECTED_LATEST_BUILD_PATH = os.path.join(WORKSPACE, 'cifuzz-prev-build')
37
+
38
+ # pylint: disable=unused-argument
39
+
40
+
41
+ def _create_config(**kwargs):
42
+ """Creates a config object and then sets every attribute that is a key in
43
+ |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an
44
+ attribute of Config."""
45
+ defaults = {
46
+ 'cfl_platform': 'github',
47
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT,
48
+ 'workspace': WORKSPACE,
49
+ }
50
+ for default_key, default_value in defaults.items():
51
+ if default_key not in kwargs:
52
+ kwargs[default_key] = default_value
53
+
54
+ return test_helpers.create_run_config(**kwargs)
55
+
56
+
57
+ def _create_deployment(**kwargs):
58
+ config = _create_config(**kwargs)
59
+ workspace = workspace_utils.Workspace(config)
60
+ return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace)
61
+
62
+
63
+ class OSSFuzzTest(fake_filesystem_unittest.TestCase):
64
+ """Tests OSSFuzz."""
65
+
66
+ def setUp(self):
67
+ self.setUpPyfakefs()
68
+ self.deployment = _create_deployment()
69
+ self.corpus_dir = os.path.join(self.deployment.workspace.corpora,
70
+ EXAMPLE_FUZZER)
71
+
72
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=True)
73
+ def test_download_corpus(self, mock_download_and_unpack_zip):
74
+ """Tests that we can download a corpus for a valid project."""
75
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
76
+ expected_url = ('https://storage.googleapis.com/example-backup.'
77
+ 'clusterfuzz-external.appspot.com/corpus/libFuzzer/'
78
+ 'example_crash_fuzzer/public.zip')
79
+ call_args, _ = mock_download_and_unpack_zip.call_args
80
+ self.assertEqual(call_args, (expected_url, self.corpus_dir))
81
+ self.assertTrue(os.path.exists(self.corpus_dir))
82
+
83
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=False)
84
+ def test_download_corpus_fail(self, _):
85
+ """Tests that when downloading fails, an empty corpus directory is still
86
+ returned."""
87
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
88
+ self.assertEqual(os.listdir(self.corpus_dir), [])
89
+
90
+ def test_get_latest_build_name(self):
91
+ """Tests that the latest build name can be retrieved from GCS."""
92
+ latest_build_name = self.deployment.get_latest_build_name()
93
+ self.assertTrue(latest_build_name.endswith('.zip'))
94
+ self.assertTrue('address' in latest_build_name)
95
+
96
+ @parameterized.parameterized.expand([
97
+ ('upload_build', ('commit',),
98
+ 'Not uploading latest build because on OSS-Fuzz.'),
99
+ ('upload_corpus', ('target', 'corpus-dir'),
100
+ 'Not uploading corpus because on OSS-Fuzz.'),
101
+ ('upload_crashes', tuple(), 'Not uploading crashes because on OSS-Fuzz.'),
102
+ ])
103
+ def test_noop_methods(self, method, method_args, expected_message):
104
+ """Tests that certain methods are noops for OSS-Fuzz."""
105
+ with mock.patch('logging.info') as mock_info:
106
+ method = getattr(self.deployment, method)
107
+ self.assertIsNone(method(*method_args))
108
+ mock_info.assert_called_with(expected_message)
109
+
110
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=True)
111
+ def test_download_latest_build(self, mock_download_and_unpack_zip):
112
+ """Tests that downloading the latest build works as intended under normal
113
+ circumstances."""
114
+ self.assertEqual(self.deployment.download_latest_build(),
115
+ EXPECTED_LATEST_BUILD_PATH)
116
+ expected_url = ('https://storage.googleapis.com/clusterfuzz-builds/example/'
117
+ 'example-address-202008030600.zip')
118
+ mock_download_and_unpack_zip.assert_called_with(expected_url,
119
+ EXPECTED_LATEST_BUILD_PATH)
120
+
121
+ @mock.patch('http_utils.download_and_unpack_zip', return_value=False)
122
+ def test_download_latest_build_fail(self, _):
123
+ """Tests that download_latest_build returns None when it fails to download a
124
+ build."""
125
+ self.assertIsNone(self.deployment.download_latest_build())
126
+
127
+
128
+ class ClusterFuzzLiteTest(fake_filesystem_unittest.TestCase):
129
+ """Tests for ClusterFuzzLite."""
130
+
131
+ def setUp(self):
132
+ self.setUpPyfakefs()
133
+ self.deployment = _create_deployment(mode='batch',
134
+ oss_fuzz_project_name='',
135
+ cloud_bucket='gs://bucket')
136
+ self.corpus_dir = os.path.join(self.deployment.workspace.corpora,
137
+ EXAMPLE_FUZZER)
138
+
139
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus',
140
+ return_value=True)
141
+ def test_download_corpus(self, mock_download_corpus):
142
+ """Tests that download_corpus works for a valid project."""
143
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
144
+ mock_download_corpus.assert_called_with('example_crash_fuzzer',
145
+ self.corpus_dir)
146
+ self.assertTrue(os.path.exists(self.corpus_dir))
147
+
148
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus',
149
+ side_effect=Exception)
150
+ def test_download_corpus_fail(self, _):
151
+ """Tests that when downloading fails, an empty corpus directory is still
152
+ returned."""
153
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
154
+ self.assertEqual(os.listdir(self.corpus_dir), [])
155
+
156
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build',
157
+ side_effect=[False, True])
158
+ @mock.patch('repo_manager.RepoManager.get_commit_list',
159
+ return_value=['commit1', 'commit2'])
160
+ @mock.patch('continuous_integration.GithubCiMixin.repo_dir',
161
+ return_value='/path/to/repo')
162
+ def test_download_latest_build(self, mock_repo_dir, mock_get_commit_list,
163
+ mock_download_build):
164
+ """Tests that downloading the latest build works as intended under normal
165
+ circumstances."""
166
+ self.assertEqual(self.deployment.download_latest_build(),
167
+ EXPECTED_LATEST_BUILD_PATH)
168
+ expected_artifact_name = 'address-commit2'
169
+ mock_download_build.assert_called_with(expected_artifact_name,
170
+ EXPECTED_LATEST_BUILD_PATH)
171
+
172
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build',
173
+ side_effect=Exception)
174
+ @mock.patch('repo_manager.RepoManager.get_commit_list',
175
+ return_value=['commit1', 'commit2'])
176
+ @mock.patch('continuous_integration.GithubCiMixin.repo_dir',
177
+ return_value='/path/to/repo')
178
+ def test_download_latest_build_fail(self, mock_repo_dir, mock_get_commit_list,
179
+ _):
180
+ """Tests that download_latest_build returns None when it fails to download a
181
+ build."""
182
+ self.assertIsNone(self.deployment.download_latest_build())
183
+
184
+ @mock.patch('filestore.github_actions.GithubActionsFilestore.upload_build')
185
+ def test_upload_build(self, mock_upload_build):
186
+ """Tests that upload_build works as intended."""
187
+ self.deployment.upload_build('commit')
188
+ mock_upload_build.assert_called_with('address-commit',
189
+ '/workspace/build-out')
190
+
191
+
192
+ class NoClusterFuzzDeploymentTest(fake_filesystem_unittest.TestCase):
193
+ """Tests for NoClusterFuzzDeployment."""
194
+
195
+ def setUp(self):
196
+ self.setUpPyfakefs()
197
+ config = test_helpers.create_run_config(workspace=WORKSPACE,
198
+ cfl_platform='other',
199
+ filestore='no_filestore',
200
+ no_clusterfuzz_deployment=True)
201
+ workspace = workspace_utils.Workspace(config)
202
+ self.deployment = clusterfuzz_deployment.get_clusterfuzz_deployment(
203
+ config, workspace)
204
+
205
+ self.corpus_dir = os.path.join(workspace.corpora, EXAMPLE_FUZZER)
206
+
207
+ @mock.patch('logging.info')
208
+ def test_download_corpus(self, mock_info):
209
+ """Tests that download corpus returns the path to the empty corpus
210
+ directory."""
211
+ self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir)
212
+ mock_info.assert_called_with(
213
+ 'Not downloading corpus because no ClusterFuzz deployment.')
214
+ self.assertTrue(os.path.exists(self.corpus_dir))
215
+
216
+ @parameterized.parameterized.expand([
217
+ ('upload_build', ('commit',),
218
+ 'Not uploading latest build because no ClusterFuzz deployment.'),
219
+ ('upload_corpus', ('target', 'corpus-dir'),
220
+ 'Not uploading corpus because no ClusterFuzz deployment.'),
221
+ ('upload_crashes', tuple(),
222
+ 'Not uploading crashes because no ClusterFuzz deployment.'),
223
+ ('download_latest_build', tuple(),
224
+ 'Not downloading latest build because no ClusterFuzz deployment.')
225
+ ])
226
+ def test_noop_methods(self, method, method_args, expected_message):
227
+ """Tests that certain methods are noops for NoClusterFuzzDeployment."""
228
+ with mock.patch('logging.info') as mock_info:
229
+ method = getattr(self.deployment, method)
230
+ self.assertIsNone(method(*method_args))
231
+ mock_info.assert_called_with(expected_message)
232
+
233
+
234
+ class GetClusterFuzzDeploymentTest(unittest.TestCase):
235
+ """Tests for get_clusterfuzz_deployment."""
236
+
237
+ def setUp(self):
238
+ test_helpers.patch_environ(self)
239
+ os.environ['GITHUB_REPOSITORY'] = 'owner/myproject'
240
+
241
+ @parameterized.parameterized.expand([
242
+ (config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI,
243
+ clusterfuzz_deployment.OSSFuzz),
244
+ (config_utils.BaseConfig.Platform.INTERNAL_GITHUB,
245
+ clusterfuzz_deployment.OSSFuzz),
246
+ (config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI,
247
+ clusterfuzz_deployment.ClusterFuzzLite),
248
+ (config_utils.BaseConfig.Platform.EXTERNAL_GITHUB,
249
+ clusterfuzz_deployment.ClusterFuzzLite),
250
+ ])
251
+ def test_get_clusterfuzz_deployment(self, platform, expected_deployment_cls):
252
+ """Tests that get_clusterfuzz_deployment returns the correct value."""
253
+ with mock.patch('config_utils.BaseConfig.platform',
254
+ return_value=platform,
255
+ new_callable=mock.PropertyMock):
256
+ with mock.patch('filestore_utils.get_filestore', return_value=None):
257
+ with mock.patch('platform_config.github._get_event_data',
258
+ return_value={}):
259
+ config = _create_config()
260
+ workspace = workspace_utils.Workspace(config)
261
+
262
+ self.assertIsInstance(
263
+ clusterfuzz_deployment.get_clusterfuzz_deployment(
264
+ config, workspace), expected_deployment_cls)
265
+
266
+
267
+ if __name__ == '__main__':
268
+ unittest.main()
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/config_utils_test.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for config_utils."""
15
+ import os
16
+ import unittest
17
+ from unittest import mock
18
+
19
+ import config_utils
20
+ import constants
21
+ import test_helpers
22
+
23
+ # pylint: disable=no-self-use,protected-access
24
+
25
+
26
+ class BaseConfigTest(unittest.TestCase):
27
+ """Tests for BaseConfig."""
28
+
29
+ def setUp(self):
30
+ test_helpers.patch_environ(self)
31
+
32
+ def _create_config(self):
33
+ return config_utils.BuildFuzzersConfig()
34
+
35
+ def test_language_default(self):
36
+ """Tests that the correct default language is set."""
37
+ config = self._create_config()
38
+ self.assertEqual(config.language, 'c++')
39
+
40
+ def test_language(self):
41
+ """Tests that the correct language is set."""
42
+ language = 'python'
43
+ os.environ['LANGUAGE'] = language
44
+ config = self._create_config()
45
+ self.assertEqual(config.language, language)
46
+
47
+ def test_is_coverage(self):
48
+ """Tests that is_coverage is set correctly."""
49
+ # Test it is set when it is supposed to be.
50
+ os.environ['SANITIZER'] = 'coverage'
51
+ config = self._create_config()
52
+ self.assertTrue(config.is_coverage)
53
+
54
+ # Test it is not set when it is not supposed to be.
55
+ os.environ['SANITIZER'] = 'address'
56
+ config = self._create_config()
57
+ self.assertFalse(config.is_coverage)
58
+
59
+ @mock.patch('logging.error')
60
+ def test_validate_no_workspace(self, mock_error):
61
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
62
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
63
+ config = self._create_config()
64
+ self.assertFalse(config.validate())
65
+ mock_error.assert_called_with('Must set WORKSPACE.')
66
+
67
+ @mock.patch('logging.error')
68
+ def test_validate_invalid_language(self, mock_error):
69
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
70
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
71
+ os.environ['WORKSPACE'] = '/workspace'
72
+ os.environ['LANGUAGE'] = 'invalid-language'
73
+ config = self._create_config()
74
+ self.assertFalse(config.validate())
75
+ mock_error.assert_called_with('Invalid LANGUAGE: %s. Must be one of: %s.',
76
+ os.environ['LANGUAGE'], constants.LANGUAGES)
77
+
78
+ @mock.patch('logging.error')
79
+ def test_validate_invalid_sanitizer(self, mock_error):
80
+ """Tests that validate returns False if GITHUB_WORKSPACE isn't set."""
81
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
82
+ os.environ['WORKSPACE'] = '/workspace'
83
+ os.environ['SANITIZER'] = 'invalid-sanitizer'
84
+ config = self._create_config()
85
+ self.assertFalse(config.validate())
86
+ mock_error.assert_called_with('Invalid SANITIZER: %s. Must be one of: %s.',
87
+ os.environ['SANITIZER'],
88
+ config_utils.SANITIZERS)
89
+
90
+ def test_validate(self):
91
+ """Tests that validate returns True if config is valid."""
92
+ os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example'
93
+ os.environ['WORKSPACE'] = '/workspace'
94
+ os.environ['REPOSITORY'] = 'repo'
95
+ config = self._create_config()
96
+ self.assertTrue(config.validate())
97
+
98
+
99
+ class BuildFuzzersConfigTest(unittest.TestCase):
100
+ """Tests for BuildFuzzersConfig."""
101
+
102
+ def setUp(self):
103
+ test_helpers.patch_environ(self)
104
+
105
+ def _create_config(self):
106
+ return config_utils.BuildFuzzersConfig()
107
+
108
+ @mock.patch('platform_config.github._get_event_data', return_value={})
109
+ def test_github_base_ref(self, _):
110
+ """Tests that base_ref is set properly."""
111
+ expected_base_ref = 'expected_base_ref'
112
+ os.environ['GITHUB_BASE_REF'] = expected_base_ref
113
+ os.environ['CFL_PLATFORM'] = 'github'
114
+ os.environ['GITHUB_REPOSITORY'] = 'owner/repo'
115
+ config = self._create_config()
116
+ self.assertEqual(config.base_ref, expected_base_ref)
117
+
118
+ def test_base_ref(self):
119
+ """Tests that base_ref is set properly."""
120
+ expected_base_ref = 'expected_base_ref'
121
+ os.environ['GIT_BASE_REF'] = expected_base_ref
122
+ config = self._create_config()
123
+ self.assertEqual(config.base_ref, expected_base_ref)
124
+
125
+ def test_keep_unaffected_defaults_to_true(self):
126
+ """Tests that keep_unaffected_fuzz_targets defaults to true."""
127
+ config = self._create_config()
128
+ self.assertTrue(config.keep_unaffected_fuzz_targets)
129
+
130
+ def test_keep_unaffected_defaults_to_false_when_pr(self):
131
+ """Tests that keep_unaffected_fuzz_targets defaults to false when from a
132
+ pr."""
133
+ os.environ['GIT_BASE_REF'] = 'base-ref'
134
+ config = self._create_config()
135
+ self.assertFalse(config.keep_unaffected_fuzz_targets)
136
+
137
+
138
+ class RunFuzzersConfigTest(unittest.TestCase):
139
+ """Tests for RunFuzzersConfig."""
140
+
141
+ def setUp(self):
142
+ test_helpers.patch_environ(self)
143
+
144
+ def _create_config(self):
145
+ return config_utils.RunFuzzersConfig()
146
+
147
+ def test_coverage(self):
148
+ """Tests that mode is overriden properly based on is_coverage."""
149
+ # Test that it is overriden when it is supposed to be.
150
+ os.environ['SANITIZER'] = 'coverage'
151
+ os.environ['MODE'] = 'code-change'
152
+ config = self._create_config()
153
+ self.assertEqual(config.mode, 'coverage')
154
+
155
+ # Test that it isn't overriden when it isn't supposed to be.
156
+ os.environ['SANITIZER'] = 'address'
157
+ mode = 'code-change'
158
+ os.environ['MODE'] = mode
159
+ config = self._create_config()
160
+ self.assertEqual(config.mode, mode)
161
+
162
+ def test_run_config_validate(self):
163
+ """Tests that _run_config_validate returns True when the config is valid."""
164
+ self.assertTrue(self._create_config()._run_config_validate())
165
+
166
+ @mock.patch('logging.error')
167
+ def test_run_config_invalid_mode(self, mock_error):
168
+ """Tests that _run_config_validate returns False when mode is invalid."""
169
+ fake_mode = 'fake-mode'
170
+ os.environ['MODE'] = fake_mode
171
+ self.assertFalse(self._create_config()._run_config_validate())
172
+ mock_error.assert_called_with('Invalid MODE: %s. Must be one of %s.',
173
+ fake_mode,
174
+ config_utils.RunFuzzersConfig.MODES)
175
+
176
+
177
+ class GetSanitizerTest(unittest.TestCase):
178
+ """Tests for _get_sanitizer."""
179
+
180
+ def setUp(self):
181
+ test_helpers.patch_environ(self)
182
+ self.sanitizer = 'memory'
183
+
184
+ def test_default_value(self):
185
+ """Tests that the default value returned by _get_sanitizer is correct."""
186
+ self.assertEqual(config_utils._get_sanitizer(), 'address')
187
+
188
+ def test_normal_case(self):
189
+ """Tests that _get_sanitizer returns the correct value in normal cases."""
190
+ os.environ['SANITIZER'] = self.sanitizer
191
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
192
+
193
+ def test_capitalization(self):
194
+ """Tests that that _get_sanitizer handles capitalization properly."""
195
+ os.environ['SANITIZER'] = self.sanitizer.upper()
196
+ self.assertEqual(config_utils._get_sanitizer(), self.sanitizer)
197
+
198
+
199
+ if __name__ == '__main__':
200
+ unittest.main()
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/continuous_integration.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Implementations for various CI systems."""
15
+
16
+ import os
17
+ import collections
18
+ import sys
19
+ import logging
20
+
21
+ # pylint: disable=wrong-import-position,import-error
22
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
23
+ import build_specified_commit
24
+ import docker
25
+ import helper
26
+ import repo_manager
27
+ import retry
28
+ import utils
29
+ import workspace_utils
30
+
31
+ # pylint: disable=too-few-public-methods
32
+
33
+ BuildPreparationResult = collections.namedtuple(
34
+ 'BuildPreparationResult', ['success', 'image_repo_path', 'repo_manager'])
35
+
36
+ _IMAGE_BUILD_TRIES = 3
37
+ _IMAGE_BUILD_BACKOFF = 2
38
+
39
+
40
+ def fix_git_repo_for_diff(repo_manager_obj):
41
+ """Fixes git repos cloned by the "checkout" action so that diffing works on
42
+ them."""
43
+ command = [
44
+ 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD',
45
+ 'refs/remotes/origin/master'
46
+ ]
47
+ return utils.execute(command, location=repo_manager_obj.repo_dir)
48
+
49
+
50
+ class BaseCi:
51
+ """Class representing common CI functionality."""
52
+
53
+ def __init__(self, config):
54
+ self.config = config
55
+ self.workspace = workspace_utils.Workspace(config)
56
+ self._repo_dir = None
57
+
58
+ @property
59
+ def repo_dir(self):
60
+ """Returns the source repo path, if it has been checked out. None is
61
+ returned otherwise."""
62
+ raise NotImplementedError('Child class must implement method.')
63
+
64
+ def prepare_for_fuzzer_build(self):
65
+ """Builds the fuzzer builder image and gets the source code we need to
66
+ fuzz."""
67
+ raise NotImplementedError('Child class must implement method.')
68
+
69
+ def get_diff_base(self):
70
+ """Returns the base to diff against with git to get the change under
71
+ test."""
72
+ if self.config.base_ref:
73
+ logging.debug('Diffing against base_ref: %s.', self.config.base_ref)
74
+ return self.config.base_ref
75
+ if self.config.base_commit:
76
+ logging.debug('Diffing against base_commit: %s.', self.config.base_commit)
77
+ return self.config.base_commit
78
+ # TODO(metzman): Do we want this at all? What purpose does it serve? I guess
79
+ # it is a decent fallback when there is no base_commit or base_ref.
80
+ logging.debug('Diffing against origin.')
81
+ return 'origin'
82
+
83
+ def get_changed_code_under_test(self, repo_manager_obj):
84
+ """Returns the changed files that need to be tested."""
85
+ if self.config.base_ref:
86
+ repo_manager_obj.fetch_branch(self.config.base_ref)
87
+ fix_git_repo_for_diff(repo_manager_obj)
88
+ base = self.get_diff_base()
89
+ logging.info('Diffing against %s.', base)
90
+ # git diff <commit>... is equivalent to
91
+ # git diff $(git merge-base <commit> HEAD)
92
+ return repo_manager_obj.get_git_diff(base + '...')
93
+
94
+ def get_build_command(self, host_repo_path, image_repo_path):
95
+ """Returns the command for building the project that is run inside the
96
+ project builder container."""
97
+ raise NotImplementedError('Child class must implement method.')
98
+
99
+ def _build_external_project_docker_image(self, manager):
100
+ """Helper for child classes that builds an external project's docker image.
101
+ Returns a BuildPreparationResult indicating failure or success."""
102
+ build_integration_abs_path = os.path.join(
103
+ manager.repo_dir, self.config.build_integration_path)
104
+ if not build_external_project_docker_image(manager.repo_dir,
105
+ build_integration_abs_path):
106
+ logging.error('Failed to build external project.')
107
+ return get_build_preparation_failure()
108
+ image_repo_path = os.path.join('/src', self.config.project_repo_name)
109
+ return BuildPreparationResult(success=True,
110
+ image_repo_path=image_repo_path,
111
+ repo_manager=manager)
112
+
113
+ def _make_repo_storage_dir(self):
114
+ os.makedirs(self.workspace.repo_storage, exist_ok=True)
115
+
116
+ def _clone_repo_and_checkout(self, repo_url, repo_name):
117
+ """Helper for child classes that clones the git repo specified by |repo_url|
118
+ to |repo_name|, checks out the specified commit, and returns the
119
+ |manager|."""
120
+ self._make_repo_storage_dir()
121
+ # Checkout project's repo in the shared volume.
122
+ manager = repo_manager.clone_repo_and_get_manager(
123
+ repo_url,
124
+ self.workspace.repo_storage,
125
+ repo_name=repo_name,
126
+ username=self.config.actor,
127
+ password=self.config.token)
128
+ self._checkout_specified_commit(manager)
129
+ return manager
130
+
131
+ def _checkout_specified_commit(self, manager):
132
+ checkout_specified_commit(manager, self.config.pr_ref, self.config.git_sha)
133
+
134
+ def _detect_main_repo(self):
135
+ """Helper for child classes that detects the main repo and returns a tuple
136
+ containing the inffered url and path to the repo in the image."""
137
+ inferred_url, image_repo_path = build_specified_commit.detect_main_repo(
138
+ self.config.oss_fuzz_project_name,
139
+ repo_name=self.config.project_repo_name)
140
+ if not inferred_url or not image_repo_path:
141
+ logging.error('Could not detect repo.')
142
+ return inferred_url, image_repo_path
143
+
144
+ def _create_repo_manager_for_project_src_path(self):
145
+ """Returns a repo manager for |project_src_path|."""
146
+ return repo_manager.RepoManager(self.config.project_src_path)
147
+
148
+
149
+ def get_build_command():
150
+ """Returns the command to build the project inside the project builder
151
+ container."""
152
+ return 'compile'
153
+
154
+
155
+ def get_replace_repo_and_build_command(host_repo_path, image_repo_path):
156
+ """Returns the command to replace the repo located at |image_repo_path| with
157
+ |host_repo_path| and build the project inside the project builder
158
+ container."""
159
+ rm_path = os.path.join(image_repo_path, '*')
160
+ image_src_path = os.path.dirname(image_repo_path)
161
+ build_command = get_build_command()
162
+ command = (f'cd / && rm -rf {rm_path} && cp -r {host_repo_path} '
163
+ f'{image_src_path} && cd - && {build_command}')
164
+ return command
165
+
166
+
167
+ def get_ci(config):
168
+ """Determines what kind of CI is being used and returns the object
169
+ representing that system."""
170
+
171
+ if config.platform == config.Platform.EXTERNAL_GENERIC_CI:
172
+ # Non-OSS-Fuzz projects must bring their own source and their own build
173
+ # integration (which is relative to that source).
174
+ return ExternalGeneric(config)
175
+ if config.platform == config.Platform.EXTERNAL_GITHUB:
176
+ # Non-OSS-Fuzz projects must bring their own source and their own build
177
+ # integration (which is relative to that source).
178
+ return ExternalGithub(config)
179
+
180
+ if config.platform == config.Platform.INTERNAL_GENERIC_CI:
181
+ # Builds of OSS-Fuzz projects not hosted on Github must bring their own
182
+ # source since the checkout logic CIFuzz implements is github-specific.
183
+ # TODO(metzman): Consider moving Github-actions builds of OSS-Fuzz projects
184
+ # to this system to reduce implementation complexity.
185
+ return InternalGeneric(config)
186
+
187
+ return InternalGithub(config)
188
+
189
+
190
+ def checkout_specified_commit(repo_manager_obj, pr_ref, git_sha):
191
+ """Checks out the specified commit or pull request using
192
+ |repo_manager_obj|."""
193
+ try:
194
+ if pr_ref:
195
+ repo_manager_obj.checkout_pr(pr_ref)
196
+ else:
197
+ repo_manager_obj.checkout_commit(git_sha)
198
+ except (RuntimeError, ValueError):
199
+ logging.error(
200
+ 'Can not check out requested state %s. '
201
+ 'Using current repo state.', pr_ref or git_sha)
202
+
203
+
204
+ class GithubCiMixin:
205
+ """Mixin for Github based CI systems."""
206
+
207
+ def __init__(self, config):
208
+ super().__init__(config)
209
+ # Unlike in other classes, here _repo_dir is the parent directory of the
210
+ # repo, not its actual directory.
211
+ self._repo_dir = self.workspace.repo_storage
212
+
213
+ @property
214
+ def repo_dir(self):
215
+ """Returns the source repo path, if it has been checked out. None is
216
+ returned otherwise."""
217
+ if not os.path.exists(self._repo_dir):
218
+ logging.warning('Repo dir: %s does not exist.', self._repo_dir)
219
+ return None
220
+
221
+ # Note: this assumes there is only one repo checked out here.
222
+ listing = os.listdir(self._repo_dir)
223
+ if len(listing) != 1:
224
+ raise RuntimeError('Invalid repo directory.')
225
+
226
+ repo_path = os.path.join(self._repo_dir, listing[0])
227
+ if not os.path.isdir(repo_path):
228
+ raise RuntimeError('Repo is not a directory.')
229
+
230
+ return repo_path
231
+
232
+
233
+ class InternalGithub(GithubCiMixin, BaseCi):
234
+ """Class representing CI for an OSS-Fuzz project on Github Actions."""
235
+
236
+ def _copy_repo_from_image(self, image_repo_path):
237
+ self._make_repo_storage_dir()
238
+ repo_name = os.path.basename(image_repo_path)
239
+ host_repo_path = os.path.join(self._repo_dir, repo_name)
240
+ bash_command = f'cp -r {image_repo_path} {host_repo_path}'
241
+ docker_args, _ = docker.get_base_docker_run_args(
242
+ self.workspace, self.config.sanitizer, self.config.language,
243
+ self.config.architecture, self.config.docker_in_docker)
244
+ docker_args.extend([
245
+ docker.get_project_image_name(self.config.oss_fuzz_project_name),
246
+ '/bin/bash', '-c', bash_command
247
+ ])
248
+ if not helper.docker_run(docker_args):
249
+ raise RuntimeError('Failed to copy repo.')
250
+ return repo_manager.RepoManager(host_repo_path)
251
+
252
+ def prepare_for_fuzzer_build(self):
253
+ """Builds the fuzzer builder image, checks out the pull request/commit and
254
+ returns the BuildPreparationResult."""
255
+ logging.info('InternalGithub: preparing for fuzzer build.')
256
+ assert self.config.pr_ref or self.config.git_sha
257
+ # _detect_main_repo builds the image as a side effect.
258
+ _, image_repo_path = self._detect_main_repo()
259
+ if not image_repo_path:
260
+ return get_build_preparation_failure()
261
+
262
+ # Use the same name used in the docker image so we can overwrite it.
263
+ manager = self._copy_repo_from_image(image_repo_path)
264
+ self._checkout_specified_commit(manager)
265
+ return BuildPreparationResult(success=True,
266
+ image_repo_path=image_repo_path,
267
+ repo_manager=manager)
268
+
269
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
270
+ """Returns the command for building the project that is run inside the
271
+ project builder container. Command also replaces |image_repo_path| with
272
+ |host_repo_path|."""
273
+ return get_replace_repo_and_build_command(host_repo_path, image_repo_path)
274
+
275
+
276
+ def get_build_preparation_failure():
277
+ """Returns a BuildPreparationResult indicating failure."""
278
+ return BuildPreparationResult(success=False,
279
+ image_repo_path=None,
280
+ repo_manager=None)
281
+
282
+
283
+ class InternalGeneric(BaseCi):
284
+ """Class representing CI for an OSS-Fuzz project on a CI other than Github
285
+ actions."""
286
+
287
+ def __init__(self, config):
288
+ super().__init__(config)
289
+ self._repo_dir = config.project_src_path
290
+
291
+ @property
292
+ def repo_dir(self):
293
+ """Returns the source repo path, if it has been checked out. None is
294
+ returned otherwise."""
295
+ return self._repo_dir
296
+
297
+ def prepare_for_fuzzer_build(self):
298
+ """Builds the project builder image for an OSS-Fuzz project outside of
299
+ GitHub actions. Returns the repo_manager. Does not checkout source code
300
+ since external projects are expected to bring their own source code to
301
+ CIFuzz."""
302
+ logging.info('InternalGeneric: preparing for fuzzer build.')
303
+ # detect_main_repo builds the image as a side effect.
304
+ _, image_repo_path = self._detect_main_repo()
305
+
306
+ if not image_repo_path:
307
+ return get_build_preparation_failure()
308
+
309
+ manager = self._create_repo_manager_for_project_src_path()
310
+ return BuildPreparationResult(success=True,
311
+ image_repo_path=image_repo_path,
312
+ repo_manager=manager)
313
+
314
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
315
+ """Returns the command for building the project that is run inside the
316
+ project builder container. Command also replaces |image_repo_path| with
317
+ |host_repo_path|."""
318
+ return get_replace_repo_and_build_command(host_repo_path, image_repo_path)
319
+
320
+
321
+ @retry.wrap(_IMAGE_BUILD_TRIES, _IMAGE_BUILD_BACKOFF)
322
+ def build_external_project_docker_image(project_src, build_integration_path):
323
+ """Builds the project builder image for an external (non-OSS-Fuzz) project.
324
+ Returns True on success."""
325
+ dockerfile_path = os.path.join(build_integration_path, 'Dockerfile')
326
+ command = [
327
+ '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f', dockerfile_path, project_src
328
+ ]
329
+ return helper.docker_build(command)
330
+
331
+
332
+ class ExternalGeneric(BaseCi):
333
+ """CI implementation for generic CI for external (non-OSS-Fuzz) projects."""
334
+
335
+ def __init__(self, config):
336
+ super().__init__(config)
337
+ self._repo_dir = config.project_src_path
338
+
339
+ @property
340
+ def repo_dir(self):
341
+ """Returns the source repo path, if it has been checked out. None is
342
+ returned otherwise."""
343
+ return self._repo_dir
344
+
345
+ def prepare_for_fuzzer_build(self):
346
+ logging.info('ExternalGeneric: preparing for fuzzer build.')
347
+ manager = self._create_repo_manager_for_project_src_path()
348
+ return self._build_external_project_docker_image(manager)
349
+
350
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
351
+ """Returns the command for building the project that is run inside the
352
+ project builder container."""
353
+ return get_build_command()
354
+
355
+
356
+ class ExternalGithub(GithubCiMixin, BaseCi):
357
+ """Class representing CI for a non-OSS-Fuzz project on Github Actions."""
358
+
359
+ def prepare_for_fuzzer_build(self):
360
+ """Builds the project builder image for a non-OSS-Fuzz project on GitHub
361
+ actions. Sets the repo manager. Does not checkout source code since external
362
+ projects are expected to bring their own source code to CIFuzz. Returns True
363
+ on success."""
364
+ logging.info('ExternalGithub: preparing for fuzzer build.')
365
+ # Checkout before building, so we don't need to rely on copying the source
366
+ # from the image.
367
+ # TODO(metzman): Figure out if we want second copy at all.
368
+ manager = self._clone_repo_and_checkout(self.config.git_url,
369
+ self.config.project_repo_name)
370
+ return self._build_external_project_docker_image(manager)
371
+
372
+ def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use
373
+ """Returns the command for building the project that is run inside the
374
+ project builder container."""
375
+ return get_build_command()
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/docker_test.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests the functionality of the docker module."""
15
+ import unittest
16
+ from unittest import mock
17
+
18
+ import docker
19
+ import test_helpers
20
+ import workspace_utils
21
+
22
+ CONTAINER_NAME = 'example-container'
23
+ config = test_helpers.create_run_config(oss_fuzz_project_name='project',
24
+ workspace='/workspace')
25
+ config.workspace = '/workspace'
26
+ WORKSPACE = workspace_utils.Workspace(config)
27
+ SANITIZER = 'example-sanitizer'
28
+ LANGUAGE = 'example-language'
29
+
30
+
31
+ class GetProjectImageTest(unittest.TestCase):
32
+ """Tests for get_project_image."""
33
+
34
+ def test_get_project_image(self):
35
+ """Tests that get_project_image_name works as intended."""
36
+ project = 'my-project'
37
+ self.assertEqual(docker.get_project_image_name(project),
38
+ 'gcr.io/oss-fuzz/my-project')
39
+
40
+
41
+ class GetDeleteImagesTest(unittest.TestCase):
42
+ """Tests for delete_images."""
43
+
44
+ @mock.patch('utils.execute')
45
+ def test_delete_images(self, mock_execute): # pylint: disable=no-self-use
46
+ """Tests that get_project_image_name works as intended."""
47
+ images = ['image']
48
+ docker.delete_images(images)
49
+ expected_calls = [
50
+ mock.call(['docker', 'rmi', '-f'] + images),
51
+ mock.call(['docker', 'builder', 'prune', '-f'])
52
+ ]
53
+
54
+ mock_execute.assert_has_calls(expected_calls)
55
+
56
+
57
+ class GetBaseDockerRunArgsTest(unittest.TestCase):
58
+ """Tests get_base_docker_run_args."""
59
+
60
+ @mock.patch('utils.get_container_name', return_value=CONTAINER_NAME)
61
+ def test_get_base_docker_run_args_container(self, _):
62
+ """Tests that get_base_docker_run_args works as intended when inside a
63
+ container."""
64
+ docker_args, docker_container = docker.get_base_docker_run_args(
65
+ WORKSPACE, SANITIZER, LANGUAGE)
66
+ self.assertEqual(docker_container, CONTAINER_NAME)
67
+ expected_docker_args = []
68
+ expected_docker_args = [
69
+ '-e',
70
+ 'FUZZING_ENGINE=libfuzzer',
71
+ '-e',
72
+ 'CIFUZZ=True',
73
+ '-e',
74
+ f'SANITIZER={SANITIZER}',
75
+ '-e',
76
+ 'ARCHITECTURE=x86_64',
77
+ '-e',
78
+ f'FUZZING_LANGUAGE={LANGUAGE}',
79
+ '-e',
80
+ f'OUT={WORKSPACE.out}',
81
+ '--volumes-from',
82
+ CONTAINER_NAME,
83
+ ]
84
+ self.assertEqual(docker_args, expected_docker_args)
85
+
86
+ @mock.patch('utils.get_container_name', return_value=None)
87
+ def test_get_base_docker_run_args_no_container(self, _):
88
+ """Tests that get_base_docker_run_args works as intended when not inside a
89
+ container."""
90
+ docker_args, docker_container = docker.get_base_docker_run_args(
91
+ WORKSPACE, SANITIZER, LANGUAGE)
92
+ self.assertEqual(docker_container, None)
93
+ expected_docker_args = [
94
+ '-e', 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e',
95
+ f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e',
96
+ f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v',
97
+ f'{WORKSPACE.workspace}:{WORKSPACE.workspace}'
98
+ ]
99
+ self.assertEqual(docker_args, expected_docker_args)
100
+
101
+
102
+ class GetBaseDockerRunCommandTest(unittest.TestCase):
103
+ """Tests get_base_docker_run_args."""
104
+
105
+ @mock.patch('utils.get_container_name', return_value=None)
106
+ def test_get_base_docker_run_command_no_container(self, _):
107
+ """Tests that get_base_docker_run_args works as intended when not inside a
108
+ container."""
109
+ docker_args, docker_container = docker.get_base_docker_run_command(
110
+ WORKSPACE, SANITIZER, LANGUAGE)
111
+ self.assertEqual(docker_container, None)
112
+ expected_docker_command = [
113
+ 'docker', 'run', '--rm', '--privileged', '-e',
114
+ 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e',
115
+ f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e',
116
+ f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v',
117
+ f'{WORKSPACE.workspace}:{WORKSPACE.workspace}'
118
+ ]
119
+ self.assertEqual(docker_args, expected_docker_command)
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/filestore_utils.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """External filestore interface. Cannot be depended on by filestore code."""
15
+ import filestore
16
+ import filestore.filesystem
17
+ import filestore.git
18
+ import filestore.github_actions
19
+ import filestore.gsutil
20
+ import filestore.no_filestore
21
+ import filestore.gitlab
22
+
23
+ FILESTORE_MAPPING = {
24
+ 'filesystem': filestore.filesystem.FilesystemFilestore,
25
+ 'gsutil': filestore.gsutil.GSUtilFilestore,
26
+ 'github-actions': filestore.github_actions.GithubActionsFilestore,
27
+ 'git': filestore.git.GitFilestore,
28
+ # TODO(metzman): Change to "no-filestore"
29
+ 'no_filestore': filestore.no_filestore.NoFilestore,
30
+ 'gitlab': filestore.gitlab.GitlabFilestore,
31
+ }
32
+
33
+
34
+ def get_filestore(config):
35
+ """Returns the correct filestore object based on the platform in |config|.
36
+ Raises an exception if there is no correct filestore for the platform."""
37
+ if config.platform == config.Platform.EXTERNAL_GITHUB:
38
+ ci_filestore = filestore.github_actions.GithubActionsFilestore(config)
39
+ if not config.git_store_repo:
40
+ return ci_filestore
41
+
42
+ return filestore.git.GitFilestore(config, ci_filestore)
43
+
44
+ filestore_cls = FILESTORE_MAPPING.get(config.filestore)
45
+ if filestore_cls is None:
46
+ raise filestore.FilestoreError(
47
+ f'Filestore: {config.filestore} doesn\'t exist.')
48
+ return filestore_cls(config)
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/fuzz_target.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """A module to handle running a fuzz target for a specified amount of time."""
15
+ import collections
16
+ import logging
17
+ import multiprocessing
18
+ import os
19
+ import shutil
20
+ import stat
21
+ import tempfile
22
+ from typing import Optional
23
+
24
+ import clusterfuzz.environment
25
+ import clusterfuzz.fuzz
26
+
27
+ import config_utils
28
+ import logs
29
+
30
+ logs.init()
31
+
32
+ # Use len_control=0 since we don't have enough time fuzzing for len_control to
33
+ # make sense (probably).
34
+ LIBFUZZER_OPTIONS_BATCH = ['-len_control=0']
35
+ # Use a fixed seed for determinism for code change fuzzing.
36
+ LIBFUZZER_OPTIONS_CODE_CHANGE = LIBFUZZER_OPTIONS_BATCH + ['-seed=1337']
37
+ LIBFUZZER_OPTIONS_NO_REPORT_OOM = ['-rss_limit_mb=0']
38
+
39
+ # The number of reproduce attempts for a crash.
40
+ REPRODUCE_ATTEMPTS = 10
41
+
42
+ DEFAULT_REPRODUCE_TIME_SECONDS = 30
43
+ PER_LANGUAGE_REPRODUCE_TIMEOUTS = {
44
+ 'python': 30 * 4 # Python takes a bit longer on startup.
45
+ }
46
+ MINIMIZE_TIME_SECONDS = 60 * 4
47
+
48
+ # Seconds on top of duration until a timeout error is raised.
49
+ BUFFER_TIME = 10
50
+
51
+ # Log message if we can't check if crash reproduces on an recent build.
52
+ COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE = (
53
+ 'Could not run previous build of target to determine if this code change '
54
+ '(pr/commit) introduced crash. Assuming crash was newly introduced.')
55
+
56
+ FuzzResult = collections.namedtuple('FuzzResult',
57
+ ['testcase', 'stacktrace', 'corpus_path'])
58
+
59
+
60
+ def get_libfuzzer_parallel_options():
61
+ """Returns a list containing options to pass to libFuzzer to fuzz using all
62
+ available cores."""
63
+ return ['-jobs=' + str(multiprocessing.cpu_count())]
64
+
65
+
66
+ class ReproduceError(Exception):
67
+ """Error for when we can't attempt to reproduce a crash."""
68
+
69
+
70
+ def get_fuzz_target_corpus_dir(workspace, target_name):
71
+ """Returns the directory for storing |target_name|'s corpus in |workspace|."""
72
+ return os.path.join(workspace.corpora, target_name)
73
+
74
+
75
+ def get_fuzz_target_pruned_corpus_dir(workspace, target_name):
76
+ """Returns the directory for storing |target_name|'s puned corpus in
77
+ |workspace|."""
78
+ return os.path.join(workspace.pruned_corpora, target_name)
79
+
80
+
81
+ class FuzzTarget: # pylint: disable=too-many-instance-attributes
82
+ """A class to manage a single fuzz target.
83
+
84
+ Attributes:
85
+ target_name: The name of the fuzz target.
86
+ duration: The length of time in seconds that the target should run.
87
+ target_path: The location of the fuzz target binary.
88
+ workspace: The workspace for storing things related to fuzzing.
89
+ """
90
+
91
+ # pylint: disable=too-many-arguments
92
+ def __init__(self, target_path, duration, workspace, clusterfuzz_deployment,
93
+ config):
94
+ """Represents a single fuzz target.
95
+
96
+ Args:
97
+ target_path: The location of the fuzz target binary.
98
+ duration: The length of time in seconds the target should run.
99
+ workspace: The path used for storing things needed for fuzzing.
100
+ clusterfuzz_deployment: The object representing the ClusterFuzz
101
+ deployment.
102
+ config: The config of this project.
103
+ """
104
+ self.target_path = target_path
105
+ self.target_name = os.path.basename(self.target_path)
106
+ self.duration = int(duration)
107
+ self.workspace = workspace
108
+ self.clusterfuzz_deployment = clusterfuzz_deployment
109
+ self.config = config
110
+ self.latest_corpus_path = get_fuzz_target_corpus_dir(
111
+ self.workspace, self.target_name)
112
+ os.makedirs(self.latest_corpus_path, exist_ok=True)
113
+ self.pruned_corpus_path = get_fuzz_target_pruned_corpus_dir(
114
+ self.workspace, self.target_name)
115
+ os.makedirs(self.pruned_corpus_path, exist_ok=True)
116
+
117
+ def _download_corpus(self):
118
+ """Downloads the corpus for the target from ClusterFuzz and returns the path
119
+ to the corpus. An empty directory is provided if the corpus can't be
120
+ downloaded or is empty."""
121
+ self.clusterfuzz_deployment.download_corpus(self.target_name,
122
+ self.latest_corpus_path)
123
+ return self.latest_corpus_path
124
+
125
+ def _target_artifact_path(self):
126
+ """Target artifact path."""
127
+ artifact_path = os.path.join(self.workspace.artifacts, self.target_name,
128
+ self.config.sanitizer)
129
+ os.makedirs(artifact_path, exist_ok=True)
130
+ return artifact_path
131
+
132
+ def _save_crash(self, crash):
133
+ """Add stacktraces to crashes."""
134
+ target_reproducer_path = os.path.join(self._target_artifact_path(),
135
+ os.path.basename(crash.input_path))
136
+ shutil.copy(crash.input_path, target_reproducer_path)
137
+ bug_summary_artifact_path = target_reproducer_path + '.summary'
138
+ with open(bug_summary_artifact_path, 'w') as handle:
139
+ handle.write(crash.stacktrace)
140
+
141
+ # Set permissions of testcase to be the same as summary so that we're sure
142
+ # it can be read by necessary users.
143
+ permissions_mode = os.stat(bug_summary_artifact_path).st_mode
144
+ os.chmod(target_reproducer_path, permissions_mode & 0o777)
145
+ return target_reproducer_path
146
+
147
+ def prune(self):
148
+ """Prunes the corpus and returns the result."""
149
+ self._download_corpus()
150
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
151
+ self.config.sanitizer,
152
+ self.target_path):
153
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
154
+ result = engine_impl.minimize_corpus(self.target_path, [],
155
+ [self.latest_corpus_path],
156
+ self.pruned_corpus_path,
157
+ self._target_artifact_path(),
158
+ self.duration)
159
+
160
+ print(result.logs)
161
+ return FuzzResult(None, result.logs, self.pruned_corpus_path)
162
+
163
+ def fuzz(self, batch=False) -> Optional[FuzzResult]:
164
+ """Starts the fuzz target run for the length of time specified by duration.
165
+
166
+ Returns:
167
+ FuzzResult namedtuple with stacktrace and testcase if applicable.
168
+ """
169
+ logging.info('Running fuzzer: %s.', self.target_name)
170
+
171
+ self._download_corpus()
172
+ corpus_path = self.latest_corpus_path
173
+
174
+ logging.info('Starting fuzzing')
175
+ with tempfile.TemporaryDirectory() as artifacts_dir:
176
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
177
+ self.config.sanitizer,
178
+ self.target_path) as env:
179
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
180
+ options = engine_impl.prepare(corpus_path, env.target_path,
181
+ env.build_dir)
182
+ options.merge_back_new_testcases = False
183
+ options.analyze_dictionary = False
184
+ if batch:
185
+ options.arguments.extend(LIBFUZZER_OPTIONS_BATCH)
186
+ else:
187
+ options.arguments.extend(LIBFUZZER_OPTIONS_CODE_CHANGE)
188
+
189
+ if not self.config.report_ooms:
190
+ options.arguments.extend(LIBFUZZER_OPTIONS_NO_REPORT_OOM)
191
+
192
+ if self.config.parallel_fuzzing:
193
+ if self.config.sanitizer == 'memory':
194
+ # TODO(https://github.com/google/oss-fuzz/issues/11915): Don't gate
195
+ # this after jobs is fixed for MSAN.
196
+ logging.info('Not using jobs because it breaks MSAN.')
197
+ else:
198
+ options.arguments.extend(get_libfuzzer_parallel_options())
199
+
200
+ result = engine_impl.fuzz(self.target_path, options, artifacts_dir,
201
+ self.duration)
202
+ print(f'Fuzzing logs:\n{result.logs}')
203
+
204
+ if not result.crashes:
205
+ # Libfuzzer max time was reached.
206
+ logging.info('Fuzzer %s finished with no crashes discovered.',
207
+ self.target_name)
208
+ return FuzzResult(None, None, self.latest_corpus_path)
209
+
210
+ if result.timed_out:
211
+ logging.info('Not reporting crash in %s because process timed out.',
212
+ self.target_name)
213
+ return FuzzResult(None, None, self.latest_corpus_path)
214
+
215
+ # Only report first crash.
216
+ crash = result.crashes[0]
217
+ logging.info('Fuzzer: %s. Detected bug.', self.target_name)
218
+
219
+ is_reportable = self.is_crash_reportable(crash.input_path,
220
+ crash.reproduce_args,
221
+ batch=batch)
222
+ if is_reportable or self.config.upload_all_crashes:
223
+ logging.info('SAVING CRASH')
224
+ fuzzer_logs = result.logs
225
+ testcase_path = self._save_crash(crash)
226
+ if is_reportable and self.config.minimize_crashes:
227
+ # TODO(metzman): We don't want to minimize unreproducible crashes.
228
+ # Use is_reportable to decide this even though reportable crashes
229
+ # are a subset of reproducible ones.
230
+ self.minimize_testcase(testcase_path)
231
+ else:
232
+ logging.info('NOT MINIMIZED')
233
+ else:
234
+ fuzzer_logs = None
235
+ testcase_path = None
236
+
237
+ return FuzzResult(testcase_path, fuzzer_logs, self.latest_corpus_path)
238
+
239
+ def minimize_testcase(self, testcase_path):
240
+ """Minimizes the testcase located at |testcase_path|."""
241
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
242
+ self.config.sanitizer,
243
+ self.target_path):
244
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
245
+ minimized_testcase_path = testcase_path + '-minimized'
246
+ return engine_impl.minimize_testcase(self.target_path, [],
247
+ testcase_path,
248
+ minimized_testcase_path,
249
+ max_time=MINIMIZE_TIME_SECONDS)
250
+
251
+ def free_disk_if_needed(self, delete_fuzz_target=True):
252
+ """Deletes things that are no longer needed from fuzzing this fuzz target to
253
+ save disk space if needed."""
254
+ if not self.config.low_disk_space:
255
+ logging.info('Not freeing disk space after running fuzz target.')
256
+ return
257
+ logging.info('Deleting corpus and seed corpus of %s to save disk.',
258
+ self.target_name)
259
+
260
+ # Delete the seed corpus, corpus, and fuzz target.
261
+ for corpus_path in [self.latest_corpus_path, self.pruned_corpus_path]:
262
+ # Use ignore_errors=True to fix
263
+ # https://github.com/google/oss-fuzz/issues/5383.
264
+ shutil.rmtree(corpus_path, ignore_errors=True)
265
+
266
+ target_seed_corpus_path = self.target_path + '_seed_corpus.zip'
267
+ if os.path.exists(target_seed_corpus_path):
268
+ os.remove(target_seed_corpus_path)
269
+
270
+ if delete_fuzz_target:
271
+ logging.info('Deleting fuzz target: %s.', self.target_name)
272
+ os.remove(self.target_path)
273
+ logging.info('Done deleting.')
274
+
275
+ def is_reproducible(self, testcase, target_path, reproduce_args):
276
+ """Checks if the testcase reproduces.
277
+
278
+ Args:
279
+ testcase: The path to the testcase to be tested.
280
+ target_path: The path to the fuzz target to be tested
281
+ reproduce_args: The arguments to pass to the target to reproduce the
282
+ crash.
283
+
284
+ Returns:
285
+ True if crash is reproducible and we were able to run the
286
+ binary.
287
+
288
+ Raises:
289
+ ReproduceError if we can't attempt to reproduce the crash.
290
+ """
291
+ if not os.path.exists(target_path):
292
+ logging.info('Target: %s does not exist.', target_path)
293
+ raise ReproduceError(f'Target {target_path} not found.')
294
+
295
+ os.chmod(target_path, stat.S_IRWXO)
296
+
297
+ logging.info('Trying to reproduce crash using: %s.', testcase)
298
+ with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE,
299
+ self.config.sanitizer,
300
+ target_path):
301
+ reproduce_time_seconds = PER_LANGUAGE_REPRODUCE_TIMEOUTS.get(
302
+ self.config.language, DEFAULT_REPRODUCE_TIME_SECONDS)
303
+ for _ in range(REPRODUCE_ATTEMPTS):
304
+ engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE)
305
+ try:
306
+ result = engine_impl.reproduce(target_path,
307
+ testcase,
308
+ arguments=reproduce_args,
309
+ max_time=reproduce_time_seconds)
310
+ except TimeoutError as error:
311
+ logging.error('%s.', error)
312
+ return False
313
+
314
+ if result.return_code != 0:
315
+ logging.info('Reproduce command returned: %s. Reproducible on %s.',
316
+ result.return_code, target_path)
317
+
318
+ return True
319
+
320
+ logging.info('Reproduce command returned: 0. Not reproducible on %s.',
321
+ target_path)
322
+ return False
323
+
324
+ def is_crash_reportable(self, testcase, reproduce_args, batch=False):
325
+ """Returns True if a crash is reportable. This means the crash is
326
+ reproducible but not reproducible on a build from the ClusterFuzz deployment
327
+ (meaning the crash was introduced by this PR/commit/code change).
328
+
329
+ Args:
330
+ testcase: The path to the testcase that triggered the crash.
331
+ reproduce_args: The arguments to pass to the target to reproduce the
332
+ crash.
333
+
334
+ Returns:
335
+ True if the crash was introduced by the current pull request.
336
+
337
+ Raises:
338
+ ReproduceError if we can't attempt to reproduce the crash on the PR build.
339
+ """
340
+
341
+ if not self.is_crash_type_reportable(testcase):
342
+ return False
343
+
344
+ if not os.path.exists(testcase):
345
+ raise ReproduceError(f'Testcase {testcase} not found.')
346
+
347
+ try:
348
+ reproducible_on_code_change = self.is_reproducible(
349
+ testcase, self.target_path, reproduce_args)
350
+ except ReproduceError as error:
351
+ logging.error('Could not check for crash reproducibility.'
352
+ 'Please file an issue:'
353
+ 'https://github.com/google/oss-fuzz/issues/new.')
354
+ raise error
355
+
356
+ if not reproducible_on_code_change:
357
+ logging.info('Crash is not reproducible.')
358
+ return self.config.report_unreproducible_crashes
359
+
360
+ logging.info('Crash is reproducible.')
361
+ if batch:
362
+ # We don't need to check if the crash is novel for batch fuzzing.
363
+ return True
364
+
365
+ return self.is_crash_novel(testcase, reproduce_args)
366
+
367
+ def is_crash_type_reportable(self, testcase):
368
+ """Returns True if |testcase| is an actual crash. If crash is a timeout or
369
+ OOM then returns True if config says we should report those."""
370
+ # TODO(metzman): Use a less hacky method.
371
+ testcase = os.path.basename(testcase)
372
+ if testcase.startswith('oom-'):
373
+ return self.config.report_ooms
374
+ if testcase.startswith('timeout-'):
375
+ return self.config.report_timeouts
376
+ return True
377
+
378
+ def is_crash_novel(self, testcase, reproduce_args):
379
+ """Returns whether or not the crash is new. A crash is considered new if it
380
+ can't be reproduced on an older ClusterFuzz build of the target."""
381
+ if not os.path.exists(testcase):
382
+ raise ReproduceError('Testcase %s not found.' % testcase)
383
+ clusterfuzz_build_dir = self.clusterfuzz_deployment.download_latest_build()
384
+ if not clusterfuzz_build_dir:
385
+ # Crash is reproducible on PR build and we can't test on a recent
386
+ # ClusterFuzz/OSS-Fuzz build.
387
+ logging.info(COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE)
388
+ return True
389
+
390
+ clusterfuzz_target_path = os.path.join(clusterfuzz_build_dir,
391
+ self.target_name)
392
+
393
+ try:
394
+ reproducible_on_clusterfuzz_build = self.is_reproducible(
395
+ testcase, clusterfuzz_target_path, reproduce_args)
396
+ except ReproduceError:
397
+ # This happens if the project has ClusterFuzz builds, but the fuzz target
398
+ # is not in it (e.g. because the fuzz target is new).
399
+ logging.info(COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE)
400
+ return True
401
+
402
+ if reproducible_on_clusterfuzz_build:
403
+ logging.info('The crash is reproducible on previous build. '
404
+ 'Code change (pr/commit) did not introduce crash.')
405
+ return False
406
+ logging.info('The crash is not reproducible on previous build. '
407
+ 'Code change (pr/commit) introduced crash.')
408
+ return True
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/logs.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Log helpers."""
15
+
16
+ import logging
17
+ import os
18
+
19
+
20
+ def init():
21
+ """Initialize logging."""
22
+ log_level = logging.DEBUG if os.getenv('CIFUZZ_DEBUG') else logging.INFO
23
+ logging.basicConfig(
24
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25
+ level=log_level)
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/run_cifuzz.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Script for running CIFuzz end-to-end. This is meant to work outside any
15
+ docker image. This cannot depend on any CIFuzz code or third party packages."""
16
+ import os
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ import logging
21
+
22
+ INFRA_DIR = os.path.dirname(os.path.dirname(__file__))
23
+ DEFAULT_ENVS = [('DRY_RUN', '0'), ('SANITIZER', 'address')]
24
+ BASE_CIFUZZ_DOCKER_TAG = 'ghcr.io/aixcc-finals'
25
+
26
+
27
+ def set_default_env_var_if_unset(env_var, default_value):
28
+ """Sets the value of |env_var| in the environment to |default_value| if it was
29
+ not already set."""
30
+ if env_var not in os.environ:
31
+ os.environ[env_var] = default_value
32
+
33
+
34
+ def docker_run(name, workspace, project_src_path):
35
+ """Runs a CIFuzz docker container with |name|."""
36
+ command = [
37
+ 'docker', 'run', '--name', name, '--rm', '-e', 'PROJECT_SRC_PATH', '-e',
38
+ 'OSS_FUZZ_PROJECT_NAME', '-e', 'WORKSPACE', '-e', 'REPOSITORY', '-e',
39
+ 'DRY_RUN', '-e', 'CI', '-e', 'SANITIZER', '-e', 'GIT_SHA', '-e',
40
+ 'FILESTORE', '-e', 'NO_CLUSTERFUZZ_DEPLOYMENT'
41
+ ]
42
+ if project_src_path:
43
+ command += ['-v', f'{project_src_path}:{project_src_path}']
44
+ command += [
45
+ '-v', '/var/run/docker.sock:/var/run/docker.sock', '-v',
46
+ f'{workspace}:{workspace}', f'{BASE_CIFUZZ_DOCKER_TAG}/{name}'
47
+ ]
48
+ print('Running docker command:', command)
49
+ subprocess.run(command, check=True)
50
+
51
+
52
+ def docker_build(image):
53
+ """Builds the CIFuzz |image|. Only suitable for building CIFuzz images."""
54
+ command = [
55
+ 'docker', 'build', '-t', f'{BASE_CIFUZZ_DOCKER_TAG}/{image}', '--file',
56
+ f'{image}.Dockerfile', '.'
57
+ ]
58
+ subprocess.run(command, check=True, cwd=INFRA_DIR)
59
+
60
+
61
+ def main():
62
+ """Builds and runs fuzzers using CIFuzz."""
63
+ for env_var, default_value in DEFAULT_ENVS:
64
+ set_default_env_var_if_unset(env_var, default_value)
65
+
66
+ repository = os.getenv('REPOSITORY')
67
+ assert repository
68
+
69
+ project_src_path = os.getenv('PROJECT_SRC_PATH')
70
+
71
+ with tempfile.TemporaryDirectory() as temp_dir:
72
+ if 'WORKSPACE' not in os.environ:
73
+ os.environ['WORKSPACE'] = temp_dir
74
+
75
+ workspace = os.environ['WORKSPACE']
76
+
77
+ docker_build('build_fuzzers')
78
+ docker_run('build_fuzzers', workspace, project_src_path)
79
+ docker_build('run_fuzzers')
80
+ try:
81
+ docker_run('run_fuzzers', workspace, project_src_path)
82
+ except subprocess.CalledProcessError:
83
+ logging.error('run_fuzzers failed.')
84
+ return 1
85
+ return 0
86
+
87
+
88
+ if __name__ == '__main__':
89
+ sys.exit(main())
local-test-libxml2-delta-02/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Tests for running fuzzers."""
15
+ import json
16
+ import os
17
+ import shutil
18
+ import stat
19
+ import sys
20
+ import tempfile
21
+ import unittest
22
+ from unittest import mock
23
+
24
+ import parameterized
25
+ from pyfakefs import fake_filesystem_unittest
26
+
27
+ import build_fuzzers
28
+ import fuzz_target
29
+ import run_fuzzers
30
+
31
+ # pylint: disable=wrong-import-position
32
+ INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
33
+ sys.path.append(INFRA_DIR)
34
+
35
+ import helper
36
+ import test_helpers
37
+
38
+ # NOTE: This integration test relies on
39
+ # https://github.com/google/oss-fuzz/tree/master/projects/example project.
40
+ EXAMPLE_PROJECT = 'example'
41
+
42
+ # Location of files used for testing.
43
+ TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
44
+ 'test_data')
45
+
46
+ MEMORY_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'memory')
47
+ MEMORY_FUZZER = 'curl_fuzzer_memory'
48
+
49
+ UNDEFINED_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'undefined')
50
+ UNDEFINED_FUZZER = 'curl_fuzzer_undefined'
51
+
52
+ FUZZ_SECONDS = 10
53
+
54
+
55
+ class RunFuzzerIntegrationTestMixin: # pylint: disable=too-few-public-methods,invalid-name
56
+ """Mixin for integration test classes that runbuild_fuzzers on builds of a
57
+ specific sanitizer."""
58
+ # These must be defined by children.
59
+ FUZZER_DIR = None
60
+ FUZZER = None
61
+
62
+ def setUp(self):
63
+ """Patch the environ so that we can execute runner scripts."""
64
+ test_helpers.patch_environ(self, runner=True)
65
+
66
+ def _test_run_with_sanitizer(self, fuzzer_dir, sanitizer):
67
+ """Calls run_fuzzers on fuzzer_dir and |sanitizer| and asserts
68
+ the run succeeded and that no bug was found."""
69
+ with test_helpers.temp_dir_copy(fuzzer_dir) as fuzzer_dir_copy:
70
+ config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
71
+ workspace=fuzzer_dir_copy,
72
+ oss_fuzz_project_name='curl',
73
+ sanitizer=sanitizer)
74
+ result = run_fuzzers.run_fuzzers(config)
75
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
76
+
77
+
78
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
79
+ 'INTEGRATION_TESTS=1 not set')
80
+ class RunMemoryFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
81
+ unittest.TestCase):
82
+ """Integration test for build_fuzzers with an MSAN build."""
83
+ FUZZER_DIR = MEMORY_FUZZER_DIR
84
+ FUZZER = MEMORY_FUZZER
85
+
86
+ def test_run_with_memory_sanitizer(self):
87
+ """Tests run_fuzzers with a valid MSAN build."""
88
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'memory')
89
+
90
+
91
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
92
+ 'INTEGRATION_TESTS=1 not set')
93
+ class RunUndefinedFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin,
94
+ unittest.TestCase):
95
+ """Integration test for build_fuzzers with an UBSAN build."""
96
+ FUZZER_DIR = UNDEFINED_FUZZER_DIR
97
+ FUZZER = UNDEFINED_FUZZER
98
+
99
+ def test_run_with_undefined_sanitizer(self):
100
+ """Tests run_fuzzers with a valid UBSAN build."""
101
+ self._test_run_with_sanitizer(self.FUZZER_DIR, 'undefined')
102
+
103
+
104
+ class BaseFuzzTargetRunnerTest(unittest.TestCase):
105
+ """Tests BaseFuzzTargetRunner."""
106
+
107
+ def _create_runner(self, **kwargs): # pylint: disable=no-self-use
108
+ defaults = {
109
+ 'fuzz_seconds': FUZZ_SECONDS,
110
+ 'oss_fuzz_project_name': EXAMPLE_PROJECT
111
+ }
112
+ for default_key, default_value in defaults.items():
113
+ if default_key not in kwargs:
114
+ kwargs[default_key] = default_value
115
+
116
+ config = test_helpers.create_run_config(**kwargs)
117
+ return run_fuzzers.BaseFuzzTargetRunner(config)
118
+
119
+ def _test_initialize_fail(self, expected_error_args, **create_runner_kwargs):
120
+ with mock.patch('logging.error') as mock_error:
121
+ runner = self._create_runner(**create_runner_kwargs)
122
+ self.assertFalse(runner.initialize())
123
+ mock_error.assert_called_with(*expected_error_args)
124
+
125
+ @parameterized.parameterized.expand([(0,), (None,), (-1,)])
126
+ def test_initialize_invalid_fuzz_seconds(self, fuzz_seconds):
127
+ """Tests initialize fails with an invalid fuzz seconds."""
128
+ expected_error_args = ('Fuzz_seconds argument must be greater than 1, '
129
+ 'but was: %s.', fuzz_seconds)
130
+ with tempfile.TemporaryDirectory() as tmp_dir:
131
+ out_path = os.path.join(tmp_dir, 'build-out')
132
+ os.mkdir(out_path)
133
+ with mock.patch('utils.get_fuzz_targets') as mock_get_fuzz_targets:
134
+ mock_get_fuzz_targets.return_value = [
135
+ os.path.join(out_path, 'fuzz_target')
136
+ ]
137
+ self._test_initialize_fail(expected_error_args,
138
+ fuzz_seconds=fuzz_seconds,
139
+ workspace=tmp_dir)
140
+
141
+ def test_initialize_no_out_dir(self):
142
+ """Tests initialize fails with no out dir."""
143
+ with tempfile.TemporaryDirectory() as tmp_dir:
144
+ out_path = os.path.join(tmp_dir, 'build-out')
145
+ expected_error_args = ('Out directory: %s does not exist.', out_path)
146
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
147
+
148
+ def test_initialize_nonempty_artifacts(self):
149
+ """Tests initialize with a file artifacts path."""
150
+ with tempfile.TemporaryDirectory() as tmp_dir:
151
+ out_path = os.path.join(tmp_dir, 'build-out')
152
+ os.mkdir(out_path)
153
+ os.makedirs(os.path.join(tmp_dir, 'out'))
154
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
155
+ with open(artifacts_path, 'w') as artifacts_handle:
156
+ artifacts_handle.write('fake')
157
+ expected_error_args = (
158
+ 'Artifacts path: %s exists and is not an empty directory.',
159
+ artifacts_path)
160
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
161
+
162
+ def test_initialize_bad_artifacts(self):
163
+ """Tests initialize with a non-empty artifacts path."""
164
+ with tempfile.TemporaryDirectory() as tmp_dir:
165
+ out_path = os.path.join(tmp_dir, 'build-out')
166
+ os.mkdir(out_path)
167
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
168
+ os.makedirs(artifacts_path)
169
+ artifact_path = os.path.join(artifacts_path, 'artifact')
170
+ with open(artifact_path, 'w') as artifact_handle:
171
+ artifact_handle.write('fake')
172
+ expected_error_args = (
173
+ 'Artifacts path: %s exists and is not an empty directory.',
174
+ artifacts_path)
175
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
176
+
177
+ @mock.patch('utils.get_fuzz_targets')
178
+ @mock.patch('logging.error')
179
+ def test_initialize_empty_artifacts(self, mock_log_error,
180
+ mock_get_fuzz_targets):
181
+ """Tests initialize with an empty artifacts dir."""
182
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
183
+ with tempfile.TemporaryDirectory() as tmp_dir:
184
+ out_path = os.path.join(tmp_dir, 'build-out')
185
+ os.mkdir(out_path)
186
+ artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts')
187
+ os.makedirs(artifacts_path)
188
+ runner = self._create_runner(workspace=tmp_dir)
189
+ self.assertTrue(runner.initialize())
190
+ mock_log_error.assert_not_called()
191
+ self.assertTrue(os.path.isdir(artifacts_path))
192
+
193
+ @mock.patch('utils.get_fuzz_targets')
194
+ @mock.patch('logging.error')
195
+ def test_initialize_no_artifacts(self, mock_log_error, mock_get_fuzz_targets):
196
+ """Tests initialize with no artifacts dir (the expected setting)."""
197
+ mock_get_fuzz_targets.return_value = ['fuzz-target']
198
+ with tempfile.TemporaryDirectory() as tmp_dir:
199
+ out_path = os.path.join(tmp_dir, 'build-out')
200
+ os.mkdir(out_path)
201
+ runner = self._create_runner(workspace=tmp_dir)
202
+ self.assertTrue(runner.initialize())
203
+ mock_log_error.assert_not_called()
204
+ self.assertTrue(os.path.isdir(os.path.join(tmp_dir, 'out', 'artifacts')))
205
+
206
+ def test_initialize_no_fuzz_targets(self):
207
+ """Tests initialize with no fuzz targets."""
208
+ with tempfile.TemporaryDirectory() as tmp_dir:
209
+ out_path = os.path.join(tmp_dir, 'build-out')
210
+ os.makedirs(out_path)
211
+ expected_error_args = ('No fuzz targets were found in out directory: %s.',
212
+ out_path)
213
+ self._test_initialize_fail(expected_error_args, workspace=tmp_dir)
214
+
215
+
216
+ class CiFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
217
+ """Tests that CiFuzzTargetRunner works as intended."""
218
+
219
+ def setUp(self):
220
+ self.setUpPyfakefs()
221
+
222
+ @mock.patch('clusterfuzz_deployment.OSSFuzz.upload_crashes')
223
+ @mock.patch('utils.get_fuzz_targets')
224
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.run_fuzz_target')
225
+ @mock.patch('run_fuzzers.CiFuzzTargetRunner.create_fuzz_target_obj')
226
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
227
+ mock_run_fuzz_target, mock_get_fuzz_targets,
228
+ mock_upload_crashes):
229
+ """Tests that run_fuzz_targets quits on the first crash it finds."""
230
+ workspace = 'workspace'
231
+ out_path = os.path.join(workspace, 'build-out')
232
+ self.fs.create_dir(out_path)
233
+ config = test_helpers.create_run_config(
234
+ fuzz_seconds=FUZZ_SECONDS,
235
+ workspace=workspace,
236
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
237
+ runner = run_fuzzers.CiFuzzTargetRunner(config)
238
+
239
+ mock_get_fuzz_targets.return_value = ['target1', 'target2']
240
+ runner.initialize()
241
+ testcase = os.path.join(workspace, 'testcase')
242
+ self.fs.create_file(testcase)
243
+ stacktrace = 'stacktrace'
244
+ corpus_dir = 'corpus'
245
+ self.fs.create_dir(corpus_dir)
246
+ mock_run_fuzz_target.return_value = fuzz_target.FuzzResult(
247
+ testcase, stacktrace, corpus_dir)
248
+ magic_mock = mock.MagicMock()
249
+ magic_mock.target_name = 'target1'
250
+ mock_create_fuzz_target_obj.return_value = magic_mock
251
+ self.assertTrue(runner.run_fuzz_targets())
252
+ self.assertEqual(mock_run_fuzz_target.call_count, 1)
253
+ self.assertEqual(mock_upload_crashes.call_count, 1)
254
+
255
+
256
+ class BatchFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase):
257
+ """Tests that BatchFuzzTargetRunnerTest works as intended."""
258
+ WORKSPACE = 'workspace'
259
+ STACKTRACE = 'stacktrace'
260
+ CORPUS_DIR = 'corpus'
261
+
262
+ def setUp(self):
263
+ self.setUpPyfakefs()
264
+ out_dir = os.path.join(self.WORKSPACE, 'build-out')
265
+ self.fs.create_dir(out_dir)
266
+ self.testcase1 = os.path.join(out_dir, 'testcase-aaa')
267
+ self.fs.create_file(self.testcase1)
268
+ self.testcase2 = os.path.join(out_dir, 'testcase-bbb')
269
+ self.fs.create_file(self.testcase2)
270
+ self.config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
271
+ workspace=self.WORKSPACE,
272
+ cfl_platform='github')
273
+
274
+ @mock.patch('utils.get_fuzz_targets', return_value=['target1', 'target2'])
275
+ @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_crashes')
276
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.run_fuzz_target')
277
+ @mock.patch('run_fuzzers.BatchFuzzTargetRunner.create_fuzz_target_obj')
278
+ def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj,
279
+ mock_run_fuzz_target, mock_upload_crashes, _):
280
+ """Tests that run_fuzz_targets doesn't quit on the first crash it finds."""
281
+ runner = run_fuzzers.BatchFuzzTargetRunner(self.config)
282
+ runner.initialize()
283
+
284
+ call_count = 0
285
+
286
+ def mock_run_fuzz_target_impl(_):
287
+ nonlocal call_count
288
+ if call_count == 0:
289
+ testcase = self.testcase1
290
+ elif call_count == 1:
291
+ testcase = self.testcase2
292
+ assert call_count != 2
293
+ call_count += 1
294
+ if not os.path.exists(self.CORPUS_DIR):
295
+ self.fs.create_dir(self.CORPUS_DIR)
296
+ return fuzz_target.FuzzResult(testcase, self.STACKTRACE, self.CORPUS_DIR)
297
+
298
+ mock_run_fuzz_target.side_effect = mock_run_fuzz_target_impl
299
+ magic_mock = mock.MagicMock()
300
+ magic_mock.target_name = 'target1'
301
+ mock_create_fuzz_target_obj.return_value = magic_mock
302
+ self.assertTrue(runner.run_fuzz_targets())
303
+ self.assertEqual(mock_run_fuzz_target.call_count, 2)
304
+ self.assertEqual(mock_upload_crashes.call_count, 1)
305
+
306
+
307
+ class GetCoverageTargetsTest(unittest.TestCase):
308
+ """Tests for get_coverage_fuzz_targets."""
309
+
310
+ def test_get_fuzz_targets(self):
311
+ """Tests that get_coverage_fuzz_targets returns expected targets."""
312
+ with tempfile.TemporaryDirectory() as temp_dir:
313
+ # Setup.
314
+ fuzz_target_path = os.path.join(temp_dir, 'fuzz-target')
315
+ with open(fuzz_target_path, 'w') as file_handle:
316
+ file_handle.write('')
317
+ fuzz_target_st = os.stat(fuzz_target_path)
318
+ os.chmod(fuzz_target_path, fuzz_target_st.st_mode | stat.S_IEXEC)
319
+ non_fuzz_target1 = os.path.join(temp_dir, 'non-fuzz-target1')
320
+ with open(non_fuzz_target1, 'w') as file_handle:
321
+ file_handle.write('LLVMFuzzerTestOneInput')
322
+ subdir = os.path.join(temp_dir, 'subdir')
323
+ os.mkdir(subdir)
324
+ non_fuzz_target2 = os.path.join(subdir, 'non-fuzz-target1')
325
+ with open(non_fuzz_target2, 'w') as file_handle:
326
+ file_handle.write('LLVMFuzzerTestOneInput')
327
+
328
+ self.assertEqual(run_fuzzers.get_coverage_fuzz_targets(temp_dir),
329
+ [fuzz_target_path])
330
+
331
+
332
+ @unittest.skip('TODO(metzman): Fix this test')
333
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
334
+ 'INTEGRATION_TESTS=1 not set')
335
+ class CoverageReportIntegrationTest(unittest.TestCase):
336
+ """Integration tests for coverage reports."""
337
+ SANITIZER = 'coverage'
338
+
339
+ def setUp(self):
340
+ test_helpers.patch_environ(self, runner=True)
341
+
342
+ @mock.patch('filestore.github_actions._upload_artifact_with_upload_js')
343
+ def test_coverage_report(self, _):
344
+ """Tests generation of coverage reports end-to-end, from building to
345
+ generation."""
346
+
347
+ with test_helpers.docker_temp_dir() as temp_dir:
348
+ shared = os.path.join(temp_dir, 'shared')
349
+ os.mkdir(shared)
350
+ copy_command = ('cp -r /opt/code_coverage /shared && '
351
+ 'cp $(which llvm-profdata) /shared && '
352
+ 'cp $(which llvm-cov) /shared')
353
+ assert helper.docker_run([
354
+ '-v', f'{shared}:/shared', 'ghcr.io/aixcc-finals/base-runner', 'bash',
355
+ '-c', copy_command
356
+ ])
357
+
358
+ os.environ['CODE_COVERAGE_SRC'] = os.path.join(shared, 'code_coverage')
359
+ os.environ['PATH'] += os.pathsep + shared
360
+ # Do coverage build.
361
+ build_config = test_helpers.create_build_config(
362
+ oss_fuzz_project_name=EXAMPLE_PROJECT,
363
+ project_repo_name='oss-fuzz',
364
+ workspace=temp_dir,
365
+ git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523',
366
+ base_commit='da0746452433dc18bae699e355a9821285d863c8',
367
+ sanitizer=self.SANITIZER,
368
+ cfl_platform='github',
369
+ # Needed for test not to fail because of permissions issues.
370
+ bad_build_check=False)
371
+ self.assertTrue(build_fuzzers.build_fuzzers(build_config))
372
+
373
+ # TODO(metzman): Get rid of this here and make 'compile' do this.
374
+ chmod_command = ('chmod -R +r /out && '
375
+ 'find /out -type d -exec chmod +x {} +')
376
+
377
+ assert helper.docker_run([
378
+ '-v', f'{os.path.join(temp_dir, "build-out")}:/out',
379
+ 'ghcr.io/aixcc-finals/base-builder', 'bash', '-c', chmod_command
380
+ ])
381
+
382
+ # Generate report.
383
+ run_config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS,
384
+ workspace=temp_dir,
385
+ sanitizer=self.SANITIZER,
386
+ mode='coverage',
387
+ cfl_platform='github')
388
+ result = run_fuzzers.run_fuzzers(run_config)
389
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
390
+ expected_summary_path = os.path.join(
391
+ TEST_DATA_PATH, 'example_coverage_report_summary.json')
392
+ with open(expected_summary_path) as file_handle:
393
+ expected_summary = json.loads(file_handle.read())
394
+ actual_summary_path = os.path.join(temp_dir, 'cifuzz-coverage',
395
+ 'report', 'linux', 'summary.json')
396
+ with open(actual_summary_path) as file_handle:
397
+ actual_summary = json.loads(file_handle.read())
398
+ self.assertEqual(expected_summary, actual_summary)
399
+
400
+
401
+ @unittest.skipIf(not os.getenv('INTEGRATION_TESTS'),
402
+ 'INTEGRATION_TESTS=1 not set')
403
+ class RunAddressFuzzersIntegrationTest(RunFuzzerIntegrationTestMixin,
404
+ unittest.TestCase):
405
+ """Integration tests for build_fuzzers with an ASAN build."""
406
+
407
+ BUILD_DIR_NAME = 'cifuzz-latest-build'
408
+
409
+ def test_new_bug_found(self):
410
+ """Tests run_fuzzers with a valid ASAN build."""
411
+ # Set the first return value to True, then the second to False to
412
+ # emulate a bug existing in the current PR but not on the downloaded
413
+ # OSS-Fuzz build.
414
+ with mock.patch('fuzz_target.FuzzTarget.is_reproducible',
415
+ side_effect=[True, False]):
416
+ with tempfile.TemporaryDirectory() as tmp_dir:
417
+ workspace = os.path.join(tmp_dir, 'workspace')
418
+ shutil.copytree(TEST_DATA_PATH, workspace)
419
+ config = test_helpers.create_run_config(
420
+ fuzz_seconds=FUZZ_SECONDS,
421
+ workspace=workspace,
422
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
423
+ result = run_fuzzers.run_fuzzers(config)
424
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.BUG_FOUND)
425
+
426
+ @mock.patch('fuzz_target.FuzzTarget.is_reproducible',
427
+ side_effect=[True, True])
428
+ def test_old_bug_found(self, _):
429
+ """Tests run_fuzzers with a bug found in OSS-Fuzz before."""
430
+ with tempfile.TemporaryDirectory() as tmp_dir:
431
+ workspace = os.path.join(tmp_dir, 'workspace')
432
+ shutil.copytree(TEST_DATA_PATH, workspace)
433
+ config = test_helpers.create_run_config(
434
+ fuzz_seconds=FUZZ_SECONDS,
435
+ workspace=workspace,
436
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
437
+ result = run_fuzzers.run_fuzzers(config)
438
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND)
439
+
440
+ def test_invalid_build(self):
441
+ """Tests run_fuzzers with an invalid ASAN build."""
442
+ with tempfile.TemporaryDirectory() as tmp_dir:
443
+ out_path = os.path.join(tmp_dir, 'build-out')
444
+ os.mkdir(out_path)
445
+ config = test_helpers.create_run_config(
446
+ fuzz_seconds=FUZZ_SECONDS,
447
+ workspace=tmp_dir,
448
+ oss_fuzz_project_name=EXAMPLE_PROJECT)
449
+ result = run_fuzzers.run_fuzzers(config)
450
+ self.assertEqual(result, run_fuzzers.RunFuzzersResult.ERROR)
451
+
452
+
453
+ class GetFuzzTargetRunnerTest(unittest.TestCase):
454
+ """Tests for get_fuzz_fuzz_target_runner."""
455
+
456
+ @parameterized.parameterized.expand([
457
+ ('batch', run_fuzzers.BatchFuzzTargetRunner),
458
+ ('code-change', run_fuzzers.CiFuzzTargetRunner),
459
+ ('coverage', run_fuzzers.CoverageTargetRunner)
460
+ ])
461
+ def test_get_fuzz_target_runner(self, mode, fuzz_target_runner_cls):
462
+ """Tests that get_fuzz_target_runner returns the correct runner based on the
463
+ specified mode."""
464
+ with tempfile.TemporaryDirectory() as tmp_dir:
465
+ run_config = test_helpers.create_run_config(
466
+ fuzz_seconds=FUZZ_SECONDS,
467
+ workspace=tmp_dir,
468
+ oss_fuzz_project_name='example',
469
+ mode=mode)
470
+ runner = run_fuzzers.get_fuzz_target_runner(run_config)
471
+ self.assertTrue(isinstance(runner, fuzz_target_runner_cls))
472
+
473
+
474
+ if __name__ == '__main__':
475
+ unittest.main()
local-test-libxml2-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-libxml2-delta-02/fuzz-tooling/infra/uploader/Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from ubuntu:16.04
2
+
3
+ RUN apt-get update && apt-get upgrade -y
4
+ RUN apt-get install -y curl
5
+
6
+ ENTRYPOINT ["curl", "--retry", "5", "-X", "PUT", "-T"]
7
+