diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc b/local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9569343db26a021c7df7c10823b0b562cffde25 Binary files /dev/null and b/local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/constants.cpython-312.pyc differ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc b/local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38c5ef74a76adafd60a4187bcd3b14d2a96b7a42 Binary files /dev/null and b/local-test-commons-compress-delta-03/fuzz-tooling/infra/__pycache__/templates.cpython-312.pyc differ diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/README.md b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e155e2cb91f146dcac565bc60705d01b8ac74c98 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/README.md @@ -0,0 +1,6 @@ +Building all infra images: + +```bash +# run from project root +infra/base-images/all.sh +``` diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/aixcc_build_all.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/aixcc_build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed8eee86385559020055682e668aee685f68ad12 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/aixcc_build_all.sh @@ -0,0 +1,59 @@ +#!/bin/bash -eux + +if [ "$1" = "--cache-from" ]; then + PULL_CACHE=1 + shift + CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes + shift +elif [ "$1" = "--cache-to" ]; then + PUSH_CACHE=1 + shift + CACHE_TAG="${1//\//-}" # s/\//-/g -> for branch names that contain slashes + shift +fi + +ARG_TAG="$1" +shift + +BASE_IMAGES=( + "ghcr.io/aixcc-finals/base-image infra/base-images/base-image" + "ghcr.io/aixcc-finals/base-clang infra/base-images/base-clang" + "ghcr.io/aixcc-finals/base-builder infra/base-images/base-builder" + "ghcr.io/aixcc-finals/base-builder-go infra/base-images/base-builder-go" + "ghcr.io/aixcc-finals/base-builder-jvm infra/base-images/base-builder-jvm" + "ghcr.io/aixcc-finals/base-builder-python infra/base-images/base-builder-python" + "ghcr.io/aixcc-finals/base-builder-rust infra/base-images/base-builder-rust" + "ghcr.io/aixcc-finals/base-builder-ruby infra/base-images/base-builder-ruby" + "ghcr.io/aixcc-finals/base-builder-swift infra/base-images/base-builder-swift" + "ghcr.io/aixcc-finals/base-runner infra/base-images/base-runner" + "ghcr.io/aixcc-finals/base-runner-debug infra/base-images/base-runner-debug" +) + +for tuple in "${BASE_IMAGES[@]}"; do + read -r image path <<< "$tuple" + + if [ "${PULL_CACHE+x}" ]; then + + docker buildx build \ + --build-arg IMG_TAG="${ARG_TAG}" \ + --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \ + --tag "${image}:${ARG_TAG}" --push "$@" "${path}" + + elif [ "${PUSH_CACHE+x}" ]; then + + docker buildx build \ + --build-arg IMG_TAG="${ARG_TAG}" \ + --cache-from=type=registry,ref="${image}:${CACHE_TAG}" \ + --cache-to=type=registry,ref="${image}:${CACHE_TAG}",mode=max \ + --tag "${image}:${ARG_TAG}" --push "$@" "${path}" + + else + + docker buildx build \ + --build-arg IMG_TAG="${ARG_TAG}" \ + --tag "${image}:${ARG_TAG}" --push "$@" "${path}" + + fi + +done + diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/all.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/all.sh new file mode 100644 index 0000000000000000000000000000000000000000..75b806bbef6800e0f98c2682571aacf06f701071 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/base-images/all.sh @@ -0,0 +1,28 @@ +#!/bin/bash -eux +# Copyright 2016 Google Inc. +# +# 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. +# +################################################################################ + +docker build --pull -t ghcr.io/aixcc-finals/base-image "$@" infra/base-images/base-image +docker build -t ghcr.io/aixcc-finals/base-clang "$@" infra/base-images/base-clang +docker build -t ghcr.io/aixcc-finals/base-builder "$@" infra/base-images/base-builder +docker build -t ghcr.io/aixcc-finals/base-builder-go "$@" infra/base-images/base-builder-go +docker build -t ghcr.io/aixcc-finals/base-builder-jvm "$@" infra/base-images/base-builder-jvm +docker build -t ghcr.io/aixcc-finals/base-builder-python "$@" infra/base-images/base-builder-python +docker build -t ghcr.io/aixcc-finals/base-builder-rust "$@" infra/base-images/base-builder-rust +docker build -t ghcr.io/aixcc-finals/base-builder-ruby "$@" infra/base-images/base-builder-ruby +docker build -t ghcr.io/aixcc-finals/base-builder-swift "$@" infra/base-images/base-builder-swift +docker build -t ghcr.io/aixcc-finals/base-runner "$@" infra/base-images/base-runner +docker build -t ghcr.io/aixcc-finals/base-runner-debug "$@" infra/base-images/base-runner-debug diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build.py new file mode 100644 index 0000000000000000000000000000000000000000..a97a2e591ccf4ebbf59adb0eb9553c8fde0674e6 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build.py @@ -0,0 +1,292 @@ +#!/usr/bin/env python +# Copyright 2019 Google Inc. +# +# 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 modified projects.""" + +from __future__ import print_function + +import enum +import os +import re +import sys +import subprocess +import yaml + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import constants + +CANARY_PROJECT = 'skcms' + +DEFAULT_ARCHITECTURES = ['x86_64'] +DEFAULT_ENGINES = ['afl', 'honggfuzz', 'libfuzzer', 'centipede'] +DEFAULT_SANITIZERS = ['address', 'undefined'] + + +def get_changed_files_output(): + """Returns the output of a git command that discovers changed files.""" + branch_commit_hash = subprocess.check_output( + ['git', 'merge-base', 'HEAD', 'origin/HEAD']).strip().decode() + + return subprocess.check_output( + ['git', 'diff', '--name-only', branch_commit_hash + '..']).decode() + + +def get_modified_buildable_projects(): + """Returns a list of all the projects modified in this commit that have a + build.sh file.""" + git_output = get_changed_files_output() + projects_regex = '.*projects/(?P.*)/.*\n' + modified_projects = set(re.findall(projects_regex, git_output)) + projects_dir = os.path.join(get_oss_fuzz_root(), 'projects') + # Filter out projects without Dockerfile files since new projects and reverted + # projects frequently don't have them. In these cases we don't want Travis's + # builds to fail. + modified_buildable_projects = [] + for project in modified_projects: + if not os.path.exists(os.path.join(projects_dir, project, 'Dockerfile')): + print('Project {0} does not have Dockerfile. skipping build.'.format( + project)) + continue + modified_buildable_projects.append(project) + return modified_buildable_projects + + +def get_oss_fuzz_root(): + """Get the absolute path of the root of the oss-fuzz checkout.""" + script_path = os.path.realpath(__file__) + return os.path.abspath( + os.path.dirname(os.path.dirname(os.path.dirname(script_path)))) + + +def execute_helper_command(helper_command): + """Execute |helper_command| using helper.py.""" + root = get_oss_fuzz_root() + script_path = os.path.join(root, 'infra', 'helper.py') + command = ['python', script_path] + helper_command + print('Running command: %s' % ' '.join(command)) + subprocess.check_call(command) + + +def build_fuzzers(project, engine, sanitizer, architecture): + """Execute helper.py's build_fuzzers command on |project|. Build the fuzzers + with |engine| and |sanitizer| for |architecture|.""" + execute_helper_command([ + 'build_fuzzers', project, '--engine', engine, '--sanitizer', sanitizer, + '--architecture', architecture + ]) + + +def check_build(project, engine, sanitizer, architecture): + """Execute helper.py's check_build command on |project|, assuming it was most + recently built with |engine| and |sanitizer| for |architecture|.""" + execute_helper_command([ + 'check_build', project, '--engine', engine, '--sanitizer', sanitizer, + '--architecture', architecture + ]) + + +def should_build_coverage(project_yaml): + """Returns True if a coverage build should be done based on project.yaml + contents.""" + # Enable coverage builds on projects that use engines. Those that don't use + # engines shouldn't get coverage builds. + engines = project_yaml.get('fuzzing_engines', DEFAULT_ENGINES) + engineless = 'none' in engines + if engineless: + assert_message = ('Forbidden to specify multiple engines for ' + '"fuzzing_engines" if "none" is specified.') + assert len(engines) == 1, assert_message + return False + if 'wycheproof' in engines: + return False + + language = project_yaml.get('language') + if language not in constants.LANGUAGES_WITH_COVERAGE_SUPPORT: + print(('Project is written in "{language}", ' + 'coverage is not supported yet.').format(language=language)) + return False + + return True + + +def flatten_options(option_list): + """Generator that flattens |option_list| (a list of sanitizers, architectures + or fuzzing engines) by returning each element in the list that isn't a + dictionary. For elements that are dictionaries, the sole key is returned.""" + result = [] + for option in option_list: + if isinstance(option, dict): + keys = list(option.keys()) + assert len(keys) == 1 + result.append(keys[0]) + continue + result.append(option) + print(result) + return result + + +def should_build(project_yaml): + """Returns True on if the build specified is enabled in the project.yaml.""" + + if os.getenv('SANITIZER') == 'coverage': + # This assumes we only do coverage builds with libFuzzer on x86_64. + return should_build_coverage(project_yaml) + + def is_enabled(env_var, yaml_name, defaults): + """Is the value of |env_var| enabled in |project_yaml| (in the |yaml_name| + section)? Uses |defaults| if |yaml_name| section is unspecified.""" + return os.getenv(env_var) in flatten_options( + project_yaml.get(yaml_name, defaults)) + + return (is_enabled('ENGINE', 'fuzzing_engines', DEFAULT_ENGINES) and + is_enabled('SANITIZER', 'sanitizers', DEFAULT_SANITIZERS) and + is_enabled('ARCHITECTURE', 'architectures', DEFAULT_ARCHITECTURES)) + + +def build_project(project): + """Do the build of |project| that is specified by the environment variables - + SANITIZER, ENGINE, and ARCHITECTURE.""" + root = get_oss_fuzz_root() + project_yaml_path = os.path.join(root, 'projects', project, 'project.yaml') + with open(project_yaml_path) as file_handle: + project_yaml = yaml.safe_load(file_handle) + + if project_yaml.get('disabled', False): + print('Project {0} is disabled, skipping build.'.format(project)) + return + + engine = os.getenv('ENGINE') + sanitizer = os.getenv('SANITIZER') + architecture = os.getenv('ARCHITECTURE') + + if not should_build(project_yaml): + print(('Specified build: engine: {0}, sanitizer: {1}, architecture: {2} ' + 'not enabled for this project: {3}. Skipping build.').format( + engine, sanitizer, architecture, project)) + + return + + print('Building project', project) + build_fuzzers(project, engine, sanitizer, architecture) + + run_tests = project_yaml.get('run_tests', True) + if engine != 'none' and sanitizer != 'coverage' and run_tests: + check_build(project, engine, sanitizer, architecture) + + +class BuildModifiedProjectsResult(enum.Enum): + """Enum containing the return values of build_modified_projects().""" + NONE_BUILT = 0 + BUILD_SUCCESS = 1 + BUILD_FAIL = 2 + + +def build_modified_projects(): + """Build modified projects. Returns BuildModifiedProjectsResult.NONE_BUILT if + no builds were attempted. Returns BuildModifiedProjectsResult.BUILD_SUCCESS if + all attempts succeed, otherwise returns + BuildModifiedProjectsResult.BUILD_FAIL.""" + projects = get_modified_buildable_projects() + if not projects: + return BuildModifiedProjectsResult.NONE_BUILT + + failed_projects = [] + for project in projects: + try: + build_project(project) + except subprocess.CalledProcessError: + failed_projects.append(project) + + if failed_projects: + print('Failed projects:', ' '.join(failed_projects)) + return BuildModifiedProjectsResult.BUILD_FAIL + + return BuildModifiedProjectsResult.BUILD_SUCCESS + + +def is_infra_changed(): + """Returns True if the infra directory was changed.""" + git_output = get_changed_files_output() + infra_code_regex = '.*infra/.*\n' + return re.search(infra_code_regex, git_output) is not None + + +def build_base_images(): + """Builds base images.""" + # TODO(jonathanmetzman): Investigate why caching fails so often and + # when we improve it, build base-clang as well. Also, move this function + # to a helper command when we can support base-clang. + execute_helper_command(['pull_images']) + images = [ + 'base-image', + 'base-builder', + 'base-builder-go', + 'base-builder-javascript', + 'base-builder-jvm', + 'base-builder-python', + 'base-builder-rust', + 'base-builder-swift', + 'base-builder-ruby', + 'base-runner', + ] + for image in images: + try: + execute_helper_command(['build_image', image, '--no-pull', '--cache']) + except subprocess.CalledProcessError: + return 1 + + return 0 + + +def build_canary_project(): + """Builds a specific project when infra/ is changed to verify that infra/ + changes don't break things. Returns False if build was attempted but + failed.""" + + try: + build_project('skcms') + except subprocess.CalledProcessError: + return False + + return True + + +def main(): + """Build modified projects or canary project.""" + os.environ['OSS_FUZZ_CI'] = '1' + infra_changed = is_infra_changed() + if infra_changed: + print('Pulling and building base images first.') + if build_base_images(): + return 1 + + result = build_modified_projects() + if result == BuildModifiedProjectsResult.BUILD_FAIL: + return 1 + + # It's unnecessary to build the canary if we've built any projects already. + no_projects_built = result == BuildModifiedProjectsResult.NONE_BUILT + should_build_canary = no_projects_built and infra_changed + if should_build_canary and not build_canary_project(): + return 1 + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba3e5f31a2ed6fbc471be6d9aecdb1da16741e7 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/build_test.py @@ -0,0 +1,124 @@ +# 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 for build.py""" + +import os +import sys +import unittest +from unittest import mock + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.append(INFRA_DIR) + +from ci import build + + +def patch_environ(testcase_obj): + """Patch environment.""" + env = {} + patcher = mock.patch.dict(os.environ, env) + testcase_obj.addCleanup(patcher.stop) + patcher.start() + + +def _set_coverage_build(): + """Set the right environment variables for a coverage build.""" + os.environ['SANITIZER'] = 'coverage' + os.environ['ENGINE'] = 'libfuzzer' + os.environ['ARCHITECTURE'] = 'x86_64' + + +class TestShouldBuild(unittest.TestCase): + """Tests that should_build() works as intended.""" + + def setUp(self): + patch_environ(self) + + def test_none_engine_coverage_build(self): + """Tests that should_build returns False for a coverage build of a + project that specifies 'none' for fuzzing_engines.""" + _set_coverage_build() + project_yaml = { + 'language': 'c++', + 'fuzzing_engines': ['none'], + 'sanitizers': ['address'] + } + self.assertFalse(build.should_build(project_yaml)) + + def test_unspecified_engines_coverage_build(self): + """Tests that should_build returns True for a coverage build of a + project that doesn't specify fuzzing_engines.""" + _set_coverage_build() + project_yaml = {'language': 'c++'} + self.assertTrue(build.should_build(project_yaml)) + + def test_libfuzzer_coverage_build(self): + """Tests that should_build returns True for coverage build of a project + specifying 'libfuzzer' for fuzzing_engines.""" + _set_coverage_build() + project_yaml = { + 'language': 'c++', + 'fuzzing_engines': ['libfuzzer'], + 'sanitizers': ['address'] + } + self.assertTrue(build.should_build(project_yaml)) + + def test_go_coverage_build(self): + """Tests that should_build returns True for coverage build of a project + specifying 'libfuzzer' for fuzzing_engines.""" + _set_coverage_build() + project_yaml = {'language': 'go'} + self.assertTrue(build.should_build(project_yaml)) + + def test_engine_project_none_build(self): + """Tests that should_build returns False for an engine: 'none' build when + the project doesn't specify engines.""" + os.environ['SANITIZER'] = 'address' + os.environ['ENGINE'] = 'none' + os.environ['ARCHITECTURE'] = 'x86_64' + project_yaml = { + 'language': 'c++', + 'fuzzing_engines': ['libfuzzer'], + 'sanitizers': ['address'] + } + self.assertFalse(build.should_build(project_yaml)) + + def test_centipede_none_build(self): + """Tests that should_build returns True for none sanitizer build of a + project specifying 'centipede' for fuzzing_engines.""" + os.environ['SANITIZER'] = 'none' + os.environ['ENGINE'] = 'centipede' + os.environ['ARCHITECTURE'] = 'x86_64' + project_yaml = { + 'language': 'c++', + 'fuzzing_engines': ['centipede'], + 'sanitizers': ['none'] + } + self.assertTrue(build.should_build(project_yaml)) + + def test_centipede_address_build(self): + """Tests that should_build returns True for address sanitizer build of a + project specifying 'centipede' for fuzzing_engines.""" + os.environ['SANITIZER'] = 'address' + os.environ['ENGINE'] = 'centipede' + os.environ['ARCHITECTURE'] = 'x86_64' + project_yaml = { + 'language': 'c++', + 'fuzzing_engines': ['centipede'], + 'sanitizers': ['address'] + } + self.assertTrue(build.should_build(project_yaml)) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/requirements.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..303274fd5fbec5d190a3baa80dd449f579a2b5a9 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/ci/requirements.txt @@ -0,0 +1,9 @@ +# Requirements for submitting code changes to infra/ (needed by presubmit.py). +parameterized==0.7.4 +pyfakefs==4.5.6 +pylint==2.5.3 +pytest==7.1.2 +pytest-xdist==2.5.0 +PyYAML==6.0 +requests==2.31.0 +yapf==0.32.0 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/CHANGELOG b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/CHANGELOG new file mode 100644 index 0000000000000000000000000000000000000000..bc6699c0bd7688bffc217b5fe22bfb97487df366 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/CHANGELOG @@ -0,0 +1,3 @@ + Next Release: + + Improve detection of changed files better by fixing https://github.com/google/oss-fuzz/issues/7011 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py new file mode 100644 index 0000000000000000000000000000000000000000..c3784a4a505ce9de36c78a680d893ddd802b24e2 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets.py @@ -0,0 +1,113 @@ +# 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 dealing with fuzz targets affected by the change-under-test +(CUT).""" +import logging +import os +import sys + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils + + +def remove_unaffected_fuzz_targets(clusterfuzz_deployment, out_dir, + files_changed, repo_path): + """Removes all non affected fuzz targets in the out directory. + + Args: + clusterfuzz_deployment: The ClusterFuzz deployment object. + out_dir: The location of the fuzz target binaries. + files_changed: A list of files changed compared to HEAD. + repo_path: The location of the OSS-Fuzz repo in the docker image. + + This function will not delete fuzz targets unless it knows that the fuzz + targets are unaffected. For example, this means that fuzz targets which don't + have coverage data on will not be deleted. + """ + if not files_changed: + # Don't remove any fuzz targets if there is no difference from HEAD. + logging.info('No files changed compared to HEAD.') + return + + logging.info('Files changed in PR: %s', files_changed) + + fuzz_target_paths = utils.get_fuzz_targets(out_dir) + if not fuzz_target_paths: + # Nothing to remove. + logging.error('No fuzz targets found in out dir.') + return + + coverage = clusterfuzz_deployment.get_coverage(repo_path) + if not coverage: + # Don't remove any fuzz targets unless we have data. + logging.error('Could not find latest coverage report.') + return + + affected_fuzz_targets = get_affected_fuzz_targets(coverage, fuzz_target_paths, + files_changed) + + if not affected_fuzz_targets: + logging.info('No affected fuzz targets detected, keeping all as fallback.') + return + + logging.info('Using affected fuzz targets: %s.', affected_fuzz_targets) + unaffected_fuzz_targets = set(fuzz_target_paths) - affected_fuzz_targets + logging.info('Removing unaffected fuzz targets: %s.', unaffected_fuzz_targets) + + # Remove all the targets that are not affected. + for fuzz_target_path in unaffected_fuzz_targets: + try: + os.remove(fuzz_target_path) + except OSError as error: + logging.error('%s occurred while removing file %s', error, + fuzz_target_path) + + +def is_fuzz_target_affected(coverage, fuzz_target_path, files_changed): + """Returns True if a fuzz target (|fuzz_target_path|) is affected by + |files_changed|.""" + fuzz_target = os.path.basename(fuzz_target_path) + covered_files = coverage.get_files_covered_by_target(fuzz_target) + if not covered_files: + # Assume a fuzz target is affected if we can't get its coverage from + # OSS-Fuzz. + # TODO(metzman): Figure out what we should do if covered_files is []. + # Should we act as if we couldn't get the coverage? + logging.info('Could not get coverage for %s. Treating as affected.', + fuzz_target) + return True + + covered_files = [ + os.path.normpath(covered_file) for covered_file in covered_files + ] + logging.info('Fuzz target %s is affected by: %s', fuzz_target, covered_files) + for filename in files_changed: + if filename in covered_files: + logging.info('Fuzz target %s is affected by changed file: %s', + fuzz_target, filename) + return True + + logging.info('Fuzz target %s is not affected.', fuzz_target) + return False + + +def get_affected_fuzz_targets(coverage, fuzz_target_paths, files_changed): + """Returns a list of paths of affected targets.""" + affected_fuzz_targets = set() + for fuzz_target_path in fuzz_target_paths: + if is_fuzz_target_affected(coverage, fuzz_target_path, files_changed): + affected_fuzz_targets.add(fuzz_target_path) + + return affected_fuzz_targets diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3197ebbf1ae89dd327a2d4ea191f082360165389 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py @@ -0,0 +1,113 @@ +# 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 affected_fuzz_targets.py""" +import os +import shutil +import tempfile +import unittest +from unittest import mock + +import parameterized + +import affected_fuzz_targets +import clusterfuzz_deployment +import get_coverage +import test_helpers +import workspace_utils + +# pylint: disable=protected-access + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +EXAMPLE_FILE_CHANGED = 'test.txt' + +TEST_DATA_OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'test_data', 'build-out') + + +class RemoveUnaffectedFuzzTargetsTest(unittest.TestCase): + """Tests remove_unaffected_fuzzers.""" + + TEST_FUZZER_1 = os.path.join(TEST_DATA_OUT_PATH, 'example_crash_fuzzer') + TEST_FUZZER_2 = os.path.join(TEST_DATA_OUT_PATH, 'example_nocrash_fuzzer') + + # yapf: disable + @parameterized.parameterized.expand([ + # Tests specific affected fuzzers are kept. + ([[EXAMPLE_FILE_CHANGED], None], 2,), + + # Tests specific affected fuzzer is kept. + ([[EXAMPLE_FILE_CHANGED], ['not/a/real/file']], 1), + + # Tests all fuzzers are kept if none are deemed affected. + ([None, None], 2), + + # Tests that multiple fuzzers are kept if multiple fuzzers are affected. + ([[EXAMPLE_FILE_CHANGED], [EXAMPLE_FILE_CHANGED]], 2), + ]) + # yapf: enable + def test_remove_unaffected_fuzz_targets(self, side_effect, expected_dir_len): + """Tests that remove_unaffected_fuzzers has the intended effect.""" + config = test_helpers.create_run_config( + cfl_platform='github', + oss_fuzz_project_name=EXAMPLE_PROJECT, + workspace='/workspace') + workspace = workspace_utils.Workspace(config) + deployment = clusterfuzz_deployment.get_clusterfuzz_deployment( + config, workspace) + # We can't use fakefs in this test because this test executes + # utils.is_fuzz_target_local. This function relies on the executable bit + # being set, which doesn't work properly in fakefs. + with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( + 'get_coverage.OSSFuzzCoverage.get_files_covered_by_target' + ) as mock_get_files: + with mock.patch('get_coverage._get_oss_fuzz_fuzzer_stats_dir_url', + return_value=1): + mock_get_files.side_effect = side_effect + shutil.copy(self.TEST_FUZZER_1, tmp_dir) + shutil.copy(self.TEST_FUZZER_2, tmp_dir) + + affected_fuzz_targets.remove_unaffected_fuzz_targets( + deployment, tmp_dir, [EXAMPLE_FILE_CHANGED], '') + self.assertEqual(expected_dir_len, len(os.listdir(tmp_dir))) + + +class IsFuzzTargetAffectedTest(unittest.TestCase): + """Tests for is_fuzz_target_affected.""" + + def setUp(self): + self.fuzz_target_path = '/fuzz_target' + + def test_relative_paths(self): + """Tests that is_fuzz_target_affected works as intended when the covered + files are relative paths.""" + with mock.patch.object( + get_coverage.FilesystemCoverage, + 'get_files_covered_by_target', + ) as get_files_covered_by_target: + get_files_covered_by_target.return_value = [ + '/work/build/../../src/systemd/src/basic/alloc-util.c' + ] + coverage = get_coverage.FilesystemCoverage('/', '/') + + self.assertTrue( + affected_fuzz_targets.is_fuzz_target_affected( + coverage, self.fuzz_target_path, + ['/src/systemd/src/basic/alloc-util.c'])) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/base_runner_utils.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/base_runner_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d04a54adb18a2bcf7faf5402a93d5b078367d2e9 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/base_runner_utils.py @@ -0,0 +1,33 @@ +# 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. +"""Utilities for scripts from ghcr.io/aixcc-finals/base-runner.""" + +import os + +import config_utils + + +def get_env(config, workspace): + """Returns a dictionary containing the current environment with additional env + vars set to values needed to run a fuzzer.""" + env = os.environ.copy() + env['SANITIZER'] = config.sanitizer + env['FUZZING_LANGUAGE'] = config.language + env['OUT'] = workspace.out + env['CIFUZZ'] = 'True' + env['FUZZING_ENGINE'] = config_utils.DEFAULT_ENGINE + env['ARCHITECTURE'] = config.architecture + # Do this so we don't fail in tests. + env['FUZZER_ARGS'] = '-rss_limit_mb=2560 -timeout=25' + return env diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build-images.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build-images.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3d94c1f4cf29c3943d6cce7a06a2dba38af580e --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build-images.sh @@ -0,0 +1,34 @@ +#! /bin/bash -eux +# 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. + +# Script for building the docker images for cifuzz. + +CIFUZZ_DIR=$(dirname "$0") +CIFUZZ_DIR=$(realpath $CIFUZZ_DIR) +INFRA_DIR=$(realpath $CIFUZZ_DIR/..) +OSS_FUZZ_ROOT=$(realpath $INFRA_DIR/..) + +# Build cifuzz-base. +docker build --tag ghcr.io/aixcc-finals/cifuzz-base --file $CIFUZZ_DIR/cifuzz-base/Dockerfile $OSS_FUZZ_ROOT + +# Build run-fuzzers and build-fuzzers images. +docker build \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers-test:v1 \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 \ + --file $INFRA_DIR/build_fuzzers.Dockerfile $INFRA_DIR +docker build \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 \ + --tag ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers-test:v1 \ + --file $INFRA_DIR/run_fuzzers.Dockerfile $INFRA_DIR diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..fd15642e8d88c44f3ea82ba64108a8994d160ef0 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5bec6b5573cc7720f5031bc7d50de944320f81 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py @@ -0,0 +1,60 @@ +# 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. +"""Builds a specific OSS-Fuzz project's fuzzers for CI tools.""" +import logging +import sys + +import build_fuzzers +import logs +import config_utils + +# pylint: disable=c-extension-no-member +# pylint gets confused because of the relative import of cifuzz. + +logs.init() + + +def build_fuzzers_entrypoint(): + """Builds OSS-Fuzz project's fuzzers for CI tools.""" + config = config_utils.BuildFuzzersConfig() + + if config.dry_run: + # Sets the default return code on error to success. + returncode = 0 + else: + # The default return code when an error occurs. + returncode = 1 + + if not build_fuzzers.build_fuzzers(config): + logging.error('Error building fuzzers for (commit: %s, pr_ref: %s).', + config.git_sha, config.pr_ref) + return returncode + + return 0 + + +def main(): + """Builds OSS-Fuzz project's fuzzers for CI tools. + + Note: The resulting fuzz target binaries of this build are placed in + the directory: ${GITHUB_WORKSPACE}/out + + Returns: + 0 on success or nonzero on failure. + """ + return build_fuzzers_entrypoint() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py new file mode 100644 index 0000000000000000000000000000000000000000..36a4d4b2287401b29bf3f8b31c203296142b7179 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py @@ -0,0 +1,403 @@ +# 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 cifuzz module.""" +import os +import shutil +import sys +import tempfile +import unittest +from unittest import mock + +import parameterized + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.append(INFRA_DIR) + +OSS_FUZZ_DIR = os.path.dirname(INFRA_DIR) + +import build_fuzzers +import continuous_integration +import repo_manager +import test_helpers + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +# Location of data used for testing. +TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'test_data') + +# An example fuzzer that triggers an crash. +# Binary is a copy of the example project's do_stuff_fuzzer and can be +# generated by running "python3 infra/helper.py build_fuzzers example". +EXAMPLE_CRASH_FUZZER = 'example_crash_fuzzer' + +# An example fuzzer that does not trigger a crash. +# Binary is a modified version of example project's do_stuff_fuzzer. It is +# created by removing the bug in my_api.cpp. +EXAMPLE_NOCRASH_FUZZER = 'example_nocrash_fuzzer' + +# A fuzzer to be built in build_fuzzers integration tests. +EXAMPLE_BUILD_FUZZER = 'do_stuff_fuzzer' + +# pylint: disable=no-self-use,protected-access,too-few-public-methods,unused-argument + + +def docker_command_has_env_var_arg(command, env_var_arg): + """Returns True if a docker command has a specific env var argument.""" + for idx, element in enumerate(command): + if idx == 0: + # We're looking for the variable which can't be the first argument. + continue + + if element == env_var_arg and command[idx - 1] == '-e': + return True + return False + + +class BuildFuzzersTest(unittest.TestCase): + """Unit tests for build_fuzzers.""" + + @mock.patch('build_specified_commit.detect_main_repo', + return_value=('example.com', '/path')) + @mock.patch('repo_manager._clone', return_value=None) + @mock.patch('continuous_integration.checkout_specified_commit') + @mock.patch('helper.docker_run', return_value=False) # We want to quit early. + def test_cifuzz_env_var(self, mock_docker_run, _, __, ___): + """Tests that the CIFUZZ env var is set.""" + + with tempfile.TemporaryDirectory() as tmp_dir: + build_fuzzers.build_fuzzers( + test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name=EXAMPLE_PROJECT, + workspace=tmp_dir, + pr_ref='refs/pull/1757/merge')) + + docker_run_command = mock_docker_run.call_args_list[0][0][0] + + self.assertTrue( + docker_command_has_env_var_arg(docker_run_command, 'CIFUZZ=True')) + + @mock.patch('build_specified_commit.detect_main_repo', + return_value=('example.com', '/path')) + @mock.patch('repo_manager._clone', return_value=None) + @mock.patch('continuous_integration.checkout_specified_commit') + @mock.patch('helper.docker_run', return_value=False) # We want to quit early. + def test_extra_env_var(self, mock_docker_run, _, __, ___): + """Tests that the CIFUZZ env var is set.""" + + extra_env_var = 'CFL_EXTRA_TOKEN' + with tempfile.TemporaryDirectory() as tmp_dir: + with mock.patch.dict(os.environ, {extra_env_var: 'BLAH'}): + build_fuzzers.build_fuzzers( + test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name=EXAMPLE_PROJECT, + workspace=tmp_dir, + pr_ref='refs/pull/1757/merge')) + + docker_run_command = mock_docker_run.call_args_list[0][0][0] + self.assertTrue( + docker_command_has_env_var_arg(docker_run_command, extra_env_var)) + + +class InternalGithubBuildTest(unittest.TestCase): + """Tests for building OSS-Fuzz projects on GitHub actions.""" + PROJECT_REPO_NAME = 'myproject' + SANITIZER = 'address' + GIT_SHA = 'fake' + PR_REF = 'fake' + + def _create_builder(self, tmp_dir, oss_fuzz_project_name='myproject'): + """Creates an InternalGithubBuilder and returns it.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=oss_fuzz_project_name, + project_repo_name=self.PROJECT_REPO_NAME, + workspace=tmp_dir, + sanitizer=self.SANITIZER, + git_sha=self.GIT_SHA, + pr_ref=self.PR_REF, + cfl_platform='github') + cfl_platform = continuous_integration.get_ci(config) + builder = build_fuzzers.Builder(config, cfl_platform) + builder.repo_manager = repo_manager.RepoManager('/fake') + return builder + + @mock.patch('helper.docker_run', return_value=True) + @mock.patch('continuous_integration.checkout_specified_commit', + side_effect=None) + def test_correct_host_repo_path(self, _, __): + """Tests that the correct self.host_repo_path is set by + build_image_and_checkout_src. Specifically, we want the name of the + directory the repo is in to match the name used in the docker + image/container, so that it will replace the host's copy properly.""" + image_repo_path = '/src/repo_dir' + with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( + 'build_specified_commit.detect_main_repo', + return_value=('inferred_url', image_repo_path)): + builder = self._create_builder(tmp_dir) + builder.build_image_and_checkout_src() + + self.assertEqual(os.path.basename(builder.host_repo_path), + os.path.basename(image_repo_path)) + + @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build', + return_value=True) + def test_upload_build_disabled(self, mock_upload_build): + """Test upload build (disabled).""" + with tempfile.TemporaryDirectory() as tmp_dir: + builder = self._create_builder(tmp_dir) + builder.upload_build() + + mock_upload_build.assert_not_called() + + @mock.patch('repo_manager.RepoManager.get_current_commit', + return_value='commit') + @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_build', + return_value=True) + def test_upload_build(self, mock_upload_build, mock_get_current_commit): + """Test upload build.""" + with tempfile.TemporaryDirectory() as tmp_dir: + builder = self._create_builder(tmp_dir, oss_fuzz_project_name='') + builder.config.upload_build = True + builder.upload_build() + + mock_upload_build.assert_called_with('commit') + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class BuildFuzzersIntegrationTest(unittest.TestCase): + """Integration tests for build_fuzzers.""" + + def setUp(self): + self.temp_dir_ctx_manager = test_helpers.docker_temp_dir() + self.workspace = self.temp_dir_ctx_manager.__enter__() + self.out_dir = os.path.join(self.workspace, 'build-out') + test_helpers.patch_environ(self) + + base_runner_path = os.path.join(INFRA_DIR, 'base-images', 'base-runner') + os.environ['PATH'] = os.environ['PATH'] + os.pathsep + base_runner_path + + def tearDown(self): + self.temp_dir_ctx_manager.__exit__(None, None, None) + + def test_external_github_project(self): + """Tests building fuzzers from an external project on Github.""" + project_repo_name = 'external-project' + git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git' + # This test is dependant on the state of + # github.com/jonathanmetzman/cifuzz-external-example. + config = test_helpers.create_build_config( + project_repo_name=project_repo_name, + workspace=self.workspace, + git_url=git_url, + git_sha='HEAD', + cfl_platform='github', + base_commit='HEAD^1') + self.assertTrue(build_fuzzers.build_fuzzers(config)) + self.assertTrue( + os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER))) + + def test_external_generic_project(self): + """Tests building fuzzers from an external project not on Github.""" + project_repo_name = 'cifuzz-external-example' + git_url = 'https://github.com/jonathanmetzman/cifuzz-external-example.git' + # This test is dependant on the state of + # github.com/jonathanmetzman/cifuzz-external-example. + manager = repo_manager.clone_repo_and_get_manager( + 'https://github.com/jonathanmetzman/cifuzz-external-example', + self.workspace) + project_src_path = manager.repo_dir + config = test_helpers.create_build_config( + project_repo_name=project_repo_name, + workspace=self.workspace, + git_url=git_url, + filestore='no_filestore', + git_sha='HEAD', + project_src_path=project_src_path, + base_commit='HEAD^1') + self.assertTrue(build_fuzzers.build_fuzzers(config)) + self.assertTrue( + os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER))) + + def test_valid_commit(self): + """Tests building fuzzers with valid inputs.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='oss-fuzz', + workspace=self.workspace, + git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523', + base_commit='da0746452433dc18bae699e355a9821285d863c8', + cfl_platform='github') + self.assertTrue(build_fuzzers.build_fuzzers(config)) + self.assertTrue( + os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER))) + + def test_valid_pull_request(self): + """Tests building fuzzers with valid pull request.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='oss-fuzz', + workspace=self.workspace, + pr_ref='refs/pull/1757/merge', + base_ref='master', + cfl_platform='github') + self.assertTrue(build_fuzzers.build_fuzzers(config)) + self.assertTrue( + os.path.exists(os.path.join(self.out_dir, EXAMPLE_BUILD_FUZZER))) + + def test_invalid_pull_request(self): + """Tests building fuzzers with invalid pull request.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='oss-fuzz', + workspace=self.workspace, + pr_ref='ref-1/merge', + base_ref='master', + cfl_platform='github') + self.assertTrue(build_fuzzers.build_fuzzers(config)) + + def test_invalid_oss_fuzz_project_name(self): + """Tests building fuzzers with invalid project name.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name='not_a_valid_project', + project_repo_name='oss-fuzz', + workspace=self.workspace, + git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523') + self.assertFalse(build_fuzzers.build_fuzzers(config)) + + def test_invalid_repo_name(self): + """Tests building fuzzers with invalid repo name.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='not-real-repo', + workspace=self.workspace, + git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523') + self.assertFalse(build_fuzzers.build_fuzzers(config)) + + def test_invalid_git_sha(self): + """Tests building fuzzers with invalid commit SHA.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='oss-fuzz', + workspace=self.workspace, + git_sha='', + cfl_platform='github') + with self.assertRaises(AssertionError): + build_fuzzers.build_fuzzers(config) + + def test_invalid_workspace(self): + """Tests building fuzzers with invalid workspace.""" + config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='oss-fuzz', + workspace=os.path.join(self.workspace, 'not', 'a', 'dir'), + git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523') + self.assertFalse(build_fuzzers.build_fuzzers(config)) + + +class CheckFuzzerBuildTest(unittest.TestCase): + """Tests the check_fuzzer_build function in the cifuzz module.""" + + SANITIZER = 'address' + LANGUAGE = 'c++' + + def setUp(self): + self.temp_dir_obj = tempfile.TemporaryDirectory() + workspace_path = os.path.join(self.temp_dir_obj.name, 'workspace') + self.config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + sanitizer=self.SANITIZER, + language=self.LANGUAGE, + workspace=workspace_path, + pr_ref='refs/pull/1757/merge') + self.workspace = test_helpers.create_workspace(workspace_path) + shutil.copytree(TEST_DATA_PATH, workspace_path) + test_helpers.patch_environ(self, runner=True) + + def tearDown(self): + self.temp_dir_obj.cleanup() + + def test_correct_fuzzer_build(self): + """Checks check_fuzzer_build function returns True for valid fuzzers.""" + self.assertTrue(build_fuzzers.check_fuzzer_build(self.config)) + + def test_not_a_valid_path(self): + """Tests that False is returned when a nonexistent path is given.""" + self.config.workspace = 'not/a/valid/path' + self.assertFalse(build_fuzzers.check_fuzzer_build(self.config)) + + def test_no_valid_fuzzers(self): + """Tests that False is returned when an empty directory is given.""" + with tempfile.TemporaryDirectory() as tmp_dir: + self.config.workspace = tmp_dir + os.mkdir(os.path.join(self.config.workspace, 'build-out')) + self.assertFalse(build_fuzzers.check_fuzzer_build(self.config)) + + @mock.patch('utils.execute', return_value=(None, None, 0)) + def test_allow_broken_fuzz_targets_percentage(self, mock_execute): + """Tests that ALLOWED_BROKEN_TARGETS_PERCENTAGE is set when running + docker if passed to check_fuzzer_build.""" + percentage = '0' + self.config.allowed_broken_targets_percentage = percentage + build_fuzzers.check_fuzzer_build(self.config) + self.assertEqual( + mock_execute.call_args[1]['env']['ALLOWED_BROKEN_TARGETS_PERCENTAGE'], + percentage) + + +@unittest.skip('Test is too long to be run with presubmit.') +class BuildSantizerIntegrationTest(unittest.TestCase): + """Integration tests for the build_fuzzers. + Note: This test relies on "curl" being an OSS-Fuzz project.""" + PROJECT_NAME = 'curl' + PR_REF = 'fake_pr' + + @classmethod + def _create_config(cls, tmp_dir, sanitizer): + return test_helpers.create_build_config( + oss_fuzz_project_name=cls.PROJECT_NAME, + project_repo_name=cls.PROJECT_NAME, + workspace=tmp_dir, + pr_ref=cls.PR_REF, + sanitizer=sanitizer) + + @parameterized.parameterized.expand([('memory',), ('undefined',)]) + def test_valid_project_curl(self, sanitizer): + """Tests that MSAN can be detected from project.yaml""" + with tempfile.TemporaryDirectory() as tmp_dir: + self.assertTrue( + build_fuzzers.build_fuzzers(self._create_config(tmp_dir, sanitizer))) + + +class GetDockerBuildFuzzersArgsNotContainerTest(unittest.TestCase): + """Tests that _get_docker_build_fuzzers_args_not_container works as + intended.""" + + def test_get_docker_build_fuzzers_args_no_container(self): + """Tests that _get_docker_build_fuzzers_args_not_container works + as intended.""" + host_repo_path = '/host/repo' + result = build_fuzzers._get_docker_build_fuzzers_args_not_container( + host_repo_path) + expected_result = ['-v', '/host/repo:/host/repo'] + self.assertEqual(result, expected_result) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..920e32e42965c314c7fcc5c7808315bb68e051a0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.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. +"""Builds fuzzers and runs fuzzers. Entrypoint used for external users""" +import logging +import sys + +import build_fuzzers_entrypoint +import run_fuzzers_entrypoint + + +def main(): + """Builds and runs fuzzers for CI tools. + + NOTE: Any crash report will be in the filepath: $WORKSPACE/out/testcase + This can be used with GitHub's upload-artifact action to surface the logs. + + Required environment variables: + Returns: + 0 on success or 1 on failure. + """ + logging.debug("Using cifuzz_combined_entrypoint.") + result = build_fuzzers_entrypoint.build_fuzzers_entrypoint() + if result != 0: + return result + return run_fuzzers_entrypoint.run_fuzzers_entrypoint() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py new file mode 100644 index 0000000000000000000000000000000000000000..30e28beda330c621ac3a0f5b9d1ee2dc11a5e463 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cloudbuild.yaml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..03b1961e50ff9c701133753e918179177323726e --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/cloudbuild.yaml @@ -0,0 +1,52 @@ +# TODO(metzman): Get rid of cifuzz-build-fuzzers and cifuzz-run-fuzzers. +steps: +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - '-t' + - ghcr.io/aixcc-finals/cifuzz-base + - '-t' + - ghcr.io/aixcc-finals/cifuzz-base:v1 + - '-f' + - infra/cifuzz/cifuzz-base/Dockerfile + - . +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - '-t' + - ghcr.io/aixcc-finals/cifuzz-build-fuzzers + - '-t' + - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1 + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 + - '-f' + - infra/build_fuzzers.Dockerfile + - infra +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - '-t' + - ghcr.io/aixcc-finals/cifuzz-run-fuzzers + - '-t' + - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1 + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 + - '-f' + - infra/run_fuzzers.Dockerfile + - infra +images: +- ghcr.io/aixcc-finals/cifuzz-base +- ghcr.io/aixcc-finals/cifuzz-base:v1 +- ghcr.io/aixcc-finals/cifuzz-run-fuzzers +- ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1 +- ghcr.io/aixcc-finals/cifuzz-build-fuzzers +- ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1 +- ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers +- ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 +- ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers +- ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 +timeout: 1800s diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..b36fc78dec9ab35b045aa6b42b790e1904a98e67 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py @@ -0,0 +1,385 @@ +# 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 interacting with the ClusterFuzz deployment.""" +import logging +import os +import sys +import urllib.error +import urllib.request + +import config_utils +import continuous_integration +import filestore_utils +import http_utils +import get_coverage +import repo_manager + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils + + +class BaseClusterFuzzDeployment: + """Base class for ClusterFuzz deployments.""" + + def __init__(self, config, workspace): + self.config = config + self.workspace = workspace + self.ci_system = continuous_integration.get_ci(config) + + def download_latest_build(self): + """Downloads the latest build from ClusterFuzz. + + Returns: + A path to where the OSS-Fuzz build was stored, or None if it wasn't. + """ + raise NotImplementedError('Child class must implement method.') + + def upload_build(self, commit): + """Uploads the build with the given commit sha to the filestore.""" + raise NotImplementedError('Child class must implement method.') + + def download_corpus(self, target_name, corpus_dir): + """Downloads the corpus for |target_name| from ClusterFuzz to |corpus_dir|. + + Returns: + A path to where the OSS-Fuzz build was stored, or None if it wasn't. + """ + raise NotImplementedError('Child class must implement method.') + + def upload_crashes(self): + """Uploads crashes in |crashes_dir| to filestore.""" + raise NotImplementedError('Child class must implement method.') + + def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument + """Uploads the corpus for |target_name| to filestore.""" + raise NotImplementedError('Child class must implement method.') + + def upload_coverage(self): + """Uploads the coverage report to the filestore.""" + raise NotImplementedError('Child class must implement method.') + + def get_coverage(self, repo_path): + """Returns the project coverage object for the project.""" + raise NotImplementedError('Child class must implement method.') + + +def _make_empty_dir_if_nonexistent(path): + """Makes an empty directory at |path| if it does not exist.""" + os.makedirs(path, exist_ok=True) + + +class ClusterFuzzLite(BaseClusterFuzzDeployment): + """Class representing a deployment of ClusterFuzzLite.""" + + COVERAGE_NAME = 'latest' + LATEST_BUILD_WINDOW = 3 + + def __init__(self, config, workspace): + super().__init__(config, workspace) + self.filestore = filestore_utils.get_filestore(self.config) + + def download_latest_build(self): + if os.path.exists(self.workspace.clusterfuzz_build): + # This path is necessary because download_latest_build can be called + # multiple times.That is the case because it is called only when we need + # to see if a bug is novel, i.e. until we want to check a bug is novel we + # don't want to waste time calling this, but therefore this method can be + # called if multiple bugs are found. + return self.workspace.clusterfuzz_build + + repo_dir = self.ci_system.repo_dir + if not repo_dir: + raise RuntimeError('Repo checkout does not exist.') + + _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build) + repo = repo_manager.RepoManager(repo_dir) + + diff_base = self.ci_system.get_diff_base() + if not diff_base: + diff_base = 'HEAD^' + + # Builds are stored by commit, so try the latest |LATEST_BUILD_WINDOW| + # commits before the current diff base. + # TODO(ochang): If API usage becomes an issue, this can be optimized by the + # filestore accepting a list of filenames to try. + try: + # TODO(metzman): Why do we default to 'origin', we should avoid going down + # this path entirely and not need to catch an exception. + commit_list = repo.get_commit_list(diff_base, + limit=self.LATEST_BUILD_WINDOW) + except ValueError as error: + logging.error('Can\'t get commit list: %s', error) + return None + + for old_commit in commit_list: + logging.info('Trying to downloading previous build %s.', old_commit) + build_name = self._get_build_name(old_commit) + try: + if self.filestore.download_build(build_name, + self.workspace.clusterfuzz_build): + logging.info('Done downloading previous build.') + return self.workspace.clusterfuzz_build + + logging.info('Build for %s does not exist.', old_commit) + except Exception as err: # pylint: disable=broad-except + logging.error('Could not download build for %s because of: %s', + old_commit, err) + + return None + + def download_corpus(self, target_name, corpus_dir): + _make_empty_dir_if_nonexistent(corpus_dir) + logging.info('Downloading corpus for %s to %s.', target_name, corpus_dir) + corpus_name = self._get_corpus_name(target_name) + try: + self.filestore.download_corpus(corpus_name, corpus_dir) + logging.info('Done downloading corpus. Contains %d elements.', + len(os.listdir(corpus_dir))) + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to download corpus for target: %s. Error: %s', + target_name, str(err)) + return corpus_dir + + def _get_build_name(self, name): + return f'{self.config.sanitizer}-{name}' + + def _get_corpus_name(self, target_name): # pylint: disable=no-self-use + """Returns the name of the corpus artifact.""" + return target_name + + def upload_corpus(self, target_name, corpus_dir, replace=False): + """Upload the corpus produced by |target_name|.""" + logging.info('Uploading corpus in %s for %s.', corpus_dir, target_name) + name = self._get_corpus_name(target_name) + try: + self.filestore.upload_corpus(name, corpus_dir, replace=replace) + logging.info('Done uploading corpus.') + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to upload corpus for target: %s. Error: %s.', + target_name, err) + + def upload_build(self, commit): + """Upload the build produced by CIFuzz as the latest build.""" + logging.info('Uploading latest build in %s.', self.workspace.out) + build_name = self._get_build_name(commit) + try: + result = self.filestore.upload_build(build_name, self.workspace.out) + logging.info('Done uploading latest build.') + return result + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to upload latest build: %s. Error: %s', + self.workspace.out, err) + + def upload_crashes(self): + """Uploads crashes.""" + artifact_dirs = os.listdir(self.workspace.artifacts) + if not artifact_dirs: + logging.info('No crashes in %s. Not uploading.', self.workspace.artifacts) + return + + for crash_target in artifact_dirs: + artifact_dir = os.path.join(self.workspace.artifacts, crash_target) + if not os.path.isdir(artifact_dir): + logging.warning('%s is not an expected artifact directory, skipping.', + crash_target) + continue + + logging.info('Uploading crashes in %s.', artifact_dir) + try: + self.filestore.upload_crashes(crash_target, artifact_dir) + logging.info('Done uploading crashes.') + except Exception as err: # pylint: disable=broad-except + logging.error('Failed to upload crashes. Error: %s', err) + + def upload_coverage(self): + """Uploads the coverage report to the filestore.""" + self.filestore.upload_coverage(self.COVERAGE_NAME, + self.workspace.coverage_report) + + def get_coverage(self, repo_path): + """Returns the project coverage object for the project.""" + _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_coverage) + try: + if not self.filestore.download_coverage( + self.COVERAGE_NAME, self.workspace.clusterfuzz_coverage): + logging.error('Could not download coverage.') + return None + return get_coverage.FilesystemCoverage( + repo_path, self.workspace.clusterfuzz_coverage) + except Exception as err: # pylint: disable=broad-except + logging.error('Could not get coverage: %s.', err) + return None + + +class OSSFuzz(BaseClusterFuzzDeployment): + """The OSS-Fuzz ClusterFuzz deployment.""" + + # Location of clusterfuzz builds on GCS. + CLUSTERFUZZ_BUILDS = 'clusterfuzz-builds' + + # Zip file name containing the corpus. + CORPUS_ZIP_NAME = 'public.zip' + + def get_latest_build_name(self): + """Gets the name of the latest OSS-Fuzz build of a project. + + Returns: + A string with the latest build version or None. + """ + version_file = ( + f'{self.config.oss_fuzz_project_name}-{self.config.sanitizer}' + '-latest.version') + version_url = utils.url_join(utils.GCS_BASE_URL, self.CLUSTERFUZZ_BUILDS, + self.config.oss_fuzz_project_name, + version_file) + try: + response = urllib.request.urlopen(version_url) + except urllib.error.HTTPError: + logging.error('Error getting latest build version for %s from: %s.', + self.config.oss_fuzz_project_name, version_url) + return None + return response.read().decode() + + def download_latest_build(self): + """Downloads the latest OSS-Fuzz build from GCS. + + Returns: + A path to where the OSS-Fuzz build was stored, or None if it wasn't. + """ + if os.path.exists(self.workspace.clusterfuzz_build): + # This function can be called multiple times, don't download the build + # again. + return self.workspace.clusterfuzz_build + + _make_empty_dir_if_nonexistent(self.workspace.clusterfuzz_build) + + latest_build_name = self.get_latest_build_name() + if not latest_build_name: + return None + + logging.info('Downloading latest build.') + oss_fuzz_build_url = utils.url_join(utils.GCS_BASE_URL, + self.CLUSTERFUZZ_BUILDS, + self.config.oss_fuzz_project_name, + latest_build_name) + if http_utils.download_and_unpack_zip(oss_fuzz_build_url, + self.workspace.clusterfuzz_build): + logging.info('Done downloading latest build.') + return self.workspace.clusterfuzz_build + + return None + + def upload_build(self, commit): # pylint: disable=no-self-use + """Noop Implementation of upload_build.""" + logging.info('Not uploading latest build because on OSS-Fuzz.') + + def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument + """Noop Implementation of upload_corpus.""" + logging.info('Not uploading corpus because on OSS-Fuzz.') + + def upload_crashes(self): # pylint: disable=no-self-use + """Noop Implementation of upload_crashes.""" + logging.info('Not uploading crashes because on OSS-Fuzz.') + + def download_corpus(self, target_name, corpus_dir): + """Downloads the latest OSS-Fuzz corpus for the target. + + Returns: + The local path to to corpus or None if download failed. + """ + _make_empty_dir_if_nonexistent(corpus_dir) + project_qualified_fuzz_target_name = target_name + qualified_name_prefix = self.config.oss_fuzz_project_name + '_' + if not target_name.startswith(qualified_name_prefix): + project_qualified_fuzz_target_name = qualified_name_prefix + target_name + + corpus_url = (f'{utils.GCS_BASE_URL}{self.config.oss_fuzz_project_name}' + '-backup.clusterfuzz-external.appspot.com/corpus/' + f'libFuzzer/{project_qualified_fuzz_target_name}/' + f'{self.CORPUS_ZIP_NAME}') + logging.info('Downloading corpus from OSS-Fuzz: %s', corpus_url) + + if not http_utils.download_and_unpack_zip(corpus_url, corpus_dir): + logging.warning('Failed to download corpus for %s.', target_name) + return corpus_dir + + def upload_coverage(self): + """Noop Implementation of upload_coverage_report.""" + logging.info('Not uploading coverage report because on OSS-Fuzz.') + + def get_coverage(self, repo_path): + """Returns the project coverage object for the project.""" + try: + return get_coverage.OSSFuzzCoverage(repo_path, + self.config.oss_fuzz_project_name) + except get_coverage.CoverageError: + return None + + +class NoClusterFuzzDeployment(BaseClusterFuzzDeployment): + """ClusterFuzzDeployment implementation used when there is no deployment of + ClusterFuzz to use.""" + + def upload_build(self, commit): # pylint: disable=no-self-use + """Noop Implementation of upload_build.""" + logging.info('Not uploading latest build because no ClusterFuzz ' + 'deployment.') + + def upload_corpus(self, target_name, corpus_dir, replace=False): # pylint: disable=no-self-use,unused-argument + """Noop Implementation of upload_corpus.""" + logging.info('Not uploading corpus because no ClusterFuzz deployment.') + + def upload_crashes(self): # pylint: disable=no-self-use + """Noop Implementation of upload_crashes.""" + logging.info('Not uploading crashes because no ClusterFuzz deployment.') + + def download_corpus(self, target_name, corpus_dir): + """Noop Implementation of download_corpus.""" + logging.info('Not downloading corpus because no ClusterFuzz deployment.') + return _make_empty_dir_if_nonexistent(corpus_dir) + + def download_latest_build(self): # pylint: disable=no-self-use + """Noop Implementation of download_latest_build.""" + logging.info( + 'Not downloading latest build because no ClusterFuzz deployment.') + + def upload_coverage(self): + """Noop Implementation of upload_coverage.""" + logging.info( + 'Not uploading coverage report because no ClusterFuzz deployment.') + + def get_coverage(self, repo_path): + """Noop Implementation of get_coverage.""" + logging.info( + 'Not getting project coverage because no ClusterFuzz deployment.') + + +_PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING = { + config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI: OSSFuzz, + config_utils.BaseConfig.Platform.INTERNAL_GITHUB: OSSFuzz, + config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI: ClusterFuzzLite, + config_utils.BaseConfig.Platform.EXTERNAL_GITHUB: ClusterFuzzLite, +} + + +def get_clusterfuzz_deployment(config, workspace): + """Returns object reprsenting deployment of ClusterFuzz used by |config|.""" + deployment_cls = _PLATFORM_CLUSTERFUZZ_DEPLOYMENT_MAPPING[config.platform] + if config.no_clusterfuzz_deployment: + logging.info('Overriding ClusterFuzzDeployment. Using None.') + deployment_cls = NoClusterFuzzDeployment + result = deployment_cls(config, workspace) + logging.info('ClusterFuzzDeployment: %s.', result) + return result diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py new file mode 100644 index 0000000000000000000000000000000000000000..31c7b03ecb82dbaed32681ba8a94c61044a67e28 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py @@ -0,0 +1,268 @@ +# 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 clusterfuzz_deployment.py""" + +import os +import unittest +from unittest import mock + +import parameterized +from pyfakefs import fake_filesystem_unittest + +import clusterfuzz_deployment +import config_utils +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' + +WORKSPACE = '/workspace' +EXPECTED_LATEST_BUILD_PATH = os.path.join(WORKSPACE, 'cifuzz-prev-build') + +# pylint: disable=unused-argument + + +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) + + +class OSSFuzzTest(fake_filesystem_unittest.TestCase): + """Tests OSSFuzz.""" + + def setUp(self): + self.setUpPyfakefs() + self.deployment = _create_deployment() + self.corpus_dir = os.path.join(self.deployment.workspace.corpora, + EXAMPLE_FUZZER) + + @mock.patch('http_utils.download_and_unpack_zip', return_value=True) + def test_download_corpus(self, mock_download_and_unpack_zip): + """Tests that we can download a corpus for a valid project.""" + self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir) + expected_url = ('https://storage.googleapis.com/example-backup.' + 'clusterfuzz-external.appspot.com/corpus/libFuzzer/' + 'example_crash_fuzzer/public.zip') + call_args, _ = mock_download_and_unpack_zip.call_args + self.assertEqual(call_args, (expected_url, self.corpus_dir)) + self.assertTrue(os.path.exists(self.corpus_dir)) + + @mock.patch('http_utils.download_and_unpack_zip', return_value=False) + def test_download_corpus_fail(self, _): + """Tests that when downloading fails, an empty corpus directory is still + returned.""" + self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir) + self.assertEqual(os.listdir(self.corpus_dir), []) + + def test_get_latest_build_name(self): + """Tests that the latest build name can be retrieved from GCS.""" + latest_build_name = self.deployment.get_latest_build_name() + self.assertTrue(latest_build_name.endswith('.zip')) + self.assertTrue('address' in latest_build_name) + + @parameterized.parameterized.expand([ + ('upload_build', ('commit',), + 'Not uploading latest build because on OSS-Fuzz.'), + ('upload_corpus', ('target', 'corpus-dir'), + 'Not uploading corpus because on OSS-Fuzz.'), + ('upload_crashes', tuple(), 'Not uploading crashes because on OSS-Fuzz.'), + ]) + def test_noop_methods(self, method, method_args, expected_message): + """Tests that certain methods are noops for OSS-Fuzz.""" + with mock.patch('logging.info') as mock_info: + method = getattr(self.deployment, method) + self.assertIsNone(method(*method_args)) + mock_info.assert_called_with(expected_message) + + @mock.patch('http_utils.download_and_unpack_zip', return_value=True) + def test_download_latest_build(self, mock_download_and_unpack_zip): + """Tests that downloading the latest build works as intended under normal + circumstances.""" + self.assertEqual(self.deployment.download_latest_build(), + EXPECTED_LATEST_BUILD_PATH) + expected_url = ('https://storage.googleapis.com/clusterfuzz-builds/example/' + 'example-address-202008030600.zip') + mock_download_and_unpack_zip.assert_called_with(expected_url, + EXPECTED_LATEST_BUILD_PATH) + + @mock.patch('http_utils.download_and_unpack_zip', return_value=False) + def test_download_latest_build_fail(self, _): + """Tests that download_latest_build returns None when it fails to download a + build.""" + self.assertIsNone(self.deployment.download_latest_build()) + + +class ClusterFuzzLiteTest(fake_filesystem_unittest.TestCase): + """Tests for ClusterFuzzLite.""" + + def setUp(self): + self.setUpPyfakefs() + self.deployment = _create_deployment(mode='batch', + oss_fuzz_project_name='', + cloud_bucket='gs://bucket') + self.corpus_dir = os.path.join(self.deployment.workspace.corpora, + EXAMPLE_FUZZER) + + @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus', + return_value=True) + def test_download_corpus(self, mock_download_corpus): + """Tests that download_corpus works for a valid project.""" + self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir) + mock_download_corpus.assert_called_with('example_crash_fuzzer', + self.corpus_dir) + self.assertTrue(os.path.exists(self.corpus_dir)) + + @mock.patch('filestore.github_actions.GithubActionsFilestore.download_corpus', + side_effect=Exception) + def test_download_corpus_fail(self, _): + """Tests that when downloading fails, an empty corpus directory is still + returned.""" + self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir) + self.assertEqual(os.listdir(self.corpus_dir), []) + + @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build', + side_effect=[False, True]) + @mock.patch('repo_manager.RepoManager.get_commit_list', + return_value=['commit1', 'commit2']) + @mock.patch('continuous_integration.GithubCiMixin.repo_dir', + return_value='/path/to/repo') + def test_download_latest_build(self, mock_repo_dir, mock_get_commit_list, + mock_download_build): + """Tests that downloading the latest build works as intended under normal + circumstances.""" + self.assertEqual(self.deployment.download_latest_build(), + EXPECTED_LATEST_BUILD_PATH) + expected_artifact_name = 'address-commit2' + mock_download_build.assert_called_with(expected_artifact_name, + EXPECTED_LATEST_BUILD_PATH) + + @mock.patch('filestore.github_actions.GithubActionsFilestore.download_build', + side_effect=Exception) + @mock.patch('repo_manager.RepoManager.get_commit_list', + return_value=['commit1', 'commit2']) + @mock.patch('continuous_integration.GithubCiMixin.repo_dir', + return_value='/path/to/repo') + def test_download_latest_build_fail(self, mock_repo_dir, mock_get_commit_list, + _): + """Tests that download_latest_build returns None when it fails to download a + build.""" + self.assertIsNone(self.deployment.download_latest_build()) + + @mock.patch('filestore.github_actions.GithubActionsFilestore.upload_build') + def test_upload_build(self, mock_upload_build): + """Tests that upload_build works as intended.""" + self.deployment.upload_build('commit') + mock_upload_build.assert_called_with('address-commit', + '/workspace/build-out') + + +class NoClusterFuzzDeploymentTest(fake_filesystem_unittest.TestCase): + """Tests for NoClusterFuzzDeployment.""" + + def setUp(self): + self.setUpPyfakefs() + config = test_helpers.create_run_config(workspace=WORKSPACE, + cfl_platform='other', + filestore='no_filestore', + no_clusterfuzz_deployment=True) + workspace = workspace_utils.Workspace(config) + self.deployment = clusterfuzz_deployment.get_clusterfuzz_deployment( + config, workspace) + + self.corpus_dir = os.path.join(workspace.corpora, EXAMPLE_FUZZER) + + @mock.patch('logging.info') + def test_download_corpus(self, mock_info): + """Tests that download corpus returns the path to the empty corpus + directory.""" + self.deployment.download_corpus(EXAMPLE_FUZZER, self.corpus_dir) + mock_info.assert_called_with( + 'Not downloading corpus because no ClusterFuzz deployment.') + self.assertTrue(os.path.exists(self.corpus_dir)) + + @parameterized.parameterized.expand([ + ('upload_build', ('commit',), + 'Not uploading latest build because no ClusterFuzz deployment.'), + ('upload_corpus', ('target', 'corpus-dir'), + 'Not uploading corpus because no ClusterFuzz deployment.'), + ('upload_crashes', tuple(), + 'Not uploading crashes because no ClusterFuzz deployment.'), + ('download_latest_build', tuple(), + 'Not downloading latest build because no ClusterFuzz deployment.') + ]) + def test_noop_methods(self, method, method_args, expected_message): + """Tests that certain methods are noops for NoClusterFuzzDeployment.""" + with mock.patch('logging.info') as mock_info: + method = getattr(self.deployment, method) + self.assertIsNone(method(*method_args)) + mock_info.assert_called_with(expected_message) + + +class GetClusterFuzzDeploymentTest(unittest.TestCase): + """Tests for get_clusterfuzz_deployment.""" + + def setUp(self): + test_helpers.patch_environ(self) + os.environ['GITHUB_REPOSITORY'] = 'owner/myproject' + + @parameterized.parameterized.expand([ + (config_utils.BaseConfig.Platform.INTERNAL_GENERIC_CI, + clusterfuzz_deployment.OSSFuzz), + (config_utils.BaseConfig.Platform.INTERNAL_GITHUB, + clusterfuzz_deployment.OSSFuzz), + (config_utils.BaseConfig.Platform.EXTERNAL_GENERIC_CI, + clusterfuzz_deployment.ClusterFuzzLite), + (config_utils.BaseConfig.Platform.EXTERNAL_GITHUB, + clusterfuzz_deployment.ClusterFuzzLite), + ]) + def test_get_clusterfuzz_deployment(self, platform, expected_deployment_cls): + """Tests that get_clusterfuzz_deployment returns the correct value.""" + with mock.patch('config_utils.BaseConfig.platform', + return_value=platform, + new_callable=mock.PropertyMock): + with mock.patch('filestore_utils.get_filestore', return_value=None): + with mock.patch('platform_config.github._get_event_data', + return_value={}): + config = _create_config() + workspace = workspace_utils.Workspace(config) + + self.assertIsInstance( + clusterfuzz_deployment.get_clusterfuzz_deployment( + config, workspace), expected_deployment_cls) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a3cb8f7ad9265f3eaaac9af4a810d412e3fc00 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils.py @@ -0,0 +1,283 @@ +# 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 enum +import importlib +import logging +import os +import sys + +import environment + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import platform_config +import constants + +SANITIZERS = ['address', 'memory', 'undefined', 'coverage'] + +# TODO(metzman): Set these on config objects so there's one source of truth. +DEFAULT_ENGINE = 'libfuzzer' + +# This module deals a lot with env variables. Many of these will be set by users +# and others beyond CIFuzz's control. Thus, you should be careful about using +# the environment.py helpers for getting env vars, since it can cause values +# that should be interpreted as strings to be returned as other types (bools or +# ints for example). The environment.py helpers should not be used for values +# that are supposed to be strings. + + +def _get_sanitizer(): + return os.getenv('SANITIZER', constants.DEFAULT_SANITIZER).lower() + + +def _get_architecture(): + return os.getenv('ARCHITECTURE', constants.DEFAULT_ARCHITECTURE).lower() + + +def _is_dry_run(): + """Returns True if configured to do a dry run.""" + return environment.get_bool('DRY_RUN', False) + + +def _get_language(): + """Returns the project language.""" + # Get language from environment. We took this approach because the convenience + # given to OSS-Fuzz users by not making them specify the language again (and + # getting it from the project.yaml) is outweighed by the complexity in + # implementing this. A lot of the complexity comes from our unittests not + # setting a proper projet at this point. + return os.getenv('LANGUAGE', constants.DEFAULT_LANGUAGE) + + +def _get_extra_environment_variables(): + """Gets extra environment variables specified by the user with + CFL_EXTRA_$NAME=$VALUE.""" + return [key for key in os.environ if key.startswith('CFL_EXTRA_')] + + +# pylint: disable=too-many-instance-attributes + + +class ConfigError(Exception): + """Error for invalid configuration.""" + + +class BaseConfig: + """Object containing constant configuration for CIFuzz.""" + + class Platform(enum.Enum): + """Enum representing the different platforms CIFuzz runs on.""" + EXTERNAL_GITHUB = 0 # Non-OSS-Fuzz on GitHub actions. + INTERNAL_GITHUB = 1 # OSS-Fuzz on GitHub actions. + INTERNAL_GENERIC_CI = 2 # OSS-Fuzz on any CI. + EXTERNAL_GENERIC_CI = 3 # Non-OSS-Fuzz on any CI. + + @property + def is_github(self): + """Returns True if running on GitHub.""" + return self.cfl_platform == 'github' + + def __init__(self): + # Need to set these before calling self.platform. + self.oss_fuzz_project_name = os.getenv('OSS_FUZZ_PROJECT_NAME') + self.cfl_platform = os.getenv('CFL_PLATFORM') + logging.debug('Is github: %s.', self.is_github) + + self.platform_conf = _get_platform_config(self.cfl_platform) + self.base_commit = self.platform_conf.base_commit + self.base_ref = self.platform_conf.base_ref + self.pr_ref = self.platform_conf.pr_ref + self.workspace = self.platform_conf.workspace + self.project_src_path = self.platform_conf.project_src_path + self.actor = self.platform_conf.actor + self.token = self.platform_conf.token + self.project_repo_owner = self.platform_conf.project_repo_owner + self.project_repo_name = self.platform_conf.project_repo_name + self.filestore = self.platform_conf.filestore + + # This determines if builds are done using docker in docker + # rather than the normal method which is sibling containers. + self.docker_in_docker = self.platform_conf.docker_in_docker + + self.dry_run = _is_dry_run() # Check if failures should not be reported. + self.sanitizer = _get_sanitizer() + self.architecture = _get_architecture() + self.language = _get_language() + self.low_disk_space = environment.get_bool('LOW_DISK_SPACE', False) + + self.git_store_repo = os.environ.get('GIT_STORE_REPO') + self.git_store_branch = os.environ.get('GIT_STORE_BRANCH') + self.git_store_branch_coverage = os.environ.get('GIT_STORE_BRANCH_COVERAGE', + self.git_store_branch) + self.cloud_bucket = os.environ.get('CLOUD_BUCKET') + self.no_clusterfuzz_deployment = environment.get_bool( + 'NO_CLUSTERFUZZ_DEPLOYMENT', False) + self.build_integration_path = ( + constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH) + + self.parallel_fuzzing = environment.get_bool('PARALLEL_FUZZING', False) + self.extra_environment_variables = _get_extra_environment_variables() + self.output_sarif = environment.get_bool('OUTPUT_SARIF', False) + + # TODO(metzman): Fix tests to create valid configurations and get rid of + # CIFUZZ_TEST here and in presubmit.py. + if not os.getenv('CIFUZZ_TEST') and not self.validate(): + raise ConfigError('Invalid Configuration.') + + def validate(self): + """Returns False if the configuration is invalid.""" + # Do validation here so that unittests don't need to make a fully-valid + # config. + # pylint: disable=too-many-return-statements + if not self.workspace: + logging.error('Must set WORKSPACE.') + return False + + if self.sanitizer not in SANITIZERS: + logging.error('Invalid SANITIZER: %s. Must be one of: %s.', + self.sanitizer, SANITIZERS) + return False + + if self.architecture not in constants.ARCHITECTURES: + logging.error('Invalid ARCHITECTURE: %s. Must be one of: %s.', + self.architecture, constants.ARCHITECTURES) + return False + + if self.architecture == 'i386' and self.sanitizer != 'address': + logging.error( + 'ARCHITECTURE=i386 can be used with SANITIZER=address only.') + return False + + if self.language not in constants.LANGUAGES: + logging.error('Invalid LANGUAGE: %s. Must be one of: %s.', self.language, + constants.LANGUAGES) + return False + + if not self.project_repo_name: + logging.error('Must set REPOSITORY.') + return False + + return True + + @property + def is_internal(self): + """Returns True if this is an OSS-Fuzz project.""" + return bool(self.oss_fuzz_project_name) + + @property + def platform(self): + """Returns the platform CIFuzz is runnning on.""" + if not self.is_internal: + if not self.is_github: + return self.Platform.EXTERNAL_GENERIC_CI + return self.Platform.EXTERNAL_GITHUB + + if self.is_github: + return self.Platform.INTERNAL_GITHUB + return self.Platform.INTERNAL_GENERIC_CI + + @property + def is_coverage(self): + """Returns True if this CIFuzz run (building fuzzers and running them) for + generating a coverage report.""" + return self.sanitizer == 'coverage' + + +def _get_platform_config(cfl_platform): + """Returns the CI environment object for |cfl_platform|.""" + module_name = f'platform_config.{cfl_platform}' + try: + cls = importlib.import_module(module_name).PlatformConfig + except ImportError: + cls = platform_config.BasePlatformConfig + return cls() + + +class RunFuzzersConfig(BaseConfig): + """Class containing constant configuration for running fuzzers in CIFuzz.""" + + MODES = ['batch', 'code-change', 'coverage', 'prune'] + + def __init__(self): + super().__init__() + # TODO(metzman): Pick a better default for pruning. + self.fuzz_seconds = int(os.environ.get('FUZZ_SECONDS', 600)) + self.mode = os.environ.get('MODE', 'code-change').lower() + if self.is_coverage: + self.mode = 'coverage' + + self.report_unreproducible_crashes = environment.get_bool( + 'REPORT_UNREPRODUCIBLE_CRASHES', False) + + self.minimize_crashes = environment.get_bool('MINIMIZE_CRASHES', False) + if self.mode == 'batch': + logging.warning( + 'Minimizing crashes reduces fuzzing time in batch fuzzing.') + self.report_timeouts = environment.get_bool('REPORT_TIMEOUTS', False) + self.report_ooms = environment.get_bool('REPORT_OOMS', True) + self.upload_all_crashes = environment.get_bool('UPLOAD_ALL_CRASHES', False) + + # TODO(metzman): Fix tests to create valid configurations and get rid of + # CIFUZZ_TEST here and in presubmit.py. + if not os.getenv('CIFUZZ_TEST') and not self._run_config_validate(): + raise ConfigError('Invalid Run Configuration.') + + def _run_config_validate(self): + """Do extra validation on RunFuzzersConfig.__init__(). Do not name this + validate or else it will be called when using the parent's __init__ and will + fail. Returns True if valid.""" + if self.mode not in self.MODES: + logging.error('Invalid MODE: %s. Must be one of %s.', self.mode, + self.MODES) + return False + + return True + + +class BuildFuzzersConfig(BaseConfig): + """Class containing constant configuration for building fuzzers in CIFuzz.""" + + def __init__(self): + """Get the configuration from CIFuzz from the environment. These variables + are set by GitHub or the user.""" + super().__init__() + self.git_sha = self.platform_conf.git_sha + self.git_url = self.platform_conf.git_url + + self.allowed_broken_targets_percentage = os.getenv( + 'ALLOWED_BROKEN_TARGETS_PERCENTAGE') + self.bad_build_check = environment.get_bool('BAD_BUILD_CHECK', True) + + self.keep_unaffected_fuzz_targets = environment.get_bool( + 'KEEP_UNAFFECTED_FUZZ_TARGETS') + + self.upload_build = environment.get_bool('UPLOAD_BUILD', False) + if not self.keep_unaffected_fuzz_targets: + has_base_for_diff = (self.base_ref or self.base_commit) + if not has_base_for_diff: + logging.info( + 'Keeping all fuzzers because there is nothing to diff against.') + self.keep_unaffected_fuzz_targets = True + elif self.upload_build: + logging.info('Keeping all fuzzers because we are uploading build.') + self.keep_unaffected_fuzz_targets = True + elif self.sanitizer == 'coverage': + logging.info('Keeping all fuzzers because we are doing coverage.') + self.keep_unaffected_fuzz_targets = True + + if self.sanitizer == 'coverage': + self.bad_build_check = False diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..cb82dee44026532eb0b0127a6bb565e25e965f1e --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/config_utils_test.py @@ -0,0 +1,200 @@ +# 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 config_utils.""" +import os +import unittest +from unittest import mock + +import config_utils +import constants +import test_helpers + +# pylint: disable=no-self-use,protected-access + + +class BaseConfigTest(unittest.TestCase): + """Tests for BaseConfig.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def _create_config(self): + return config_utils.BuildFuzzersConfig() + + def test_language_default(self): + """Tests that the correct default language is set.""" + config = self._create_config() + self.assertEqual(config.language, 'c++') + + def test_language(self): + """Tests that the correct language is set.""" + language = 'python' + os.environ['LANGUAGE'] = language + config = self._create_config() + self.assertEqual(config.language, language) + + def test_is_coverage(self): + """Tests that is_coverage is set correctly.""" + # Test it is set when it is supposed to be. + os.environ['SANITIZER'] = 'coverage' + config = self._create_config() + self.assertTrue(config.is_coverage) + + # Test it is not set when it is not supposed to be. + os.environ['SANITIZER'] = 'address' + config = self._create_config() + self.assertFalse(config.is_coverage) + + @mock.patch('logging.error') + def test_validate_no_workspace(self, mock_error): + """Tests that validate returns False if GITHUB_WORKSPACE isn't set.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + config = self._create_config() + self.assertFalse(config.validate()) + mock_error.assert_called_with('Must set WORKSPACE.') + + @mock.patch('logging.error') + def test_validate_invalid_language(self, mock_error): + """Tests that validate returns False if GITHUB_WORKSPACE isn't set.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + os.environ['WORKSPACE'] = '/workspace' + os.environ['LANGUAGE'] = 'invalid-language' + config = self._create_config() + self.assertFalse(config.validate()) + mock_error.assert_called_with('Invalid LANGUAGE: %s. Must be one of: %s.', + os.environ['LANGUAGE'], constants.LANGUAGES) + + @mock.patch('logging.error') + def test_validate_invalid_sanitizer(self, mock_error): + """Tests that validate returns False if GITHUB_WORKSPACE isn't set.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + os.environ['WORKSPACE'] = '/workspace' + os.environ['SANITIZER'] = 'invalid-sanitizer' + config = self._create_config() + self.assertFalse(config.validate()) + mock_error.assert_called_with('Invalid SANITIZER: %s. Must be one of: %s.', + os.environ['SANITIZER'], + config_utils.SANITIZERS) + + def test_validate(self): + """Tests that validate returns True if config is valid.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + os.environ['WORKSPACE'] = '/workspace' + os.environ['REPOSITORY'] = 'repo' + config = self._create_config() + self.assertTrue(config.validate()) + + +class BuildFuzzersConfigTest(unittest.TestCase): + """Tests for BuildFuzzersConfig.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def _create_config(self): + return config_utils.BuildFuzzersConfig() + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github_base_ref(self, _): + """Tests that base_ref is set properly.""" + expected_base_ref = 'expected_base_ref' + os.environ['GITHUB_BASE_REF'] = expected_base_ref + os.environ['CFL_PLATFORM'] = 'github' + os.environ['GITHUB_REPOSITORY'] = 'owner/repo' + config = self._create_config() + self.assertEqual(config.base_ref, expected_base_ref) + + def test_base_ref(self): + """Tests that base_ref is set properly.""" + expected_base_ref = 'expected_base_ref' + os.environ['GIT_BASE_REF'] = expected_base_ref + config = self._create_config() + self.assertEqual(config.base_ref, expected_base_ref) + + def test_keep_unaffected_defaults_to_true(self): + """Tests that keep_unaffected_fuzz_targets defaults to true.""" + config = self._create_config() + self.assertTrue(config.keep_unaffected_fuzz_targets) + + def test_keep_unaffected_defaults_to_false_when_pr(self): + """Tests that keep_unaffected_fuzz_targets defaults to false when from a + pr.""" + os.environ['GIT_BASE_REF'] = 'base-ref' + config = self._create_config() + self.assertFalse(config.keep_unaffected_fuzz_targets) + + +class RunFuzzersConfigTest(unittest.TestCase): + """Tests for RunFuzzersConfig.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def _create_config(self): + return config_utils.RunFuzzersConfig() + + def test_coverage(self): + """Tests that mode is overriden properly based on is_coverage.""" + # Test that it is overriden when it is supposed to be. + os.environ['SANITIZER'] = 'coverage' + os.environ['MODE'] = 'code-change' + config = self._create_config() + self.assertEqual(config.mode, 'coverage') + + # Test that it isn't overriden when it isn't supposed to be. + os.environ['SANITIZER'] = 'address' + mode = 'code-change' + os.environ['MODE'] = mode + config = self._create_config() + self.assertEqual(config.mode, mode) + + def test_run_config_validate(self): + """Tests that _run_config_validate returns True when the config is valid.""" + self.assertTrue(self._create_config()._run_config_validate()) + + @mock.patch('logging.error') + def test_run_config_invalid_mode(self, mock_error): + """Tests that _run_config_validate returns False when mode is invalid.""" + fake_mode = 'fake-mode' + os.environ['MODE'] = fake_mode + self.assertFalse(self._create_config()._run_config_validate()) + mock_error.assert_called_with('Invalid MODE: %s. Must be one of %s.', + fake_mode, + config_utils.RunFuzzersConfig.MODES) + + +class GetSanitizerTest(unittest.TestCase): + """Tests for _get_sanitizer.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.sanitizer = 'memory' + + def test_default_value(self): + """Tests that the default value returned by _get_sanitizer is correct.""" + self.assertEqual(config_utils._get_sanitizer(), 'address') + + def test_normal_case(self): + """Tests that _get_sanitizer returns the correct value in normal cases.""" + os.environ['SANITIZER'] = self.sanitizer + self.assertEqual(config_utils._get_sanitizer(), self.sanitizer) + + def test_capitalization(self): + """Tests that that _get_sanitizer handles capitalization properly.""" + os.environ['SANITIZER'] = self.sanitizer.upper() + self.assertEqual(config_utils._get_sanitizer(), self.sanitizer) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..f3e93b7aae7b3df012c9d77fa15f0f79d9fc6915 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration.py @@ -0,0 +1,375 @@ +# 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. +"""Implementations for various CI systems.""" + +import os +import collections +import sys +import logging + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import build_specified_commit +import docker +import helper +import repo_manager +import retry +import utils +import workspace_utils + +# pylint: disable=too-few-public-methods + +BuildPreparationResult = collections.namedtuple( + 'BuildPreparationResult', ['success', 'image_repo_path', 'repo_manager']) + +_IMAGE_BUILD_TRIES = 3 +_IMAGE_BUILD_BACKOFF = 2 + + +def fix_git_repo_for_diff(repo_manager_obj): + """Fixes git repos cloned by the "checkout" action so that diffing works on + them.""" + command = [ + 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD', + 'refs/remotes/origin/master' + ] + return utils.execute(command, location=repo_manager_obj.repo_dir) + + +class BaseCi: + """Class representing common CI functionality.""" + + def __init__(self, config): + self.config = config + self.workspace = workspace_utils.Workspace(config) + self._repo_dir = None + + @property + def repo_dir(self): + """Returns the source repo path, if it has been checked out. None is + returned otherwise.""" + raise NotImplementedError('Child class must implement method.') + + def prepare_for_fuzzer_build(self): + """Builds the fuzzer builder image and gets the source code we need to + fuzz.""" + raise NotImplementedError('Child class must implement method.') + + def get_diff_base(self): + """Returns the base to diff against with git to get the change under + test.""" + if self.config.base_ref: + logging.debug('Diffing against base_ref: %s.', self.config.base_ref) + return self.config.base_ref + if self.config.base_commit: + logging.debug('Diffing against base_commit: %s.', self.config.base_commit) + return self.config.base_commit + # TODO(metzman): Do we want this at all? What purpose does it serve? I guess + # it is a decent fallback when there is no base_commit or base_ref. + logging.debug('Diffing against origin.') + return 'origin' + + def get_changed_code_under_test(self, repo_manager_obj): + """Returns the changed files that need to be tested.""" + if self.config.base_ref: + repo_manager_obj.fetch_branch(self.config.base_ref) + fix_git_repo_for_diff(repo_manager_obj) + base = self.get_diff_base() + logging.info('Diffing against %s.', base) + # git diff ... is equivalent to + # git diff $(git merge-base HEAD) + return repo_manager_obj.get_git_diff(base + '...') + + def get_build_command(self, host_repo_path, image_repo_path): + """Returns the command for building the project that is run inside the + project builder container.""" + raise NotImplementedError('Child class must implement method.') + + def _build_external_project_docker_image(self, manager): + """Helper for child classes that builds an external project's docker image. + Returns a BuildPreparationResult indicating failure or success.""" + build_integration_abs_path = os.path.join( + manager.repo_dir, self.config.build_integration_path) + if not build_external_project_docker_image(manager.repo_dir, + build_integration_abs_path): + logging.error('Failed to build external project.') + return get_build_preparation_failure() + image_repo_path = os.path.join('/src', self.config.project_repo_name) + return BuildPreparationResult(success=True, + image_repo_path=image_repo_path, + repo_manager=manager) + + def _make_repo_storage_dir(self): + os.makedirs(self.workspace.repo_storage, exist_ok=True) + + def _clone_repo_and_checkout(self, repo_url, repo_name): + """Helper for child classes that clones the git repo specified by |repo_url| + to |repo_name|, checks out the specified commit, and returns the + |manager|.""" + self._make_repo_storage_dir() + # Checkout project's repo in the shared volume. + manager = repo_manager.clone_repo_and_get_manager( + repo_url, + self.workspace.repo_storage, + repo_name=repo_name, + username=self.config.actor, + password=self.config.token) + self._checkout_specified_commit(manager) + return manager + + def _checkout_specified_commit(self, manager): + checkout_specified_commit(manager, self.config.pr_ref, self.config.git_sha) + + def _detect_main_repo(self): + """Helper for child classes that detects the main repo and returns a tuple + containing the inffered url and path to the repo in the image.""" + inferred_url, image_repo_path = build_specified_commit.detect_main_repo( + self.config.oss_fuzz_project_name, + repo_name=self.config.project_repo_name) + if not inferred_url or not image_repo_path: + logging.error('Could not detect repo.') + return inferred_url, image_repo_path + + def _create_repo_manager_for_project_src_path(self): + """Returns a repo manager for |project_src_path|.""" + return repo_manager.RepoManager(self.config.project_src_path) + + +def get_build_command(): + """Returns the command to build the project inside the project builder + container.""" + return 'compile' + + +def get_replace_repo_and_build_command(host_repo_path, image_repo_path): + """Returns the command to replace the repo located at |image_repo_path| with + |host_repo_path| and build the project inside the project builder + container.""" + rm_path = os.path.join(image_repo_path, '*') + image_src_path = os.path.dirname(image_repo_path) + build_command = get_build_command() + command = (f'cd / && rm -rf {rm_path} && cp -r {host_repo_path} ' + f'{image_src_path} && cd - && {build_command}') + return command + + +def get_ci(config): + """Determines what kind of CI is being used and returns the object + representing that system.""" + + if config.platform == config.Platform.EXTERNAL_GENERIC_CI: + # Non-OSS-Fuzz projects must bring their own source and their own build + # integration (which is relative to that source). + return ExternalGeneric(config) + if config.platform == config.Platform.EXTERNAL_GITHUB: + # Non-OSS-Fuzz projects must bring their own source and their own build + # integration (which is relative to that source). + return ExternalGithub(config) + + if config.platform == config.Platform.INTERNAL_GENERIC_CI: + # Builds of OSS-Fuzz projects not hosted on Github must bring their own + # source since the checkout logic CIFuzz implements is github-specific. + # TODO(metzman): Consider moving Github-actions builds of OSS-Fuzz projects + # to this system to reduce implementation complexity. + return InternalGeneric(config) + + return InternalGithub(config) + + +def checkout_specified_commit(repo_manager_obj, pr_ref, git_sha): + """Checks out the specified commit or pull request using + |repo_manager_obj|.""" + try: + if pr_ref: + repo_manager_obj.checkout_pr(pr_ref) + else: + repo_manager_obj.checkout_commit(git_sha) + except (RuntimeError, ValueError): + logging.error( + 'Can not check out requested state %s. ' + 'Using current repo state.', pr_ref or git_sha) + + +class GithubCiMixin: + """Mixin for Github based CI systems.""" + + def __init__(self, config): + super().__init__(config) + # Unlike in other classes, here _repo_dir is the parent directory of the + # repo, not its actual directory. + self._repo_dir = self.workspace.repo_storage + + @property + def repo_dir(self): + """Returns the source repo path, if it has been checked out. None is + returned otherwise.""" + if not os.path.exists(self._repo_dir): + logging.warning('Repo dir: %s does not exist.', self._repo_dir) + return None + + # Note: this assumes there is only one repo checked out here. + listing = os.listdir(self._repo_dir) + if len(listing) != 1: + raise RuntimeError('Invalid repo directory.') + + repo_path = os.path.join(self._repo_dir, listing[0]) + if not os.path.isdir(repo_path): + raise RuntimeError('Repo is not a directory.') + + return repo_path + + +class InternalGithub(GithubCiMixin, BaseCi): + """Class representing CI for an OSS-Fuzz project on Github Actions.""" + + def _copy_repo_from_image(self, image_repo_path): + self._make_repo_storage_dir() + repo_name = os.path.basename(image_repo_path) + host_repo_path = os.path.join(self._repo_dir, repo_name) + bash_command = f'cp -r {image_repo_path} {host_repo_path}' + docker_args, _ = docker.get_base_docker_run_args( + self.workspace, self.config.sanitizer, self.config.language, + self.config.architecture, self.config.docker_in_docker) + docker_args.extend([ + docker.get_project_image_name(self.config.oss_fuzz_project_name), + '/bin/bash', '-c', bash_command + ]) + if not helper.docker_run(docker_args): + raise RuntimeError('Failed to copy repo.') + return repo_manager.RepoManager(host_repo_path) + + def prepare_for_fuzzer_build(self): + """Builds the fuzzer builder image, checks out the pull request/commit and + returns the BuildPreparationResult.""" + logging.info('InternalGithub: preparing for fuzzer build.') + assert self.config.pr_ref or self.config.git_sha + # _detect_main_repo builds the image as a side effect. + _, image_repo_path = self._detect_main_repo() + if not image_repo_path: + return get_build_preparation_failure() + + # Use the same name used in the docker image so we can overwrite it. + manager = self._copy_repo_from_image(image_repo_path) + self._checkout_specified_commit(manager) + return BuildPreparationResult(success=True, + image_repo_path=image_repo_path, + repo_manager=manager) + + def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use + """Returns the command for building the project that is run inside the + project builder container. Command also replaces |image_repo_path| with + |host_repo_path|.""" + return get_replace_repo_and_build_command(host_repo_path, image_repo_path) + + +def get_build_preparation_failure(): + """Returns a BuildPreparationResult indicating failure.""" + return BuildPreparationResult(success=False, + image_repo_path=None, + repo_manager=None) + + +class InternalGeneric(BaseCi): + """Class representing CI for an OSS-Fuzz project on a CI other than Github + actions.""" + + def __init__(self, config): + super().__init__(config) + self._repo_dir = config.project_src_path + + @property + def repo_dir(self): + """Returns the source repo path, if it has been checked out. None is + returned otherwise.""" + return self._repo_dir + + def prepare_for_fuzzer_build(self): + """Builds the project builder image for an OSS-Fuzz project outside of + GitHub actions. Returns the repo_manager. Does not checkout source code + since external projects are expected to bring their own source code to + CIFuzz.""" + logging.info('InternalGeneric: preparing for fuzzer build.') + # detect_main_repo builds the image as a side effect. + _, image_repo_path = self._detect_main_repo() + + if not image_repo_path: + return get_build_preparation_failure() + + manager = self._create_repo_manager_for_project_src_path() + return BuildPreparationResult(success=True, + image_repo_path=image_repo_path, + repo_manager=manager) + + def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use + """Returns the command for building the project that is run inside the + project builder container. Command also replaces |image_repo_path| with + |host_repo_path|.""" + return get_replace_repo_and_build_command(host_repo_path, image_repo_path) + + +@retry.wrap(_IMAGE_BUILD_TRIES, _IMAGE_BUILD_BACKOFF) +def build_external_project_docker_image(project_src, build_integration_path): + """Builds the project builder image for an external (non-OSS-Fuzz) project. + Returns True on success.""" + dockerfile_path = os.path.join(build_integration_path, 'Dockerfile') + command = [ + '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f', dockerfile_path, project_src + ] + return helper.docker_build(command) + + +class ExternalGeneric(BaseCi): + """CI implementation for generic CI for external (non-OSS-Fuzz) projects.""" + + def __init__(self, config): + super().__init__(config) + self._repo_dir = config.project_src_path + + @property + def repo_dir(self): + """Returns the source repo path, if it has been checked out. None is + returned otherwise.""" + return self._repo_dir + + def prepare_for_fuzzer_build(self): + logging.info('ExternalGeneric: preparing for fuzzer build.') + manager = self._create_repo_manager_for_project_src_path() + return self._build_external_project_docker_image(manager) + + def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use + """Returns the command for building the project that is run inside the + project builder container.""" + return get_build_command() + + +class ExternalGithub(GithubCiMixin, BaseCi): + """Class representing CI for a non-OSS-Fuzz project on Github Actions.""" + + def prepare_for_fuzzer_build(self): + """Builds the project builder image for a non-OSS-Fuzz project on GitHub + actions. Sets the repo manager. Does not checkout source code since external + projects are expected to bring their own source code to CIFuzz. Returns True + on success.""" + logging.info('ExternalGithub: preparing for fuzzer build.') + # Checkout before building, so we don't need to rely on copying the source + # from the image. + # TODO(metzman): Figure out if we want second copy at all. + manager = self._clone_repo_and_checkout(self.config.git_url, + self.config.project_repo_name) + return self._build_external_project_docker_image(manager) + + def get_build_command(self, host_repo_path, image_repo_path): # pylint: disable=no-self-use + """Returns the command for building the project that is run inside the + project builder container.""" + return get_build_command() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5c4fa32895773b9a742509bc46d5f5df008e5a98 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/continuous_integration_test.py @@ -0,0 +1,88 @@ +# 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 continuous_integration_module.""" +import os +import sys +import unittest +from unittest import mock + +import continuous_integration +import docker + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import repo_manager + +# pylint: disable=no-self-use + + +class FixGitRepoForDiffTest(unittest.TestCase): + """Tests for fix_git_repo_for_diff.""" + + @mock.patch('utils.execute') + def test_fix_git_repo_for_diff(self, mock_execute): + """Tests that fix_git_repo_for_diff works as intended.""" + repo_dir = '/dir' + repo_manager_obj = repo_manager.RepoManager(repo_dir) + continuous_integration.fix_git_repo_for_diff(repo_manager_obj) + expected_command = [ + 'git', 'symbolic-ref', 'refs/remotes/origin/HEAD', + 'refs/remotes/origin/master' + ] + + mock_execute.assert_called_with(expected_command, location=repo_dir) + + +class GetBuildCommand(unittest.TestCase): + """Tests for get_build_command.""" + + def test_build_command(self): + """Tests that get_build_command works as intended.""" + self.assertEqual(continuous_integration.get_build_command(), 'compile') + + +class GetReplaceRepoAndBuildCommand(unittest.TestCase): + """Tests for get_replace_repo_and_build_command.""" + + def test_get_replace_repo_and_build_command(self): + """Tests that get_replace_repo_and_build_command works as intended.""" + host_repo_path = '/path/on/host/to/repo' + image_repo_path = '/src/repo' + command = continuous_integration.get_replace_repo_and_build_command( + host_repo_path, image_repo_path) + expected_command = ('cd / && rm -rf /src/repo/* && ' + 'cp -r /path/on/host/to/repo /src && cd - ' + '&& compile') + self.assertEqual(command, expected_command) + + +class BuildExternalProjetDockerImage(unittest.TestCase): + """Tests for build_external_project_docker_image.""" + + @mock.patch('helper.docker_build') + def test_build_external_project_docker_image(self, mock_docker_build): + """Tests that build_external_project_docker_image works as intended.""" + build_integration_path = '.clusterfuzzlite' + project_src = '/path/to/project/src' + continuous_integration.build_external_project_docker_image( + project_src, build_integration_path) + + mock_docker_build.assert_called_with([ + '-t', docker.EXTERNAL_PROJECT_IMAGE, '-f', + os.path.join('.clusterfuzzlite', 'Dockerfile'), project_src + ]) + + +# TODO(metzman): Write tests for the rest of continuous_integration.py. diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker.py new file mode 100644 index 0000000000000000000000000000000000000000..36e4d7c572cccc0faa3638439193af5973f0e65e --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker.py @@ -0,0 +1,127 @@ +# 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 dealing with docker.""" +import logging +import os +import sys +import uuid + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import constants +import utils +import environment + +BASE_BUILDER_TAG = 'ghcr.io/aixcc-finals/base-builder' +PROJECT_TAG_PREFIX = 'gcr.io/oss-fuzz/' + +# Default fuzz configuration. +_DEFAULT_DOCKER_RUN_ARGS = [ + '-e', 'FUZZING_ENGINE=' + constants.DEFAULT_ENGINE, '-e', 'CIFUZZ=True' +] + +UNIQUE_ID_SUFFIX = '-' + uuid.uuid4().hex + +# TODO(metzman): Make run_fuzzers able to delete this image. +EXTERNAL_PROJECT_IMAGE = 'external-cfl-project' + UNIQUE_ID_SUFFIX + +_DEFAULT_DOCKER_RUN_COMMAND = [ + 'docker', + 'run', + '--rm', + '--privileged', +] + + +def get_docker_env_vars(env_mapping): + """Returns a list of docker arguments that sets each key in |env_mapping| as + an env var and the value of that key in |env_mapping| as the value.""" + env_var_args = [] + for env_var, env_var_val in env_mapping.items(): + env_var_args.extend(['-e', f'{env_var}={env_var_val}']) + return env_var_args + + +def get_project_image_name(project): + """Returns the name of the project builder image for |project_name|.""" + # TODO(jonathanmetzman): We may need unique names to support parallel fuzzing + # for CIFuzz (like CFL supports). Don't do this for now because no one has + # asked for it and build_specified_commit would need to be modified to support + # this. + if project: + return PROJECT_TAG_PREFIX + project + + return EXTERNAL_PROJECT_IMAGE + + +def delete_images(images): + """Deletes |images|.""" + command = ['docker', 'rmi', '-f'] + images + utils.execute(command) + utils.execute(['docker', 'builder', 'prune', '-f']) + + +def get_base_docker_run_args(workspace, + sanitizer=constants.DEFAULT_SANITIZER, + language=constants.DEFAULT_LANGUAGE, + architecture=constants.DEFAULT_ARCHITECTURE, + docker_in_docker=False): + """Returns arguments that should be passed to every invocation of 'docker + run'.""" + docker_args = _DEFAULT_DOCKER_RUN_ARGS.copy() + env_mapping = { + 'SANITIZER': sanitizer, + 'ARCHITECTURE': architecture, + 'FUZZING_LANGUAGE': language, + 'OUT': workspace.out + } + docker_args += get_docker_env_vars(env_mapping) + docker_container = environment.get('CFL_CONTAINER_ID', + utils.get_container_name()) + logging.info('Docker container: %s.', docker_container) + if docker_container and not docker_in_docker: + # Don't map specific volumes if in a docker container, it breaks when + # running a sibling container. + docker_args += ['--volumes-from', docker_container] + else: + docker_args += _get_args_mapping_host_path_to_container(workspace.workspace) + return docker_args, docker_container + + +def get_base_docker_run_command(workspace, + sanitizer=constants.DEFAULT_SANITIZER, + language=constants.DEFAULT_LANGUAGE, + architecture=constants.DEFAULT_ARCHITECTURE, + docker_in_docker=False): + """Returns part of the command that should be used everytime 'docker run' is + invoked.""" + docker_args, docker_container = get_base_docker_run_args( + workspace, + sanitizer, + language, + architecture, + docker_in_docker=docker_in_docker) + command = _DEFAULT_DOCKER_RUN_COMMAND.copy() + docker_args + return command, docker_container + + +def _get_args_mapping_host_path_to_container(host_path, container_path=None): + """Get arguments to docker run that will map |host_path| a path on the host to + a path in the container. If |container_path| is specified, that path is mapped + to. If not, then |host_path| is mapped to itself in the container.""" + # WARNING: Do not use this function when running in production (and + # --volumes-from) is used for mapping volumes. It will break production. + container_path = host_path if container_path is None else container_path + return ['-v', f'{host_path}:{container_path}'] diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker_test.py new file mode 100644 index 0000000000000000000000000000000000000000..045131c10c5b94ed7739769890a243c2776dc999 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/docker_test.py @@ -0,0 +1,119 @@ +# 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 the functionality of the docker module.""" +import unittest +from unittest import mock + +import docker +import test_helpers +import workspace_utils + +CONTAINER_NAME = 'example-container' +config = test_helpers.create_run_config(oss_fuzz_project_name='project', + workspace='/workspace') +config.workspace = '/workspace' +WORKSPACE = workspace_utils.Workspace(config) +SANITIZER = 'example-sanitizer' +LANGUAGE = 'example-language' + + +class GetProjectImageTest(unittest.TestCase): + """Tests for get_project_image.""" + + def test_get_project_image(self): + """Tests that get_project_image_name works as intended.""" + project = 'my-project' + self.assertEqual(docker.get_project_image_name(project), + 'gcr.io/oss-fuzz/my-project') + + +class GetDeleteImagesTest(unittest.TestCase): + """Tests for delete_images.""" + + @mock.patch('utils.execute') + def test_delete_images(self, mock_execute): # pylint: disable=no-self-use + """Tests that get_project_image_name works as intended.""" + images = ['image'] + docker.delete_images(images) + expected_calls = [ + mock.call(['docker', 'rmi', '-f'] + images), + mock.call(['docker', 'builder', 'prune', '-f']) + ] + + mock_execute.assert_has_calls(expected_calls) + + +class GetBaseDockerRunArgsTest(unittest.TestCase): + """Tests get_base_docker_run_args.""" + + @mock.patch('utils.get_container_name', return_value=CONTAINER_NAME) + def test_get_base_docker_run_args_container(self, _): + """Tests that get_base_docker_run_args works as intended when inside a + container.""" + docker_args, docker_container = docker.get_base_docker_run_args( + WORKSPACE, SANITIZER, LANGUAGE) + self.assertEqual(docker_container, CONTAINER_NAME) + expected_docker_args = [] + expected_docker_args = [ + '-e', + 'FUZZING_ENGINE=libfuzzer', + '-e', + 'CIFUZZ=True', + '-e', + f'SANITIZER={SANITIZER}', + '-e', + 'ARCHITECTURE=x86_64', + '-e', + f'FUZZING_LANGUAGE={LANGUAGE}', + '-e', + f'OUT={WORKSPACE.out}', + '--volumes-from', + CONTAINER_NAME, + ] + self.assertEqual(docker_args, expected_docker_args) + + @mock.patch('utils.get_container_name', return_value=None) + def test_get_base_docker_run_args_no_container(self, _): + """Tests that get_base_docker_run_args works as intended when not inside a + container.""" + docker_args, docker_container = docker.get_base_docker_run_args( + WORKSPACE, SANITIZER, LANGUAGE) + self.assertEqual(docker_container, None) + expected_docker_args = [ + '-e', 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e', + f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e', + f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v', + f'{WORKSPACE.workspace}:{WORKSPACE.workspace}' + ] + self.assertEqual(docker_args, expected_docker_args) + + +class GetBaseDockerRunCommandTest(unittest.TestCase): + """Tests get_base_docker_run_args.""" + + @mock.patch('utils.get_container_name', return_value=None) + def test_get_base_docker_run_command_no_container(self, _): + """Tests that get_base_docker_run_args works as intended when not inside a + container.""" + docker_args, docker_container = docker.get_base_docker_run_command( + WORKSPACE, SANITIZER, LANGUAGE) + self.assertEqual(docker_container, None) + expected_docker_command = [ + 'docker', 'run', '--rm', '--privileged', '-e', + 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e', + f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e', + f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v', + f'{WORKSPACE.workspace}:{WORKSPACE.workspace}' + ] + self.assertEqual(docker_args, expected_docker_command) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/environment.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..e99a67910948bcd4ef49e6f7684a976f49f68827 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/environment.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. +"""Module for dealing with env vars.""" + +import ast +import os + + +def _eval_value(value_string): + """Returns evaluated value.""" + try: + return ast.literal_eval(value_string) + except: # pylint: disable=bare-except + # String fallback. + return value_string + + +def get(env_var, default_value=None): + """Returns an environment variable value.""" + value_string = os.getenv(env_var) + if value_string is None: + return default_value + + return _eval_value(value_string) + + +def get_bool(env_var, default_value=None): + """Returns a boolean environment variable value. This is needed because a lot + of CIFuzz users specified 'false' for dry-run. So we need to special case + this.""" + value = get(env_var, default_value) + if not isinstance(value, str): + return bool(value) + + lower_value = value.lower() + allowed_values = {'true', 'false'} + if lower_value not in allowed_values: + raise Exception(f'Bool env var {env_var} value {value} is invalid. ' + f'Must be one of {allowed_values}.') + return lower_value == 'true' diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/example_cifuzz.yml b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/example_cifuzz.yml new file mode 100644 index 0000000000000000000000000000000000000000..e19f2c7cd2397a1e49c453ade22a7a87e14c91e0 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/example_cifuzz.yml @@ -0,0 +1,33 @@ +name: CIFuzz +on: [pull_request] +permissions: {} +jobs: + Fuzzing: + runs-on: ubuntu-latest + permissions: + security-events: write + steps: + - name: Build Fuzzers + id: build + uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master + with: + oss-fuzz-project-name: 'example' + - name: Run Fuzzers + uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master + with: + oss-fuzz-project-name: 'example' + fuzz-seconds: 600 + output-sarif: true + - name: Upload Crash + uses: actions/upload-artifact@v3 + if: failure() && steps.build.outcome == 'success' + with: + name: artifacts + path: ./out/artifacts + - name: Upload Sarif + if: always() && steps.build.outcome == 'success' + uses: github/codeql-action/upload-sarif@v2 + with: + # Path to SARIF file relative to the root of the repository + sarif_file: cifuzz-sarif/results.sarif + checkout_path: cifuzz-sarif diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..acb0189693eb876f8e38efe75a69fbde86a03b56 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils.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. +"""External filestore interface. Cannot be depended on by filestore code.""" +import filestore +import filestore.filesystem +import filestore.git +import filestore.github_actions +import filestore.gsutil +import filestore.no_filestore +import filestore.gitlab + +FILESTORE_MAPPING = { + 'filesystem': filestore.filesystem.FilesystemFilestore, + 'gsutil': filestore.gsutil.GSUtilFilestore, + 'github-actions': filestore.github_actions.GithubActionsFilestore, + 'git': filestore.git.GitFilestore, + # TODO(metzman): Change to "no-filestore" + 'no_filestore': filestore.no_filestore.NoFilestore, + 'gitlab': filestore.gitlab.GitlabFilestore, +} + + +def get_filestore(config): + """Returns the correct filestore object based on the platform in |config|. + Raises an exception if there is no correct filestore for the platform.""" + if config.platform == config.Platform.EXTERNAL_GITHUB: + ci_filestore = filestore.github_actions.GithubActionsFilestore(config) + if not config.git_store_repo: + return ci_filestore + + return filestore.git.GitFilestore(config, ci_filestore) + + filestore_cls = FILESTORE_MAPPING.get(config.filestore) + if filestore_cls is None: + raise filestore.FilestoreError( + f'Filestore: {config.filestore} doesn\'t exist.') + return filestore_cls(config) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/filestore_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e1307376548252e0633cb2c2343feee2c0f745 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9789d8a7ed8ee1798412981a5a6ea79cd82969 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target.py @@ -0,0 +1,408 @@ +# 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 module to handle running a fuzz target for a specified amount of time.""" +import collections +import logging +import multiprocessing +import os +import shutil +import stat +import tempfile +from typing import Optional + +import clusterfuzz.environment +import clusterfuzz.fuzz + +import config_utils +import logs + +logs.init() + +# Use len_control=0 since we don't have enough time fuzzing for len_control to +# make sense (probably). +LIBFUZZER_OPTIONS_BATCH = ['-len_control=0'] +# Use a fixed seed for determinism for code change fuzzing. +LIBFUZZER_OPTIONS_CODE_CHANGE = LIBFUZZER_OPTIONS_BATCH + ['-seed=1337'] +LIBFUZZER_OPTIONS_NO_REPORT_OOM = ['-rss_limit_mb=0'] + +# The number of reproduce attempts for a crash. +REPRODUCE_ATTEMPTS = 10 + +DEFAULT_REPRODUCE_TIME_SECONDS = 30 +PER_LANGUAGE_REPRODUCE_TIMEOUTS = { + 'python': 30 * 4 # Python takes a bit longer on startup. +} +MINIMIZE_TIME_SECONDS = 60 * 4 + +# Seconds on top of duration until a timeout error is raised. +BUFFER_TIME = 10 + +# Log message if we can't check if crash reproduces on an recent build. +COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE = ( + 'Could not run previous build of target to determine if this code change ' + '(pr/commit) introduced crash. Assuming crash was newly introduced.') + +FuzzResult = collections.namedtuple('FuzzResult', + ['testcase', 'stacktrace', 'corpus_path']) + + +def get_libfuzzer_parallel_options(): + """Returns a list containing options to pass to libFuzzer to fuzz using all + available cores.""" + return ['-jobs=' + str(multiprocessing.cpu_count())] + + +class ReproduceError(Exception): + """Error for when we can't attempt to reproduce a crash.""" + + +def get_fuzz_target_corpus_dir(workspace, target_name): + """Returns the directory for storing |target_name|'s corpus in |workspace|.""" + return os.path.join(workspace.corpora, target_name) + + +def get_fuzz_target_pruned_corpus_dir(workspace, target_name): + """Returns the directory for storing |target_name|'s puned corpus in + |workspace|.""" + return os.path.join(workspace.pruned_corpora, target_name) + + +class FuzzTarget: # pylint: disable=too-many-instance-attributes + """A class to manage a single fuzz target. + + Attributes: + target_name: The name of the fuzz target. + duration: The length of time in seconds that the target should run. + target_path: The location of the fuzz target binary. + workspace: The workspace for storing things related to fuzzing. + """ + + # pylint: disable=too-many-arguments + def __init__(self, target_path, duration, workspace, clusterfuzz_deployment, + config): + """Represents a single fuzz target. + + Args: + target_path: The location of the fuzz target binary. + duration: The length of time in seconds the target should run. + workspace: The path used for storing things needed for fuzzing. + clusterfuzz_deployment: The object representing the ClusterFuzz + deployment. + config: The config of this project. + """ + self.target_path = target_path + self.target_name = os.path.basename(self.target_path) + self.duration = int(duration) + self.workspace = workspace + self.clusterfuzz_deployment = clusterfuzz_deployment + self.config = config + self.latest_corpus_path = get_fuzz_target_corpus_dir( + self.workspace, self.target_name) + os.makedirs(self.latest_corpus_path, exist_ok=True) + self.pruned_corpus_path = get_fuzz_target_pruned_corpus_dir( + self.workspace, self.target_name) + os.makedirs(self.pruned_corpus_path, exist_ok=True) + + def _download_corpus(self): + """Downloads the corpus for the target from ClusterFuzz and returns the path + to the corpus. An empty directory is provided if the corpus can't be + downloaded or is empty.""" + self.clusterfuzz_deployment.download_corpus(self.target_name, + self.latest_corpus_path) + return self.latest_corpus_path + + def _target_artifact_path(self): + """Target artifact path.""" + artifact_path = os.path.join(self.workspace.artifacts, self.target_name, + self.config.sanitizer) + os.makedirs(artifact_path, exist_ok=True) + return artifact_path + + def _save_crash(self, crash): + """Add stacktraces to crashes.""" + target_reproducer_path = os.path.join(self._target_artifact_path(), + os.path.basename(crash.input_path)) + shutil.copy(crash.input_path, target_reproducer_path) + bug_summary_artifact_path = target_reproducer_path + '.summary' + with open(bug_summary_artifact_path, 'w') as handle: + handle.write(crash.stacktrace) + + # Set permissions of testcase to be the same as summary so that we're sure + # it can be read by necessary users. + permissions_mode = os.stat(bug_summary_artifact_path).st_mode + os.chmod(target_reproducer_path, permissions_mode & 0o777) + return target_reproducer_path + + def prune(self): + """Prunes the corpus and returns the result.""" + self._download_corpus() + with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE, + self.config.sanitizer, + self.target_path): + engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE) + result = engine_impl.minimize_corpus(self.target_path, [], + [self.latest_corpus_path], + self.pruned_corpus_path, + self._target_artifact_path(), + self.duration) + + print(result.logs) + return FuzzResult(None, result.logs, self.pruned_corpus_path) + + def fuzz(self, batch=False) -> Optional[FuzzResult]: + """Starts the fuzz target run for the length of time specified by duration. + + Returns: + FuzzResult namedtuple with stacktrace and testcase if applicable. + """ + logging.info('Running fuzzer: %s.', self.target_name) + + self._download_corpus() + corpus_path = self.latest_corpus_path + + logging.info('Starting fuzzing') + with tempfile.TemporaryDirectory() as artifacts_dir: + with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE, + self.config.sanitizer, + self.target_path) as env: + engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE) + options = engine_impl.prepare(corpus_path, env.target_path, + env.build_dir) + options.merge_back_new_testcases = False + options.analyze_dictionary = False + if batch: + options.arguments.extend(LIBFUZZER_OPTIONS_BATCH) + else: + options.arguments.extend(LIBFUZZER_OPTIONS_CODE_CHANGE) + + if not self.config.report_ooms: + options.arguments.extend(LIBFUZZER_OPTIONS_NO_REPORT_OOM) + + if self.config.parallel_fuzzing: + if self.config.sanitizer == 'memory': + # TODO(https://github.com/google/oss-fuzz/issues/11915): Don't gate + # this after jobs is fixed for MSAN. + logging.info('Not using jobs because it breaks MSAN.') + else: + options.arguments.extend(get_libfuzzer_parallel_options()) + + result = engine_impl.fuzz(self.target_path, options, artifacts_dir, + self.duration) + print(f'Fuzzing logs:\n{result.logs}') + + if not result.crashes: + # Libfuzzer max time was reached. + logging.info('Fuzzer %s finished with no crashes discovered.', + self.target_name) + return FuzzResult(None, None, self.latest_corpus_path) + + if result.timed_out: + logging.info('Not reporting crash in %s because process timed out.', + self.target_name) + return FuzzResult(None, None, self.latest_corpus_path) + + # Only report first crash. + crash = result.crashes[0] + logging.info('Fuzzer: %s. Detected bug.', self.target_name) + + is_reportable = self.is_crash_reportable(crash.input_path, + crash.reproduce_args, + batch=batch) + if is_reportable or self.config.upload_all_crashes: + logging.info('SAVING CRASH') + fuzzer_logs = result.logs + testcase_path = self._save_crash(crash) + if is_reportable and self.config.minimize_crashes: + # TODO(metzman): We don't want to minimize unreproducible crashes. + # Use is_reportable to decide this even though reportable crashes + # are a subset of reproducible ones. + self.minimize_testcase(testcase_path) + else: + logging.info('NOT MINIMIZED') + else: + fuzzer_logs = None + testcase_path = None + + return FuzzResult(testcase_path, fuzzer_logs, self.latest_corpus_path) + + def minimize_testcase(self, testcase_path): + """Minimizes the testcase located at |testcase_path|.""" + with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE, + self.config.sanitizer, + self.target_path): + engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE) + minimized_testcase_path = testcase_path + '-minimized' + return engine_impl.minimize_testcase(self.target_path, [], + testcase_path, + minimized_testcase_path, + max_time=MINIMIZE_TIME_SECONDS) + + def free_disk_if_needed(self, delete_fuzz_target=True): + """Deletes things that are no longer needed from fuzzing this fuzz target to + save disk space if needed.""" + if not self.config.low_disk_space: + logging.info('Not freeing disk space after running fuzz target.') + return + logging.info('Deleting corpus and seed corpus of %s to save disk.', + self.target_name) + + # Delete the seed corpus, corpus, and fuzz target. + for corpus_path in [self.latest_corpus_path, self.pruned_corpus_path]: + # Use ignore_errors=True to fix + # https://github.com/google/oss-fuzz/issues/5383. + shutil.rmtree(corpus_path, ignore_errors=True) + + target_seed_corpus_path = self.target_path + '_seed_corpus.zip' + if os.path.exists(target_seed_corpus_path): + os.remove(target_seed_corpus_path) + + if delete_fuzz_target: + logging.info('Deleting fuzz target: %s.', self.target_name) + os.remove(self.target_path) + logging.info('Done deleting.') + + def is_reproducible(self, testcase, target_path, reproduce_args): + """Checks if the testcase reproduces. + + Args: + testcase: The path to the testcase to be tested. + target_path: The path to the fuzz target to be tested + reproduce_args: The arguments to pass to the target to reproduce the + crash. + + Returns: + True if crash is reproducible and we were able to run the + binary. + + Raises: + ReproduceError if we can't attempt to reproduce the crash. + """ + if not os.path.exists(target_path): + logging.info('Target: %s does not exist.', target_path) + raise ReproduceError(f'Target {target_path} not found.') + + os.chmod(target_path, stat.S_IRWXO) + + logging.info('Trying to reproduce crash using: %s.', testcase) + with clusterfuzz.environment.Environment(config_utils.DEFAULT_ENGINE, + self.config.sanitizer, + target_path): + reproduce_time_seconds = PER_LANGUAGE_REPRODUCE_TIMEOUTS.get( + self.config.language, DEFAULT_REPRODUCE_TIME_SECONDS) + for _ in range(REPRODUCE_ATTEMPTS): + engine_impl = clusterfuzz.fuzz.get_engine(config_utils.DEFAULT_ENGINE) + try: + result = engine_impl.reproduce(target_path, + testcase, + arguments=reproduce_args, + max_time=reproduce_time_seconds) + except TimeoutError as error: + logging.error('%s.', error) + return False + + if result.return_code != 0: + logging.info('Reproduce command returned: %s. Reproducible on %s.', + result.return_code, target_path) + + return True + + logging.info('Reproduce command returned: 0. Not reproducible on %s.', + target_path) + return False + + def is_crash_reportable(self, testcase, reproduce_args, batch=False): + """Returns True if a crash is reportable. This means the crash is + reproducible but not reproducible on a build from the ClusterFuzz deployment + (meaning the crash was introduced by this PR/commit/code change). + + Args: + testcase: The path to the testcase that triggered the crash. + reproduce_args: The arguments to pass to the target to reproduce the + crash. + + Returns: + True if the crash was introduced by the current pull request. + + Raises: + ReproduceError if we can't attempt to reproduce the crash on the PR build. + """ + + if not self.is_crash_type_reportable(testcase): + return False + + if not os.path.exists(testcase): + raise ReproduceError(f'Testcase {testcase} not found.') + + try: + reproducible_on_code_change = self.is_reproducible( + testcase, self.target_path, reproduce_args) + except ReproduceError as error: + logging.error('Could not check for crash reproducibility.' + 'Please file an issue:' + 'https://github.com/google/oss-fuzz/issues/new.') + raise error + + if not reproducible_on_code_change: + logging.info('Crash is not reproducible.') + return self.config.report_unreproducible_crashes + + logging.info('Crash is reproducible.') + if batch: + # We don't need to check if the crash is novel for batch fuzzing. + return True + + return self.is_crash_novel(testcase, reproduce_args) + + def is_crash_type_reportable(self, testcase): + """Returns True if |testcase| is an actual crash. If crash is a timeout or + OOM then returns True if config says we should report those.""" + # TODO(metzman): Use a less hacky method. + testcase = os.path.basename(testcase) + if testcase.startswith('oom-'): + return self.config.report_ooms + if testcase.startswith('timeout-'): + return self.config.report_timeouts + return True + + def is_crash_novel(self, testcase, reproduce_args): + """Returns whether or not the crash is new. A crash is considered new if it + can't be reproduced on an older ClusterFuzz build of the target.""" + if not os.path.exists(testcase): + raise ReproduceError('Testcase %s not found.' % testcase) + clusterfuzz_build_dir = self.clusterfuzz_deployment.download_latest_build() + if not clusterfuzz_build_dir: + # Crash is reproducible on PR build and we can't test on a recent + # ClusterFuzz/OSS-Fuzz build. + logging.info(COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE) + return True + + clusterfuzz_target_path = os.path.join(clusterfuzz_build_dir, + self.target_name) + + try: + reproducible_on_clusterfuzz_build = self.is_reproducible( + testcase, clusterfuzz_target_path, reproduce_args) + except ReproduceError: + # This happens if the project has ClusterFuzz builds, but the fuzz target + # is not in it (e.g. because the fuzz target is new). + logging.info(COULD_NOT_TEST_ON_CLUSTERFUZZ_MESSAGE) + return True + + if reproducible_on_clusterfuzz_build: + logging.info('The crash is reproducible on previous build. ' + 'Code change (pr/commit) did not introduce crash.') + return False + logging.info('The crash is not reproducible on previous build. ' + 'Code change (pr/commit) introduced crash.') + return True diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/fuzz_target_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e553a25aecacfebc1a15e920fc54f19388d396d6 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report.py new file mode 100644 index 0000000000000000000000000000000000000000..9901c452a0fe536670e5ec6da68b73a902d985e5 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py new file mode 100644 index 0000000000000000000000000000000000000000..df2c9b206b84cdc92b5304f2669ea4cadcc71cae --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py @@ -0,0 +1,71 @@ +# 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 generate_coverage_report.""" + +import unittest +from unittest import mock + +import generate_coverage_report +import test_helpers + +OUT_DIR = '/outdir' +PROJECT = 'example-project' +SANITIZER = 'coverage' + + +class TestRunCoverageCommand(unittest.TestCase): + """Tests run_coverage_command""" + + def setUp(self): + test_helpers.patch_environ(self, empty=True) + + @mock.patch('utils.execute') + def test_run_coverage_command(self, mock_execute): # pylint: disable=no-self-use + """Tests that run_coverage_command works as intended.""" + config = test_helpers.create_run_config(oss_fuzz_project_name=PROJECT, + sanitizer=SANITIZER) + workspace = test_helpers.create_workspace() + generate_coverage_report.run_coverage_command(config, workspace) + expected_command = 'coverage' + expected_env = { + 'SANITIZER': config.sanitizer, + 'FUZZING_LANGUAGE': config.language, + 'OUT': workspace.out, + 'CIFUZZ': 'True', + 'FUZZING_ENGINE': 'libfuzzer', + 'ARCHITECTURE': 'x86_64', + 'FUZZER_ARGS': '-rss_limit_mb=2560 -timeout=25', + 'HTTP_PORT': '', + 'COVERAGE_EXTRA_ARGS': '', + 'CORPUS_DIR': workspace.corpora, + 'COVERAGE_OUTPUT_DIR': workspace.coverage_report + } + mock_execute.assert_called_with(expected_command, env=expected_env) + + +class DownloadCorporaTest(unittest.TestCase): + """Tests for download_corpora.""" + + def test_download_corpora(self): # pylint: disable=no-self-use + """Tests that download_corpora works as intended.""" + clusterfuzz_deployment = mock.Mock() + clusterfuzz_deployment.workspace = test_helpers.create_workspace() + fuzz_target_paths = ['/path/to/fuzzer1', '/path/to/fuzzer2'] + expected_calls = [ + mock.call('fuzzer1', '/workspace/cifuzz-corpus/fuzzer1'), + mock.call('fuzzer2', '/workspace/cifuzz-corpus/fuzzer2') + ] + generate_coverage_report.download_corpora(fuzz_target_paths, + clusterfuzz_deployment) + clusterfuzz_deployment.download_corpus.assert_has_calls(expected_calls) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..762de7928cb93f074b73b51a37514e3807104d37 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage.py @@ -0,0 +1,208 @@ +# 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 determining coverage of fuzz targets.""" +import json +import logging +import os +import sys + +import http_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils + +# The path to get OSS-Fuzz project's latest report json file.` +OSS_FUZZ_LATEST_COVERAGE_INFO_PATH = 'oss-fuzz-coverage/latest_report_info/' + + +# pylint: disable=too-few-public-methods +class CoverageError(Exception): + """Exceptions for project coverage.""" + + +class BaseCoverage: + """Gets coverage data for a project.""" + + def __init__(self, repo_path): + self.repo_path = _normalize_repo_path(repo_path) + + def get_files_covered_by_target(self, target): + """Returns a list of source files covered by the specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + A list of files that the fuzz target covers or None. + """ + target_cov = self.get_target_coverage(target) + if not target_cov: + logging.info('No coverage available for %s.', target) + return None + + coverage_per_file = get_coverage_per_file(target_cov) + if not coverage_per_file: + logging.info('No files found in coverage report.') + return None + + affected_file_list = [] + for file_cov in coverage_per_file: + norm_file_path = os.path.normpath(file_cov['filename']) + if not norm_file_path.startswith(self.repo_path): + # Exclude files outside of the main repo. + continue + + if not is_file_covered(file_cov): + # Don't consider a file affected if code in it is never executed. + continue + + # TODO(metzman): It's weird to me that we access file_cov['filename'] + # again and not norm_file_path, figure out if this makes sense. + relative_path = utils.remove_prefix(file_cov['filename'], self.repo_path) + affected_file_list.append(relative_path) + + return affected_file_list + + def get_target_coverage(self, target): + """Get the coverage report for a specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + The target's coverage json dict or None on failure. + """ + raise NotImplementedError('Child class must implement method.') + + +class OSSFuzzCoverage(BaseCoverage): + """Gets coverage data for a project from OSS-Fuzz.""" + + def __init__(self, repo_path, oss_fuzz_project_name): + """Constructor for OSSFuzzCoverage.""" + super().__init__(repo_path) + self.oss_fuzz_project_name = oss_fuzz_project_name + self.fuzzer_stats_url = _get_oss_fuzz_fuzzer_stats_dir_url( + self.oss_fuzz_project_name) + if self.fuzzer_stats_url is None: + raise CoverageError('Could not get latest coverage.') + + def get_target_coverage(self, target): + """Get the coverage report for a specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + The target's coverage json dict or None on failure. + """ + if not self.fuzzer_stats_url: + return None + + target_url = utils.url_join(self.fuzzer_stats_url, target + '.json') + return http_utils.get_json_from_url(target_url) + + +def _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name): + """Gets and returns a dictionary containing the latest coverage report info + for |project|.""" + latest_report_info_url = utils.url_join(utils.GCS_BASE_URL, + OSS_FUZZ_LATEST_COVERAGE_INFO_PATH, + oss_fuzz_project_name + '.json') + latest_cov_info = http_utils.get_json_from_url(latest_report_info_url) + if latest_cov_info is None: + logging.error('Could not get the coverage report json from url: %s.', + latest_report_info_url) + return None + return latest_cov_info + + +def _get_oss_fuzz_fuzzer_stats_dir_url(oss_fuzz_project_name): + """Gets latest coverage report info for a specific OSS-Fuzz project from + GCS. + + Args: + oss_fuzz_project_name: The name of the project. + + Returns: + The projects coverage report info in json dict or None on failure. + """ + latest_cov_info = _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name) + + if not latest_cov_info: + return None + + if 'fuzzer_stats_dir' not in latest_cov_info: + logging.error('fuzzer_stats_dir not in latest coverage info.') + return None + + fuzzer_stats_dir_gs_url = latest_cov_info['fuzzer_stats_dir'] + fuzzer_stats_dir_url = utils.gs_url_to_https(fuzzer_stats_dir_gs_url) + return fuzzer_stats_dir_url + + +class FilesystemCoverage(BaseCoverage): + """Class that gets a project's coverage from the filesystem.""" + + def __init__(self, repo_path, project_coverage_dir): + super().__init__(repo_path) + self.project_coverage_dir = project_coverage_dir + + def get_target_coverage(self, target): + """Get the coverage report for a specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + The target's coverage json dict or None on failure. + """ + logging.info('Getting coverage for %s from filesystem.', target) + fuzzer_stats_json_path = os.path.join(self.project_coverage_dir, + 'fuzzer_stats', target + '.json') + if not os.path.exists(fuzzer_stats_json_path): + logging.warning('%s does not exist.', fuzzer_stats_json_path) + return None + + with open(fuzzer_stats_json_path) as fuzzer_stats_json_file_handle: + try: + return json.load(fuzzer_stats_json_file_handle) + except json.decoder.JSONDecodeError as err: + logging.error('Could not decode: %s. Error: %s.', + fuzzer_stats_json_path, err) + return None + + +def is_file_covered(file_cov): + """Returns whether the file is covered.""" + return file_cov['summary']['regions']['covered'] + + +def get_coverage_per_file(target_cov): + """Returns the coverage per file within |target_cov|.""" + try: + return target_cov['data'][0]['files'] + except (IndexError, TypeError, KeyError): + logging.error('target_cov: %s is malformed.', target_cov) + return None + + +def _normalize_repo_path(repo_path): + """Normalizes and returns |repo_path| to make sure cases like /src/curl and + /src/curl/ are both handled.""" + repo_path = os.path.normpath(repo_path) + if not repo_path.endswith('/'): + repo_path += '/' + return repo_path diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/get_coverage_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3551f22adf5c0f77a2627c986de033bc71a8febb --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dfcef216766cea9ac3c56da6580f512d585af1bd --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..64d0598acf5f1b3e0afc92f34d5b660ff989e4f2 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/http_utils_test.py @@ -0,0 +1,71 @@ +# 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 http_utils.py""" + +import unittest +from unittest import mock + +from pyfakefs import fake_filesystem_unittest + +import http_utils + +mock_get_response = mock.MagicMock(status_code=200, content=b'') + + +class DownloadUrlTest(unittest.TestCase): + """Tests that download_url works.""" + URL = 'https://example.com/file' + FILE_PATH = '/tmp/file' + + @mock.patch('time.sleep') + @mock.patch('requests.get', return_value=mock_get_response) + def test_download_url_no_error(self, mock_urlretrieve, _): + """Tests that download_url works when there is no error.""" + self.assertTrue(http_utils.download_url(self.URL, self.FILE_PATH)) + self.assertEqual(1, mock_urlretrieve.call_count) + + @mock.patch('time.sleep') + @mock.patch('logging.error') + @mock.patch('requests.get', + return_value=mock.MagicMock(status_code=404, content=b'')) + def test_download_url_http_error(self, mock_get, mock_error, _): + """Tests that download_url doesn't retry when there is an HTTP error.""" + self.assertFalse(http_utils.download_url(self.URL, self.FILE_PATH)) + mock_error.assert_called_with( + 'Unable to download from: %s. Code: %d. Content: %s.', self.URL, 404, + b'') + self.assertEqual(1, mock_get.call_count) + + @mock.patch('time.sleep') + @mock.patch('requests.get', side_effect=ConnectionResetError) + def test_download_url_connection_error(self, mock_get, mock_sleep): + """Tests that download_url doesn't retry when there is an HTTP error.""" + self.assertFalse(http_utils.download_url(self.URL, self.FILE_PATH)) + self.assertEqual(4, mock_get.call_count) + self.assertEqual(3, mock_sleep.call_count) + + +class DownloadAndUnpackZipTest(fake_filesystem_unittest.TestCase): + """Tests download_and_unpack_zip.""" + + def setUp(self): + self.setUpPyfakefs() + + @mock.patch('requests.get', return_value=mock_get_response) + def test_bad_zip_download(self, _): + """Tests download_and_unpack_zip returns none when a bad zip is passed.""" + self.fs.create_file('/url_tmp.zip', contents='Test file.') + self.assertFalse( + http_utils.download_and_unpack_zip('/not/a/real/url', + '/extract-directory')) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/logs.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/logs.py new file mode 100644 index 0000000000000000000000000000000000000000..e6fd83e8a02cdbe73961a4c839ed4444bdad6ec7 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/logs.py @@ -0,0 +1,25 @@ +# 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. +"""Log helpers.""" + +import logging +import os + + +def init(): + """Initialize logging.""" + log_level = logging.DEBUG if os.getenv('CIFUZZ_DEBUG') else logging.INFO + logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=log_level) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/requirements.txt b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..d09da56ada1ec32208bf7a667598cf6ba940be65 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/requirements.txt @@ -0,0 +1,4 @@ +clusterfuzz==2.5.9 +requests==2.28.0 +protobuf==3.20.2 +gsutil==5.20 diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_cifuzz.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_cifuzz.py new file mode 100644 index 0000000000000000000000000000000000000000..e515fb2875fd3e215de7ff5afc5d9091a8d05a9b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_cifuzz.py @@ -0,0 +1,89 @@ +# 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. +"""Script for running CIFuzz end-to-end. This is meant to work outside any +docker image. This cannot depend on any CIFuzz code or third party packages.""" +import os +import subprocess +import sys +import tempfile +import logging + +INFRA_DIR = os.path.dirname(os.path.dirname(__file__)) +DEFAULT_ENVS = [('DRY_RUN', '0'), ('SANITIZER', 'address')] +BASE_CIFUZZ_DOCKER_TAG = 'ghcr.io/aixcc-finals' + + +def set_default_env_var_if_unset(env_var, default_value): + """Sets the value of |env_var| in the environment to |default_value| if it was + not already set.""" + if env_var not in os.environ: + os.environ[env_var] = default_value + + +def docker_run(name, workspace, project_src_path): + """Runs a CIFuzz docker container with |name|.""" + command = [ + 'docker', 'run', '--name', name, '--rm', '-e', 'PROJECT_SRC_PATH', '-e', + 'OSS_FUZZ_PROJECT_NAME', '-e', 'WORKSPACE', '-e', 'REPOSITORY', '-e', + 'DRY_RUN', '-e', 'CI', '-e', 'SANITIZER', '-e', 'GIT_SHA', '-e', + 'FILESTORE', '-e', 'NO_CLUSTERFUZZ_DEPLOYMENT' + ] + if project_src_path: + command += ['-v', f'{project_src_path}:{project_src_path}'] + command += [ + '-v', '/var/run/docker.sock:/var/run/docker.sock', '-v', + f'{workspace}:{workspace}', f'{BASE_CIFUZZ_DOCKER_TAG}/{name}' + ] + print('Running docker command:', command) + subprocess.run(command, check=True) + + +def docker_build(image): + """Builds the CIFuzz |image|. Only suitable for building CIFuzz images.""" + command = [ + 'docker', 'build', '-t', f'{BASE_CIFUZZ_DOCKER_TAG}/{image}', '--file', + f'{image}.Dockerfile', '.' + ] + subprocess.run(command, check=True, cwd=INFRA_DIR) + + +def main(): + """Builds and runs fuzzers using CIFuzz.""" + for env_var, default_value in DEFAULT_ENVS: + set_default_env_var_if_unset(env_var, default_value) + + repository = os.getenv('REPOSITORY') + assert repository + + project_src_path = os.getenv('PROJECT_SRC_PATH') + + with tempfile.TemporaryDirectory() as temp_dir: + if 'WORKSPACE' not in os.environ: + os.environ['WORKSPACE'] = temp_dir + + workspace = os.environ['WORKSPACE'] + + docker_build('build_fuzzers') + docker_run('build_fuzzers', workspace, project_src_path) + docker_build('run_fuzzers') + try: + docker_run('run_fuzzers', workspace, project_src_path) + except subprocess.CalledProcessError: + logging.error('run_fuzzers failed.') + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..a136f6991083426eb939f2c1cdef8afd28dc96ea --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..924914199677e732c81d7d927553b60341bdbe7b --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py @@ -0,0 +1,97 @@ +# 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. +"""Runs a specific OSS-Fuzz project's fuzzers for CI tools.""" +import logging +import sys + +import config_utils +import docker +import logs +import run_fuzzers + +# pylint: disable=c-extension-no-member +# pylint gets confused because of the relative import of cifuzz. + +logs.init() + + +def delete_unneeded_docker_images(config): + """Deletes unneeded docker images if running in an environment with low + disk space.""" + if not config.low_disk_space: + return + logging.info('Deleting builder docker images to save disk space.') + project_image = docker.get_project_image_name(config.oss_fuzz_project_name) + images = [ + project_image, + docker.BASE_BUILDER_TAG, + docker.BASE_BUILDER_TAG + '-go', + docker.BASE_BUILDER_TAG + '-javascript', + docker.BASE_BUILDER_TAG + '-jvm', + docker.BASE_BUILDER_TAG + '-python', + docker.BASE_BUILDER_TAG + '-rust', + docker.BASE_BUILDER_TAG + '-ruby', + docker.BASE_BUILDER_TAG + '-swift', + ] + docker.delete_images(images) + + +def run_fuzzers_entrypoint(): + """This is the entrypoint for the run_fuzzers github action. + This action can be added to any OSS-Fuzz project's workflow that uses + Github.""" + config = config_utils.RunFuzzersConfig() + # The default return code when an error occurs. + returncode = 1 + if config.dry_run: + # Sets the default return code on error to success. + returncode = 0 + + delete_unneeded_docker_images(config) + # Run the specified project's fuzzers from the build. + result = run_fuzzers.run_fuzzers(config) + if result == run_fuzzers.RunFuzzersResult.ERROR: + logging.error('Error occurred while running in workspace %s.', + config.workspace) + return returncode + if result == run_fuzzers.RunFuzzersResult.BUG_FOUND: + logging.info('Bug found.') + if not config.dry_run: + # Return 2 when a bug was found by a fuzzer causing the CI to fail. + return 2 + return 0 + + +def main(): + """Runs project's fuzzers for CI tools. + This is the entrypoint for the run_fuzzers github action. + + NOTE: libFuzzer binaries must be located in the $WORKSPACE/build-out + directory in order for this action to be used. This action will only fuzz the + binaries that are located in that directory. It is recommended that you add + the build_fuzzers action preceding this one. + + NOTE: Any crash report will be in the filepath: + ${GITHUB_WORKSPACE}/out/testcase + This can be used in parallel with the upload-artifact action to surface the + logs. + + Returns: + 0 on success or nonzero on failure. + """ + return run_fuzzers_entrypoint() + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py new file mode 100644 index 0000000000000000000000000000000000000000..64fddcdff897e0af6102c0b58de05a89051d49e2 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py @@ -0,0 +1,475 @@ +# 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 running fuzzers.""" +import json +import os +import shutil +import stat +import sys +import tempfile +import unittest +from unittest import mock + +import parameterized +from pyfakefs import fake_filesystem_unittest + +import build_fuzzers +import fuzz_target +import run_fuzzers + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.append(INFRA_DIR) + +import helper +import test_helpers + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +# Location of files used for testing. +TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'test_data') + +MEMORY_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'memory') +MEMORY_FUZZER = 'curl_fuzzer_memory' + +UNDEFINED_FUZZER_DIR = os.path.join(TEST_DATA_PATH, 'undefined') +UNDEFINED_FUZZER = 'curl_fuzzer_undefined' + +FUZZ_SECONDS = 10 + + +class RunFuzzerIntegrationTestMixin: # pylint: disable=too-few-public-methods,invalid-name + """Mixin for integration test classes that runbuild_fuzzers on builds of a + specific sanitizer.""" + # These must be defined by children. + FUZZER_DIR = None + FUZZER = None + + def setUp(self): + """Patch the environ so that we can execute runner scripts.""" + test_helpers.patch_environ(self, runner=True) + + def _test_run_with_sanitizer(self, fuzzer_dir, sanitizer): + """Calls run_fuzzers on fuzzer_dir and |sanitizer| and asserts + the run succeeded and that no bug was found.""" + with test_helpers.temp_dir_copy(fuzzer_dir) as fuzzer_dir_copy: + config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS, + workspace=fuzzer_dir_copy, + oss_fuzz_project_name='curl', + sanitizer=sanitizer) + result = run_fuzzers.run_fuzzers(config) + self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class RunMemoryFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin, + unittest.TestCase): + """Integration test for build_fuzzers with an MSAN build.""" + FUZZER_DIR = MEMORY_FUZZER_DIR + FUZZER = MEMORY_FUZZER + + def test_run_with_memory_sanitizer(self): + """Tests run_fuzzers with a valid MSAN build.""" + self._test_run_with_sanitizer(self.FUZZER_DIR, 'memory') + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class RunUndefinedFuzzerIntegrationTest(RunFuzzerIntegrationTestMixin, + unittest.TestCase): + """Integration test for build_fuzzers with an UBSAN build.""" + FUZZER_DIR = UNDEFINED_FUZZER_DIR + FUZZER = UNDEFINED_FUZZER + + def test_run_with_undefined_sanitizer(self): + """Tests run_fuzzers with a valid UBSAN build.""" + self._test_run_with_sanitizer(self.FUZZER_DIR, 'undefined') + + +class BaseFuzzTargetRunnerTest(unittest.TestCase): + """Tests BaseFuzzTargetRunner.""" + + def _create_runner(self, **kwargs): # pylint: disable=no-self-use + defaults = { + 'fuzz_seconds': FUZZ_SECONDS, + 'oss_fuzz_project_name': EXAMPLE_PROJECT + } + for default_key, default_value in defaults.items(): + if default_key not in kwargs: + kwargs[default_key] = default_value + + config = test_helpers.create_run_config(**kwargs) + return run_fuzzers.BaseFuzzTargetRunner(config) + + def _test_initialize_fail(self, expected_error_args, **create_runner_kwargs): + with mock.patch('logging.error') as mock_error: + runner = self._create_runner(**create_runner_kwargs) + self.assertFalse(runner.initialize()) + mock_error.assert_called_with(*expected_error_args) + + @parameterized.parameterized.expand([(0,), (None,), (-1,)]) + def test_initialize_invalid_fuzz_seconds(self, fuzz_seconds): + """Tests initialize fails with an invalid fuzz seconds.""" + expected_error_args = ('Fuzz_seconds argument must be greater than 1, ' + 'but was: %s.', fuzz_seconds) + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.mkdir(out_path) + with mock.patch('utils.get_fuzz_targets') as mock_get_fuzz_targets: + mock_get_fuzz_targets.return_value = [ + os.path.join(out_path, 'fuzz_target') + ] + self._test_initialize_fail(expected_error_args, + fuzz_seconds=fuzz_seconds, + workspace=tmp_dir) + + def test_initialize_no_out_dir(self): + """Tests initialize fails with no out dir.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + expected_error_args = ('Out directory: %s does not exist.', out_path) + self._test_initialize_fail(expected_error_args, workspace=tmp_dir) + + def test_initialize_nonempty_artifacts(self): + """Tests initialize with a file artifacts path.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.mkdir(out_path) + os.makedirs(os.path.join(tmp_dir, 'out')) + artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts') + with open(artifacts_path, 'w') as artifacts_handle: + artifacts_handle.write('fake') + expected_error_args = ( + 'Artifacts path: %s exists and is not an empty directory.', + artifacts_path) + self._test_initialize_fail(expected_error_args, workspace=tmp_dir) + + def test_initialize_bad_artifacts(self): + """Tests initialize with a non-empty artifacts path.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.mkdir(out_path) + artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts') + os.makedirs(artifacts_path) + artifact_path = os.path.join(artifacts_path, 'artifact') + with open(artifact_path, 'w') as artifact_handle: + artifact_handle.write('fake') + expected_error_args = ( + 'Artifacts path: %s exists and is not an empty directory.', + artifacts_path) + self._test_initialize_fail(expected_error_args, workspace=tmp_dir) + + @mock.patch('utils.get_fuzz_targets') + @mock.patch('logging.error') + def test_initialize_empty_artifacts(self, mock_log_error, + mock_get_fuzz_targets): + """Tests initialize with an empty artifacts dir.""" + mock_get_fuzz_targets.return_value = ['fuzz-target'] + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.mkdir(out_path) + artifacts_path = os.path.join(tmp_dir, 'out', 'artifacts') + os.makedirs(artifacts_path) + runner = self._create_runner(workspace=tmp_dir) + self.assertTrue(runner.initialize()) + mock_log_error.assert_not_called() + self.assertTrue(os.path.isdir(artifacts_path)) + + @mock.patch('utils.get_fuzz_targets') + @mock.patch('logging.error') + def test_initialize_no_artifacts(self, mock_log_error, mock_get_fuzz_targets): + """Tests initialize with no artifacts dir (the expected setting).""" + mock_get_fuzz_targets.return_value = ['fuzz-target'] + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.mkdir(out_path) + runner = self._create_runner(workspace=tmp_dir) + self.assertTrue(runner.initialize()) + mock_log_error.assert_not_called() + self.assertTrue(os.path.isdir(os.path.join(tmp_dir, 'out', 'artifacts'))) + + def test_initialize_no_fuzz_targets(self): + """Tests initialize with no fuzz targets.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.makedirs(out_path) + expected_error_args = ('No fuzz targets were found in out directory: %s.', + out_path) + self._test_initialize_fail(expected_error_args, workspace=tmp_dir) + + +class CiFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase): + """Tests that CiFuzzTargetRunner works as intended.""" + + def setUp(self): + self.setUpPyfakefs() + + @mock.patch('clusterfuzz_deployment.OSSFuzz.upload_crashes') + @mock.patch('utils.get_fuzz_targets') + @mock.patch('run_fuzzers.CiFuzzTargetRunner.run_fuzz_target') + @mock.patch('run_fuzzers.CiFuzzTargetRunner.create_fuzz_target_obj') + def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj, + mock_run_fuzz_target, mock_get_fuzz_targets, + mock_upload_crashes): + """Tests that run_fuzz_targets quits on the first crash it finds.""" + workspace = 'workspace' + out_path = os.path.join(workspace, 'build-out') + self.fs.create_dir(out_path) + config = test_helpers.create_run_config( + fuzz_seconds=FUZZ_SECONDS, + workspace=workspace, + oss_fuzz_project_name=EXAMPLE_PROJECT) + runner = run_fuzzers.CiFuzzTargetRunner(config) + + mock_get_fuzz_targets.return_value = ['target1', 'target2'] + runner.initialize() + testcase = os.path.join(workspace, 'testcase') + self.fs.create_file(testcase) + stacktrace = 'stacktrace' + corpus_dir = 'corpus' + self.fs.create_dir(corpus_dir) + mock_run_fuzz_target.return_value = fuzz_target.FuzzResult( + testcase, stacktrace, corpus_dir) + magic_mock = mock.MagicMock() + magic_mock.target_name = 'target1' + mock_create_fuzz_target_obj.return_value = magic_mock + self.assertTrue(runner.run_fuzz_targets()) + self.assertEqual(mock_run_fuzz_target.call_count, 1) + self.assertEqual(mock_upload_crashes.call_count, 1) + + +class BatchFuzzTargetRunnerTest(fake_filesystem_unittest.TestCase): + """Tests that BatchFuzzTargetRunnerTest works as intended.""" + WORKSPACE = 'workspace' + STACKTRACE = 'stacktrace' + CORPUS_DIR = 'corpus' + + def setUp(self): + self.setUpPyfakefs() + out_dir = os.path.join(self.WORKSPACE, 'build-out') + self.fs.create_dir(out_dir) + self.testcase1 = os.path.join(out_dir, 'testcase-aaa') + self.fs.create_file(self.testcase1) + self.testcase2 = os.path.join(out_dir, 'testcase-bbb') + self.fs.create_file(self.testcase2) + self.config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS, + workspace=self.WORKSPACE, + cfl_platform='github') + + @mock.patch('utils.get_fuzz_targets', return_value=['target1', 'target2']) + @mock.patch('clusterfuzz_deployment.ClusterFuzzLite.upload_crashes') + @mock.patch('run_fuzzers.BatchFuzzTargetRunner.run_fuzz_target') + @mock.patch('run_fuzzers.BatchFuzzTargetRunner.create_fuzz_target_obj') + def test_run_fuzz_targets_quits(self, mock_create_fuzz_target_obj, + mock_run_fuzz_target, mock_upload_crashes, _): + """Tests that run_fuzz_targets doesn't quit on the first crash it finds.""" + runner = run_fuzzers.BatchFuzzTargetRunner(self.config) + runner.initialize() + + call_count = 0 + + def mock_run_fuzz_target_impl(_): + nonlocal call_count + if call_count == 0: + testcase = self.testcase1 + elif call_count == 1: + testcase = self.testcase2 + assert call_count != 2 + call_count += 1 + if not os.path.exists(self.CORPUS_DIR): + self.fs.create_dir(self.CORPUS_DIR) + return fuzz_target.FuzzResult(testcase, self.STACKTRACE, self.CORPUS_DIR) + + mock_run_fuzz_target.side_effect = mock_run_fuzz_target_impl + magic_mock = mock.MagicMock() + magic_mock.target_name = 'target1' + mock_create_fuzz_target_obj.return_value = magic_mock + self.assertTrue(runner.run_fuzz_targets()) + self.assertEqual(mock_run_fuzz_target.call_count, 2) + self.assertEqual(mock_upload_crashes.call_count, 1) + + +class GetCoverageTargetsTest(unittest.TestCase): + """Tests for get_coverage_fuzz_targets.""" + + def test_get_fuzz_targets(self): + """Tests that get_coverage_fuzz_targets returns expected targets.""" + with tempfile.TemporaryDirectory() as temp_dir: + # Setup. + fuzz_target_path = os.path.join(temp_dir, 'fuzz-target') + with open(fuzz_target_path, 'w') as file_handle: + file_handle.write('') + fuzz_target_st = os.stat(fuzz_target_path) + os.chmod(fuzz_target_path, fuzz_target_st.st_mode | stat.S_IEXEC) + non_fuzz_target1 = os.path.join(temp_dir, 'non-fuzz-target1') + with open(non_fuzz_target1, 'w') as file_handle: + file_handle.write('LLVMFuzzerTestOneInput') + subdir = os.path.join(temp_dir, 'subdir') + os.mkdir(subdir) + non_fuzz_target2 = os.path.join(subdir, 'non-fuzz-target1') + with open(non_fuzz_target2, 'w') as file_handle: + file_handle.write('LLVMFuzzerTestOneInput') + + self.assertEqual(run_fuzzers.get_coverage_fuzz_targets(temp_dir), + [fuzz_target_path]) + + +@unittest.skip('TODO(metzman): Fix this test') +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class CoverageReportIntegrationTest(unittest.TestCase): + """Integration tests for coverage reports.""" + SANITIZER = 'coverage' + + def setUp(self): + test_helpers.patch_environ(self, runner=True) + + @mock.patch('filestore.github_actions._upload_artifact_with_upload_js') + def test_coverage_report(self, _): + """Tests generation of coverage reports end-to-end, from building to + generation.""" + + with test_helpers.docker_temp_dir() as temp_dir: + shared = os.path.join(temp_dir, 'shared') + os.mkdir(shared) + copy_command = ('cp -r /opt/code_coverage /shared && ' + 'cp $(which llvm-profdata) /shared && ' + 'cp $(which llvm-cov) /shared') + assert helper.docker_run([ + '-v', f'{shared}:/shared', 'ghcr.io/aixcc-finals/base-runner', 'bash', + '-c', copy_command + ]) + + os.environ['CODE_COVERAGE_SRC'] = os.path.join(shared, 'code_coverage') + os.environ['PATH'] += os.pathsep + shared + # Do coverage build. + build_config = test_helpers.create_build_config( + oss_fuzz_project_name=EXAMPLE_PROJECT, + project_repo_name='oss-fuzz', + workspace=temp_dir, + git_sha='0b95fe1039ed7c38fea1f97078316bfc1030c523', + base_commit='da0746452433dc18bae699e355a9821285d863c8', + sanitizer=self.SANITIZER, + cfl_platform='github', + # Needed for test not to fail because of permissions issues. + bad_build_check=False) + self.assertTrue(build_fuzzers.build_fuzzers(build_config)) + + # TODO(metzman): Get rid of this here and make 'compile' do this. + chmod_command = ('chmod -R +r /out && ' + 'find /out -type d -exec chmod +x {} +') + + assert helper.docker_run([ + '-v', f'{os.path.join(temp_dir, "build-out")}:/out', + 'ghcr.io/aixcc-finals/base-builder', 'bash', '-c', chmod_command + ]) + + # Generate report. + run_config = test_helpers.create_run_config(fuzz_seconds=FUZZ_SECONDS, + workspace=temp_dir, + sanitizer=self.SANITIZER, + mode='coverage', + cfl_platform='github') + result = run_fuzzers.run_fuzzers(run_config) + self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND) + expected_summary_path = os.path.join( + TEST_DATA_PATH, 'example_coverage_report_summary.json') + with open(expected_summary_path) as file_handle: + expected_summary = json.loads(file_handle.read()) + actual_summary_path = os.path.join(temp_dir, 'cifuzz-coverage', + 'report', 'linux', 'summary.json') + with open(actual_summary_path) as file_handle: + actual_summary = json.loads(file_handle.read()) + self.assertEqual(expected_summary, actual_summary) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class RunAddressFuzzersIntegrationTest(RunFuzzerIntegrationTestMixin, + unittest.TestCase): + """Integration tests for build_fuzzers with an ASAN build.""" + + BUILD_DIR_NAME = 'cifuzz-latest-build' + + def test_new_bug_found(self): + """Tests run_fuzzers with a valid ASAN build.""" + # Set the first return value to True, then the second to False to + # emulate a bug existing in the current PR but not on the downloaded + # OSS-Fuzz build. + with mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=[True, False]): + with tempfile.TemporaryDirectory() as tmp_dir: + workspace = os.path.join(tmp_dir, 'workspace') + shutil.copytree(TEST_DATA_PATH, workspace) + config = test_helpers.create_run_config( + fuzz_seconds=FUZZ_SECONDS, + workspace=workspace, + oss_fuzz_project_name=EXAMPLE_PROJECT) + result = run_fuzzers.run_fuzzers(config) + self.assertEqual(result, run_fuzzers.RunFuzzersResult.BUG_FOUND) + + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=[True, True]) + def test_old_bug_found(self, _): + """Tests run_fuzzers with a bug found in OSS-Fuzz before.""" + with tempfile.TemporaryDirectory() as tmp_dir: + workspace = os.path.join(tmp_dir, 'workspace') + shutil.copytree(TEST_DATA_PATH, workspace) + config = test_helpers.create_run_config( + fuzz_seconds=FUZZ_SECONDS, + workspace=workspace, + oss_fuzz_project_name=EXAMPLE_PROJECT) + result = run_fuzzers.run_fuzzers(config) + self.assertEqual(result, run_fuzzers.RunFuzzersResult.NO_BUG_FOUND) + + def test_invalid_build(self): + """Tests run_fuzzers with an invalid ASAN build.""" + with tempfile.TemporaryDirectory() as tmp_dir: + out_path = os.path.join(tmp_dir, 'build-out') + os.mkdir(out_path) + config = test_helpers.create_run_config( + fuzz_seconds=FUZZ_SECONDS, + workspace=tmp_dir, + oss_fuzz_project_name=EXAMPLE_PROJECT) + result = run_fuzzers.run_fuzzers(config) + self.assertEqual(result, run_fuzzers.RunFuzzersResult.ERROR) + + +class GetFuzzTargetRunnerTest(unittest.TestCase): + """Tests for get_fuzz_fuzz_target_runner.""" + + @parameterized.parameterized.expand([ + ('batch', run_fuzzers.BatchFuzzTargetRunner), + ('code-change', run_fuzzers.CiFuzzTargetRunner), + ('coverage', run_fuzzers.CoverageTargetRunner) + ]) + def test_get_fuzz_target_runner(self, mode, fuzz_target_runner_cls): + """Tests that get_fuzz_target_runner returns the correct runner based on the + specified mode.""" + with tempfile.TemporaryDirectory() as tmp_dir: + run_config = test_helpers.create_run_config( + fuzz_seconds=FUZZ_SECONDS, + workspace=tmp_dir, + oss_fuzz_project_name='example', + mode=mode) + runner = run_fuzzers.get_fuzz_target_runner(run_config) + self.assertTrue(isinstance(runner, fuzz_target_runner_cls)) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6bf2dd7e2da113ec3b179fcb3e0d319ed75c26e8 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils.py @@ -0,0 +1,251 @@ +# 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. +"""Module for outputting SARIF data.""" +import copy +import json +import logging +import os + +from clusterfuzz import stacktraces + +SARIF_RULES = [ + { + 'id': 'no-crashes', + 'shortDescription': { + 'text': 'Don\'t crash' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/416.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'heap-use-after-free', + 'shortDescription': { + 'text': 'Use of a heap-object after it has been freed.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/416.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'heap-buffer-overflow', + 'shortDescription': { + 'text': 'A read or write past the end of a heap buffer.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/122.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'stack-buffer-overflow', + 'shortDescription': { + 'text': 'A read or write past the end of a stack buffer.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/121.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'global-buffer-overflow', + 'shortDescription': { + 'text': 'A read or write past the end of a global buffer.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/121.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'stack-use-after-return', + 'shortDescription': { + 'text': + 'A stack-based variable has been used after the function returned.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/562.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'stack-use-after-scope', + 'shortDescription': { + 'text': + 'A stack-based variable has been used outside of the scope in which it exists.' + }, + 'helpUri': 'https://cwe.mitre.org/data/definitions/562.html', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': 'initialization-order-fiasco', + 'shortDescription': { + 'text': 'Problem with order of initialization of global objects.' + }, + 'helpUri': 'https://isocpp.org/wiki/faq/ctors#static-init-order', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': + 'direct-leak', + 'shortDescription': { + 'text': 'Memory is leaked.' + }, + 'helpUri': + 'https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer', + 'properties': { + 'category': 'Crashes' + } + }, + { + 'id': + 'indirect-leak', + 'shortDescription': { + 'text': 'Memory is leaked.' + }, + 'helpUri': + 'https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer', + 'properties': { + 'category': 'Crashes' + } + }, +] +SARIF_DATA = { + 'version': + '2.1.0', + '$schema': + 'http://json.schemastore.org/sarif-2.1.0-rtm.4', + 'runs': [{ + 'tool': { + 'driver': { + 'name': 'ClusterFuzzLite/CIFuzz', + 'informationUri': 'https://google.github.io/clusterfuzzlite/', + 'rules': SARIF_RULES, + } + }, + 'results': [] + }] +} + +SRC_ROOT = '/src/' + + +def redact_src_path(src_path): + """Redact the src path so that it can be reported to users.""" + src_path = os.path.normpath(src_path) + if src_path.startswith(SRC_ROOT): + src_path = src_path[len(SRC_ROOT):] + + src_path = os.sep.join(src_path.split(os.sep)[1:]) + return src_path + + +def get_error_frame(crash_info): + """Returns the stackframe where the error occurred.""" + if not crash_info.crash_state: + return None + state = crash_info.crash_state.split('\n')[0] + logging.info('state: %s frames %s, %s', state, crash_info.frames, + [f.function_name for f in crash_info.frames[0]]) + + for crash_frames in crash_info.frames: + for frame in crash_frames: + # TODO(metzman): Do something less fragile here. + if frame.function_name is None: + continue + if state in frame.function_name: + return frame + return None + + +def get_error_source_info(crash_info): + """Returns the filename and the line where the bug occurred.""" + frame = get_error_frame(crash_info) + if not frame: + return (None, 1) + try: + return redact_src_path(frame.filename), int(frame.fileline or 1) + except TypeError: + return (None, 1) + + +def get_rule_index(crash_type): + """Returns the rule index describe the rule that |crash_type| ran afoul of.""" + # Don't include "READ" or "WRITE" or number of bytes. + crash_type = crash_type.replace('\n', ' ').split(' ')[0].lower() + logging.info('crash_type: %s.', crash_type) + for idx, rule in enumerate(SARIF_RULES): + if rule['id'] == crash_type: + logging.info('Rule index: %d.', idx) + return idx + + return get_rule_index('no-crashes') + + +def get_sarif_data(stacktrace, target_path): + """Returns a description of the crash in SARIF.""" + data = copy.deepcopy(SARIF_DATA) + if stacktrace is None: + return data + + fuzz_target = os.path.basename(target_path) + stack_parser = stacktraces.StackParser(fuzz_target=fuzz_target, + symbolized=True, + detect_ooms_and_hangs=True, + include_ubsan=True) + crash_info = stack_parser.parse(stacktrace) + error_source_info = get_error_source_info(crash_info) + rule_idx = get_rule_index(crash_info.crash_type) + rule_id = SARIF_RULES[rule_idx]['id'] + uri = error_source_info[0] + + result = { + 'level': 'error', + 'message': { + 'text': crash_info.crash_type + }, + 'locations': [{ + 'physicalLocation': { + 'artifactLocation': { + 'uri': uri, + 'index': 0 + }, + 'region': { + 'startLine': error_source_info[1], + # We don't have this granualarity fuzzing. + 'startColumn': 1, + } + } + }], + 'ruleId': rule_id, + 'ruleIndex': rule_idx + } + if uri: + data['runs'][0]['results'].append(result) + return data + + +def write_stacktrace_to_sarif(stacktrace, target_path, workspace): + """Writes a description of the crash in stacktrace to a SARIF file.""" + data = get_sarif_data(stacktrace, target_path) + if not os.path.exists(workspace.sarif): + os.makedirs(workspace.sarif) + with open(os.path.join(workspace.sarif, 'results.sarif'), 'w') as file_handle: + file_handle.write(json.dumps(data)) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils_test.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/sarif_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e8870887c071e4694a6550af0a4f432ad3838a8f --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_helpers.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..846a8a888ecda9c48f66d5486cb118387fbf1511 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/test_helpers.py @@ -0,0 +1,117 @@ +# 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. +"""Contains convenient helpers for writing tests.""" + +import contextlib +import os +import sys +import shutil +import tempfile +from unittest import mock + +import config_utils +import docker +import workspace_utils + +INFRA_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +# pylint: disable=wrong-import-position,import-error +sys.path.append(INFRA_DIR) + +import helper + + +# TODO(metzman): Get rid of these decorators. +@mock.patch('config_utils._is_dry_run', return_value=True) +@mock.patch('platform_config.BasePlatformConfig.project_src_path', + return_value=None) +@mock.patch('os.path.basename', return_value=None) +def _create_config(config_cls, _, __, ___, **kwargs): + """Creates a config object from |config_cls| 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.""" + with mock.patch('config_utils.BaseConfig.validate', return_value=True): + config = config_cls() + for key, value in kwargs.items(): + assert hasattr(config, key), 'Config doesn\'t have attribute: ' + key + setattr(config, key, value) + + return config + + +def create_build_config(**kwargs): + """Wrapper around _create_config for build configs.""" + return _create_config(config_utils.BuildFuzzersConfig, **kwargs) + + +def create_run_config(**kwargs): + """Wrapper around _create_config for run configs.""" + return _create_config(config_utils.RunFuzzersConfig, **kwargs) + + +def create_workspace(workspace_path='/workspace'): + """Returns a workspace located at |workspace_path| ('/workspace' by + default).""" + config = create_run_config(workspace=workspace_path) + return workspace_utils.Workspace(config) + + +def patch_environ(testcase_obj, env=None, empty=False, runner=False): + """Patch environment. |testcase_obj| is the unittest.TestCase that contains + tests. |env|, if specified, is a dictionary of environment variables to start + from. If |empty| is True then the new patched environment will be empty. If + |runner| is True then the necessary environment variables will be set to run + the scripts from base-runner.""" + if env is None: + env = {} + + patcher = mock.patch.dict(os.environ, env) + testcase_obj.addCleanup(patcher.stop) + patcher.start() + if empty: + for key in os.environ.copy(): + del os.environ[key] + + if runner: + # Add the scripts for base-runner to the path since the wont be in + # /usr/local/bin on host machines during testing. + base_runner_dir = os.path.join(INFRA_DIR, 'base-images', 'base-runner') + os.environ['PATH'] = (os.environ.get('PATH', '') + os.pathsep + + base_runner_dir) + if 'GOPATH' not in os.environ: + # A GOPATH must be set or else the coverage script fails, even for getting + # the coverage of non-Go programs. + os.environ['GOPATH'] = '/root/go' + + +@contextlib.contextmanager +def temp_dir_copy(directory): + """Context manager that yields a temporary copy of |directory|.""" + with tempfile.TemporaryDirectory() as temp_dir: + temp_copy_path = os.path.join(temp_dir, os.path.basename(directory)) + shutil.copytree(directory, temp_copy_path) + yield temp_copy_path + + +@contextlib.contextmanager +def docker_temp_dir(): + """Returns a temporary a directory that is useful for use with docker. On + cleanup this contextmanager uses docker to delete the directory's contents so + that if anything is owned by root it can be deleted (which + tempfile.TemporaryDirectory() cannot do) by non-root users.""" + with tempfile.TemporaryDirectory() as temp_dir: + yield temp_dir + helper.docker_run([ + '-v', f'{temp_dir}:/temp_dir', '-t', docker.BASE_BUILDER_TAG, + '/bin/bash', '-c', 'rm -rf /temp_dir/*' + ]) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/workspace_utils.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/workspace_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ba24456bea54ed0bc61190489cade8ae6e83f4da --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/cifuzz/workspace_utils.py @@ -0,0 +1,85 @@ +# 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 representing the workspace directory which CIFuzz uses.""" + +import os +import shutil + + +class Workspace: + """Class representing the workspace directory.""" + + def __init__(self, config): + self.workspace = config.workspace + + def initialize_dir(self, directory): # pylint: disable=no-self-use + """Creates directory if it doesn't already exist, otherwise does nothing.""" + os.makedirs(directory, exist_ok=True) + + @property + def repo_storage(self): + """The parent directory for repo storage.""" + return os.path.join(self.workspace, 'storage') + + @property + def out(self): + """The out directory used for storing the fuzzer build built by + build_fuzzers.""" + # Don't use 'out' because it needs to be used by artifacts. + return os.path.join(self.workspace, 'build-out') + + @property + def work(self): + """The directory used as the work directory for the fuzzer build/run.""" + return os.path.join(self.workspace, 'work') + + @property + def artifacts(self): + """The directory used to store artifacts for download by CI-system users.""" + # This is hardcoded by a lot of clients, so we need to use this. + return os.path.join(self.workspace, 'out', 'artifacts') + + @property + def clusterfuzz_build(self): + """The directory where builds from ClusterFuzz are stored.""" + return os.path.join(self.workspace, 'cifuzz-prev-build') + + @property + def clusterfuzz_coverage(self): + """The directory where builds from ClusterFuzz are stored.""" + return os.path.join(self.workspace, 'cifuzz-prev-coverage') + + @property + def coverage_report(self): + """The directory where coverage reports generated by cifuzz are put.""" + return os.path.join(self.workspace, 'cifuzz-coverage') + + @property + def corpora(self): + """The directory where corpora from ClusterFuzz are stored.""" + return os.path.join(self.workspace, 'cifuzz-corpus') + + @property + def pruned_corpora(self): + """The directory where pruned corpora are stored.""" + return os.path.join(self.workspace, 'cifuzz-pruned-corpus') + + @property + def sarif(self): + """The directory where sarif files are stored.""" + return os.path.join(self.workspace, 'cifuzz-sarif') + + def make_repo_for_sarif(self, repo_manager): + """Copies the repo over for the sarif upload GitHub action.""" + return shutil.copytree(repo_manager.repo_dir, self.sarif, symlinks=True) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/Makefile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..04db9976eac198bd430650da656998169912dc2f --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/README.md b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48e111d1abc6d96661659f9a19dd7fc6f969baad --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27e8795c55df12d3c17399eda52c738c1b914240 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030446345096fedc53fe7ea5826a36982a460c42 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..713d61d757c0c135271591bf17d9a1c108f37c27 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a0737f28b1ae8de07b002f03d56fdab471674723 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/target.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/target.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb1b1dd0c2488c39f2d6de94f861dd1a96775b3a --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d7ef1ceef23bcb5ab7bca9a1933f6742fb054b7 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc55eb7f4c3e9778b378c16355a5f0fafeefbaf6 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/vuln.dict b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/SystemSan/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..bf066ea4829f64c1138ed1021f857e2e4d8bd5fc --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddcb567a53961994b68f0f112cf5ccdf1f6061d5 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..39822c98ea26518efdc8cc770f983574827bddbf --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild b/local-test-commons-compress-delta-03/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild new file mode 100644 index 0000000000000000000000000000000000000000..ebb4451f18c6ffda192e2dc6d5cfd5701a3b02a1 --- /dev/null +++ b/local-test-commons-compress-delta-03/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-commons-compress-delta-03/fuzz-tooling/infra/tools/hold_back_images.py b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/hold_back_images.py new file mode 100644 index 0000000000000000000000000000000000000000..659eb5debc28f0bbfbfcd34d863c88571b89c9f5 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/tools/hold_back_images.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python +# 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 pinning builder images for projects that break on upgrades. Works +with projects that use language builders.""" +import argparse +import logging +import os +import re +import sys +import subprocess + +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) +PROJECTS_DIR = os.path.join(ROOT_DIR, 'projects') + +IMAGE_DIGEST_REGEX = re.compile(r'\[(.+)\]\n') +FROM_LINE_REGEX = re.compile( + r'FROM (ghcr.io\/aixcc-finals\/base-builder[\-a-z0-9]*)(\@?.*)') + + +def get_latest_docker_image_digest(image): + """Returns a pinnable version of the latest |image|. This version will have a + SHA.""" + subprocess.run(['docker', 'pull', image], check=True) + subprocess.run(['docker', 'pull', image], stdout=subprocess.PIPE, check=True) + + command = [ + 'docker', 'image', 'inspect', '--format', '{{.RepoDigests}}', image + ] + output = subprocess.run(command, check=True, + stdout=subprocess.PIPE).stdout.decode('utf-8') + return IMAGE_DIGEST_REGEX.match(output).groups(1)[0] + + +def get_args(): + """Returns parsed arguments.""" + parser = argparse.ArgumentParser(sys.argv[0], + description='Hold back builder images.') + parser.add_argument('projects', help='Projects.', nargs='+') + + parser.add_argument('--hold-image-digest', + required=False, + nargs='?', + default=None, + help='Image to hold on to.') + + parser.add_argument('--update-held', + action='store_true', + default=False, + help='Update held images.') + + parser.add_argument('--issue-number', + required=False, + nargs='?', + default=None, + help='Issue to reference.') + + args = parser.parse_args() + return args + + +def get_hold_image_digest(line, hold_image_digest, update_held): + """Returns the image digest for the |line| we want to pin. If the image is + already pinned then it is only updated if |update_held. If |hold_image_digest + is specified then it is returned, otherwise the latest pinnable version is + returned.""" + matches = FROM_LINE_REGEX.match(line).groups() + if matches[1] and not update_held: + return None, False + initial_image = matches[0] + if hold_image_digest: + return hold_image_digest, True + return get_latest_docker_image_digest(initial_image), True + + +def hold_image(project, hold_image_digest, update_held, issue_number): + """Rewrites the Dockerfile of |project| to pin the base-builder image on + upgrade.""" + dockerfile_path = os.path.join(PROJECTS_DIR, project, 'Dockerfile') + with open(dockerfile_path, 'r') as dockerfile_handle: + dockerfile = dockerfile_handle.readlines() + for idx, line in enumerate(dockerfile[:]): + if not line.startswith('FROM ghcr.io/aixcc-finals/base-builder'): + continue + + hold_image_digest, should_hold = get_hold_image_digest( + line.strip(), hold_image_digest, update_held) + if not should_hold: + logging.error('Not holding back %s.', project) + break + dockerfile[idx] = f'FROM {hold_image_digest}\n' + if issue_number: + comment = ('# Held back because of github.com/google/oss-fuzz/pull/' + f'{issue_number}\n# Please fix failure and upgrade.\n') + dockerfile.insert(idx, comment) + break + else: + # This path is taken when we don't break out of the loop. + assert None, f'Could not find FROM line in {project}' + dockerfile = ''.join(dockerfile) + with open(dockerfile_path, 'w') as dockerfile_handle: + dockerfile_handle.write(dockerfile) + + +def main(): + """Script for pinning builder images for projects that break on upgrades.""" + args = get_args() + for project in args.projects: + hold_image(project, args.hold_image_digest, args.update_held, + args.issue_number) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/infra/uploader/Dockerfile b/local-test-commons-compress-delta-03/fuzz-tooling/infra/uploader/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..814678833ec765fbb06bc21300b67ad5e6e1668f --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/infra/uploader/Dockerfile @@ -0,0 +1,7 @@ +from ubuntu:16.04 + +RUN apt-get update && apt-get upgrade -y +RUN apt-get install -y curl + +ENTRYPOINT ["curl", "--retry", "5", "-X", "PUT", "-T"] + diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c96ec6ccf66a65a0f5b8319c5d21e1800242bf8 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdBuildFuzzerFromWorkspaceCFLite.ts @@ -0,0 +1,49 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import {commandHistory} from '../commandUtils'; +import {setStatusText} from '../utils'; +import {buildFuzzersFromWorkspaceClusterfuzzLite} from '../ossfuzzWrappers'; + +export async function cmdInputCollectorBuildFuzzersFromWorkspaceCFLite() { + // Create an history object + const args = new Object({ + toClean: false, + }); + + const commandObject = new Object({ + commandType: 'oss-fuzz.WSBuildFuzzers', + Arguments: args, + dispatcherFunc: cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite, + }); + console.log('L1: ' + commandHistory.length); + commandHistory.push(commandObject); + + await cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite(args); + return true; +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +async function cmdDispatchbuildFuzzersFromWorkspaceClusterfuzzLite(_args: any) { + await setStatusText('[CFLite] Building fuzzers: starting'); + const res = await buildFuzzersFromWorkspaceClusterfuzzLite(); + if (res) { + await setStatusText('[CFLite] Building fuzzers: finished'); + } else { + await setStatusText('[CFLite] Building fuzzers: failed'); + } +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDispatcherGenerateClusterfuzzLite.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDispatcherGenerateClusterfuzzLite.ts new file mode 100644 index 0000000000000000000000000000000000000000..5005742a99ad8e838cba8c605a5fd6e300c0f75d --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDispatcherGenerateClusterfuzzLite.ts @@ -0,0 +1,38 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +/** + * Command for generating template fuzzers. This is a short-cut for rapid + * prototyping as well as an archive for inspiration. + */ +import * as vscode from 'vscode'; +import {setStatusText} from '../utils'; + +import {setupProjectInitialFiles} from '../projectIntegrationHelper'; + +export async function cmdDispatcherGenerateClusterfuzzLite( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _context: vscode.ExtensionContext +) { + await setStatusText('Creating OSS-Fuzz setup: starting'); + const res = await setupProjectInitialFiles(true); + if (res) { + await setStatusText('Creating OSS-Fuzz setup: finished'); + } else { + await setStatusText('Creating OSS-Fuzz setup: failed'); + } + return; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts new file mode 100644 index 0000000000000000000000000000000000000000..377aed4c40ccee7efd25c29edfbba8d0e351cfe4 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdDisplayCoverage.ts @@ -0,0 +1,71 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import * as vscode from 'vscode'; +import {loadCoverageIntoWorkspace} from '../coverageHelper'; +import {println} from '../logger'; +import {getApi, FileDownloader} from '@microsoft/vscode-file-downloader-api'; + +/* + * Displays code coverage from OSS-Fuzz. + * + * Downloads a code coverage report from the OSS-Fuzz online storage, and then overlays + * the relevant source files with the coverage information. + */ +export async function displayCodeCoverageFromOssFuzz( + context: vscode.ExtensionContext +) { + const projectName = await vscode.window.showInputBox({ + value: '', + placeHolder: "The project you'd like to get code coverage for.", + }); + if (!projectName) { + return; + } + println('Getting code coverage for ' + projectName); + + const fileDownloader: FileDownloader = await getApi(); + + const currentDate = new Date(); + const yesterday = new Date(currentDate); + yesterday.setDate(yesterday.getDate() - 1); + + const day = yesterday.getDate(); + const month = yesterday.getMonth(); + const year = yesterday.getFullYear(); + + try { + const codeCoverageFile: vscode.Uri = await fileDownloader.downloadFile( + vscode.Uri.parse( + 'https://storage.googleapis.com/oss-fuzz-coverage/' + + projectName + + '/textcov_reports/' + + year.toString() + + month.toString() + + day.toString() + + '/all_cov.json' + ), + 'all_cov.json', + context + ); + await loadCoverageIntoWorkspace(context, codeCoverageFile); + } catch (err) { + println( + 'Could not get the URL. Currently, this feature is only supported for Python projects' + ); + return; + } +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdEndToEndCoverage.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdEndToEndCoverage.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f747306232fad87e3cd7e895aa13e71ebc00463 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdEndToEndCoverage.ts @@ -0,0 +1,192 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import * as vscode from 'vscode'; +const fs = require('fs'); +import {println} from '../logger'; +import {commandHistory} from '../commandUtils'; +import {buildFuzzersFromWorkspace, runFuzzerHandler} from '../ossfuzzWrappers'; +import {listFuzzersForProject, systemSync, setStatusText} from '../utils'; +import { + compareLocalToRemoteCoverage, + loadCoverageIntoWorkspace, +} from '../coverageHelper'; +import {extensionConfig} from '../config'; + +/** + * Performs the activities: + * 1) Build a project using address sanitizer + * 2) Run each fuzzer of the project, saving corpus + * 3) Build project using coverage sanitizer + * 4) Collect coverage + * @param context + * @returns + */ +export async function runEndToEndAndGetCoverage( + context: vscode.ExtensionContext +) { + println('Getting code coverage'); + await setStatusText('end-to-end coverage: getting input'); + const ossFuzzProjectNameInput = await vscode.window.showInputBox({ + value: '', + placeHolder: 'The OSS-Fuzz project name', + }); + if (!ossFuzzProjectNameInput) { + println('Did not get a ossFuzzTargetProject'); + return; + } + const secondsToRunEachFuzzer = await vscode.window.showInputBox({ + value: '', + placeHolder: 'Seconds to run each fuzzer', + }); + if (!secondsToRunEachFuzzer) { + println('Did not get number of seconds to run each fuzzer'); + return; + } + + // Create an history object + const args = new Object({ + projectName: ossFuzzProjectNameInput.toString(), + secondsToRun: secondsToRunEachFuzzer.toString(), + vsContext: context, + }); + + const commandObject = new Object({ + commandType: 'oss-fuzz.cmdDispatchEndToEndRun', + Arguments: args, + dispatcherFunc: cmdDispatchEndToEndRun, + }); + console.log('L1: ' + commandHistory.length); + commandHistory.push(commandObject); + + await cmdDispatchEndToEndRun(args); + return; +} + +async function cmdDispatchEndToEndRun(args: any) { + await setStatusText('end-to-end coverage: starting'); + const res = await endToEndRun( + args.projectName, + args.secondsToRun, + args.vsContext + ); + if (res) { + await setStatusText('end-to-end coverage: finished succesfully'); + } else { + await setStatusText('end-to-end coverage: failed'); + } + return; +} + +async function endToEndRun( + ossFuzzProjectNameInput: string, + secondsToRunEachFuzzer: string, + context: vscode.ExtensionContext +) { + await setStatusText('end-to-end coverage: build with ASAN'); + vscode.window.showInformationMessage( + 'Building project: ' + ossFuzzProjectNameInput.toString() + ); + if ( + (await buildFuzzersFromWorkspace( + ossFuzzProjectNameInput.toString(), + '', + true + )) === false + ) { + println('Failed to build project'); + return false; + } + println('Build projects'); + + // List all of the fuzzers in the project + const fuzzersInProject = await listFuzzersForProject( + ossFuzzProjectNameInput, + extensionConfig.ossFuzzPepositoryWorkPath + ); + + // Run all of the fuzzers in the project + await setStatusText('end-to-end coverage: collecting corpus'); + println('Fuzzers found in project: ' + fuzzersInProject.toString()); + println('Running each of the fuzzers to collect a corpus'); + for (const fuzzName of fuzzersInProject) { + println('Running fuzzer: ' + fuzzName); + await setStatusText('end-to-end coverage: collecting corpus: ' + fuzzName); + // Corpus directory + const fuzzerCorpusPath = + extensionConfig.ossFuzzPepositoryWorkPath + + '/build/corpus/' + + ossFuzzProjectNameInput + + '/' + + fuzzName; + + await systemSync('mkdir', ['-p', fuzzerCorpusPath]); + + await runFuzzerHandler( + ossFuzzProjectNameInput, + fuzzName, + secondsToRunEachFuzzer.toString(), + fuzzerCorpusPath + ); + } + + // Build with code coverage + println('Building project with coverage sanitizer'); + await setStatusText('end-to-end coverage: building with coverage'); + await buildFuzzersFromWorkspace( + ossFuzzProjectNameInput.toString(), + 'coverage', + true + ); + + // Run coverage command + println('Collecting code coverage'); + await setStatusText('end-to-end coverage: collecting coverage'); + const args: Array = [ + extensionConfig.ossFuzzPepositoryWorkPath + '/infra/helper.py', + 'coverage', + '--port', + '', + '--no-corpus-download', + ossFuzzProjectNameInput.toString(), + ]; + await systemSync('python3', args); + await setStatusText('end-to-end coverage: finished collecting coverage'); + println('Load coverage report with the command:'); + println( + 'python3 -m http.server 8008 --directory /tmp/oss-fuzz/build/out/' + + ossFuzzProjectNameInput.toString() + + '/report/' + ); + + println('Trying to load code coverage in IDE'); + const allCovPath = + extensionConfig.ossFuzzPepositoryWorkPath + + '/build/out/' + + ossFuzzProjectNameInput.toString() + + '/textcov_reports/all_cov.json'; + if (fs.existsSync(allCovPath)) { + const generatedCodeCoverageFile = vscode.Uri.file(allCovPath); + await loadCoverageIntoWorkspace(context, generatedCodeCoverageFile); + } + + await compareLocalToRemoteCoverage( + context, + ossFuzzProjectNameInput.toString() + ); + + return true; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFI.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFI.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc2ecce80e2933e403c98e8f9ce4f7a2de5f5575 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFI.ts @@ -0,0 +1,24 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import {runFuzzIntrospector} from '../fuzzIntrospectorHelper'; + +/** + * Function for setting up Fuzz Introspector by way of a Python virtual env. + */ +export async function runFuzzIntrospectorHandler() { + runFuzzIntrospector(); +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFuzzer.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFuzzer.ts new file mode 100644 index 0000000000000000000000000000000000000000..5814f52c99275308032b8fc59f4879d88b67423c --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdRunFuzzer.ts @@ -0,0 +1,83 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import * as vscode from 'vscode'; +import {println} from '../logger'; +import {commandHistory} from '../commandUtils'; +import {runFuzzerHandler} from '../ossfuzzWrappers'; + +export async function cmdInputCollectorRunSpecificFuzzer() { + let projectNameArg = ''; + let fuzzerName = ''; + let secondsToRun = ''; + + // Runs a fuzzer from a given project. + const projectNameFromPrompt = await vscode.window.showInputBox({ + value: '', + placeHolder: 'Type a project name', + }); + if (!projectNameFromPrompt) { + println('Failed to get project name'); + return; + } + projectNameArg = projectNameFromPrompt.toString(); + const fuzzerNameFromPrompt = await vscode.window.showInputBox({ + value: '', + placeHolder: 'Type a fuzzer name', + }); + if (!fuzzerNameFromPrompt) { + println('Failed to get fuzzer name'); + return; + } + fuzzerName = fuzzerNameFromPrompt.toString(); + const secondsToRunInp = await vscode.window.showInputBox({ + value: '', + placeHolder: 'Type the number of seconds to run the fuzzer', + }); + if (!secondsToRunInp) { + return; + } + secondsToRun = secondsToRunInp.toString(); + + // Create an history object + const args = new Object({ + projectName: projectNameArg, + fuzzerName: fuzzerName, + secondsToRun: secondsToRun, + fuzzerCorpusPath: '', + }); + + const commandObject = new Object({ + commandType: 'oss-fuzz.RunFuzzer', + Arguments: args, + dispatcherFunc: cmdDispatchRunFuzzerHandler, + }); + console.log('L1: ' + commandHistory.length); + commandHistory.push(commandObject); + + await cmdDispatchRunFuzzerHandler(args); + return true; +} + +async function cmdDispatchRunFuzzerHandler(args: any) { + await runFuzzerHandler( + args.projectName, + args.fuzzerName, + args.secondsToRun, + args.fuzzerCorpusPath + ); + return; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts new file mode 100644 index 0000000000000000000000000000000000000000..0a15ed666737957e188aba70e9fdb679e59cc340 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetOSSFuzzPath.ts @@ -0,0 +1,59 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import * as vscode from 'vscode'; + +import {println} from '../logger'; +import {extensionConfig} from '../config'; + +// Set the oss-fuzz path. +export async function setOssFuzzPath() { + println('Setting path'); + const newOssFuzzPath = await vscode.window.showInputBox({ + value: '', + placeHolder: 'Type path', + }); + if (!newOssFuzzPath) { + println('Failed getting path'); + return; + } + + const fpathh = vscode.Uri.file(newOssFuzzPath); + let isValid = false; + try { + if (await vscode.workspace.fs.readDirectory(fpathh)) { + println('Is a directory'); + const helperPathURI = vscode.Uri.file( + newOssFuzzPath + '/infra/helper.py' + ); + if (await vscode.workspace.fs.readFile(helperPathURI)) { + println('Found helper file'); + isValid = true; + } + isValid = true; + } else { + isValid = false; + } + } catch { + isValid = false; + } + + if (isValid) { + extensionConfig.ossFuzzPepositoryWorkPath = newOssFuzzPath; + } else { + println('Not setting OSS-Fuzz path'); + } +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupCIFuzz.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupCIFuzz.ts new file mode 100644 index 0000000000000000000000000000000000000000..e11b97bb9a6099d0bac292e8f8a679463d0c242e --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupCIFuzz.ts @@ -0,0 +1,87 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import * as vscode from 'vscode'; +import {println} from '../logger'; +import {determineWorkspaceLanguage} from '../utils'; +import {cifuzzGenerator} from '../cifuzz'; + +export async function setupCIFuzzHandler() { + const workspaceFolder = vscode.workspace.workspaceFolders; + if (!workspaceFolder) { + return false; + } + + const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder + + /** + * Go through GitHub workflows to find potential traces of CIFuzz + */ + const githubWorkflowsPath = vscode.Uri.file(wsPath + '/.github/workflows'); + try { + await vscode.workspace.fs.readDirectory(githubWorkflowsPath); + } catch { + println('Did not find a workflows path.'); + return false; + } + + for (const [name, type] of await vscode.workspace.fs.readDirectory( + githubWorkflowsPath + )) { + // Skip directories. + if (type === 2) { + continue; + } + + // Read the files. + println('Is a file'); + const workflowFile = vscode.Uri.file(wsPath + '/.github/workflows/' + name); + const doc = await vscode.workspace.openTextDocument(workflowFile); + if (doc.getText().includes('cifuzz')) { + println('Found existing CIFuzz, will not continue.'); + return false; + } + } + + println('Did not find CIFuzz, creating one.'); + const projectName = await vscode.window.showInputBox({ + value: '', + placeHolder: 'OSS-Fuzz project name', + }); + if (!projectName) { + println('Failed to get project name'); + return false; + } + + /* + * There is no CIFuzz found, so we create one. + */ + // Determine the language of the workspace. + const targetLanguage = await determineWorkspaceLanguage(); + println('Target language: ' + targetLanguage); + + // Generate a CIFuzz workflow text. + const cifuzzWorkflowText = cifuzzGenerator(targetLanguage, projectName, 30); + + // Create the CIFuzz .yml file and write the contents to it to path + // .github/workflows/cifuzz.yml + const cifuzzYml = vscode.Uri.file(wsPath + '/.github/workflows/cifuzz.yml'); + const wsedit = new vscode.WorkspaceEdit(); + wsedit.createFile(cifuzzYml, {ignoreIfExists: true}); + wsedit.insert(cifuzzYml, new vscode.Position(0, 0), cifuzzWorkflowText); + vscode.workspace.applyEdit(wsedit); + return true; +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupFI.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupFI.ts new file mode 100644 index 0000000000000000000000000000000000000000..bae19f3739517e649c37782c23373763c279e408 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdSetupFI.ts @@ -0,0 +1,24 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +import {setUpFuzzIntrospector} from '../fuzzIntrospectorHelper'; + +/** + * Function for setting up Fuzz Introspector by way of a Python virtual env. + */ +export async function setUpFuzzIntrospectorHandler() { + setUpFuzzIntrospector(); +} diff --git a/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTemplate.ts b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTemplate.ts new file mode 100644 index 0000000000000000000000000000000000000000..964cc6788ba18faec29f4a475ad37b696b6ad375 --- /dev/null +++ b/local-test-commons-compress-delta-03/fuzz-tooling/tools/vscode-extension/src/commands/cmdTemplate.ts @@ -0,0 +1,357 @@ +// 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. +// +//////////////////////////////////////////////////////////////////////////////// + +/** + * Command for generating template fuzzers. This is a short-cut for rapid + * prototyping as well as an archive for inspiration. + */ +import * as vscode from 'vscode'; +import {println} from '../logger'; + +export const cLangSimpleStringFuzzer = `#include +#include +#include + +int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + char *new_str = (char *)malloc(size+1); + if (new_str == NULL){ + return 0; + } + memcpy(new_str, data, size); + new_str[size] = '\\0'; + + // Insert fuzzer contents here + // fuzz data in new_str + + // end of fuzzer contents + + free(new_str); + return 0; +}`; + +const cLangFileInputFuzzer = `int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + char filename[256]; + sprintf(filename, "/tmp/libfuzzer.%d", getpid()); + + // Create a file on the filesystem with fuzzer data in it + FILE *fp = fopen(filename, "wb"); + if (!fp) { + return 0; + } + fwrite(data, size, 1, fp); + fclose(fp); + + // Fuzzer logic here. Use the file as a source of data. + + // Fuzzer logic end + + // Clean up the file. + unlink(filename); + + return 0; +}`; + +const cLangBareTemplateFuzzer = `int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + return 0; +}`; + +const cppLangBareTemplateFuzzer = `extern "C" int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + return 0; +}`; + +const cppLangStdStringTemplateFuzzer = `extern "C" int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + std::string input(reinterpret_cast(data), size); + + return 0; +}`; + +export const cppLangFDPTemplateFuzzer = `#include + +#include + +extern "C" int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + FuzzedDataProvider fdp(data, size); + + // Extract higher level data types used for fuzzing, e.g. + // int ran_int = fdp.ConsumeIntegralInRange(1, 1024); + // std::string s = fdp.ConsumeRandomLengthString(); + + return 0; +}`; + +const cppLangFileInputFuzzer = `extern "C" int +LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) +{ + char filename[256]; + sprintf(filename, "/tmp/libfuzzer.%d", getpid()); + + FILE *fp = fopen(filename, "wb"); + if (!fp) { + return 0; + } + fwrite(data, size, 1, fp); + fclose(fp); + + // Fuzzer logic here + + // Fuzzer logic end + + unlink(filename); +}`; + +const pythonLangBareTemplate = `import sys +import atheris + + +def TestOneInput(fuzz_bytes): + return + + +def main(): + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + + +if __name__ == "__main__": + main()`; + +export const pythonLangFileInputFuzzer = `import sys +import atheris + +@atheris.instrument_func +def TestOneInput(data): + # Write fuzz data to a file + with open('/tmp/fuzz_input.b') as f: + f.write(data) + + # Use '/tmp/fuzz_input.b' as input to file handling logic. + + +def main(): + atheris.instrument_all() + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + + +if __name__ == "__main__": + main()`; + +const pythonLongFdpTemplate = `import sys +import atheris + +def TestOneInput(fuzz_bytes): + fdp = atheris.FuzzedDataProvider(fuzz_bytes) + return + +def main(): + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + +if __name__ == "__main__": + main()`; + +export const javaLangBareTemplate = `import com.code_intelligence.jazzer.api.FuzzedDataProvider; +public class SampleFuzzer { + public static void fuzzerTestOneInput(FuzzedDataProvider fdp) { + // Use fdp to create arbitrary types seeded with fuzz data + } +} +`; + +/** + * C templates + */ +async function cTemplates() { + let template = ''; + const result = await vscode.window.showQuickPick( + ['Bare template', 'Null-terminated string input', 'File input'], + { + placeHolder: 'Pick which template', + } + ); + vscode.window.showInformationMessage(`Got: ${result}`); + + if (result === 'Null-terminated string input') { + template = cLangSimpleStringFuzzer; + } else if (result === 'File input') { + template = cLangFileInputFuzzer; + } else if (result === 'Bare template') { + template = cLangBareTemplateFuzzer; + } else { + template = 'empty'; + } + const workspaceFolder = vscode.workspace.workspaceFolders; + if (!workspaceFolder) { + return; + } + + const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder + + const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.c'); + const wsedit = new vscode.WorkspaceEdit(); + wsedit.createFile(cifuzzYml, {ignoreIfExists: true}); + wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template); + vscode.workspace.applyEdit(wsedit); + return; +} + +/** + * CPP templates + */ +async function cppTemplates() { + let template = ''; + const result = await vscode.window.showQuickPick( + [ + 'Bare template', + 'Simple CPP string', + 'File input fuzzer', + 'Fuzzed data provider', + ], + { + placeHolder: 'Pick which template', + } + ); + vscode.window.showInformationMessage(`Got: ${result}`); + + if (result === 'Bare template') { + template = cppLangBareTemplateFuzzer; + } else if (result === 'Simple CPP string') { + template = cppLangStdStringTemplateFuzzer; + } else if (result === 'File input fuzzer') { + template = cppLangFileInputFuzzer; + } else if (result === 'Fuzzed data provider') { + template = cppLangFDPTemplateFuzzer; + } else { + template = 'empty'; + } + const workspaceFolder = vscode.workspace.workspaceFolders; + if (!workspaceFolder) { + return; + } + + const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder + + const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.cpp'); + const wsedit = new vscode.WorkspaceEdit(); + wsedit.createFile(cifuzzYml, {ignoreIfExists: true}); + wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template); + vscode.workspace.applyEdit(wsedit); + return; +} + +/** + * Python templates + */ +async function pythonTepmlates() { + let template = ''; + const result = await vscode.window.showQuickPick( + ['Bare template', 'Fuzzed Data Provider', 'File input fuzzer'], + { + placeHolder: 'Pick which template', + } + ); + vscode.window.showInformationMessage(`Got: ${result}`); + + if (result === 'Fuzzed Data Provider') { + template = pythonLongFdpTemplate; + } else if (result === 'Bare template') { + template = pythonLangBareTemplate; + } else if (result === 'File input fuzzer') { + template = pythonLangFileInputFuzzer; + } else { + template = 'empty'; + } + const workspaceFolder = vscode.workspace.workspaceFolders; + if (!workspaceFolder) { + return; + } + + const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder + + const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.py'); + const wsedit = new vscode.WorkspaceEdit(); + wsedit.createFile(cifuzzYml, {ignoreIfExists: true}); + wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template); + vscode.workspace.applyEdit(wsedit); + return; +} + +/** + * Java templates + */ +async function javaTemplates() { + let template = ''; + const result = await vscode.window.showQuickPick(['Bare template'], { + placeHolder: 'Pick which template', + }); + vscode.window.showInformationMessage(`Got: ${result}`); + + if (result === 'Bare template') { + template = javaLangBareTemplate; + } else { + template = 'empty'; + } + const workspaceFolder = vscode.workspace.workspaceFolders; + if (!workspaceFolder) { + return; + } + + const wsPath = workspaceFolder[0].uri.fsPath; // gets the path of the first workspace folder + + const cifuzzYml = vscode.Uri.file(wsPath + '/oss-fuzz-template.java'); + const wsedit = new vscode.WorkspaceEdit(); + wsedit.createFile(cifuzzYml, {ignoreIfExists: true}); + wsedit.insert(cifuzzYml, new vscode.Position(0, 0), template); + vscode.workspace.applyEdit(wsedit); + return; +} + +export async function cmdDispatcherTemplate(context: vscode.ExtensionContext) { + println('Creating template'); + const options: { + [key: string]: (context: vscode.ExtensionContext) => Promise; + } = { + C: cTemplates, + CPP: cppTemplates, + Python: pythonTepmlates, + Java: javaTemplates, + }; + + const quickPick = vscode.window.createQuickPick(); + quickPick.items = Object.keys(options).map(label => ({label})); + quickPick.onDidChangeSelection(selection => { + if (selection[0]) { + options[selection[0].label](context).catch(console.error); + } + }); + quickPick.onDidHide(() => quickPick.dispose()); + quickPick.placeholder = 'Pick language'; + quickPick.show(); + + return; +}