diff --git a/.gitattributes b/.gitattributes index 1b8a28fb7c07c4e0e7e17a2920412369f8aa93c4..b0432f403d9a9ae4f43178a87ae1a3c4dd6d46b7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -274,3 +274,16 @@ local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parser local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_AdobeIllustrator.pdf filter=lfs diff=lfs merge=lfs -text local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_XFA_govdocs1_258578.pdf filter=lfs diff=lfs merge=lfs -text local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_deeplyEmbeddedAttachments.pdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_bad_page_303226.pdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_childAttachments.pdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDFFileEmbInAnnotation_noContents.pdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testJournalParser.pdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-parser-nlp-module/src/test/resources/test-documents/testJournalParser.pdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.hdf filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.he5 filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/GLDAS_CLM10SUBP_3H.A19790202.0000.001.grb filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/egyl03.gdas.200811.00Z.grb2 filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/sresa1b_ncar_ccsm3_0_run1_200001.nc filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/gdas1.forecmwf.2014062612.grib2 filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/test-columnar.sas7bdat filter=lfs diff=lfs merge=lfs -text +local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/testLinux-ppc-32be filter=lfs diff=lfs merge=lfs -text diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/base-images/aixcc_build_all.sh b/local-test-tika-delta-01/fuzz-tooling/infra/base-images/aixcc_build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed8eee86385559020055682e668aee685f68ad12 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3197ebbf1ae89dd327a2d4ea191f082360165389 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/base_runner_utils.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/base_runner_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d04a54adb18a2bcf7faf5402a93d5b078367d2e9 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..fd15642e8d88c44f3ea82ba64108a8994d160ef0 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers.py @@ -0,0 +1,217 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module used by CI tools in order to interact with fuzzers. This module helps +CI tools to build fuzzers.""" + +import logging +import os +import sys + +import affected_fuzz_targets +import base_runner_utils +import clusterfuzz_deployment +import continuous_integration +import docker +import logs +import workspace_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import helper +import utils + +logs.init() + + +def check_project_src_path(project_src_path): + """Returns True if |project_src_path| exists.""" + if not os.path.exists(project_src_path): + logging.error( + 'PROJECT_SRC_PATH: %s does not exist. ' + 'Are you mounting it correctly?', project_src_path) + return False + return True + + +# pylint: disable=too-many-arguments + + +class Builder: # pylint: disable=too-many-instance-attributes + """Class for fuzzer builders.""" + + def __init__(self, config, ci_system): + self.config = config + self.ci_system = ci_system + self.workspace = workspace_utils.Workspace(config) + self.workspace.initialize_dir(self.workspace.out) + self.workspace.initialize_dir(self.workspace.work) + self.clusterfuzz_deployment = ( + clusterfuzz_deployment.get_clusterfuzz_deployment( + self.config, self.workspace)) + self.image_repo_path = None + self.host_repo_path = None + self.repo_manager = None + + def build_image_and_checkout_src(self): + """Builds the project builder image and checkout source code for the patch + we want to fuzz (if necessary). Returns True on success.""" + result = self.ci_system.prepare_for_fuzzer_build() + if not result.success: + return False + self.image_repo_path = result.image_repo_path + self.repo_manager = result.repo_manager + if self.config.output_sarif: + self.workspace.make_repo_for_sarif(self.repo_manager) + logging.info('repo_dir: %s.', self.repo_manager.repo_dir) + self.host_repo_path = self.repo_manager.repo_dir + return True + + def build_fuzzers(self): + """Moves the source code we want to fuzz into the project builder and builds + the fuzzers from that source code. Returns True on success.""" + docker_args, docker_container = docker.get_base_docker_run_args( + self.workspace, self.config.sanitizer, self.config.language, + self.config.architecture, self.config.docker_in_docker) + if not docker_container: + docker_args.extend( + _get_docker_build_fuzzers_args_not_container(self.host_repo_path)) + + build_command = self.ci_system.get_build_command(self.host_repo_path, + self.image_repo_path) + + # Set extra environment variables so that they are visible to the build. + for key in self.config.extra_environment_variables: + # Don't specify their value in case they get echoed. + docker_args.extend(['-e', key]) + + docker_args.extend([ + docker.get_project_image_name(self.config.oss_fuzz_project_name), + '/bin/bash', + '-c', + build_command, + ]) + logging.info('Building with %s sanitizer.', self.config.sanitizer) + + # TODO(metzman): Stop using helper.docker_run so we can get rid of + # docker.get_base_docker_run_args and merge its contents into + # docker.get_base_docker_run_command. + if not helper.docker_run(docker_args): + logging.error('Building fuzzers failed.') + return False + + return True + + def upload_build(self): + """Upload build.""" + if self.config.upload_build: + self.clusterfuzz_deployment.upload_build( + self.repo_manager.get_current_commit()) + + return True + + def check_fuzzer_build(self): + """Checks the fuzzer build. Returns True on success or if config specifies + to skip check.""" + if not self.config.bad_build_check: + return True + + return check_fuzzer_build(self.config) + + def build(self): + """Builds the image, checkouts the source (if needed), builds the fuzzers + and then removes the unaffectted fuzzers. Returns True on success.""" + methods = [ + self.build_image_and_checkout_src, + self.build_fuzzers, + self.remove_unaffected_fuzz_targets, + self.upload_build, + self.check_fuzzer_build, + ] + for method in methods: + if not method(): + return False + return True + + def remove_unaffected_fuzz_targets(self): + """Removes the fuzzers unaffected by the patch.""" + if self.config.keep_unaffected_fuzz_targets: + logging.info('Not removing unaffected fuzz targets.') + return True + + logging.info('Removing unaffected fuzz targets.') + changed_files = self.ci_system.get_changed_code_under_test( + self.repo_manager) + affected_fuzz_targets.remove_unaffected_fuzz_targets( + self.clusterfuzz_deployment, self.workspace.out, changed_files, + self.image_repo_path) + return True + + +def build_fuzzers(config): + """Builds all of the fuzzers for a specific OSS-Fuzz project. + + Args: + config: The configuration object for building fuzzers. + + Returns: + True if build succeeded. + """ + # Do some quick validation. + if config.project_src_path and not check_project_src_path( + config.project_src_path): + return False + + # Get the builder and then build the fuzzers. + ci_system = continuous_integration.get_ci(config) + logging.info('ci_system: %s.', ci_system) + builder = Builder(config, ci_system) + return builder.build() + + +def check_fuzzer_build(config): + """Checks the integrity of the built fuzzers. + + Args: + config: The config object. + + Returns: + True if fuzzers pass OSS-Fuzz's build check. + """ + workspace = workspace_utils.Workspace(config) + if not os.path.exists(workspace.out): + logging.error('Invalid out directory: %s.', workspace.out) + return False + if not os.listdir(workspace.out): + logging.error('No fuzzers found in out directory: %s.', workspace.out) + return False + + env = base_runner_utils.get_env(config, workspace) + if config.allowed_broken_targets_percentage is not None: + env['ALLOWED_BROKEN_TARGETS_PERCENTAGE'] = ( + config.allowed_broken_targets_percentage) + + stdout, stderr, retcode = utils.execute('test_all.py', env=env) + print(f'Build check: stdout: {stdout}\nstderr: {stderr}') + if retcode == 0: + logging.info('Build check passed.') + return True + logging.error('Build check failed.') + return False + + +def _get_docker_build_fuzzers_args_not_container(host_repo_path): + """Returns arguments to the docker build arguments that are needed to use + |host_repo_path| when the host of the OSS-Fuzz builder container is not + another container.""" + return ['-v', f'{host_repo_path}:{host_repo_path}'] diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..2a5bec6b5573cc7720f5031bc7d50de944320f81 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/build_fuzzers_test.py new file mode 100644 index 0000000000000000000000000000000000000000..36a4d4b2287401b29bf3f8b31c203296142b7179 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f3ada4f2762c6e6ddf058b6be9a67b31c154594 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz-base/Dockerfile @@ -0,0 +1,44 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +FROM ghcr.io/aixcc-finals/base-runner + +RUN apt-get update && \ + apt-get install -y systemd && \ + wget https://download.docker.com/linux/ubuntu/dists/focal/pool/stable/amd64/docker-ce-cli_20.10.8~3-0~ubuntu-focal_amd64.deb -O /tmp/docker-ce.deb && \ + dpkg -i /tmp/docker-ce.deb && \ + rm /tmp/docker-ce.deb + +ENV PATH=/opt/gcloud/google-cloud-sdk/bin/:$PATH +ENV OSS_FUZZ_ROOT=/opt/oss-fuzz + +# Do this step before copying to make rebuilding faster when developing. +COPY ./infra/cifuzz/requirements.txt /tmp/requirements.txt +RUN python3 -m pip install -r /tmp/requirements.txt && rm /tmp/requirements.txt + +ADD . ${OSS_FUZZ_ROOT} +# Don't use the default npm location since jazzer.js can break us. +# This means javascript needed by cifuzz/clusterfuzzlite must be executed in +# OSS_FUZZ_ROOT. +RUN cd ${OSS_FUZZ_ROOT} && npm install ${OSS_FUZZ_ROOT}/infra/cifuzz + + +ENV PYTHONUNBUFFERED=1 + +# Python file to execute when the docker container starts up. +# We can't use the env var $OSS_FUZZ_ROOT here. Since it's a constant env var, +# just expand to '/opt/oss-fuzz'. +ENTRYPOINT ["python3", "/opt/oss-fuzz/infra/cifuzz/cifuzz_combined_entrypoint.py"] diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_combined_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..920e32e42965c314c7fcc5c7808315bb68e051a0 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py new file mode 100644 index 0000000000000000000000000000000000000000..30e28beda330c621ac3a0f5b9d1ee2dc11a5e463 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py @@ -0,0 +1,48 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""End-to-End tests for CIFuzz.""" +import os +import unittest + +import run_cifuzz +import test_helpers + +CIFUZZ_DIR = os.path.dirname(os.path.abspath(__file__)) +EXTERNAL_PROJECT_PATH = os.path.join(CIFUZZ_DIR, 'test_data', + 'external-project') + + +# This test will fail if not run as root because the fuzzer build process +# creates binaries that only root can write to. +# Use a seperate env var to keep this seperate from integration tests which +# don't have this annoying property. +@unittest.skipIf(not os.getenv('END_TO_END_TESTS'), + 'END_TO_END_TESTS=1 not set') +class EndToEndTest(unittest.TestCase): + """End-to-End tests for CIFuzz.""" + + def setUp(self): + test_helpers.patch_environ(self, runner=True) + + def test_simple(self): + """Simple end-to-end test using run_cifuzz.main().""" + os.environ['REPOSITORY'] = 'external-project' + os.environ['PROJECT_SRC_PATH'] = EXTERNAL_PROJECT_PATH + os.environ['FILESTORE'] = 'no_filestore' + os.environ['NO_CLUSTERFUZZ_DEPLOYMENT'] = 'True' + + with test_helpers.docker_temp_dir() as temp_dir: + os.environ['WORKSPACE'] = temp_dir + # TODO(metzman): Verify the crash, affected fuzzers, and other things. + self.assertEqual(run_cifuzz.main(), 1) diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cloudbuild.yaml b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..03b1961e50ff9c701133753e918179177323726e --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..b36fc78dec9ab35b045aa6b42b790e1904a98e67 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/clusterfuzz_deployment_test.py new file mode 100644 index 0000000000000000000000000000000000000000..31c7b03ecb82dbaed32681ba8a94c61044a67e28 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/config_utils.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a3cb8f7ad9265f3eaaac9af4a810d412e3fc00 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/config_utils_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/config_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..cb82dee44026532eb0b0127a6bb565e25e965f1e --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/continuous_integration.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/continuous_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..f3e93b7aae7b3df012c9d77fa15f0f79d9fc6915 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/docker.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/docker.py new file mode 100644 index 0000000000000000000000000000000000000000..36e4d7c572cccc0faa3638439193af5973f0e65e --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/docker_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/docker_test.py new file mode 100644 index 0000000000000000000000000000000000000000..045131c10c5b94ed7739769890a243c2776dc999 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/environment.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..e99a67910948bcd4ef49e6f7684a976f49f68827 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/example_cifuzz.yml b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/example_cifuzz.yml new file mode 100644 index 0000000000000000000000000000000000000000..e19f2c7cd2397a1e49c453ade22a7a87e14c91e0 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..acb0189693eb876f8e38efe75a69fbde86a03b56 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e1307376548252e0633cb2c2343feee2c0f745 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/filestore_utils_test.py @@ -0,0 +1,50 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for filestore_utils.""" +import unittest +from unittest import mock + +import parameterized + +import platform_config +import filestore +from filestore import github_actions +import filestore_utils +import test_helpers + + +class GetFilestoreTest(unittest.TestCase): + """Tests for get_filestore.""" + + @parameterized.parameterized.expand([ + ({ + 'cfl_platform': 'github', + }, github_actions.GithubActionsFilestore), + ]) + def test_get_filestore(self, config_kwargs, filestore_cls): + """Tests that get_filestore returns the right filestore given a certain + platform.""" + run_config = test_helpers.create_run_config(**config_kwargs) + filestore_impl = filestore_utils.get_filestore(run_config) + self.assertIsInstance(filestore_impl, filestore_cls) + + @mock.patch('config_utils.BaseConfig.platform', return_value='other') + @mock.patch('config_utils._get_platform_config', + return_value=platform_config.BasePlatformConfig()) + def test_get_filestore_unsupported_platform(self, _, __): + """Tests that get_filestore exceptions given a platform it doesn't + support.""" + run_config = test_helpers.create_run_config() + with self.assertRaises(filestore.FilestoreError): + filestore_utils.get_filestore(run_config) diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/fuzz_target_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/fuzz_target_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e553a25aecacfebc1a15e920fc54f19388d396d6 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/fuzz_target_test.py @@ -0,0 +1,298 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests the functionality of the fuzz_target module.""" + +import os +import shutil +import tempfile +import unittest +from unittest import mock + +import certifi +# Importing this later causes import failures with pytest for some reason. +# TODO(ochang): Figure out why. +import parameterized +import google.cloud.ndb # pylint: disable=unused-import +from pyfakefs import fake_filesystem_unittest +from clusterfuzz.fuzz import engine + +import clusterfuzz_deployment +import fuzz_target +import test_helpers +import workspace_utils + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +# An example fuzzer that triggers an error. +EXAMPLE_FUZZER = 'example_crash_fuzzer' + +# Mock return values for engine_impl.reproduce. +EXECUTE_SUCCESS_RESULT = engine.ReproduceResult([], 0, 0, '') +EXECUTE_FAILURE_RESULT = engine.ReproduceResult([], 1, 0, '') + +TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'test_data') + + +def _create_config(**kwargs): + """Creates a config object and then sets every attribute that is a key in + |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an + attribute of Config.""" + defaults = { + 'cfl_platform': 'github', + 'oss_fuzz_project_name': EXAMPLE_PROJECT, + 'workspace': '/workspace' + } + for default_key, default_value in defaults.items(): + if default_key not in kwargs: + kwargs[default_key] = default_value + + return test_helpers.create_run_config(**kwargs) + + +def _create_deployment(**kwargs): + config = _create_config(**kwargs) + workspace = workspace_utils.Workspace(config) + return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace) + + +@mock.patch('utils.get_container_name', return_value='container') +class IsReproducibleTest(fake_filesystem_unittest.TestCase): + """Tests the is_reproducible method in the fuzz_target.FuzzTarget class.""" + + def setUp(self): + """Sets up example fuzz target to test is_reproducible method.""" + self.fuzz_target_name = 'fuzz-target' + deployment = _create_deployment() + self.config = deployment.config + self.workspace = deployment.workspace + self.fuzz_target_path = os.path.join(self.workspace.out, + self.fuzz_target_name) + self.setUpPyfakefs() + self.fs.create_file(self.fuzz_target_path) + self.testcase_path = '/testcase' + self.fs.create_file(self.testcase_path) + + self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, + fuzz_target.REPRODUCE_ATTEMPTS, + self.workspace, deployment, + deployment.config) + + # ClusterFuzz requires ROOT_DIR. + root_dir = os.environ['ROOT_DIR'] + test_helpers.patch_environ(self, empty=True) + os.environ['ROOT_DIR'] = root_dir + + # There's an extremely bad issue that happens if this test is run: Other tests + # in this file fail in CI with stacktraces using referencing fakefs even if + # the tests do not use fakefs. + # TODO(metzman): Stop using fakefs. + @mock.patch('os.chmod') + @unittest.skip('Skip because of weird failures.') + def test_repro_timed_out(self, mock_chmod, mock_get_container_name): + """Tests that is_reproducible behaves correctly when reproduction times + out.""" + del mock_get_container_name + del mock_chmod + + with mock.patch( + 'clusterfuzz._internal.bot.fuzzers.libFuzzer.engine.LibFuzzerEngine.' + 'reproduce', + side_effect=TimeoutError): + self.assertFalse( + self.target.is_reproducible('/testcase', self.target.target_path, [])) + + def test_reproducible(self, _): + """Tests that is_reproducible returns True if crash is detected and that + is_reproducible uses the correct command to reproduce a crash.""" + all_repro = [EXECUTE_FAILURE_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = all_repro + + result = self.target.is_reproducible(self.testcase_path, + self.fuzz_target_path, []) + mock_get_engine().reproduce.assert_called_once_with( + '/workspace/build-out/fuzz-target', + '/testcase', + arguments=[], + max_time=30) + self.assertTrue(result) + self.assertEqual(1, mock_get_engine().reproduce.call_count) + + def test_flaky(self, _): + """Tests that is_reproducible returns True if crash is detected on the last + attempt.""" + last_time_repro = [EXECUTE_SUCCESS_RESULT] * 9 + [EXECUTE_FAILURE_RESULT] + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = last_time_repro + self.assertTrue( + self.target.is_reproducible(self.testcase_path, self.fuzz_target_path, + [])) + self.assertEqual(fuzz_target.REPRODUCE_ATTEMPTS, + mock_get_engine().reproduce.call_count) + + def test_nonexistent_fuzzer(self, _): + """Tests that is_reproducible raises an error if it could not attempt + reproduction because the fuzzer doesn't exist.""" + with self.assertRaises(fuzz_target.ReproduceError): + self.target.is_reproducible(self.testcase_path, '/non-existent-path', []) + + def test_unreproducible(self, _): + """Tests that is_reproducible returns False for a crash that did not + reproduce.""" + all_unrepro = [EXECUTE_SUCCESS_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = all_unrepro + result = self.target.is_reproducible(self.testcase_path, + self.fuzz_target_path, []) + self.assertFalse(result) + + +class IsCrashReportableTest(fake_filesystem_unittest.TestCase): + """Tests the is_crash_reportable method of FuzzTarget.""" + + def setUp(self): + """Sets up example fuzz target to test is_crash_reportable method.""" + self.setUpPyfakefs() + self.fuzz_target_path = '/example/do_stuff_fuzzer' + deployment = _create_deployment() + self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, 100, + deployment.workspace, deployment, + deployment.config) + self.oss_fuzz_build_path = '/oss-fuzz-build' + self.fs.create_file(self.fuzz_target_path) + self.oss_fuzz_target_path = os.path.join( + self.oss_fuzz_build_path, os.path.basename(self.fuzz_target_path)) + self.fs.create_file(self.oss_fuzz_target_path) + self.testcase_path = '/testcase' + self.fs.create_file(self.testcase_path, contents='') + + # Do this to prevent pyfakefs from messing with requests. + self.fs.add_real_directory(os.path.dirname(certifi.__file__)) + + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=[True, False]) + @mock.patch('logging.info') + def test_new_reproducible_crash(self, mock_info, _): + """Tests that a new reproducible crash returns True.""" + with tempfile.TemporaryDirectory() as tmp_dir: + self.target.out_dir = tmp_dir + self.assertTrue(self.target.is_crash_reportable(self.testcase_path, [])) + mock_info.assert_called_with( + 'The crash is not reproducible on previous build. ' + 'Code change (pr/commit) introduced crash.') + + # yapf: disable + @parameterized.parameterized.expand([ + # Reproducible on PR build, but also reproducible on OSS-Fuzz. + ([True, True],), + + # Not reproducible on PR build, but somehow reproducible on OSS-Fuzz. + # Unlikely to happen in real world except if test is flaky. + ([False, True],), + + # Not reproducible on PR build, and not reproducible on OSS-Fuzz. + ([False, False],), + ]) + # yapf: enable + def test_invalid_crash(self, is_reproducible_retvals): + """Tests that a nonreportable crash causes the method to return False.""" + with mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=is_reproducible_retvals): + with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build', + return_value=self.oss_fuzz_build_path): + self.assertFalse(self.target.is_crash_reportable( + self.testcase_path, [])) + + @mock.patch('logging.info') + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', return_value=[True]) + def test_reproducible_no_oss_fuzz_target(self, _, mock_info): + """Tests that is_crash_reportable returns True when a crash reproduces on + the PR build but the target is not in the OSS-Fuzz build (usually because it + is new).""" + os.remove(self.oss_fuzz_target_path) + + def is_reproducible_side_effect(testcase, target_path, reproduce_arguments): + del testcase + del reproduce_arguments + if os.path.dirname(target_path) == self.oss_fuzz_build_path: + raise fuzz_target.ReproduceError() + return True + + with mock.patch( + 'fuzz_target.FuzzTarget.is_reproducible', + side_effect=is_reproducible_side_effect) as mock_is_reproducible: + with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build', + return_value=self.oss_fuzz_build_path): + self.assertTrue(self.target.is_crash_reportable(self.testcase_path, [])) + mock_is_reproducible.assert_any_call(self.testcase_path, + self.oss_fuzz_target_path, []) + mock_info.assert_called_with( + 'Could not run previous build of target to determine if this code ' + 'change (pr/commit) introduced crash. Assuming crash was newly ' + 'introduced.') + + +class FuzzTest(fake_filesystem_unittest.TestCase): + """Fuzz test.""" + + def setUp(self): + """Sets up example fuzz target.""" + self.setUpPyfakefs() + deployment = _create_deployment() + config = deployment.config + workspace = deployment.workspace + self.fuzz_target = fuzz_target.FuzzTarget('/path/fuzz-target', 10, + workspace, deployment, config) + + def test_get_fuzz_target_artifact(self): + """Tests that get_fuzz_target_artifact works as intended.""" + # pylint: disable=protected-access + fuzz_target_artifact = self.fuzz_target._target_artifact_path() + self.assertEqual('/workspace/out/artifacts/fuzz-target/address', + fuzz_target_artifact) + + +class TimeoutIntegrationTest(unittest.TestCase): + """Tests handling of fuzzer timeout (timeout crashes reported by + libFuzzer).""" + TIMEOUT_FUZZER_NAME = 'timeout_fuzzer' + + @parameterized.parameterized.expand([(True, True), (False, False)]) + def test_timeout_reported(self, report_timeouts, expect_crash): + """Tests that timeouts are not reported.""" + with test_helpers.temp_dir_copy(TEST_DATA_PATH) as temp_dir: + fuzz_target_path = os.path.join(temp_dir, 'build-out', + self.TIMEOUT_FUZZER_NAME) + shutil.copy(os.path.join(temp_dir, self.TIMEOUT_FUZZER_NAME), + fuzz_target_path) + deployment = _create_deployment(workspace=temp_dir, + report_timeouts=report_timeouts) + config = deployment.config + fuzz_target_obj = fuzz_target.FuzzTarget(fuzz_target_path, + fuzz_target.REPRODUCE_ATTEMPTS, + deployment.workspace, deployment, + config) + with mock.patch('clusterfuzz._internal.bot.fuzzers.libfuzzer.' + 'fix_timeout_argument_for_reproduction') as _: + with mock.patch( + 'clusterfuzz._internal.bot.fuzzers.libFuzzer.fuzzer.get_arguments', + return_value=['-timeout=1', '-rss_limit_mb=2560']): + fuzz_result = fuzz_target_obj.fuzz() + self.assertEqual(bool(fuzz_result.testcase), expect_crash) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report.py new file mode 100644 index 0000000000000000000000000000000000000000..9901c452a0fe536670e5ec6da68b73a902d985e5 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report.py @@ -0,0 +1,48 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for generating coverage reports.""" +import os + +import base_runner_utils +import fuzz_target +import utils + + +def run_coverage_command(config, workspace): + """Runs the coverage command in base-runner to generate a coverage report.""" + env = base_runner_utils.get_env(config, workspace) + env['HTTP_PORT'] = '' + env['COVERAGE_EXTRA_ARGS'] = '' + env['CORPUS_DIR'] = workspace.corpora + env['COVERAGE_OUTPUT_DIR'] = workspace.coverage_report + command = 'coverage' + return utils.execute(command, env=env) + + +def download_corpora(fuzz_target_paths, clusterfuzz_deployment): + """Downloads corpora for fuzz targets in |fuzz_target_paths| using + |clusterfuzz_deployment| to download corpora from ClusterFuzz/OSS-Fuzz.""" + for target_path in fuzz_target_paths: + target_name = os.path.basename(target_path) + corpus_dir = fuzz_target.get_fuzz_target_corpus_dir( + clusterfuzz_deployment.workspace, target_name) + clusterfuzz_deployment.download_corpus(target_name, corpus_dir) + + +def generate_coverage_report(fuzz_target_paths, workspace, + clusterfuzz_deployment, config): + """Generates a coverage report using Clang's source based coverage.""" + download_corpora(fuzz_target_paths, clusterfuzz_deployment) + run_coverage_command(config, workspace) + clusterfuzz_deployment.upload_coverage() diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py new file mode 100644 index 0000000000000000000000000000000000000000..df2c9b206b84cdc92b5304f2669ea4cadcc71cae --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/get_coverage.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/get_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..762de7928cb93f074b73b51a37514e3807104d37 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/get_coverage_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/get_coverage_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3551f22adf5c0f77a2627c986de033bc71a8febb --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/get_coverage_test.py @@ -0,0 +1,253 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for get_coverage.py""" +import os +import json +import unittest +from unittest import mock + +import parameterized +from pyfakefs import fake_filesystem_unittest +import pytest + +import get_coverage + +# pylint: disable=protected-access + +TEST_DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'test_data') + +PROJECT_NAME = 'curl' +REPO_PATH = '/src/curl' +FUZZ_TARGET = 'curl_fuzzer' +PROJECT_COV_JSON_FILENAME = 'example_curl_cov.json' +FUZZ_TARGET_COV_JSON_FILENAME = 'example_curl_fuzzer_cov.json' +INVALID_TARGET = 'not-a-fuzz-target' + +with open(os.path.join(TEST_DATA_PATH, + PROJECT_COV_JSON_FILENAME),) as cov_file_handle: + PROJECT_COV_INFO = json.loads(cov_file_handle.read()) + + +class GetOssFuzzFuzzerStatsDirUrlTest(unittest.TestCase): + """Tests _get_oss_fuzz_fuzzer_stats_dir_url.""" + + @mock.patch('http_utils.get_json_from_url', + return_value={ + 'fuzzer_stats_dir': + 'gs://oss-fuzz-coverage/systemd/fuzzer_stats/20210303' + }) + def test_get_valid_project(self, mock_get_json_from_url): + """Tests that a project's coverage report can be downloaded and parsed. + + NOTE: This test relies on the PROJECT_NAME repo's coverage report. + The "example" project was not used because it has no coverage reports. + """ + result = get_coverage._get_oss_fuzz_fuzzer_stats_dir_url(PROJECT_NAME) + (url,), _ = mock_get_json_from_url.call_args + self.assertEqual( + 'https://storage.googleapis.com/oss-fuzz-coverage/' + 'latest_report_info/curl.json', url) + + expected_result = ( + 'https://storage.googleapis.com/oss-fuzz-coverage/systemd/fuzzer_stats/' + '20210303') + self.assertEqual(result, expected_result) + + def test_get_invalid_project(self): + """Tests that passing a bad project returns None.""" + self.assertIsNone( + get_coverage._get_oss_fuzz_fuzzer_stats_dir_url('not-a-proj')) + + +class OSSFuzzCoverageGetTargetCoverageTest(unittest.TestCase): + """Tests OSSFuzzCoverage.get_target_coverage.""" + + def setUp(self): + with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info', + return_value=PROJECT_COV_INFO): + self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage( + REPO_PATH, PROJECT_NAME) + + @mock.patch('http_utils.get_json_from_url', return_value={}) + def test_valid_target(self, mock_get_json_from_url): + """Tests that a target's coverage report can be downloaded and parsed.""" + self.oss_fuzz_coverage.get_target_coverage(FUZZ_TARGET) + (url,), _ = mock_get_json_from_url.call_args + self.assertEqual( + 'https://storage.googleapis.com/oss-fuzz-coverage/' + 'curl/fuzzer_stats/20200226/curl_fuzzer.json', url) + + def test_invalid_target(self): + """Tests that passing an invalid target coverage report returns None.""" + self.assertIsNone( + self.oss_fuzz_coverage.get_target_coverage(INVALID_TARGET)) + + @mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info', + return_value=None) + def test_invalid_project_json(self, _): # pylint: disable=no-self-use + """Tests an invalid project JSON results in None being returned.""" + with pytest.raises(get_coverage.CoverageError): + get_coverage.OSSFuzzCoverage(REPO_PATH, PROJECT_NAME) + + +def _get_expected_curl_covered_file_list(): + """Returns the expected covered file list for + FUZZ_TARGET_COV_JSON_FILENAME.""" + curl_files_list_path = os.path.join(TEST_DATA_PATH, + 'example_curl_file_list.json') + with open(curl_files_list_path) as file_handle: + return json.loads(file_handle.read()) + + +def _get_example_curl_coverage(): + """Returns the contents of the fuzzer stats JSON file for + FUZZ_TARGET_COV_JSON_FILENAME.""" + with open(os.path.join(TEST_DATA_PATH, + FUZZ_TARGET_COV_JSON_FILENAME)) as file_handle: + return json.loads(file_handle.read()) + + +class OSSFuzzCoverageGetFilesCoveredByTargetTest(unittest.TestCase): + """Tests OSSFuzzCoverage.get_files_covered_by_target.""" + + def setUp(self): + with mock.patch('get_coverage._get_oss_fuzz_latest_cov_report_info', + return_value=PROJECT_COV_INFO): + self.oss_fuzz_coverage = get_coverage.OSSFuzzCoverage( + REPO_PATH, PROJECT_NAME) + + @parameterized.parameterized.expand([({ + 'data': [] + },), ({ + 'data': [[]] + },), ({ + 'data': [{}] + },)]) + def test_malformed_cov_data(self, coverage_data): + """Tests that covered files can be retrieved from a coverage report.""" + with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage', + return_value=coverage_data): + self.oss_fuzz_coverage.get_files_covered_by_target(FUZZ_TARGET) + + def test_valid_target(self): + """Tests that covered files can be retrieved from a coverage report.""" + fuzzer_cov_data = _get_example_curl_coverage() + with mock.patch('get_coverage.OSSFuzzCoverage.get_target_coverage', + return_value=fuzzer_cov_data): + file_list = self.oss_fuzz_coverage.get_files_covered_by_target( + FUZZ_TARGET) + + expected_file_list = _get_expected_curl_covered_file_list() + self.assertCountEqual(file_list, expected_file_list) + + def test_invalid_target(self): + """Tests passing invalid fuzz target returns None.""" + self.assertIsNone( + self.oss_fuzz_coverage.get_files_covered_by_target(INVALID_TARGET)) + + +class FilesystemCoverageGetFilesCoveredByTargetTest( + fake_filesystem_unittest.TestCase): + """Tests FilesystemCoverage.get_files_covered_by_target.""" + + def setUp(self): + _fuzzer_cov_data = _get_example_curl_coverage() + self._expected_file_list = _get_expected_curl_covered_file_list() + self.coverage_path = '/coverage' + self.filesystem_coverage = get_coverage.FilesystemCoverage( + REPO_PATH, self.coverage_path) + self.setUpPyfakefs() + self.fs.create_file(os.path.join(self.coverage_path, 'fuzzer_stats', + FUZZ_TARGET + '.json'), + contents=json.dumps(_fuzzer_cov_data)) + + def test_valid_target(self): + """Tests that covered files can be retrieved from a coverage report.""" + file_list = self.filesystem_coverage.get_files_covered_by_target( + FUZZ_TARGET) + self.assertCountEqual(file_list, self._expected_file_list) + + def test_invalid_target(self): + """Tests passing invalid fuzz target returns None.""" + self.assertIsNone( + self.filesystem_coverage.get_files_covered_by_target(INVALID_TARGET)) + + +class IsFileCoveredTest(unittest.TestCase): + """Tests for is_file_covered.""" + + def test_is_file_covered_covered(self): + """Tests that is_file_covered returns True for a covered file.""" + file_coverage = { + 'filename': '/src/systemd/src/basic/locale-util.c', + 'summary': { + 'regions': { + 'count': 204, + 'covered': 200, + 'notcovered': 200, + 'percent': 98.03 + } + } + } + self.assertTrue(get_coverage.is_file_covered(file_coverage)) + + def test_is_file_covered_not_covered(self): + """Tests that is_file_covered returns False for a not covered file.""" + file_coverage = { + 'filename': '/src/systemd/src/basic/locale-util.c', + 'summary': { + 'regions': { + 'count': 204, + 'covered': 0, + 'notcovered': 0, + 'percent': 0 + } + } + } + self.assertFalse(get_coverage.is_file_covered(file_coverage)) + + +class GetOssFuzzLatestCovReportInfo(unittest.TestCase): + """Tests that _get_oss_fuzz_latest_cov_report_info works as + intended.""" + + PROJECT = 'project' + LATEST_REPORT_INFO_URL = ('https://storage.googleapis.com/oss-fuzz-coverage/' + 'latest_report_info/project.json') + + @mock.patch('logging.error') + @mock.patch('http_utils.get_json_from_url', return_value={'coverage': 1}) + def test_get_oss_fuzz_latest_cov_report_info(self, mock_get_json_from_url, + mock_error): + """Tests that _get_oss_fuzz_latest_cov_report_info works as intended.""" + result = get_coverage._get_oss_fuzz_latest_cov_report_info(self.PROJECT) + self.assertEqual(result, {'coverage': 1}) + mock_error.assert_not_called() + mock_get_json_from_url.assert_called_with(self.LATEST_REPORT_INFO_URL) + + @mock.patch('logging.error') + @mock.patch('http_utils.get_json_from_url', return_value=None) + def test_get_oss_fuzz_latest_cov_report_info_fail(self, _, mock_error): + """Tests that _get_oss_fuzz_latest_cov_report_info works as intended when we + can't get latest report info.""" + result = get_coverage._get_oss_fuzz_latest_cov_report_info('project') + self.assertIsNone(result) + mock_error.assert_called_with( + 'Could not get the coverage report json from url: %s.', + self.LATEST_REPORT_INFO_URL) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/http_utils.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/http_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dfcef216766cea9ac3c56da6580f512d585af1bd --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/http_utils.py @@ -0,0 +1,118 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utility module for HTTP.""" +import json +import logging +import os +import sys +import tempfile +import zipfile + +import requests + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import retry + +_DOWNLOAD_URL_RETRIES = 3 +_DOWNLOAD_URL_BACKOFF = 1 +_HTTP_REQUEST_TIMEOUT = 10 + + +def download_and_unpack_zip(url, extract_directory, headers=None): + """Downloads and unpacks a zip file from an HTTP URL. + + Args: + url: A url to the zip file to be downloaded and unpacked. + extract_directory: The path where the zip file should be extracted to. + headers: (Optional) HTTP headers to send with the download request. + + Returns: + True on success. + """ + if headers is None: + headers = {} + + if not os.path.exists(extract_directory): + logging.error('Extract directory: %s does not exist.', extract_directory) + return False + + # Gives the temporary zip file a unique identifier in the case that + # that download_and_unpack_zip is done in parallel. + with tempfile.NamedTemporaryFile(suffix='.zip') as tmp_file: + if not download_url(url, tmp_file.name, headers=headers): + return False + + try: + with zipfile.ZipFile(tmp_file.name, 'r') as zip_file: + zip_file.extractall(extract_directory) + except zipfile.BadZipFile: + logging.error('Error unpacking zip from %s. Bad Zipfile.', url) + return False + + return True + + +def download_url(*args, **kwargs): + """Wrapper around _download_url that returns False if _download_url + exceptions.""" + try: + return _download_url(*args, **kwargs) + except Exception: # pylint: disable=broad-except + return False + + +def get_json_from_url(url): + """Gets a json object from a specified HTTP URL. + + Args: + url: The url of the json to be downloaded. + + Returns: + A dictionary deserialized from JSON or None on failure. + """ + try: + return requests.get(url, timeout=_HTTP_REQUEST_TIMEOUT).json() + except (ValueError, TypeError, json.JSONDecodeError, + requests.exceptions.ReadTimeout) as err: + logging.error('Loading json from url %s failed with: %s.', url, str(err)) + return None + + +@retry.wrap(_DOWNLOAD_URL_RETRIES, _DOWNLOAD_URL_BACKOFF) +def _download_url(url, filename, headers=None): + """Downloads the file located at |url|, using HTTP to |filename|. + + Args: + url: A url to a file to download. + filename: The path the file should be downloaded to. + headers: (Optional) HTTP headers to send with the download request. + + Returns: + True on success. + """ + if headers is None: + headers = {} + + response = requests.get(url, headers=headers) + + if response.status_code != 200: + logging.error('Unable to download from: %s. Code: %d. Content: %s.', url, + response.status_code, response.content) + return False + + with open(filename, 'wb') as file_handle: + file_handle.write(response.content) + + return True diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github.py new file mode 100644 index 0000000000000000000000000000000000000000..dc66e495acd02bb3ede6b92e289a02e2216a219c --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github.py @@ -0,0 +1,146 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on Github.""" +import json +import logging +import os + +import platform_config + + +def _get_github_event_path(): + return os.getenv('GITHUB_EVENT_PATH') + + +def _get_event_data(): + """Returns the GitHub event data.""" + github_event_path = _get_github_event_path() + with open(github_event_path, encoding='utf-8') as file_handle: + return json.load(file_handle) + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for GitHub.""" + + def __init__(self): + self._event_data = _get_event_data() + self._event = os.getenv('GITHUB_EVENT_NAME') + + @property + def workspace(self): + """Returns the workspace.""" + return os.getenv('GITHUB_WORKSPACE') + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz. This is used only by GitHub + projects when commit fuzzing. It is not used when PR fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + return os.getenv('GITHUB_SHA') + + @property + def actor(self): + """Name of the actor for the CI.""" + return os.getenv('GITHUB_ACTOR') + + @property + def token(self): + """Returns the CI API token.""" + return os.getenv('GITHUB_TOKEN') + + @property + def project_src_path(self): + """Returns the manually checked out path of the project's source if + specified or None. The path returned is relative to |self.workspace| since + on github the checkout will be relative to there.""" + project_src_path = super().project_src_path + if project_src_path is None: + # Not set for internal GitHub users. + return project_src_path + # On GitHub (external users), this path is relative to |workspace|. + return os.path.join(self.workspace, project_src_path) + + @property + def _project_repo_owner_and_name(self): + """Returns a tuple containing the project repo owner and the name of the + repo.""" + # On GitHub this includes owner and repo name. + repository = os.getenv('GITHUB_REPOSITORY') + # Use os.path.split to split owner from repo. + return os.path.split(repository) + + @property + def project_repo_owner(self): + """Returns the project repo owner (githubism).""" + return self._project_repo_owner_and_name[0] + + @property + def project_repo_name(self): + """Returns the project repo name.""" + return self._project_repo_owner_and_name[1] + + @property + def git_url(self): + """Returns the repo URL. This is only used by GitHub users. Right now it is + needed by external on GitHub because we need to clone a new repo because the + copy they give us doesn't work for diffing. It isn't used by OSS-Fuzz on + github users since the Git URL is determined using repo detection. + + TODO(metzman): Try to eliminate the need for this by making the clone + from external github projects usable. + TODO(metzman): As an easier goal, maybe make OSS-Fuzz GitHub use this too + for: 1. Consistency 2. Maybe it will allow use on forks.""" + repository = os.getenv('GITHUB_REPOSITORY') + github_server_url = os.getenv('GITHUB_SERVER_URL', 'https://github.com') + # TODO(metzman): Probably need to change this to github.server_url. + return os.path.join(github_server_url, repository) + + @property + def base_commit(self): + """Returns the base commit to diff against (commit fuzzing).""" + base_commit = None + if self._event == 'push': + base_commit = self._event_data['before'] + logging.debug('base_commit: %s', base_commit) + return base_commit + + @property + def pr_ref(self): + """Returns the pull request to checkout and fuzz. This is used only by + GitHub projects when PR fuzzing. It is not used when commit fuzzing. It is + definitely needed by OSS-Fuzz on GitHub since they have no copy of the repo + on the host and the repo on the builder image is a clone from main/master. + Right now it is needed by external on GitHub because we need to clone a new + repo because the copy they give us doesn't work for diffing. + + TODO(metzman): Try to eliminate the need for this by 1. Making the clone + from external github projects usable. 2. Forcing OSS-Fuzz on Github to clone + before starting CIFuzz.""" + if self._event == 'pull_request': + pr_ref = f'refs/pull/{self._event_data["pull_request"]["number"]}/merge' + logging.debug('pr_ref: %s', pr_ref) + return pr_ref + return None + + @property + def base_ref(self): + """Returns the base branch to diff against (pr fuzzing).""" + return os.getenv('GITHUB_BASE_REF') diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github_test.py new file mode 100644 index 0000000000000000000000000000000000000000..11cc6866cdffd122bd0a1dbba91c1b87e676cc39 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/github_test.py @@ -0,0 +1,87 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for platform_config.github.""" +import os +import unittest +from unittest import mock + +import platform_config.github +import test_helpers + +# pylint: disable=arguments-differ + + +class GetProjectRepoOwnerAndNameTest(unittest.TestCase): + """Tests for get_project_repo_owner and get_project_repo_name.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): + test_helpers.patch_environ(self) + self.repo_owner = 'repo-owner' + self.repo_name = 'repo-name' + os.environ['GITHUB_REPOSITORY'] = f'{self.repo_owner}/{self.repo_name}' + self.platform_conf = platform_config.github.PlatformConfig() + + def test_github_repository_owner(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + self.assertEqual(self.platform_conf.project_repo_owner, self.repo_owner) + + def test_github_repository_name(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + os.environ['GITHUB_REPOSITORY'] = f'{self.repo_owner}/{self.repo_name}' + self.assertEqual(self.platform_conf.project_repo_name, self.repo_name) + + +class ProjectSrcPathTest(unittest.TestCase): + """Tests for project_src_path.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.workspace = '/workspace' + os.environ['GITHUB_WORKSPACE'] = self.workspace + self.project_src_dir_name = 'project-src' + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github_unset(self, _): + """Tests that project_src_path returns None when no PROJECT_SRC_PATH is + set.""" + github_env = platform_config.github.PlatformConfig() + self.assertIsNone(github_env.project_src_path) + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github(self, _): + """Tests that project_src_path returns the correct result on GitHub.""" + os.environ['PROJECT_SRC_PATH'] = self.project_src_dir_name + expected_project_src_path = os.path.join(self.workspace, + self.project_src_dir_name) + github_env = platform_config.github.PlatformConfig() + self.assertEqual(github_env.project_src_path, expected_project_src_path) + + +class GetGitUrlTest(unittest.TestCase): + """Tests for GenericPlatformConfig.git_url.""" + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def setUp(self, _): + test_helpers.patch_environ(self) + self.platform_conf = platform_config.github.PlatformConfig() + + def test_repository(self): + """Tests that the correct result is returned when repository contains the + owner and repo name (as it does on GitHub).""" + os.environ['GITHUB_REPOSITORY'] = 'repo/owner' + self.assertEqual('https://github.com/repo/owner', + self.platform_conf.git_url) diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py new file mode 100644 index 0000000000000000000000000000000000000000..186cbefc4db9d2dc3693e36a20ed4ec40227d748 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/gitlab.py @@ -0,0 +1,78 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run on GitLab.""" +import logging +import os + +import environment +import platform_config + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for GitLab.""" + + @property + def workspace(self): + """Returns the workspace.""" + return os.path.join(os.getenv('CI_BUILDS_DIR'), os.getenv('CI_JOB_ID')) + + @property + def git_sha(self): + """Returns the Git SHA to checkout and fuzz.""" + return os.getenv('CI_COMMIT_SHA') + + @property + def project_src_path(self): + """Returns the directory with the source of the project""" + return os.getenv('CI_PROJECT_DIR') + + @property + def token(self): + """Returns the job token""" + return os.getenv('CI_JOB_TOKEN') + + @property + def project_repo_name(self): + """Returns the project's name""" + return os.getenv('CI_PROJECT_NAME') + + @property + def base_commit(self): + """Returns the previous commit sha for commit-fuzzing""" + base_commit = None + if os.getenv('CI_PIPELINE_SOURCE') == 'push': + base_commit = os.getenv('CI_COMMIT_BEFORE_SHA') + logging.debug('base_commit: %s.', base_commit) + return base_commit + + @property + def base_ref(self): + """Returns the base commit sha for a merge request""" + # Could also be CI_MERGE_REQUEST_TARGET_BRANCH_NAME. + return os.getenv('CI_MERGE_REQUEST_DIFF_BASE_SHA') + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'gitlab') + + @property + def artifacts_dir(self): + """Gitlab: returns the directory to put artifacts""" + return environment.get('CFL_ARTIFACTS_DIR', 'artifacts') + + @property + def cache_dir(self): + """Gitlab: returns the directory to use as cache""" + return environment.get('CFL_CACHE_DIR', 'cache') diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/standalone.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/standalone.py new file mode 100644 index 0000000000000000000000000000000000000000..1975dfb1b842a28b9f2ceea809ef2f0d4d7a4a49 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/platform_config/standalone.py @@ -0,0 +1,33 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run standalone.""" +import os + +import platform_config + +# pylint: disable=too-few-public-methods + + +class PlatformConfig(platform_config.BasePlatformConfig): + """CI environment for Standalone.""" + + @property + def filestore(self): + """Returns the filestore used to store persistent data.""" + return os.environ.get('FILESTORE', 'filesystem') + + @property + def filestore_root_dir(self): + """Returns the filestore used to store persistent data.""" + return os.environ['FILESTORE_ROOT_DIR'] diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..a136f6991083426eb939f2c1cdef8afd28dc96ea --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers.py @@ -0,0 +1,321 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for running fuzzers.""" +import enum +import logging +import os +import sys +import time + +import clusterfuzz_deployment +import fuzz_target +import generate_coverage_report +import workspace_utils +import sarif_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import utils + + +class RunFuzzersResult(enum.Enum): + """Enum result from running fuzzers.""" + ERROR = 0 + BUG_FOUND = 1 + NO_BUG_FOUND = 2 + + +class BaseFuzzTargetRunner: + """Base class for fuzzer runners.""" + + def __init__(self, config): + self.config = config + self.workspace = workspace_utils.Workspace(config) + self.clusterfuzz_deployment = ( + clusterfuzz_deployment.get_clusterfuzz_deployment( + self.config, self.workspace)) + + # Set by the initialize method. + self.fuzz_target_paths = None + + def get_fuzz_targets(self): + """Returns fuzz targets in out directory.""" + return utils.get_fuzz_targets(self.workspace.out) + + def initialize(self): + """Initialization method. Must be called before calling run_fuzz_targets. + Returns True on success.""" + # Use a separate initialization function so we can return False on failure + # instead of exceptioning like we need to do if this were done in the + # __init__ method. + + logging.info('Using %s sanitizer.', self.config.sanitizer) + + # TODO(metzman) Add a check to ensure we aren't over time limit. + if not self.config.fuzz_seconds or self.config.fuzz_seconds < 1: + logging.error( + 'Fuzz_seconds argument must be greater than 1, but was: %s.', + self.config.fuzz_seconds) + return False + + if not os.path.exists(self.workspace.out): + logging.error('Out directory: %s does not exist.', self.workspace.out) + return False + + if not os.path.exists(self.workspace.artifacts): + os.makedirs(self.workspace.artifacts) + elif (not os.path.isdir(self.workspace.artifacts) or + os.listdir(self.workspace.artifacts)): + logging.error('Artifacts path: %s exists and is not an empty directory.', + self.workspace.artifacts) + return False + + self.fuzz_target_paths = self.get_fuzz_targets() + logging.info('Fuzz targets: %s', self.fuzz_target_paths) + if not self.fuzz_target_paths: + logging.error('No fuzz targets were found in out directory: %s.', + self.workspace.out) + return False + + return True + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after running |fuzz_target_obj|.""" + raise NotImplementedError('Child class must implement method.') + + def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use + """Fuzzes with |fuzz_target_obj| and returns the result.""" + raise NotImplementedError('Child class must implement method.') + + @property + def quit_on_bug_found(self): + """Property that is checked to determine if fuzzing should quit after first + bug is found.""" + raise NotImplementedError('Child class must implement method.') + + def create_fuzz_target_obj(self, target_path, run_seconds): + """Returns a fuzz target object.""" + return fuzz_target.FuzzTarget(target_path, run_seconds, self.workspace, + self.clusterfuzz_deployment, self.config) + + def run_fuzz_targets(self): + """Runs fuzz targets. Returns True if a bug was found.""" + fuzzers_left_to_run = len(self.fuzz_target_paths) + + # Make a copy since we will mutate it. + fuzz_seconds = self.config.fuzz_seconds + + min_seconds_per_fuzzer = fuzz_seconds // fuzzers_left_to_run + bug_found = False + for target_path in self.fuzz_target_paths: + # By doing this, we can ensure that every fuzz target runs for at least + # min_seconds_per_fuzzer, but that other fuzzers will have longer to run + # if one ends early. + run_seconds = max(fuzz_seconds // fuzzers_left_to_run, + min_seconds_per_fuzzer) + + target = self.create_fuzz_target_obj(target_path, run_seconds) + start_time = time.time() + result = self.run_fuzz_target(target) + self.cleanup_after_fuzz_target_run(target) + + # It's OK if this goes negative since we take max when determining + # run_seconds. + fuzz_seconds -= time.time() - start_time + + fuzzers_left_to_run -= 1 + if not result.testcase or not result.stacktrace: + logging.info('Fuzzer %s finished running without reportable crashes.', + target.target_name) + continue + + bug_found = True + if self.quit_on_bug_found: + logging.info('Bug found. Stopping fuzzing.') + break + + # pylint: disable=undefined-loop-variable + if not target_path: + logging.error('Ran no fuzz targets.') + elif self.config.output_sarif: + # TODO(metzman): Handle multiple crashes. + write_fuzz_result_to_sarif(result, target_path, self.workspace) + self.clusterfuzz_deployment.upload_crashes() + return bug_found + + +def write_fuzz_result_to_sarif(fuzz_result, target_path, workspace): + """Write results of fuzzing to SARIF.""" + logging.info('Writing sarif results.') + sarif_utils.write_stacktrace_to_sarif(fuzz_result.stacktrace, target_path, + workspace) + + +class PruneTargetRunner(BaseFuzzTargetRunner): + """Runner that prunes corpora.""" + + @property + def quit_on_bug_found(self): + return False + + def run_fuzz_target(self, fuzz_target_obj): + """Prunes with |fuzz_target_obj| and returns the result.""" + result = fuzz_target_obj.prune() + logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path)) + self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name, + result.corpus_path, + replace=True) + return result + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after pruning with |fuzz_target_obj|.""" + fuzz_target_obj.free_disk_if_needed() + + +NON_FUZZ_TARGETS_FOR_COVERAGE = { + 'llvm-symbolizer', + 'jazzer_agent_deploy.jar', + 'jazzer_driver', + 'jazzer_driver_with_sanitizer', +} + + +def is_coverage_fuzz_target(file_path): + """Returns whether |file_path| is a fuzz target binary for the purposes of a + coverage report. Inspired by infra/base-images/base-runner/coverage.""" + if not os.path.isfile(file_path): + return False + if not utils.is_executable(file_path): + return False + filename = os.path.basename(file_path) + return filename not in NON_FUZZ_TARGETS_FOR_COVERAGE + + +def get_coverage_fuzz_targets(out): + """Returns a list of fuzz targets in |out| for coverage.""" + # We only want fuzz targets from the root because during the coverage build, + # a lot of the image's filesystem is copied into /out for the purpose of + # generating coverage reports. + fuzz_targets = [] + for filename in os.listdir(out): + file_path = os.path.join(out, filename) + if is_coverage_fuzz_target(file_path): + fuzz_targets.append(file_path) + return fuzz_targets + + +class CoverageTargetRunner(BaseFuzzTargetRunner): + """Runner that runs the 'coverage' command.""" + + @property + def quit_on_bug_found(self): + raise NotImplementedError('Not implemented for CoverageTargetRunner.') + + def get_fuzz_targets(self): + """Returns fuzz targets in out directory.""" + return get_coverage_fuzz_targets(self.workspace.out) + + def run_fuzz_targets(self): + """Generates a coverage report. Always returns False since it never finds + any bugs.""" + generate_coverage_report.generate_coverage_report( + self.fuzz_target_paths, self.workspace, self.clusterfuzz_deployment, + self.config) + return False + + def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use + """Fuzzes with |fuzz_target_obj| and returns the result.""" + raise NotImplementedError('Not implemented for CoverageTargetRunner.') + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after running |fuzz_target_obj|.""" + raise NotImplementedError('Not implemented for CoverageTargetRunner.') + + +class CiFuzzTargetRunner(BaseFuzzTargetRunner): + """Runner for fuzz targets used in CI (patch-fuzzing) context.""" + + @property + def quit_on_bug_found(self): + return True + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): # pylint: disable=no-self-use + """Cleans up after running |fuzz_target_obj|.""" + fuzz_target_obj.free_disk_if_needed() + + def run_fuzz_target(self, fuzz_target_obj): # pylint: disable=no-self-use + return fuzz_target_obj.fuzz() + + +class BatchFuzzTargetRunner(BaseFuzzTargetRunner): + """Runner for fuzz targets used in batch fuzzing context.""" + + @property + def quit_on_bug_found(self): + return False + + def run_fuzz_target(self, fuzz_target_obj): + """Fuzzes with |fuzz_target_obj| and returns the result.""" + result = fuzz_target_obj.fuzz(batch=True) + logging.debug('Corpus path contents: %s.', os.listdir(result.corpus_path)) + self.clusterfuzz_deployment.upload_corpus(fuzz_target_obj.target_name, + result.corpus_path) + return result + + def cleanup_after_fuzz_target_run(self, fuzz_target_obj): + """Cleans up after running |fuzz_target_obj|.""" + # This must be done after we upload the corpus, otherwise it will be deleted + # before we get a chance to upload it. We can't delete the fuzz target + # because it is needed when we upload the build. + fuzz_target_obj.free_disk_if_needed(delete_fuzz_target=False) + + +_MODE_RUNNER_MAPPING = { + 'batch': BatchFuzzTargetRunner, + 'coverage': CoverageTargetRunner, + 'prune': PruneTargetRunner, + 'code-change': CiFuzzTargetRunner, +} + + +def get_fuzz_target_runner(config): + """Returns a fuzz target runner object based on the mode of + |config|.""" + runner = _MODE_RUNNER_MAPPING[config.mode](config) + logging.info('run fuzzers MODE is: %s. Runner: %s.', config.mode, runner) + return runner + + +def run_fuzzers(config): # pylint: disable=too-many-locals + """Runs fuzzers for a specific OSS-Fuzz project. + + Args: + config: A RunFuzzTargetsConfig. + + Returns: + A RunFuzzersResult enum value indicating what happened during fuzzing. + """ + fuzz_target_runner = get_fuzz_target_runner(config) + if not fuzz_target_runner.initialize(): + # We didn't fuzz at all because of internal (CIFuzz) errors. And we didn't + # find any bugs. + return RunFuzzersResult.ERROR + + if not fuzz_target_runner.run_fuzz_targets(): + # We fuzzed successfully, but didn't find any bugs (in the fuzz target). + return RunFuzzersResult.NO_BUG_FOUND + + # We fuzzed successfully and found bug(s) in the fuzz targets. + return RunFuzzersResult.BUG_FOUND diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers_entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..924914199677e732c81d7d927553b60341bdbe7b --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/run_fuzzers_test.py new file mode 100644 index 0000000000000000000000000000000000000000..64fddcdff897e0af6102c0b58de05a89051d49e2 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils_test.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e8870887c071e4694a6550af0a4f432ad3838a8f --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/sarif_utils_test.py @@ -0,0 +1,128 @@ +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for sarif_utils.py""" +import os +import unittest +from unittest import mock + +import sarif_utils + +CRASH_INFO_FILELINE = 403 + +TEST_DATA = os.path.join(os.path.dirname(__file__), 'test_data') + + +class GetSarifDataTest(unittest.TestCase): + """Tests for get_sarif_data.""" + + def setUp(self): + self.maxDiff = None # pylint: disable=invalid-name + + def test_get_sarif_data_none(self): + """Tests get_sarif_data when there was no crash.""" + self.assertEqual(sarif_utils.get_sarif_data(None, '/root/target'), + sarif_utils.SARIF_DATA) + + def test_ordinary_case(self): + stacktrace_filename = os.path.join(TEST_DATA, + 'sarif_utils_systemd_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + expected_result = { + 'level': 'error', + 'message': { + 'text': 'Heap-buffer-overflow\nREAD 4' + }, + 'locations': [{ + 'physicalLocation': { + 'artifactLocation': { + 'uri': 'src/core/fuzz-unit-file.c', + 'index': 0 + }, + 'region': { + 'startLine': 30, + # We don't have this granualarity fuzzing. + 'startColumn': 1, + } + } + }], + 'ruleId': 'heap-buffer-overflow', + 'ruleIndex': 2 + } + actual_result = sarif_utils.get_sarif_data( + stacktrace, '/root/target')['runs'][0]['results'][0] + self.assertEqual(actual_result, expected_result) + + def test_llvmfuzzertestoneinput_case(self): + stacktrace_filename = os.path.join(TEST_DATA, + 'sarif_utils_only_llvmfuzzer_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + actual_result = sarif_utils.get_sarif_data( + stacktrace, '/root/target')['runs'][0]['results'] + self.assertEqual(actual_result, []) + + def test_msan(self): + """Tests that MSAN stacktraces don't exception.""" + stacktrace_filename = os.path.join(TEST_DATA, 'sarif_utils_msan_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + + actual_result = sarif_utils.get_sarif_data(stacktrace, '/root/target') + + +class RedactSrcPathTest(unittest.TestCase): + """Tests for redact_src_path.""" + + def test_redact_src_path(self): + """Tests redact_src_path.""" + path = '/src/src-repo/subdir/file' + self.assertEqual(sarif_utils.redact_src_path(path), 'subdir/file') + + +def _get_mock_crash_info(): + """Returns a mock crash_info to be used in tests.""" + stack_frame = mock.MagicMock() + stack_frame.filename = '/src/repo-dir/sub/vuln.cc' + stack_frame.function_name = 'vuln_func' + stack_frame.fileline = CRASH_INFO_FILELINE + crash1_frames = [stack_frame, stack_frame] + frames = [crash1_frames] + crash_info = mock.MagicMock() + crash_info.frames = frames + crash_info.crash_state = 'vuln_func\nvuln_func0\nvuln_func1' + return crash_info + + +class GetErrorSourceInfoTest(unittest.TestCase): + """Tests for get_error_source_info.""" + + def test_redact_src_path(self): + """Tests that get_error_source_info finds the right source info.""" + crash_info = _get_mock_crash_info() + source_info = sarif_utils.get_error_source_info(crash_info) + expected_source_info = ('sub/vuln.cc', CRASH_INFO_FILELINE) + self.assertEqual(source_info, expected_source_info) + + +class GetRuleIndexTest(unittest.TestCase): + """Tests for get_rule_index.""" + CRASH_INFO_CRASH_TYPE = 'Heap-use-after-free READ 8' + + def test_get_rule_index(self): + """Tests that get_rule_index finds the right rule index.""" + index = sarif_utils.get_rule_index(self.CRASH_INFO_CRASH_TYPE) + self.assertEqual(sarif_utils.SARIF_RULES[index]['id'], + 'heap-use-after-free') + self.assertEqual(sarif_utils.get_rule_index('no-crashes'), 0) diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/test_helpers.py b/local-test-tika-delta-01/fuzz-tooling/infra/cifuzz/test_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..846a8a888ecda9c48f66d5486cb118387fbf1511 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/Makefile b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..04db9976eac198bd430650da656998169912dc2f --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/Makefile @@ -0,0 +1,41 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 -Werror + +all: SystemSan target target_file target_dns + +SystemSan: SystemSan.cpp inspect_dns.cpp inspect_utils.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +# Needs atheris. +python-test: all + ./SystemSan python shell_injection_poc_fuzzer.py + +target: target.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +target_file: target_file.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +target_dns: target_dns.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +test: all vuln.dict + ./SystemSan ./target -dict=vuln.dict + ./SystemSan ./target_file -dict=vuln.dict + ./SystemSan ./target_dns -dict=vuln.dict + +pytorch-lightning-1.5.10: + cp SystemSan.cpp PoEs/pytorch-lightning-1.5.10/; \ + cd PoEs/pytorch-lightning-1.5.10/; \ + docker build . --tag syssan_pytorch-lightning; \ + docker run -t systemsan_pytorch-lightning:latest; + +node-shell-quote-v1.7.3: + cp SystemSan.cpp PoEs/node-shell-quote-v1.7.3/; \ + cd PoEs/node-shell-quote-v1.7.3/; \ + docker build . --tag systemsan_node-shell-quote; \ + docker run -t systemsan_node-shell-quote:latest; + +clean: + rm -f SystemSan /tmp/tripwire target target_file target_dns diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..120de50346ebeb22f0e173becb2f623e54e61139 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/Dockerfile @@ -0,0 +1,35 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Build and run the proof of error in shell-quote v1.7.3. + +FROM ghcr.io/aixcc-finals/base-builder + +RUN apt update && \ + apt install -y \ + vim \ + npm && \ + git clone \ + --depth 1 \ + https://github.com/substack/node-shell-quote.git && \ + npm config set @gitlab-org:registry \ + https://gitlab.com/api/v4/packages/npm/ + +COPY ./build.sh $SRC +RUN ./build.sh + +COPY . $SRC +RUN make SystemSan + +CMD ["make", "run"] diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b34a8c2b09f781b773ace8bc13dfb7d345b1cfd --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/build.sh @@ -0,0 +1,22 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build and install project (using current CFLAGS, CXXFLAGS). +npm install ./node-shell-quote/ + +# Build fuzzers. +npm i -g @gitlab-org/jsfuzz diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js new file mode 100644 index 0000000000000000000000000000000000000000..82608cd2169fc7d757e0d69782a8eaa3b5e9cc88 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/node-shell-quote-v1.7.3/target.js @@ -0,0 +1,35 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* Exploit shell quote with fuzzer's input as a parameter of echo. + * This PoC is extended from a report in GitHub Advisory Database: + * https://github.com/advisories/GHSA-g4rg-993r-mgx7 + * The original report records a shell injection exploit in shell-quote v1.7.2, + * we show that a similar shell corruption exploit still persists in v1.7.3, + * after a commit that intends to fix the original exploit. + * */ + +/* Fuzz the target program with buf generated by Jsfuzz. */ +function fuzz(buf) { + buf = String(buf) + const childProcess = require('child_process'); + const shellQuote = require('shell-quote'); + childProcess.execSync(shellQuote.quote(['echo', buf])); +} + +/* Run Jsfuzz. */ +module.exports = { + fuzz +}; diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c577797f37169886ac3ffd48e12ad21c5986689d --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Dockerfile @@ -0,0 +1,32 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Build and run the proof of error in pytorch-lightning. + +FROM ghcr.io/aixcc-finals/base-builder-python + +RUN apt update && \ + apt install -y vim && \ + git clone \ + --depth 1 \ + --branch 1.5.10 \ + https://github.com/PyTorchLightning/pytorch-lightning.git + +COPY ./build.sh $SRC +RUN ./build.sh + +COPY . $SRC +RUN make SystemSan + +CMD ["make", "run"] diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..2169bc15a592d7136d9d166159eb09dec8c49d01 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/Makefile @@ -0,0 +1,12 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 + +SystemSan: SystemSan.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +run: clean SystemSan fuzz_pytorch_lightning.py + ./SystemSan ./fuzz_pytorch_lightning.py -dict=vuln.dict + +clean: + rm -f SystemSan /tmp/tripwire diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c9b1adbf5a1b1241e50b8e88a03529cfb69e0b0 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/build.sh @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build and install project (using current CFLAGS, CXXFLAGS). +cd pytorch-lightning +pip3 install . + +# Build fuzzers in $OUT. +for fuzzer in $(find $SRC -name '*_fuzzer.py'); do + compile_python_fuzzer $fuzzer +done diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..0d07da3a6269381d688e8f3ac7da5d5d0ee7d04a --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py @@ -0,0 +1,65 @@ +#!/usr/local/bin/python3 +# +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Exploit pytorch lightning with fuzzer's input as a random env variable. + +This PoC is extended from a report in GitHub Advisory Database: +https://github.com/advisories/GHSA-r5qj-cvf9-p85h +The original report documents an exploit using a specific environment variable, +we show a way to achieve the same exploit with an arbitrary env variable. +""" + +import os +import sys +import atheris + +with atheris.instrument_imports(): + from pytorch_lightning import Trainer + from pytorch_lightning.utilities.argparse import parse_env_variables + + +def prepare_fuzzing_input(data): + """Prepare the data needed by the exploit with input data from fuzzers.""" + data = data.replace(b'\0', b'') + env_name = 'AN_ARBITRARY_ENV_NAME' + return data, env_name + + +def exploit_target(env_value, env_name): + """This target is based on a snippet from the official documentation of + `parse_env_variables`: + https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.utilities.argparse.html # pylint: disable=line-too-long + It might not be the most realistic example, + but serves as a PoC to show that SystemSan works for Python.""" + os.environb[env_name.encode()] = env_value + parse_env_variables(Trainer, template=env_name) + + +def TestOneInput(data): # pylint: disable=invalid-name + """Exploit the target only with input data from fuzzers.""" + env_value, env_name = prepare_fuzzing_input(data) + exploit_target(env_value, env_name) + + +def main(): + """Fuzz target with atheris.""" + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..0d19aa407357659d0beb8487443c65eead7dab6a --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict @@ -0,0 +1 @@ +"os.system('/tmp/tripwire')" diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/README.md b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48e111d1abc6d96661659f9a19dd7fc6f969baad --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/README.md @@ -0,0 +1,66 @@ +# System Sanitizers + +We use `ptrace` to instrument system calls made by the target program to detect +various vulnerabilities. + +## Command injection + +This detector currently works by + +- Checking if `execve` is called with `/tmp/tripwire` (which comes from our dictionary). +- Checking if `execve` is invoking a shell with invalid syntax. This is likely + caused by our input. + +## Arbitrary file open + +TODO: documentation. + +## Proof of concept + +### Cleanup +Note this will delete /tmp/tripwire if it exists. +```shell +make clean +``` + +### Run test +Note this will overwrite /tmp/tripwire if it exists. +```shell +make test +``` + +Look for one of the following lines: + +> ===BUG DETECTED: Shell injection=== + +which indicates the detection of executing the planted `/tmp/tripwire`. + + +> ===BUG DETECTED: Shell corruption=== + +which indicates the detection of executing a syntactic erroneous command. + + +### Command injection PoC in Python with `pytorch-lightning` +With `SystemSan`, [`Artheris`](https://github.com/google/atheris) can detect a shell injection bug in [version v1.5.10 of `pytorch-lightning`](https://github.com/PyTorchLightning/pytorch-lightning/tree/1.5.0). +```shell +make pytorch-lightning-1.5.10 +``` + +### Command injection PoC in JavaScript with `shell-quote` +With `SystemSan`, [`Jsfuzz`](https://gitlab.com/gitlab-org/security-products/analyzers/fuzzers/jsfuzz) can detect a shell corrpution bug in [the latest version (v1.7.3) of `shell-quote`](https://github.com/substack/node-shell-quote) without any seed. +```shell +make node-shell-quote-v1.7.3 +``` +This is based on [a shell injection exploit report](https://wh0.github.io/2021/10/28/shell-quote-rce-exploiting.html) of [version v1.7.2 of `shell-quote`](https://github.com/substack/node-shell-quote/tree/v1.7.2). +`SystemSan` can also discover the same shell injection bug with a corpus file containing: +``` +`:`/tmp/tripwire``:` +``` + +## Trophies + +- +- + + diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27e8795c55df12d3c17399eda52c738c1b914240 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp @@ -0,0 +1,493 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify shell injection vulnerabilities. */ + +/* C standard library */ +#include +#include +#include +#include + +/* POSIX */ +#include +#include +#include +#include + +/* Linux */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "inspect_utils.h" +#include "inspect_dns.h" + +#define DEBUG_LOGS 0 + +#if DEBUG_LOGS +#define debug_log(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fflush(stdout); \ + fputc('\n', stderr); \ + } while (0) +#else +#define debug_log(...) +#endif + +#define fatal_log(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + exit(EXIT_FAILURE); \ + } while (0) + +// The magic string that we'll use to detect full control over the command +// executed. +const std::string kTripWire = "/tmp/tripwire"; +// Shell injection bug confirmed with /tmp/tripwire. +const std::string kInjectionError = "Shell injection"; +// Shell corruption bug detected based on syntax error. +const std::string kCorruptionError = "Shell corruption"; +// The magic string that we'll use to detect arbitrary file open +const std::string kFzAbsoluteDirectory = "/fz/"; +// Arbitrary file open in /fz/ +const std::string kArbitraryFileOpenError = "Arbitrary file open"; +// Assuming only shorter (than this constant) top dir are legitly used. +constexpr int kRootDirMaxLength = 16; + +// The PID of the root process we're fuzzing. +pid_t g_root_pid; + +// Map of a PID/TID its PID/TID creator and wether it ran exec. +std::map root_pids; + +// Assuming the longest pathname is "/bin/bash". +constexpr int kShellPathnameLength = 20; + +// Syntax error messages of each shell. +const std::map> kShellSyntaxErrors = { + {"bash", + { + ": command not found", // General + ": syntax error", // Unfinished " or ' or ` or if, leading | or ; + ": missing `]'", // Unfinished [ + ": event not found", // ! leads large numbers + ": No such file or directory", // Leading < or / + }}, + {"csh", + { + ": Command not found.", // General + ": Missing }.", // Unfinished { + "Too many ('s.", // Unfinished ( + "Invalid null command.", // Leading | or < or > + "Missing name for redirect.", // Single < or > + ": No match.", // Leading ? or [ or * + "Modifier failed.", // Leading ^ + "No previous left hand side.", // A ^ + ": No such job.", // Leading % + ": No current job.", // A % + ": Undefined variable.", // Containing $ + ": Event not found.", // ! leads large numbers + // TODO: Make this more specific. + "Unmatched", // Unfinished " or ' or `, leading ; + }}, + {"dash", + { + "not found", // General + "Syntax error", // Unfinished " or ' or ` or if, leading | or ; or & + "missing ]", // Unfinished [ + "No such file", // Leading < + }}, + {"zsh", + { + ": command not found", // General + ": syntax error", // Unfinished " or ' or ` + ": ']' expected", // Unfinished [ + ": no such file or directory", // Leading < or / + ": parse error near", // Leading |, or & + ": no such user or named directory", // Leading ~ + }}, +}; + +// Shells used by Processes. +std::map g_shell_pids; + +struct Tracee { + pid_t pid; + bool syscall_enter = true; + + Tracee(pid_t pid) : pid(pid) {} +}; + +pid_t run_child(char **argv) { + // Run the program under test with its args as a child process + pid_t pid = fork(); + switch (pid) { + case -1: + fatal_log("Fork failed: %s", strerror(errno)); + case 0: + raise(SIGSTOP); + execvp(argv[0], argv); + fatal_log("execvp: %s", strerror(errno)); + } + return pid; +} + +// Construct a string with the memory specified in a register. +std::string read_string(pid_t pid, unsigned long reg, unsigned long length) { + auto memory = read_memory(pid, reg, length); + if (!memory.size()) { + return ""; + } + + std::string content(reinterpret_cast(memory.data()), + std::min(memory.size(), length)); + return content; +} + +void inspect_for_injection(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's registers for the sign of shell injection. + std::string path = read_string(pid, regs.rdi, kTripWire.length()); + if (!path.length()) { + return; + } + debug_log("inspecting"); + if (path == kTripWire) { + report_bug(kInjectionError, pid); + } +} + +std::string get_pathname(pid_t pid, const user_regs_struct ®s) { + // Parse the pathname from the memory specified in the RDI register. + std::string pathname = read_string(pid, regs.rdi, kShellPathnameLength); + debug_log("Pathname is %s (len %lu)\n", pathname.c_str(), pathname.length()); + return pathname; +} + +std::string match_shell(std::string binary_pathname); + +// Identify the exact shell behind sh +std::string identify_sh(std::string path) { + char shell_pathname[kShellPathnameLength]; + auto written = readlink(path.c_str(), shell_pathname, kShellPathnameLength - 1); + if (written == -1) { + std::cerr << "Cannot query which shell is behind sh: readlink failed on " + << path << ": " + << strerror(errno) << "\n"; + std::cerr << "Assuming the shell is dash\n"; + return "dash"; + } + shell_pathname[written] = '\0'; + + debug_log("sh links to %s\n", shell_pathname); + std::string shell_pathname_str(shell_pathname); + + return match_shell(shell_pathname_str); +} + +std::string match_shell(std::string binary_pathname) { + // Identify the name of the shell used in the pathname. + if (!binary_pathname.length()) { + return ""; + } + + // We use c_str() to accept only the null terminated string. + std::string binary_name = binary_pathname.substr( + binary_pathname.find_last_of("/") + 1).c_str(); + + debug_log("Binary is %s (%lu)\n", binary_name.c_str(), + binary_name.length()); + + for (const auto &item : kShellSyntaxErrors) { + std::string known_shell = item.first; + if (binary_name == "sh") { + debug_log("Matched sh: Needs to identify which specific shell it is.\n"); + return identify_sh(binary_pathname); + } + if (binary_name == known_shell) { + debug_log("Matched %s\n", binary_name.c_str()); + return known_shell; + } + } + return ""; +} + +std::string get_shell(pid_t pid, const user_regs_struct ®s) { + // Get shell name used in a process. + std::string binary_pathname = get_pathname(pid, regs); + return match_shell(binary_pathname); +} + +void match_error_pattern(std::string buffer, std::string shell, pid_t pid) { + auto error_patterns = kShellSyntaxErrors.at(shell); + for (const auto &pattern : error_patterns) { + if (buffer.find(pattern) != std::string::npos) { + std::cerr << "--- Found a sign of shell corruption ---\n" + << buffer.c_str() + << "\n----------------------------------------\n"; + // If a shell corruption error happens, kill its parent. + auto parent = root_pids[pid]; + while (!parent.ran_exec) { + if (parent.parent_tid == g_root_pid) { + break; + } + parent = root_pids[parent.parent_tid]; + } + report_bug(kCorruptionError, parent.parent_tid); + } + } +} + +void inspect_for_corruption(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's registers for shell corruption. + std::string buffer = read_string(pid, regs.rsi, regs.rdx); + debug_log("Write buffer: %s\n", buffer.c_str()); + match_error_pattern(buffer, g_shell_pids[pid], pid); +} + +void log_file_open(std::string path, int flags, pid_t pid) { + report_bug(kArbitraryFileOpenError, pid); + std::cerr << "===File opened: " << path.c_str() << ", flags = " << flags << ","; + switch (flags & 3) { + case O_RDONLY: + std::cerr << "O_RDONLY"; + break; + case O_WRONLY: + std::cerr << "O_WRONLY"; + break; + case O_RDWR: + std::cerr << "O_RDWR"; + break; + default: + std::cerr << "unknown"; + } + std::cerr << "===\n"; +} + +bool has_unprintable(const std::string &value) { + for (size_t i = 0; i < value.length(); i++) { + if (value[i] & 0x80) { + return true; + } + } + return false; +} + +void inspect_for_arbitrary_file_open(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's register for the sign of arbitrary file open. + std::string path = read_string(pid, regs.rsi, kRootDirMaxLength); + if (!path.length()) { + return; + } + if (path.substr(0, kFzAbsoluteDirectory.length()) == kFzAbsoluteDirectory) { + log_file_open(path, regs.rdx, pid); + return; + } + if (path[0] == '/' && path.length() > 1) { + std::string path_absolute_topdir = path; + size_t root_dir_end = path.find('/', 1); + if (root_dir_end != std::string::npos) { + path_absolute_topdir = path.substr(0, root_dir_end); + } + if (has_unprintable(path_absolute_topdir)) { + struct stat dirstat; + if (stat(path_absolute_topdir.c_str(), &dirstat) != 0) { + log_file_open(path, regs.rdx, pid); + } + } + } +} + +int trace(std::map pids) { + unsigned long exit_status = 0; + while (!pids.empty()) { + std::vector new_pids; + + auto it = pids.begin(); + + while (it != pids.end()) { + auto pid = it->first; + auto &tracee = it->second; + int status = 0; + + int result = waitpid(pid, &status, __WALL | WNOHANG); + if (result == -1) { + it = pids.erase(it); + continue; + } + + if (result == 0) { + // Nothing to report yet. + ++it; + continue; + } + + if (WIFEXITED(status) || WIFSIGNALED(status)) { + debug_log("%d exited", pid); + it = pids.erase(it); + // Remove pid from the watchlist when it exits + g_shell_pids.erase(pid); + root_pids.erase(pid); + continue; + } + + // ptrace sets 0x80 for syscalls (with PTRACE_O_TRACESYSGOOD set). + bool is_syscall = + WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80); + int sig = 0; + if (!is_syscall) { + // Handle generic signal. + siginfo_t siginfo; + if (ptrace(PTRACE_GETSIGINFO, pid, nullptr, &siginfo) == -1) { + debug_log("ptrace(PTRACE_GETSIGINFO, %d): %s", pid, strerror(errno)); + continue; + } + sig = siginfo.si_signo; + debug_log("forwarding signal %d to %d", sig, pid); + } + + if ((status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8)))) { + debug_log("%d exiting", pid); + if (pid == g_root_pid) { + if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &exit_status) == -1) { + debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno)); + } + debug_log("got exit status from root process: %lu", exit_status); + } + + if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) { + debug_log("ptrace(PTRACE_DETACH, %d): %s", pid, strerror(errno)); + } + continue; + } + + if (WIFSTOPPED(status) && + (status >> 8 == (SIGTRAP | (PTRACE_EVENT_CLONE << 8)) || + status >> 8 == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) || + status >> 8 == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)))) { + long new_pid; + if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &new_pid) == -1) { + debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno)); + continue; + } + debug_log("forked %ld", new_pid); + new_pids.push_back(new_pid); + root_pids.emplace(new_pid, ThreadParent(pid)); + } + + if (is_syscall) { + user_regs_struct regs; + if (ptrace(PTRACE_GETREGS, pid, 0, ®s) == -1) { + debug_log("ptrace(PTRACE_GETREGS, %d): %s", pid, strerror(errno)); + continue; + } + + if (tracee.syscall_enter) { + if (regs.orig_rax == __NR_execve) { + // This is a new process. + auto parent = root_pids[pid]; + parent.ran_exec = true; + root_pids[pid] = parent; + inspect_for_injection(pid, regs); + std::string shell = get_shell(pid, regs); + if (shell != "") { + debug_log("Shell parsed: %s", shell.c_str()); + g_shell_pids.insert(std::make_pair(pid, shell)); + } + } + + inspect_dns_syscalls(pid, regs); + + if (regs.orig_rax == __NR_openat) { + // TODO(metzman): Re-enable this once we have config/flag support. + // inspect_for_arbitrary_file_open(pid, regs); + } + + if (regs.orig_rax == __NR_write && + g_shell_pids.find(pid) != g_shell_pids.end()) { + debug_log("Inspecting the `write` buffer of shell process %d.", + pid); + inspect_for_corruption(pid, regs); + } + } + + // TODO: Check for commands with invalid syntax passed to /bin/sh and + // other shells. + // TODO: It's possible the process we're fuzzing can communicate with + // another process to execute code. Our check wouldn't catch this + // currently. + tracee.syscall_enter = !tracee.syscall_enter; + } + + if (ptrace(PTRACE_SYSCALL, pid, nullptr, sig) == -1) { + debug_log("ptrace(PTRACE_SYSCALL, %d): %s", pid, strerror(errno)); + continue; + } + + ++it; + } + + for (const auto &pid : new_pids) { + pids.emplace(pid, Tracee(pid)); + } + } + return static_cast(exit_status >> 8); +} + +int main(int argc, char **argv) { + if (argc <= 1) { + fatal_log("Expecting at least one arguments, received %d", argc - 1); + } + + // Create an executable tripwire file, as programs may check for existence + // before actually calling exec. + std::ofstream tripwire(kTripWire); + tripwire.close(); + chmod(kTripWire.c_str(), 0755); + + pid_t pid = run_child(argv + 1); + + long options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK | + PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | + PTRACE_O_TRACEEXIT; + + if (ptrace(PTRACE_SEIZE, pid, nullptr, options) == -1) { + fatal_log("ptrace(PTRACE_SEIZE): %s", strerror(errno)); + } + + if (waitpid(pid, nullptr, __WALL) == -1) { + fatal_log("waitpid: %s", strerror(errno)); + } + + if (ptrace(PTRACE_SYSCALL, pid, 0, 0) == -1) { + fatal_log("ptrace(PTRACE_SYSCALL): %s", strerror(errno)); + } + + g_root_pid = pid; + std::map pids; + pids.emplace(pid, Tracee(pid)); + root_pids.emplace(pid, ThreadParent(pid)); + return trace(pids); +} diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030446345096fedc53fe7ea5826a36982a460c42 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp @@ -0,0 +1,236 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify shell injection vulnerabilities. */ + +/* POSIX */ +#include +#include + +/* Linux */ +#include +#include +#include + +#include + +#include "inspect_utils.h" + + +// Arbitrary domain name resolution. +const std::string kArbitraryDomainNameResolution = "Arbitrary domain name resolution"; + +// Global constant for one file descriptor about of a DNS socket +int kFdDns = 0; +const size_t kDnsHeaderLen = 12; + + +void inspect_for_arbitrary_dns_connect(pid_t pid, const user_regs_struct ®s) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct sockaddr_in)); + if (memory.size()) { + struct sockaddr_in * sa = reinterpret_cast(memory.data()); + if (sa->sin_family == AF_INET && htons(sa->sin_port) == 53) { + // save file descriptor for later sendmmsg + kFdDns = regs.rdi; + } + } +} + +struct DnsHeader { + uint16_t tx_id; + uint16_t flags; + uint16_t questions; + uint16_t answers; + uint16_t nameservers; + uint16_t additional; +}; + +struct DnsHeader parse_dns_header(std::vector data) { + struct DnsHeader h; + h.tx_id = (((uint16_t) data[0]) << 8) | ((uint16_t) data[1]); + h.flags = (((uint16_t) data[2]) << 8) | ((uint16_t) data[3]); + h.questions = (((uint16_t) data[4]) << 8) | ((uint16_t) data[5]); + h.answers = (((uint16_t) data[6]) << 8) | ((uint16_t) data[7]); + h.nameservers = (((uint16_t) data[8]) << 8) | ((uint16_t) data[9]); + h.additional = (((uint16_t) data[10]) << 8) | ((uint16_t) data[11]); + return h; +} + +bool dns_flags_standard_query(uint16_t flags) { + if ((flags & 0x8000) == 0) { + // Query, not response. + if (((flags & 0x7800) >> 11) == 0) { + // Opcode 0 is standard query. + if ((flags & 0x0200) == 0) { + // Message is not truncated. + if ((flags & 0x0040) == 0) { + // Z-bit reserved flag is unset. + return true; + } + } + } + } + return false; +} + +struct DnsRequest { + // Start of name in the byte vector. + size_t offset; + // End of name in the byte vector. + size_t end; + // Length of top level domain. + uint8_t tld_size; + // Number of levels/dots in domain name. + size_t nb_levels; + // DNS type like A is 1. + uint16_t dns_type; + // DNS class like IN is 1. + uint16_t dns_class; +}; + +struct DnsRequest parse_dns_request(std::vector data, size_t offset) { + struct DnsRequest r; + r.offset = offset; + r.tld_size = 0; + r.nb_levels = 0; + while(offset < data.size()) { + uint8_t rlen = uint8_t(data[offset]); + if (rlen == 0) { + offset++; + break; + } + r.nb_levels++; + offset += rlen+1; + r.tld_size = rlen; + } + if (offset <= 4 + data.size()) { + r.end = offset; + r.dns_type = (((uint16_t) data[offset]) << 8) | ((uint16_t) data[offset+1]); + r.dns_class = (((uint16_t) data[offset+2]) << 8) | ((uint16_t) data[offset+3]); + } else { + r.end = data.size(); + } + return r; +} + +void log_dns_request(struct DnsRequest r, std::vector data) { + size_t offset = r.offset; + std::cerr << "===Domain resolved: "; + while(offset < r.end) { + uint8_t rlen = uint8_t(data[offset]); + if (rlen == 0) { + break; + } + std::cerr << '.'; + for (uint8_t i = 1; i < rlen+1; i++) { + std::cerr << (char) data[offset + i]; + } + offset += rlen+1; + } + std::cerr << "===\n"; + std::cerr << "===DNS request type: " << r.dns_type << ", class: " << r.dns_class << "===\n"; +} + +void inspect_for_arbitrary_dns_pkt(std::vector data, pid_t pid) { + if (data.size() < kDnsHeaderLen + 1) { + return; + } + struct DnsHeader h = parse_dns_header(data); + if (h.questions != 1) { + return; + } + if (h.answers != 0 || h.nameservers != 0) { + return; + } + if (!dns_flags_standard_query(h.flags)) { + return; + } + + struct DnsRequest req = parse_dns_request(data, kDnsHeaderLen); + // Alert if the top level domain is only one character and + // if there is more than just the TLD. + if (req.tld_size == 1 && req.nb_levels > 1 && req.end < data.size()) { + report_bug(kArbitraryDomainNameResolution, pid); + log_dns_request(req, data); + } +} + +void inspect_for_arbitrary_dns_fdbuffer(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, regs.rdx); + if (memory.size()) { + inspect_for_arbitrary_dns_pkt(memory, pid); + } + } +} + +void inspect_for_arbitrary_dns_iov(pid_t pid, unsigned long iov) { + auto memory = read_memory(pid, iov, sizeof(struct iovec)); + if (memory.size()) { + struct iovec * iovec = reinterpret_cast(memory.data()); + memory = read_memory(pid, (unsigned long) iovec->iov_base, iovec->iov_len); + if (memory.size()) { + inspect_for_arbitrary_dns_pkt(memory, pid); + } + } +} + +void inspect_for_arbitrary_dns_sendmsg(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct msghdr)); + if (memory.size()) { + struct msghdr * msg = reinterpret_cast(memory.data()); + if (msg->msg_iovlen == 1) { + inspect_for_arbitrary_dns_iov(pid, (unsigned long) msg->msg_iov); + } + } + } +} + +void inspect_for_arbitrary_dns_sendmmsg(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct mmsghdr)); + if (memory.size()) { + struct mmsghdr * msg = reinterpret_cast(memory.data()); + if (msg->msg_hdr.msg_iovlen == 1) { + inspect_for_arbitrary_dns_iov(pid, (unsigned long) msg->msg_hdr.msg_iov); + } + } + } +} + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s) { + switch (regs.orig_rax) { + case __NR_connect: + inspect_for_arbitrary_dns_connect(pid, regs); + break; + case __NR_close: + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + // reset DNS file descriptor on close + kFdDns = 0; + } + break; + case __NR_sendmmsg: + inspect_for_arbitrary_dns_sendmmsg(pid, regs); + break; + case __NR_sendmsg: + inspect_for_arbitrary_dns_sendmsg(pid, regs); + break; + case __NR_sendto: + // fallthrough + case __NR_write: + inspect_for_arbitrary_dns_fdbuffer(pid, regs); + } +} diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h new file mode 100644 index 0000000000000000000000000000000000000000..849af4e980679c3b8cbbd875216a06ba7b909f3a --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h @@ -0,0 +1,26 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +/* Linux */ +#include + + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s); diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..713d61d757c0c135271591bf17d9a1c108f37c27 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + +/* C standard library */ +#include + +/* POSIX */ +#include + +/* Linux */ +#include + +#include +#include +#include +#include + +#include "inspect_utils.h" + +extern pid_t g_root_pid; +extern std::map root_pids; + +std::vector read_memory(pid_t pid, unsigned long long address, + size_t size) { + std::vector memory; + + for (size_t i = 0; i < size; i += sizeof(long)) { + long word = ptrace(PTRACE_PEEKTEXT, pid, address + i, 0); + if (word == -1) { + return memory; + } + + std::byte *word_bytes = reinterpret_cast(&word); + memory.insert(memory.end(), word_bytes, word_bytes + sizeof(long)); + } + + return memory; +} + +void report_bug(std::string bug_type, pid_t tid) { + // Report the bug found based on the bug code. + std::cerr << "===BUG DETECTED: " << bug_type.c_str() << "===\n"; + // Rely on sanitizers/libFuzzer to produce a stacktrace by sending SIGABRT + // to the root process. + // Note: this may not be reliable or consistent if shell injection happens + // in an async way. + // Find the thread group id, that is the pid. + pid_t pid = tid; + auto parent = root_pids[tid]; + while (!parent.ran_exec) { + // Find the first parent which ran exec syscall. + if (parent.parent_tid == g_root_pid) { + break; + } + pid = parent.parent_tid; + parent = root_pids[parent.parent_tid]; + } + tgkill(pid, tid, SIGABRT); +} diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a0737f28b1ae8de07b002f03d56fdab471674723 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h @@ -0,0 +1,39 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +#include +#include + +// Structure to know which thread id triggered the bug. +struct ThreadParent { + // Parent thread ID, ie creator. + pid_t parent_tid; + // Current thread ID ran exec to become another process. + bool ran_exec = false; + + ThreadParent() : parent_tid(0) {} + ThreadParent(pid_t tid) : parent_tid(tid) {} +}; + +std::vector read_memory(pid_t pid, unsigned long long address, + size_t size); + +void report_bug(std::string bug_type, pid_t tid); diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target.cpp b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb1b1dd0c2488c39f2d6de94f861dd1a96775b3a --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target.cpp @@ -0,0 +1,28 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* A sample target program under test, + * /tmp/tripwire or other commands will be injected into its shell command */ + +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + system(str.c_str()); + return 0; +} diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d7ef1ceef23bcb5ab7bca9a1933f6742fb054b7 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp @@ -0,0 +1,39 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#include +#include +#include +#include + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + + struct addrinfo *result = NULL; + + getaddrinfo(str.c_str(), NULL, NULL, &result); + if (result) { + freeaddrinfo(result); + } + + return 0; +} diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc55eb7f4c3e9778b378c16355a5f0fafeefbaf6 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp @@ -0,0 +1,32 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* A sample target program under test, + * /tmp/tripwire or other commands will be injected into its shell command */ + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + FILE *fp = fopen(str.c_str(), "r"); + if (fp) { + fclose(fp); + } + return 0; +} diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/vuln.dict b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..bf066ea4829f64c1138ed1021f857e2e4d8bd5fc --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/SystemSan/vuln.dict @@ -0,0 +1,3 @@ +"/tmp/tripwire" +"/fz/" +"f.z" \ No newline at end of file diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_all.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8f578084205f3ef21338021a525e1b043478302 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_all.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build all C/C++ projects. +c_project_yaml=$(find projects/ -name project.yaml -exec grep -l 'language: c' {} \;) +projs=$(echo $c_project_yaml | xargs dirname | xargs basename -a | sort) + +cd infra/experimental/chronos + +for proj in $projs; do + if [ ! -f ../../../projects/$proj/Dockerfile ]; then + # Incomplete integration. + echo "Skipping $proj as it's incomplete." + continue + fi + + echo ./build_on_cloudbuild.sh $proj c + ./build_on_cloudbuild.sh $proj c +done \ No newline at end of file diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f3f20804f4ef9e9dbedd3275286bb4353ef422d --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh @@ -0,0 +1,163 @@ +#!/bin/bash -eu +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +_PROJECT=$1 +_FUZZING_LANGUAGE=$2 +_SANITIZER=${3:-address} + +BASE=$PWD + +# Final image is either ccache or replay script, depending on which worked. +FINAL_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-${_SANITIZER} + +# Always build an image with ccache. +CCACHE_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-${_SANITIZER} + +# Step 1: build the base image +cd projects/${_PROJECT} +docker build -t gcr.io/oss-fuzz/${_PROJECT} . + + +# Step 2: create a container where `compile` has run which enables ccaching +# and also generates a replay build script. +cd ${BASE} +mkdir -p ccaches/${_PROJECT} +mkdir -p build/out/${_PROJECT} +B_START=$SECONDS + +docker container rm -f ${_PROJECT}-origin-${_SANITIZER} + +docker run \ + --env=SANITIZER=${_SANITIZER} \ + --env=CCACHE_DIR=/workspace/ccache \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --env=CAPTURE_REPLAY_SCRIPT=1 \ + --name=${_PROJECT}-origin-${_SANITIZER} \ + -v=$PWD/ccaches/${_PROJECT}/ccache:/workspace/ccache \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + gcr.io/oss-fuzz/${_PROJECT} \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && compile" +B_TIME=$(($SECONDS - $B_START)) + +# Step 3: save (commit, locally) the cached container as an image +docker container commit -c "ENV REPLAY_ENABLED=1" -c "ENV CAPTURE_REPLAY_SCRIPT=" ${_PROJECT}-origin-${_SANITIZER} $FINAL_IMAGE_NAME + +# Step 4: save the list of executables created from a vanilla build. This is +# needed for validating if replay and ccaching works. +# notes: run a shell the container with e.g. +# `docker run --entrypoint /bin/bash -it local/ossfuzz/htslib-origin-address` +executables_vanilla="$(find ./build/out/${_PROJECT} -executable -type f | sort)" + + +# Step 5: Build with replay enabled, and validate the executables are the same +# in terms of naming. +# Note that an important step is removing everything in $OUT/ which is done +# in the docker command. +R_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + --name=${_PROJECT}-origin-${_SANITIZER}-replay-recached \ + $FINAL_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +R_TIME=$(($SECONDS - $R_START)) + +# Step 6: Extract the newly build executables +executables_replay="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + +echo "Executables vanilla: " +echo ${executables_vanilla} + +echo "------------------------------------------------------" +echo "Executables replay: " +echo ${executables_replay} + +REPLAY_WORKED= + +# Step 7: match executables from vanilla builds and replay builds. +# If this step is successful, then the process can exit as it's ready. +if [[ "$executables_replay" == "$executables_vanilla" ]] +then + REPLAY_WORKED=1 + + if [ -z "${RUN_ALL+1}" ]; then + echo "${_PROJECT}: Replay worked." + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME};" + exit 0 + fi +else + echo "${_PROJECT}: Replay did not work" + R_TIME="N/A" +fi + +# Step 8: prepare Dockerfile for ccache +cp -rf ccaches/${_PROJECT}/ccache ./projects/${_PROJECT}/ccache-cache + +infra/experimental/chronos/prepare-ccache ${_PROJECT} + +cd projects/${_PROJECT} + +# Step 9: Build an image with CCache's new items (modifications are done on the +# dockerfile) +docker build -t $CCACHE_IMAGE_NAME . + +cd ${BASE} + +# Step 10: Run a `compile` with ccache's image. +# Run the ccache build +A_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --name=${_PROJECT}-origin-${_SANITIZER}-recached \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + $CCACHE_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +A_TIME=$(($SECONDS - $A_START)) + +# Step 11: extract the executables from the ccache build +executables_ccache="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + + +# Step 12: validate the ccache builds are successful +if [[ "$executables_ccache" == "$executables_vanilla" ]] +then + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME}; CCache=${A_TIME};" + + if [[ -z "${REPLAY_WORKED}" || ${R_TIME} -gt ${A_TIME} ]]; then + if [ ${R_TIME} -gt ${A_TIME} ]; then + echo "Replay was slower than ccache." + fi + + # Replay didn't work or was slower, so make the default "cached" image use the ccache one. + docker image tag \ + $CCACHE_IMAGE_NAME \ + $FINAL_IMAGE_NAME + fi + + exit 0 +else + echo "${_PROJECT}: Replay and ccaching did not work." + exit 1 +fi + diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddcb567a53961994b68f0f112cf5ccdf1f6061d5 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/build_on_cloudbuild.sh @@ -0,0 +1,26 @@ +#!/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +PROJECT=$1 +FUZZING_LANGUAGE=$2 + +gcloud builds submit "https://github.com/google/oss-fuzz" \ + --async \ + --git-source-revision=master \ + --config=cloudbuild.yaml \ + --substitutions=_PROJECT=$PROJECT,_FUZZING_LANGUAGE=$FUZZING_LANGUAGE \ + --project=oss-fuzz \ + --region=us-central1 diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/chronos.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/chronos.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd83b49095eafd5264d16195d5f80c4d204e8dbd --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/chronos.sh @@ -0,0 +1,81 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# This script records the ENV and commands needed for fuzz target recompilation. +# It intercepts bash commands to save: 1) the ENV variable values before +# building the fuzz target (`recompile_env.sh`) and 2) all subsequent bash +# commands from that point (`recompile`). Combined with Docker, this setup +# allows for recompiling the fuzz target without rebuilding the entire project. +# Usage: +# 1. Set FUZZ_TARGET (e.g., in project's Dockerfile) +# 2. Source this file before compiling the fuzz target (e.g., source chronos.sh +# at the beginning of project's build.sh). + +export START_RECORDING="false" +RECOMPILE_ENV="/usr/local/bin/recompile_env.sh" + + +# Initialize the recompile script as compile in case Chronos did not trap any +# command containing the fuzz target. +initialize_recompile_script() { + export RECOMPILE_SCRIPT="/usr/local/bin/recompile" + cp "/usr/local/bin/compile" "$RECOMPILE_SCRIPT" +} + +reset_recompile_script() { + rm "$RECOMPILE_SCRIPT" + echo "#!/bin/bash" > "$RECOMPILE_SCRIPT" + echo "source $RECOMPILE_ENV" >> "$RECOMPILE_SCRIPT" + chmod +x "$RECOMPILE_SCRIPT" +} + + +# Execute or record command for recompilation. +execute_or_record_command() { + record_command() { + echo "cd \"$(pwd)\"" >> "$RECOMPILE_SCRIPT" + echo "$@" >> "$RECOMPILE_SCRIPT" + } + + # Check if any element in the command array contains the FUZZ_TARGET. + if [[ "$BASH_COMMAND" == *"$FUZZ_TARGET"* ]]; then + export START_RECORDING="true" + # Save all environment variables, excluding read-only ones + reset_recompile_script + declare -p | grep -Ev 'declare -[^ ]*r[^ ]*' > "$RECOMPILE_ENV" + fi + + if [[ "$START_RECORDING" == "true" ]]; then + record_command "$BASH_COMMAND" + echo "Recorded execution of: $BASH_COMMAND" + fi +} + + +main() { + # Initialize. + initialize_recompile_script + + # Set up trap for DEBUG to intercept commands. + trap 'execute_or_record_command' DEBUG + + # Enable extended debugging mode + shopt -s extdebug + # Ensure trap works in subshells and functions. + set -T +} + +main diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7f584fc77bf03a7a1a71c784be1fce9c83aa5cd5 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild.yaml @@ -0,0 +1,58 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +# Supports building by way of ccache now. +# High-level steps: +# 1) Build image for project +# 2) Run an ASAN build and store ccache +# 3) Copy ccache cache to host and copy into project's OSS-Fuzz folder +# 4) Build image for project and copy ccache in, storing image as *-ofg-cache-address +# 5) Run an coverage build and store ccache +# 6) Copy ccache cache to host and copy into project's OSS-Fuzz folder +# 7) Build image for project and copy ccache in, storing image as *-ofg-cache-coverage +# TODO (David): add support for use of dedicated replay_build.sh +steps: +- name: 'gcr.io/cloud-builders/docker' + entrypoint: /bin/bash + args: + - /workspace/infra/experimental/chronos/build_cache_local.sh + - ${_PROJECT} + - ${_FUZZING_LANGUAGE} + - address + env: + - RUN_ALL=1 +- name: 'gcr.io/cloud-builders/docker' + entrypoint: /bin/bash + args: + - /workspace/infra/experimental/chronos/build_cache_local.sh + - ${_PROJECT} + - ${_FUZZING_LANGUAGE} + - coverage + env: + - RUN_ALL=1 +images: +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-address +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-coverage +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-address +- us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-coverage +timeout: 72000s # 20 hours, same as build_lib.py +logsBucket: oss-fuzz-gcb-logs +tags: +- ${_PROJECT} +- chronos +options: + pool: + name: projects/oss-fuzz/locations/us-central1/workerPools/buildpool-chronos diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e336525bedafd2843b82f45f5cc92721375362c3 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml @@ -0,0 +1,34 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +steps: +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - -t + - gcloud + - . + dir: infra/experimental/chronos +- name: 'gcloud' + args: + - infra/experimental/chronos/build_all.sh + entrypoint: /bin/bash +timeout: 1800s +serviceAccount: 'projects/oss-fuzz/serviceAccounts/llm-eval@oss-fuzz.iam.gserviceaccount.com' +options: + logging: CLOUD_LOGGING_ONLY +tags: +- chronos-all \ No newline at end of file diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh new file mode 100644 index 0000000000000000000000000000000000000000..f48b335c552a0dd5347d72dcd5d0b566e6782ab6 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/e2e-replay-build.sh @@ -0,0 +1,63 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Sample projects: simd, wt, libheif, htslib +PROJECT=liblouis +LOG=replay-${PROJECT}.txt +OUT1=replay-out-${PROJECT}-1 +OUT2=replay-out-${PROJECT}-2 +python infra/helper.py build_image --no-pull "$PROJECT" + +# AddressSanitizer. +mkdir -p build/out/${PROJECT} +echo "start" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +# Remove container name we are about to use. +docker container rm "${PROJECT}-origin-asan" + +# Build once, clean container if needed +docker run -v $PWD/build/out/${PROJECT}:/out \ + -ti --entrypoint="/bin/sh" \ + --env FUZZING_LANGUAGE=c --env SANITIZER="address" \ + --name "${PROJECT}-origin-asan" \ + "gcr.io/oss-fuzz/${PROJECT}" -c "compile" + +# Copy outs and log data +cp -rf $PWD/build/out/${PROJECT} ${OUT1} +rm -rf $PWD/build/out/${PROJECT} +ls -la $PWD/build/out/ >> ${LOG} +echo "next" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +docker commit "${PROJECT}-origin-asan" "gcr.io/oss-fuzz/${PROJECT}-ofg-cached-asan" + +# Run the replay command +docker run -v $PWD/build/out/${PROJECT}:/out \ + -e REPLAY_ENABLED=1 -ti --entrypoint="/bin/sh" \ + --env FUZZING_LANGUAGE=c --env SANITIZER="address" \ + "gcr.io/oss-fuzz/${PROJECT}-ofg-cached-asan" -c "compile" +echo "finish" >> ${LOG} +echo $(date +%Y:%m:%d:%H:%M:%S) >> ${LOG} +cp -rf $PWD/build/out/${PROJECT} ${OUT2} + +# Now match the artifacts +SUCCESS=$(infra/experimental/chronos/match_artifacts $OUT1 $OUT2) + +if [[ $SUCCESS -eq 0 ]]; then + echo "SUCCESS REPLAY" >> ${LOG} +else + echo "FAIL REPLAY" >> ${LOG} +fi diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh new file mode 100644 index 0000000000000000000000000000000000000000..39822c98ea26518efdc8cc770f983574827bddbf --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/match_artifacts.sh @@ -0,0 +1,35 @@ +#!/usr/bin/bash -eux +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +CMP1=$1 +CMP2=$2 + +for exec1 in $(find $CMP1/ -type f -executable); do + base=$(basename $exec1) + + exec2=$CMP2/${base} + if [ ! -f ${exec2} ]; then + exit 1 + fi + + comparison=$(cmp --silent $exec1 $exec2; echo $?) + if [[ $comparison -ne 0 ]]; then + exit 1 + fi +done + +exit 0 diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-ccache b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-ccache new file mode 100644 index 0000000000000000000000000000000000000000..3b0f56719680dc7cbda30a7ab2b18b61365de5bb --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-ccache @@ -0,0 +1,22 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +PROJECT=$1 +{ + echo "COPY ccache-cache/ /ccache/cache"; + echo "ENV PATH=\"/ccache/bin:\$PATH\"" +} >> "projects/$PROJECT/Dockerfile" diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild new file mode 100644 index 0000000000000000000000000000000000000000..ebb4451f18c6ffda192e2dc6d5cfd5701a3b02a1 --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/chronos/prepare-replay-rebuild @@ -0,0 +1,21 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +PROJECT=$1 +{ + echo "ENV REPLAY_ENABLED=1"; +} >> "projects/$PROJECT/Dockerfile" diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3142ae038ae6b65902623f39df75b349ff7f67b --- /dev/null +++ b/local-test-tika-delta-01/fuzz-tooling/infra/experimental/sanitizers/ExecSan/README.md @@ -0,0 +1,3 @@ +# Moved + +This has moved to . diff --git a/local-test-tika-delta-01/fuzz-tooling/infra/tools/hold_back_images.py b/local-test-tika-delta-01/fuzz-tooling/infra/tools/hold_back_images.py new file mode 100644 index 0000000000000000000000000000000000000000..659eb5debc28f0bbfbfcd34d863c88571b89c9f5 --- /dev/null +++ b/local-test-tika-delta-01/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-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/GLDAS_CLM10SUBP_3H.A19790202.0000.001.grb b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/GLDAS_CLM10SUBP_3H.A19790202.0000.001.grb new file mode 100644 index 0000000000000000000000000000000000000000..dff994c888f5b02a0e0ff932c104e3f684130b05 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/GLDAS_CLM10SUBP_3H.A19790202.0000.001.grb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60c92cc56040d963efcb94447c2f7085abc5d8de462af544489fef8b96b49c81 +size 1362900 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/egyl03.gdas.200811.00Z.grb2 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/egyl03.gdas.200811.00Z.grb2 new file mode 100644 index 0000000000000000000000000000000000000000..f028b7a6e4278b2d99148d399943a0c61d2b1cdb --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/egyl03.gdas.200811.00Z.grb2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bfcab9666d9d27155c8ce9fcfcce8a62bab6083dcb1ab1861be28e333e8fad5 +size 3447292 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/gdas1.forecmwf.2014062612.grib2 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/gdas1.forecmwf.2014062612.grib2 new file mode 100644 index 0000000000000000000000000000000000000000..5aad6d8f9296e7a16449dce8e6b194f9eee9154f --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/gdas1.forecmwf.2014062612.grib2 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4beeaa512242e778e196abd30b2931e398d45f4a551f90130c89d9a212053e4 +size 2489194 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/sresa1b_ncar_ccsm3_0_run1_200001.nc b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/sresa1b_ncar_ccsm3_0_run1_200001.nc new file mode 100644 index 0000000000000000000000000000000000000000..4b6338fe11b086710877544dea3d3afe0f258853 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/sresa1b_ncar_ccsm3_0_run1_200001.nc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c2047ee329654f3bebf0a4b0d99eada50f1183728a3c7c129b0bc50d404511b +size 2767916 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.hdf b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.hdf new file mode 100644 index 0000000000000000000000000000000000000000..fadf4e53852193f43d69c12183bb832381937741 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.hdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ceda2cac5c01e87a0c21c06d755eb38133b05056637902da37f9c220016df36 +size 542529 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.he5 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.he5 new file mode 100644 index 0000000000000000000000000000000000000000..fe6c0abbe1cabf31de888c4b18852dbf3f958699 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parser-scientific-module/src/test/resources/test-documents/test.he5 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0d4b6ef38aaf26f982edac5662658f599f00f592182b82d2cd31555a7fc9a5b +size 1396916 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parsers-extended-integration-tests/src/test/resources/test-documents/testOCR.jpg b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parsers-extended-integration-tests/src/test/resources/test-documents/testOCR.jpg new file mode 100644 index 0000000000000000000000000000000000000000..86e51d5126258e425aa6eca19e0501fa16e14e56 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parsers-extended-integration-tests/src/test/resources/test-documents/testOCR.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4663ae52f0508d4ea47736459672b974493ea494a3cacdc6746ac7278dd5c5d0 +size 3408 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parsers-extended-integration-tests/src/test/resources/test-documents/testOCR.png b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parsers-extended-integration-tests/src/test/resources/test-documents/testOCR.png new file mode 100644 index 0000000000000000000000000000000000000000..98c62341732b6b02feba881f20fdc630e2fb04fe --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-extended/tika-parsers-extended-integration-tests/src/test/resources/test-documents/testOCR.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e83cdf28f8db7eb3b3f5a59fcef9d7ab89ad0e22bfeae285d52fa5fa4ae22c1e +size 28245 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-dl/src/test/resources/org/apache/tika/dl/imagerec/cat.jpg b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-dl/src/test/resources/org/apache/tika/dl/imagerec/cat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..6c916846516ac32c2505d136bc70201fec67c322 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-dl/src/test/resources/org/apache/tika/dl/imagerec/cat.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:643dbb91a62b47947d320a588aa9d837640cc9baf3fe00010c9fe52b3fef8a1a +size 7686 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-dl/src/test/resources/org/apache/tika/dl/imagerec/lion.jpg b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-dl/src/test/resources/org/apache/tika/dl/imagerec/lion.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5f7cb3390f215e0bc6c6de500bc10f12507d17ff --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-dl/src/test/resources/org/apache/tika/dl/imagerec/lion.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57f071879b67ea97b8bcfcc2db15815358440c8a01bebefae773165afb3ddaea +size 44441 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-parser-nlp-module/src/test/resources/test-documents/testJournalParser.pdf b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-parser-nlp-module/src/test/resources/test-documents/testJournalParser.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a6d22dbf78ba9fd3ae1120cb5a1acdc3f3ef90fc --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-parser-nlp-module/src/test/resources/test-documents/testJournalParser.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:105f9d5fa72021d79c8382de941f3ac42cced7758735b276cc401eb451b7d515 +size 985125 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ShortAudioSampleFrench.mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ShortAudioSampleFrench.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..194d13afe3f8e6ef939c9685eb5e2fe2bdae7176 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ShortAudioSampleFrench.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7be8ec540eb26410cfa3fd3b081888504087f2801780cf2309528b3608f75fe0 +size 25861 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/de-DE_(We_Are_At_School_x2).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/de-DE_(We_Are_At_School_x2).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..7614d1f729714d5b7e785a8545c45413df5e7304 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/de-DE_(We_Are_At_School_x2).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:99048c9cedd7a156fe47272ba65d70b7e6e2350ed610c006a20204c65de0fb0c +size 38547 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-AU_(A_Little_Bottle_Of_Water).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-AU_(A_Little_Bottle_Of_Water).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..7cedb249e412465cc2cc1639715f58a0c33f0031 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-AU_(A_Little_Bottle_Of_Water).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c53de699fd87de1162f95449a0e3201e7bfa7dac4e0f3ffba27e027b9e06b0ee +size 33365 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-GB_(A_Little_Bottle_Of_Water).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-GB_(A_Little_Bottle_Of_Water).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..da1d36a45d23ff359f21c5e14788e478e654b32b --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-GB_(A_Little_Bottle_Of_Water).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8239c1e2038a926ef4fa10c01e26ae290bf2d563f4eff6becbe61a46eff5f224 +size 35872 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-US_(A_Little_Bottle_Of_Water).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-US_(A_Little_Bottle_Of_Water).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..29ef09cde64138d60736fd4c863f49ff5a894243 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-US_(A_Little_Bottle_Of_Water).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3cb0e5f24e7d2a9ae2af504bd9899e4a4131cdcf4db8915c39d929f8613441b +size 29603 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-US_(Hi).mp4 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-US_(Hi).mp4 new file mode 100644 index 0000000000000000000000000000000000000000..7948415bd5bc136e7c4edd67f406003e42d37a4d --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/en-US_(Hi).mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2253aeab3de56fd5e2164a15f653e88b06e58b02c36e0197823dc71b8bb48ce3 +size 21739 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/it-IT_(We_Are_Having_Class_x2).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/it-IT_(We_Are_Having_Class_x2).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..2a821475cc40406b58a234e9f426eb8f710f3b71 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/it-IT_(We_Are_Having_Class_x2).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65ff8307feceb4d3430b8537c6aab7a75aa75706e7df84a5673a93f53c9ce5f8 +size 42219 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ja-JP_(We_Are_At_School).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ja-JP_(We_Are_At_School).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..2f32c6aa62043e1d7cc60b6af50998684f969b39 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ja-JP_(We_Are_At_School).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5fc709c3e7d80d2d01b080f5980b48ed45c9d017599362dbec996b30a7ea9ec +size 21699 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ko-KR_(Annyeonghaseyo).mp4 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ko-KR_(Annyeonghaseyo).mp4 new file mode 100644 index 0000000000000000000000000000000000000000..fdc794e00f7dbf9535e1ea154ce7ae1f83c09c2c --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ko-KR_(Annyeonghaseyo).mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e65e147f66f528960df67eb3395ba0f60be5049680127ccd8dad517ae0389c46 +size 144151 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ko-KR_(We_Are_Having_Class_x2).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ko-KR_(We_Are_Having_Class_x2).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..8a92ebc73571182d97bfd1410c87e7baa4cc6135 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/ko-KR_(We_Are_Having_Class_x2).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee000d4a2186ea280da26507c80f88d2d723ef2baaf40b2a6b01175b2cfd268f +size 66843 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/pt-BR_(We_Are_At_School).mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/pt-BR_(We_Are_At_School).mp3 new file mode 100644 index 0000000000000000000000000000000000000000..9501733ee8ae101f3daccf92858595b87c421ba1 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-ml/tika-transcribe-aws/src/test/resources/test-documents/pt-BR_(We_Are_At_School).mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38770cbf648e879442616cbba477c74ff49f856192f40d69e01358282d97d4ae +size 29043 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-audiovideo-module/src/test/resources/test-documents/testMP3id3v2.mp3 b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-audiovideo-module/src/test/resources/test-documents/testMP3id3v2.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d3c0be0d959d5efee98dedb56e35b1b0976863ba --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-audiovideo-module/src/test/resources/test-documents/testMP3id3v2.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b99c497f4962c072413066b08e55849f113f7441e759c2052cb4cd74e6aae520 +size 39577 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-audiovideo-module/src/test/resources/test-documents/testWAV.wav b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-audiovideo-module/src/test/resources/test-documents/testWAV.wav new file mode 100644 index 0000000000000000000000000000000000000000..d50f737e4d9ed14041e586f30e3cdbcff3dddaa0 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-audiovideo-module/src/test/resources/test-documents/testWAV.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be314759f29249b0ad5fb0437fa099d9820da65efc055397ffc8a552325ae9b5 +size 3884 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/test-columnar.sas7bdat b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/test-columnar.sas7bdat new file mode 100644 index 0000000000000000000000000000000000000000..408c15d5a56f2a689e7277de1a7bec686140dae7 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/test-columnar.sas7bdat @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39c3ab824a23abc5b9fe832d4c7c5978b7d41cc8b0bb2da289714e3400430ea0 +size 131072 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/testLinux-ppc-32be b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/testLinux-ppc-32be new file mode 100644 index 0000000000000000000000000000000000000000..5f50b97395dbd00116d71f06ffdbac59a88b5757 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-code-module/src/test/resources/test-documents/testLinux-ppc-32be @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fcd5fb925bec5796870bbf864388632c130d3c8d79295c59ef74fbb1d7765fd +size 248480 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testJournalParser.pdf b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testJournalParser.pdf new file mode 100644 index 0000000000000000000000000000000000000000..a6d22dbf78ba9fd3ae1120cb5a1acdc3f3ef90fc --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testJournalParser.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:105f9d5fa72021d79c8382de941f3ac42cced7758735b276cc401eb451b7d515 +size 985125 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDFFileEmbInAnnotation_noContents.pdf b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDFFileEmbInAnnotation_noContents.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4cca3794429b4252ca088bfdeaa91fdc9be4c241 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDFFileEmbInAnnotation_noContents.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a667c1515735cabccb2d0edeee6cc47b037f8a2dc26a02a8486e02b229e800fa +size 198342 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_bad_page_303226.pdf b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_bad_page_303226.pdf new file mode 100644 index 0000000000000000000000000000000000000000..239a8878eb38201c6141d0dd2a9da060ae2410f9 --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_bad_page_303226.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da14d24dd22effebec987312abf0312750bdbbaf93f54c9aef3b9ec7041e40ba +size 138027 diff --git a/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_childAttachments.pdf b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_childAttachments.pdf new file mode 100644 index 0000000000000000000000000000000000000000..be49da93338e426bf546d4088f16e893974a973a --- /dev/null +++ b/local-test-tika-delta-02/afc-tika/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/resources/test-documents/testPDF_childAttachments.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9396d203b78cc367d8879c867f45de0f8ea16e15ecd5831e570240aba081083e +size 2318262 diff --git a/local-test-tika-delta-02/fuzz-tooling/docs/images/freetype_coverage_2.png b/local-test-tika-delta-02/fuzz-tooling/docs/images/freetype_coverage_2.png new file mode 100644 index 0000000000000000000000000000000000000000..e1a7e94c6383d039cb49a22db4ea892d8d6f340f --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/docs/images/freetype_coverage_2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aed63942130ebabb9a73071997b9265a5a6c3d1f27ee1d4616a910dd8f814920 +size 35094 diff --git a/local-test-tika-delta-02/fuzz-tooling/docs/images/pcre2_testcase.png b/local-test-tika-delta-02/fuzz-tooling/docs/images/pcre2_testcase.png new file mode 100644 index 0000000000000000000000000000000000000000..4556d625e2b5837952dede8e82208f9205aa91ed --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/docs/images/pcre2_testcase.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:43f0d12f5c749ff48a16fcbc462131d40a62c9d0bc65ee97e56c13ff605d9e6b +size 204561 diff --git a/local-test-tika-delta-02/fuzz-tooling/docs/images/punycode.png b/local-test-tika-delta-02/fuzz-tooling/docs/images/punycode.png new file mode 100644 index 0000000000000000000000000000000000000000..0522182ec88f5d9583370517cfdf934dfb4335e5 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/docs/images/punycode.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6938c5ed85c62639b5768842b05d73c93cfc50f31311c4857dfefb548870db3 +size 314214