diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift b/local-test-zookeeper-delta-01/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift new file mode 100644 index 0000000000000000000000000000000000000000..ab855a620191656e572d6a68a869e26f020b0dc5 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift @@ -0,0 +1,33 @@ +#!/bin/bash -eu +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +cp /usr/local/bin/llvm-symbolizer-swift $OUT/llvm-symbolizer + +export SWIFTFLAGS="-Xswiftc -parse-as-library -Xswiftc -static-stdlib --static-swift-stdlib" +if [ "$SANITIZER" = "coverage" ] +then + export SWIFTFLAGS="$SWIFTFLAGS -Xswiftc -profile-generate -Xswiftc -profile-coverage-mapping -Xswiftc -sanitize=fuzzer" +else + export SWIFTFLAGS="$SWIFTFLAGS -Xswiftc -sanitize=fuzzer,$SANITIZER --sanitize=$SANITIZER" + for f in $CFLAGS; do + export SWIFTFLAGS="$SWIFTFLAGS -Xcc=$f" + done + + for f in $CXXFLAGS; do + export SWIFTFLAGS="$SWIFTFLAGS -Xcxx=$f" + done +fi diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/actions/build_fuzzers/action.yml b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/actions/build_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..164c890e91849dc1374c71f0320896f098c5ad97 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/actions/build_fuzzers/action.yml @@ -0,0 +1,55 @@ +# action.yml +name: 'build-fuzzers' +description: "Builds an OSS-Fuzz project's fuzzers." +inputs: + oss-fuzz-project-name: + description: 'Name of the corresponding OSS-Fuzz project.' + required: true + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + allowed-broken-targets-percentage: + description: 'The percentage of broken targets allowed in bad_build_check.' + required: false + sanitizer: + description: 'The sanitizer to build the fuzzers with.' + default: 'address' + architecture: + description: 'The architecture used to build the fuzzers.' + default: 'x86_64' + project-src-path: + description: "The path to the project's source code checkout." + required: false + bad-build-check: + description: "Whether or not OSS-Fuzz's check for bad builds should be done." + required: false + default: true + keep-unaffected-fuzz-targets: + description: "Whether to keep unaffected fuzzers or delete them." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false +runs: + using: 'docker' + image: '../../../build_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + DRY_RUN: ${{ inputs.dry-run}} + ALLOWED_BROKEN_TARGETS_PERCENTAGE: ${{ inputs.allowed-broken-targets-percentage}} + SANITIZER: ${{ inputs.sanitizer }} + ARCHITECTURE: ${{ inputs.architecture }} + PROJECT_SRC_PATH: ${{ inputs.project-src-path }} + LOW_DISK_SPACE: 'True' + BAD_BUILD_CHECK: ${{ inputs.bad-build-check }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + KEEP_UNAFFECTED_FUZZ_TARGETS: ${{ inputs.keep-unaffected-fuzz-targets }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..197aed2b02e4af2b3725040a5ce46f258337af82 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml @@ -0,0 +1,82 @@ +# action.yml +name: 'run-fuzzers' +description: 'Runs fuzz target binaries for a specified length of time.' +inputs: + oss-fuzz-project-name: + description: 'The OSS-Fuzz project name.' + required: true + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + fuzz-seconds: + description: 'The total time allotted for fuzzing in seconds.' + required: true + default: 600 + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + sanitizer: + description: 'The sanitizer to run the fuzzers with.' + default: 'address' + mode: + description: | + The mode to run the fuzzers with ("code-change", "batch", "coverage", or "prune"). + "code-change" is for fuzzing a pull request or commit. + "batch" is for non-interactive fuzzing of an entire project. + "coverage" is for coverage generation. + "prune" is for corpus pruning. + required: false + default: 'code-change' + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: false + report-unreproducible-crashes: + description: 'If True, then unreproducible crashes will be reported.' + required: false + default: False + minimize-crashes: + description: 'If True, reportable crashes will be minimized.' + required: false + default: False + parallel-fuzzing: + description: "Whether to use all available cores for fuzzing." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false + report-timeouts: + description: "Whether to report fails due to timeout." + required: false + default: true + report-ooms: + description: "Whether to report fails due to OOM." + required: false + default: true +runs: + using: 'docker' + image: '../../../run_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + FUZZ_SECONDS: ${{ inputs.fuzz-seconds }} + DRY_RUN: ${{ inputs.dry-run}} + SANITIZER: ${{ inputs.sanitizer }} + MODE: ${{ inputs.mode }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + REPORT_UNREPRODUCIBLE_CRASHES: ${{ inputs.report-unreproducible-crashes }} + MINIMIZE_CRASHES: ${{ inputs.minimize-crashes }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + PARALLEL_FUZZING: ${{ inputs.parallel-fuzzing }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} + REPORT_TIMEOUTS: ${{ inputs.report-timeouts }} + REPORT_OOMS: ${{ inputs.report-ooms}} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..fd15642e8d88c44f3ea82ba64108a8994d160ef0 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers.py @@ -0,0 +1,217 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module used by CI tools in order to interact with fuzzers. This module helps +CI tools to build fuzzers.""" + +import logging +import os +import sys + +import affected_fuzz_targets +import base_runner_utils +import clusterfuzz_deployment +import continuous_integration +import docker +import logs +import workspace_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import helper +import utils + +logs.init() + + +def check_project_src_path(project_src_path): + """Returns True if |project_src_path| exists.""" + if not os.path.exists(project_src_path): + logging.error( + 'PROJECT_SRC_PATH: %s does not exist. ' + 'Are you mounting it correctly?', project_src_path) + return False + return True + + +# pylint: disable=too-many-arguments + + +class Builder: # pylint: disable=too-many-instance-attributes + """Class for fuzzer builders.""" + + def __init__(self, config, ci_system): + self.config = config + self.ci_system = ci_system + self.workspace = workspace_utils.Workspace(config) + self.workspace.initialize_dir(self.workspace.out) + self.workspace.initialize_dir(self.workspace.work) + self.clusterfuzz_deployment = ( + clusterfuzz_deployment.get_clusterfuzz_deployment( + self.config, self.workspace)) + self.image_repo_path = None + self.host_repo_path = None + self.repo_manager = None + + def build_image_and_checkout_src(self): + """Builds the project builder image and checkout source code for the patch + we want to fuzz (if necessary). Returns True on success.""" + result = self.ci_system.prepare_for_fuzzer_build() + if not result.success: + return False + self.image_repo_path = result.image_repo_path + self.repo_manager = result.repo_manager + if self.config.output_sarif: + self.workspace.make_repo_for_sarif(self.repo_manager) + logging.info('repo_dir: %s.', self.repo_manager.repo_dir) + self.host_repo_path = self.repo_manager.repo_dir + return True + + def build_fuzzers(self): + """Moves the source code we want to fuzz into the project builder and builds + the fuzzers from that source code. Returns True on success.""" + docker_args, docker_container = docker.get_base_docker_run_args( + self.workspace, self.config.sanitizer, self.config.language, + self.config.architecture, self.config.docker_in_docker) + if not docker_container: + docker_args.extend( + _get_docker_build_fuzzers_args_not_container(self.host_repo_path)) + + build_command = self.ci_system.get_build_command(self.host_repo_path, + self.image_repo_path) + + # Set extra environment variables so that they are visible to the build. + for key in self.config.extra_environment_variables: + # Don't specify their value in case they get echoed. + docker_args.extend(['-e', key]) + + docker_args.extend([ + docker.get_project_image_name(self.config.oss_fuzz_project_name), + '/bin/bash', + '-c', + build_command, + ]) + logging.info('Building with %s sanitizer.', self.config.sanitizer) + + # TODO(metzman): Stop using helper.docker_run so we can get rid of + # docker.get_base_docker_run_args and merge its contents into + # docker.get_base_docker_run_command. + if not helper.docker_run(docker_args): + logging.error('Building fuzzers failed.') + return False + + return True + + def upload_build(self): + """Upload build.""" + if self.config.upload_build: + self.clusterfuzz_deployment.upload_build( + self.repo_manager.get_current_commit()) + + return True + + def check_fuzzer_build(self): + """Checks the fuzzer build. Returns True on success or if config specifies + to skip check.""" + if not self.config.bad_build_check: + return True + + return check_fuzzer_build(self.config) + + def build(self): + """Builds the image, checkouts the source (if needed), builds the fuzzers + and then removes the unaffectted fuzzers. Returns True on success.""" + methods = [ + self.build_image_and_checkout_src, + self.build_fuzzers, + self.remove_unaffected_fuzz_targets, + self.upload_build, + self.check_fuzzer_build, + ] + for method in methods: + if not method(): + return False + return True + + def remove_unaffected_fuzz_targets(self): + """Removes the fuzzers unaffected by the patch.""" + if self.config.keep_unaffected_fuzz_targets: + logging.info('Not removing unaffected fuzz targets.') + return True + + logging.info('Removing unaffected fuzz targets.') + changed_files = self.ci_system.get_changed_code_under_test( + self.repo_manager) + affected_fuzz_targets.remove_unaffected_fuzz_targets( + self.clusterfuzz_deployment, self.workspace.out, changed_files, + self.image_repo_path) + return True + + +def build_fuzzers(config): + """Builds all of the fuzzers for a specific OSS-Fuzz project. + + Args: + config: The configuration object for building fuzzers. + + Returns: + True if build succeeded. + """ + # Do some quick validation. + if config.project_src_path and not check_project_src_path( + config.project_src_path): + return False + + # Get the builder and then build the fuzzers. + ci_system = continuous_integration.get_ci(config) + logging.info('ci_system: %s.', ci_system) + builder = Builder(config, ci_system) + return builder.build() + + +def check_fuzzer_build(config): + """Checks the integrity of the built fuzzers. + + Args: + config: The config object. + + Returns: + True if fuzzers pass OSS-Fuzz's build check. + """ + workspace = workspace_utils.Workspace(config) + if not os.path.exists(workspace.out): + logging.error('Invalid out directory: %s.', workspace.out) + return False + if not os.listdir(workspace.out): + logging.error('No fuzzers found in out directory: %s.', workspace.out) + return False + + env = base_runner_utils.get_env(config, workspace) + if config.allowed_broken_targets_percentage is not None: + env['ALLOWED_BROKEN_TARGETS_PERCENTAGE'] = ( + config.allowed_broken_targets_percentage) + + stdout, stderr, retcode = utils.execute('test_all.py', env=env) + print(f'Build check: stdout: {stdout}\nstderr: {stderr}') + if retcode == 0: + logging.info('Build check passed.') + return True + logging.error('Build check failed.') + return False + + +def _get_docker_build_fuzzers_args_not_container(host_repo_path): + """Returns arguments to the docker build arguments that are needed to use + |host_repo_path| when the host of the OSS-Fuzz builder container is not + another container.""" + return ['-v', f'{host_repo_path}:{host_repo_path}'] diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f3ada4f2762c6e6ddf058b6be9a67b31c154594 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile @@ -0,0 +1,44 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +FROM ghcr.io/aixcc-finals/base-runner + +RUN apt-get update && \ + apt-get install -y systemd && \ + wget https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce-cli_20.10.8~3-0~ubuntu-focal_amd64.deb -O /tmp/docker-ce.deb && \ + dpkg -i /tmp/docker-ce.deb && \ + rm /tmp/docker-ce.deb + +ENV PATH=/opt/gcloud/google-cloud-sdk/bin/:$PATH +ENV OSS_FUZZ_ROOT=/opt/oss-fuzz + +# Do this step before copying to make rebuilding faster when developing. +COPY ./infra/cifuzz/requirements.txt /tmp/requirements.txt +RUN python3 -m pip install -r /tmp/requirements.txt && rm /tmp/requirements.txt + +ADD . ${OSS_FUZZ_ROOT} +# Don't use the default npm location since jazzer.js can break us. +# This means javascript needed by cifuzz/clusterfuzzlite must be executed in +# OSS_FUZZ_ROOT. +RUN cd ${OSS_FUZZ_ROOT} && npm install ${OSS_FUZZ_ROOT}/infra/cifuzz + + +ENV PYTHONUNBUFFERED=1 + +# Python file to execute when the docker container starts up. +# We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var, +# just expand to '/opt/oss-fuzz'. +ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/cifuzz_combined_entrypoint.py"] diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py new file mode 100644 index 0000000000000000000000000000000000000000..30e28beda330c621ac3a0f5b9d1ee2dc11a5e463 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py @@ -0,0 +1,48 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""End-to-End tests for CIFuzz.""" +import os +import unittest + +import run_cifuzz +import test_helpers + +CIFUZZ_DIR = os.path.dirname(os.path.abspath(__file__)) +EXTERNAL_PROJECT_PATH = os.path.join(CIFUZZ_DIR, 'test_data', + 'external-project') + + +# This test will fail if not run as root because the fuzzer build process +# creates binaries that only root can write to. +# Use a seperate env var to keep this seperate from integration tests which +# don't have this annoying property. +@unittest.skipIf(not os.getenv('END_TO_END_TESTS'), + 'END_TO_END_TESTS=1 not set') +class EndToEndTest(unittest.TestCase): + """End-to-End tests for CIFuzz.""" + + def setUp(self): + test_helpers.patch_environ(self, runner=True) + + def test_simple(self): + """Simple end-to-end test using run_cifuzz.main().""" + os.environ['REPOSITORY'] = 'external-project' + os.environ['PROJECT_SRC_PATH'] = EXTERNAL_PROJECT_PATH + os.environ['FILESTORE'] = 'no_filestore' + os.environ['NO_CLUSTERFUZZ_DEPLOYMENT'] = 'True' + + with test_helpers.docker_temp_dir() as temp_dir: + os.environ['WORKSPACE'] = temp_dir + # TODO(metzman): Verify the crash, affected fuzzers, and other things. + self.assertEqual(run_cifuzz.main(), 1) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5b782e46d4d3116b628143666db8f3f6406ace0 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml @@ -0,0 +1,75 @@ +# action.yml +name: 'build-fuzzers' +description: "Builds an OSS-Fuzz project's fuzzers." +inputs: + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + allowed-broken-targets-percentage: + description: 'The percentage of broken targets allowed in bad_build_check.' + required: false + sanitizer: + description: 'The sanitizer to build the fuzzers with.' + default: 'address' + project-src-path: + description: "The path to the project's source code checkout." + required: false + bad-build-check: + description: "Whether or not OSS-Fuzz's check for bad builds should be done." + required: false + default: true + keep-unaffected-fuzz-targets: + description: "Whether to keep unaffected fuzzers or delete them." + required: false + default: false + storage-repo: + description: | + The git repo to use for storing certain artifacts from fuzzing. + required: false + storage-repo-branch: + description: | + The branch of the git repo to use for storing certain artifacts from + fuzzing. + required: false + storage-repo-branch-coverage: + description: | + The branch of the git repo to use for storing coverage reports. + required: false + upload-build: + description: | + If set, will upload the build. + default: false + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false +runs: + using: 'docker' + image: '../../../build_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + DRY_RUN: ${{ inputs.dry-run}} + ALLOWED_BROKEN_TARGETS_PERCENTAGE: ${{ inputs.allowed-broken-targets-percentage}} + SANITIZER: ${{ inputs.sanitizer }} + PROJECT_SRC_PATH: ${{ inputs.project-src-path }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + BAD_BUILD_CHECK: ${{ inputs.bad-build-check }} + UPLOAD_BUILD: ${{ inputs.upload-build }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + KEEP_UNAFFECTED_FUZZ_TARGETS: ${{ inputs.keep-unaffected-fuzz-targets }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/external-actions/run_fuzzers/action.yml b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/external-actions/run_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ca11e448a0d86d74112eac5133783b57dbe55c0 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/external-actions/run_fuzzers/action.yml @@ -0,0 +1,97 @@ +# action.yml +name: 'run-fuzzers' +description: 'Runs fuzz target binaries for a specified length of time.' +inputs: + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + fuzz-seconds: + description: 'The total time allotted for fuzzing in seconds.' + required: true + default: 600 + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + sanitizer: + description: 'The sanitizer to run the fuzzers with.' + default: 'address' + mode: + description: | + The mode to run the fuzzers with ("code-change", "batch", "coverage", or "prune"). + "code-change" is for fuzzing a pull request or commit. + "batch" is for non-interactive fuzzing of an entire project. + "coverage" is for coverage generation. + "prune" is for corpus pruning. + required: false + default: 'code-change' + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: true + storage-repo: + description: | + The git repo to use for storing certain artifacts from fuzzing. + required: false + storage-repo-branch: + description: | + The branch of the git repo to use for storing certain artifacts from + fuzzing. + default: main + required: false + storage-repo-branch-coverage: + description: | + The branch of the git repo to use for storing coverage reports. + default: gh-pages + required: false + report-unreproducible-crashes: + description: 'If True, then unreproducible crashes will be reported.' + required: false + default: false + minimize-crashes: + description: 'If True, reportable crashes will be minimized.' + required: false + default: False + parallel-fuzzing: + description: "Whether to use all available cores for fuzzing." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false + report-timeouts: + description: "Whether to report fails due to timeout." + required: false + default: true + report-ooms: + description: "Whether to report fails due to OOM." + required: false + default: true +runs: + using: 'docker' + image: '../../../run_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + FUZZ_SECONDS: ${{ inputs.fuzz-seconds }} + DRY_RUN: ${{ inputs.dry-run}} + SANITIZER: ${{ inputs.sanitizer }} + MODE: ${{ inputs.mode }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + GIT_STORE_REPO: ${{ inputs.storage-repo }} + GIT_STORE_BRANCH: ${{ inputs.storage-repo-branch }} + GIT_STORE_BRANCH_COVERAGE: ${{ inputs.storage-repo-branch-coverage }} + REPORT_UNREPRODUCIBLE_CRASHES: ${{ inputs.report-unreproducible-crashes }} + MINIMIZE_CRASHES: ${{ inputs.minimize-crashes }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + PARALLEL_FUZZING: ${{ inputs.parallel-fuzzing }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} + REPORT_TIMEOUTS: ${{ inputs.report-timeouts }} + REPORT_OOMS: ${{ inputs.report-ooms}} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bce4271ce61303b8567beee2cc6343646be2aeda --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/__init__.py @@ -0,0 +1,54 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for a generic filestore.""" + + +class FilestoreError(Exception): + """Error using the filestore.""" + + +# pylint: disable=unused-argument,no-self-use +class BaseFilestore: + """Base class for a filestore.""" + + def __init__(self, config): + self.config = config + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def upload_corpus(self, name, directory, replace=False): + """Uploads the corpus at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def upload_build(self, name, directory): + """Uploads the build at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + raise NotImplementedError('Child class must implement method.') + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + raise NotImplementedError('Child class must implement method.') + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + raise NotImplementedError('Child class must implement method.') + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + raise NotImplementedError('Child class must implement method.') diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddea132661e3acae27eb5abff61f1432eb65ba5 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py @@ -0,0 +1,107 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Filestore implementation using a filesystem directory.""" +import logging +import os +import shutil +import subprocess +import sys + +from distutils import dir_util + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, + os.pardir, os.pardir)) +import filestore + + +def recursive_list_dir(directory): + """Returns list of all files in |directory|, including those in + subdirectories.""" + files = [] + for root, _, filenames in os.walk(directory): + for filename in filenames: + files.append(os.path.join(root, filename)) + return files + + +class FilesystemFilestore(filestore.BaseFilestore): + """Filesystem implementation using a filesystem directory.""" + BUILD_DIR = 'build' + CRASHES_DIR = 'crashes' + CORPUS_DIR = 'corpus' + COVERAGE_DIR = 'coverage' + + def __init__(self, config): + super().__init__(config) + self._filestore_root_dir = self.config.platform_conf.filestore_root_dir + + def _get_filestore_path(self, name, prefix_dir): + """Returns the filesystem path in the filestore for |name| and + |prefix_dir|.""" + return os.path.join(self._filestore_root_dir, prefix_dir, name) + + def _upload_directory(self, name, directory, prefix, delete=False): + filestore_path = self._get_filestore_path(name, prefix) + if os.path.exists(filestore_path): + initial_files = set(recursive_list_dir(filestore_path)) + else: + initial_files = set() + + # Make directory and any parents. + os.makedirs(filestore_path, exist_ok=True) + copied_files = set(dir_util.copy_tree(directory, filestore_path)) + if not delete: + return True + + files_to_delete = initial_files - copied_files + for file_path in files_to_delete: + os.remove(file_path) + return True + + def _download_directory(self, name, dst_directory, prefix): + filestore_path = self._get_filestore_path(name, prefix) + return dir_util.copy_tree(filestore_path, dst_directory) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, directory, self.CRASHES_DIR) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, + directory, + self.CORPUS_DIR, + delete=replace) + + def upload_build(self, name, directory): + """Uploads the build located at |directory| to |name|.""" + return self._upload_directory(name, directory, self.BUILD_DIR) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(name, directory, self.COVERAGE_DIR) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.CORPUS_DIR) + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.BUILD_DIR) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_directory(name, dst_directory, self.COVERAGE_DIR) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/git/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/git/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..636ed693f4357f160ad14e3ccadd6ea07eddb38b --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/git/__init__.py @@ -0,0 +1,158 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for a git based filestore.""" + +import logging +import os +import shutil +import subprocess +import sys +import tempfile + +import filestore + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) +sys.path.append(INFRA_DIR) + +import retry + +_PUSH_RETRIES = 3 +_PUSH_BACKOFF = 1 +_GIT_EMAIL = 'cifuzz@clusterfuzz.com' +_GIT_NAME = 'CIFuzz' +_CORPUS_DIR = 'corpus' +_COVERAGE_DIR = 'coverage' + + +def git_runner(repo_path): + """Returns a gits runner for the repo_path.""" + + def func(*args): + return subprocess.check_call(('git', '-C', repo_path) + args) + + return func + + +# pylint: disable=unused-argument,no-self-use +class GitFilestore(filestore.BaseFilestore): + """Generic git filestore. This still relies on another filestore provided by + the CI for larger artifacts or artifacts which make sense to be included as + the result of a workflow run.""" + + def __init__(self, config, ci_filestore): + super().__init__(config) + self.repo_path = tempfile.mkdtemp() + self._git = git_runner(self.repo_path) + self._clone(self.config.git_store_repo) + + self._ci_filestore = ci_filestore + + def __del__(self): + shutil.rmtree(self.repo_path) + + def _clone(self, repo_url): + """Clones repo URL.""" + self._git('clone', repo_url, '.') + self._git('config', '--local', 'user.email', _GIT_EMAIL) + self._git('config', '--local', 'user.name', _GIT_NAME) + + def _reset_git(self, branch): + """Resets the git repo.""" + self._git('fetch', 'origin') + try: + self._git('checkout', '-B', branch, 'origin/' + branch) + self._git('reset', '--hard', 'HEAD') + except subprocess.CalledProcessError: + self._git('checkout', '--orphan', branch) + + self._git('clean', '-fxd') + + # pylint: disable=too-many-arguments + @retry.wrap(_PUSH_RETRIES, _PUSH_BACKOFF) + def _upload_to_git(self, + message, + branch, + upload_path, + local_path, + replace=False): + """Uploads a directory to git. If `replace` is True, then existing contents + in the upload_path is deleted.""" + self._reset_git(branch) + + full_repo_path = os.path.join(self.repo_path, upload_path) + if replace and os.path.exists(full_repo_path): + shutil.rmtree(full_repo_path) + + shutil.copytree(local_path, full_repo_path, dirs_exist_ok=True) + self._git('add', '.') + try: + self._git('commit', '-m', message) + except subprocess.CalledProcessError: + logging.debug('No changes, skipping git push.') + return + + self._git('push', 'origin', branch) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return self._ci_filestore.upload_crashes(name, directory) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the corpus at |directory| to |name|.""" + self._upload_to_git('Corpus upload', + self.config.git_store_branch, + os.path.join(_CORPUS_DIR, name), + directory, + replace=replace) + + def upload_build(self, name, directory): + """Uploads the build at |directory| to |name|.""" + return self._ci_filestore.upload_build(name, directory) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + self._upload_to_git('Coverage upload', + self.config.git_store_branch_coverage, + os.path.join(_COVERAGE_DIR, name), + directory, + replace=True) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + self._reset_git(self.config.git_store_branch) + path = os.path.join(self.repo_path, _CORPUS_DIR, name) + if not os.path.exists(path): + logging.debug('Corpus does not exist at %s.', path) + return False + + shutil.copytree(path, dst_directory, dirs_exist_ok=True) + return True + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._ci_filestore.download_build(name, dst_directory) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + self._reset_git(self.config.git_store_branch_coverage) + path = os.path.join(self.repo_path, _COVERAGE_DIR, name) + if not os.path.exists(path): + logging.debug('Coverage does not exist at %s.', path) + return False + + shutil.copytree(path, dst_directory, dirs_exist_ok=True) + return True diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/github_actions/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/github_actions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4750a39b9709d49b9f207321480147b1e1d75476 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/github_actions/__init__.py @@ -0,0 +1,179 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Implementation of a filestore using Github actions artifacts.""" +import logging +import os +import shutil +import sys +import tarfile +import tempfile + +# pylint: disable=wrong-import-position,import-error +INFRA_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, + os.path.pardir)) +sys.path.append(INFRA_DIR) +OSS_FUZZ_ROOT_DIR = os.path.dirname(INFRA_DIR) + +import utils +import http_utils +import filestore +from filestore.github_actions import github_api + +UPLOAD_JS = os.path.join(os.path.dirname(__file__), 'upload.js') + + +def tar_directory(directory, archive_path): + """Tars a |directory| and stores archive at |archive_path|. |archive_path| + must end in .tar""" + assert archive_path.endswith('.tar') + # Do this because make_archive will append the extension to archive_path. + archive_path = os.path.splitext(archive_path)[0] + + root_directory = os.path.abspath(directory) + shutil.make_archive(archive_path, + 'tar', + root_dir=root_directory, + base_dir='./') + + +class GithubActionsFilestore(filestore.BaseFilestore): + """Implementation of BaseFilestore using Github actions artifacts. Relies on + github_actions_toolkit for using the GitHub actions API and the github_api + module for using GitHub's standard API. We need to use both because the GitHub + actions API is the only way to upload an artifact but it does not support + downloading artifacts from other runs. The standard GitHub API does support + this however.""" + + ARTIFACT_PREFIX = 'cifuzz-' + BUILD_PREFIX = 'build-' + CRASHES_PREFIX = 'crashes-' + CORPUS_PREFIX = 'corpus-' + COVERAGE_PREFIX = 'coverage-' + + def __init__(self, config): + super().__init__(config) + self.github_api_http_headers = github_api.get_http_auth_headers(config) + + def _get_artifact_name(self, name): + """Returns |name| prefixed with |self.ARITFACT_PREFIX| if it isn't already + prefixed. Otherwise returns |name|.""" + if name.startswith(self.ARTIFACT_PREFIX): + return name + return f'{self.ARTIFACT_PREFIX}{name}' + + def _upload_directory(self, name, directory): # pylint: disable=no-self-use + """Uploads |directory| as artifact with |name|.""" + name = self._get_artifact_name(name) + with tempfile.TemporaryDirectory() as temp_dir: + archive_path = os.path.join(temp_dir, name + '.tar') + tar_directory(directory, archive_path) + _raw_upload_directory(name, temp_dir) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return _raw_upload_directory(self.CRASHES_PREFIX + name, directory) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the corpus at |directory| to |name|.""" + # Not applicable as the the entire corpus is uploaded under a single + # artifact name. + del replace + return self._upload_directory(self.CORPUS_PREFIX + name, directory) + + def upload_build(self, name, directory): + """Uploads the build at |directory| to |name|.""" + return self._upload_directory(self.BUILD_PREFIX + name, directory) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(self.COVERAGE_PREFIX + name, directory) + + def download_corpus(self, name, dst_directory): # pylint: disable=unused-argument,no-self-use + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_artifact(self.CORPUS_PREFIX + name, dst_directory) + + def _find_artifact(self, name): + """Finds an artifact using the GitHub API and returns it.""" + logging.debug('Listing artifacts.') + artifacts = self._list_artifacts() + artifact = github_api.find_artifact(name, artifacts) + logging.debug('Artifact: %s.', artifact) + return artifact + + def _download_artifact(self, name, dst_directory): + """Downloads artifact with |name| to |dst_directory|. Returns True on + success.""" + name = self._get_artifact_name(name) + + with tempfile.TemporaryDirectory() as temp_dir: + if not self._raw_download_artifact(name, temp_dir): + logging.warning('Could not download artifact: %s.', name) + return False + + artifact_tarfile_path = os.path.join(temp_dir, name + '.tar') + if not os.path.exists(artifact_tarfile_path): + logging.error('Artifact zip did not contain a tarfile.') + return False + + # TODO(jonathanmetzman): Replace this with archive.unpack from + # libClusterFuzz so we can avoid path traversal issues. + with tarfile.TarFile(artifact_tarfile_path) as artifact_tarfile: + artifact_tarfile.extractall(dst_directory) + return True + + def _raw_download_artifact(self, name, dst_directory): + """Downloads the artifact with |name| to |dst_directory|. Returns True on + success. Does not do any untarring or adding prefix to |name|.""" + artifact = self._find_artifact(name) + if not artifact: + logging.warning('Could not find artifact: %s.', name) + return False + download_url = artifact['archive_download_url'] + return http_utils.download_and_unpack_zip( + download_url, dst_directory, headers=self.github_api_http_headers) + + def _list_artifacts(self): + """Returns a list of artifacts.""" + return github_api.list_artifacts(self.config.project_repo_owner, + self.config.project_repo_name, + self.github_api_http_headers) + + def download_build(self, name, dst_directory): + """Downloads the build with name |name| to |dst_directory|.""" + return self._download_artifact(self.BUILD_PREFIX + name, dst_directory) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_artifact(self.COVERAGE_PREFIX + name, dst_directory) + + +def _upload_artifact_with_upload_js(name, artifact_paths, directory): + """Uploads the artifacts in |artifact_paths| that are located in |directory| + to |name|, using the upload.js script.""" + command = [UPLOAD_JS, name, directory] + artifact_paths + _, _, retcode = utils.execute(command, location=OSS_FUZZ_ROOT_DIR) + return retcode == 0 + + +def _raw_upload_directory(name, directory): + """Uploads the artifacts located in |directory| to |name|. Does not do any + tarring or adding prefixes to |name|.""" + # Get file paths. + artifact_paths = [] + for root, _, curr_file_paths in os.walk(directory): + for file_path in curr_file_paths: + artifact_paths.append(os.path.join(root, file_path)) + logging.debug('Artifact paths: %s.', artifact_paths) + return _upload_artifact_with_upload_js(name, artifact_paths, directory) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1d6f54e41c8dad942072dc859e42d9c1f8fd82ad --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api_test.py @@ -0,0 +1,41 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for github_api.""" +import os +import sys +import unittest + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.abspath( + os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, + os.path.pardir))) + +from filestore.github_actions import github_api +import test_helpers + + +class GetHttpAuthHeaders(unittest.TestCase): + """Tests for get_http_auth_headers.""" + + def test_get_http_auth_headers(self): + """Tests that get_http_auth_headers returns the correct result.""" + token = 'example githubtoken' + run_config = test_helpers.create_run_config(token=token) + expected_headers = { + 'Authorization': f'token {token}', + 'Accept': 'application/vnd.github.v3+json', + } + self.assertEqual(expected_headers, + github_api.get_http_auth_headers(run_config)) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43ee0ce8f17a4231bb46f41377d1277cb87a854b --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py @@ -0,0 +1,133 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""GitLab filestore implementation.""" +import logging + +import json +import os +import shutil +import tempfile + +import filestore +import http_utils + +# pylint: disable=no-self-use,unused-argument + + +class GitlabFilestore(filestore.BaseFilestore): + """Implementation of BaseFilestore using GitLab. + Needs a cache to upload and download builds. + Needs a git repository for corpus and coverage. + """ + + BUILD_PREFIX = 'build-' + CORPUS_PREFIX = 'corpus-' + COVERAGE_PREFIX = 'coverage-' + CRASHES_PREFIX = 'crashes-' + + def __init__(self, config): + super().__init__(config) + self.artifacts_dir = self.config.platform_conf.artifacts_dir + self.cache_dir = self.config.platform_conf.cache_dir + if self.config.git_store_repo: + self.git_filestore = filestore.git.GitFilestore(config, None) + else: + self.git_filestore = None + + def upload_crashes(self, name, directory): + """GitLab artifacts implementation of upload_crashes.""" + # Upload crashes as job artifacts. + if os.listdir(directory): + dest_dir_artifacts = os.path.join(self.config.project_src_path, + self.artifacts_dir, + self.CRASHES_PREFIX + name) + logging.info('Uploading artifacts to %s.', dest_dir_artifacts) + shutil.copytree(directory, dest_dir_artifacts) + + def upload_corpus(self, name, directory, replace=False): + """GitLab artifacts implementation of upload_corpus.""" + # Use the git filestore if any. + if self.git_filestore: + self.git_filestore.upload_corpus(name, directory, replace) + return + # Fall back to cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.CORPUS_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + # Remove previous corpus from cache if any. + shutil.rmtree(dest_dir_cache, ignore_errors=True) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + + def upload_build(self, name, directory): + """GitLab artifacts implementation of upload_build.""" + # Puts build into the cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.BUILD_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + + def upload_coverage(self, name, directory): + """GitLab artifacts implementation of upload_coverage.""" + # Use the git filestore. + if self.git_filestore: + self.git_filestore.upload_coverage(name, directory) + return + # Fall back to cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.COVERAGE_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + # And also updates coverage reports as artifacts + # as it should not be too big. + dest_dir_artifacts = os.path.join(self.config.project_src_path, + self.artifacts_dir, + self.COVERAGE_PREFIX + name) + logging.info('Uploading artifacts to %s.', dest_dir_artifacts) + shutil.copytree(directory, dest_dir_artifacts) + + def _copy_from_cache(self, src_dir_cache, dst_directory): + if not os.path.exists(src_dir_cache): + logging.info('Cache %s does not exist.', src_dir_cache) + return False + logging.info('Copying %s from cache to %s.', src_dir_cache, dst_directory) + shutil.copytree(src_dir_cache, dst_directory, dirs_exist_ok=True) + return True + + def download_corpus(self, name, dst_directory): + """GitLab artifacts implementation of download_corpus.""" + # Use the git filestore if any. + if self.git_filestore: + self.git_filestore.download_corpus(name, dst_directory) + return + # Fall back to cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.CORPUS_PREFIX + name) + self._copy_from_cache(src_dir_cache, dst_directory) + + def download_build(self, name, dst_directory): + """GitLab artifacts implementation of download_build.""" + # Gets build from the cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.BUILD_PREFIX + name) + return self._copy_from_cache(src_dir_cache, dst_directory) + + def download_coverage(self, name, dst_directory): + """GitLab artifacts implementation of download_coverage.""" + # Use the git filestore if any. + if self.git_filestore: + return self.git_filestore.download_coverage(name, dst_directory) + # Fall back to cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.COVERAGE_PREFIX + name) + return self._copy_from_cache(src_dir_cache, dst_directory) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85f85508d78e8a01d11dcbed7c3f463d830d322b --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py @@ -0,0 +1,109 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Filestore implementation using gsutil.""" +import logging +import os +import posixpath +import subprocess +import sys + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, + os.pardir, os.pardir)) +import filestore +import utils + + +def _gsutil_execute(*args, parallel=True): + """Executes a gsutil command, passing |*args| to gsutil and returns the + stdout, stderr and returncode. Exceptions on failure.""" + command = ['gsutil'] + if parallel: + command.append('-m') + command += list(args) + logging.info('Executing gsutil command: %s', command) + return utils.execute(command, check_result=True) + + +def _rsync(src, dst, recursive=True, delete=False): + """Executes gsutil rsync on |src| and |dst|""" + args = ['rsync'] + if recursive: + args.append('-r') + if delete: + args.append('-d') + args += [src, dst] + return _gsutil_execute(*args) + + +class GSUtilFilestore(filestore.BaseFilestore): + """Filestore implementation using gsutil.""" + BUILD_DIR = 'build' + CRASHES_DIR = 'crashes' + CORPUS_DIR = 'corpus' + COVERAGE_DIR = 'coverage' + + def __init__(self, config): + super().__init__(config) + self._cloud_bucket = self.config.cloud_bucket + + def _get_gsutil_url(self, name, prefix_dir): + """Returns the gsutil URL for |name| and |prefix_dir|.""" + if not prefix_dir: + return posixpath.join(self._cloud_bucket, name) + return posixpath.join(self._cloud_bucket, prefix_dir, name) + + def _upload_directory(self, name, directory, prefix, delete=False): + gsutil_url = self._get_gsutil_url(name, prefix) + return _rsync(directory, gsutil_url, delete=delete) + + def _download_directory(self, name, dst_directory, prefix): + gsutil_url = self._get_gsutil_url(name, prefix) + return _rsync(gsutil_url, dst_directory) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + # Name is going to be "current". I don't know if this makes sense outside of + # GitHub Actions. + gsutil_url = self._get_gsutil_url(name, self.CRASHES_DIR) + logging.info('Uploading crashes to %s.', gsutil_url) + return _rsync(directory, gsutil_url) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, + directory, + self.CORPUS_DIR, + delete=replace) + + def upload_build(self, name, directory): + """Uploads the build located at |directory| to |name|.""" + return self._upload_directory(name, directory, self.BUILD_DIR) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(name, directory, self.COVERAGE_DIR) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.CORPUS_DIR) + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.BUILD_DIR) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_directory(name, dst_directory, self.COVERAGE_DIR) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d063116ebcffcf2552225a58a824e4e4409be49 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py @@ -0,0 +1,51 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Empty filestore implementation for platforms that haven't implemented it.""" +import logging + +import filestore + +# pylint:disable=no-self-use,unused-argument + + +class NoFilestore(filestore.BaseFilestore): + """Empty Filestore implementation.""" + + def upload_crashes(self, name, directory): + """Noop implementation of upload_crashes.""" + logging.info('Not uploading crashes because no Filestore.') + + def upload_corpus(self, name, directory, replace=False): + """Noop implementation of upload_corpus.""" + logging.info('Not uploading corpus because no Filestore.') + + def upload_build(self, name, directory): + """Noop implementation of upload_build.""" + logging.info('Not uploading build because no Filestore.') + + def upload_coverage(self, name, directory): + """Noop implementation of upload_coverage.""" + logging.info('Not uploading coverage because no Filestore.') + + def download_corpus(self, name, dst_directory): + """Noop implementation of download_corpus.""" + logging.info('Not downloading corpus because no Filestore.') + + def download_build(self, name, dst_directory): + """Noop implementation of download_build.""" + logging.info('Not downloading build because no Filestore.') + + def download_coverage(self, name, dst_directory): + """Noop implementation of download_coverage.""" + logging.info('Not downloading coverage because no Filestore.') diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e1307376548252e0633cb2c2343feee2c0f745 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils_test.py @@ -0,0 +1,50 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for filestore_utils.""" +import unittest +from unittest import mock + +import parameterized + +import platform_config +import filestore +from filestore import github_actions +import filestore_utils +import test_helpers + + +class GetFilestoreTest(unittest.TestCase): + """Tests for get_filestore.""" + + @parameterized.parameterized.expand([ + ({ + 'cfl_platform': 'github', + }, github_actions.GithubActionsFilestore), + ]) + def test_get_filestore(self, config_kwargs, filestore_cls): + """Tests that get_filestore returns the right filestore given a certain + platform.""" + run_config = test_helpers.create_run_config(**config_kwargs) + filestore_impl = filestore_utils.get_filestore(run_config) + self.assertIsInstance(filestore_impl, filestore_cls) + + @mock.patch('config_utils.BaseConfig.platform', return_value='other') + @mock.patch('config_utils._get_platform_config', + return_value=platform_config.BasePlatformConfig()) + def test_get_filestore_unsupported_platform(self, _, __): + """Tests that get_filestore exceptions given a platform it doesn't + support.""" + run_config = test_helpers.create_run_config() + with self.assertRaises(filestore.FilestoreError): + filestore_utils.get_filestore(run_config) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/fuzz_target_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/fuzz_target_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e553a25aecacfebc1a15e920fc54f19388d396d6 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/fuzz_target_test.py @@ -0,0 +1,298 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests the functionality of the fuzz_target module.""" + +import os +import shutil +import tempfile +import unittest +from unittest import mock + +import certifi +# Importing this later causes import failures with pytest for some reason. +# TODO(ochang): Figure out why. +import parameterized +import google.cloud.ndb # pylint: disable=unused-import +from pyfakefs import fake_filesystem_unittest +from clusterfuzz.fuzz import engine + +import clusterfuzz_deployment +import fuzz_target +import test_helpers +import workspace_utils + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +# An example fuzzer that triggers an error. +EXAMPLE_FUZZER = 'example_crash_fuzzer' + +# Mock return values for engine_impl.reproduce. +EXECUTE_SUCCESS_RESULT = engine.ReproduceResult([], 0, 0, '') +EXECUTE_FAILURE_RESULT = engine.ReproduceResult([], 1, 0, '') + +TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'test_data') + + +def _create_config(**kwargs): + """Creates a config object and then sets every attribute that is a key in + |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an + attribute of Config.""" + defaults = { + 'cfl_platform': 'github', + 'oss_fuzz_project_name': EXAMPLE_PROJECT, + 'workspace': '/workspace' + } + for default_key, default_value in defaults.items(): + if default_key not in kwargs: + kwargs[default_key] = default_value + + return test_helpers.create_run_config(**kwargs) + + +def _create_deployment(**kwargs): + config = _create_config(**kwargs) + workspace = workspace_utils.Workspace(config) + return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace) + + +@mock.patch('utils.get_container_name', return_value='container') +class IsReproducibleTest(fake_filesystem_unittest.TestCase): + """Tests the is_reproducible method in the fuzz_target.FuzzTarget class.""" + + def setUp(self): + """Sets up example fuzz target to test is_reproducible method.""" + self.fuzz_target_name = 'fuzz-target' + deployment = _create_deployment() + self.config = deployment.config + self.workspace = deployment.workspace + self.fuzz_target_path = os.path.join(self.workspace.out, + self.fuzz_target_name) + self.setUpPyfakefs() + self.fs.create_file(self.fuzz_target_path) + self.testcase_path = '/testcase' + self.fs.create_file(self.testcase_path) + + self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, + fuzz_target.REPRODUCE_ATTEMPTS, + self.workspace, deployment, + deployment.config) + + # ClusterFuzz requires ROOT_DIR. + root_dir = os.environ['ROOT_DIR'] + test_helpers.patch_environ(self, empty=True) + os.environ['ROOT_DIR'] = root_dir + + # There's an extremely bad issue that happens if this test is run: Other tests + # in this file fail in CI with stacktraces using referencing fakefs even if + # the tests do not use fakefs. + # TODO(metzman): Stop using fakefs. + @mock.patch('os.chmod') + @unittest.skip('Skip because of weird failures.') + def test_repro_timed_out(self, mock_chmod, mock_get_container_name): + """Tests that is_reproducible behaves correctly when reproduction times + out.""" + del mock_get_container_name + del mock_chmod + + with mock.patch( + 'clusterfuzz._internal.bot.fuzzers.libFuzzer.engine.LibFuzzerEngine.' + 'reproduce', + side_effect=TimeoutError): + self.assertFalse( + self.target.is_reproducible('/testcase', self.target.target_path, [])) + + def test_reproducible(self, _): + """Tests that is_reproducible returns True if crash is detected and that + is_reproducible uses the correct command to reproduce a crash.""" + all_repro = [EXECUTE_FAILURE_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = all_repro + + result = self.target.is_reproducible(self.testcase_path, + self.fuzz_target_path, []) + mock_get_engine().reproduce.assert_called_once_with( + '/workspace/build-out/fuzz-target', + '/testcase', + arguments=[], + max_time=30) + self.assertTrue(result) + self.assertEqual(1, mock_get_engine().reproduce.call_count) + + def test_flaky(self, _): + """Tests that is_reproducible returns True if crash is detected on the last + attempt.""" + last_time_repro = [EXECUTE_SUCCESS_RESULT] * 9 + [EXECUTE_FAILURE_RESULT] + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = last_time_repro + self.assertTrue( + self.target.is_reproducible(self.testcase_path, self.fuzz_target_path, + [])) + self.assertEqual(fuzz_target.REPRODUCE_ATTEMPTS, + mock_get_engine().reproduce.call_count) + + def test_nonexistent_fuzzer(self, _): + """Tests that is_reproducible raises an error if it could not attempt + reproduction because the fuzzer doesn't exist.""" + with self.assertRaises(fuzz_target.ReproduceError): + self.target.is_reproducible(self.testcase_path, '/non-existent-path', []) + + def test_unreproducible(self, _): + """Tests that is_reproducible returns False for a crash that did not + reproduce.""" + all_unrepro = [EXECUTE_SUCCESS_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = all_unrepro + result = self.target.is_reproducible(self.testcase_path, + self.fuzz_target_path, []) + self.assertFalse(result) + + +class IsCrashReportableTest(fake_filesystem_unittest.TestCase): + """Tests the is_crash_reportable method of FuzzTarget.""" + + def setUp(self): + """Sets up example fuzz target to test is_crash_reportable method.""" + self.setUpPyfakefs() + self.fuzz_target_path = '/example/do_stuff_fuzzer' + deployment = _create_deployment() + self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, 100, + deployment.workspace, deployment, + deployment.config) + self.oss_fuzz_build_path = '/oss-fuzz-build' + self.fs.create_file(self.fuzz_target_path) + self.oss_fuzz_target_path = os.path.join( + self.oss_fuzz_build_path, os.path.basename(self.fuzz_target_path)) + self.fs.create_file(self.oss_fuzz_target_path) + self.testcase_path = '/testcase' + self.fs.create_file(self.testcase_path, contents='') + + # Do this to prevent pyfakefs from messing with requests. + self.fs.add_real_directory(os.path.dirname(certifi.__file__)) + + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=[True, False]) + @mock.patch('logging.info') + def test_new_reproducible_crash(self, mock_info, _): + """Tests that a new reproducible crash returns True.""" + with tempfile.TemporaryDirectory() as tmp_dir: + self.target.out_dir = tmp_dir + self.assertTrue(self.target.is_crash_reportable(self.testcase_path, [])) + mock_info.assert_called_with( + 'The crash is not reproducible on previous build. ' + 'Code change (pr/commit) introduced crash.') + + # yapf: disable + @parameterized.parameterized.expand([ + # Reproducible on PR build, but also reproducible on OSS-Fuzz. + ([True, True],), + + # Not reproducible on PR build, but somehow reproducible on OSS-Fuzz. + # Unlikely to happen in real world except if test is flaky. + ([False, True],), + + # Not reproducible on PR build, and not reproducible on OSS-Fuzz. + ([False, False],), + ]) + # yapf: enable + def test_invalid_crash(self, is_reproducible_retvals): + """Tests that a nonreportable crash causes the method to return False.""" + with mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=is_reproducible_retvals): + with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build', + return_value=self.oss_fuzz_build_path): + self.assertFalse(self.target.is_crash_reportable( + self.testcase_path, [])) + + @mock.patch('logging.info') + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', return_value=[True]) + def test_reproducible_no_oss_fuzz_target(self, _, mock_info): + """Tests that is_crash_reportable returns True when a crash reproduces on + the PR build but the target is not in the OSS-Fuzz build (usually because it + is new).""" + os.remove(self.oss_fuzz_target_path) + + def is_reproducible_side_effect(testcase, target_path, reproduce_arguments): + del testcase + del reproduce_arguments + if os.path.dirname(target_path) == self.oss_fuzz_build_path: + raise fuzz_target.ReproduceError() + return True + + with mock.patch( + 'fuzz_target.FuzzTarget.is_reproducible', + side_effect=is_reproducible_side_effect) as mock_is_reproducible: + with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build', + return_value=self.oss_fuzz_build_path): + self.assertTrue(self.target.is_crash_reportable(self.testcase_path, [])) + mock_is_reproducible.assert_any_call(self.testcase_path, + self.oss_fuzz_target_path, []) + mock_info.assert_called_with( + 'Could not run previous build of target to determine if this code ' + 'change (pr/commit) introduced crash. Assuming crash was newly ' + 'introduced.') + + +class FuzzTest(fake_filesystem_unittest.TestCase): + """Fuzz test.""" + + def setUp(self): + """Sets up example fuzz target.""" + self.setUpPyfakefs() + deployment = _create_deployment() + config = deployment.config + workspace = deployment.workspace + self.fuzz_target = fuzz_target.FuzzTarget('/path/fuzz-target', 10, + workspace, deployment, config) + + def test_get_fuzz_target_artifact(self): + """Tests that get_fuzz_target_artifact works as intended.""" + # pylint: disable=protected-access + fuzz_target_artifact = self.fuzz_target._target_artifact_path() + self.assertEqual('/workspace/out/artifacts/fuzz-target/address', + fuzz_target_artifact) + + +class TimeoutIntegrationTest(unittest.TestCase): + """Tests handling of fuzzer timeout (timeout crashes reported by + libFuzzer).""" + TIMEOUT_FUZZER_NAME = 'timeout_fuzzer' + + @parameterized.parameterized.expand([(True, True), (False, False)]) + def test_timeout_reported(self, report_timeouts, expect_crash): + """Tests that timeouts are not reported.""" + with test_helpers.temp_dir_copy(TEST_DATA_PATH) as temp_dir: + fuzz_target_path = os.path.join(temp_dir, 'build-out', + self.TIMEOUT_FUZZER_NAME) + shutil.copy(os.path.join(temp_dir, self.TIMEOUT_FUZZER_NAME), + fuzz_target_path) + deployment = _create_deployment(workspace=temp_dir, + report_timeouts=report_timeouts) + config = deployment.config + fuzz_target_obj = fuzz_target.FuzzTarget(fuzz_target_path, + fuzz_target.REPRODUCE_ATTEMPTS, + deployment.workspace, deployment, + config) + with mock.patch('clusterfuzz._internal.bot.fuzzers.libfuzzer.' + 'fix_timeout_argument_for_reproduction') as _: + with mock.patch( + 'clusterfuzz._internal.bot.fuzzers.libFuzzer.fuzzer.get_arguments', + return_value=['-timeout=1', '-rss_limit_mb=2560']): + fuzz_result = fuzz_target_obj.fuzz() + self.assertEqual(bool(fuzz_result.testcase), expect_crash) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report.py new file mode 100644 index 0000000000000000000000000000000000000000..9901c452a0fe536670e5ec6da68b73a902d985e5 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report.py @@ -0,0 +1,48 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for generating coverage reports.""" +import os + +import base_runner_utils +import fuzz_target +import utils + + +def run_coverage_command(config, workspace): + """Runs the coverage command in base-runner to generate a coverage report.""" + env = base_runner_utils.get_env(config, workspace) + env['HTTP_PORT'] = '' + env['COVERAGE_EXTRA_ARGS'] = '' + env['CORPUS_DIR'] = workspace.corpora + env['COVERAGE_OUTPUT_DIR'] = workspace.coverage_report + command = 'coverage' + return utils.execute(command, env=env) + + +def download_corpora(fuzz_target_paths, clusterfuzz_deployment): + """Downloads corpora for fuzz targets in |fuzz_target_paths| using + |clusterfuzz_deployment| to download corpora from ClusterFuzz/OSS-Fuzz.""" + for target_path in fuzz_target_paths: + target_name = os.path.basename(target_path) + corpus_dir = fuzz_target.get_fuzz_target_corpus_dir( + clusterfuzz_deployment.workspace, target_name) + clusterfuzz_deployment.download_corpus(target_name, corpus_dir) + + +def generate_coverage_report(fuzz_target_paths, workspace, + clusterfuzz_deployment, config): + """Generates a coverage report using Clang's source based coverage.""" + download_corpora(fuzz_target_paths, clusterfuzz_deployment) + run_coverage_command(config, workspace) + clusterfuzz_deployment.upload_coverage() diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/get_coverage_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/get_coverage_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3551f22adf5c0f77a2627c986de033bc71a8febb --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/get_coverage_test.py @@ -0,0 +1,253 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for get_coverage.py""" +import os +import json +import unittest +from unittest import mock + +import parameterized +from pyfakefs import fake_filesystem_unittest +import pytest + +import get_coverage + +# pylint: disable=protected-access + +TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'test_data') + +PROJECT_NAME = 'curl' +REPO_PATH = '/src/curl' +FUZZ_TARGET = 'curl_fuzzer' +PROJECT_COV_JSON_FILENAME = 'example_curl_cov.json' +FUZZ_TARGET_COV_JSON_FILENAME = 'example_curl_fuzzer_cov.json' +INVALID_TARGET = 'not-a-fuzz-target' + +with open(os.path.join(TEST_DATA_PATH, + PROJECT_COV_JSON_FILENAME),) as cov_file_handle: + PROJECT_COV_INFO = json.loads(cov_file_handle.read()) + + +class GetOssFuzzFuzzerStatsDirUrlTest(unittest.TestCase): + """Tests _get_oss_fuzz_fuzzer_stats_dir_url.""" + + @mock.patch('http_utils.get_json_from_url', + return_value={ + 'fuzzer_stats_dir': + 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303' + }) + def test_get_valid_project(self, mock_get_json_from_url): + """Tests that a project's coverage report can be downloaded and parsed. + + NOTE: This test relies on the PROJECT_NAME repo's coverage report. + The "example" project was not used because it has no coverage reports. + """ + result = get_coverage._get_oss_fuzz_fuzzer_stats_dir_url(PROJECT_NAME) + (url,), _ = mock_get_json_from_url.call_args + self.assertEqual( + 'https://storage.googleapis.com/oss-fuzz-coverage/' + 'latest_report_info/curl.json', url) + + expected_result = ( + 'https://storage.googleapis.com/oss-fuzz-coverage/systemd/fuzzer_stats/' + '20210303') + self.assertEqual(result, expected_result) + + def test_get_invalid_project(self): + """Tests that passing a bad project returns None.""" + self.assertIsNone( + get_coverage._get_oss_fuzz_fuzzer_stats_dir_url('not-a-proj')) + + +class OSSFuzzCoverageGetTargetCoverageTest(unittest.TestCase): + """Tests OSSFuzzCoverage.get_target_coverage.""" + + def setUp(self): + with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info', + return_value=PROJECT_COV_INFO): + self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage( + REPO_PATH, PROJECT_NAME) + + @mock.patch('http_utils.get_json_from_url', return_value={}) + def test_valid_target(self, mock_get_json_from_url): + """Tests that a target's coverage report can be downloaded and parsed.""" + self.oss_fuzz_coverage.get_target_coverage(FUZZ_TARGET) + (url,), _ = mock_get_json_from_url.call_args + self.assertEqual( + 'https://storage.googleapis.com/oss-fuzz-coverage/' + 'curl/fuzzer_stats/20200226/curl_fuzzer.json', url) + + def test_invalid_target(self): + """Tests that passing an invalid target coverage report returns None.""" + self.assertIsNone( + self.oss_fuzz_coverage.get_target_coverage(INVALID_TARGET)) + + @mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info', + return_value=None) + def test_invalid_project_json(self, _): # pylint: disable=no-self-use + """Tests an invalid project JSON results in None being returned.""" + with pytest.raises(get_coverage.CoverageError): + get_coverage.OSSFuzzCoverage(REPO_PATH, PROJECT_NAME) + + +def _get_expected_curl_covered_file_list(): + """Returns the expected covered file list for + FUZZ_TARGET_COV_JSON_FILENAME.""" + curl_files_list_path = os.path.join(TEST_DATA_PATH, + 'example_curl_file_list.json') + with open(curl_files_list_path) as file_handle: + return json.loads(file_handle.read()) + + +def _get_example_curl_coverage(): + """Returns the contents of the fuzzer stats JSON file for + FUZZ_TARGET_COV_JSON_FILENAME.""" + with open(os.path.join(TEST_DATA_PATH, + FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle: + return json.loads(file_handle.read()) + + +class OSSFuzzCoverageGetFilesCoveredByTargetTest(unittest.TestCase): + """Tests OSSFuzzCoverage.get_files_covered_by_target.""" + + def setUp(self): + with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info', + return_value=PROJECT_COV_INFO): + self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage( + REPO_PATH, PROJECT_NAME) + + @parameterized.parameterized.expand([({ + 'data': [] + },), ({ + 'data': [[]] + },), ({ + 'data': [{}] + },)]) + def test_malformed_cov_data(self, coverage_data): + """Tests that covered files can be retrieved from a coverage report.""" + with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage', + return_value=coverage_data): + self.oss_fuzz_coverage.get_files_covered_by_target(FUZZ_TARGET) + + def test_valid_target(self): + """Tests that covered files can be retrieved from a coverage report.""" + fuzzer_cov_data = _get_example_curl_coverage() + with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage', + return_value=fuzzer_cov_data): + file_list = self.oss_fuzz_coverage.get_files_covered_by_target( + FUZZ_TARGET) + + expected_file_list = _get_expected_curl_covered_file_list() + self.assertCountEqual(file_list, expected_file_list) + + def test_invalid_target(self): + """Tests passing invalid fuzz target returns None.""" + self.assertIsNone( + self.oss_fuzz_coverage.get_files_covered_by_target(INVALID_TARGET)) + + +class FilesystemCoverageGetFilesCoveredByTargetTest( + fake_filesystem_unittest.TestCase): + """Tests FilesystemCoverage.get_files_covered_by_target.""" + + def setUp(self): + _fuzzer_cov_data = _get_example_curl_coverage() + self._expected_file_list = _get_expected_curl_covered_file_list() + self.coverage_path = '/coverage' + self.filesystem_coverage = get_coverage.FilesystemCoverage( + REPO_PATH, self.coverage_path) + self.setUpPyfakefs() + self.fs.create_file(os.path.join(self.coverage_path, 'fuzzer_stats', + FUZZ_TARGET + '.json'), + contents=json.dumps(_fuzzer_cov_data)) + + def test_valid_target(self): + """Tests that covered files can be retrieved from a coverage report.""" + file_list = self.filesystem_coverage.get_files_covered_by_target( + FUZZ_TARGET) + self.assertCountEqual(file_list, self._expected_file_list) + + def test_invalid_target(self): + """Tests passing invalid fuzz target returns None.""" + self.assertIsNone( + self.filesystem_coverage.get_files_covered_by_target(INVALID_TARGET)) + + +class IsFileCoveredTest(unittest.TestCase): + """Tests for is_file_covered.""" + + def test_is_file_covered_covered(self): + """Tests that is_file_covered returns True for a covered file.""" + file_coverage = { + 'filename': '/src/systemd/src/basic/locale-util.c', + 'summary': { + 'regions': { + 'count': 204, + 'covered': 200, + 'notcovered': 200, + 'percent': 98.03 + } + } + } + self.assertTrue(get_coverage.is_file_covered(file_coverage)) + + def test_is_file_covered_not_covered(self): + """Tests that is_file_covered returns False for a not covered file.""" + file_coverage = { + 'filename': '/src/systemd/src/basic/locale-util.c', + 'summary': { + 'regions': { + 'count': 204, + 'covered': 0, + 'notcovered': 0, + 'percent': 0 + } + } + } + self.assertFalse(get_coverage.is_file_covered(file_coverage)) + + +class GetOssFuzzLatestCovReportInfo(unittest.TestCase): + """Tests that _get_oss_fuzz_latest_cov_report_info works as + intended.""" + + PROJECT = 'project' + LATEST_REPORT_INFO_URL = ('https://storage.googleapis.com/oss-fuzz-coverage/' + 'latest_report_info/project.json') + + @mock.patch('logging.error') + @mock.patch('http_utils.get_json_from_url', return_value={'coverage': 1}) + def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, + mock_error): + """Tests that _get_oss_fuzz_latest_cov_report_info works as intended.""" + result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT) + self.assertEqual(result, {'coverage': 1}) + mock_error.assert_not_called() + mock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL) + + @mock.patch('logging.error') + @mock.patch('http_utils.get_json_from_url', return_value=None) + def test_get_oss_fuzz_latest_cov_report_info_fail(self, _, mock_error): + """Tests that _get_oss_fuzz_latest_cov_report_info works as intended when we + can't get latest report info.""" + result = get_coverage._get_oss_fuzz_latest_cov_report_info('project') + self.assertIsNone(result) + mock_error.assert_called_with( + 'Could not get the coverage report json from url: %s.', + self.LATEST_REPORT_INFO_URL) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/http_utils.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/http_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dfcef216766cea9ac3c56da6580f512d585af1bd --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/http_utils.py @@ -0,0 +1,118 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utility module for HTTP.""" +import json +import logging +import os +import sys +import tempfile +import zipfile + +import requests + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import retry + +_DOWNLOAD_URL_RETRIES = 3 +_DOWNLOAD_URL_BACKOFF = 1 +_HTTP_REQUEST_TIMEOUT = 10 + + +def download_and_unpack_zip(url, extract_directory, headers=None): + """Downloads and unpacks a zip file from an HTTP URL. + + Args: + url: A url to the zip file to be downloaded and unpacked. + extract_directory: The path where the zip file should be extracted to. + headers: (Optional) HTTP headers to send with the download request. + + Returns: + True on success. + """ + if headers is None: + headers = {} + + if not os.path.exists(extract_directory): + logging.error('Extract directory: %s does not exist.', extract_directory) + return False + + # Gives the temporary zip file a unique identifier in the case that + # that download_and_unpack_zip is done in parallel. + with tempfile.NamedTemporaryFile(suffix='.zip') as tmp_file: + if not download_url(url, tmp_file.name, headers=headers): + return False + + try: + with zipfile.ZipFile(tmp_file.name, 'r') as zip_file: + zip_file.extractall(extract_directory) + except zipfile.BadZipFile: + logging.error('Error unpacking zip from %s. Bad Zipfile.', url) + return False + + return True + + +def download_url(*args, **kwargs): + """Wrapper around _download_url that returns False if _download_url + exceptions.""" + try: + return _download_url(*args, **kwargs) + except Exception: # pylint: disable=broad-except + return False + + +def get_json_from_url(url): + """Gets a json object from a specified HTTP URL. + + Args: + url: The url of the json to be downloaded. + + Returns: + A dictionary deserialized from JSON or None on failure. + """ + try: + return requests.get(url, timeout=_HTTP_REQUEST_TIMEOUT).json() + except (ValueError, TypeError, json.JSONDecodeError, + requests.exceptions.ReadTimeout) as err: + logging.error('Loading json from url %s failed with: %s.', url, str(err)) + return None + + +@retry.wrap(_DOWNLOAD_URL_RETRIES, _DOWNLOAD_URL_BACKOFF) +def _download_url(url, filename, headers=None): + """Downloads the file located at |url|, using HTTP to |filename|. + + Args: + url: A url to a file to download. + filename: The path the file should be downloaded to. + headers: (Optional) HTTP headers to send with the download request. + + Returns: + True on success. + """ + if headers is None: + headers = {} + + response = requests.get(url, headers=headers) + + if response.status_code != 200: + logging.error('Unable to download from: %s. Code: %d. Content: %s.', url, + response.status_code, response.content) + return False + + with open(filename, 'wb') as file_handle: + file_handle.write(response.content) + + return True diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/__init__.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..219edbe457260f6bb9c3310665d853f2720ffc1d --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/__init__.py @@ -0,0 +1,124 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run.""" +import logging +import os + +import environment + + +class BasePlatformConfig: + """Base class for PlatformConfig subclasses.""" + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or None.""" + path = os.getenv('PROJECT_SRC_PATH') + if not path: + logging.debug('No PROJECT_SRC_PATH.') + return path + + logging.debug('PROJECT_SRC_PATH: %s.', path) + return path + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('WORKSPACE') + + # Optional config variables. + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz. This is used only by GitHub + projects when commit fuzzing. It is not used when PR fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return None + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + # TODO(metzman) Rename base_commit to git_base_commit. + return os.getenv('GIT_BASE_COMMIT') + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + # TODO(metzman) Rename base_ref to git_base_ref. + return os.getenv('GIT_BASE_REF') + + @property + def pr_ref(self): + """Returns the pull request to checkout and fuzz. This is used only by + GitHub projects when PR fuzzing. It is not used when commit fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return None + + @property + def project_repo_owner(self): + """Returns the project repo owner (githubism).""" + return None + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return os.environ.get('REPOSITORY') + + @property + def actor(self): + """Name of the actor for the CI.""" + return None + + @property + def token(self): + """Returns the CI API token.""" + return None + + @property + def docker_in_docker(self): + """Returns whether or not CFL is running using Docker in Docker.""" + return environment.get_bool('DOCKER_IN_DOCKER', False) + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE') + + @property + def git_url(self): + """Returns the repo URL. This is only used by GitHub users. Right now it is + needed by external on GitHub because we need to clone a new repo because the + copy they give us doesn't work for diffing. It isn't used by OSS-Fuzz on + github users since the Git URL is determined using repo detection. + + TODO(metzman): Try to eliminate the need for this by making the clone + from external github projects usable. + TODO(metzman): As an easier goal, maybe make OSS-Fuzz GitHub use this too + for: 1. Consistency 2. Maybe it will allow use on forks.""" + return None diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gcb.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gcb.py new file mode 100644 index 0000000000000000000000000000000000000000..59b7e2fab641cc9709cba880b475a9395ae36d98 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gcb.py @@ -0,0 +1,40 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on Github.""" +import logging +import os + +import platform_config + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Google Cloud Build.""" + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or the default.""" + project_src_path = os.getenv('PROJECT_SRC_PATH', '/workspace') + logging.debug('PROJECT_SRC_PATH: %s.', project_src_path) + return project_src_path + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('WORKSPACE', '/builder/home') + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gsutil') diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github.py new file mode 100644 index 0000000000000000000000000000000000000000..dc66e495acd02bb3ede6b92e289a02e2216a219c --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github.py @@ -0,0 +1,146 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on Github.""" +import json +import logging +import os + +import platform_config + + +def _get_github_event_path(): + return os.getenv('GITHUB_EVENT_PATH') + + +def _get_event_data(): + """Returns the GitHub event data.""" + github_event_path = _get_github_event_path() + with open(github_event_path, encoding='utf-8') as file_handle: + return json.load(file_handle) + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for GitHub.""" + + def __init__(self): + self._event_data = _get_event_data() + self._event = os.getenv('GITHUB_EVENT_NAME') + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('GITHUB_WORKSPACE') + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz. This is used only by GitHub + projects when commit fuzzing. It is not used when PR fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return os.getenv('GITHUB_SHA') + + @property + def actor(self): + """Name of the actor for the CI.""" + return os.getenv('GITHUB_ACTOR') + + @property + def token(self): + """Returns the CI API token.""" + return os.getenv('GITHUB_TOKEN') + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or None. The path returned is relative to |self.workspace| since + on github the checkout will be relative to there.""" + project_src_path = super().project_src_path + if project_src_path is None: + # Not set for internal GitHub users. + return project_src_path + # On GitHub (external users), this path is relative to |workspace|. + return os.path.join(self.workspace, project_src_path) + + @property + def _project_repo_owner_and_name(self): + """Returns a tuple containing the project repo owner and the name of the + repo.""" + # On GitHub this includes owner and repo name. + repository = os.getenv('GITHUB_REPOSITORY') + # Use os.path.split to split owner from repo. + return os.path.split(repository) + + @property + def project_repo_owner(self): + """Returns the project repo owner (githubism).""" + return self._project_repo_owner_and_name[0] + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return self._project_repo_owner_and_name[1] + + @property + def git_url(self): + """Returns the repo URL. This is only used by GitHub users. Right now it is + needed by external on GitHub because we need to clone a new repo because the + copy they give us doesn't work for diffing. It isn't used by OSS-Fuzz on + github users since the Git URL is determined using repo detection. + + TODO(metzman): Try to eliminate the need for this by making the clone + from external github projects usable. + TODO(metzman): As an easier goal, maybe make OSS-Fuzz GitHub use this too + for: 1. Consistency 2. Maybe it will allow use on forks.""" + repository = os.getenv('GITHUB_REPOSITORY') + github_server_url = os.getenv('GITHUB_SERVER_URL', 'https://github.com') + # TODO(metzman): Probably need to change this to github.server_url. + return os.path.join(github_server_url, repository) + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + base_commit = None + if self._event == 'push': + base_commit = self._event_data['before'] + logging.debug('base_commit: %s', base_commit) + return base_commit + + @property + def pr_ref(self): + """Returns the pull request to checkout and fuzz. This is used only by + GitHub projects when PR fuzzing. It is not used when commit fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + if self._event == 'pull_request': + pr_ref = f'refs/pull/{self._event_data["pull_request"]["number"]}/merge' + logging.debug('pr_ref: %s', pr_ref) + return pr_ref + return None + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + return os.getenv('GITHUB_BASE_REF') diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github_test.py new file mode 100644 index 0000000000000000000000000000000000000000..11cc6866cdffd122bd0a1dbba91c1b87e676cc39 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github_test.py @@ -0,0 +1,87 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for platform_config.github.""" +import os +import unittest +from unittest import mock + +import platform_config.github +import test_helpers + +# pylint: disable=arguments-differ + + +class GetProjectRepoOwnerAndNameTest(unittest.TestCase): + """Tests for get_project_repo_owner and get_project_repo_name.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): + test_helpers.patch_environ(self) + self.repo_owner = 'repo-owner' + self.repo_name = 'repo-name' + os.environ['GITHUB_REPOSITORY'] = f'{self.repo_owner}/{self.repo_name}' + self.platform_conf = platform_config.github.PlatformConfig() + + def test_github_repository_owner(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + self.assertEqual(self.platform_conf.project_repo_owner, self.repo_owner) + + def test_github_repository_name(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + os.environ['GITHUB_REPOSITORY'] = f'{self.repo_owner}/{self.repo_name}' + self.assertEqual(self.platform_conf.project_repo_name, self.repo_name) + + +class ProjectSrcPathTest(unittest.TestCase): + """Tests for project_src_path.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.workspace = '/workspace' + os.environ['GITHUB_WORKSPACE'] = self.workspace + self.project_src_dir_name = 'project-src' + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github_unset(self, _): + """Tests that project_src_path returns None when no PROJECT_SRC_PATH is + set.""" + github_env = platform_config.github.PlatformConfig() + self.assertIsNone(github_env.project_src_path) + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github(self, _): + """Tests that project_src_path returns the correct result on GitHub.""" + os.environ['PROJECT_SRC_PATH'] = self.project_src_dir_name + expected_project_src_path = os.path.join(self.workspace, + self.project_src_dir_name) + github_env = platform_config.github.PlatformConfig() + self.assertEqual(github_env.project_src_path, expected_project_src_path) + + +class GetGitUrlTest(unittest.TestCase): + """Tests for GenericPlatformConfig.git_url.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): + test_helpers.patch_environ(self) + self.platform_conf = platform_config.github.PlatformConfig() + + def test_repository(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + os.environ['GITHUB_REPOSITORY'] = 'repo/owner' + self.assertEqual('https://github.com/repo/owner', + self.platform_conf.git_url) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py new file mode 100644 index 0000000000000000000000000000000000000000..186cbefc4db9d2dc3693e36a20ed4ec40227d748 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py @@ -0,0 +1,78 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on GitLab.""" +import logging +import os + +import environment +import platform_config + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for GitLab.""" + + @property + def workspace(self): + """Returns the workspace.""" + return os.path.join(os.getenv('CI_BUILDS_DIR'), os.getenv('CI_JOB_ID')) + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz.""" + return os.getenv('CI_COMMIT_SHA') + + @property + def project_src_path(self): + """Returns the directory with the source of the project""" + return os.getenv('CI_PROJECT_DIR') + + @property + def token(self): + """Returns the job token""" + return os.getenv('CI_JOB_TOKEN') + + @property + def project_repo_name(self): + """Returns the project's name""" + return os.getenv('CI_PROJECT_NAME') + + @property + def base_commit(self): + """Returns the previous commit sha for commit-fuzzing""" + base_commit = None + if os.getenv('CI_PIPELINE_SOURCE') == 'push': + base_commit = os.getenv('CI_COMMIT_BEFORE_SHA') + logging.debug('base_commit: %s.', base_commit) + return base_commit + + @property + def base_ref(self): + """Returns the base commit sha for a merge request""" + # Could also be CI_MERGE_REQUEST_TARGET_BRANCH_NAME. + return os.getenv('CI_MERGE_REQUEST_DIFF_BASE_SHA') + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gitlab') + + @property + def artifacts_dir(self): + """Gitlab: returns the directory to put artifacts""" + return environment.get('CFL_ARTIFACTS_DIR', 'artifacts') + + @property + def cache_dir(self): + """Gitlab: returns the directory to use as cache""" + return environment.get('CFL_CACHE_DIR', 'cache') diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py new file mode 100644 index 0000000000000000000000000000000000000000..75b26f526a4f887383afa122e668d2a6010ff606 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py @@ -0,0 +1,82 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for platform_config.""" +import os +import unittest + +import platform_config +import test_helpers + + +class GetProjectRepoOwnerAndNameTest(unittest.TestCase): + """Tests for get_project_repo_owner and get_project_repo_name.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.repo_owner = 'repo-owner' + self.repo_name = 'repo-name' + self.env = platform_config.BasePlatformConfig() + + def test_unset_repository(self): + """Tests that the correct result is returned when repository is not set.""" + self.assertIsNone(self.env.project_repo_name) + + def test_owner(self): + """Tests that the correct result is returned for owner.""" + self.assertIsNone(self.env.project_repo_owner) + + def test_empty_repository(self): + """Tests that the correct result is returned when repository is an empty + string.""" + os.environ['REPOSITORY'] = '' + self.assertEqual(self.env.project_repo_name, '') + + def test_repository(self): + """Tests that the correct result is returned when repository contains the + just the repo name (as it does outside of GitHub).""" + os.environ['REPOSITORY'] = self.repo_name + self.assertEqual(self.env.project_repo_name, self.repo_name) + + +class ProjectSrcPathTest(unittest.TestCase): + """Tests for project_src_path.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def test_not_github(self): + """Tests that project_src_path returns the correct result not on + GitHub.""" + project_src_path = 'project-src' + os.environ['PROJECT_SRC_PATH'] = project_src_path + generic_ci_env = platform_config.BasePlatformConfig() + self.assertEqual(generic_ci_env.project_src_path, project_src_path) + + +class GetGitUrlTest(unittest.TestCase): + """Tests for BasePlatformConfig.git_url.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.env = platform_config.BasePlatformConfig() + + def test_unset_repository(self): + """Tests that the correct result is returned when repository is not set.""" + self.assertEqual(self.env.git_url, None) + + def test_repository(self): + """Tests that the correct result is returned when GITHUB_REPOSITORY is + set.""" + os.environ['GITHUB_REPOSITORY'] = 'repo/owner' + self.assertIsNone(self.env.git_url) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/prow.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/prow.py new file mode 100644 index 0000000000000000000000000000000000000000..69c035ae80194e86b3fff7759db0f0f0aca4a64b --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/prow.py @@ -0,0 +1,64 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on prow.""" +import logging +import os + +import platform_config + +# pylint: disable=too-few-public-methods + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Prow.""" + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or the current directory if not. Prow will run ClusterfuzzLite + at the directory head for the repo.""" + project_src_path = os.getenv('PROJECT_SRC_PATH', os.getcwd()) + logging.debug('PROJECT_SRC_PATH: %s.', project_src_path) + return project_src_path + + @property + def workspace(self): + """Returns the workspace.""" + # Let Prow user override workspace, but default to using artifacts dir + return os.getenv('WORKSPACE', os.getenv('ARTIFACTS')) + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + return os.getenv('PULL_BASE_REF') + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return os.getenv('REPO_NAME') + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + return os.getenv('PULL_BASE_SHA') + + @property + def docker_in_docker(self): + """Returns True if using Docker in Docker.""" + return True + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gsutil') diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/standalone.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/standalone.py new file mode 100644 index 0000000000000000000000000000000000000000..1975dfb1b842a28b9f2ceea809ef2f0d4d7a4a49 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/platform_config/standalone.py @@ -0,0 +1,33 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run standalone.""" +import os + +import platform_config + +# pylint: disable=too-few-public-methods + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Standalone.""" + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'filesystem') + + @property + def filestore_root_dir(self): + """Returns the filestore used to store persistent data.""" + return os.environ['FILESTORE_ROOT_DIR'] diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..a136f6991083426eb939f2c1cdef8afd28dc96ea --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers.py @@ -0,0 +1,321 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for running fuzzers.""" +import enum +import logging +import os +import sys +import time + +import clusterfuzz_deployment +import fuzz_target +import generate_coverage_report +import workspace_utils +import sarif_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import utils + + +class RunFuzzersResult(enum.Enum): + """Enum result from running fuzzers.""" + ERROR = 0 + BUG_FOUND = 1 + NO_BUG_FOUND = 2 + + +class BaseFuzzTargetRunner: + """Base class for fuzzer runners.""" + + def __init__(self, config): + self.config = config + self.workspace = workspace_utils.Workspace(config) + self.clusterfuzz_deployment = ( + clusterfuzz_deployment.get_clusterfuzz_deployment( + self.config, self.workspace)) + + # Set by the initialize method. + self.fuzz_target_paths = None + + def get_fuzz_targets(self): + """Returns fuzz targets in out directory.""" + return utils.get_fuzz_targets(self.workspace.out) + + def initialize(self): + """Initialization method. Must be called before calling run_fuzz_targets. + Returns True on success.""" + # Use a separate initialization function so we can return False on failure + # instead of exceptioning like we need to do if this were done in the + # __init__ method. + + logging.info('Using %s sanitizer.', self.config.sanitizer) + + # TODO(metzman) Add a check to ensure we aren't over time limit. + if not self.config.fuzz_seconds or self.config.fuzz_seconds < 1: + logging.error( + 'Fuzz_seconds argument must be greater than 1, but was: %s.', + self.config.fuzz_seconds) + return False + + if not os.path.exists(self.workspace.out): + logging.error('Out directory: %s does not exist.', self.workspace.out) + return False + + if not os.path.exists(self.workspace.artifacts): + os.makedirs(self.workspace.artifacts) + elif (not os.path.isdir(self.workspace.artifacts) or + os.listdir(self.workspace.artifacts)): + logging.error('Artifacts path: %s exists and is not an empty directory.', + self.workspace.artifacts) + return False + + self.fuzz_target_paths = self.get_fuzz_targets() + logging.info('Fuzz targets: %s', self.fuzz_target_paths) + if not self.fuzz_target_paths: + logging.error('No fuzz targets were found in out directory: %s.', + self.workspace.out) + return False + + return True + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after running |fuzz_target_obj|.""" + raise NotImplementedError('Child class must implement method.') + + def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use + """Fuzzes with |fuzz_target_obj| and returns the result.""" + raise NotImplementedError('Child class must implement method.') + + @property + def quit_on_bug_found(self): + """Property that is checked to determine if fuzzing should quit after first + bug is found.""" + raise NotImplementedError('Child class must implement method.') + + def create_fuzz_target_obj(self, target_path, run_seconds): + """Returns a fuzz target object.""" + return fuzz_target.FuzzTarget(target_path, run_seconds, self.workspace, + self.clusterfuzz_deployment, self.config) + + def run_fuzz_targets(self): + """Runs fuzz targets. Returns True if a bug was found.""" + fuzzers_left_to_run = len(self.fuzz_target_paths) + + # Make a copy since we will mutate it. + fuzz_seconds = self.config.fuzz_seconds + + min_seconds_per_fuzzer = fuzz_seconds // fuzzers_left_to_run + bug_found = False + for target_path in self.fuzz_target_paths: + # By doing this, we can ensure that every fuzz target runs for at least + # min_seconds_per_fuzzer, but that other fuzzers will have longer to run + # if one ends early. + run_seconds = max(fuzz_seconds // fuzzers_left_to_run, + min_seconds_per_fuzzer) + + target = self.create_fuzz_target_obj(target_path, run_seconds) + start_time = time.time() + result = self.run_fuzz_target(target) + self.cleanup_after_fuzz_target_run(target) + + # It's OK if this goes negative since we take max when determining + # run_seconds. + fuzz_seconds -= time.time() - start_time + + fuzzers_left_to_run -= 1 + if not result.testcase or not result.stacktrace: + logging.info('Fuzzer %s finished running without reportable crashes.', + target.target_name) + continue + + bug_found = True + if self.quit_on_bug_found: + logging.info('Bug found. Stopping fuzzing.') + break + + # pylint: disable=undefined-loop-variable + if not target_path: + logging.error('Ran no fuzz targets.') + elif self.config.output_sarif: + # TODO(metzman): Handle multiple crashes. + write_fuzz_result_to_sarif(result, target_path, self.workspace) + self.clusterfuzz_deployment.upload_crashes() + return bug_found + + +def write_fuzz_result_to_sarif(fuzz_result, target_path, workspace): + """Write results of fuzzing to SARIF.""" + logging.info('Writing sarif results.') + sarif_utils.write_stacktrace_to_sarif(fuzz_result.stacktrace, target_path, + workspace) + + +class PruneTargetRunner(BaseFuzzTargetRunner): + """Runner that prunes corpora.""" + + @property + def quit_on_bug_found(self): + return False + + def run_fuzz_target(self, fuzz_target_obj): + """Prunes with |fuzz_target_obj| and returns the result.""" + result = fuzz_target_obj.prune() + logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path)) + self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name, + result.corpus_path, + replace=True) + return result + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after pruning with |fuzz_target_obj|.""" + fuzz_target_obj.free_disk_if_needed() + + +NON_FUZZ_TARGETS_FOR_COVERAGE = { + 'llvm-symbolizer', + 'jazzer_agent_deploy.jar', + 'jazzer_driver', + 'jazzer_driver_with_sanitizer', +} + + +def is_coverage_fuzz_target(file_path): + """Returns whether |file_path| is a fuzz target binary for the purposes of a + coverage report. Inspired by infra/base-images/base-runner/coverage.""" + if not os.path.isfile(file_path): + return False + if not utils.is_executable(file_path): + return False + filename = os.path.basename(file_path) + return filename not in NON_FUZZ_TARGETS_FOR_COVERAGE + + +def get_coverage_fuzz_targets(out): + """Returns a list of fuzz targets in |out| for coverage.""" + # We only want fuzz targets from the root because during the coverage build, + # a lot of the image's filesystem is copied into /out for the purpose of + # generating coverage reports. + fuzz_targets = [] + for filename in os.listdir(out): + file_path = os.path.join(out, filename) + if is_coverage_fuzz_target(file_path): + fuzz_targets.append(file_path) + return fuzz_targets + + +class CoverageTargetRunner(BaseFuzzTargetRunner): + """Runner that runs the 'coverage' command.""" + + @property + def quit_on_bug_found(self): + raise NotImplementedError('Not implemented for CoverageTargetRunner.') + + def get_fuzz_targets(self): + """Returns fuzz targets in out directory.""" + return get_coverage_fuzz_targets(self.workspace.out) + + def run_fuzz_targets(self): + """Generates a coverage report. Always returns False since it never finds + any bugs.""" + generate_coverage_report.generate_coverage_report( + self.fuzz_target_paths, self.workspace, self.clusterfuzz_deployment, + self.config) + return False + + def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use + """Fuzzes with |fuzz_target_obj| and returns the result.""" + raise NotImplementedError('Not implemented for CoverageTargetRunner.') + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after running |fuzz_target_obj|.""" + raise NotImplementedError('Not implemented for CoverageTargetRunner.') + + +class CiFuzzTargetRunner(BaseFuzzTargetRunner): + """Runner for fuzz targets used in CI (patch-fuzzing) context.""" + + @property + def quit_on_bug_found(self): + return True + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after running |fuzz_target_obj|.""" + fuzz_target_obj.free_disk_if_needed() + + def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use + return fuzz_target_obj.fuzz() + + +class BatchFuzzTargetRunner(BaseFuzzTargetRunner): + """Runner for fuzz targets used in batch fuzzing context.""" + + @property + def quit_on_bug_found(self): + return False + + def run_fuzz_target(self, fuzz_target_obj): + """Fuzzes with |fuzz_target_obj| and returns the result.""" + result = fuzz_target_obj.fuzz(batch=True) + logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path)) + self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name, + result.corpus_path) + return result + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): + """Cleans up after running |fuzz_target_obj|.""" + # This must be done after we upload the corpus, otherwise it will be deleted + # before we get a chance to upload it. We can't delete the fuzz target + # because it is needed when we upload the build. + fuzz_target_obj.free_disk_if_needed(delete_fuzz_target=False) + + +_MODE_RUNNER_MAPPING = { + 'batch': BatchFuzzTargetRunner, + 'coverage': CoverageTargetRunner, + 'prune': PruneTargetRunner, + 'code-change': CiFuzzTargetRunner, +} + + +def get_fuzz_target_runner(config): + """Returns a fuzz target runner object based on the mode of + |config|.""" + runner = _MODE_RUNNER_MAPPING[config.mode](config) + logging.info('run fuzzers MODE is: %s. Runner: %s.', config.mode, runner) + return runner + + +def run_fuzzers(config): # pylint: disable=too-many-locals + """Runs fuzzers for a specific OSS-Fuzz project. + + Args: + config: A RunFuzzTargetsConfig. + + Returns: + A RunFuzzersResult enum value indicating what happened during fuzzing. + """ + fuzz_target_runner = get_fuzz_target_runner(config) + if not fuzz_target_runner.initialize(): + # We didn't fuzz at all because of internal (CIFuzz) errors. And we didn't + # find any bugs. + return RunFuzzersResult.ERROR + + if not fuzz_target_runner.run_fuzz_targets(): + # We fuzzed successfully, but didn't find any bugs (in the fuzz target). + return RunFuzzersResult.NO_BUG_FOUND + + # We fuzzed successfully and found bug(s) in the fuzz targets. + return RunFuzzersResult.BUG_FOUND diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils_test.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e8870887c071e4694a6550af0a4f432ad3838a8f --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils_test.py @@ -0,0 +1,128 @@ +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for sarif_utils.py""" +import os +import unittest +from unittest import mock + +import sarif_utils + +CRASH_INFO_FILELINE = 403 + +TEST_DATA = os.path.join(os.path.dirname(__file__), 'test_data') + + +class GetSarifDataTest(unittest.TestCase): + """Tests for get_sarif_data.""" + + def setUp(self): + self.maxDiff = None # pylint: disable=invalid-name + + def test_get_sarif_data_none(self): + """Tests get_sarif_data when there was no crash.""" + self.assertEqual(sarif_utils.get_sarif_data(None, '/root/target'), + sarif_utils.SARIF_DATA) + + def test_ordinary_case(self): + stacktrace_filename = os.path.join(TEST_DATA, + 'sarif_utils_systemd_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + expected_result = { + 'level': 'error', + 'message': { + 'text': 'Heap-buffer-overflow\nREAD 4' + }, + 'locations': [{ + 'physicalLocation': { + 'artifactLocation': { + 'uri': 'src/core/fuzz-unit-file.c', + 'index': 0 + }, + 'region': { + 'startLine': 30, + # We don't have this granualarity fuzzing. + 'startColumn': 1, + } + } + }], + 'ruleId': 'heap-buffer-overflow', + 'ruleIndex': 2 + } + actual_result = sarif_utils.get_sarif_data( + stacktrace, '/root/target')['runs'][0]['results'][0] + self.assertEqual(actual_result, expected_result) + + def test_llvmfuzzertestoneinput_case(self): + stacktrace_filename = os.path.join(TEST_DATA, + 'sarif_utils_only_llvmfuzzer_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + actual_result = sarif_utils.get_sarif_data( + stacktrace, '/root/target')['runs'][0]['results'] + self.assertEqual(actual_result, []) + + def test_msan(self): + """Tests that MSAN stacktraces don't exception.""" + stacktrace_filename = os.path.join(TEST_DATA, 'sarif_utils_msan_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + + actual_result = sarif_utils.get_sarif_data(stacktrace, '/root/target') + + +class RedactSrcPathTest(unittest.TestCase): + """Tests for redact_src_path.""" + + def test_redact_src_path(self): + """Tests redact_src_path.""" + path = '/src/src-repo/subdir/file' + self.assertEqual(sarif_utils.redact_src_path(path), 'subdir/file') + + +def _get_mock_crash_info(): + """Returns a mock crash_info to be used in tests.""" + stack_frame = mock.MagicMock() + stack_frame.filename = '/src/repo-dir/sub/vuln.cc' + stack_frame.function_name = 'vuln_func' + stack_frame.fileline = CRASH_INFO_FILELINE + crash1_frames = [stack_frame, stack_frame] + frames = [crash1_frames] + crash_info = mock.MagicMock() + crash_info.frames = frames + crash_info.crash_state = 'vuln_func\nvuln_func0\nvuln_func1' + return crash_info + + +class GetErrorSourceInfoTest(unittest.TestCase): + """Tests for get_error_source_info.""" + + def test_redact_src_path(self): + """Tests that get_error_source_info finds the right source info.""" + crash_info = _get_mock_crash_info() + source_info = sarif_utils.get_error_source_info(crash_info) + expected_source_info = ('sub/vuln.cc', CRASH_INFO_FILELINE) + self.assertEqual(source_info, expected_source_info) + + +class GetRuleIndexTest(unittest.TestCase): + """Tests for get_rule_index.""" + CRASH_INFO_CRASH_TYPE = 'Heap-use-after-free READ 8' + + def test_get_rule_index(self): + """Tests that get_rule_index finds the right rule index.""" + index = sarif_utils.get_rule_index(self.CRASH_INFO_CRASH_TYPE) + self.assertEqual(sarif_utils.SARIF_RULES[index]['id'], + 'heap-use-after-free') + self.assertEqual(sarif_utils.get_rule_index('no-crashes'), 0) diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/TimeoutFuzzer.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/TimeoutFuzzer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3034d300ed52a6487df3f42a3e83325bae403ad9 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/TimeoutFuzzer.cpp @@ -0,0 +1,36 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Example of a standalone runner for "fuzz targets". +// It reads all files passed as parameters and feeds their contents +// one by one into the fuzz target (LLVMFuzzerTestOneInput). +// This runner does not do any fuzzing, but allows us to run the fuzz target +// on the test corpus (e.g. "do_stuff_test_data") or on a single file, +// e.g. the one that comes from a bug report. + +// This is a fuzz target that times out on every input by infinite looping. +// This is used for testing. +// Build instructions: +// 1. clang++ -fsanitize=fuzzer TimeoutFuzzer.cpp -o timeout_fuzzer +// 2. strip timeout_fuzzer +// The binary is stripped to save space in the git repo. + +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { + while (true) + ; + return 0; +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt new file mode 100644 index 0000000000000000000000000000000000000000..8caebad0cbf1d7778b7d7ea0346410ba012f8acd --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt @@ -0,0 +1,68 @@ +AddressSanitizer: heap-buffer-overflow on address 0x62500001b530 at pc 0x00000052138a bp 0x7ffe62db2c10 sp 0x7ffe62db23d8 +READ of size 52 at 0x62500001b530 thread T0 +SCARINESS: 26 (multi-byte-read-heap-buffer-overflow) + #0 0x521389 in __asan_memcpy /src/llvm-project/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:22:3 + #1 0x567590 in yr_object_set_string /src/yara/libyara/object.c:1122:5 + #2 0x5afced in dex_parse /src/yara/libyara/modules/dex/dex.c:781:5 + #3 0x5b4a8b in dex__load /src/yara/libyara/modules/dex/dex.c:1218:7 + #4 0x56537c in yr_modules_load /src/yara/libyara/modules.c:179:16 + #5 0x5d6583 in yr_execute_code /src/yara/libyara/exec.c:1276:18 + #6 0x56f5c0 in yr_scanner_scan_mem_blocks /src/yara/libyara/scanner.c:444:3 + #7 0x56bf23 in yr_rules_scan_mem_blocks /src/yara/libyara/rules.c:235:12 + #8 0x56c182 in yr_rules_scan_mem /src/yara/libyara/rules.c:285:10 + #9 0x5548d2 in LLVMFuzzerTestOneInput /src/yara/tests/oss-fuzz/dex_fuzzer.cc:40:3 + #10 0x45a3b1 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:556:15 + #11 0x459ad5 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:470:3 + #12 0x45be77 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:698:19 + #13 0x45cc05 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:830:5 + #14 0x44ac88 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:824:6 + #15 0x474ab2 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:19:10 + #16 0x7f4409b7a82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) + #17 0x41e348 in _start (out/dex_fuzzer+0x41e348) + +0x62500001b530 is located 0 bytes to the right of 9264-byte region [0x625000019100,0x62500001b530) +allocated by thread T0 here: + #0 0x521f4d in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:145:3 + #1 0x4331b7 in operator new(unsigned long) (out/dex_fuzzer+0x4331b7) + #2 0x459ad5 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:470:3 + #3 0x45be77 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:698:19 + #4 0x45cc05 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:830:5 + #5 0x44ac88 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:824:6 + #6 0x474ab2 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:19:10 + #7 0x7f4409b7a82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) + +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/llvm-project/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:22:3 in __asan_memcpy +Shadow bytes around the buggy address: + 0x0c4a7fffb650: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb660: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb670: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb680: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb690: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +=>0x0c4a7fffb6a0: 00 00 00 00 00 00[fa]fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6b0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb + Shadow gap: cc +==12==ABORTING \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_output.txt b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_output.txt new file mode 100644 index 0000000000000000000000000000000000000000..64cb0af8ceda12d9b7fbbb11a4463cd7b10c476a --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_output.txt @@ -0,0 +1,202 @@ +/github/workspace/build-out/do_stuff_fuzzer -timeout=25 -rss_limit_mb=2560 -dict=/github/workspace/build-out/do_stuff_fuzzer.dict -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmp9p1w4p8r/ -max_total_time=600 -print_final_stats=1 /github/workspace/cifuzz-corpus/do_stuff_fuzzer >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 77 ============ +Dictionary: 3 entries +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (86 inline 8-bit counters): 86 [0x6150e0, 0x615136), +INFO: Loaded 1 PC tables (86 PCs): 86 [0x5c8b08,0x5c9068), +INFO: 5 files found in /github/workspace/cifuzz-corpus/do_stuff_fuzzer +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +INFO: seed corpus: files: 5 min: 3b max: 44b total: 64b rss: 31Mb +#6 INITED cov: 64 ft: 70 corp: 5/64b exec/s: 0 rss: 32Mb +#9 NEW cov: 64 ft: 72 corp: 6/74b lim: 4096 exec/s: 0 rss: 32Mb L: 10/44 MS: 3 ChangeBit-InsertByte-ManualDict- DE: "foo"- +#17 NEW cov: 64 ft: 74 corp: 7/86b lim: 4096 exec/s: 0 rss: 32Mb L: 12/44 MS: 3 ChangeBit-ManualDict-PersAutoDict- DE: "ouch"-"foo"- +#18 NEW cov: 64 ft: 76 corp: 8/100b lim: 4096 exec/s: 0 rss: 32Mb L: 14/44 MS: 1 CrossOver- +#22 NEW cov: 64 ft: 78 corp: 9/141b lim: 4096 exec/s: 0 rss: 32Mb L: 41/44 MS: 4 InsertRepeatedBytes-CopyPart-ChangeBinInt-ChangeBit- +#24 NEW cov: 64 ft: 80 corp: 10/151b lim: 4096 exec/s: 0 rss: 32Mb L: 10/44 MS: 2 CrossOver-CopyPart- +#28 NEW cov: 64 ft: 81 corp: 11/171b lim: 4096 exec/s: 0 rss: 32Mb L: 20/44 MS: 4 InsertByte-PersAutoDict-ShuffleBytes-ManualDict- DE: "foo"-"ouch"- +#43 NEW cov: 65 ft: 83 corp: 12/175b lim: 4096 exec/s: 0 rss: 32Mb L: 4/44 MS: 5 InsertByte-ChangeBit-ManualDict-ManualDict-EraseBytes- DE: "bar"-"bar"- +#54 NEW cov: 65 ft: 84 corp: 13/191b lim: 4096 exec/s: 0 rss: 32Mb L: 16/44 MS: 1 CrossOver- +#64 NEW cov: 65 ft: 86 corp: 14/209b lim: 4096 exec/s: 0 rss: 32Mb L: 18/44 MS: 5 InsertByte-ChangeBinInt-CMP-PersAutoDict-CopyPart- DE: "\000\000"-"foo"- +#75 REDUCE cov: 65 ft: 86 corp: 14/203b lim: 4096 exec/s: 0 rss: 32Mb L: 35/44 MS: 1 EraseBytes- +#76 REDUCE cov: 65 ft: 86 corp: 14/195b lim: 4096 exec/s: 0 rss: 32Mb L: 36/36 MS: 1 EraseBytes- +================================================================= +==26==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000003114 at pc 0x00000056d1db bp 0x7fffd6a72bf0 sp 0x7fffd6a72be8 +READ of size 4 at 0x603000003114 thread T0 +SCARINESS: 17 (4-byte-read-heap-buffer-overflow) + #0 0x56d1da in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:26:10 + #1 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #2 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #5 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #6 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7fcfaa2aa082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #9 0x41f74d in _start (build-out/do_stuff_fuzzer+0x41f74d) + +DEDUP_TOKEN: DoStuff(std::__1::basic_string, std::__1::allocator > const&)--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +0x603000003114 is located 0 bytes to the right of 20-byte region [0x603000003100,0x603000003114) +allocated by thread T0 here: + #0 0x569dfd in operator new(unsigned long) /src/llvm-project/compiler-rt/lib/asan/asan_new_delete.cpp:95:3 + #1 0x56c9d4 in __libcpp_operator_new /usr/local/bin/../include/c++/v1/new:245:10 + #2 0x56c9d4 in __libcpp_allocate /usr/local/bin/../include/c++/v1/new:271:10 + #3 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator.h:105:38 + #4 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator_traits.h:262:20 + #5 0x56c9d4 in __vallocate /usr/local/bin/../include/c++/v1/vector:931:37 + #6 0x56c9d4 in vector /usr/local/bin/../include/c++/v1/vector:1236:9 + #7 0x56c9d4 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:14:20 + #8 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #9 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #10 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #11 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #12 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #13 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #14 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #15 0x7fcfaa2aa082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: operator new(unsigned long)--__libcpp_operator_new--__libcpp_allocate +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/cifuzz-example/my_api.cpp:26:10 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) +Shadow bytes around the buggy address: + 0x0c067fff85d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff85e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff85f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8600: fa fa fd fd fd fa fa fa fd fd fd fa fa fa fd fd + 0x0c067fff8610: fd fa fa fa fd fd fd fa fa fa 00 00 00 00 fa fa +=>0x0c067fff8620: 00 00[04]fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8630: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8640: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8650: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8660: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8670: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==26==ABORTING +MS: 4 PersAutoDict-ManualDict-CrossOver-PersAutoDict- DE: "foo"-"ouch"-"bar"-; base unit: 1a25c32303e03f997166aee1c665b5ae9f66ec7d +0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x66,0x6f,0x6f,0xff,0x1,0x62,0x61,0x72,0x63,0x68,0x6f,0x75,0x63,0x68,0x66,0x6f,0x66,0x6e,0x6f,0x6d,0x67,0x6d, +\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377foo\377\001barchouchfofnomgm +artifact_prefix='/tmp/tmp9p1w4p8r/'; Test unit written to /tmp/tmp9p1w4p8r/crash-1c750df432fe458b738987ba69cd20a598708775 +Base64: //////////////////////9mb2//AWJhcmNob3VjaGZvZm5vbWdt +stat::number_of_executed_units: 90 +stat::average_exec_per_sec: 0 +stat::new_units_added: 11 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 33 +/github/workspace/build-out/do_stuff_fuzzer -timeout=25 -rss_limit_mb=2560 -dict=/github/workspace/build-out/do_stuff_fuzzer.dict -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmp9p1w4p8r/ -max_total_time=600 -print_final_stats=1 /github/workspace/cifuzz-corpus/do_stuff_fuzzer >fuzz-1.log 2>&1 +================== Job 1 exited with exit code 77 ============ +Dictionary: 3 entries +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (86 inline 8-bit counters): 86 [0x6150e0, 0x615136), +INFO: Loaded 1 PC tables (86 PCs): 86 [0x5c8b08,0x5c9068), +INFO: 15 files found in /github/workspace/cifuzz-corpus/do_stuff_fuzzer +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +INFO: seed corpus: files: 15 min: 3b max: 44b total: 239b rss: 31Mb +#16 INITED cov: 65 ft: 86 corp: 13/159b exec/s: 0 rss: 32Mb +#38 NEW cov: 65 ft: 88 corp: 14/188b lim: 4096 exec/s: 0 rss: 32Mb L: 29/35 MS: 2 InsertByte-CopyPart- +#43 REDUCE cov: 65 ft: 88 corp: 14/187b lim: 4096 exec/s: 0 rss: 32Mb L: 2/35 MS: 5 InsertByte-ChangeByte-ChangeBinInt-EraseBytes-EraseBytes- +#64 NEW cov: 66 ft: 89 corp: 15/191b lim: 4096 exec/s: 0 rss: 32Mb L: 4/35 MS: 1 ChangeByte- +#78 REDUCE cov: 66 ft: 89 corp: 15/190b lim: 4096 exec/s: 0 rss: 32Mb L: 15/35 MS: 4 ChangeBinInt-CopyPart-EraseBytes-EraseBytes- +#95 REDUCE cov: 66 ft: 89 corp: 15/188b lim: 4096 exec/s: 0 rss: 32Mb L: 16/35 MS: 2 ChangeBinInt-EraseBytes- +#110 REDUCE cov: 66 ft: 89 corp: 15/184b lim: 4096 exec/s: 0 rss: 32Mb L: 31/31 MS: 5 CrossOver-ChangeByte-ShuffleBytes-InsertByte-EraseBytes- +#146 REDUCE cov: 66 ft: 89 corp: 15/183b lim: 4096 exec/s: 0 rss: 32Mb L: 1/31 MS: 1 EraseBytes- +#157 NEW cov: 66 ft: 90 corp: 16/210b lim: 4096 exec/s: 0 rss: 32Mb L: 27/31 MS: 1 CrossOver- +#230 REDUCE cov: 66 ft: 92 corp: 17/318b lim: 4096 exec/s: 0 rss: 32Mb L: 108/108 MS: 3 CopyPart-InsertRepeatedBytes-CrossOver- +#277 NEW cov: 66 ft: 94 corp: 18/429b lim: 4096 exec/s: 0 rss: 32Mb L: 111/111 MS: 2 ManualDict-CMP- DE: "bar"-"\000\000\000\000"- +#337 NEW cov: 67 ft: 95 corp: 19/439b lim: 4096 exec/s: 0 rss: 32Mb L: 10/111 MS: 5 ChangeByte-ChangeBit-ManualDict-CopyPart-EraseBytes- DE: "bar"- +================================================================= +==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000007d94 at pc 0x00000056d1db bp 0x7ffdb9da4b50 sp 0x7ffdb9da4b48 +READ of size 4 at 0x603000007d94 thread T0 +SCARINESS: 17 (4-byte-read-heap-buffer-overflow) + #0 0x56d1da in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:26:10 + #1 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #2 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #5 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #6 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7fc2c6bd3082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #9 0x41f74d in _start (build-out/do_stuff_fuzzer+0x41f74d) + +DEDUP_TOKEN: DoStuff(std::__1::basic_string, std::__1::allocator > const&)--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +0x603000007d94 is located 0 bytes to the right of 20-byte region [0x603000007d80,0x603000007d94) +allocated by thread T0 here: + #0 0x569dfd in operator new(unsigned long) /src/llvm-project/compiler-rt/lib/asan/asan_new_delete.cpp:95:3 + #1 0x56c9d4 in __libcpp_operator_new /usr/local/bin/../include/c++/v1/new:245:10 + #2 0x56c9d4 in __libcpp_allocate /usr/local/bin/../include/c++/v1/new:271:10 + #3 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator.h:105:38 + #4 0x56c9d4 in allocate /usr/local/bin/../include/c++/v1/__memory/allocator_traits.h:262:20 + #5 0x56c9d4 in __vallocate /usr/local/bin/../include/c++/v1/vector:931:37 + #6 0x56c9d4 in vector /usr/local/bin/../include/c++/v1/vector:1236:9 + #7 0x56c9d4 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) /src/cifuzz-example/my_api.cpp:14:20 + #8 0x56c5d6 in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:15:3 + #9 0x43de23 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #10 0x43d60a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #11 0x43ecd9 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:757:19 + #12 0x43f9a5 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:895:5 + #13 0x42ed0f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #14 0x458362 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #15 0x7fc2c6bd3082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: operator new(unsigned long)--__libcpp_operator_new--__libcpp_allocate +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/cifuzz-example/my_api.cpp:26:10 in DoStuff(std::__1::basic_string, std::__1::allocator > const&) +Shadow bytes around the buggy address: + 0x0c067fff8f60: fa fa fd fd fd fa fa fa fd fd fd fa fa fa fd fd + 0x0c067fff8f70: fd fa fa fa fd fd fd fa fa fa fd fd fd fa fa fa + 0x0c067fff8f80: fd fd fd fa fa fa fd fd fd fa fa fa fd fd fd fa + 0x0c067fff8f90: fa fa fd fd fd fa fa fa fd fd fd fa fa fa fd fd + 0x0c067fff8fa0: fd fa fa fa fd fd fd fa fa fa fd fd fd fa fa fa +=>0x0c067fff8fb0: 00 00[04]fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8fc0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8fd0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8fe0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff8ff0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c067fff9000: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==30==ABORTING +MS: 4 ShuffleBytes-ManualDict-CrossOver-PersAutoDict- DE: "foo"-"bar"-; base unit: 8fc7da8d952ed1aa5c7415e21b3d52b42402973d +0x66,0x6f,0x6f,0x63,0x6f,0x75,0x6f,0x75,0x63,0x68,0x63,0x68,0x66,0x62,0x61,0x72,0x6f,0x6f,0x6d,0x67,0x66,0x6f,0x6f,0x2f,0x99,0x6f,0x6f,0x90,0x6f,0x6f,0x6d,0x0,0x0,0x67,0x2f, +foocououchchfbaroomgfoo/\231oo\220oom\000\000g/ +artifact_prefix='/tmp/tmp9p1w4p8r/'; Test unit written to /tmp/tmp9p1w4p8r/crash-f8a2a1e84f58a2d676e5ad8078119a39b78df901 +Base64: Zm9vY291b3VjaGNoZmJhcm9vbWdmb28vmW9vkG9vbQAAZy8= +stat::number_of_executed_units: 366 +stat::average_exec_per_sec: 0 +stat::new_units_added: 11 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 33 diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict new file mode 100644 index 0000000000000000000000000000000000000000..6a82ac4b3aa09ea8bbe6fc127e1bad4ed1c28ebb --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict @@ -0,0 +1,6 @@ +# A dictionary for more efficient fuzzing of DoStuff(). +# If the inputs contain multi-byte tokens, list them here. +# See https://llvm.org/docs/LibFuzzer.html#dictionaries +"foo" +"bar" +"ouch" diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h new file mode 100644 index 0000000000000000000000000000000000000000..325aa15ccc7f6fbed196437aeb75c94a88a630a6 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h @@ -0,0 +1,19 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// A library that does ... stuff. +// Serves as an example of good fuzz testing and OSS-Fuzz integration. +#include + +size_t DoStuff(const std::string &str); diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_bug_summary.txt b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_bug_summary.txt new file mode 100644 index 0000000000000000000000000000000000000000..b55e9c6b73b5d645ca7fba6a196f2485bd423b24 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_bug_summary.txt @@ -0,0 +1,22 @@ +MemorySanitizer: use-of-uninitialized-value +#0 0x52675f in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:13:7 +#1 0x45a431 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:599:15 +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +#7 0x41eab8 in _start (out/do_stuff_fuzzer+0x41eab8) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) +Uninitialized value was created by a heap allocation +#0 0x4d57ad in malloc /src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cpp:901:3 +#1 0x437c07 in operator new(unsigned long) (out/do_stuff_fuzzer+0x437c07) +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +DEDUP_TOKEN: malloc--operator new(unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) + +SUMMARY: \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_output.txt b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_output.txt new file mode 100644 index 0000000000000000000000000000000000000000..c803bfb1c928e7613baa0f7dfd39238e59ecc9b4 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/msan_crash_fuzzer_output.txt @@ -0,0 +1,39 @@ +Dictionary: 3 entries +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (184 inline 8-bit counters): 184 [0x829300, 0x8293b8), +INFO: Loaded 1 PC tables (184 PCs): 184 [0x5dc910,0x5dd490), +INFO: 5 files found in /tmp/do_stuff_fuzzer_corpus +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +==13==WARNING: MemorySanitizer: use-of-uninitialized-value +#0 0x52675f in LLVMFuzzerTestOneInput /src/cifuzz-example/do_stuff_fuzzer.cpp:13:7 +#1 0x45a431 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:599:15 +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +#7 0x41eab8 in _start (out/do_stuff_fuzzer+0x41eab8) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) +Uninitialized value was created by a heap allocation +#0 0x4d57ad in malloc /src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cpp:901:3 +#1 0x437c07 in operator new(unsigned long) (out/do_stuff_fuzzer+0x437c07) +#2 0x45ba46 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:792:3 +#3 0x45bed9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:845:3 +#4 0x44a4bc in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:906:6 +#5 0x474432 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 +#6 0x7eff5562683f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2083f) +DEDUP_TOKEN: malloc--operator new(unsigned long)--fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) + +SUMMARY: MemorySanitizer: use-of-uninitialized-value /src/cifuzz-example/do_stuff_fuzzer.cpp:13:7 in LLVMFuzzerTestOneInput +Unique heap origins: 65 +Stack depot allocated bytes: 4424 +Unique origin histories: 29 +History depot allocated bytes: 696 +Exiting +MS: 0 ; base unit: 0000000000000000000000000000000000000000 + + +artifact_prefix='./'; Test unit written to ./crash-da39a3ee5e6b4b0d3255bfef95601890afd80709 +Base64: diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_msan_stack.txt b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_msan_stack.txt new file mode 100644 index 0000000000000000000000000000000000000000..9214d8f81f9c77c12b77b6da46db80473941f9fd --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_msan_stack.txt @@ -0,0 +1,62 @@ +Dictionary: 3 entries +2024-05-07 18:49:02,343 - root - INFO - Fuzzer: do_stuff_fuzzer. Detected bug. +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 1 modules (83 inline 8-bit counters): 83 [0x563ff0e03e98, 0x563ff0e03eeb), +INFO: Loaded 1 PC tables (83 PCs): 83 [0x563ff0e03ef0,0x563ff0e04420), +INFO: 0 files found in /github/workspace/cifuzz-corpus/do_stuff_fuzzer +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes +INFO: A corpus is not provided, starting from an empty corpus +#2 INITED cov: 2 ft: 2 corp: 1/1b exec/s: 0 rss: 69Mb +#4 NEW cov: 3 ft: 3 corp: 2/3b lim: 4096 exec/s: 0 rss: 69Mb L: 2/2 MS: 2 ChangeBit-InsertByte- +==23==WARNING: MemorySanitizer: use-of-uninitialized-value + #0 0x563ff0d278f0 in LLVMFuzzerTestOneInput /src/cifuzz-external-example/do_stuff_fuzzer.cpp:24:1 + #1 0x563ff0c24340 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13 + #2 0x563ff0c23b65 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:516:7 + #3 0x563ff0c25335 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:760:19 + #4 0x563ff0c26125 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector>&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:905:5 + #5 0x563ff0c14436 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:914:6 + #6 0x563ff0c40962 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f4c156ed082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 87b331c034a6458c64ce09c03939e947212e18ce) + #8 0x563ff0c055ad in _start (build-out/do_stuff_fuzzer+0x4a5ad) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) + Uninitialized value was stored to memory at + #0 0x563ff0d278e9 in LLVMFuzzerTestOneInput /src/cifuzz-external-example/do_stuff_fuzzer.cpp + #1 0x563ff0c24340 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13 + #2 0x563ff0c23b65 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:516:7 + #3 0x563ff0c25335 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:760:19 + #4 0x563ff0c26125 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector>&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:905:5 + #5 0x563ff0c14436 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:914:6 + #6 0x563ff0c40962 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f4c156ed082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 87b331c034a6458c64ce09c03939e947212e18ce) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) + Uninitialized value was created by a heap deallocation + #0 0x563ff0cc7480 in free /src/llvm-project/compiler-rt/lib/msan/msan_interceptors.cpp:218:3 + #1 0x563ff0d27800 in LLVMFuzzerTestOneInput /src/cifuzz-external-example/do_stuff_fuzzer.cpp:21:5 + #2 0x563ff0c24340 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:614:13 + #3 0x563ff0c23b65 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:516:7 + #4 0x563ff0c25335 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:760:19 + #5 0x563ff0c26125 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector>&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:905:5 + #6 0x563ff0c14436 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:914:6 + #7 0x563ff0c40962 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f4c156ed082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 87b331c034a6458c64ce09c03939e947212e18ce) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: MemorySanitizer: use-of-uninitialized-value /src/cifuzz-external-example/do_stuff_fuzzer.cpp:24:1 in LLVMFuzzerTestOneInput +Unique heap origins: 201 +Stack depot allocated bytes: 9764880 +Unique origin histories: 181 +History depot allocated bytes: 196608 +Exiting +MS: 5 ShuffleBytes-CopyPart-InsertByte-CopyPart-ManualDict- DE: "bar"-; base unit: adc83b19e793491b1c6ea0fd8b46cd9f32e592fc +0xa,0x62,0x61,0x72,0xa, +\012bar\012 +artifact_prefix='/tmp/tmp1tc5b3m2/'; Test unit written to /tmp/tmp1tc5b3m2/crash-c935b6724d7e27401ac9af3773700ca86ac38dea +Base64: CmJhcgo= +stat::number_of_executed_units: 159 +stat::average_exec_per_sec: 0 +stat::new_units_added: 1 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 69 diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt new file mode 100644 index 0000000000000000000000000000000000000000..71f6e29ad3bf104ca54293b7395f3c0057c205a0 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt @@ -0,0 +1,302 @@ +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82577 inline 8-bit counters): 82573 [0x7fc55e6bedf0, 0x7fc55e6d307d), 4 [0x5e9c28, 0x5e9c2c), +2023-05-04 01:02:55,065 - root - INFO - Not reporting crash in fuzz-bus-label because process timed out. +2023-05-04 01:02:55,069 - root - INFO - Deleting corpus and seed corpus of fuzz-bus-label to save disk. +INFO: Loaded 2 PC tables (82577 PCs): 82573 [0x7fc55e6d3080,0x7fc55e815950), 4 [0x5a6c78,0x5a6cb8), +INFO: 256 files found in /github/workspace/cifuzz-corpus/fuzz-bus-label +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 256 min: 1b max: 5242880b total: 30968483b rss: 48Mb +#257 INITED cov: 41 ft: 230 corp: 111/4360b exec/s: 0 rss: 73Mb +#131072 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#262144 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#524288 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 77Mb +#609082 DONE cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43505 rss: 77Mb +Done 609082 runs in 14 second(s) +stat::number_of_executed_units: 609082 +stat::average_exec_per_sec: 43505 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 77 +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-1.log 2>&1 +2023-05-04 01:02:55,082 - root - INFO - Deleting fuzz target: fuzz-bus-label. +2023-05-04 01:02:55,083 - root - INFO - Done deleting. +2023-05-04 01:02:55,084 - root - INFO - Fuzzer fuzz-bus-label finished running without reportable crashes. +2023-05-04 01:02:55,084 - root - INFO - Running fuzzer: fuzz-dhcp-server. +2023-05-04 01:02:55,085 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip +2023-05-04 01:02:55,088 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:02:55,145 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip HTTP/1.1" 200 806749 +2023-05-04 01:02:55,350 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83640 inline 8-bit counters): 82573 [0x7fe86ff70df0, 0x7fe86ff8507d), 1067 [0x60c638, 0x60ca63), +INFO: Loaded 2 PC tables (83640 PCs): 82573 [0x7fe86ff85080,0x7fe8700c7950), 1067 [0x60ca68,0x610d18), +INFO: 1153 files found in /github/workspace/cifuzz-corpus/fuzz-dhcp-server +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 1153 min: 1b max: 5242879b total: 17056071b rss: 50Mb +#1155 INITED cov: 577 ft: 1116 corp: 203/54Kb exec/s: 0 rss: 86Mb +#1167 NEW cov: 577 ft: 1117 corp: 204/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeASCIIInt-CrossOver- +#1509 NEW cov: 577 ft: 1118 corp: 205/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeBit-CopyPart- +#63018 NEW cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21006 rss: 86Mb L: 245/1071 MS: 4 InsertByte-ChangeByte-CMP-InsertByte- DE: "2\000\000\000\000\000\000\000"- +#65536 pulse cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21845 rss: 86Mb +Loaded 1024/1155 files from /github/workspace/cifuzz-corpus/fuzz-dhcp-server +#99784 NEW cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19956 rss: 105Mb L: 243/1071 MS: 2 ChangeASCIIInt-ChangeBinInt- +#131072 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 21845 rss: 105Mb +#262144 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 20164 rss: 105Mb +#275639 DONE cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19688 rss: 105Mb +###### Recommended dictionary. ###### +"2\000\000\000\000\000\000\000" # Uses: 17879 +###### End of recommended dictionary. ###### +Done 275639 runs in 14 second(s) +stat::number_of_executed_units: 275639 +stat::average_exec_per_sec: 19688 +stat::new_units_added: 4 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 105 +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-1.log 2>&1 +2023-05-04 01:03:18,374 - root - INFO - Not reporting crash in fuzz-dhcp-server because process timed out. +2023-05-04 01:03:18,377 - root - INFO - Deleting corpus and seed corpus of fuzz-dhcp-server to save disk. +2023-05-04 01:03:18,399 - root - INFO - Deleting fuzz target: fuzz-dhcp-server. +2023-05-04 01:03:18,400 - root - INFO - Done deleting. +2023-05-04 01:03:18,400 - root - INFO - Fuzzer fuzz-dhcp-server finished running without reportable crashes. +2023-05-04 01:03:18,401 - root - INFO - Running fuzzer: fuzz-bcd. +2023-05-04 01:03:18,401 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip +2023-05-04 01:03:18,404 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:18,582 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip HTTP/1.1" 200 2293254 +2023-05-04 01:03:18,804 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83175 inline 8-bit counters): 82573 [0x7f1b5387edf0, 0x7f1b5389307d), 602 [0x5f8718, 0x5f8972), +INFO: Loaded 2 PC tables (83175 PCs): 82573 [0x7f1b53893080,0x7f1b539d5950), 602 [0x5f8978,0x5faf18), +INFO: 1260 files found in /github/workspace/cifuzz-corpus/fuzz-bcd +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 946175 bytes +INFO: seed corpus: files: 1260 min: 1b max: 946175b total: 10373697b rss: 48Mb +#1261 INITED cov: 137 ft: 653 corp: 282/1416Kb exec/s: 0 rss: 91Mb +#65536 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#131072 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#262144 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 37449 rss: 98Mb +#475081 DONE cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 33934 rss: 98Mb +Done 475081 runs in 14 second(s) +stat::number_of_executed_units: 475081 +stat::average_exec_per_sec: 33934 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 98 +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-1.log 2>&1 +2023-05-04 01:03:41,821 - root - INFO - Not reporting crash in fuzz-bcd because process timed out. +2023-05-04 01:03:41,822 - root - INFO - Deleting corpus and seed corpus of fuzz-bcd to save disk. +2023-05-04 01:03:41,848 - root - INFO - Deleting fuzz target: fuzz-bcd. +2023-05-04 01:03:41,848 - root - INFO - Done deleting. +2023-05-04 01:03:41,848 - root - INFO - Fuzzer fuzz-bcd finished running without reportable crashes. +2023-05-04 01:03:41,848 - root - INFO - Running fuzzer: fuzz-varlink. +2023-05-04 01:03:41,849 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip +2023-05-04 01:03:41,852 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:41,906 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip HTTP/1.1" 200 2586434 +2023-05-04 01:03:42,671 - root - INFO - Starting fuzzing +2023-05-04 01:04:05,709 - root - INFO - Not reporting crash in fuzz-varlink because process timed out. +Fuzzing logs: +/github/workspace/build-out/fuzz-varlink -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpbtf4f932/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-varlink >fuzz-0.log 2>&1 +2023-05-04 01:04:05,709 - root - INFO - Deleting corpus and seed corpus of fuzz-varlink to save disk. +2023-05-04 01:04:05,806 - root - INFO - Deleting fuzz target: fuzz-varlink. +2023-05-04 01:04:05,806 - root - INFO - Done deleting. +2023-05-04 01:04:05,806 - root - INFO - Fuzzer fuzz-varlink finished running without reportable crashes. +2023-05-04 01:04:05,806 - root - INFO - Running fuzzer: fuzz-unit-file. +2023-05-04 01:04:05,807 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip +2023-05-04 01:04:05,809 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:04:05,897 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip HTTP/1.1" 200 4999974 +2023-05-04 01:04:07,869 - root - INFO - Starting fuzzing +2023-05-04 01:04:09,516 - root - INFO - Fuzzer: fuzz-unit-file. Detected bug. +Fuzzing logs: +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-0.log 2>&1 +2023-05-04 01:04:09,517 - root - INFO - Trying to reproduce crash using: /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03. +================== Job 0 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7f3b0de4cdf0, 0x7f3b0de6107d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7f3b0de61080,0x7f3b0dfa3950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==74==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7fffeea64fe0 sp 0x7fffeea64fd8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in LLVMFuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==74==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 67 +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-1.log 2>&1 +================== Job 1 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7ff1ba038df0, 0x7ff1ba04d07d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7ff1ba04d080,0x7ff1ba18f950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==78==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7ffc2e6825c0 sp 0x7ffc2e6825b8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--samLLVM2FuzzerTestOneInput --fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in samsamLLVM2FuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==78==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 68 diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/Makefile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..04db9976eac198bd430650da656998169912dc2f --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/Makefile @@ -0,0 +1,41 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 -Werror + +all: SystemSan target target_file target_dns + +SystemSan: SystemSan.cpp inspect_dns.cpp inspect_utils.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +# Needs atheris. +python-test: all + ./SystemSan python shell_injection_poc_fuzzer.py + +target: target.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +target_file: target_file.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +target_dns: target_dns.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +test: all vuln.dict + ./SystemSan ./target -dict=vuln.dict + ./SystemSan ./target_file -dict=vuln.dict + ./SystemSan ./target_dns -dict=vuln.dict + +pytorch-lightning-1.5.10: + cp SystemSan.cpp PoEs/pytorch-lightning-1.5.10/; \ + cd PoEs/pytorch-lightning-1.5.10/; \ + docker build . --tag syssan_pytorch-lightning; \ + docker run -t systemsan_pytorch-lightning:latest; + +node-shell-quote-v1.7.3: + cp SystemSan.cpp PoEs/node-shell-quote-v1.7.3/; \ + cd PoEs/node-shell-quote-v1.7.3/; \ + docker build . --tag systemsan_node-shell-quote; \ + docker run -t systemsan_node-shell-quote:latest; + +clean: + rm -f SystemSan /tmp/tripwire target target_file target_dns diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..120de50346ebeb22f0e173becb2f623e54e61139 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile @@ -0,0 +1,35 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Build and run the proof of error in shell-quote v1.7.3. + +FROM ghcr.io/aixcc-finals/base-builder + +RUN apt update && \ + apt install -y \ + vim \ + npm && \ + git clone \ + --depth 1 \ + https://github.com/substack/node-shell-quote.git && \ + npm config set @gitlab-org:registry \ + https://gitlab.com/api/v4/packages/npm/ + +COPY ./build.sh $SRC +RUN ./build.sh + +COPY . $SRC +RUN make SystemSan + +CMD ["make", "run"] diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Makefile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..bdf30d06cc05af35782b5ee878a7a65a5ccdf107 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Makefile @@ -0,0 +1,12 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 + +SystemSan: SystemSan.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +run: clean SystemSan target.js + ./SystemSan jsfuzz ./target.js + +clean: + rm -f SystemSan /tmp/tripwire diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b34a8c2b09f781b773ace8bc13dfb7d345b1cfd --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh @@ -0,0 +1,22 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build and install project (using current CFLAGS, CXXFLAGS). +npm install ./node-shell-quote/ + +# Build fuzzers. +npm i -g @gitlab-org/jsfuzz diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js new file mode 100644 index 0000000000000000000000000000000000000000..82608cd2169fc7d757e0d69782a8eaa3b5e9cc88 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js @@ -0,0 +1,35 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* Exploit shell quote with fuzzer's input as a parameter of echo. + * This PoC is extended from a report in GitHub Advisory Database: + * https://github.com/advisories/GHSA-g4rg-993r-mgx7 + * The original report records a shell injection exploit in shell-quote v1.7.2, + * we show that a similar shell corruption exploit still persists in v1.7.3, + * after a commit that intends to fix the original exploit. + * */ + +/* Fuzz the target program with buf generated by Jsfuzz. */ +function fuzz(buf) { + buf = String(buf) + const childProcess = require('child_process'); + const shellQuote = require('shell-quote'); + childProcess.execSync(shellQuote.quote(['echo', buf])); +} + +/* Run Jsfuzz. */ +module.exports = { + fuzz +}; diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c577797f37169886ac3ffd48e12ad21c5986689d --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile @@ -0,0 +1,32 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Build and run the proof of error in pytorch-lightning. + +FROM ghcr.io/aixcc-finals/base-builder-python + +RUN apt update && \ + apt install -y vim && \ + git clone \ + --depth 1 \ + --branch 1.5.10 \ + https://github.com/PyTorchLightning/pytorch-lightning.git + +COPY ./build.sh $SRC +RUN ./build.sh + +COPY . $SRC +RUN make SystemSan + +CMD ["make", "run"] diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..2169bc15a592d7136d9d166159eb09dec8c49d01 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile @@ -0,0 +1,12 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 + +SystemSan: SystemSan.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +run: clean SystemSan fuzz_pytorch_lightning.py + ./SystemSan ./fuzz_pytorch_lightning.py -dict=vuln.dict + +clean: + rm -f SystemSan /tmp/tripwire diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c9b1adbf5a1b1241e50b8e88a03529cfb69e0b0 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build and install project (using current CFLAGS, CXXFLAGS). +cd pytorch-lightning +pip3 install . + +# Build fuzzers in $OUT. +for fuzzer in $(find $SRC -name '*_fuzzer.py'); do + compile_python_fuzzer $fuzzer +done diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..0d07da3a6269381d688e8f3ac7da5d5d0ee7d04a --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py @@ -0,0 +1,65 @@ +#!/usr/local/bin/python3 +# +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Exploit pytorch lightning with fuzzer's input as a random env variable. + +This PoC is extended from a report in GitHub Advisory Database: +https://github.com/advisories/GHSA-r5qj-cvf9-p85h +The original report documents an exploit using a specific environment variable, +we show a way to achieve the same exploit with an arbitrary env variable. +""" + +import os +import sys +import atheris + +with atheris.instrument_imports(): + from pytorch_lightning import Trainer + from pytorch_lightning.utilities.argparse import parse_env_variables + + +def prepare_fuzzing_input(data): + """Prepare the data needed by the exploit with input data from fuzzers.""" + data = data.replace(b'\0', b'') + env_name = 'AN_ARBITRARY_ENV_NAME' + return data, env_name + + +def exploit_target(env_value, env_name): + """This target is based on a snippet from the official documentation of + `parse_env_variables`: + https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.utilities.argparse.html # pylint: disable=line-too-long + It might not be the most realistic example, + but serves as a PoC to show that SystemSan works for Python.""" + os.environb[env_name.encode()] = env_value + parse_env_variables(Trainer, template=env_name) + + +def TestOneInput(data): # pylint: disable=invalid-name + """Exploit the target only with input data from fuzzers.""" + env_value, env_name = prepare_fuzzing_input(data) + exploit_target(env_value, env_name) + + +def main(): + """Fuzz target with atheris.""" + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..0d19aa407357659d0beb8487443c65eead7dab6a --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict @@ -0,0 +1 @@ +"os.system('/tmp/tripwire')" diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/README.md b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48e111d1abc6d96661659f9a19dd7fc6f969baad --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/README.md @@ -0,0 +1,66 @@ +# System Sanitizers + +We use `ptrace` to instrument system calls made by the target program to detect +various vulnerabilities. + +## Command injection + +This detector currently works by + +- Checking if `execve` is called with `/tmp/tripwire` (which comes from our dictionary). +- Checking if `execve` is invoking a shell with invalid syntax. This is likely + caused by our input. + +## Arbitrary file open + +TODO: documentation. + +## Proof of concept + +### Cleanup +Note this will delete /tmp/tripwire if it exists. +```shell +make clean +``` + +### Run test +Note this will overwrite /tmp/tripwire if it exists. +```shell +make test +``` + +Look for one of the following lines: + +> ===BUG DETECTED: Shell injection=== + +which indicates the detection of executing the planted `/tmp/tripwire`. + + +> ===BUG DETECTED: Shell corruption=== + +which indicates the detection of executing a syntactic erroneous command. + + +### Command injection PoC in Python with `pytorch-lightning` +With `SystemSan`, [`Artheris`](https://github.com/google/atheris) can detect a shell injection bug in [version v1.5.10 of `pytorch-lightning`](https://github.com/PyTorchLightning/pytorch-lightning/tree/1.5.0). +```shell +make pytorch-lightning-1.5.10 +``` + +### Command injection PoC in JavaScript with `shell-quote` +With `SystemSan`, [`Jsfuzz`](https://gitlab.com/gitlab-org/security-products/analyzers/fuzzers/jsfuzz) can detect a shell corrpution bug in [the latest version (v1.7.3) of `shell-quote`](https://github.com/substack/node-shell-quote) without any seed. +```shell +make node-shell-quote-v1.7.3 +``` +This is based on [a shell injection exploit report](https://wh0.github.io/2021/10/28/shell-quote-rce-exploiting.html) of [version v1.7.2 of `shell-quote`](https://github.com/substack/node-shell-quote/tree/v1.7.2). +`SystemSan` can also discover the same shell injection bug with a corpus file containing: +``` +`:`/tmp/tripwire``:` +``` + +## Trophies + +- +- + + diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27e8795c55df12d3c17399eda52c738c1b914240 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp @@ -0,0 +1,493 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify shell injection vulnerabilities. */ + +/* C standard library */ +#include +#include +#include +#include + +/* POSIX */ +#include +#include +#include +#include + +/* Linux */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "inspect_utils.h" +#include "inspect_dns.h" + +#define DEBUG_LOGS 0 + +#if DEBUG_LOGS +#define debug_log(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fflush(stdout); \ + fputc('\n', stderr); \ + } while (0) +#else +#define debug_log(...) +#endif + +#define fatal_log(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + exit(EXIT_FAILURE); \ + } while (0) + +// The magic string that we'll use to detect full control over the command +// executed. +const std::string kTripWire = "/tmp/tripwire"; +// Shell injection bug confirmed with /tmp/tripwire. +const std::string kInjectionError = "Shell injection"; +// Shell corruption bug detected based on syntax error. +const std::string kCorruptionError = "Shell corruption"; +// The magic string that we'll use to detect arbitrary file open +const std::string kFzAbsoluteDirectory = "/fz/"; +// Arbitrary file open in /fz/ +const std::string kArbitraryFileOpenError = "Arbitrary file open"; +// Assuming only shorter (than this constant) top dir are legitly used. +constexpr int kRootDirMaxLength = 16; + +// The PID of the root process we're fuzzing. +pid_t g_root_pid; + +// Map of a PID/TID its PID/TID creator and wether it ran exec. +std::map root_pids; + +// Assuming the longest pathname is "/bin/bash". +constexpr int kShellPathnameLength = 20; + +// Syntax error messages of each shell. +const std::map> kShellSyntaxErrors = { + {"bash", + { + ": command not found", // General + ": syntax error", // Unfinished " or ' or ` or if, leading | or ; + ": missing `]'", // Unfinished [ + ": event not found", // ! leads large numbers + ": No such file or directory", // Leading < or / + }}, + {"csh", + { + ": Command not found.", // General + ": Missing }.", // Unfinished { + "Too many ('s.", // Unfinished ( + "Invalid null command.", // Leading | or < or > + "Missing name for redirect.", // Single < or > + ": No match.", // Leading ? or [ or * + "Modifier failed.", // Leading ^ + "No previous left hand side.", // A ^ + ": No such job.", // Leading % + ": No current job.", // A % + ": Undefined variable.", // Containing $ + ": Event not found.", // ! leads large numbers + // TODO: Make this more specific. + "Unmatched", // Unfinished " or ' or `, leading ; + }}, + {"dash", + { + "not found", // General + "Syntax error", // Unfinished " or ' or ` or if, leading | or ; or & + "missing ]", // Unfinished [ + "No such file", // Leading < + }}, + {"zsh", + { + ": command not found", // General + ": syntax error", // Unfinished " or ' or ` + ": ']' expected", // Unfinished [ + ": no such file or directory", // Leading < or / + ": parse error near", // Leading |, or & + ": no such user or named directory", // Leading ~ + }}, +}; + +// Shells used by Processes. +std::map g_shell_pids; + +struct Tracee { + pid_t pid; + bool syscall_enter = true; + + Tracee(pid_t pid) : pid(pid) {} +}; + +pid_t run_child(char **argv) { + // Run the program under test with its args as a child process + pid_t pid = fork(); + switch (pid) { + case -1: + fatal_log("Fork failed: %s", strerror(errno)); + case 0: + raise(SIGSTOP); + execvp(argv[0], argv); + fatal_log("execvp: %s", strerror(errno)); + } + return pid; +} + +// Construct a string with the memory specified in a register. +std::string read_string(pid_t pid, unsigned long reg, unsigned long length) { + auto memory = read_memory(pid, reg, length); + if (!memory.size()) { + return ""; + } + + std::string content(reinterpret_cast(memory.data()), + std::min(memory.size(), length)); + return content; +} + +void inspect_for_injection(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's registers for the sign of shell injection. + std::string path = read_string(pid, regs.rdi, kTripWire.length()); + if (!path.length()) { + return; + } + debug_log("inspecting"); + if (path == kTripWire) { + report_bug(kInjectionError, pid); + } +} + +std::string get_pathname(pid_t pid, const user_regs_struct ®s) { + // Parse the pathname from the memory specified in the RDI register. + std::string pathname = read_string(pid, regs.rdi, kShellPathnameLength); + debug_log("Pathname is %s (len %lu)\n", pathname.c_str(), pathname.length()); + return pathname; +} + +std::string match_shell(std::string binary_pathname); + +// Identify the exact shell behind sh +std::string identify_sh(std::string path) { + char shell_pathname[kShellPathnameLength]; + auto written = readlink(path.c_str(), shell_pathname, kShellPathnameLength - 1); + if (written == -1) { + std::cerr << "Cannot query which shell is behind sh: readlink failed on " + << path << ": " + << strerror(errno) << "\n"; + std::cerr << "Assuming the shell is dash\n"; + return "dash"; + } + shell_pathname[written] = '\0'; + + debug_log("sh links to %s\n", shell_pathname); + std::string shell_pathname_str(shell_pathname); + + return match_shell(shell_pathname_str); +} + +std::string match_shell(std::string binary_pathname) { + // Identify the name of the shell used in the pathname. + if (!binary_pathname.length()) { + return ""; + } + + // We use c_str() to accept only the null terminated string. + std::string binary_name = binary_pathname.substr( + binary_pathname.find_last_of("/") + 1).c_str(); + + debug_log("Binary is %s (%lu)\n", binary_name.c_str(), + binary_name.length()); + + for (const auto &item : kShellSyntaxErrors) { + std::string known_shell = item.first; + if (binary_name == "sh") { + debug_log("Matched sh: Needs to identify which specific shell it is.\n"); + return identify_sh(binary_pathname); + } + if (binary_name == known_shell) { + debug_log("Matched %s\n", binary_name.c_str()); + return known_shell; + } + } + return ""; +} + +std::string get_shell(pid_t pid, const user_regs_struct ®s) { + // Get shell name used in a process. + std::string binary_pathname = get_pathname(pid, regs); + return match_shell(binary_pathname); +} + +void match_error_pattern(std::string buffer, std::string shell, pid_t pid) { + auto error_patterns = kShellSyntaxErrors.at(shell); + for (const auto &pattern : error_patterns) { + if (buffer.find(pattern) != std::string::npos) { + std::cerr << "--- Found a sign of shell corruption ---\n" + << buffer.c_str() + << "\n----------------------------------------\n"; + // If a shell corruption error happens, kill its parent. + auto parent = root_pids[pid]; + while (!parent.ran_exec) { + if (parent.parent_tid == g_root_pid) { + break; + } + parent = root_pids[parent.parent_tid]; + } + report_bug(kCorruptionError, parent.parent_tid); + } + } +} + +void inspect_for_corruption(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's registers for shell corruption. + std::string buffer = read_string(pid, regs.rsi, regs.rdx); + debug_log("Write buffer: %s\n", buffer.c_str()); + match_error_pattern(buffer, g_shell_pids[pid], pid); +} + +void log_file_open(std::string path, int flags, pid_t pid) { + report_bug(kArbitraryFileOpenError, pid); + std::cerr << "===File opened: " << path.c_str() << ", flags = " << flags << ","; + switch (flags & 3) { + case O_RDONLY: + std::cerr << "O_RDONLY"; + break; + case O_WRONLY: + std::cerr << "O_WRONLY"; + break; + case O_RDWR: + std::cerr << "O_RDWR"; + break; + default: + std::cerr << "unknown"; + } + std::cerr << "===\n"; +} + +bool has_unprintable(const std::string &value) { + for (size_t i = 0; i < value.length(); i++) { + if (value[i] & 0x80) { + return true; + } + } + return false; +} + +void inspect_for_arbitrary_file_open(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's register for the sign of arbitrary file open. + std::string path = read_string(pid, regs.rsi, kRootDirMaxLength); + if (!path.length()) { + return; + } + if (path.substr(0, kFzAbsoluteDirectory.length()) == kFzAbsoluteDirectory) { + log_file_open(path, regs.rdx, pid); + return; + } + if (path[0] == '/' && path.length() > 1) { + std::string path_absolute_topdir = path; + size_t root_dir_end = path.find('/', 1); + if (root_dir_end != std::string::npos) { + path_absolute_topdir = path.substr(0, root_dir_end); + } + if (has_unprintable(path_absolute_topdir)) { + struct stat dirstat; + if (stat(path_absolute_topdir.c_str(), &dirstat) != 0) { + log_file_open(path, regs.rdx, pid); + } + } + } +} + +int trace(std::map pids) { + unsigned long exit_status = 0; + while (!pids.empty()) { + std::vector new_pids; + + auto it = pids.begin(); + + while (it != pids.end()) { + auto pid = it->first; + auto &tracee = it->second; + int status = 0; + + int result = waitpid(pid, &status, __WALL | WNOHANG); + if (result == -1) { + it = pids.erase(it); + continue; + } + + if (result == 0) { + // Nothing to report yet. + ++it; + continue; + } + + if (WIFEXITED(status) || WIFSIGNALED(status)) { + debug_log("%d exited", pid); + it = pids.erase(it); + // Remove pid from the watchlist when it exits + g_shell_pids.erase(pid); + root_pids.erase(pid); + continue; + } + + // ptrace sets 0x80 for syscalls (with PTRACE_O_TRACESYSGOOD set). + bool is_syscall = + WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80); + int sig = 0; + if (!is_syscall) { + // Handle generic signal. + siginfo_t siginfo; + if (ptrace(PTRACE_GETSIGINFO, pid, nullptr, &siginfo) == -1) { + debug_log("ptrace(PTRACE_GETSIGINFO, %d): %s", pid, strerror(errno)); + continue; + } + sig = siginfo.si_signo; + debug_log("forwarding signal %d to %d", sig, pid); + } + + if ((status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8)))) { + debug_log("%d exiting", pid); + if (pid == g_root_pid) { + if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &exit_status) == -1) { + debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno)); + } + debug_log("got exit status from root process: %lu", exit_status); + } + + if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) { + debug_log("ptrace(PTRACE_DETACH, %d): %s", pid, strerror(errno)); + } + continue; + } + + if (WIFSTOPPED(status) && + (status >> 8 == (SIGTRAP | (PTRACE_EVENT_CLONE << 8)) || + status >> 8 == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) || + status >> 8 == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)))) { + long new_pid; + if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &new_pid) == -1) { + debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno)); + continue; + } + debug_log("forked %ld", new_pid); + new_pids.push_back(new_pid); + root_pids.emplace(new_pid, ThreadParent(pid)); + } + + if (is_syscall) { + user_regs_struct regs; + if (ptrace(PTRACE_GETREGS, pid, 0, ®s) == -1) { + debug_log("ptrace(PTRACE_GETREGS, %d): %s", pid, strerror(errno)); + continue; + } + + if (tracee.syscall_enter) { + if (regs.orig_rax == __NR_execve) { + // This is a new process. + auto parent = root_pids[pid]; + parent.ran_exec = true; + root_pids[pid] = parent; + inspect_for_injection(pid, regs); + std::string shell = get_shell(pid, regs); + if (shell != "") { + debug_log("Shell parsed: %s", shell.c_str()); + g_shell_pids.insert(std::make_pair(pid, shell)); + } + } + + inspect_dns_syscalls(pid, regs); + + if (regs.orig_rax == __NR_openat) { + // TODO(metzman): Re-enable this once we have config/flag support. + // inspect_for_arbitrary_file_open(pid, regs); + } + + if (regs.orig_rax == __NR_write && + g_shell_pids.find(pid) != g_shell_pids.end()) { + debug_log("Inspecting the `write` buffer of shell process %d.", + pid); + inspect_for_corruption(pid, regs); + } + } + + // TODO: Check for commands with invalid syntax passed to /bin/sh and + // other shells. + // TODO: It's possible the process we're fuzzing can communicate with + // another process to execute code. Our check wouldn't catch this + // currently. + tracee.syscall_enter = !tracee.syscall_enter; + } + + if (ptrace(PTRACE_SYSCALL, pid, nullptr, sig) == -1) { + debug_log("ptrace(PTRACE_SYSCALL, %d): %s", pid, strerror(errno)); + continue; + } + + ++it; + } + + for (const auto &pid : new_pids) { + pids.emplace(pid, Tracee(pid)); + } + } + return static_cast(exit_status >> 8); +} + +int main(int argc, char **argv) { + if (argc <= 1) { + fatal_log("Expecting at least one arguments, received %d", argc - 1); + } + + // Create an executable tripwire file, as programs may check for existence + // before actually calling exec. + std::ofstream tripwire(kTripWire); + tripwire.close(); + chmod(kTripWire.c_str(), 0755); + + pid_t pid = run_child(argv + 1); + + long options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK | + PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | + PTRACE_O_TRACEEXIT; + + if (ptrace(PTRACE_SEIZE, pid, nullptr, options) == -1) { + fatal_log("ptrace(PTRACE_SEIZE): %s", strerror(errno)); + } + + if (waitpid(pid, nullptr, __WALL) == -1) { + fatal_log("waitpid: %s", strerror(errno)); + } + + if (ptrace(PTRACE_SYSCALL, pid, 0, 0) == -1) { + fatal_log("ptrace(PTRACE_SYSCALL): %s", strerror(errno)); + } + + g_root_pid = pid; + std::map pids; + pids.emplace(pid, Tracee(pid)); + root_pids.emplace(pid, ThreadParent(pid)); + return trace(pids); +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030446345096fedc53fe7ea5826a36982a460c42 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp @@ -0,0 +1,236 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify shell injection vulnerabilities. */ + +/* POSIX */ +#include +#include + +/* Linux */ +#include +#include +#include + +#include + +#include "inspect_utils.h" + + +// Arbitrary domain name resolution. +const std::string kArbitraryDomainNameResolution = "Arbitrary domain name resolution"; + +// Global constant for one file descriptor about of a DNS socket +int kFdDns = 0; +const size_t kDnsHeaderLen = 12; + + +void inspect_for_arbitrary_dns_connect(pid_t pid, const user_regs_struct ®s) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct sockaddr_in)); + if (memory.size()) { + struct sockaddr_in * sa = reinterpret_cast(memory.data()); + if (sa->sin_family == AF_INET && htons(sa->sin_port) == 53) { + // save file descriptor for later sendmmsg + kFdDns = regs.rdi; + } + } +} + +struct DnsHeader { + uint16_t tx_id; + uint16_t flags; + uint16_t questions; + uint16_t answers; + uint16_t nameservers; + uint16_t additional; +}; + +struct DnsHeader parse_dns_header(std::vector data) { + struct DnsHeader h; + h.tx_id = (((uint16_t) data[0]) << 8) | ((uint16_t) data[1]); + h.flags = (((uint16_t) data[2]) << 8) | ((uint16_t) data[3]); + h.questions = (((uint16_t) data[4]) << 8) | ((uint16_t) data[5]); + h.answers = (((uint16_t) data[6]) << 8) | ((uint16_t) data[7]); + h.nameservers = (((uint16_t) data[8]) << 8) | ((uint16_t) data[9]); + h.additional = (((uint16_t) data[10]) << 8) | ((uint16_t) data[11]); + return h; +} + +bool dns_flags_standard_query(uint16_t flags) { + if ((flags & 0x8000) == 0) { + // Query, not response. + if (((flags & 0x7800) >> 11) == 0) { + // Opcode 0 is standard query. + if ((flags & 0x0200) == 0) { + // Message is not truncated. + if ((flags & 0x0040) == 0) { + // Z-bit reserved flag is unset. + return true; + } + } + } + } + return false; +} + +struct DnsRequest { + // Start of name in the byte vector. + size_t offset; + // End of name in the byte vector. + size_t end; + // Length of top level domain. + uint8_t tld_size; + // Number of levels/dots in domain name. + size_t nb_levels; + // DNS type like A is 1. + uint16_t dns_type; + // DNS class like IN is 1. + uint16_t dns_class; +}; + +struct DnsRequest parse_dns_request(std::vector data, size_t offset) { + struct DnsRequest r; + r.offset = offset; + r.tld_size = 0; + r.nb_levels = 0; + while(offset < data.size()) { + uint8_t rlen = uint8_t(data[offset]); + if (rlen == 0) { + offset++; + break; + } + r.nb_levels++; + offset += rlen+1; + r.tld_size = rlen; + } + if (offset <= 4 + data.size()) { + r.end = offset; + r.dns_type = (((uint16_t) data[offset]) << 8) | ((uint16_t) data[offset+1]); + r.dns_class = (((uint16_t) data[offset+2]) << 8) | ((uint16_t) data[offset+3]); + } else { + r.end = data.size(); + } + return r; +} + +void log_dns_request(struct DnsRequest r, std::vector data) { + size_t offset = r.offset; + std::cerr << "===Domain resolved: "; + while(offset < r.end) { + uint8_t rlen = uint8_t(data[offset]); + if (rlen == 0) { + break; + } + std::cerr << '.'; + for (uint8_t i = 1; i < rlen+1; i++) { + std::cerr << (char) data[offset + i]; + } + offset += rlen+1; + } + std::cerr << "===\n"; + std::cerr << "===DNS request type: " << r.dns_type << ", class: " << r.dns_class << "===\n"; +} + +void inspect_for_arbitrary_dns_pkt(std::vector data, pid_t pid) { + if (data.size() < kDnsHeaderLen + 1) { + return; + } + struct DnsHeader h = parse_dns_header(data); + if (h.questions != 1) { + return; + } + if (h.answers != 0 || h.nameservers != 0) { + return; + } + if (!dns_flags_standard_query(h.flags)) { + return; + } + + struct DnsRequest req = parse_dns_request(data, kDnsHeaderLen); + // Alert if the top level domain is only one character and + // if there is more than just the TLD. + if (req.tld_size == 1 && req.nb_levels > 1 && req.end < data.size()) { + report_bug(kArbitraryDomainNameResolution, pid); + log_dns_request(req, data); + } +} + +void inspect_for_arbitrary_dns_fdbuffer(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, regs.rdx); + if (memory.size()) { + inspect_for_arbitrary_dns_pkt(memory, pid); + } + } +} + +void inspect_for_arbitrary_dns_iov(pid_t pid, unsigned long iov) { + auto memory = read_memory(pid, iov, sizeof(struct iovec)); + if (memory.size()) { + struct iovec * iovec = reinterpret_cast(memory.data()); + memory = read_memory(pid, (unsigned long) iovec->iov_base, iovec->iov_len); + if (memory.size()) { + inspect_for_arbitrary_dns_pkt(memory, pid); + } + } +} + +void inspect_for_arbitrary_dns_sendmsg(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct msghdr)); + if (memory.size()) { + struct msghdr * msg = reinterpret_cast(memory.data()); + if (msg->msg_iovlen == 1) { + inspect_for_arbitrary_dns_iov(pid, (unsigned long) msg->msg_iov); + } + } + } +} + +void inspect_for_arbitrary_dns_sendmmsg(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct mmsghdr)); + if (memory.size()) { + struct mmsghdr * msg = reinterpret_cast(memory.data()); + if (msg->msg_hdr.msg_iovlen == 1) { + inspect_for_arbitrary_dns_iov(pid, (unsigned long) msg->msg_hdr.msg_iov); + } + } + } +} + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s) { + switch (regs.orig_rax) { + case __NR_connect: + inspect_for_arbitrary_dns_connect(pid, regs); + break; + case __NR_close: + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + // reset DNS file descriptor on close + kFdDns = 0; + } + break; + case __NR_sendmmsg: + inspect_for_arbitrary_dns_sendmmsg(pid, regs); + break; + case __NR_sendmsg: + inspect_for_arbitrary_dns_sendmsg(pid, regs); + break; + case __NR_sendto: + // fallthrough + case __NR_write: + inspect_for_arbitrary_dns_fdbuffer(pid, regs); + } +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h new file mode 100644 index 0000000000000000000000000000000000000000..849af4e980679c3b8cbbd875216a06ba7b909f3a --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h @@ -0,0 +1,26 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +/* Linux */ +#include + + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s); diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..713d61d757c0c135271591bf17d9a1c108f37c27 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + +/* C standard library */ +#include + +/* POSIX */ +#include + +/* Linux */ +#include + +#include +#include +#include +#include + +#include "inspect_utils.h" + +extern pid_t g_root_pid; +extern std::map root_pids; + +std::vector read_memory(pid_t pid, unsigned long long address, + size_t size) { + std::vector memory; + + for (size_t i = 0; i < size; i += sizeof(long)) { + long word = ptrace(PTRACE_PEEKTEXT, pid, address + i, 0); + if (word == -1) { + return memory; + } + + std::byte *word_bytes = reinterpret_cast(&word); + memory.insert(memory.end(), word_bytes, word_bytes + sizeof(long)); + } + + return memory; +} + +void report_bug(std::string bug_type, pid_t tid) { + // Report the bug found based on the bug code. + std::cerr << "===BUG DETECTED: " << bug_type.c_str() << "===\n"; + // Rely on sanitizers/libFuzzer to produce a stacktrace by sending SIGABRT + // to the root process. + // Note: this may not be reliable or consistent if shell injection happens + // in an async way. + // Find the thread group id, that is the pid. + pid_t pid = tid; + auto parent = root_pids[tid]; + while (!parent.ran_exec) { + // Find the first parent which ran exec syscall. + if (parent.parent_tid == g_root_pid) { + break; + } + pid = parent.parent_tid; + parent = root_pids[parent.parent_tid]; + } + tgkill(pid, tid, SIGABRT); +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a0737f28b1ae8de07b002f03d56fdab471674723 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h @@ -0,0 +1,39 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +#include +#include + +// Structure to know which thread id triggered the bug. +struct ThreadParent { + // Parent thread ID, ie creator. + pid_t parent_tid; + // Current thread ID ran exec to become another process. + bool ran_exec = false; + + ThreadParent() : parent_tid(0) {} + ThreadParent(pid_t tid) : parent_tid(tid) {} +}; + +std::vector read_memory(pid_t pid, unsigned long long address, + size_t size); + +void report_bug(std::string bug_type, pid_t tid); diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb1b1dd0c2488c39f2d6de94f861dd1a96775b3a --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target.cpp @@ -0,0 +1,28 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* A sample target program under test, + * /tmp/tripwire or other commands will be injected into its shell command */ + +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + system(str.c_str()); + return 0; +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d7ef1ceef23bcb5ab7bca9a1933f6742fb054b7 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp @@ -0,0 +1,39 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#include +#include +#include +#include + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + + struct addrinfo *result = NULL; + + getaddrinfo(str.c_str(), NULL, NULL, &result); + if (result) { + freeaddrinfo(result); + } + + return 0; +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc55eb7f4c3e9778b378c16355a5f0fafeefbaf6 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp @@ -0,0 +1,32 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* A sample target program under test, + * /tmp/tripwire or other commands will be injected into its shell command */ + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + FILE *fp = fopen(str.c_str(), "r"); + if (fp) { + fclose(fp); + } + return 0; +} diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/vuln.dict b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..bf066ea4829f64c1138ed1021f857e2e4d8bd5fc --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/SystemSan/vuln.dict @@ -0,0 +1,3 @@ +"/tmp/tripwire" +"/fz/" +"f.z" \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/Dockerfile b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..579a46da68b2fb092a02ef73990be8d10dac7098 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/Dockerfile @@ -0,0 +1,18 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +FROM gcr.io/cloud-builders/gcloud + +RUN apt-get update && apt-get install -y jq \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/README.md b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67c59f71bd6108f0d12d1125e39f5a2a1eda9128 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/README.md @@ -0,0 +1,49 @@ +# Chronos: rebuilding OSS-Fuzz harnesses using cached builds + +## Pre-built images. + +Daily pre-built images are available at: + +- `us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/-ofg-cached-address` +- `us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/-ofg-cached-coverage` + +They can be used as drop-in replacements for the usual `gcr.io/oss-fuzz/` images. + +These images are generated in 2 ways: +- (Preferred) [Generate](https://github.com/google/oss-fuzz/blob/master/infra/base-images/base-builder/bash_parser.py) + a replay build script that can be re-run alongside existing build artifacts, + leveraging existing build system mechanisms to avoid rebuilding (e.g. running + `make` twice should not actually rebuild everything). This is error-prone, so + we validate the script works by running it. +- (Fallback, if the replay build script didn't work). We leverage + [ccache](https://ccache.dev/), to provide a compiler cache. This is often not + as fast as the replay build script, because some project builds spend + significant time doing non-compiler tasks (e.g. checking out submodules, + running configure scripts). + +Note: this mechanism does not work for every single OSS-Fuzz project today. The +resulting image may either: +- Not provide much performance improvement compared with a normal image, or +- Not exist at all (if neither approach worked). + +Stats from a recent run: +(Feb 3 2025). + +## Usage locally + +**Example 1: htslib** + +From the OSS-Fuzz root + +```sh +$ RUN_ALL=1 ./infra/experimental/chronos/build_cache_local.sh htslib c address +... +... +Vanilla compile time: +17 +Replay worked +Replay compile time: +2 +Ccache compile time: +9 +``` diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_all.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8f578084205f3ef21338021a525e1b043478302 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_all.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build all C/C++ projects. +c_project_yaml=$(find projects/ -name project.yaml -exec grep -l 'language: c' {} \;) +projs=$(echo $c_project_yaml | xargs dirname | xargs basename -a | sort) + +cd infra/experimental/chronos + +for proj in $projs; do + if [ ! -f ../../../projects/$proj/Dockerfile ]; then + # Incomplete integration. + echo "Skipping $proj as it's incomplete." + continue + fi + + echo ./build_on_cloudbuild.sh $proj c + ./build_on_cloudbuild.sh $proj c +done \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f3f20804f4ef9e9dbedd3275286bb4353ef422d --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh @@ -0,0 +1,163 @@ +#!/bin/bash -eu +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +_PROJECT=$1 +_FUZZING_LANGUAGE=$2 +_SANITIZER=${3:-address} + +BASE=$PWD + +# Final image is either ccache or replay script, depending on which worked. +FINAL_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-${_SANITIZER} + +# Always build an image with ccache. +CCACHE_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-${_SANITIZER} + +# Step 1: build the base image +cd projects/${_PROJECT} +docker build -t gcr.io/oss-fuzz/${_PROJECT} . + + +# Step 2: create a container where `compile` has run which enables ccaching +# and also generates a replay build script. +cd ${BASE} +mkdir -p ccaches/${_PROJECT} +mkdir -p build/out/${_PROJECT} +B_START=$SECONDS + +docker container rm -f ${_PROJECT}-origin-${_SANITIZER} + +docker run \ + --env=SANITIZER=${_SANITIZER} \ + --env=CCACHE_DIR=/workspace/ccache \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --env=CAPTURE_REPLAY_SCRIPT=1 \ + --name=${_PROJECT}-origin-${_SANITIZER} \ + -v=$PWD/ccaches/${_PROJECT}/ccache:/workspace/ccache \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + gcr.io/oss-fuzz/${_PROJECT} \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && compile" +B_TIME=$(($SECONDS - $B_START)) + +# Step 3: save (commit, locally) the cached container as an image +docker container commit -c "ENV REPLAY_ENABLED=1" -c "ENV CAPTURE_REPLAY_SCRIPT=" ${_PROJECT}-origin-${_SANITIZER} $FINAL_IMAGE_NAME + +# Step 4: save the list of executables created from a vanilla build. This is +# needed for validating if replay and ccaching works. +# notes: run a shell the container with e.g. +# `docker run --entrypoint /bin/bash -it local/ossfuzz/htslib-origin-address` +executables_vanilla="$(find ./build/out/${_PROJECT} -executable -type f | sort)" + + +# Step 5: Build with replay enabled, and validate the executables are the same +# in terms of naming. +# Note that an important step is removing everything in $OUT/ which is done +# in the docker command. +R_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + --name=${_PROJECT}-origin-${_SANITIZER}-replay-recached \ + $FINAL_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +R_TIME=$(($SECONDS - $R_START)) + +# Step 6: Extract the newly build executables +executables_replay="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + +echo "Executables vanilla: " +echo ${executables_vanilla} + +echo "------------------------------------------------------" +echo "Executables replay: " +echo ${executables_replay} + +REPLAY_WORKED= + +# Step 7: match executables from vanilla builds and replay builds. +# If this step is successful, then the process can exit as it's ready. +if [[ "$executables_replay" == "$executables_vanilla" ]] +then + REPLAY_WORKED=1 + + if [ -z "${RUN_ALL+1}" ]; then + echo "${_PROJECT}: Replay worked." + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME};" + exit 0 + fi +else + echo "${_PROJECT}: Replay did not work" + R_TIME="N/A" +fi + +# Step 8: prepare Dockerfile for ccache +cp -rf ccaches/${_PROJECT}/ccache ./projects/${_PROJECT}/ccache-cache + +infra/experimental/chronos/prepare-ccache ${_PROJECT} + +cd projects/${_PROJECT} + +# Step 9: Build an image with CCache's new items (modifications are done on the +# dockerfile) +docker build -t $CCACHE_IMAGE_NAME . + +cd ${BASE} + +# Step 10: Run a `compile` with ccache's image. +# Run the ccache build +A_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --name=${_PROJECT}-origin-${_SANITIZER}-recached \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + $CCACHE_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +A_TIME=$(($SECONDS - $A_START)) + +# Step 11: extract the executables from the ccache build +executables_ccache="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + + +# Step 12: validate the ccache builds are successful +if [[ "$executables_ccache" == "$executables_vanilla" ]] +then + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME}; CCache=${A_TIME};" + + if [[ -z "${REPLAY_WORKED}" || ${R_TIME} -gt ${A_TIME} ]]; then + if [ ${R_TIME} -gt ${A_TIME} ]; then + echo "Replay was slower than ccache." + fi + + # Replay didn't work or was slower, so make the default "cached" image use the ccache one. + docker image tag \ + $CCACHE_IMAGE_NAME \ + $FINAL_IMAGE_NAME + fi + + exit 0 +else + echo "${_PROJECT}: Replay and ccaching did not work." + exit 1 +fi + diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddcb567a53961994b68f0f112cf5ccdf1f6061d5 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +PROJECT=$1 +FUZZING_LANGUAGE=$2 + +gcloud builds submit "https://github.com/google/oss-fuzz" \ + --async \ + --git-source-revision=master \ + --config=cloudbuild.yaml \ + --substitutions=_PROJECT=$PROJECT,_FUZZING_LANGUAGE=$FUZZING_LANGUAGE \ + --project=oss-fuzz \ + --region=us-central1 diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/chronos.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/chronos.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd83b49095eafd5264d16195d5f80c4d204e8dbd --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/chronos.sh @@ -0,0 +1,81 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# This script records the ENV and commands needed for fuzz target recompilation. +# It intercepts bash commands to save: 1) the ENV variable values before +# building the fuzz target (`recompile_env.sh`) and 2) all subsequent bash +# commands from that point (`recompile`). Combined with Docker, this setup +# allows for recompiling the fuzz target without rebuilding the entire project. +# Usage: +# 1. Set FUZZ_TARGET (e.g., in project's Dockerfile) +# 2. Source this file before compiling the fuzz target (e.g., source chronos.sh +# at the beginning of project's build.sh). + +export START_RECORDING="false" +RECOMPILE_ENV="/usr/local/bin/recompile_env.sh" + + +# Initialize the recompile script as compile in case Chronos did not trap any +# command containing the fuzz target. +initialize_recompile_script() { + export RECOMPILE_SCRIPT="/usr/local/bin/recompile" + cp "/usr/local/bin/compile" "$RECOMPILE_SCRIPT" +} + +reset_recompile_script() { + rm "$RECOMPILE_SCRIPT" + echo "#!/bin/bash" > "$RECOMPILE_SCRIPT" + echo "source $RECOMPILE_ENV" >> "$RECOMPILE_SCRIPT" + chmod +x "$RECOMPILE_SCRIPT" +} + + +# Execute or record command for recompilation. +execute_or_record_command() { + record_command() { + echo "cd \"$(pwd)\"" >> "$RECOMPILE_SCRIPT" + echo "$@" >> "$RECOMPILE_SCRIPT" + } + + # Check if any element in the command array contains the FUZZ_TARGET. + if [[ "$BASH_COMMAND" == *"$FUZZ_TARGET"* ]]; then + export START_RECORDING="true" + # Save all environment variables, excluding read-only ones + reset_recompile_script + declare -p | grep -Ev 'declare -[^ ]*r[^ ]*' > "$RECOMPILE_ENV" + fi + + if [[ "$START_RECORDING" == "true" ]]; then + record_command "$BASH_COMMAND" + echo "Recorded execution of: $BASH_COMMAND" + fi +} + + +main() { + # Initialize. + initialize_recompile_script + + # Set up trap for DEBUG to intercept commands. + trap 'execute_or_record_command' DEBUG + + # Enable extended debugging mode + shopt -s extdebug + # Ensure trap works in subshells and functions. + set -T +} + +main diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7f584fc77bf03a7a1a71c784be1fce9c83aa5cd5 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml @@ -0,0 +1,58 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +# Supports building by way of ccache now. +# High-level steps: +# 1) Build image for project +# 2) Run an ASAN build and store ccache +# 3) Copy ccache cache to host and copy into project's OSS-Fuzz folder +# 4) Build image for project and copy ccache in, storing image as *-ofg-cache-address +# 5) Run an coverage build and store ccache +# 6) Copy ccache cache to host and copy into project's OSS-Fuzz folder +# 7) Build image for project and copy ccache in, storing image as *-ofg-cache-coverage +# TODO (David): add support for use of dedicated replay_build.sh +steps: +- name: 'gcr.io/cloud-builders/docker' + entrypoint: /bin/bash + args: + - /workspace/infra/experimental/chronos/build_cache_local.sh + - ${_PROJECT} + - ${_FUZZING_LANGUAGE} + - address + env: + - RUN_ALL=1 +- name: 'gcr.io/cloud-builders/docker' + entrypoint: /bin/bash + args: + - /workspace/infra/experimental/chronos/build_cache_local.sh + - ${_PROJECT} + - ${_FUZZING_LANGUAGE} + - coverage + env: + - RUN_ALL=1 +images: +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-address +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-coverage +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-address +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-coverage +timeout: 72000s # 20 hours, same as build_lib.py +logsBucket: oss-fuzz-gcb-logs +tags: +- ${_PROJECT} +- chronos +options: + pool: + name: projects/oss-fuzz/locations/us-central1/workerPools/buildpool-chronos diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e336525bedafd2843b82f45f5cc92721375362c3 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml @@ -0,0 +1,34 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +steps: +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - -t + - gcloud + - . + dir: infra/experimental/chronos +- name: 'gcloud' + args: + - infra/experimental/chronos/build_all.sh + entrypoint: /bin/bash +timeout: 1800s +serviceAccount: 'projects/oss-fuzz/serviceAccounts/llm-eval@oss-fuzz.iam.gserviceaccount.com' +options: + logging: CLOUD_LOGGING_ONLY +tags: +- chronos-all \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh new file mode 100644 index 0000000000000000000000000000000000000000..f48b335c552a0dd5347d72dcd5d0b566e6782ab6 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh @@ -0,0 +1,63 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Sample projects: simd, wt, libheif, htslib +PROJECT=liblouis +LOG=replay-${PROJECT}.txt +OUT1=replay-out-${PROJECT}-1 +OUT2=replay-out-${PROJECT}-2 +python infra/helper.py build_image --no-pull "$PROJECT" + +# AddressSanitizer. +mkdir -p build/out/${PROJECT} +echo "start" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +# Remove container name we are about to use. +docker container rm "${PROJECT}-origin-asan" + +# Build once, clean container if needed +docker run -v $PWD/build/out/${PROJECT}:/out \ + -ti --entrypoint="/bin/sh" \ + --env FUZZING_LANGUAGE=c --env SANITIZER="address" \ + --name "${PROJECT}-origin-asan" \ + "gcr.io/oss-fuzz/${PROJECT}" -c "compile" + +# Copy outs and log data +cp -rf $PWD/build/out/${PROJECT} ${OUT1} +rm -rf $PWD/build/out/${PROJECT} +ls -la $PWD/build/out/ >> ${LOG} +echo "next" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +docker commit "${PROJECT}-origin-asan" "gcr.io/oss-fuzz/${PROJECT}-ofg-cached-asan" + +# Run the replay command +docker run -v $PWD/build/out/${PROJECT}:/out \ + -e REPLAY_ENABLED=1 -ti --entrypoint="/bin/sh" \ + --env FUZZING_LANGUAGE=c --env SANITIZER="address" \ + "gcr.io/oss-fuzz/${PROJECT}-ofg-cached-asan" -c "compile" +echo "finish" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +cp -rf $PWD/build/out/${PROJECT} ${OUT2} + +# Now match the artifacts +SUCCESS=$(infra/experimental/chronos/match_artifacts $OUT1 $OUT2) + +if [[ $SUCCESS -eq 0 ]]; then + echo "SUCCESS REPLAY" >> ${LOG} +else + echo "FAIL REPLAY" >> ${LOG} +fi diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..39822c98ea26518efdc8cc770f983574827bddbf --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh @@ -0,0 +1,35 @@ +#!/usr/bin/bash -eux +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +CMP1=$1 +CMP2=$2 + +for exec1 in $(find $CMP1/ -type f -executable); do + base=$(basename $exec1) + + exec2=$CMP2/${base} + if [ ! -f ${exec2} ]; then + exit 1 + fi + + comparison=$(cmp --silent $exec1 $exec2; echo $?) + if [[ $comparison -ne 0 ]]; then + exit 1 + fi +done + +exit 0 diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-ccache b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-ccache new file mode 100644 index 0000000000000000000000000000000000000000..3b0f56719680dc7cbda30a7ab2b18b61365de5bb --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-ccache @@ -0,0 +1,22 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +PROJECT=$1 +{ + echo "COPY ccache-cache/ /ccache/cache"; + echo "ENV PATH=\"/ccache/bin:\$PATH\"" +} >> "projects/$PROJECT/Dockerfile" diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild new file mode 100644 index 0000000000000000000000000000000000000000..ebb4451f18c6ffda192e2dc6d5cfd5701a3b02a1 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild @@ -0,0 +1,21 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +PROJECT=$1 +{ + echo "ENV REPLAY_ENABLED=1"; +} >> "projects/$PROJECT/Dockerfile" diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3142ae038ae6b65902623f39df75b349ff7f67b --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md @@ -0,0 +1,3 @@ +# Moved + +This has moved to . diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/tools/wycheproof/.gitignore b/local-test-zookeeper-delta-01/fuzz-tooling/infra/tools/wycheproof/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..30d9eff972346c4978622c6f567e7808ad21764d --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/tools/wycheproof/.gitignore @@ -0,0 +1 @@ +wycheproof.zip \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/infra/tools/wycheproof/package.bash b/local-test-zookeeper-delta-01/fuzz-tooling/infra/tools/wycheproof/package.bash new file mode 100644 index 0000000000000000000000000000000000000000..842222587d1c414fba9451a9ac573f9cf35c93e1 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/infra/tools/wycheproof/package.bash @@ -0,0 +1,18 @@ +#!/bin/bash +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# Script for zipping ClusterFuzz's blackbox fuzzer for wycheproof. +zip wycheproof.zip run.py launcher.py