diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..580cd305b56be53270602277b76a21ea664e84b4 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile @@ -0,0 +1,26 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +# Copy/Run this now to make the cache more resilient. +COPY fuzzbench_install_dependencies /usr/local/bin +RUN fuzzbench_install_dependencies + +ENV OSS_FUZZ_ON_DEMAND=1 + +COPY fuzzbench_build fuzzbench_run_fuzzer fuzzbench_measure /usr/local/bin/ diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_install_dependencies b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_install_dependencies new file mode 100644 index 0000000000000000000000000000000000000000..94c0b8764805a90e348eed66d70816c723e42297 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_install_dependencies @@ -0,0 +1,22 @@ +#! /bin/bash -eux +# 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. +# +################################################################################ + +apt-get update && apt-get install -y gcc gfortran python-dev libopenblas-dev liblapack-dev cython libpq-dev +wget -O /tmp/requirements.txt https://raw.githubusercontent.com/google/fuzzbench/master/requirements.txt +pip3 install pip --upgrade +CFLAGS= CXXFLAGS= pip3 install -r /tmp/requirements.txt +rm /tmp/requirements.txt diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-javascript/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-javascript/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1f5b27da6c1607355ce2296bda4fd15ec2d8b129 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-javascript/Dockerfile @@ -0,0 +1,20 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +RUN install_javascript.sh diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-jvm/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-jvm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6ae5da8afd452877d486cd9c91aaca9cf2c655d8 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-jvm/Dockerfile @@ -0,0 +1,68 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} AS base + +ENV JAVA_HOME /usr/lib/jvm/java-17-openjdk-amd64 +ENV JAVA_15_HOME /usr/lib/jvm/java-15-openjdk-amd64 +ENV JVM_LD_LIBRARY_PATH $JAVA_HOME/lib/server +ENV PATH $PATH:$JAVA_HOME/bin +ENV JAZZER_API_PATH "/usr/local/lib/jazzer_api_deploy.jar" +ENV JAZZER_JUNIT_PATH "/usr/local/bin/jazzer_junit.jar" + +RUN install_java.sh + +RUN chmod 777 /usr/local/bin && chmod 777 /usr/local/lib + +FROM base AS builder +RUN useradd -m jazzer_user + +USER jazzer_user + +WORKDIR $SRC + +RUN git clone https://github.com/aixcc-finals/jazzer-aixcc jazzer && \ + cd jazzer && \ + git checkout 43791565a765b854b537d878c9cab757ff1f2140 + +WORKDIR $SRC/jazzer + +RUN echo "build --java_runtime_version=local_jdk_17" >> .bazelrc \ + && echo "build --cxxopt=-stdlib=libc++" >> .bazelrc \ + && echo "build --linkopt=-lc++" >> .bazelrc + +RUN bazel build \ + //src/main/java/com/code_intelligence/jazzer:jazzer_standalone_deploy.jar \ + //deploy:jazzer-api \ + //deploy:jazzer-junit \ + //launcher:jazzer + +RUN cp $(bazel cquery --output=files //src/main/java/com/code_intelligence/jazzer:jazzer_standalone_deploy.jar) /usr/local/bin/jazzer_agent_deploy.jar && \ + cp $(bazel cquery --output=files //launcher:jazzer) /usr/local/bin/jazzer_driver && \ + cp $(bazel cquery --output=files //deploy:jazzer-api) $JAZZER_API_PATH && \ + cp $(bazel cquery --output=files //deploy:jazzer-junit) $JAZZER_JUNIT_PATH + +FROM base AS final + +COPY --from=builder /usr/local/bin/jazzer_agent_deploy.jar /usr/local/bin/jazzer_agent_deploy.jar +COPY --from=builder /usr/local/bin/jazzer_driver /usr/local/bin/jazzer_driver +COPY --from=builder $JAZZER_API_PATH $JAZZER_API_PATH +COPY --from=builder $JAZZER_JUNIT_PATH $JAZZER_JUNIT_PATH + +RUN chmod 755 /usr/local/bin && chmod 755 /usr/local/lib + +WORKDIR $SRC diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-python/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-python/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..df40041305a859953acd669a74095fb2d9a7b249 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-python/Dockerfile @@ -0,0 +1,20 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +RUN install_python.sh diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-ruby/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-ruby/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b478d07b516a7d7bbb064db949e0bf7acee08c47 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-ruby/Dockerfile @@ -0,0 +1,56 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +RUN git clone https://github.com/trailofbits/ruzzy.git $SRC/ruzzy + +RUN install_ruby.sh +ENV PATH="$PATH:/usr/local/rvm/rubies/ruby-3.3.1/bin" + +RUN gem update --system 3.5.11 + +# Install ruzzy +WORKDIR $SRC/ruzzy + +# The MAKE variable allows overwriting the make command at runtime. This forces the +# Ruby C extension to respect ENV variables when compiling, like CC, CFLAGS, etc. +ENV MAKE="make --environment-overrides V=1" + +RUN CC="clang" \ +CXX="clang++" \ +LDSHARED="clang -shared" \ +LDSHAREDXX="clang++ -shared" \ +gem build + +RUN MAKE="make --environment-overrides V=1" \ +CC="clang" \ +CXX="clang++" \ +LDSHARED="clang -shared" \ +LDSHAREDXX="clang++ -shared" \ +CXXFLAGS="-fPIC" \ +CFLAGS="-fPIC" \ +RUZZY_DEBUG=1 gem install --install-dir /install/ruzzy --development --verbose ruzzy-*.gem + + +ENV LDSHARED="$CC -shared" +ENV LDSHAREDXX="$CXX -shared" + +ENV GEM_HOME="$OUT/fuzz-gem" +ENV GEM_PATH="/install/ruzzy" + +COPY ruzzy-build /usr/bin/ruzzy-build diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-ruby/ruzzy-build b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-ruby/ruzzy-build new file mode 100644 index 0000000000000000000000000000000000000000..459e909905d57466667a49ed4e5291798e1715f1 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-ruby/ruzzy-build @@ -0,0 +1,28 @@ +#!/usr/bin/env bash -e +# 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. +# +################################################################################ + +fuzz_target=$(basename "$1") +echo "BASENAME: $fuzz_target ---" +harness_sh=${fuzz_target::-3} + +cp $1 $OUT/$fuzz_target + +echo """#!/usr/bin/env bash + +ruzzy $fuzz_target +""" > $OUT/$harness_sh +chmod +x $OUT/$harness_sh diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-rust/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-rust/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..899adc9cff849fa96b422bba682c300ec04af5c0 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder-rust/Dockerfile @@ -0,0 +1,37 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +ENV CARGO_HOME=/rust +ENV RUSTUP_HOME=/rust/rustup +ENV PATH=$PATH:/rust/bin +# Set up custom environment variable for source code copy for coverage reports +ENV OSSFUZZ_RUSTPATH /rust + +# Force rustup to ignore `rust-toolchain` and `rust-toolchain.toml` files by +# manually specifying what toolchain to use. Note that this environment variable +# is additionally used by `install_rust.sh` as the toolchain to install. +# cf https://rust-lang.github.io/rustup/overrides.html +ENV RUSTUP_TOOLCHAIN nightly-2024-07-12 + +# Configure the linker used by default for x86_64 linux to be `clang` instead of +# rustc's default of `cc` which is able to find custom-built libraries like +# `libc++` by default more easily. +ENV CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER clang + +RUN install_rust.sh diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..59b24d7a6cd9c4102df408d45dd71def7711c6f3 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/Dockerfile @@ -0,0 +1,213 @@ +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-clang:${IMG_TAG} + +COPY install_deps.sh / +RUN /install_deps.sh && rm /install_deps.sh + +# Build and install latest Python 3.10. +ENV PYTHON_VERSION 3.10.14 +RUN PYTHON_DEPS="\ + zlib1g-dev \ + libncurses5-dev \ + libgdbm-dev \ + libnss3-dev \ + libssl-dev \ + libsqlite3-dev \ + libreadline-dev \ + libffi-dev \ + libbz2-dev \ + liblzma-dev" && \ + unset CFLAGS CXXFLAGS && \ + apt-get install -y $PYTHON_DEPS && \ + cd /tmp && \ + curl -O https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz && \ + tar -xvf Python-$PYTHON_VERSION.tar.xz && \ + cd Python-$PYTHON_VERSION && \ + ./configure --enable-optimizations --enable-shared && \ + make -j$(nproc) install && \ + ldconfig && \ + ln -s /usr/local/bin/python3 /usr/local/bin/python && \ + cd .. && \ + rm -r /tmp/Python-$PYTHON_VERSION.tar.xz /tmp/Python-$PYTHON_VERSION && \ + rm -rf /usr/local/lib/python${PYTHON_VERSION%.*}/test && \ + python3 -m ensurepip && \ + python3 -m pip install --upgrade pip && \ + apt-get remove -y $PYTHON_DEPS # https://github.com/google/oss-fuzz/issues/3888 + + +ENV CCACHE_VERSION 4.10.2 +RUN cd /tmp && curl -OL https://github.com/ccache/ccache/releases/download/v$CCACHE_VERSION/ccache-$CCACHE_VERSION.tar.xz && \ + tar -xvf ccache-$CCACHE_VERSION.tar.xz && cd ccache-$CCACHE_VERSION && \ + mkdir build && cd build && \ + export LDFLAGS='-lpthread' && \ + cmake -D CMAKE_BUILD_TYPE=Release .. && \ + make -j && make install && \ + rm -rf /tmp/ccache-$CCACHE_VERSION /tmp/ccache-$CCACHE_VERSION.tar.xz + +# Install six for Bazel rules. +RUN unset CFLAGS CXXFLAGS && pip3 install -v --no-cache-dir \ + six==1.15.0 && rm -rf /tmp/* + +# Install Bazel through Bazelisk, which automatically fetches the latest Bazel version. +ENV BAZELISK_VERSION 1.9.0 +RUN curl -L https://github.com/bazelbuild/bazelisk/releases/download/v$BAZELISK_VERSION/bazelisk-linux-amd64 -o /usr/local/bin/bazel && \ + chmod +x /usr/local/bin/bazel + +# Default build flags for various sanitizers. +ENV SANITIZER_FLAGS_address "-fsanitize=address -fsanitize-address-use-after-scope" +ENV SANITIZER_FLAGS_hwaddress "-fsanitize=hwaddress -fuse-ld=lld -Wno-unused-command-line-argument" + +# Set of '-fsanitize' flags matches '-fno-sanitize-recover' + 'unsigned-integer-overflow'. +ENV SANITIZER_FLAGS_undefined "-fsanitize=array-bounds,bool,builtin,enum,function,integer-divide-by-zero,null,object-size,return,returns-nonnull-attribute,shift,signed-integer-overflow,unsigned-integer-overflow,unreachable,vla-bound,vptr -fno-sanitize-recover=array-bounds,bool,builtin,enum,function,integer-divide-by-zero,null,object-size,return,returns-nonnull-attribute,shift,signed-integer-overflow,unreachable,vla-bound,vptr" + +# Don't include "function" since it is unsupported on aarch64. +ENV SANITIZER_FLAGS_undefined_aarch64 "-fsanitize=array-bounds,bool,builtin,enum,integer-divide-by-zero,null,object-size,return,returns-nonnull-attribute,shift,signed-integer-overflow,unsigned-integer-overflow,unreachable,vla-bound,vptr -fno-sanitize-recover=array-bounds,bool,builtin,enum,integer-divide-by-zero,null,object-size,return,returns-nonnull-attribute,shift,signed-integer-overflow,unreachable,vla-bound,vptr" + +ENV SANITIZER_FLAGS_memory "-fsanitize=memory -fsanitize-memory-track-origins" + +ENV SANITIZER_FLAGS_thread "-fsanitize=thread" + +ENV SANITIZER_FLAGS_introspector "-O0 -flto -fno-inline-functions -fuse-ld=gold -Wno-unused-command-line-argument" + +# Do not use any sanitizers in the coverage build. +ENV SANITIZER_FLAGS_coverage "" + +# We use unsigned-integer-overflow as an additional coverage signal and have to +# suppress error messages. See https://github.com/google/oss-fuzz/issues/910. +ENV UBSAN_OPTIONS="silence_unsigned_overflow=1" + +# To suppress warnings from binaries running during compilation. +ENV DFSAN_OPTIONS='warn_unimplemented=0' + +# Default build flags for coverage feedback. +ENV COVERAGE_FLAGS="-fsanitize=fuzzer-no-link" + +# Use '-Wno-unused-command-line-argument' to suppress "warning: -ldl: 'linker' input unused" +# messages which are treated as errors by some projects. +ENV COVERAGE_FLAGS_coverage "-fprofile-instr-generate -fcoverage-mapping -pthread -Wl,--no-as-needed -Wl,-ldl -Wl,-lm -Wno-unused-command-line-argument" + +# Default sanitizer, fuzzing engine and architecture to use. +ENV SANITIZER="address" +ENV FUZZING_ENGINE="libfuzzer" +ENV ARCHITECTURE="x86_64" + +# DEPRECATED - NEW CODE SHOULD NOT USE THIS. OLD CODE SHOULD STOP. Please use +# LIB_FUZZING_ENGINE instead. +# Path to fuzzing engine library to support some old users of +# LIB_FUZZING_ENGINE. +ENV LIB_FUZZING_ENGINE_DEPRECATED="/usr/lib/libFuzzingEngine.a" + +# Argument passed to compiler to link against fuzzing engine. +# Defaults to the path, but is "-fsanitize=fuzzer" in libFuzzer builds. +ENV LIB_FUZZING_ENGINE="/usr/lib/libFuzzingEngine.a" + +# TODO: remove after tpm2 catchup. +ENV FUZZER_LDFLAGS "" + +WORKDIR $SRC + +RUN git clone https://github.com/AFLplusplus/AFLplusplus.git aflplusplus && \ + cd aflplusplus && \ + git checkout daaefcddc063b356018c29027494a00bcfc3e240 && \ + wget --no-check-certificate -O oss.sh https://raw.githubusercontent.com/vanhauser-thc/binary_blobs/master/oss.sh && \ + rm -rf .git && \ + chmod 755 oss.sh + +# Do precompiles before copying other scripts for better cache efficiency. +COPY precompile_afl /usr/local/bin/ +RUN precompile_afl + +RUN cd $SRC && \ + curl -L -O https://github.com/google/honggfuzz/archive/oss-fuzz.tar.gz && \ + mkdir honggfuzz && \ + cd honggfuzz && \ + tar -xz --strip-components=1 -f $SRC/oss-fuzz.tar.gz && \ + rm -rf examples $SRC/oss-fuzz.tar.gz + + +COPY precompile_honggfuzz /usr/local/bin/ +RUN precompile_honggfuzz + +RUN cd $SRC && \ + git clone https://github.com/google/fuzztest && \ + cd fuzztest && \ + git checkout a37d133f714395cabc20dd930969a889495c9f53 && \ + rm -rf .git + +ENV CENTIPEDE_BIN_DIR=$SRC/fuzztest/bazel-bin +COPY precompile_centipede /usr/local/bin/ +RUN precompile_centipede + +COPY sanitizers /usr/local/lib/sanitizers + +COPY bazel_build_fuzz_tests \ + cargo \ + compile \ + compile_afl \ + compile_centipede \ + compile_honggfuzz \ + compile_fuzztests.sh \ + compile_go_fuzzer \ + compile_javascript_fuzzer \ + compile_libfuzzer \ + compile_native_go_fuzzer \ + compile_python_fuzzer \ + debug_afl \ + # Go, JavaScript, Java, Python, Rust, and Swift installation scripts. + install_go.sh \ + install_javascript.sh \ + install_java.sh \ + install_python.sh \ + install_ruby.sh \ + install_rust.sh \ + install_swift.sh \ + python_coverage_helper.py \ + bash_parser.py \ + srcmap \ + write_labels.py \ + /usr/local/bin/ + +# TODO: Build this as part of a multi-stage build. +ADD https://commondatastorage.googleapis.com/clusterfuzz-builds/jcc/clang-jcc /usr/local/bin/ +ADD https://commondatastorage.googleapis.com/clusterfuzz-builds/jcc/clang++-jcc /usr/local/bin +ADD https://commondatastorage.googleapis.com/clusterfuzz-builds/jcc/clang-jcc2 /usr/local/bin/ +ADD https://commondatastorage.googleapis.com/clusterfuzz-builds/jcc/clang++-jcc2 /usr/local/bin +RUN chmod +x /usr/local/bin/clang-jcc /usr/local/bin/clang++-jcc /usr/local/bin/clang-jcc2 /usr/local/bin/clang++-jcc2 + +COPY llvmsymbol.diff $SRC +COPY detect_repo.py /opt/cifuzz/ +COPY bazel.bazelrc /root/.bazelrc + +# Set up ccache binary and cache directory. +# /ccache/bin will contain the compiler wrappers, and /ccache/cache will +# contain the actual cache, which can be saved. +# To use this, set PATH=/ccache/bin:$PATH. +RUN mkdir -p /ccache/bin && mkdir -p /ccache/cache && \ + ln -s /usr/local/bin/ccache /ccache/bin/clang && \ + ln -s /usr/local/bin/ccache /ccache/bin/clang++ && \ + ln -s /usr/local/bin/ccache /ccache/bin/clang-jcc && \ + ln -s /usr/local/bin/ccache /ccache/bin/clang++-jcc +ENV CCACHE_DIR /ccache/cache + +# Don't check that the compiler is the same, so we can switch between jcc and +# clang under the hood and re-use the same build cache. +ENV CCACHE_COMPILERCHECK none +ENV CCACHE_COMPILERTYPE clang + +CMD ["compile"] diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/README.md b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4e94bb0888c92f094cfefea3b9bf70d41bb8db22 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/README.md @@ -0,0 +1,83 @@ +# base-builder +> Abstract base image for project builders. + +Every project image supports multiple commands that can be invoked through docker after the image is built: + +
+docker run --rm -ti gcr.io/oss-fuzz/$project <command> <arguments...>
+
+ +# Supported Commands + +| Command | Description | +|---------|-------------| +| `compile` (default) | build all fuzz targets +| `/bin/bash` | drop into shell, execute `compile` script to start build. + +# Build Configuration + +A single build image can build same set of fuzzers in many configurations. +The configuration is picked through one or more environment variables. + +| Env Variable | Description +| ------------- | -------- +| `$SANITIZER ("address")` | Specifies predefined sanitizer configuration to use. `address` or `memory` or `undefined`. +| `$SANITIZER_FLAGS` | Specify compiler sanitizer flags directly. Overrides `$SANITIZER`. +| `$COVERAGE_FLAGS` | Specify compiler flags to use for fuzzer feedback coverage. +| `$BUILD_UID` | User id to use while building fuzzers. + +## Examples + +- *building sqlite3 fuzzer with UBSan (`SANITIZER=undefined`):* + + +
+docker run --rm -ti -e SANITIZER=undefined gcr.io/oss-fuzz/sqlite3
+
+ + +# Image Files Layout + +| Location|Env| Description | +|---------| -------- | ---------- | +| `/out/` | `$OUT` | Directory to store build artifacts (fuzz targets, dictionaries, options files, seed corpus archives). | +| `/src/` | `$SRC` | Directory to checkout source files | +| `/work/`| `$WORK` | Directory for storing intermediate files | +| `/usr/lib/libFuzzingEngine.a` | `$LIB_FUZZING_ENGINE` | Location of prebuilt fuzzing engine library (e.g. libFuzzer) that needs to be linked with all fuzz targets. + +While files layout is fixed within a container, the environment variables are +provided to be able to write retargetable scripts. + + +## Compiler Flags + +You *must* use special compiler flags to build your project and fuzz targets. +These flags are provided in following environment variables: + +| Env Variable | Description +| ------------- | -------- +| `$CC` | The C compiler binary. +| `$CXX`, `$CCC` | The C++ compiler binary. +| `$CFLAGS` | C compiler flags. +| `$CXXFLAGS` | C++ compiler flags. + +Most well-crafted build scripts will automatically use these variables. If not, +pass them manually to the build tool. + + +# Child Image Interface + +## Sources + +Child image has to checkout all sources that it needs to compile fuzz targets into +`$SRC` directory. When the image is executed, a directory could be mounted on top +of these with local checkouts using +`docker run -v $HOME/my_project:/src/my_project ...`. + +## Other Required Files + +Following files have to be added by child images: + +| File Location | Description | +| ------------- | ----------- | +| `$SRC/build.sh` | build script to build the project and its fuzz targets | diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bash_parser.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bash_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..1d816992d009774c01a438023beb20c15162b7ea --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bash_parser.py @@ -0,0 +1,235 @@ +#!/usr/bin/python3 +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import sys + +from glob import glob + +import bashlex + + +def find_all_bash_scripts_in_src(): + """Finds all bash scripts that exist in SRC/. This is used to idenfiy scripts + that may be needed for reading during the AST parsing. This is the case + when a given build script calls another build script, then we need to + read those.""" + all_local_scripts = [ + y for x in os.walk('/src/') for y in glob(os.path.join(x[0], '*.sh')) + ] + scripts_we_care_about = [] + to_ignore = {'aflplusplus', 'honggfuzz', '/fuzztest', '/centipede'} + for s in all_local_scripts: + if any([x for x in to_ignore if x in s]): + continue + scripts_we_care_about.append(s) + + print(scripts_we_care_about) + return scripts_we_care_about + + +def should_discard_command(ast_tree) -> bool: + """Returns True if the command shuold be avoided, otherwise False""" + try: + first_word = ast_tree.parts[0].word + except: # pylint: disable=bare-except + return False + + if ('cmake' in first_word and + any('--build' in part.word for part in ast_tree.parts)): + return False + + cmds_to_avoid_replaying = { + 'configure', 'autoheader', 'autoconf', 'autoreconf', 'cmake', 'autogen.sh' + } + if any([cmd for cmd in cmds_to_avoid_replaying if cmd in first_word]): + return True + + # Avoid all "make clean" calls. We dont want to erase previously build + # files. + try: + second_word = ast_tree.parts[1].word + except: # pylint: disable=bare-except + return False + if 'make' in first_word and 'clean' in second_word: + return True + + # No match was found to commands we dont want to build. There is no + # indication we shuold avoid. + return False + + +def is_local_redirection(ast_node, all_local_scripts): + """Return the list of scripts corresponding to the command, in case + the command is an execution of a local script.""" + # print("Checking") + + # Capture local script called with ./random/path/build.sh + + if len(ast_node.parts) >= 2: + try: + ast_node.parts[0].word + except: + return [] + if ast_node.parts[0].word == '.': + suffixes_matching = [] + #print(ast_node.parts[1].word) + for bash_script in all_local_scripts: + #print("- %s"%(bash_script)) + cmd_to_exec = ast_node.parts[1].word.replace('$SRC', 'src') + if bash_script.endswith(cmd_to_exec): + suffixes_matching.append(bash_script) + #print(suffixes_matching) + return suffixes_matching + # Capture a local script called with $SRC/random/path/build.sh + if len(ast_node.parts) >= 1: + if '$SRC' in ast_node.parts[0].word: + suffixes_matching = [] + print(ast_node.parts[0].word) + for bash_script in all_local_scripts: + print("- %s" % (bash_script)) + cmd_to_exec = ast_node.parts[0].word.replace('$SRC', 'src') + if bash_script.endswith(cmd_to_exec): + suffixes_matching.append(bash_script) + print(suffixes_matching) + return suffixes_matching + + return [] + + +def handle_ast_command(ast_node, all_scripts_in_fs, raw_script): + """Generate bash script string for command node""" + new_script = '' + if should_discard_command(ast_node): + return '' + + matches = is_local_redirection(ast_node, all_scripts_in_fs) + if len(matches) == 1: + new_script += parse_script(matches[0], all_scripts_in_fs) + '\n' + return '' + + # Extract the command from the script string + idx_start = ast_node.pos[0] + idx_end = ast_node.pos[1] + new_script += raw_script[idx_start:idx_end] + #new_script += '\n' + + # If mkdir is used, then ensure that '-p' is provided, as + # otherwise we will run into failures. We don't have to worry + # about multiple uses of -p as `mkdir -p -p -p`` is valid. + new_script = new_script.replace('mkdir', 'mkdir -p') + return new_script + + +def handle_ast_list(ast_node, all_scripts_in_fs, raw_script): + """Handles bashlex AST list.""" + new_script = '' + try_hard = 1 + + if not try_hard: + list_start = ast_node.pos[0] + list_end = ast_node.pos[1] + new_script += raw_script[list_start:list_end] # + '\n' + else: + # This is more refined logic. Ideally, this should work, but it's a bit + # more intricate to get right due to e.g. white-space between positions + # and more extensive parsing needed. We don't neccesarily need this + # level of success rate for what we're trying to achieve, so am disabling + # this for now. + for part in ast_node.parts: + if part.kind == 'list': + new_script += handle_ast_list(part, all_scripts_in_fs, raw_script) + elif part.kind == 'command': + new_script += handle_ast_command(part, all_scripts_in_fs, raw_script) + else: + idx_start = part.pos[0] + idx_end = part.pos[1] + new_script += raw_script[idx_start:idx_end] + new_script += ' ' + + # Make sure what was created is valid syntax, and otherwise return empty + try: + bashlex.parse(new_script) + except: # pylint: disable=bare-except + # Maybe return the original here instead of skipping? + return '' + return new_script + + +def handle_ast_compound(ast_node, all_scripts_in_fs, raw_script): + """Handles bashlex compound AST node.""" + new_script = '' + list_start = ast_node.pos[0] + list_end = ast_node.pos[1] + new_script += raw_script[list_start:list_end] + '\n' + return new_script + + +def handle_node(ast_node, all_scripts_in_fs, build_script): + """Generates a bash script string for a given node""" + if ast_node.kind == 'command': + return handle_ast_command(ast_node, all_scripts_in_fs, build_script) + elif ast_node.kind == 'list': + return handle_ast_list(ast_node, all_scripts_in_fs, build_script) + elif ast_node.kind == 'compound': + print('todo: handle compound') + return handle_ast_compound(ast_node, all_scripts_in_fs, build_script) + elif ast_node.kind == 'pipeline': + # Not supported + return '' + else: + raise Exception(f'Missing node handling: {ast_node.kind}') + + +def parse_script(bash_script, all_scripts) -> str: + """Top-level bash script parser""" + new_script = '' + with open(bash_script, 'r', encoding='utf-8') as f: + build_script = f.read() + try: + parts = bashlex.parse(build_script) + except bashlex.errors.ParsingError: + return '' + for part in parts: + new_script += handle_node(part, all_scripts, build_script) + new_script += '\n' + print("-" * 45) + print(part.kind) + print(part.dump()) + + return new_script + + +def main(): + """Main function""" + all_scripts = find_all_bash_scripts_in_src() + replay_bash_script = parse_script(sys.argv[1], all_scripts) + + print("REPLAYABLE BASH SCRIPT") + print("#" * 60) + print(replay_bash_script) + print("#" * 60) + + out_dir = os.getenv('OUT', '/out') + with open(f'{out_dir}/replay-build-script.sh', 'w', encoding='utf-8') as f: + f.write(replay_bash_script) + + src_dir = os.getenv('SRC', '/src') + with open(f'{src_dir}/replay_build.sh', 'w', encoding='utf-8') as f: + f.write(replay_bash_script) + + +if __name__ == "__main__": + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bazel.bazelrc b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bazel.bazelrc new file mode 100644 index 0000000000000000000000000000000000000000..a82293d7e8a10f4de481da391c6e64bb8bf32c3f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bazel.bazelrc @@ -0,0 +1,20 @@ +# 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. +# +################################################################################ + + +# Pass variables from environment. +build --action_env=FUZZ_INTROSPECTOR +build --action_env=FUZZINTRO_OUTDIR diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bazel_build_fuzz_tests b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bazel_build_fuzz_tests new file mode 100644 index 0000000000000000000000000000000000000000..5d52c424839503cd405d7edb83fee5691870fd6e --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bazel_build_fuzz_tests @@ -0,0 +1,90 @@ +#!/bin/bash -eu +# +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +: "${BAZEL_FUZZ_TEST_TAG:=fuzz-test}" +: "${BAZEL_FUZZ_TEST_EXCLUDE_TAG:=no-oss-fuzz}" +: "${BAZEL_PACKAGE_SUFFIX:=_oss_fuzz}" +: "${BAZEL_TOOL:=bazel}" +: "${BAZEL_EXTRA_BUILD_FLAGS:=}" + +if [ "$FUZZING_LANGUAGE" = "jvm" ]; then + BAZEL_LANGUAGE=java +else + BAZEL_LANGUAGE=cc +fi + +if [[ -z "${BAZEL_FUZZ_TEST_QUERY:-}" ]]; then + BAZEL_FUZZ_TEST_QUERY=" + let all_fuzz_tests = attr(tags, \"${BAZEL_FUZZ_TEST_TAG}\", \"//...\") in + let lang_fuzz_tests = attr(generator_function, \"^${BAZEL_LANGUAGE}_fuzz_test\$\", \$all_fuzz_tests) in + \$lang_fuzz_tests - attr(tags, \"${BAZEL_FUZZ_TEST_EXCLUDE_TAG}\", \$lang_fuzz_tests) + " +fi + +echo "Using Bazel query to find fuzz targets: ${BAZEL_FUZZ_TEST_QUERY}" + +declare -r OSS_FUZZ_TESTS=( + $(bazel query "${BAZEL_FUZZ_TEST_QUERY}" | sed "s/$/${BAZEL_PACKAGE_SUFFIX}/") +) + +echo "Found ${#OSS_FUZZ_TESTS[@]} fuzz test packages:" +for oss_fuzz_test in "${OSS_FUZZ_TESTS[@]}"; do + echo " ${oss_fuzz_test}" +done + +declare -r BAZEL_BUILD_FLAGS=( + "--@rules_fuzzing//fuzzing:cc_engine=@rules_fuzzing_oss_fuzz//:oss_fuzz_engine" \ + "--@rules_fuzzing//fuzzing:java_engine=@rules_fuzzing_oss_fuzz//:oss_fuzz_java_engine" \ + "--@rules_fuzzing//fuzzing:cc_engine_instrumentation=oss-fuzz" \ + "--@rules_fuzzing//fuzzing:cc_engine_sanitizer=none" \ + "--cxxopt=-stdlib=libc++" \ + "--linkopt=-lc++" \ + "--verbose_failures" \ + "--spawn_strategy=standalone" \ + "--action_env=CC=${CC}" "--action_env=CXX=${CXX}" \ + ${BAZEL_EXTRA_BUILD_FLAGS[*]} +) + +echo "Building the fuzz tests with the following Bazel options:" +echo " ${BAZEL_BUILD_FLAGS[@]}" + +${BAZEL_TOOL} build "${BAZEL_BUILD_FLAGS[@]}" "${OSS_FUZZ_TESTS[@]}" + +echo "Extracting the fuzz test packages in the output directory." +for oss_fuzz_archive in $(find bazel-bin/ -name "*${BAZEL_PACKAGE_SUFFIX}.tar"); do + tar --no-same-owner -xvf "${oss_fuzz_archive}" -C "${OUT}" +done + +if [ "$SANITIZER" = "coverage" ]; then + echo "Collecting the repository source files for coverage tracking." + declare -r COVERAGE_SOURCES="${OUT}/proc/self/cwd" + mkdir -p "${COVERAGE_SOURCES}" + declare -r RSYNC_FILTER_ARGS=( + "--include" "*.h" + "--include" "*.cc" + "--include" "*.hpp" + "--include" "*.cpp" + "--include" "*.c" + "--include" "*.inc" + "--include" "*/" + "--exclude" "*" + ) + rsync -avLk "${RSYNC_FILTER_ARGS[@]}" \ + "$(bazel info execution_root)/" \ + "${COVERAGE_SOURCES}/" +fi diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bisect_clang.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bisect_clang.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2c0e49abb189d9dc1837ea193d0704dd486b51 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bisect_clang.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Use git bisect to find the Clang/LLVM commit causing a regression.""" + +import logging +import os +import re +import shutil +import subprocess +import sys + + +def execute(command, *args, expect_zero=True, **kwargs): + """Execute |command| and return the returncode, stdout and stderr.""" + kwargs['stdout'] = subprocess.PIPE + kwargs['stderr'] = subprocess.PIPE + logging.debug('Running command: "%s"', str(command)) + process = subprocess.Popen(command, *args, **kwargs) + stdout, stderr = process.communicate() + stdout = stdout.decode('utf-8') + stderr = stderr.decode('utf-8') + retcode = process.returncode + logging.info('Command: "%s" returned: %d.\nStdout: %s.\nStderr: %s', + str(command), retcode, stdout, stderr) + if expect_zero and retcode != 0: + raise subprocess.CalledProcessError(retcode, command) + return retcode, stdout, stderr + + +def search_bisect_output(output): + """Search |output| for a message indicating the culprit commit has been + found.""" + # TODO(metzman): Is it necessary to look for "good"? + culprit_regex = re.compile('([a-z0-9]{40}) is the first (good|bad) commit') + match = re.match(culprit_regex, output) + return match.group(1) if match is not None else None + + +class GitRepo: + """Class for executing commmands on a git repo.""" + + def __init__(self, repo_dir): + self.repo_dir = repo_dir + + def do_command(self, git_subcommand): + """Execute a |git_subcommand| (a list of strings).""" + command = ['git', '-C', self.repo_dir] + git_subcommand + return execute(command) + + def test_commit(self, test_command): + """Build LLVM at the currently checkedout commit, then run |test_command|. + If returncode is 0 run 'git bisect good' otherwise return 'git bisect bad'. + Return None if bisect didn't finish yet. Return the culprit commit if it + does.""" + build_clang(self.repo_dir) + retcode, _, _ = execute(test_command, shell=True, expect_zero=False) + if retcode == 0: + retcode, stdout, _ = self.do_bisect_command('good') + else: + retcode, stdout, _ = self.do_bisect_command('bad') + return search_bisect_output(stdout) + + def bisect(self, good_commit, bad_commit, test_command): + """Do git bisect assuming |good_commit| is good, |bad_commit| is bad and + |test_command| is an oracle. Return the culprit commit.""" + self.bisect_start(good_commit, bad_commit, test_command) + result = self.test_commit(test_command) + while result is None: + result = self.test_commit(test_command) + return result + + def bisect_start(self, good_commit, bad_commit, test_command): + """Start doing git bisect.""" + self.do_bisect_command('start') + # Do bad commit first since it is more likely to be recent. + self.test_start_commit(bad_commit, 'bad', test_command) + self.test_start_commit(good_commit, 'good', test_command) + + def do_bisect_command(self, subcommand): + """Execute a git bisect |subcommand| (string) and return the result.""" + return self.do_command(['bisect', subcommand]) + + def test_start_commit(self, commit, label, test_command): + """Use |test_command| to test the first good or bad |commit| (depending on + |label|).""" + assert label in ('good', 'bad'), label + self.do_command(['checkout', commit]) + build_clang(self.repo_dir) + retcode, _, _ = execute(test_command, shell=True, expect_zero=False) + if label == 'good' and retcode != 0: + raise BisectError('Test command "%s" returns %d on first good commit %s' % + (test_command, retcode, commit)) + if label == 'bad' and retcode == 0: + raise BisectError('Test command "%s" returns %d on first bad commit %s' % + (test_command, retcode, commit)) + + self.do_bisect_command(label) + + +class BisectError(Exception): + """Error that was encountered during bisection.""" + + +def get_clang_build_env(): + """Get an environment for building Clang.""" + env = os.environ.copy() + for variable in ['CXXFLAGS', 'CFLAGS']: + if variable in env: + del env[variable] + return env + + +def install_clang_build_deps(): + """Instal dependencies necessary to build clang.""" + execute([ + 'apt-get', 'install', '-y', 'build-essential', 'make', 'cmake', + 'ninja-build', 'git', 'subversion', 'g++-multilib' + ]) + + +def clone_with_retries(repo, local_path, num_retries=10): + """Clone |repo| to |local_path| if it doesn't exist already. Try up to + |num_retries| times. Return False if unable to checkout.""" + if os.path.isdir(local_path): + return + for _ in range(num_retries): + if os.path.isdir(local_path): + shutil.rmtree(local_path) + retcode, _, _ = execute(['git', 'clone', repo, local_path], + expect_zero=False) + if retcode == 0: + return + raise Exception('Could not checkout %s.' % repo) + + +def get_clang_target_arch(): + """Get target architecture we want clang to target when we build it.""" + _, arch, _ = execute(['uname', '-m']) + if 'x86_64' in arch: + return 'X86' + if 'aarch64' in arch: + return 'AArch64' + raise Exception('Unsupported target: %s.' % arch) + + +def prepare_build(llvm_project_path): + """Prepare to build clang.""" + llvm_build_dir = os.path.join(os.getenv('WORK'), 'llvm-build') + if not os.path.exists(llvm_build_dir): + os.mkdir(llvm_build_dir) + execute([ + 'cmake', '-G', 'Ninja', '-DLIBCXX_ENABLE_SHARED=OFF', + '-DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON', '-DLIBCXXABI_ENABLE_SHARED=OFF', + '-DCMAKE_BUILD_TYPE=Release', + '-DLLVM_ENABLE_PROJECTS=libcxx;libcxxabi;compiler-rt;clang', + '-DLLVM_TARGETS_TO_BUILD=' + get_clang_target_arch(), + os.path.join(llvm_project_path, 'llvm') + ], + env=get_clang_build_env(), + cwd=llvm_build_dir) + return llvm_build_dir + + +def build_clang(llvm_project_path): + """Checkout, build and install Clang.""" + # TODO(metzman): Merge Python checkout and build code with + # checkout_build_install_llvm.sh. + # TODO(metzman): Look into speeding this process using ccache. + # TODO(metzman): Make this program capable of handling MSAN and i386 Clang + # regressions. + llvm_build_dir = prepare_build(llvm_project_path) + execute(['ninja', '-C', llvm_build_dir, 'install'], env=get_clang_build_env()) + + +def find_culprit_commit(test_command, good_commit, bad_commit): + """Returns the culprit LLVM commit that introduced a bug revealed by running + |test_command|. Uses git bisect and treats |good_commit| as the first latest + known good commit and |bad_commit| as the first known bad commit.""" + llvm_project_path = os.path.join(os.getenv('SRC'), 'llvm-project') + clone_with_retries('https://github.com/llvm/llvm-project.git', + llvm_project_path) + git_repo = GitRepo(llvm_project_path) + result = git_repo.bisect(good_commit, bad_commit, test_command) + print('Culprit commit', result) + return result + + +def main(): + # pylint: disable=line-too-long + """Finds the culprit LLVM commit that introduced a clang regression. + Can be tested using this command in a libsodium shell: + python3 bisect_clang.py "cd /src/libsodium; make clean; cd -; compile && /out/secret_key_auth_fuzzer -runs=100" \ + f7e52fbdb5a7af8ea0808e98458b497125a5eca1 \ + 8288453f6aac05080b751b680455349e09d49825 + """ + # pylint: enable=line-too-long + # TODO(metzman): Check CFLAGS for things like -fsanitize=fuzzer-no-link. + # TODO(metzman): Allow test_command to be optional and for just build.sh to be + # used instead. + test_command = sys.argv[1] + # TODO(metzman): Add in more automation so that the script can automatically + # determine the commits used in last Clang roll. + good_commit = sys.argv[2] + bad_commit = sys.argv[3] + # TODO(metzman): Make verbosity configurable. + logging.getLogger().setLevel(logging.DEBUG) + install_clang_build_deps() + find_culprit_commit(test_command, good_commit, bad_commit) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bisect_clang_test.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bisect_clang_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a11bf8640d787181d6e35df225c9f17098d02619 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/bisect_clang_test.py @@ -0,0 +1,294 @@ +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +"""Tests for bisect_clang.py""" +import os +from unittest import mock +import unittest + +import bisect_clang + +FILE_DIRECTORY = os.path.dirname(__file__) +LLVM_REPO_PATH = '/llvm-project' + + +def get_git_command(*args): + """Returns a git command for the LLVM repo with |args| as arguments.""" + return ['git', '-C', LLVM_REPO_PATH] + list(args) + + +def patch_environ(testcase_obj): + """Patch environment.""" + env = {} + patcher = mock.patch.dict(os.environ, env) + testcase_obj.addCleanup(patcher.stop) + patcher.start() + + +class BisectClangTestMixin: # pylint: disable=too-few-public-methods + """Useful mixin for bisect_clang unittests.""" + + def setUp(self): # pylint: disable=invalid-name + """Initialization method for unittests.""" + patch_environ(self) + os.environ['SRC'] = '/src' + os.environ['WORK'] = '/work' + + +class GetClangBuildEnvTest(BisectClangTestMixin, unittest.TestCase): + """Tests for get_clang_build_env.""" + + def test_cflags(self): + """Test that CFLAGS are not used compiling clang.""" + os.environ['CFLAGS'] = 'blah' + self.assertNotIn('CFLAGS', bisect_clang.get_clang_build_env()) + + def test_cxxflags(self): + """Test that CXXFLAGS are not used compiling clang.""" + os.environ['CXXFLAGS'] = 'blah' + self.assertNotIn('CXXFLAGS', bisect_clang.get_clang_build_env()) + + def test_other_variables(self): + """Test that other env vars are used when compiling clang.""" + key = 'other' + value = 'blah' + os.environ[key] = value + self.assertEqual(value, bisect_clang.get_clang_build_env()[key]) + + +def read_test_data(filename): + """Returns data from |filename| in the test_data directory.""" + with open(os.path.join(FILE_DIRECTORY, 'test_data', filename)) as file_handle: + return file_handle.read() + + +class SearchBisectOutputTest(BisectClangTestMixin, unittest.TestCase): + """Tests for search_bisect_output.""" + + def test_search_bisect_output(self): + """Test that search_bisect_output finds the responsible commit when one + exists.""" + test_data = read_test_data('culprit-commit.txt') + self.assertEqual('ac9ee01fcbfac745aaedca0393a8e1c8a33acd8d', + bisect_clang.search_bisect_output(test_data)) + + def test_search_bisect_output_none(self): + """Test that search_bisect_output doesnt find a non-existent culprit + commit.""" + self.assertIsNone(bisect_clang.search_bisect_output('hello')) + + +def create_mock_popen( + output=bytes('', 'utf-8'), err=bytes('', 'utf-8'), returncode=0): + """Creates a mock subprocess.Popen.""" + + class MockPopen: + """Mock subprocess.Popen.""" + commands = [] + testcases_written = [] + + def __init__(self, command, *args, **kwargs): # pylint: disable=unused-argument + """Inits the MockPopen.""" + stdout = kwargs.pop('stdout', None) + self.command = command + self.commands.append(command) + self.stdout = None + self.stderr = None + self.returncode = returncode + if hasattr(stdout, 'write'): + self.stdout = stdout + + def communicate(self, input_data=None): # pylint: disable=unused-argument + """Mock subprocess.Popen.communicate.""" + if self.stdout: + self.stdout.write(output) + + if self.stderr: + self.stderr.write(err) + + return output, err + + def poll(self, input_data=None): # pylint: disable=unused-argument + """Mock subprocess.Popen.poll.""" + return self.returncode + + return MockPopen + + +def mock_prepare_build_impl(llvm_project_path): # pylint: disable=unused-argument + """Mocked prepare_build function.""" + return '/work/llvm-build' + + +class BuildClangTest(BisectClangTestMixin, unittest.TestCase): + """Tests for build_clang.""" + + def test_build_clang_test(self): + """Tests that build_clang works as intended.""" + with mock.patch('subprocess.Popen', create_mock_popen()) as mock_popen: + with mock.patch('bisect_clang.prepare_build', mock_prepare_build_impl): + llvm_src_dir = '/src/llvm-project' + bisect_clang.build_clang(llvm_src_dir) + self.assertEqual([['ninja', '-C', '/work/llvm-build', 'install']], + mock_popen.commands) + + +class GitRepoTest(BisectClangTestMixin, unittest.TestCase): + """Tests for GitRepo.""" + + # TODO(metzman): Mock filesystem. Until then, use a real directory. + + def setUp(self): + super().setUp() + self.git = bisect_clang.GitRepo(LLVM_REPO_PATH) + self.good_commit = 'good_commit' + self.bad_commit = 'bad_commit' + self.test_command = 'testcommand' + + def test_do_command(self): + """Test do_command creates a new process as intended.""" + # TODO(metzman): Test directory changing behavior. + command = ['subcommand', '--option'] + with mock.patch('subprocess.Popen', create_mock_popen()) as mock_popen: + self.git.do_command(command) + self.assertEqual([get_git_command('subcommand', '--option')], + mock_popen.commands) + + def _test_test_start_commit_unexpected(self, label, commit, returncode): + """Tests test_start_commit works as intended when the test returns an + unexpected value.""" + + def mock_execute_impl(command, *args, **kwargs): # pylint: disable=unused-argument + if command == self.test_command: + return returncode, '', '' + return 0, '', '' + + with mock.patch('bisect_clang.execute', mock_execute_impl): + with mock.patch('bisect_clang.prepare_build', mock_prepare_build_impl): + with self.assertRaises(bisect_clang.BisectError): + self.git.test_start_commit(commit, label, self.test_command) + + def test_test_start_commit_bad_zero(self): + """Tests test_start_commit works as intended when the test on the first bad + commit returns 0.""" + self._test_test_start_commit_unexpected('bad', self.bad_commit, 0) + + def test_test_start_commit_good_nonzero(self): + """Tests test_start_commit works as intended when the test on the first good + commit returns nonzero.""" + self._test_test_start_commit_unexpected('good', self.good_commit, 1) + + def test_test_start_commit_good_zero(self): + """Tests test_start_commit works as intended when the test on the first good + commit returns 0.""" + self._test_test_start_commit_expected('good', self.good_commit, 0) # pylint: disable=no-value-for-parameter + + @mock.patch('bisect_clang.build_clang') + def _test_test_start_commit_expected(self, label, commit, returncode, + mock_build_clang): + """Tests test_start_commit works as intended when the test returns an + expected value.""" + command_args = [] + + def mock_execute_impl(command, *args, **kwargs): # pylint: disable=unused-argument + command_args.append(command) + if command == self.test_command: + return returncode, '', '' + return 0, '', '' + + with mock.patch('bisect_clang.execute', mock_execute_impl): + self.git.test_start_commit(commit, label, self.test_command) + self.assertEqual([ + get_git_command('checkout', commit), self.test_command, + get_git_command('bisect', label) + ], command_args) + mock_build_clang.assert_called_once_with(LLVM_REPO_PATH) + + def test_test_start_commit_bad_nonzero(self): + """Tests test_start_commit works as intended when the test on the first bad + commit returns nonzero.""" + self._test_test_start_commit_expected('bad', self.bad_commit, 1) # pylint: disable=no-value-for-parameter + + @mock.patch('bisect_clang.GitRepo.test_start_commit') + def test_bisect_start(self, mock_test_start_commit): + """Tests bisect_start works as intended.""" + with mock.patch('subprocess.Popen', create_mock_popen()) as mock_popen: + self.git.bisect_start(self.good_commit, self.bad_commit, + self.test_command) + self.assertEqual(get_git_command('bisect', 'start'), + mock_popen.commands[0]) + mock_test_start_commit.assert_has_calls([ + mock.call('bad_commit', 'bad', 'testcommand'), + mock.call('good_commit', 'good', 'testcommand') + ]) + + def test_do_bisect_command(self): + """Test do_bisect_command executes a git bisect subcommand as intended.""" + subcommand = 'subcommand' + with mock.patch('subprocess.Popen', create_mock_popen()) as mock_popen: + self.git.do_bisect_command(subcommand) + self.assertEqual([get_git_command('bisect', subcommand)], + mock_popen.commands) + + @mock.patch('bisect_clang.build_clang') + def _test_test_commit(self, label, output, returncode, mock_build_clang): + """Test test_commit works as intended.""" + command_args = [] + + def mock_execute_impl(command, *args, **kwargs): # pylint: disable=unused-argument + command_args.append(command) + if command == self.test_command: + return returncode, output, '' + return 0, output, '' + + with mock.patch('bisect_clang.execute', mock_execute_impl): + result = self.git.test_commit(self.test_command) + self.assertEqual([self.test_command, + get_git_command('bisect', label)], command_args) + mock_build_clang.assert_called_once_with(LLVM_REPO_PATH) + return result + + def test_test_commit_good(self): + """Test test_commit labels a good commit as good.""" + self.assertIsNone(self._test_test_commit('good', '', 0)) # pylint: disable=no-value-for-parameter + + def test_test_commit_bad(self): + """Test test_commit labels a bad commit as bad.""" + self.assertIsNone(self._test_test_commit('bad', '', 1)) # pylint: disable=no-value-for-parameter + + def test_test_commit_culprit(self): + """Test test_commit returns the culprit""" + test_data = read_test_data('culprit-commit.txt') + self.assertEqual('ac9ee01fcbfac745aaedca0393a8e1c8a33acd8d', + self._test_test_commit('good', test_data, 0)) # pylint: disable=no-value-for-parameter + + +class GetTargetArchToBuildTest(unittest.TestCase): + """Tests for get_target_arch_to_build.""" + + def test_unrecognized(self): + """Test that an unrecognized architecture raises an exception.""" + with mock.patch('bisect_clang.execute') as mock_execute: + mock_execute.return_value = (None, 'mips', None) + with self.assertRaises(Exception): + bisect_clang.get_clang_target_arch() + + def test_recognized(self): + """Test that a recognized architecture returns the expected value.""" + arch_pairs = {'x86_64': 'X86', 'aarch64': 'AArch64'} + for uname_result, clang_target in arch_pairs.items(): + with mock.patch('bisect_clang.execute') as mock_execute: + mock_execute.return_value = (None, uname_result, None) + self.assertEqual(clang_target, bisect_clang.get_clang_target_arch()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/cargo b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/cargo new file mode 100644 index 0000000000000000000000000000000000000000..4376cfa5d4a339e1ec59193c1af58061e772fa96 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/cargo @@ -0,0 +1,55 @@ +#!/bin/bash -eu +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# This is a wrapper around calling cargo +# This just expands RUSTFLAGS in case of a coverage build +# We need this until https://github.com/rust-lang/cargo/issues/5450 is merged +# because cargo uses relative paths for the current crate +# and absolute paths for its dependencies +# +################################################################################ + +if [ "$SANITIZER" = "coverage" ] && [ $1 = "build" ] +then + crate_src_abspath=`cargo metadata --no-deps --format-version 1 | jq -r '.workspace_root'` + export RUSTFLAGS="$RUSTFLAGS --remap-path-prefix src=$crate_src_abspath/src" +fi + +if [ "$SANITIZER" = "coverage" ] && [ $1 = "fuzz" ] && [ $2 = "build" ] +then + # hack to turn cargo fuzz build into cargo build so as to get coverage + # cargo fuzz adds "--target" "x86_64-unknown-linux-gnu" + ( + # go into fuzz directory if not already the case + cd fuzz || true + fuzz_src_abspath=`pwd` + # Default directory is fuzz_targets, but some projects like image-rs use fuzzers. + while read i; do + export RUSTFLAGS="$RUSTFLAGS --remap-path-prefix $i=$fuzz_src_abspath/$i" + # Bash while syntax so that we modify RUSTFLAGS in main shell instead of a subshell. + done <<< "$(find . -name "*.rs" | cut -d/ -f2 | uniq)" + # we do not want to trigger debug assertions and stops + export RUSTFLAGS="$RUSTFLAGS -C debug-assertions=no" + # do not optimize with --release, leading to Malformed instrumentation profile data + cargo build --bins + # copies the build output in the expected target directory + cd `cargo metadata --format-version 1 --no-deps | jq -r '.target_directory'` + mkdir -p x86_64-unknown-linux-gnu/release + cp -r debug/* x86_64-unknown-linux-gnu/release/ + ) + exit 0 +fi + +/rust/bin/cargo "$@" diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile new file mode 100644 index 0000000000000000000000000000000000000000..8aa6580bc3d393ca5b75499c5fc0064bed1ee80f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile @@ -0,0 +1,420 @@ +#!/bin/bash -eu +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo "---------------------------------------------------------------" + +sysctl -w vm.mmap_rnd_bits=28 + +OSS_FUZZ_ON_DEMAND="${OSS_FUZZ_ON_DEMAND:-0}" + +# Used for Rust introspector builds +RUST_SANITIZER=$SANITIZER + +if [ "$FUZZING_LANGUAGE" = "jvm" ]; then + if [ "$FUZZING_ENGINE" != "libfuzzer" ] && [ "$FUZZING_ENGINE" != "wycheproof" ]; then + echo "ERROR: JVM projects can be fuzzed with libFuzzer or tested with wycheproof engines only." + exit 1 + fi + if [ "$SANITIZER" != "address" ] && [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "undefined" ] && [ "$SANITIZER" != "none" ] && [ "$SANITIZER" != "introspector" ]; then + echo "ERROR: JVM projects can be fuzzed with AddressSanitizer or UndefinedBehaviorSanitizer or Introspector only." + exit 1 + fi + if [ "$ARCHITECTURE" != "x86_64" ]; then + echo "ERROR: JVM projects can be fuzzed on x86_64 architecture only." + exit 1 + fi +fi + +if [ "$FUZZING_LANGUAGE" = "rust" ]; then + if [ "$SANITIZER" = "introspector" ]; then + # introspector sanitizer flag will cause cargo build to fail. Rremove it + # temporarily, RUST_SANITIZER will hold the original sanitizer. + export SANITIZER=address + fi +fi + + +if [ "$FUZZING_LANGUAGE" = "javascript" ]; then + if [ "$FUZZING_ENGINE" != "libfuzzer" ]; then + echo "ERROR: JavaScript projects can be fuzzed with libFuzzer engine only." + exit 1 + fi + if [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "none" ]; then + echo "ERROR: JavaScript projects cannot be fuzzed with sanitizers." + exit 1 + fi + if [ "$ARCHITECTURE" != "x86_64" ]; then + echo "ERROR: JavaScript projects can be fuzzed on x86_64 architecture only." + exit 1 + fi +fi + +if [ "$FUZZING_LANGUAGE" = "python" ]; then + if [ "$FUZZING_ENGINE" != "libfuzzer" ]; then + echo "ERROR: Python projects can be fuzzed with libFuzzer engine only." + exit 1 + fi + if [ "$SANITIZER" != "address" ] && [ "$SANITIZER" != "undefined" ] && [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "introspector" ]; then + echo "ERROR: Python projects can be fuzzed with AddressSanitizer or UndefinedBehaviorSanitizer or Coverage or Fuzz Introspector only." + exit 1 + fi + if [ "$ARCHITECTURE" != "x86_64" ]; then + echo "ERROR: Python projects can be fuzzed on x86_64 architecture only." + exit 1 + fi +fi + +if [ -z "${SANITIZER_FLAGS-}" ]; then + FLAGS_VAR="SANITIZER_FLAGS_${SANITIZER}" + export SANITIZER_FLAGS=${!FLAGS_VAR-} +fi + +if [[ $ARCHITECTURE == "i386" ]]; then + export CFLAGS="-m32 $CFLAGS" + cp -R /usr/i386/lib/* /usr/local/lib + cp -R /usr/i386/include/* /usr/local/include +fi + +# Don't use a fuzzing engine with Jazzer which has libFuzzer built-in or with +# FuzzBench which will provide the fuzzing engine. +if [[ $FUZZING_ENGINE != "none" ]] && [[ $FUZZING_LANGUAGE != "jvm" ]] && [[ "${OSS_FUZZ_ON_DEMAND}" == "0" ]] ; then + # compile script might override environment, use . to call it. + . compile_${FUZZING_ENGINE} +fi + +if [[ $SANITIZER_FLAGS = *sanitize=memory* ]] +then + # Take all libraries from lib/msan + # export CXXFLAGS_EXTRA="-L/usr/msan/lib $CXXFLAGS_EXTRA" + cp -R /usr/msan/lib/* /usr/local/lib/x86_64-unknown-linux-gnu/ + cp -R /usr/msan/include/* /usr/local/include + + echo 'Building without MSan instrumented libraries.' +fi + +# Coverage flag overrides. +COVERAGE_FLAGS_VAR="COVERAGE_FLAGS_${SANITIZER}" +if [[ -n ${!COVERAGE_FLAGS_VAR+x} ]] +then + export COVERAGE_FLAGS="${!COVERAGE_FLAGS_VAR}" +fi + +# Only need the default coverage instrumentation for libFuzzer or honggfuzz. +# Other engines bring their own. +if [ $FUZZING_ENGINE = "none" ] || [ $FUZZING_ENGINE = "afl" ] || [ $FUZZING_ENGINE = "centipede" ] || [ "${OSS_FUZZ_ON_DEMAND}" != "0" ]; then + export COVERAGE_FLAGS= +fi + +# Rust does not support sanitizers and coverage flags via CFLAGS/CXXFLAGS, so +# use RUSTFLAGS. +# FIXME: Support code coverage once support is in. +# See https://github.com/rust-lang/rust/issues/34701. +if [ "$RUST_SANITIZER" == "introspector" ]; then + export RUSTFLAGS="-Cdebuginfo=2 -Cforce-frame-pointers" +elif [ "$SANITIZER" != "undefined" ] && [ "$SANITIZER" != "coverage" ] && [ "$SANITIZER" != "none" ] && [ "$ARCHITECTURE" != 'i386' ]; then + export RUSTFLAGS="--cfg fuzzing -Zsanitizer=${SANITIZER} -Cdebuginfo=1 -Cforce-frame-pointers" +else + export RUSTFLAGS="--cfg fuzzing -Cdebuginfo=1 -Cforce-frame-pointers" +fi +if [ "$SANITIZER" = "coverage" ] +then + # link to C++ from comment in f5098035eb1a14aa966c8651d88ea3d64323823d + export RUSTFLAGS="$RUSTFLAGS -Cinstrument-coverage -C link-arg=-lc++" +fi + +# Add Rust libfuzzer flags. +# See https://github.com/rust-fuzz/libfuzzer/blob/master/build.rs#L12. +export CUSTOM_LIBFUZZER_PATH="$LIB_FUZZING_ENGINE_DEPRECATED" +export CUSTOM_LIBFUZZER_STD_CXX=c++ + +export CFLAGS="$CFLAGS $SANITIZER_FLAGS $COVERAGE_FLAGS" +export CXXFLAGS="$CFLAGS $CXXFLAGS_EXTRA" + +if [ "$SANITIZER" = "undefined" ]; then + # Disable "function" sanitizer for C code for now, because many projects, + # possibly via legacy C code are affected. + # The projects should be fixed and this workaround be removed in the future. + # TODO(#11778): + # https://github.com/google/oss-fuzz/issues/11778 + export CFLAGS="$CFLAGS -fno-sanitize=function" +fi + +if [ "$FUZZING_LANGUAGE" = "go" ]; then + # required by Go 1.20 + export CXX="${CXX} -lresolv" +fi + +if [ "$FUZZING_LANGUAGE" = "python" ]; then + sanitizer_with_fuzzer_lib_dir=`python3 -c "import atheris; import os; print(atheris.path())"` + sanitizer_with_fuzzer_output_lib=$OUT/sanitizer_with_fuzzer.so + if [ "$SANITIZER" = "address" ]; then + cp $sanitizer_with_fuzzer_lib_dir/asan_with_fuzzer.so $sanitizer_with_fuzzer_output_lib + elif [ "$SANITIZER" = "undefined" ]; then + cp $sanitizer_with_fuzzer_lib_dir/ubsan_with_fuzzer.so $sanitizer_with_fuzzer_output_lib + fi + + # Disable leak checking as it is unsupported. + export CFLAGS="$CFLAGS -fno-sanitize=function,leak,vptr," + export CXXFLAGS="$CXXFLAGS -fno-sanitize=function,leak,vptr" +fi + +# Copy latest llvm-symbolizer in $OUT for stack symbolization. +cp $(which llvm-symbolizer) $OUT/ + +# Copy Jazzer to $OUT if needed. +if [ "$FUZZING_LANGUAGE" = "jvm" ]; then + cp $(which jazzer_agent_deploy.jar) $(which jazzer_driver) $(which jazzer_junit.jar) $OUT/ + jazzer_driver_with_sanitizer=$OUT/jazzer_driver_with_sanitizer + if [ "$SANITIZER" = "address" ]; then + cat > $jazzer_driver_with_sanitizer << 'EOF' +#!/bin/bash +this_dir=$(dirname "$0") +"$this_dir/jazzer_driver" --asan "$@" +EOF + elif [ "$SANITIZER" = "undefined" ]; then + cat > $jazzer_driver_with_sanitizer << 'EOF' +#!/bin/bash +this_dir=$(dirname "$0") +"$this_dir/jazzer_driver" --ubsan "$@" +EOF + elif [ "$SANITIZER" = "coverage" ] || [ "$SANITIZER" = "introspector" ]; then + # Coverage & introspector builds require no instrumentation. + cp $(which jazzer_driver) $jazzer_driver_with_sanitizer + fi + chmod +x $jazzer_driver_with_sanitizer + + # Disable leak checking since the JVM triggers too many false positives. + export CFLAGS="$CFLAGS -fno-sanitize=leak" + export CXXFLAGS="$CXXFLAGS -fno-sanitize=leak" +fi + +if [ "$SANITIZER" = "introspector" ] || [ "$RUST_SANITIZER" = "introspector" ]; then + export AR=llvm-ar + export NM=llvm-nm + export RANLIB=llvm-ranlib + + export CFLAGS="$CFLAGS -g" + export CXXFLAGS="$CXXFLAGS -g" + export FI_BRANCH_PROFILE=1 + export FUZZ_INTROSPECTOR=1 + export FUZZ_INTROSPECTOR_AUTO_FUZZ=1 + + # Move ar and ranlib + mv /usr/bin/ar /usr/bin/old-ar + mv /usr/bin/nm /usr/bin/old-nm + mv /usr/bin/ranlib /usr/bin/old-ranlib + + ln -sf /usr/local/bin/llvm-ar /usr/bin/ar + ln -sf /usr/local/bin/llvm-nm /usr/bin/nm + ln -sf /usr/local/bin/llvm-ranlib /usr/bin/ranlib + + apt-get install -y libjpeg-dev zlib1g-dev libyaml-dev + python3 -m pip install --upgrade pip setuptools + python3 -m pip install cxxfilt pyyaml beautifulsoup4 lxml soupsieve rust-demangler + python3 -m pip install --prefer-binary matplotlib + + # Install Fuzz-Introspector + pushd /fuzz-introspector/src + python3 -m pip install -e . + popd + + if [ "$FUZZING_LANGUAGE" = "python" ]; then + python3 /fuzz-introspector/src/main.py light --language=python + cp -rf $SRC/inspector/ /tmp/inspector-saved + elif [ "$FUZZING_LANGUAGE" = "jvm" ]; then + python3 /fuzz-introspector/src/main.py light --language=jvm + cp -rf $SRC/inspector/ /tmp/inspector-saved + elif [ "$FUZZING_LANGUAGE" = "rust" ]; then + python3 /fuzz-introspector/src/main.py light --language=rust + cp -rf $SRC/inspector/ /tmp/inspector-saved + else + python3 /fuzz-introspector/src/main.py light + + # Make a copy of the light. This is needed because we run two versions of + # introspector: one based on pure statis analysis and one based on + # regular LTO. + cp -rf $SRC/inspector/ /tmp/inspector-saved + + + # Move coverage report. + if [ -d "$OUT/textcov_reports" ] + then + find $OUT/textcov_reports/ -name "*.covreport" -exec cp {} $SRC/inspector/ \; + find $OUT/textcov_reports/ -name "*.json" -exec cp {} $SRC/inspector/ \; + fi + + # Make fuzz-introspector HTML report using light approach. + REPORT_ARGS="--name=$PROJECT_NAME" + + # Only pass coverage_url when COVERAGE_URL is set (in cloud builds) + if [[ ! -z "${COVERAGE_URL+x}" ]]; then + REPORT_ARGS="$REPORT_ARGS --coverage-url=${COVERAGE_URL}" + fi + + # Run pure static analysis fuzz introspector + fuzz-introspector full --target-dir=$SRC \ + --language=${FUZZING_LANGUAGE} \ + --out-dir=$SRC/inspector \ + ${REPORT_ARGS} + fi + + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" +fi + +echo "---------------------------------------------------------------" +echo "CC=$CC" +echo "CXX=$CXX" +echo "CFLAGS=$CFLAGS" +echo "CXXFLAGS=$CXXFLAGS" +echo "RUSTFLAGS=$RUSTFLAGS" +echo "---------------------------------------------------------------" + +if [ "${OSS_FUZZ_ON_DEMAND}" != "0" ]; then + fuzzbench_build + cp $(which llvm-symbolizer) $OUT/ + exit 0 +fi + + +if [[ ! -z "${CAPTURE_REPLAY_SCRIPT-}" ]]; then + # Capture a replaying build script which can be used for replaying the build + # after a vanilla build. This script is meant to be used in a cached + # container. + python3 -m pip install bashlex + python3 /usr/local/bin/bash_parser.py $SRC/build.sh +fi + +# Prepare the build command to run the project's build script. +if [[ ! -z "${REPLAY_ENABLED-}" ]]; then + # If this is a replay, then use replay_build.sh. This is expected to be + # running in a cached container where a build has already happened prior. + BUILD_CMD="bash -eux $SRC/replay_build.sh" +else + BUILD_CMD="bash -eux $SRC/build.sh" +fi + +# Set +u temporarily to continue even if GOPATH and OSSFUZZ_RUSTPATH are undefined. +set +u +# We need to preserve source code files for generating a code coverage report. +# We need exact files that were compiled, so copy both $SRC and $WORK dirs. +COPY_SOURCES_CMD="cp -rL --parents $SRC $WORK /usr/include /usr/local/include $GOPATH $OSSFUZZ_RUSTPATH /rustc $OUT" +set -u + +if [ "$FUZZING_LANGUAGE" = "rust" ]; then + # Copy rust std lib to its path with a hash. + export rustch=`rustc --version --verbose | grep commit-hash | cut -d' ' -f2` + mkdir -p /rustc/$rustch/ + export rustdef=`rustup toolchain list | grep default | cut -d' ' -f1` + cp -r /rust/rustup/toolchains/$rustdef/lib/rustlib/src/rust/library/ /rustc/$rustch/ +fi + +if [ "${BUILD_UID-0}" -ne "0" ]; then + adduser -u $BUILD_UID --disabled-password --gecos '' builder + chown -R builder $SRC $OUT $WORK + su -c "$BUILD_CMD" builder + if [ "$SANITIZER" = "coverage" ]; then + # Some directories have broken symlinks (e.g. honggfuzz), ignore the errors. + su -c "$COPY_SOURCES_CMD" builder 2>/dev/null || true + fi +else + $BUILD_CMD + if [ "$SANITIZER" = "coverage" ]; then + # Some directories have broken symlinks (e.g. honggfuzz), ignore the errors. + $COPY_SOURCES_CMD 2>/dev/null || true + fi +fi + +if [ "$SANITIZER" = "introspector" ] || [ "$RUST_SANITIZER" = "introspector" ]; then + unset CXXFLAGS + unset CFLAGS + export G_ANALYTICS_TAG="G-8WTFM1Y62J" + + # If we get to here, it means the e.g. LTO had no problems and succeeded. + # TO this end, we wlil restore the original light analysis and used the + # LTO processing itself. + rm -rf $SRC/inspector + cp -rf /tmp/inspector-saved $SRC/inspector + + cd /fuzz-introspector/src + python3 -m pip install -e . + cd /src/ + + if [ "$FUZZING_LANGUAGE" = "rust" ]; then + # Restore the sanitizer flag for rust + export SANITIZER="introspector" + fi + + mkdir -p $SRC/inspector + find $SRC/ -name "fuzzerLogFile-*.data" -exec cp {} $SRC/inspector/ \; + find $SRC/ -name "fuzzerLogFile-*.data.yaml" -exec cp {} $SRC/inspector/ \; + find $SRC/ -name "fuzzerLogFile-*.data.debug_*" -exec cp {} $SRC/inspector/ \; + find $SRC/ -name "allFunctionsWithMain-*.yaml" -exec cp {} $SRC/inspector/ \; + + # Move coverage report. + if [ -d "$OUT/textcov_reports" ] + then + find $OUT/textcov_reports/ -name "*.covreport" -exec cp {} $SRC/inspector/ \; + find $OUT/textcov_reports/ -name "*.json" -exec cp {} $SRC/inspector/ \; + fi + + cd $SRC/inspector + + # Make fuzz-introspector HTML report. + REPORT_ARGS="--name=$PROJECT_NAME" + # Only pass coverage_url when COVERAGE_URL is set (in cloud builds) + if [[ ! -z "${COVERAGE_URL+x}" ]]; then + REPORT_ARGS="$REPORT_ARGS --coverage-url=${COVERAGE_URL}" + fi + + # Do different things depending on languages + if [ "$FUZZING_LANGUAGE" = "python" ]; then + echo "GOING python route" + set -x + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC/inspector" + REPORT_ARGS="$REPORT_ARGS --language=python" + fuzz-introspector report $REPORT_ARGS + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + elif [ "$FUZZING_LANGUAGE" = "jvm" ]; then + echo "GOING jvm route" + set -x + find $OUT/ -name "jacoco.xml" -exec cp {} $SRC/inspector/ \; + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC --out-dir=$SRC/inspector" + REPORT_ARGS="$REPORT_ARGS --language=jvm" + fuzz-introspector full $REPORT_ARGS + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + elif [ "$FUZZING_LANGUAGE" = "rust" ]; then + echo "GOING rust route" + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC --out-dir=$SRC/inspector" + REPORT_ARGS="$REPORT_ARGS --language=rust" + fuzz-introspector full $REPORT_ARGS + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + else + # C/C++ + mkdir -p $SRC/inspector + # Correlate fuzzer binaries to fuzz-introspector's raw data + fuzz-introspector correlate --binaries-dir=$OUT/ + + # Generate fuzz-introspector HTML report, this generates + # the file exe_to_fuzz_introspector_logs.yaml + REPORT_ARGS="$REPORT_ARGS --target-dir=$SRC/inspector" + # Use the just-generated correlation file + REPORT_ARGS="$REPORT_ARGS --correlation-file=exe_to_fuzz_introspector_logs.yaml" + fuzz-introspector report $REPORT_ARGS + + rsync -avu --delete "$SRC/inspector/" "$OUT/inspector" + fi +fi diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_afl b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_afl new file mode 100644 index 0000000000000000000000000000000000000000..484d4668c86648d042081a8a1e254dd6a5c36256 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_afl @@ -0,0 +1,53 @@ +#!/bin/bash -eu +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# If LLVM once again does weird changes then enable this: +#export AFL_LLVM_INSTRUMENT=LLVM-NATIVE + +# AFL++ setup +echo "Copying precompiled AFL++" + +# Copy AFL++ tools necessary for fuzzing. +pushd $SRC/aflplusplus > /dev/null + +cp -f libAFLDriver.a $LIB_FUZZING_ENGINE + +# Some important projects include libraries, copy those even when they don't +# start with "afl-". Use "sort -u" to avoid a warning about duplicates. +ls afl-* *.txt *.a *.o *.so | sort -u | xargs cp -t $OUT +export CC="$SRC/aflplusplus/afl-clang-fast" +export CXX="$SRC/aflplusplus/afl-clang-fast++" + +# Set sane AFL++ environment defaults: +# Be quiet, otherwise this can break some builds. +export AFL_QUIET=1 +# No leak errors during builds. +export ASAN_OPTIONS="detect_leaks=0:symbolize=0:detect_odr_violation=0:abort_on_error=1" +# Do not abort on any problems (because this is during build where it is ok) +export AFL_IGNORE_PROBLEMS=1 +# No complain on unknown AFL environment variables +export AFL_IGNORE_UNKNOWN_ENVS=1 + +# Provide a way to document the AFL++ options used in this build: +echo +echo AFL++ target compilation setup: +env | egrep '^AFL_' | tee "$OUT/afl_options.txt" +echo + +popd > /dev/null + +echo " done." diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_centipede b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_centipede new file mode 100644 index 0000000000000000000000000000000000000000..dee31e2e641f2d6e342ec13f6ff176ca53d6726d --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_centipede @@ -0,0 +1,32 @@ +#!/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. +# +################################################################################ + +echo "Skipping compilation; using precompiled centipede" + +if [[ "$SANITIZER" == 'none' ]]; then + cp "$CENTIPEDE_BIN_DIR/centipede" "$OUT" +fi + +cp "$CENTIPEDE_BIN_DIR/libcentipede_runner.pic.a" "$LIB_FUZZING_ENGINE" + +export CENTIPEDE_FLAGS=`cat "$SRC/fuzztest/centipede/clang-flags.txt" | tr '\n' ' '` +export LIBRARIES_FLAGS="-Wno-unused-command-line-argument -Wl,-ldl -Wl,-lrt -Wl,-lpthread -Wl,$SRC/fuzztest/centipede/weak.o" + +export CFLAGS="$CFLAGS $CENTIPEDE_FLAGS $LIBRARIES_FLAGS" +export CXXFLAGS="$CXXFLAGS $CENTIPEDE_FLAGS $LIBRARIES_FLAGS" + +echo 'done.' diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_fuzztests.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_fuzztests.sh new file mode 100644 index 0000000000000000000000000000000000000000..8377920e53284d940aa467b29c56bd14e0c6c437 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_fuzztests.sh @@ -0,0 +1,126 @@ +#!/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. +# +################################################################################ + +set -x + +# In order to identify fuzztest test case "bazel query" is used to search +# the project. A search of the entire project is done with a default "...", +# however, some projects may fail to, or have very long processing time, if +# searching the entire project. Additionally, it may include fuzzers in +# dependencies, which should not be build as part of a given project. +# Tensorflow is an example project that will fail when the entire project is +# queried. FUZZTEST_TARGET_FOLDER makes it posible to specify the folder +# where fuzztest fuzzers should be search for. FUZZTEST_TARGET_FOLDER is passed +# to "bazel query" below. +if [[ ${FUZZTEST_TARGET_FOLDER:-"unset"} == "unset" ]]; +then + export TARGET_FOLDER="..." +else + TARGET_FOLDER=${FUZZTEST_TARGET_FOLDER} +fi + +BUILD_ARGS="--config=oss-fuzz --subcommands" +if [[ ${FUZZTEST_EXTRA_ARGS:-"unset"} != "unset" ]]; +then + BUILD_ARGS="$BUILD_ARGS ${FUZZTEST_EXTRA_ARGS}" +fi + +# Trigger setup_configs rule of fuzztest as it generates the necessary +# configuration file based on OSS-Fuzz environment variables. +bazel run @com_google_fuzztest//bazel:setup_configs >> /etc/bazel.bazelrc + +# Bazel target names of the fuzz binaries. +FUZZ_TEST_BINARIES=$(bazel query "kind(\"cc_test\", rdeps(${TARGET_FOLDER}, @com_google_fuzztest//fuzztest:fuzztest_gtest_main))") + +# Bazel output paths of the fuzz binaries. +FUZZ_TEST_BINARIES_OUT_PATHS=$(bazel cquery "kind(\"cc_test\", rdeps(${TARGET_FOLDER}, @com_google_fuzztest//fuzztest:fuzztest_gtest_main))" --output=files) + +# Build the project and fuzz binaries +# Expose `FUZZTEST_EXTRA_TARGETS` environment variable, in the event a project +# includes non-FuzzTest fuzzers then this can be used to compile these in the +# same `bazel build` command as when building the FuzzTest fuzzers. +# This is to avoid having to call `bazel build` twice. +bazel build $BUILD_ARGS -- ${FUZZ_TEST_BINARIES[*]} ${FUZZTEST_EXTRA_TARGETS:-} + +# Iterate the fuzz binaries and list each fuzz entrypoint in the binary. For +# each entrypoint create a wrapper script that calls into the binaries the +# given entrypoint as argument. +# The scripts will be named: +# {binary_name}@{fuzztest_entrypoint} +for fuzz_main_file in $FUZZ_TEST_BINARIES_OUT_PATHS; do + FUZZ_TESTS=$($fuzz_main_file --list_fuzz_tests) + cp ${fuzz_main_file} $OUT/ + fuzz_basename=$(basename $fuzz_main_file) + chmod -x $OUT/$fuzz_basename + for fuzz_entrypoint in $FUZZ_TESTS; do + TARGET_FUZZER="${fuzz_basename}@$fuzz_entrypoint" + + # Write executer script + echo "#!/bin/sh +# LLVMFuzzerTestOneInput for fuzzer detection. +this_dir=\$(dirname \"\$0\") +chmod +x \$this_dir/$fuzz_basename +\$this_dir/$fuzz_basename --fuzz=$fuzz_entrypoint -- \$@" > $OUT/$TARGET_FUZZER + chmod +x $OUT/$TARGET_FUZZER + done +done + +# Synchronise coverage directory to bazel output artifacts. This is a +# best-effort basis in that it will include source code in common +# bazel output folders. +# For projects that store results in non-standard folders or want to +# manage what code to include in the coverage report more specifically, +# the FUZZTEST_DO_SYNC environment variable is made available. Projects +# can then implement a custom way of synchronising source code with the +# coverage build. Set FUZZTEST_DO_SYNC to something other than "yes" and +# no effort will be made to automatically synchronise the source code with +# the code coverage visualisation utility. +if [[ "$SANITIZER" = "coverage" && ${FUZZTEST_DO_SYNC:-"yes"} == "yes" ]] +then + # Synchronize bazel source files to coverage collection. + declare -r REMAP_PATH="${OUT}/proc/self/cwd" + mkdir -p "${REMAP_PATH}" + + # Synchronize the folder bazel-BAZEL_OUT_PROJECT. + declare -r RSYNC_FILTER_ARGS=("--include" "*.h" "--include" "*.cc" "--include" \ + "*.hpp" "--include" "*.cpp" "--include" "*.c" "--include" "*/" "--include" "*.inc" \ + "--exclude" "*") + + project_folders="$(find . -name 'bazel-*' -type l -printf '%P\n' | \ + grep -v -x -F \ + -e 'bazel-bin' \ + -e 'bazel-testlogs')" + for link in $project_folders; do + if [[ -d "${PWD}"/$link/external ]] + then + rsync -avLk "${RSYNC_FILTER_ARGS[@]}" "${PWD}"/$link/external "${REMAP_PATH}" + fi + # k8-opt is a common path for storing bazel output artifacts, e.g. bazel-out/k8-opt. + # It's the output folder for default amd-64 builds, but projects may specify custom + # platform output directories, see: https://github.com/bazelbuild/bazel/issues/13818 + # We support the default at the moment, and if a project needs custom synchronizing of + # output artifacts and code coverage we currently recommend using FUZZTEST_DO_SYNC. + if [[ -d "${PWD}"/$link/k8-opt ]] + then + rsync -avLk "${RSYNC_FILTER_ARGS[@]}" "${PWD}"/$link/k8-opt "${REMAP_PATH}"/$link + fi + done + + # Delete symlinks and sync the current folder. + find . -type l -ls -delete + rsync -av ${PWD}/ "${REMAP_PATH}" +fi diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..df7d3e24d23c1caf7e262040021fa04240efa8bb --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer @@ -0,0 +1,69 @@ +#!/bin/bash -eu +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +path=$1 +function=$2 +fuzzer=$3 +tags="-tags gofuzz" +if [[ $# -eq 4 ]]; then + tags="-tags $4" +fi + +# makes directory change temporary +( +cd $GOPATH/src/$path || true +# in the case we are in the right directory, with go.mod but no go.sum +go mod tidy || true +# project was downloaded with go get if go list fails +go list $tags $path || { cd $GOPATH/pkg/mod/ && cd `echo $path | cut -d/ -f1-3 | awk '{print $1"@*"}'`; } || cd - +# project does not have go.mod if go list fails again +go list $tags $path || { go mod init $path && go mod tidy ;} + +if [[ $SANITIZER = *coverage* ]]; then + fuzzed_package=`go list $tags -f '{{.Name}}' $path` + abspath=`go list $tags -f {{.Dir}} $path` + cd $abspath + cp $GOPATH/ossfuzz_coverage_runner.go ./"${function,,}"_test.go + sed -i -e 's/FuzzFunction/'$function'/' ./"${function,,}"_test.go + sed -i -e 's/mypackagebeingfuzzed/'$fuzzed_package'/' ./"${function,,}"_test.go + sed -i -e 's/TestFuzzCorpus/Test'$function'Corpus/' ./"${function,,}"_test.go + + # The repo is the module path/name, which is already created above in case it doesn't exist, + # but not always the same as the module path. This is necessary to handle SIV properly. + fuzzed_repo=$(go list $tags -f {{.Module}} "$path") + abspath_repo=`go list -m $tags -f {{.Dir}} $fuzzed_repo || go list $tags -f {{.Dir}} $fuzzed_repo` + # give equivalence to absolute paths in another file, as go test -cover uses golangish pkg.Dir + echo "s=$fuzzed_repo"="$abspath_repo"= > $OUT/$fuzzer.gocovpath + # Additional packages for which to get coverage. + pkgaddcov="" + # to prevent bash from failing about unbound variable + GO_COV_ADD_PKG_SET=${GO_COV_ADD_PKG:-} + if [[ -n "${GO_COV_ADD_PKG_SET}" ]]; then + pkgaddcov=","$GO_COV_ADD_PKG + abspath_repo=`go list -m $tags -f {{.Dir}} $GO_COV_ADD_PKG || go list $tags -f {{.Dir}} $GO_COV_ADD_PKG` + echo "s=^$GO_COV_ADD_PKG"="$abspath_repo"= >> $OUT/$fuzzer.gocovpath + fi + go test -run Test${function}Corpus -v $tags -coverpkg $fuzzed_repo/...$pkgaddcov -c -o $OUT/$fuzzer $path +else + # Compile and instrument all Go files relevant to this fuzz target. + echo "Running go-fuzz $tags -func $function -o $fuzzer.a $path" + go-fuzz $tags -func $function -o $fuzzer.a $path + + # Link Go code ($fuzzer.a) with fuzzing engine to produce fuzz target binary. + $CXX $CXXFLAGS $LIB_FUZZING_ENGINE $fuzzer.a -o $OUT/$fuzzer +fi +) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_honggfuzz b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_honggfuzz new file mode 100644 index 0000000000000000000000000000000000000000..cf206e46a4686462e1af5acc354efa13b8538976 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_honggfuzz @@ -0,0 +1,33 @@ +#!/bin/bash -eu +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo "Skipping compilation; using precompiled honggfuzz" + +cp $SRC/honggfuzz/honggfuzz.a $LIB_FUZZING_ENGINE +cp $SRC/honggfuzz/honggfuzz $OUT/ + +# Set flags necessary for netdriver compilation. +export LIB_HFND="-Wl,-u,LIBHFNETDRIVER_module_netdriver -Wl,--start-group $SRC/honggfuzz/libhfnetdriver/libhfnetdriver.a $SRC/honggfuzz/libhfcommon/libhfcommon.a -Wl,--end-group" + +export HFND_CXXFLAGS='-DHFND_FUZZING_ENTRY_FUNCTION_CXX(x,y)=extern const char* LIBHFNETDRIVER_module_netdriver;const char** LIBHFNETDRIVER_tmp1 = &LIBHFNETDRIVER_module_netdriver;extern "C" int HonggfuzzNetDriver_main(x,y);int HonggfuzzNetDriver_main(x,y)' +export HFND_CFLAGS='-DHFND_FUZZING_ENTRY_FUNCTION(x,y)=extern const char* LIBHFNETDRIVER_module_netdriver;const char** LIBHFNETDRIVER_tmp1 = &LIBHFNETDRIVER_module_netdriver;int HonggfuzzNetDriver_main(x,y);int HonggfuzzNetDriver_main(x,y)' + +# Custom coverage flags, roughly in sync with: +# https://github.com/google/honggfuzz/blob/oss-fuzz/hfuzz_cc/hfuzz-cc.c +export COVERAGE_FLAGS="-fsanitize-coverage=trace-pc-guard,indirect-calls,trace-cmp" + +echo " done." diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_javascript_fuzzer b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_javascript_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..83ece10aa814e7e8ee3440583ff124c4fa03764e --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_javascript_fuzzer @@ -0,0 +1,37 @@ +#!/bin/bash -eu +# 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. +# +################################################################################ + +project=$1 +# Path the fuzz target source file relative to the project's root. +fuzz_target=$2 +# Arguments to pass to Jazzer.js +jazzerjs_args=${@:3} + +# Copy source code into the $OUT directory and install Jazzer.js into the project. +if [ ! -d $OUT/$project ]; then + cp -r $SRC/$project $OUT/$project +fi + +fuzzer_basename=$(basename -s .js $fuzz_target) + +# Create an execution wrapper that executes Jazzer.js with the correct arguments. +echo "#!/bin/bash +# LLVMFuzzerTestOneInput so that the wrapper script is recognized as a fuzz target for 'check_build'. +project_dir=\$(dirname \"\$0\")/$project +\$project_dir/node_modules/@jazzer.js/core/dist/cli.js \$project_dir/$fuzz_target $jazzerjs_args \$JAZZERJS_EXTRA_ARGS -- \$@" > $OUT/$fuzzer_basename + +chmod +x $OUT/$fuzzer_basename diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_libfuzzer b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_libfuzzer new file mode 100644 index 0000000000000000000000000000000000000000..9acd0ccb64256e2b91e008df7ce1f1ee06ebd865 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_libfuzzer @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo -n "Compiling libFuzzer to $LIB_FUZZING_ENGINE... " +export LIB_FUZZING_ENGINE="-fsanitize=fuzzer" +if [ "$FUZZING_LANGUAGE" = "go" ]; then + export LIB_FUZZING_ENGINE="$LIB_FUZZING_ENGINE $GOPATH/gosigfuzz/gosigfuzz.o" +fi + +cp /usr/local/lib/clang/*/lib/$ARCHITECTURE-unknown-linux-gnu/libclang_rt.fuzzer.a $LIB_FUZZING_ENGINE_DEPRECATED +echo " done." diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_native_go_fuzzer b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_native_go_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..7a7fa67df811fa4d4a24f3f0d80fd17729fbb52b --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_native_go_fuzzer @@ -0,0 +1,60 @@ +#!/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. +# +################################################################################ + +function build_native_go_fuzzer() { + fuzzer=$1 + function=$2 + path=$3 + tags="-tags gofuzz" + + if [[ $SANITIZER == *coverage* ]]; then + current_dir=$(pwd) + mkdir $OUT/rawfuzzers || true + cd $abs_file_dir + go test $tags -c -run $fuzzer -o $OUT/$fuzzer -cover + cp "${fuzzer_filename}" "${OUT}/rawfuzzers/${fuzzer}" + + fuzzed_repo=$(go list $tags -f {{.Module}} "$path") + abspath_repo=`go list -m $tags -f {{.Dir}} $fuzzed_repo || go list $tags -f {{.Dir}} $fuzzed_repo` + # give equivalence to absolute paths in another file, as go test -cover uses golangish pkg.Dir + echo "s=$fuzzed_repo"="$abspath_repo"= > $OUT/$fuzzer.gocovpath + + cd $current_dir + else + go-118-fuzz-build $tags -o $fuzzer.a -func $function $abs_file_dir + $CXX $CXXFLAGS $LIB_FUZZING_ENGINE $fuzzer.a -o $OUT/$fuzzer + fi +} + +path=$1 +function=$2 +fuzzer=$3 +tags="-tags gofuzz" + +# Get absolute path. +abs_file_dir=$(go list $tags -f {{.Dir}} $path) + +# TODO(adamkorcz): Get rid of "-r" flag here. +fuzzer_filename=$(grep -r -l --include='*.go' -s "$function" "${abs_file_dir}") + +# Test if file contains a line with "func $function" and "testing.F". +if [ $(grep -r "func $function" $fuzzer_filename | grep "testing.F" | wc -l) -eq 1 ] +then + build_native_go_fuzzer $fuzzer $function $abs_file_dir +else + echo "Could not find the function: func ${function}(f *testing.F)" +fi diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_python_fuzzer b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_python_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..a36c05f3d1a2b2abb3ca492cf26022486cf33ebf --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/compile_python_fuzzer @@ -0,0 +1,128 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ + +# In order to enable PySecSan for a given module, set the environment +# variable ENABLE_PYSECSAN="YES" + +fuzzer_path=$1 +shift 1 + +fuzzer_basename=$(basename -s .py $fuzzer_path) +fuzzer_package=${fuzzer_basename}.pkg + +PYFUZZ_WORKPATH=$SRC/pyfuzzworkdir/ +FUZZ_WORKPATH=$PYFUZZ_WORKPATH/$fuzzer_basename + +if [[ $SANITIZER = *introspector* ]]; then + # Extract the source package the fuzzer targets. This must happen before + # we enter the virtual environment in the following lines because we need + # to use the same python environment that installed the fuzzer dependencies. + python3 /fuzz-introspector/frontends/python/prepare_fuzz_imports.py $fuzzer_path isossfuzz + + # We must ensure python3.9, this is because we use certain + # AST logic from there. + # The below should probably be refined + apt-get install -y python3.9 + apt-get update + apt-get install -y python3-pip + python3.9 -m pip install virtualenv + python3.9 -m virtualenv .venv + . .venv/bin/activate + pip3 install pyyaml + export PYTHONPATH="/fuzz-introspector/frontends/python/PyCG" + + ARGS="--fuzzer $fuzzer_path" + if [ -n "${PYFUZZPACKAGE-}" ]; then + ARGS="$ARGS --package=${PYFUZZPACKAGE}" + fi + python /fuzz-introspector/frontends/python/main.py $ARGS + ls -la ./ + exit 0 +fi + +# In coverage mode prepend coverage logic to the fuzzer source +if [[ $SANITIZER = *coverage* ]]; then + cat < coverage_wrapper.py +###### Coverage stub +import atexit +import coverage +cov = coverage.coverage(data_file='.coverage', cover_pylib=True) +cov.start() +# Register an exist handler that will print coverage +def exit_handler(): + cov.stop() + cov.save() +atexit.register(exit_handler) +####### End of coverage stub +EOF + + # Prepend stub and create tmp file + cat coverage_wrapper.py $fuzzer_path > tmp_fuzzer_coverage.py + + # Overwrite existing fuzzer with new fuzzer that has stub + mv tmp_fuzzer_coverage.py $fuzzer_path +fi + +# If PYSECSAN is enabled, ensure that we can build with it. +if [[ ${ENABLE_PYSECSAN:-"0"} != "0" ]]; +then + # Make sure pysecsan is installed + if [[ ! -d "/pysecsan" ]]; + then + pushd /usr/local/lib/sanitizers/pysecsan + python3 -m pip install . + popd + fi + + cat < pysecsan_wrapper.py +import pysecsan; pysecsan.add_hooks(); +EOF + + # Prepend stub and create tmp file + cat pysecsan_wrapper.py $fuzzer_path > tmp_fuzzer_pysecsan.py + + # Overwrite existing fuzzer with new fuzzer that has stub + mv tmp_fuzzer_pysecsan.py $fuzzer_path +fi + +rm -rf $PYFUZZ_WORKPATH +mkdir $PYFUZZ_WORKPATH $FUZZ_WORKPATH + +pyinstaller --distpath $OUT --workpath=$FUZZ_WORKPATH --onefile --name $fuzzer_package "$@" $fuzzer_path + +# Disable executable bit from package as OSS-Fuzz uses executable bits to +# identify fuzz targets. We re-enable the executable bit in wrapper script +# below. +chmod -x $OUT/$fuzzer_package + +# In coverage mode save source files of dependencies in pyinstalled binary +if [[ $SANITIZER = *coverage* ]]; then + rm -rf /medio/ + python3 /usr/local/bin/python_coverage_helper.py $FUZZ_WORKPATH "/medio" + zip -r $fuzzer_package.deps.zip /medio + mv $fuzzer_package.deps.zip $OUT/ +fi + +# Create execution wrapper. +echo "#!/bin/sh +# LLVMFuzzerTestOneInput for fuzzer detection. +this_dir=\$(dirname \"\$0\") +chmod +x \$this_dir/$fuzzer_package +LD_PRELOAD=\$this_dir/sanitizer_with_fuzzer.so \ +ASAN_OPTIONS=\$ASAN_OPTIONS:symbolize=1:external_symbolizer_path=\$this_dir/llvm-symbolizer:detect_leaks=0 \ +\$this_dir/$fuzzer_package \$@" > $OUT/$fuzzer_basename +chmod +x $OUT/$fuzzer_basename diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/debug_afl b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/debug_afl new file mode 100644 index 0000000000000000000000000000000000000000..c53dae8156d623620be6750bf242ed714a182dcf --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/debug_afl @@ -0,0 +1,40 @@ +#!/bin/bash +# 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. +# +################################################################################ + +# Source this file for afl++ debug sessions. +apt-get update +apt-get install -y strace gdb vim joe psmisc + +pushd $SRC/aflplusplus > /dev/null +git checkout dev +git pull +test -n "$1" && { git checkout "$1" ; git pull ; } +CFLAGS_SAVE="$CFLAGS" +CXXFLAGS_SAVE="$CXXFLAGS" +unset CFLAGS +unset CXXFLAGS +make +export CFLAGS="$CFLAGS_SAVE" +export CXXFLAGS="$CXXFLAGS_SAVE" +popd > /dev/null + +export ASAN_OPTIONS="detect_leaks=0:symbolize=0:detect_odr_violation=0:abort_on_error=1" +export AFL_LLVM_LAF_ALL=1 +export AFL_LLVM_CMPLOG=1 +touch "$OUT/afl_cmplog.txt" +export AFL_LLVM_DICT2FILE=$OUT/afl++.dict +ulimit -c unlimited diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/detect_repo.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/detect_repo.py new file mode 100644 index 0000000000000000000000000000000000000000..e677e102329f2c7b3efb49eb77df19f83b46ce9f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/detect_repo.py @@ -0,0 +1,182 @@ +# Copyright 2019 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 to get the the name of a git repo containing a specific commit +inside of an OSS-Fuzz project. + +Example Usage: + + python detect_repo.py --src_dir /src --example_commit + b534f03eecd8a109db2b085ab24d419b6486de97 + +Prints the location of the git remote repo as well as the repo's name +seperated by a space. + + https://github.com/VirusTotal/yara.git yara + +""" +import argparse +import logging +import os +import subprocess + +GO_PATH = '/root/go/src/' + + +def main(): + """Function to get a git repo's url and name referenced by OSS-Fuzz + Dockerfile. + + Raises: + ValueError when a commit or a ref is not provided. + """ + parser = argparse.ArgumentParser( + description= + 'Finds a specific git repo in an oss-fuzz project\'s docker file.') + parser.add_argument('--repo_name', help='The name of the git repo.') + parser.add_argument('--src_dir', help='The location of the possible repo.') + parser.add_argument('--example_commit', + help='A commit SHA referencing the project\'s main repo.') + + args = parser.parse_args() + if not args.repo_name and not args.example_commit: + raise ValueError( + 'Requires an example commit or a repo name to find repo location.') + if args.src_dir: + src_dir = args.src_dir + else: + src_dir = os.environ.get('SRC', '/src') + + for single_dir in get_dirs_to_search(src_dir, args.repo_name): + full_path = os.path.join(src_dir, single_dir) + if not os.path.isdir(full_path): + continue + if args.example_commit and check_for_commit(full_path, args.example_commit): + print('Detected repo:', get_repo(full_path), full_path) + return + if args.repo_name and check_for_repo_name(full_path, args.repo_name): + print('Detected repo:', get_repo(full_path), full_path) + return + logging.error('No git repos with specific commit: %s found in %s', + args.example_commit, src_dir) + + +def get_dirs_to_search(src_dir, repo_name): + """Gets a list of directories to search for the main git repo. + + Args: + src_dir: The location set for the projects SRC. + repo_name: The name of the repo you are searching for. + + Returns: + A list of directorys to search. + """ + dirs_to_search = os.listdir(src_dir) + if os.path.exists(GO_PATH) and repo_name: + for root, dirs, _ in os.walk(GO_PATH): + for test_dir in dirs: + if repo_name in test_dir: + dirs_to_search.append(os.path.join(root, test_dir)) + return dirs_to_search + + +def get_repo(repo_path): + """Gets a git repo link from a specific directory in a docker image. + + Args: + repo_path: The directory on the image where the git repo exists. + + Returns: + The repo location or None. + """ + output, return_code = execute(['git', 'config', '--get', 'remote.origin.url'], + location=repo_path, + check_result=True) + if return_code == 0 and output: + return output.rstrip() + return None + + +def check_for_repo_name(repo_path, expected_repo_name): + """Returns True if the repo at |repo_path| repo_name matches + |expected_repo_name|. + + Args: + repo_path: The directory of a git repo. + expected_repo_name: The name of the target git repo. + """ + if not os.path.exists(os.path.join(repo_path, '.git')): + return False + + repo_url, _ = execute(['git', 'config', '--get', 'remote.origin.url'], + location=repo_path) + # Handle two common cases: + # https://github.com/google/syzkaller/ + # https://github.com/google/syzkaller.git + repo_url = repo_url.replace('.git', '').rstrip().rstrip('/') + actual_repo_name = repo_url.split('/')[-1] + return actual_repo_name == expected_repo_name + + +def check_for_commit(repo_path, commit): + """Checks a directory for a specific commit. + + Args: + repo_path: The name of the directory to test for the commit. + commit: The commit SHA to check for. + + Returns: + True if directory contains that commit. + """ + + # Check if valid git repo. + if not os.path.exists(os.path.join(repo_path, '.git')): + return False + + # Check if history fetch is needed. + if os.path.exists(os.path.join(repo_path, '.git', 'shallow')): + execute(['git', 'fetch', '--unshallow'], location=repo_path) + + # Check if commit is in history. + _, return_code = execute(['git', 'cat-file', '-e', commit], + location=repo_path) + return return_code == 0 + + +def execute(command, location, check_result=False): + """Runs a shell command in the specified directory location. + + Args: + command: The command as a list to be run. + location: The directory the command is run in. + check_result: Should an exception be thrown on failed command. + + Returns: + The stdout of the command, the error code. + + Raises: + RuntimeError: running a command resulted in an error. + """ + process = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=location) + output, err = process.communicate() + if check_result and (process.returncode or err): + raise RuntimeError( + 'Error: %s\n running command: %s\n return code: %s\n out %s\n' % + (err, command, process.returncode, output)) + if output is not None: + output = output.decode('ascii') + return output, process.returncode + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0243b3ac513e942825e445bf4786bc593f48a338 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py @@ -0,0 +1,121 @@ +# Copyright 2019 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. +"""Test the functionality of the detect_repo module. +This will consist of the following functional test: + 1. Determine if an OSS-Fuzz projects main repo can be detected from example + commits. + 2. Determine if an OSS-Fuzz project main repo can be detected from a + repo name. +""" +import os +import re +import sys +import tempfile +import unittest +from unittest import mock + +import detect_repo + +# Appending to path for access to repo_manager module. +# pylint: disable=wrong-import-position +sys.path.append( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) +import repo_manager +import test_repos +# pylint: enable=wrong-import-position + + +class TestCheckForRepoName(unittest.TestCase): + """Tests for check_for_repo_name.""" + + @mock.patch('os.path.exists', return_value=True) + @mock.patch('detect_repo.execute', + return_value=('https://github.com/google/syzkaller/', None)) + def test_go_get_style_url(self, _, __): + """Tests that check_for_repo_name works on repos that were downloaded using + go get.""" + self.assertTrue(detect_repo.check_for_repo_name('fake-path', 'syzkaller')) + + @mock.patch('os.path.exists', return_value=True) + @mock.patch('detect_repo.execute', + return_value=('https://github.com/google/syzkaller', None)) + def test_missing_git_and_slash_url(self, _, __): + """Tests that check_for_repo_name works on repos who's URLs do not end in + ".git" or "/".""" + self.assertTrue(detect_repo.check_for_repo_name('fake-path', 'syzkaller')) + + @mock.patch('os.path.exists', return_value=True) + @mock.patch('detect_repo.execute', + return_value=('https://github.com/google/syzkaller.git', None)) + def test_normal_style_repo_url(self, _, __): + """Tests that check_for_repo_name works on normally cloned repos.""" + self.assertTrue(detect_repo.check_for_repo_name('fake-path', 'syzkaller')) + + +@unittest.skipIf(not os.getenv('INTEGRATION_TESTS'), + 'INTEGRATION_TESTS=1 not set') +class DetectRepoIntegrationTest(unittest.TestCase): + """Class to test the functionality of the detect_repo module.""" + + def test_infer_main_repo_from_commit(self): + """Tests that the main repo can be inferred based on an example commit.""" + + with tempfile.TemporaryDirectory() as tmp_dir: + # Construct example repo's to check for commits. + for test_repo in test_repos.TEST_REPOS: + repo_manager.clone_repo_and_get_manager(test_repo.git_url, tmp_dir) + self.check_with_repo(test_repo.git_url, + test_repo.git_repo_name, + tmp_dir, + commit=test_repo.old_commit) + + def test_infer_main_repo_from_name(self): + """Tests that the main project repo can be inferred from a repo name.""" + with tempfile.TemporaryDirectory() as tmp_dir: + for test_repo in test_repos.TEST_REPOS: + repo_manager.clone_repo_and_get_manager(test_repo.git_url, tmp_dir) + self.check_with_repo(test_repo.git_url, test_repo.git_repo_name, + tmp_dir) + + def check_with_repo(self, repo_origin, repo_name, tmp_dir, commit=None): + """Checks the detect repo's main method for a specific set of inputs. + + Args: + repo_origin: URL of the git repo. + repo_name: The name of the directory it is cloned to. + tmp_dir: The location of the directory of git repos to be searched. + commit: The commit that should be used to look up the repo. + """ + command = ['python3', 'detect_repo.py', '--src_dir', tmp_dir] + + if commit: + command += ['--example_commit', commit] + else: + command += ['--repo_name', repo_name] + + out, _ = detect_repo.execute(command, + location=os.path.dirname( + os.path.realpath(__file__))) + match = re.search(r'\bDetected repo: ([^ ]+) ([^ ]+)', out.rstrip()) + if match and match.group(1) and match.group(2): + self.assertEqual(match.group(1), repo_origin) + self.assertEqual(match.group(2), os.path.join(tmp_dir, repo_name)) + else: + self.assertIsNone(repo_origin) + self.assertIsNone(repo_name) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_deps.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_deps.sh new file mode 100644 index 0000000000000000000000000000000000000000..777e4d1b69f3865207fba671457508662d0a49c2 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_deps.sh @@ -0,0 +1,44 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ + +# Install base-builder's dependencies in a architecture-aware way. + + +case $(uname -m) in + x86_64) + dpkg --add-architecture i386 + ;; +esac + +apt-get update && \ + apt-get install -y \ + binutils-dev \ + build-essential \ + curl \ + wget \ + git \ + jq \ + patchelf \ + rsync \ + subversion \ + zip + +case $(uname -m) in + x86_64) + apt-get install -y libc6-dev-i386 + ;; +esac diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_go.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_go.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a93bd76702f33c0c3319fcc74ddbfd42852057 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_go.sh @@ -0,0 +1,43 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +cd /tmp + +wget https://go.dev/dl/go1.23.4.linux-amd64.tar.gz +mkdir temp-go +tar -C temp-go/ -xzf go1.23.4.linux-amd64.tar.gz + +mkdir /root/.go/ +mv temp-go/go/* /root/.go/ +rm -rf temp-go + +echo 'Set "GOPATH=/root/go"' +echo 'Set "PATH=$PATH:/root/.go/bin:$GOPATH/bin"' + +go install github.com/mdempsky/go114-fuzz-build@latest +ln -s $GOPATH/bin/go114-fuzz-build $GOPATH/bin/go-fuzz + +# Build signal handler +if [ -f "$GOPATH/gosigfuzz/gosigfuzz.c" ]; then + clang -c $GOPATH/gosigfuzz/gosigfuzz.c -o $GOPATH/gosigfuzz/gosigfuzz.o +fi + +cd /tmp +git clone https://github.com/AdamKorcz/go-118-fuzz-build +cd go-118-fuzz-build +go build +mv go-118-fuzz-build $GOPATH/bin/ diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_java.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_java.sh new file mode 100644 index 0000000000000000000000000000000000000000..d7743c6cd37c9c09f6459c3ed1805d7ddd4b56df --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_java.sh @@ -0,0 +1,31 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Install OpenJDK 17 and trim its size by removing unused components. This enables using Jazzer's mutation framework. +cd /tmp +curl --silent -L -O https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-x64_bin.tar.gz && \ +mkdir -p $JAVA_HOME +tar -xz --strip-components=1 -f openjdk-17.0.2_linux-x64_bin.tar.gz --directory $JAVA_HOME && \ +rm -f openjdk-17.0.2_linux-x64_bin.tar.gz +rm -rf $JAVA_HOME/jmods $JAVA_HOME/lib/src.zip + +# Install OpenJDK 15 and trim its size by removing unused components. Some projects only run with Java 15. +curl --silent -L -O https://download.java.net/java/GA/jdk15.0.2/0d1cfde4252546c6931946de8db48ee2/7/GPL/openjdk-15.0.2_linux-x64_bin.tar.gz && \ +mkdir -p $JAVA_15_HOME +tar -xz --strip-components=1 -f openjdk-15.0.2_linux-x64_bin.tar.gz --directory $JAVA_15_HOME && \ +rm -f openjdk-15.0.2_linux-x64_bin.tar.gz +rm -rf $JAVA_15_HOME/jmods $JAVA_15_HOME/lib/src.zip diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_javascript.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_javascript.sh new file mode 100644 index 0000000000000000000000000000000000000000..232658b0484dc67202352a2bc9025168fd8e4aa0 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_javascript.sh @@ -0,0 +1,27 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ +# see installation instructions: https://github.com/nodesource/distributions#available-architectures +apt-get update +apt-get install -y ca-certificates curl gnupg +mkdir -p /etc/apt/keyrings +curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg + +NODE_MAJOR=20 +echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list + +apt-get update +apt-get install nodejs -y diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_python.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_python.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d5fcb96450a9e402d1c8a5af30e09bc42bd36ff --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_python.sh @@ -0,0 +1,23 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo "ATHERIS INSTALL" +unset CFLAGS CXXFLAGS +# PYI_STATIC_ZLIB=1 is needed for installing pyinstaller 5.0 +export PYI_STATIC_ZLIB=1 +LIBFUZZER_LIB=$( echo /usr/local/lib/clang/*/lib/x86_64-unknown-linux-gnu/libclang_rt.fuzzer_no_main.a ) pip3 install -v --no-cache-dir "atheris>=2.3.0" "pyinstaller==6.10.0" "setuptools==72.1.0" "coverage==6.3.2" +rm -rf /tmp/* diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_ruby.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_ruby.sh new file mode 100644 index 0000000000000000000000000000000000000000..76e996727197aa93b49dfbb935dff7b57c077341 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_ruby.sh @@ -0,0 +1,25 @@ +#!/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. +# +################################################################################ + +apt update +apt install -y lsb-release software-properties-common gnupg2 binutils xz-utils libyaml-dev +gpg2 --keyserver keyserver.ubuntu.com --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB +curl -sSL https://get.rvm.io | bash + +. /etc/profile.d/rvm.sh + +rvm install ruby-3.3.1 diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_rust.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_rust.sh new file mode 100644 index 0000000000000000000000000000000000000000..45fbec6ed4d6afeec0897f38c9a7c1bab0c4eafa --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_rust.sh @@ -0,0 +1,22 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +curl https://sh.rustup.rs | sh -s -- -y --default-toolchain=$RUSTUP_TOOLCHAIN --profile=minimal +cargo install cargo-fuzz --locked && rm -rf /rust/registry +# Needed to recompile rust std library for MSAN +rustup component add rust-src +cp -r /usr/local/lib/x86_64-unknown-linux-gnu/* /usr/local/lib/ diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_swift.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_swift.sh new file mode 100644 index 0000000000000000000000000000000000000000..1d0d16701f39965afc493e9cb64bc0a6f76f4c16 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/install_swift.sh @@ -0,0 +1,67 @@ +#!/bin/bash -eux +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + + +SWIFT_PACKAGES="wget \ + binutils \ + git \ + gnupg2 \ + libc6-dev \ + libcurl4 \ + libedit2 \ + libgcc-9-dev \ + libpython2.7 \ + libsqlite3-0 \ + libstdc++-9-dev \ + libxml2 \ + libz3-dev \ + pkg-config \ + tzdata \ + zlib1g-dev" +SWIFT_SYMBOLIZER_PACKAGES="build-essential make cmake ninja-build git python3 g++-multilib binutils-dev zlib1g-dev" +apt-get update && apt install -y $SWIFT_PACKAGES && \ + apt install -y $SWIFT_SYMBOLIZER_PACKAGES --no-install-recommends + + +wget -q https://download.swift.org/swift-5.10.1-release/ubuntu2004/swift-5.10.1-RELEASE/swift-5.10.1-RELEASE-ubuntu20.04.tar.gz +tar xzf swift-5.10.1-RELEASE-ubuntu20.04.tar.gz +cp -r swift-5.10.1-RELEASE-ubuntu20.04/usr/* /usr/ +rm -rf swift-5.10.1-RELEASE-ubuntu20.04.tar.gz swift-5.10.1-RELEASE-ubuntu20.04/ +# TODO: Move to a seperate work dir +git clone https://github.com/llvm/llvm-project.git +cd llvm-project +git checkout 63bf228450b8403e0c5e828d276be47ffbcd00d0 # TODO: Keep in sync with base-clang. +git apply ../llvmsymbol.diff --verbose +cmake -G "Ninja" \ + -DLIBCXX_ENABLE_SHARED=OFF \ + -DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON \ + -DLIBCXXABI_ENABLE_SHARED=OFF \ + -DCMAKE_BUILD_TYPE=Release \ + -DLLVM_TARGETS_TO_BUILD=X86 \ + -DCMAKE_C_COMPILER=clang \ + -DCMAKE_CXX_COMPILER=clang++ \ + -DLLVM_BUILD_TESTS=OFF \ + -DLLVM_INCLUDE_TESTS=OFF llvm +ninja -j$(nproc) llvm-symbolizer +cp bin/llvm-symbolizer /usr/local/bin/llvm-symbolizer-swift + +cd $SRC +rm -rf llvm-project llvmsymbol.diff + +# TODO: Cleanup packages +apt-get remove --purge -y wget zlib1g-dev +apt-get autoremove -y diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/build_jcc.bash b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/build_jcc.bash new file mode 100644 index 0000000000000000000000000000000000000000..6a62c22890f0edbb24ccdd73d5a8d089f44e7632 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/build_jcc.bash @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# +# 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. +# +################################################################################ + +go build jcc.go +go build jcc2.go +gsutil cp jcc gs://clusterfuzz-builds/jcc/clang++-jcc +gsutil cp jcc gs://clusterfuzz-builds/jcc/clang-jcc + +gsutil cp jcc2 gs://clusterfuzz-builds/jcc/clang++-jcc2 +gsutil cp jcc2 gs://clusterfuzz-builds/jcc/clang-jcc2 diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/go.mod b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..c32967d291b649cbe030aae34d0121b02a971647 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/go.mod @@ -0,0 +1,3 @@ +module github.com/google/jcc + +go 1.21 diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc.go b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc.go new file mode 100644 index 0000000000000000000000000000000000000000..7eda88dd8a309908d475245261d76199817223f2 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc.go @@ -0,0 +1,88 @@ +// 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. + +package main + +import ( + "bytes" + "fmt" + "log" + "os" + "os/exec" + "path/filepath" +) + +func ExecBuildCommand(bin string, args []string) (int, string, string) { + // Executes the original command. + cmd := exec.Command(bin, args...) + var outb, errb bytes.Buffer + cmd.Stdout = &outb + cmd.Stderr = &errb + cmd.Stdin = os.Stdin + cmd.Run() + return cmd.ProcessState.ExitCode(), outb.String(), errb.String() +} + +func Compile(bin string, args []string) (int, string, string) { + // Run the actual command. + return ExecBuildCommand(bin, args) +} + +func AppendStringToFile(filepath, new_content string) error { + // Appends |new_content| to the content of |filepath|. + file, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } + defer file.Close() + + _, err = file.WriteString(new_content) + return err +} + +func WriteStdErrOut(args []string, outstr string, errstr string) { + // Prints |outstr| to stdout, prints |errstr| to stderr, and saves |errstr| to err.log. + fmt.Print(outstr) + fmt.Fprint(os.Stderr, errstr) + // Record what compile args produced the error and the error itself in log file. + AppendStringToFile("/tmp/err.log", fmt.Sprintf("%s\n", args)+errstr) +} + +func main() { + f, err := os.OpenFile("/tmp/jcc.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + + if err != nil { + log.Println(err) + } + defer f.Close() + if _, err := f.WriteString(fmt.Sprintf("%s\n", os.Args)); err != nil { + log.Println(err) + } + + args := os.Args[1:] + basename := filepath.Base(os.Args[0]) + isCPP := basename == "clang++-jcc" + newArgs := args + + var bin string + if isCPP { + bin = "clang++" + } else { + bin = "clang" + } + fullCmdArgs := append([]string{bin}, newArgs...) + retcode, out, errstr := Compile(bin, newArgs) + WriteStdErrOut(fullCmdArgs, out, errstr) + os.Exit(retcode) +} diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc2.go b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc2.go new file mode 100644 index 0000000000000000000000000000000000000000..a2d9e73ea2f58c2b1ed3279fe19ac4d6a43e8126 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc2.go @@ -0,0 +1,401 @@ +// 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. + +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/fs" + "io/ioutil" + "log" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" +) + +var MaxMissingHeaderFiles = 10 +var CppifyHeadersMagicString = "\n/* JCCCppifyHeadersMagicString */\n" + +func CopyFile(src string, dst string) { + contents, err := ioutil.ReadFile(src) + if err != nil { + panic(err) + } + err = ioutil.WriteFile(dst, contents, 0644) + if err != nil { + panic(err) + } +} + +func TryFixCCompilation(cmdline []string) ([]string, int, string, string) { + var newFile string = "" + for i, arg := range cmdline { + if !strings.HasSuffix(arg, ".c") { + continue + } + if _, err := os.Stat(arg); errors.Is(err, os.ErrNotExist) { + continue + } + newFile = strings.TrimSuffix(arg, ".c") + newFile += ".cpp" + CopyFile(arg, newFile) + CppifyHeaderIncludesFromFile(newFile) + cmdline[i] = newFile + break + } + if newFile == "" { + return []string{}, 1, "", "" + } + cppBin := "clang++" + newCmdline := []string{"-stdlib=libc++"} + newCmdline = append(cmdline, newCmdline...) + newFullArgs := append([]string{cppBin}, newCmdline...) + + retcode, out, err := Compile(cppBin, newCmdline) + if retcode == 0 { + return newFullArgs, retcode, out, err + } + correctedCmdline, corrected, _ := CorrectMissingHeaders(cppBin, newCmdline) + if corrected { + return append([]string{cppBin}, correctedCmdline...), 0, "", "" + } + return newFullArgs, retcode, out, err +} + +func ExtractMissingHeader(compilerOutput string) (string, bool) { + r := regexp.MustCompile(`fatal error: ['|<](?P
[a-zA-z0-9\/\.]+)['|>] file not found`) + matches := r.FindStringSubmatch(compilerOutput) + if len(matches) == 0 { + return "", false + } + return matches[1], true +} + +func ReplaceMissingHeaderInFile(srcFilename, curHeader, replacementHeader string) error { + srcFile, err := os.Open(srcFilename) + if err != nil { + return err + } + srcBytes, err := ioutil.ReadAll(srcFile) + if err != nil { + return err + } + src := string(srcBytes) + newSrc := ReplaceMissingHeader(src, curHeader, replacementHeader) + b := []byte(newSrc) + err = ioutil.WriteFile(srcFilename, b, 0644) + if err != nil { + return err + } + return nil +} + +func ReplaceMissingHeader(src, curHeader, replacementHeader string) string { + re := regexp.MustCompile(`#include ["|<]` + curHeader + `["|>]\n`) + replacement := "#include \"" + replacementHeader + "\"\n" + return re.ReplaceAllString(src, replacement) +} + +func GetHeaderCorrectedFilename(compilerErr string) (string, string, bool) { + re := regexp.MustCompile(`(?P[a-z\/\-\_0-9A-z\.]+):.* fatal error: .* file not found`) + matches := re.FindStringSubmatch(compilerErr) + if len(matches) < 2 { + return "", "", false + } + oldFilename := matches[1] + base := filepath.Base(oldFilename) + root := filepath.Dir(oldFilename) + newFilename := root + "/jcc-corrected-" + base + return oldFilename, newFilename, true +} + +func GetHeaderCorrectedCmd(cmd []string, compilerErr string) ([]string, string, error) { + oldFilename, newFilename, success := GetHeaderCorrectedFilename(compilerErr) + if !success { + return cmd, "", errors.New("Couldn't find buggy file") + } + // Make new cmd. + newCmd := make([]string, len(cmd)) + for i, part := range cmd { + newCmd[i] = part + } + found := false + for i, filename := range newCmd { + if filename == oldFilename { + newCmd[i] = newFilename + found = true + break + } + } + CopyFile(oldFilename, newFilename) + if found { + return newCmd, newFilename, nil + } + return cmd, "", errors.New("Couldn't find file") +} + +func CorrectMissingHeaders(bin string, cmd []string) ([]string, bool, error) { + + _, _, stderr := Compile(bin, cmd) + cmd, correctedFilename, err := GetHeaderCorrectedCmd(cmd, stderr) + if err != nil { + return cmd, false, err + } + for i := 0; i < MaxMissingHeaderFiles; i++ { + fixed, hasBrokenHeaders := TryCompileAndFixHeadersOnce(bin, cmd, correctedFilename) + if fixed { + return cmd, true, nil + } + if !hasBrokenHeaders { + return cmd, false, nil + } + } + return cmd, false, nil +} + +func ExecBuildCommand(bin string, args []string) (int, string, string) { + // Executes the original command. + cmd := exec.Command(bin, args...) + var outb, errb bytes.Buffer + cmd.Stdout = &outb + cmd.Stderr = &errb + cmd.Stdin = os.Stdin + cmd.Run() + return cmd.ProcessState.ExitCode(), outb.String(), errb.String() +} + +func Compile(bin string, args []string) (int, string, string) { + // Run the actual command. + return ExecBuildCommand(bin, args) +} + +func TryCompileAndFixHeadersOnce(bin string, cmd []string, filename string) (fixed, hasBrokenHeaders bool) { + retcode, _, err := Compile(bin, cmd) + if retcode == 0 { + fixed = true + hasBrokenHeaders = false + return + } + missingHeader, isMissing := ExtractMissingHeader(err) + if !isMissing { + fixed = false + hasBrokenHeaders = false + return + } + + newHeaderPath, found := FindMissingHeader(missingHeader) + if !found { + fixed = false + hasBrokenHeaders = true + return false, true + } + ReplaceMissingHeaderInFile(filename, missingHeader, newHeaderPath) + return false, true +} + +func FindMissingHeader(missingHeader string) (string, bool) { + envVar := "JCC_MISSING_HEADER_SEARCH_PATH" + var searchPath string + searchPath, exists := os.LookupEnv(envVar) + if !exists { + searchPath = "/src" + } + searchPath, _ = filepath.Abs(searchPath) + var headerLocation string + missingHeader = "/" + missingHeader + find := func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + if strings.HasSuffix(path, missingHeader) { + headerLocation = path + return nil + } + return nil + } + filepath.WalkDir(searchPath, find) + if headerLocation == "" { + return "", false + } + return headerLocation, true +} + +func CppifyHeaderIncludesFromFile(srcFile string) error { + contentsBytes, err := ioutil.ReadFile(srcFile) + if err != nil { + return err + } + contents := string(contentsBytes[:]) + contents, err = CppifyHeaderIncludes(contents) + if err != nil { + return err + } + b := []byte(contents) + err = ioutil.WriteFile(srcFile, b, 0644) + return err +} + +func CppifyHeaderIncludes(contents string) (string, error) { + shouldCppify, exists := os.LookupEnv("JCC_CPPIFY_PROJECT_HEADERS") + if !exists || strings.Compare(shouldCppify, "0") == 0 { + return contents, nil + } + if strings.Contains(contents, CppifyHeadersMagicString) { + return contents, nil + } + re := regexp.MustCompile(`\#include \"(?P
.+)\"\n`) + matches := re.FindAllStringSubmatch(contents, -1) + if len(matches) == 0 { + return "", nil // !!! + } + for i, match := range matches { + if i == 0 { + // So we don't cppify twice. + contents += CppifyHeadersMagicString + } + oldStr := match[0] + replacement := "extern \"C\" {\n#include \"" + match[1] + "\"\n}\n" + contents = strings.Replace(contents, oldStr, replacement, 1) + if strings.Compare(contents, "") == 0 { + panic("Failed to replace") + } + } + return contents, nil +} + +func AppendStringToFile(filepath, new_content string) error { + // Appends |new_content| to the content of |filepath|. + file, err := os.OpenFile(filepath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + return err + } + defer file.Close() + + _, err = file.WriteString(new_content) + return err +} + +func WriteStdErrOut(args []string, outstr string, errstr string) { + // Prints |outstr| to stdout, prints |errstr| to stderr, and saves |errstr| to err.log. + fmt.Print(outstr) + fmt.Fprint(os.Stderr, errstr) + // Record what compile args produced the error and the error itself in log file. + AppendStringToFile("/workspace/err.log", fmt.Sprintf("%s\n", args)+errstr) +} + +func main() { + f, err := os.OpenFile("/tmp/jcc.log", os.O_CREATE|os.O_WRONLY, 0644) + if err != nil { + log.Println(err) + } + defer f.Close() + if _, err := f.WriteString(fmt.Sprintf("%s\n", os.Args)); err != nil { + log.Println(err) + } + + args := os.Args[1:] + if args[0] == "unfreeze" { + fmt.Println("unfreeze") + unfreeze() + } + basename := filepath.Base(os.Args[0]) + isCPP := basename == "clang++-jcc" + newArgs := append(args, "-w") + + var bin string + if isCPP { + bin = "clang++" + newArgs = append(args, "-stdlib=libc++") + } else { + bin = "clang" + } + fullCmdArgs := append([]string{bin}, newArgs...) + if IsCompilingTarget(fullCmdArgs) { + WriteTargetArgsAndCommitImage(fullCmdArgs) + os.Exit(0) + } + retcode, out, errstr := Compile(bin, newArgs) + WriteStdErrOut(fullCmdArgs, out, errstr) + os.Exit(retcode) +} + +type BuildCommand struct { + CWD string `json:"CWD"` + CMD []string `json:"CMD"` +} + +func WriteTargetArgsAndCommitImage(cmdline []string) { + log.Println("WRITE COMMAND") + f, _ := os.OpenFile("/out/statefile.json", os.O_CREATE|os.O_WRONLY, 0644) + wd, _ := os.Getwd() + buildcmd := BuildCommand{ + CWD: wd, + CMD: cmdline, + } + jsonData, _ := json.Marshal(buildcmd) + f.Write(jsonData) + f.Close() + hostname, _ := os.Hostname() + dockerArgs := []string{"commit", hostname, "frozen"} + cmd := exec.Command("docker", dockerArgs...) + var outb, errb bytes.Buffer + cmd.Stdout = &outb + cmd.Stderr = &errb + cmd.Stdin = os.Stdin + cmd.Run() + fmt.Println(outb.String(), errb.String()) + fmt.Println("COMMIT IMAGE") +} + +func IsCompilingTarget(cmdline []string) bool { + for _, arg := range cmdline { + // This can fail if people do crazy things they aren't supposed + // to such as using some other means to link in libFuzzer. + if arg == "-fsanitize=fuzzer" { + return true + } + if arg == "-lFuzzingEngine" { + return true + } + } + return false +} + +func parseCommand(command string) (string, []string) { + args := strings.Fields(command) + commandBin := args[0] + commandArgs := args[1:] + return commandBin, commandArgs +} + +func unfreeze() { + content, err := ioutil.ReadFile("/out/statefile.json") + if err != nil { + log.Fatal(err) + } + var command BuildCommand + json.Unmarshal(content, &command) + bin, args := parseCommand(strings.Join(command.CMD, " ")) + os.Chdir(command.CWD) + ExecBuildCommand(bin, args) + os.Exit(0) +} diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc_test.go b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc_test.go new file mode 100644 index 0000000000000000000000000000000000000000..bc76cb263f11969de5c15d19ebfe742a8e0f5f33 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/jcc_test.go @@ -0,0 +1,186 @@ +package main + +import ( + "fmt" + "os" + "strings" + "testing" +) + +func TestExtractMissingHeader(t *testing.T) { + missingHeaderMessage := `path/to/file.cpp:8:10: fatal error: 'missingheader.h' file not found + + #include "missingheader.h" + + ^~~~~~~~~~~~ + + 1 error generated. + ` + + res, _ := ExtractMissingHeader(missingHeaderMessage) + expected := "missingheader.h" + if strings.Compare(res, expected) != 0 { + t.Errorf("Got: %s. Expected: %s.", res, expected) + } +} + +func TestGetHeaderCorrectedFilename(t *testing.T) { + missingHeaderMessage := `path/to/file.cpp:8:10: fatal error: 'missingheader.h' file not found + + #include "missingheader.h" + + ^~~~~~~~~~~~ + + 1 error generated. + ` + _, correctedFilename, _ := GetHeaderCorrectedFilename(missingHeaderMessage) + expected := "path/to/jcc-corrected-file.cpp" + if strings.Compare(correctedFilename, expected) != 0 { + t.Errorf("Got: %s. Expected: %s.", correctedFilename, expected) + } +} + +func TestFindMissingHeader(t *testing.T) { + pwd, _ := os.Getwd() + t.Setenv("JCC_MISSING_HEADER_SEARCH_PATH", pwd) + + location, _ := FindMissingHeader("header.h") + expected := pwd + "/testdata/path/to/header.h" + if strings.Compare(location, expected) != 0 { + t.Errorf("Got: %s. Expected: %s.", location, expected) + } +} + +func TestCorrectMissingHeaders(t *testing.T) { + pwd, _ := os.Getwd() + t.Setenv("JCC_MISSING_HEADER_SEARCH_PATH", pwd) + cfile := pwd + "/testdata/cfile.c" + cmd := [4]string{"-fsanitize=address", cfile, "-o", "/tmp/blah"} + res, err := CorrectMissingHeaders("clang", cmd[:]) + if !res { + fmt.Println(err) + t.Errorf("Expected successful compilation") + } +} + +func TestGetHeaderCorrectedCmd(t *testing.T) { + compilerErr := `testdata/cpp.cc:8:10: fatal error: 'missingheader.h' file not found + + #include "missingheader.h" + + ^~~~~~~~~~~~ + + 1 error generated. + ` + + cmd := [3]string{"-fsanitize=address", "file.cpp", "path/to/cpp.cc"} + expectedFixedCmd := [3]string{"-fanitize=address", "file.cpp", "path/to/jcc-corrected-cpp.cc"} + fixedCmd, _, _ := GetHeaderCorrectedCmd(cmd[:], compilerErr) + if strings.Compare(fixedCmd[1], expectedFixedCmd[1]) != 0 { + t.Errorf("Expected %s, got: %s", expectedFixedCmd, fixedCmd) + } +} + +func TestCppifyHeaderIncludes(t *testing.T) { + t.Setenv("JCC_CPPIFY_PROJECT_HEADERS", "1") + src := `// Copyright blah +#include + +#include "fuzz.h" +#include "x/y.h" +extern "C" LLVMFuzzerTestOneInput(uint8_t* data, size_t sz) { + return 0; +}` + newFile, _ := CppifyHeaderIncludes(src) + expected := `// Copyright blah +#include + +extern "C" { +#include "fuzz.h" +} +extern "C" { +#include "x/y.h" +} +extern "C" LLVMFuzzerTestOneInput(uint8_t* data, size_t sz) { + return 0; +} +/* JCCCppifyHeadersMagicString */ +` + if strings.Compare(newFile, expected) != 0 { + t.Errorf("Expected: %s, got: %s", expected, newFile) + } +} + +func TestCppifyHeaderIncludesShouldnt(t *testing.T) { + src := `// Copyright blah +#include + +#include "fuzz.h" +#include "x/y.h" +extern "C" LLVMFuzzerTestOneInput(uint8_t* data, size_t sz) { + return 0; +}` + newFile, _ := CppifyHeaderIncludes(src) + if strings.Compare(newFile, src) != 0 { + t.Errorf("Expected: %s. Got: %s", src, newFile) + } +} + +func TestCppifyHeaderIncludesAlready(t *testing.T) { + src := `// Copyright blah +#include + +#include "fuzz.h" +#include "x/y.h" +extern "C" LLVMFuzzerTestOneInput(uint8_t* data, size_t sz) { + return 0; +} +/* JCCCppifyHeadersMagicString */ +` + newFile, _ := CppifyHeaderIncludes(src) + if strings.Compare(newFile, src) != 0 { + t.Errorf("Expected %s, got: %s", src, newFile) + } +} + +func TestExtractMissingHeaderNonHeaderFailure(t *testing.T) { + missingHeaderMessage := `clang: error: no such file or directory: 'x' +clang: error: no input files` + + header, res := ExtractMissingHeader(missingHeaderMessage) + if res { + t.Errorf("Expected no match, got: %s", header) + } +} + +func TestReplaceMissingHeader(t *testing.T) { + cfile := `// Copyright 2035 Robots +#include + +#include + +// Some libraries like OpenSSL will use brackets for their own headers. +#include + +int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { + return 0; +} +` + + res := ReplaceMissingHeader(cfile, "missingheader.h", "path/to/includes/missingheader.h") + expected := `// Copyright 2035 Robots +#include + +#include + +// Some libraries like OpenSSL will use brackets for their own headers. +#include "path/to/includes/missingheader.h" + +int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) { + return 0; +} +` + if strings.Compare(res, expected) != 0 { + t.Errorf("Got: %s. Expected: %s.", res, expected) + } +} diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/.gitignore b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ea1fd92c507fc7d30a9fb1cd71f0a03d42cfca1d --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/.gitignore @@ -0,0 +1,2 @@ +jcc-corrected-cfile.c +jcc-corrected-cfile.cpp \ No newline at end of file diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cfile.c b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cfile.c new file mode 100644 index 0000000000000000000000000000000000000000..e18c414d13060ac339cf2aafe5e782a8e55e9cc3 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cfile.c @@ -0,0 +1,18 @@ +// 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. + +#include "header.h" +int main() { + return 0; +} diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cpp.cc b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cpp.cc new file mode 100644 index 0000000000000000000000000000000000000000..e18c414d13060ac339cf2aafe5e782a8e55e9cc3 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cpp.cc @@ -0,0 +1,18 @@ +// 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. + +#include "header.h" +int main() { + return 0; +} diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/path/to/header.h b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/path/to/header.h new file mode 100644 index 0000000000000000000000000000000000000000..f4d3e90abd55b52ed6e8a02f23393165ccbf34ab --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/path/to/header.h @@ -0,0 +1,15 @@ +// 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. + +int xhg(void); diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/llvmsymbol.diff b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/llvmsymbol.diff new file mode 100644 index 0000000000000000000000000000000000000000..70181bf3997985bbd8ac568f3227e18ef423f6f2 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/llvmsymbol.diff @@ -0,0 +1,50 @@ +diff --git a/llvm/lib/DebugInfo/Symbolize/CMakeLists.txt b/llvm/lib/DebugInfo/Symbolize/CMakeLists.txt +index acfb3bd0e..a499ee2e0 100644 +--- a/llvm/lib/DebugInfo/Symbolize/CMakeLists.txt ++++ b/llvm/lib/DebugInfo/Symbolize/CMakeLists.txt +@@ -12,4 +12,11 @@ add_llvm_component_library(LLVMSymbolize + Object + Support + Demangle +- ) ++ ++ LINK_LIBS ++ /usr/lib/swift_static/linux/libswiftCore.a ++ /usr/lib/swift_static/linux/libicui18nswift.a ++ /usr/lib/swift_static/linux/libicuucswift.a ++ /usr/lib/swift_static/linux/libicudataswift.a ++ /usr/lib/x86_64-linux-gnu/libstdc++.so.6 ++) +diff --git a/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp b/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp +index fb4875f79..0030769ee 100644 +--- a/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp ++++ b/llvm/lib/DebugInfo/Symbolize/Symbolize.cpp +@@ -36,6 +36,13 @@ + #include + #include + ++ ++extern "C" char *swift_demangle(const char *mangledName, ++ size_t mangledNameLength, ++ char *outputBuffer, ++ size_t *outputBufferSize, ++ uint32_t flags); ++ + namespace llvm { + namespace symbolize { + +@@ -678,6 +685,14 @@ LLVMSymbolizer::DemangleName(const std::string &Name, + free(DemangledName); + return Result; + } ++ if (!Name.empty() && Name.front() == '$') { ++ char *DemangledName = swift_demangle(Name.c_str(), Name.length(), 0, 0, 0); ++ if (DemangledName) { ++ std::string Result = DemangledName; ++ free(DemangledName); ++ return Result; ++ } ++ } + + if (DbiModuleDescriptor && DbiModuleDescriptor->isWin32Module()) + return std::string(demanglePE32ExternCFunc(Name)); diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/ossfuzz_coverage_runner.go b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/ossfuzz_coverage_runner.go new file mode 100644 index 0000000000000000000000000000000000000000..d433da24638c96dbe58c77bf00a964f8834edd18 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/ossfuzz_coverage_runner.go @@ -0,0 +1,69 @@ +// 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. + +package mypackagebeingfuzzed + +import ( + "io/ioutil" + "os" + "runtime/pprof" + "testing" +) + +func TestFuzzCorpus(t *testing.T) { + dir := os.Getenv("FUZZ_CORPUS_DIR") + if dir == "" { + t.Logf("No fuzzing corpus directory set") + return + } + infos, err := ioutil.ReadDir(dir) + if err != nil { + t.Logf("Not fuzzing corpus directory %s", err) + return + } + filename := "" + defer func() { + if r := recover(); r != nil { + t.Error("Fuzz panicked in "+filename, r) + } + }() + profname := os.Getenv("FUZZ_PROFILE_NAME") + if profname != "" { + f, err := os.Create(profname + ".cpu.prof") + if err != nil { + t.Logf("error creating profile file %s\n", err) + } else { + _ = pprof.StartCPUProfile(f) + } + } + for i := range infos { + filename = dir + infos[i].Name() + data, err := ioutil.ReadFile(filename) + if err != nil { + t.Error("Failed to read corpus file", err) + } + FuzzFunction(data) + } + if profname != "" { + pprof.StopCPUProfile() + f, err := os.Create(profname + ".heap.prof") + if err != nil { + t.Logf("error creating heap profile file %s\n", err) + } + if err = pprof.WriteHeapProfile(f); err != nil { + t.Logf("error writing heap profile file %s\n", err) + } + f.Close() + } +} diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_afl b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_afl new file mode 100644 index 0000000000000000000000000000000000000000..d6e71f2c3428745fde2b9ff2519f0ff67b3ebaa2 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_afl @@ -0,0 +1,35 @@ +#!/bin/bash -eu +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo "Precompiling AFLplusplus" + +pushd $SRC/aflplusplus > /dev/null +make clean +# Unset CFLAGS and CXXFLAGS while building AFL since we don't want to slow it +# down with sanitizers. +SAVE_CXXFLAGS=$CXXFLAGS +SAVE_CFLAGS=$CFLAGS +unset CXXFLAGS +unset CFLAGS +export AFL_IGNORE_UNKNOWN_ENVS=1 +make clean +AFL_NO_X86=1 PYTHON_INCLUDE=/ make +make -C utils/aflpp_driver + +popd > /dev/null + +echo "Done." diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_centipede b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_centipede new file mode 100644 index 0000000000000000000000000000000000000000..362ef6a5b6e51bb5c81cbbc45ddab2660b966e0d --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_centipede @@ -0,0 +1,49 @@ +#!/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. +# +################################################################################ + +echo -n "Precompiling centipede" + +# Build Centipede with bazel. +cd "$SRC/fuzztest/centipede/" +apt-get update && apt-get install libssl-dev -y +unset CXXFLAGS CFLAGS +# We need to use an older version of BAZEL because fuzztest relies on WORKSPACE +# Ref: https://github.com/google/oss-fuzz/pull/12838#issue-2733821058 +export USE_BAZEL_VERSION=7.4.0 +echo 'build --cxxopt=-stdlib=libc++ --linkopt=-lc++' >> /tmp/centipede.bazelrc +bazel --bazelrc=/tmp/centipede.bazelrc build -c opt :all +unset USE_BAZEL_VERSION + +# Prepare the weak symbols: +# This is necessary because we compile the target binary and the intermediate +# auxiliary binaries with the same cflags. The auxiliary binaries do not need +# data-flow tracing flags, but will still throw errors when they cannot find +# the corresponding functions. +# The weak symbols provides fake implementations for intermediate binaries. +$CXX "$SRC/fuzztest/centipede/weak_sancov_stubs.cc" -c -o "$SRC/fuzztest/centipede/weak.o" + +echo 'Removing extra stuff leftover to avoid bloating image.' + +rm -rf /clang-*.tgz /clang + +BAZEL_BIN_REAL_DIR=$(readlink -f $CENTIPEDE_BIN_DIR) +rm -rf $CENTIPEDE_BIN_DIR +mkdir -p $CENTIPEDE_BIN_DIR +mv $BAZEL_BIN_REAL_DIR/centipede/{centipede,libcentipede_runner.pic.a} $CENTIPEDE_BIN_DIR +rm -rf /root/.cache + +echo 'Done.' diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_honggfuzz b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_honggfuzz new file mode 100644 index 0000000000000000000000000000000000000000..34d2ab8c2497ff14b4d49b8a3828febaa5135cc1 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/precompile_honggfuzz @@ -0,0 +1,45 @@ +#!/bin/bash -eu +# Copyright 2019 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +echo "Precompiling honggfuzz" +export BUILD_OSSFUZZ_STATIC=true + +PACKAGES=( + libunwind8-dev + libblocksruntime-dev + liblzma-dev + libiberty-dev + zlib1g-dev + pkg-config) + +apt-get update && apt-get install -y ${PACKAGES[@]} + +pushd $SRC/honggfuzz > /dev/null +make clean +# These CFLAGs match honggfuzz's default, with the exception of -mtune to +# improve portability and `-D_HF_LINUX_NO_BFD` to remove assembly instructions +# from the filenames. +CC=clang CFLAGS="-O3 -funroll-loops -D_HF_LINUX_NO_BFD" make + +# libhfuzz.a will be added by CC/CXX linker directly during linking, +# but it's defined here to satisfy the build infrastructure +ar rcs honggfuzz.a libhfuzz/*.o libhfcommon/*.o +popd > /dev/null + +apt-get remove -y --purge ${PACKAGES[@]} +apt-get autoremove -y +echo "Done." diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/python_coverage_helper.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/python_coverage_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..4f244a0435c1a783f8b841b78cb8b385bbaa5f1b --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/python_coverage_helper.py @@ -0,0 +1,120 @@ +# 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. +"""Extracts file paths to copy files from pyinstaller-generated executables""" +import os +import sys +import shutil +import zipfile + + +# Finds all *.toc files in ./workpath and reads these files in order to +# identify Python files associated with a pyinstaller packaged executable. +# Copies all of the Python files to a temporary directory (/medio) following +# the original directory structure. +def get_all_files_from_toc(toc_file, file_path_set): + """ + Extract filepaths from a .toc file and add to file_path_set + """ + with open(toc_file, 'rb') as toc_file_fd: + for line in toc_file_fd: + try: + line = line.decode() + except: # pylint:disable=bare-except + continue + if '.py' not in line: + continue + + split_line = line.split(' ') + for word in split_line: + word = word.replace('\'', '').replace(',', '').replace('\n', '') + if '.py' not in word: + continue + # Check if .egg is in the path and if so we need to split it + if os.path.isfile(word): + file_path_set.add(word) + elif '.egg' in word: # check if this is an egg + egg_path_split = word.split('.egg') + if len(egg_path_split) != 2: + continue + egg_path = egg_path_split[0] + '.egg' + if not os.path.isfile(egg_path): + continue + + print('Unzipping contents of %s' % egg_path) + + # We have an egg. This needs to be unzipped and then replaced + # with the unzipped data. + tmp_dir_name = 'zipdcontents' + if os.path.isdir(tmp_dir_name): + shutil.rmtree(tmp_dir_name) + + # unzip egg and replace path with unzipped content + with zipfile.ZipFile(egg_path, 'r') as zip_f: + zip_f.extractall(tmp_dir_name) + os.remove(egg_path) + shutil.copytree(tmp_dir_name, egg_path) + + # Now the lines should be accessible, so check again + if os.path.isfile(word): + file_path_set.add(word) + + +def create_file_structure_from_tocs(work_path, out_path): + """ + Extract the Python files that are added as paths in the output of + a pyinstaller operation. The files are determined by reading through + all of the *.toc files in the workpath of pyinstaller. + + The files will be copied into the out_path using a similar file path + as they originally are. If any archive (.egg) files are present in the + .toc files, then unzip the archives and substitute the archive for the + unzipped content, i.e. we will extract the archives and collect the source + files. + """ + print('Extracts files from the pyinstaller workpath') + file_path_set = set() + for path1 in os.listdir(work_path): + full_path = os.path.join(work_path, path1) + if not os.path.isdir(full_path): + continue + + # We have a directory + for path2 in os.listdir(full_path): + if not '.toc' in path2: + continue + full_toc_file = os.path.join(full_path, path2) + get_all_files_from_toc(full_toc_file, file_path_set) + + for file_path in file_path_set: + relative_src = file_path[1:] if file_path[0] == '/' else file_path + dst_path = os.path.join(out_path, relative_src) + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + shutil.copy(file_path, dst_path) + + +def main(): + """ + Main handler. + """ + if len(sys.argv) != 3: + print('Use: python3 python_coverage_helper.py pyinstaller_workpath ' + 'destination_for_output') + sys.exit(1) + work_path = sys.argv[1] + out_path = sys.argv[2] + create_file_structure_from_tocs(work_path, out_path) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..42dcf3e0ba244c6d59a6ab3d38af5adcd5f92fbe --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore @@ -0,0 +1,4 @@ +dist +pysecsan.egg-info* +build +.venv diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/LICENSE b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6d6d1266c329fd60129d68b2a80179e0102633e0 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/LICENSE @@ -0,0 +1,13 @@ +# 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. diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/README.md b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cbb07c1f1de011555b07e9ddc57c01fac34deba4 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/README.md @@ -0,0 +1,3 @@ +# pysecsan + +Security sanitizers for vulnerability detection during runtime. diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pyproject.toml b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..636f93d09324148c5c33b90b2cfcde4feb948207 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pyproject.toml @@ -0,0 +1,22 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" + +[project] +name = "pysecsan" +version = "0.1.0" +authors = [ + { name="David Korczynski", email="david@adalogics.com" }, +] +description = "Sanitizers to detect security vulnerabilities at runtime." +readme = "README.md" +requires-python = ">=3.7" +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", +] + +[project.urls] +"Homepage" = "https://github.com/google/oss-fuzz/tree/master/infra/sanitizers/pysecsan" +"Bug Tracker" = "https://github.com/google/oss-fuzz/issues" diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/__init__.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..606ff453358402b2ef653ccae9944dd0481000ea --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/__init__.py @@ -0,0 +1,20 @@ +# 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. +"""Glue for pysecsan library.""" + +# Import sanlib and expose only needs functionality by way of __all__ +from .sanlib import * + +# pylint: disable=undefined-all-variable +__all__ = ['add_hooks'] diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/command_injection.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/command_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..1d010047588f04ad66dba55173f0a13284fbc21e --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/command_injection.py @@ -0,0 +1,106 @@ +# 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. +# +################################################################################ +"""Sanitizers for capturing code injections.""" + +from typing import Optional +from pysecsan import sanlib + + +def get_all_substr_prefixes(main_str, sub_str): + """Yields all strings prefixed with sub_str in main_str.""" + idx = 0 + while True: + idx = main_str.find(sub_str, idx) + if idx == -1: + return + yield main_str[0:idx] + # Increase idx the length of the substring from the current position + # where an occurence of the substring was found. + idx += len(sub_str) + + +# pylint: disable=unsubscriptable-object +def check_code_injection_match(elem, check_unquoted=False) -> Optional[str]: + """identify if elem is an injection match.""" + # Check exact match + if elem == 'exec-sanitizer': + return 'Explicit command injection found.' + + # Check potential for injecting into a string + if 'FROMFUZZ' in elem: + if check_unquoted: + # return true if any index is unquoted + for sub_str in get_all_substr_prefixes(elem, 'FROMFUZZ'): + if sub_str.count('\"') % 2 == 0: + return 'Fuzzer controlled content in data. Code injection potential.' + + # Return None if all fuzzer taints were quoted + return None + return 'Fuzzer-controlled data in command string. Injection potential.' + return None + + +# pylint: disable=invalid-name +def hook_pre_exec_subprocess_Popen(cmd, **kwargs): + """Hook for subprocess.Popen.""" + + arg_shell = 'shell' in kwargs and kwargs['shell'] + + # Command injections depend on whether the first argument is a list of + # strings or a string. Handle this now. + # Example: tests/poe/ansible-runner-cve-2021-4041 + if isinstance(cmd, str): + res = check_code_injection_match(cmd, check_unquoted=True) + if res is not None: + # if shell arg is true and string is tainted and unquoted that's a + # definite code injection. + if arg_shell is True: + sanlib.abort_with_issue('Code injection in Popen', 'Command injection') + + # It's a maybe: will not report this to avoid false positives. + # TODO: add more precise detection here. + + # Check for hg command injection + # Example: tests/poe/libvcs-cve-2022-21187 + if cmd[0] == 'hg': + # Check if the arguments are controlled by the fuzzer, and this given + # arg is not preceded by -- + found_dashes = False + for idx in range(1, len(cmd)): + if cmd[0] == '--': + found_dashes = True + if not found_dashes and check_code_injection_match(cmd[idx]): + sanlib.abort_with_issue( + 'command injection likely by way of mercurial. The following' + f'command {str(cmd)} is executed, and if you substitute {cmd[idx]} ' + 'with \"--config=alias.init=!touch HELLO_PY\" then you will ' + 'create HELLO_PY', 'Command injection') + + +def hook_pre_exec_os_system(cmd): + """Hook for os.system.""" + res = check_code_injection_match(cmd) + if res is not None: + sanlib.abort_with_issue(f'code injection by way of os.system\n{res}', + 'Command injection') + + +def hook_pre_exec_eval(cmd, *args, **kwargs): + """Hook for eval. Experimental atm.""" + res = check_code_injection_match(cmd, check_unquoted=True) + if res is not None: + sanlib.abort_with_issue(f'Potential code injection by way of eval\n{res}', + 'Command injection') diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py new file mode 100644 index 0000000000000000000000000000000000000000..388cb331c20f05d6f876ca3589e6490705e4fc5c --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py @@ -0,0 +1,84 @@ +# 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. +# +################################################################################ +"""Sanitizer for regular expression dos.""" + +# pylint: disable=protected-access + +import time +import os +from pysecsan import sanlib + +START_RE_TIME = None + + +# Hooks for regular expressions. +# Main problem is to identify ReDOS attemps. This is a non-trivial task +# - https://arxiv.org/pdf/1701.04045.pdf +# - https://dl.acm.org/doi/pdf/10.1145/3236024.3236027 +# and the current approach we use is simply check for extensive computing time. +# In essence, this is more of a refinement of traditional timeout checker from +# the fuzzer, which, effectively will detect these types of attacks by way of +# timeouts. +# +# Perhaps the smartest would be to use something like e.g. +# https://github.com/doyensec/regexploit to scan the regex patterns. +# Other heuristics without going too technical on identifying super-linear +# regexes: +# - check +# - if 'taint' exists in re.compile(xx) +# - check +# - for backtracking possbility in PATTERN within re.comile(PATTERN) +# - and +# - 'taint' in findall(XX) calls. +# pylint: disable=global-statement +def hook_post_exec_re_pattern_findall(self, re_str): + """Hook post exeution re.compile().findall().""" + _ = self # Satisfy lint + global START_RE_TIME + try: + endtime = time.time() - START_RE_TIME + if endtime > 4: + sanlib.abort_with_issue(f'Potential ReDOS attack.\n {re_str}', 'ReDOS') + except NameError: + sanlib.sanitizer_log( + 'starttime is not set, which it should have. Error in PySecSan', + sanlib.LOG_INFO) + os._exit(1) + + +def hook_pre_exec_re_pattern_findall(self, string): + """Hook pre execution of re.pattern().findall().""" + _ = (self, string) # Satisfy lint + global START_RE_TIME + START_RE_TIME = time.time() + + +def hook_post_exec_re_compile(retval, pattern, flags=None): + """Hook for re.compile post execution to hook returned objects functions.""" + _ = (pattern, flags) # Satisfy lint + sanlib.sanitizer_log('Inside of post compile hook', sanlib.LOG_DEBUG) + wrapper_object = sanlib.create_object_wrapper( + findall=(hook_pre_exec_re_pattern_findall, + hook_post_exec_re_pattern_findall)) + hooked_object = wrapper_object(retval) + return hooked_object + + +def hook_pre_exec_re_compile(pattern, flags=None): + """Check if tainted input exists in pattern. If so, likely chance of making + ReDOS possible.""" + _ = (pattern, flags) # Satisfy lint + sanlib.sanitizer_log('Inside re compile hook', sanlib.LOG_DEBUG) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/sanlib.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/sanlib.py new file mode 100644 index 0000000000000000000000000000000000000000..eead5c3979e545502891cc1a36b57ed3e1fb44df --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/sanlib.py @@ -0,0 +1,227 @@ +# 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. +# +################################################################################ +"""Core routines for pysecsan library.""" + +# pylint: disable=protected-access + +import re +import os +import functools +import subprocess +import traceback +import importlib.util + +from typing import Any, Callable, Optional +from pysecsan import command_injection, redos, yaml_deserialization + +LOG_DEBUG = 0 +LOG_INFO = 1 +PYSECSAN_LOG_LVL = LOG_INFO + +# Message that will be printed to stdout when an issue is found. +PYSECSAN_BUG_LABEL = r'===BUG DETECTED: PySecSan:' + + +# pylint: disable=global-statement +def sanitizer_log(msg, log_level, force=False, log_prefix=True): + """Helper printing function.""" + global PYSECSAN_LOG_LVL + if log_level >= PYSECSAN_LOG_LVL or force: + if log_prefix: + print(f'[PYSECSAN] {msg}') + else: + print(f'{msg}') + + +def sanitizer_log_always(msg, log_prefix=True): + """Wrapper for sanitizer logging. Will always log""" + sanitizer_log(msg, 0, force=True, log_prefix=log_prefix) + + +def is_module_present(mod_name): + """Identify if module is importable.""" + # pylint: disable=deprecated-method + return importlib.util.find_spec(mod_name) is not None + + +def _log_bug(bug_title): + sanitizer_log_always('%s %s ===' % (PYSECSAN_BUG_LABEL, bug_title), + log_prefix=False) + + +def abort_with_issue(msg, bug_title): + """Print message, display stacktrace and force process exit. + + Use this function for signalling an issue is found and use the messages + logged from this function to determine if a fuzzer found a bug. + """ + # Show breaker string using an ASAN approach (uses 65 =) + sanitizer_log_always("=" * 65, log_prefix=False) + + # Log issue message + _log_bug(bug_title) + sanitizer_log_always(msg) + + # Log stacktrace + sanitizer_log_always("Stacktrace:") + traceback.print_stack() + + # Force exit + # Use os._exit here to force exit. sys.exit will exit + # by throwing a SystemExit exception which the interpreter + # handles by exiting. However, code may catch this exception, + # and thus to avoid this we exit the process without exceptions. + # pylint: disable=protected-access + sanitizer_log_always("Exiting") + os._exit(1) + + +def is_exact_taint(stream) -> bool: + """Checks if stream is an exact match for taint from fuzzer.""" + # The fuzzer has to get 8 characters right. This may be a bit much, + # however, when found it shows a high level of control over the data. + if stream == 'FROMFUZZ': + return True + + return False + + +def create_object_wrapper(**methods): + """Hooks functions in an object. + + This is needed for hooking built-in types and object attributes. + + Example use case is if we want to find ReDOS vulnerabilities, that + have a pattern of + + ``` + import re + r = re.compile(REGEX) + for _ in r.findall(...) + ``` + + In the above case r.findall is a reference to + re.Pattern.findall, which is a built-in type that is non-writeable. + + In order to hook such calls we need to wrap the object, and also hook the + re.compile function to return the wrapped/hooked object. + """ + + class Wrapper(): + """Wrap an object by hiding attributes.""" + + def __init__(self, instance): + object.__setattr__(self, 'instance', instance) + + def __setattr__(self, name, value): + object.__setattr__(object.__getattribute__(self, 'instance'), name, value) + + def __getattribute__(self, name): + instance = object.__getattribute__(self, 'instance') + + def _hook_func(self, pre_hook, post_hook, orig, *args, **kargs): + if pre_hook is not None: + pre_hook(self, *args, **kargs) + # No need to pass instance here because when we extracted + # the function we used instance.__getattribute__(name) which + # seems to include it. I think. + orig_retval = orig(*args, **kargs) + + if post_hook is not None: + post_hook(self, *args, **kargs) + return orig_retval + + # If this is a wrapped method, return a bound method + if name in methods: + pre_hook = methods[name][0] + post_hook = methods[name][1] + orig = instance.__getattribute__(name) + return (lambda *args, **kargs: _hook_func(self, pre_hook, post_hook, + orig, *args, **kargs)) + + # Otherwise, just return attribute of instance + return instance.__getattribute__(name) + + return Wrapper + + +# pylint: disable=unsubscriptable-object +def add_hook(function: Callable[[Any], Any], + pre_exec_hook: Optional[Callable[[Any], Any]] = None, + post_exec_hook: Optional[Callable[[Any], Any]] = None): + """Hook a function. + + Hooks can be placed pre and post function call. At least one hook is + needed. + + This hooking is intended on non-object hooks. In order to hook functions + in objects the `create_object_wrapper` function is used in combination + with function hooking initialisation functions post execution. + """ + if pre_exec_hook is None and post_exec_hook is None: + raise Exception('Some hooks must be included') + + @functools.wraps(function) + def run(*args, **kwargs): + sanitizer_log(f'Hook start {str(function)}', LOG_DEBUG) + + # Call hook + if pre_exec_hook is not None: + pre_exec_hook(*args, **kwargs) + + # Call the original function in the even the hook did not indicate + # failure. + ret = function(*args, **kwargs) + + # Post execution hook. Overwrite return value if anything is returned + # by post hook. + if post_exec_hook is not None: + tmp_ret = post_exec_hook(ret, *args, **kwargs) + if tmp_ret is not None: + sanitizer_log('Overwriting return value', LOG_DEBUG) + ret = tmp_ret + sanitizer_log(f'Hook end {str(function)}', LOG_DEBUG) + return ret + + return run + + +def add_hooks(): + """Sets up hooks.""" + sanitizer_log('Starting', LOG_INFO) + os.system = add_hook(os.system, + pre_exec_hook=command_injection.hook_pre_exec_os_system) + subprocess.Popen = add_hook( + subprocess.Popen, + pre_exec_hook=command_injection.hook_pre_exec_subprocess_Popen) + + __builtins__['eval'] = add_hook( + __builtins__['eval'], pre_exec_hook=command_injection.hook_pre_exec_eval) + + re.compile = add_hook(re.compile, + pre_exec_hook=redos.hook_pre_exec_re_compile, + post_exec_hook=redos.hook_post_exec_re_compile) + + # Hack to determine if yaml is elligible, because pkg_resources does + # not seem to work from pyinstaller. + # pylint: disable=import-outside-toplevel + if is_module_present('yaml'): + import yaml + sanitizer_log('Hooking pyyaml.load', LOG_DEBUG) + yaml.load = add_hook( + yaml.load, + pre_exec_hook=yaml_deserialization.hook_pre_exec_pyyaml_load, + ) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/yaml_deserialization.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/yaml_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7179d37e8cd938b35277fe613afca0c375143a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/yaml_deserialization.py @@ -0,0 +1,42 @@ +# 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. +# +################################################################################ +"""Catches vulnerable yaml desrializations that can potentially lead to +arbitrary code execution.""" +from pysecsan import sanlib + +try: + import yaml +# pylint: disable=broad-except +except Exception: + pass + + +def hook_pre_exec_pyyaml_load(stream, loader): + """Hook for pyyaml.load_yaml. + + Exits if the loader is unsafe or vanilla loader and the stream passed + to the loader is controlled by the fuzz data + """ + # Ensure loader is the unsafe loader or vanilla loader + if loader not in (yaml.loader.Loader, yaml.loader.UnsafeLoader): + return + + # Check for exact taint in stream + if sanlib.is_exact_taint(stream): + msg = ( + 'Yaml deserialization issue.\n' + 'Unsafe deserialization can be used to execute arbitrary commands.\n') + sanlib.abort_with_issue(msg, 'Yaml deserialisation') diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/setup.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d54eeb94c4af3ee12d1ca47e994892566c65a3b0 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/setup.py @@ -0,0 +1,21 @@ +# 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. +"""Config for installing python as package.""" +from setuptools import setup, find_packages + +setup(name='pysecsan', + version='0.1', + author='David Korczynski', + author_email='david@adalogics.com', + packages=find_packages(exclude='tests')) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/README.md b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d0e2e6fc6cca7aa38885792bede7e10874b3e13b --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/README.md @@ -0,0 +1 @@ +# Tests including Proof of Exploits diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..c980f30c44e1be351bb7c82ed00c7f089a6fe469 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py @@ -0,0 +1,52 @@ +#!/usr/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. +"""Fuzzer targetting command injection of eval.""" +# pylint: disable=eval-used + +import sys +import atheris +import pysecsan + +pysecsan.add_hooks() + + +def list_files_perhaps(param, magicval): + """Pass fuzzer data into eval.""" + if len(param) < 3: + return + if magicval == 1337: + try: + eval("FROMFUZZ") + except ValueError: + pass + + +def test_one_input(data): + """Fuzzer entrypoint.""" + fdp = atheris.FuzzedDataProvider(data) + list_files_perhaps(fdp.ConsumeUnicodeNoSurrogates(24), + fdp.ConsumeIntInRange(500, 1500)) + + +def main(): + """Set up and start fuzzing.""" + + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/build.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..e95473cfdb58d84b8ff36f6b3140e8f4995d40f3 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/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. +# +################################################################################ + +python3 -m pip install pysecsan + +git clone https://github.com/ansible/ansible-runner/ +cd ansible-runner +git checkout cdc0961df51fa1e10b44371944aafe5ae140b98c +python3 -m pip install . +cd .. +python3 fuzz_ansible_runner.py diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/build.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..9311619c3fea1513973f0a559b69f0c61b134c8f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/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. +# +################################################################################ + +python3 -m pip install pysecsan + +git clone https://github.com/python-ldap/python-ldap +cd python-ldap +git checkout 404c36b702c5b3a7e60729745c8bda16098b1472 +python3 -m pip install . +cd ../ +python3 ./fuzz_ldap.py diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/fuzz_ldap.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/fuzz_ldap.py new file mode 100644 index 0000000000000000000000000000000000000000..bacc9b209537c7cf5995f94134a635cca326d11f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/fuzz_ldap.py @@ -0,0 +1,42 @@ +#!/usr/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. +"""Targets: https://github.com/python-ldap/python-ldap/security/advisories/GHSA-r8wq-qrxc-hmcm""" # pylint: disable=line-too-long + +import sys +import atheris +import pysecsan +import ldap.schema + +pysecsan.add_hooks() + + +def test_one_input(data): + """Fuzzer targetting regex dos in ldap.""" + fdp = atheris.FuzzedDataProvider(data) + try: + ldap.schema.split_tokens(fdp.ConsumeUnicodeNoSurrogates(1024)) + except ValueError: + pass + + +def main(): + """Set up and start fuzzing.""" + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.dict b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.dict new file mode 100644 index 0000000000000000000000000000000000000000..54636cb47520367bfbf89ceae8b1a373b7dbbd7a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.dict @@ -0,0 +1 @@ +"os.system('exec-sanitizer')" diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..da05135f91e6ba33e1f4e868adb1ef778223d760 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py @@ -0,0 +1,51 @@ +#!/usr/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. +"""Fuzzer displaying insecure use of subprocess.Popen.""" + +import sys +import subprocess +import atheris +import pysecsan + + +def list_files_perhaps(param): + """Insecure call to Popen.""" + try: + subprocess.Popen(' '.join(['ls', '-la', param]), shell=True) + except ValueError: + pass + + +def test_one_input(data): + """Fuzzer entrypoint.""" + fdp = atheris.FuzzedDataProvider(data) + + if fdp.ConsumeIntInRange(1, 10) == 5: + list_files_perhaps('FROMFUZZ') + else: + list_files_perhaps('.') + + +def main(): + """Set up and start fuzzing.""" + pysecsan.add_hooks() + + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_general.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_general.py new file mode 100644 index 0000000000000000000000000000000000000000..6581acede3f00ee595c4c849c69791b489e1e3b5 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_general.py @@ -0,0 +1,47 @@ +#!/usr/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. +"""Fuzzer for insecure yaml deserialization.""" + +import sys +import yaml +import atheris +import pysecsan + + +def serialize_with_tainted_data(param): + """Hit insecure yaml function.""" + try: + yaml.load(param, yaml.Loader) + except yaml.YAMLError: + pass + + +def test_one_input(data): + """Fuzzer routine.""" + fdp = atheris.FuzzedDataProvider(data) + serialize_with_tainted_data(fdp.ConsumeUnicodeNoSurrogates(32)) + + +def main(): + """Set up and start fuzzing.""" + pysecsan.add_hooks() + + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_simple.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..bec48d20780ba2ffdda020cfc91270b5462dd519 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_simple.py @@ -0,0 +1,54 @@ +#!/usr/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. +"""Fuzzer triggering insecure yaml serialization.""" + +import sys +import yaml +import atheris +import pysecsan + + +def serialize_with_tainted_data(param, magicval): + """Pass data to insecure yaml functions.""" + if magicval == 1337: + try: + yaml.load(param, yaml.Loader) + except yaml.YAMLError: + pass + elif magicval == 1338: + try: + yaml.load('FROMFUZZ', yaml.Loader) + except yaml.YAMLError: + pass + + +def test_one_input(data): + """Fuzzer entrypoint.""" + fdp = atheris.FuzzedDataProvider(data) + serialize_with_tainted_data(fdp.ConsumeUnicodeNoSurrogates(32), + fdp.ConsumeIntInRange(500, 1500)) + + +def main(): + """Set up and start fuzzing.""" + pysecsan.add_hooks() + + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/srcmap b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/srcmap new file mode 100644 index 0000000000000000000000000000000000000000..f967074fdc9161fa3c95814e3b24e0f2324af61c --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/srcmap @@ -0,0 +1,66 @@ +#!/bin/bash -eux +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Deterimine srcmap of checked out source code + +SRCMAP=$(tempfile) +echo "{}" > $SRCMAP + +# $1 - json file, $2 - jq program +function jq_inplace() { + F=$(tempfile) && cat $1 | jq "$2" > $F && mv $F $1 +} + +PATHS_TO_SCAN="$SRC" + +if [[ $FUZZING_LANGUAGE == "go" ]]; then + PATHS_TO_SCAN="$PATHS_TO_SCAN $GOPATH" +fi + +# Git +for DOT_GIT_DIR in $(find $PATHS_TO_SCAN -name ".git" -type d); do + GIT_DIR=$(dirname $DOT_GIT_DIR) + cd $GIT_DIR + GIT_URL=$(git config --get remote.origin.url) + GIT_REV=$(git rev-parse HEAD) + jq_inplace $SRCMAP ".\"$GIT_DIR\" = { type: \"git\", url: \"$GIT_URL\", rev: \"$GIT_REV\" }" +done + +# Subversion +for DOT_SVN_DIR in $(find $PATHS_TO_SCAN -name ".svn" -type d); do + SVN_DIR=$(dirname $DOT_SVN_DIR) + cd $SVN_DIR + SVN_URL=$(svn info | grep "^URL:" | sed 's/URL: //g') + SVN_REV=$(svn info -r HEAD | grep "^Revision:" | sed 's/Revision: //g') + jq_inplace $SRCMAP ".\"$SVN_DIR\" = { type: \"svn\", url: \"$SVN_URL\", rev: \"$SVN_REV\" }" +done + +# Mercurial +for DOT_HG_DIR in $(find $PATHS_TO_SCAN -name ".hg" -type d); do + HG_DIR=$(dirname $DOT_HG_DIR) + cd $HG_DIR + HG_URL=$(hg paths default) + HG_REV=$(hg --debug id -r. -i) + jq_inplace $SRCMAP ".\"$HG_DIR\" = { type: \"hg\", url: \"$HG_URL\", rev: \"$HG_REV\" }" +done + +if [ "${OSSFUZZ_REVISION-}" != "" ]; then + jq_inplace $SRCMAP ".\"/src\" = { type: \"git\", url: \"https://github.com/google/oss-fuzz.git\", rev: \"$OSSFUZZ_REVISION\" }" +fi + +cat $SRCMAP +rm $SRCMAP diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/test_data/culprit-commit.txt b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/test_data/culprit-commit.txt new file mode 100644 index 0000000000000000000000000000000000000000..5529d35851db8fa39204520f6bb279c3ef772848 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/test_data/culprit-commit.txt @@ -0,0 +1,30 @@ +ac9ee01fcbfac745aaedca0393a8e1c8a33acd8d is the first bad commit +commit ac9ee01fcbfac745aaedca0393a8e1c8a33acd8d +Author: John Doe +Date: Tue Aug 6 08:41:53 2019 +0000 + + [compiler-rt] Implement getrandom interception + + Summary: + Straightforward implementation of `getrandom` syscall and libc + hooks. + + Test Plan: Local MSAN failures caused by uninstrumented `getrandom` + calls stop failing. + + Patch by John Doe 3. + + Reviewers: jonhdoe2, johndoe + + Reviewed By: johndoe + + Subscribers: johndoe4, johndoe5, #sanitizers, llvm-commits + + Tags: #sanitizers, #llvm + + Differential Revision: https://reviews.llvm.org/D65551 + + llvm-svn: 367999 + +:040000 040000 8db10511ca83cc7b0265c7703684cd386350151b 62508fdc5e8919bbb2a0bd185cc109868192cdb0 M compiler-rt +bisect run success diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/write_labels.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/write_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3a6d39aa6dfc75d6694808e336d5ed1e5226ed --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-builder/write_labels.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Script for writing from project.yaml to .labels file.""" + +import os +import json +import sys + + +def main(): + """Writes labels.""" + if len(sys.argv) != 3: + print('Usage: write_labels.py labels_json out_dir', file=sys.stderr) + sys.exit(1) + + labels_by_target = json.loads(sys.argv[1]) + out = sys.argv[2] + + for target_name, labels in labels_by_target.items(): + # Skip over wildcard value applying to all fuzz targets + if target_name == '*': + continue + with open(os.path.join(out, target_name + '.labels'), 'w') as file_handle: + file_handle.write('\n'.join(labels)) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-clang/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-clang/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..959b4d430de1e2db53c6f181ee519ce84c1d126c --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-clang/Dockerfile @@ -0,0 +1,79 @@ +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Docker image with clang installed. + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-image:${IMG_TAG} + +ARG arch=x86_64 + +ENV FUZZINTRO_OUTDIR=$SRC + +# Install newer cmake. +# Many projects, as well as recent clang versions, need a newer cmake. +ENV CMAKE_VERSION 3.29.2 +RUN apt-get update && apt-get install -y wget sudo && \ + wget -q https://github.com/Kitware/CMake/releases/download/v$CMAKE_VERSION/cmake-$CMAKE_VERSION-Linux-$arch.sh && \ + chmod +x cmake-$CMAKE_VERSION-Linux-$arch.sh && \ + ./cmake-$CMAKE_VERSION-Linux-$arch.sh --skip-license --prefix="/usr/local" && \ + rm cmake-$CMAKE_VERSION-Linux-$arch.sh && \ + SUDO_FORCE_REMOVE=yes apt-get autoremove --purge -y wget sudo && \ + rm -rf /usr/local/doc/cmake /usr/local/bin/cmake-gui + +RUN apt-get update && apt-get install -y git && \ + git clone https://github.com/ossf/fuzz-introspector.git fuzz-introspector && \ + cd fuzz-introspector && \ + git checkout f9bcb8824a18d60d57e2430c5b43f525d811cae8 && \ + git submodule init && \ + git submodule update && \ + apt-get autoremove --purge -y git && \ + rm -rf .git + +COPY checkout_build_install_llvm.sh /root/ +# Keep all steps in the same script to decrease the number of intermediate +# layes in docker file. +RUN /root/checkout_build_install_llvm.sh +RUN rm /root/checkout_build_install_llvm.sh + +# Setup the environment. +ENV CC "clang" +ENV CXX "clang++" +ENV CCC "clang++" + +# FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION is described at +# https://llvm.org/docs/LibFuzzer.html#fuzzer-friendly-build-mode + +# The implicit-function-declaration and implicit-int errors are downgraded to a +# warning, to allow compiling legacy code. +# See https://releases.llvm.org/16.0.0/tools/clang/docs/ReleaseNotes.html#potentially-breaking-changes +# Same for deprecated-declarations, int-conversion, +# incompatible-function-pointer-types, enum-constexpr-conversion, +# vla-cxx-extension + +ENV CFLAGS -O1 \ + -fno-omit-frame-pointer \ + -gline-tables-only \ + -Wno-error=enum-constexpr-conversion \ + -Wno-error=incompatible-function-pointer-types \ + -Wno-error=int-conversion \ + -Wno-error=deprecated-declarations \ + -Wno-error=implicit-function-declaration \ + -Wno-error=implicit-int \ + -Wno-error=vla-cxx-extension \ + -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION +ENV CXXFLAGS_EXTRA "-stdlib=libc++" +ENV CXXFLAGS "$CFLAGS $CXXFLAGS_EXTRA" diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-clang/checkout_build_install_llvm.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-clang/checkout_build_install_llvm.sh new file mode 100644 index 0000000000000000000000000000000000000000..e5ab30d04a4c38a29855785b83a2f03be56c897f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-clang/checkout_build_install_llvm.sh @@ -0,0 +1,246 @@ +#!/bin/bash -eux +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +NPROC=$(nproc) + +TARGET_TO_BUILD= +case $(uname -m) in + x86_64) + TARGET_TO_BUILD=X86 + ARCHITECTURE_DEPS="g++-multilib" + # Use chromium's clang revision. + export CC=$WORK/llvm-stage1/bin/clang + export CXX=$WORK/llvm-stage1/bin/clang++ + ;; + aarch64) + TARGET_TO_BUILD=AArch64 + # g++ multilib is not needed on AArch64 because we don't care about i386. + # We need to install clang and lld using apt because the binary downloaded + # from Chrome's developer tools doesn't support AArch64. + # TODO(metzman): Make x86_64 use the distro's clang for consistency once + # we support AArch64 fully. + ARCHITECTURE_DEPS="clang lld g++" + export CC=clang + export CXX=clang++ + ;; + *) + echo "Error: unsupported target $(uname -m)" + exit 1 + ;; +esac + +INTROSPECTOR_DEP_PACKAGES="texinfo bison flex" +# zlib1g-dev is needed for llvm-profdata to handle coverage data from rust compiler +LLVM_DEP_PACKAGES="build-essential make ninja-build git python3 python3-distutils binutils-dev zlib1g-dev $ARCHITECTURE_DEPS $INTROSPECTOR_DEP_PACKAGES" + +apt-get update && apt-get install -y $LLVM_DEP_PACKAGES --no-install-recommends + +# For manual bumping. +# On each bump a full trial run for everything (fuzzing engines, sanitizers, +# languages, projects, ...) is needed. +# Check CMAKE_VERSION infra/base-images/base-clang/Dockerfile was released +# recently enough to fully support this clang version. +OUR_LLVM_REVISION=llvmorg-18.1.8 + +mkdir $SRC/chromium_tools +cd $SRC/chromium_tools +git clone https://chromium.googlesource.com/chromium/src/tools/clang +cd clang +# Pin clang script due to https://github.com/google/oss-fuzz/issues/7617 +git checkout 9eb79319239629c1b23cf7a59e5ebb2bab319a34 + +LLVM_SRC=$SRC/llvm-project +# Checkout +CHECKOUT_RETRIES=10 +function clone_with_retries { + REPOSITORY=$1 + LOCAL_PATH=$2 + CHECKOUT_RETURN_CODE=1 + + # Disable exit on error since we might encounter some failures while retrying. + set +e + for i in $(seq 1 $CHECKOUT_RETRIES); do + rm -rf $LOCAL_PATH + git clone $REPOSITORY $LOCAL_PATH + CHECKOUT_RETURN_CODE=$? + if [ $CHECKOUT_RETURN_CODE -eq 0 ]; then + break + fi + done + + # Re-enable exit on error. If checkout failed, script will exit. + set -e + return $CHECKOUT_RETURN_CODE +} +clone_with_retries https://github.com/llvm/llvm-project.git $LLVM_SRC + +git -C $LLVM_SRC checkout $OUR_LLVM_REVISION +echo "Using LLVM revision: $OUR_LLVM_REVISION" + +# For fuzz introspector. +echo "Applying introspector changes" +OLD_WORKING_DIR=$PWD +cd $LLVM_SRC +cp -rf /fuzz-introspector/frontends/llvm/include/llvm/Transforms/FuzzIntrospector/ ./llvm/include/llvm/Transforms/FuzzIntrospector +cp -rf /fuzz-introspector/frontends/llvm/lib/Transforms/FuzzIntrospector ./llvm/lib/Transforms/FuzzIntrospector + +# LLVM currently does not support dynamically loading LTO passes. Thus, we +# hardcode it into Clang instead. Ref: https://reviews.llvm.org/D77704 +/fuzz-introspector/frontends/llvm/patch-llvm.sh +cd $OLD_WORKING_DIR + +mkdir -p $WORK/llvm-stage2 $WORK/llvm-stage1 +python3 $SRC/chromium_tools/clang/scripts/update.py --output-dir $WORK/llvm-stage1 + +cd $WORK/llvm-stage2 +cmake -G "Ninja" \ + -DLIBCXX_ENABLE_SHARED=OFF \ + -DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON \ + -DLIBCXXABI_ENABLE_SHARED=OFF \ + -DCMAKE_BUILD_TYPE=Release \ + -DLLVM_ENABLE_RUNTIMES="compiler-rt;libcxx;libcxxabi" \ + -DLLVM_TARGETS_TO_BUILD="$TARGET_TO_BUILD" \ + -DLLVM_ENABLE_PROJECTS="clang;lld" \ + -DLLVM_BINUTILS_INCDIR="/usr/include/" \ + -DLIBCXXABI_USE_LLVM_UNWINDER=OFF \ + $LLVM_SRC/llvm + +ninja -j $NPROC +ninja install +rm -rf $WORK/llvm-stage1 $WORK/llvm-stage2 + +# libFuzzer sources. +cp -r $LLVM_SRC/compiler-rt/lib/fuzzer $SRC/libfuzzer + +# Use the clang we just built from now on. +export CC=clang +export CXX=clang++ + +function free_disk_space { + rm -rf $LLVM_SRC $SRC/chromium_tools + apt-get autoremove --purge -y $LLVM_DEP_PACKAGES + # Delete unneeded parts of LLVM to reduce image size. + # See https://github.com/google/oss-fuzz/issues/5170 + LLVM_TOOLS_TMPDIR=/tmp/llvm-tools + mkdir $LLVM_TOOLS_TMPDIR + # Move binaries with llvm- prefix that we want into LLVM_TOOLS_TMPDIR. + mv \ + /usr/local/bin/llvm-ar \ + /usr/local/bin/llvm-as \ + /usr/local/bin/llvm-config \ + /usr/local/bin/llvm-cov \ + /usr/local/bin/llvm-objcopy \ + /usr/local/bin/llvm-nm \ + /usr/local/bin/llvm-profdata \ + /usr/local/bin/llvm-ranlib \ + /usr/local/bin/llvm-symbolizer \ + /usr/local/bin/llvm-undname \ + $LLVM_TOOLS_TMPDIR + + # Delete remaining llvm- binaries. + rm -rf /usr/local/bin/llvm-* + + # Restore the llvm- binaries we want to keep. + mv $LLVM_TOOLS_TMPDIR/* /usr/local/bin/ + rm -rf $LLVM_TOOLS_TMPDIR + + # Remove binaries from LLVM build that we don't need. + rm -f \ + /usr/local/bin/bugpoint \ + /usr/local/bin/llc \ + /usr/local/bin/lli \ + /usr/local/bin/clang-check \ + /usr/local/bin/clang-refactor \ + /usr/local/bin/clang-offload-wrapper \ + /usr/local/bin/clang-offload-bundler \ + /usr/local/bin/clang-repl \ + /usr/local/bin/clang-check \ + /usr/local/bin/clang-refactor \ + /usr/local/bin/c-index-test \ + /usr/local/bin/clang-rename \ + /usr/local/bin/clang-scan-deps \ + /usr/local/bin/clang-extdef-mapping \ + /usr/local/bin/diagtool \ + /usr/local/bin/sanstats \ + /usr/local/bin/dsymutil \ + /usr/local/bin/verify-uselistorder \ + /usr/local/bin/clang-format + + # Remove unneeded clang libs, CMake files from LLVM build, lld libs, and the + # libraries. + # Note: we need fuzzer_no_main libraries for atheris. Don't delete. + rm -rf \ + /usr/local/lib/libclang* \ + /usr/local/lib/liblld* \ + /usr/local/lib/cmake/ +} + +if [ "$TARGET_TO_BUILD" == "AArch64" ] +then + free_disk_space + # Exit now on AArch64. We don't need to rebuild libc++ because on AArch64 we + # do not support MSAN nor do we care about i386. + exit 0 +fi + +function cmake_libcxx { + extra_args="$@" + cmake -G "Ninja" \ + -DLIBCXX_ENABLE_SHARED=OFF \ + -DLIBCXX_ENABLE_STATIC_ABI_LIBRARY=ON \ + -DLIBCXXABI_ENABLE_SHARED=OFF \ + -DLIBCXXABI_USE_LLVM_UNWINDER=OFF \ + -DCMAKE_BUILD_TYPE=Release \ + -DLLVM_ENABLE_PIC=ON \ + -DLLVM_TARGETS_TO_BUILD="$TARGET_TO_BUILD" \ + -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi" \ + -DLLVM_BINUTILS_INCDIR="/usr/include/" \ + $extra_args \ + -S $LLVM_SRC/runtimes +} + +# 32-bit libraries. +mkdir -p $WORK/i386 +cd $WORK/i386 +cmake_libcxx \ + -DCMAKE_INSTALL_PREFIX=/usr/i386/ \ + -DCMAKE_C_FLAGS="-m32" \ + -DCMAKE_CXX_FLAGS="-m32" + +ninja -j $NPROC cxx +ninja install-cxx +rm -rf $WORK/i386 + +# MemorySanitizer instrumented libraries. +mkdir -p $WORK/msan +cd $WORK/msan + +# https://github.com/google/oss-fuzz/issues/1099 +cat < $WORK/msan/ignorelist.txt +fun:__gxx_personality_* +EOF + +cmake_libcxx \ + -DLLVM_USE_SANITIZER=Memory \ + -DCMAKE_INSTALL_PREFIX=/usr/msan/ \ + -DCMAKE_CXX_FLAGS="-fsanitize-ignorelist=$WORK/msan/ignorelist.txt" + +ninja -j $NPROC cxx +ninja install-cxx +rm -rf $WORK/msan + +free_disk_space diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-image/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-image/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f77c7f77d453c6717e9ae9e8be994e305288841a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-image/Dockerfile @@ -0,0 +1,46 @@ +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Base image for all other images. + +ARG parent_image=ubuntu:20.04@sha256:4a45212e9518f35983a976eead0de5eecc555a2f047134e9dd2cfc589076a00d + +FROM $parent_image + +ENV DEBIAN_FRONTEND noninteractive +# Install tzadata to match ClusterFuzz +# (https://github.com/google/oss-fuzz/issues/9280). + +# Use Azure mirrors for consistent apt repository access. +RUN cp /etc/apt/sources.list /etc/apt/sources.list.backup && \ + sed -i 's|http://archive.ubuntu.com/ubuntu/|http://azure.archive.ubuntu.com/ubuntu/|g' /etc/apt/sources.list && \ + sed -i 's|http://security.ubuntu.com/ubuntu/|http://azure.archive.ubuntu.com/ubuntu/|g' /etc/apt/sources.list + + +RUN apt-get update && \ + apt-get upgrade -y && \ + apt-get install -y libc6-dev binutils libgcc-9-dev tzdata locales locales-all && \ + apt-get autoremove -y + +ENV OUT=/out +ENV SRC=/src +ENV WORK=/work +ENV PATH="$PATH:/out" +ENV HWASAN_OPTIONS=random_tags=0 +#set locale to utf8 +ENV LC_ALL=C.UTF-8 + +RUN mkdir -p $OUT $SRC $WORK && chmod a+rwx $OUT $SRC $WORK diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/Dockerfile b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f4ba223bdecff1f1f5c8ba78b0bfef9a6cc48f5 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/Dockerfile @@ -0,0 +1,139 @@ +# Copyright 2016 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# Build rust stuff in its own image. We only need the resulting binaries. +# Keeping the rust toolchain in the image wastes 1 GB. +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-image:${IMG_TAG} as temp-runner-binary-builder + +RUN apt-get update && apt-get install -y cargo libyaml-dev +RUN cargo install rustfilt + +# Using multi-stage build to copy some LLVM binaries needed in the runner image. +FROM ghcr.io/aixcc-finals/base-clang:${IMG_TAG} AS base-clang +FROM ghcr.io/aixcc-finals/base-builder-ruby:${IMG_TAG} AS base-ruby + +# The base builder image compiles a specific Python version. Using a multi-stage build +# to copy that same Python interpreter into the runner image saves build time and keeps +# the Python versions in sync. +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} AS base-builder + +# Real image that will be used later. +FROM ghcr.io/aixcc-finals/base-image:${IMG_TAG} + +COPY --from=temp-runner-binary-builder /root/.cargo/bin/rustfilt /usr/local/bin + +# Copy the binaries needed for code coverage and crash symbolization. +COPY --from=base-clang /usr/local/bin/llvm-cov \ + /usr/local/bin/llvm-profdata \ + /usr/local/bin/llvm-symbolizer \ + /usr/local/bin/ + +# Copy the pre-compiled Python binaries and libraries +COPY --from=base-builder /usr/local/bin/python3.10 /usr/local/bin/python3.10 +COPY --from=base-builder /usr/local/lib/libpython3.10.so.1.0 /usr/local/lib/libpython3.10.so.1.0 +COPY --from=base-builder /usr/local/include/python3.10 /usr/local/include/python3.10 +COPY --from=base-builder /usr/local/lib/python3.10 /usr/local/lib/python3.10 +COPY --from=base-builder /usr/local/bin/pip3 /usr/local/bin/pip3 + +# Create symbolic links to ensure compatibility +RUN ldconfig && \ + ln -s /usr/local/bin/python3.10 /usr/local/bin/python3 && \ + ln -s /usr/local/bin/python3.10 /usr/local/bin/python + +COPY install_deps.sh / +RUN /install_deps.sh && rm /install_deps.sh + +ENV CODE_COVERAGE_SRC=/opt/code_coverage +# Pin coverage to the same as in the base builder: +# https://github.com/google/oss-fuzz/blob/master/infra/base-images/base-builder/install_python.sh#L22 +RUN git clone https://chromium.googlesource.com/chromium/src/tools/code_coverage $CODE_COVERAGE_SRC && \ + cd /opt/code_coverage && \ + git checkout edba4873b5e8a390e977a64c522db2df18a8b27d && \ + pip3 install wheel && \ + # If version "Jinja2==2.10" is in requirements.txt, bump it to a patch version that + # supports upgrading its MarkupSafe dependency to a Python 3.10 compatible release: + sed -i 's/Jinja2==2.10/Jinja2==2.10.3/' requirements.txt && \ + pip3 install -r requirements.txt && \ + pip3 install MarkupSafe==2.0.1 && \ + pip3 install coverage==6.3.2 + +# Default environment options for various sanitizers. +# Note that these match the settings used in ClusterFuzz and +# shouldn't be changed unless a corresponding change is made on +# ClusterFuzz side as well. +ENV ASAN_OPTIONS="alloc_dealloc_mismatch=0:allocator_may_return_null=1:allocator_release_to_os_interval_ms=500:check_malloc_usable_size=0:detect_container_overflow=1:detect_odr_violation=0:detect_leaks=1:detect_stack_use_after_return=1:fast_unwind_on_fatal=0:handle_abort=1:handle_segv=1:handle_sigill=1:max_uar_stack_size_log=16:print_scariness=1:quarantine_size_mb=10:strict_memcmp=1:strip_path_prefix=/workspace/:symbolize=1:use_sigaltstack=1:dedup_token_length=3" +ENV MSAN_OPTIONS="print_stats=1:strip_path_prefix=/workspace/:symbolize=1:dedup_token_length=3" +ENV UBSAN_OPTIONS="print_stacktrace=1:print_summary=1:silence_unsigned_overflow=1:strip_path_prefix=/workspace/:symbolize=1:dedup_token_length=3" +ENV FUZZER_ARGS="-rss_limit_mb=2560 -timeout=25" +ENV AFL_FUZZER_ARGS="-m none" + +# Set up Golang environment variables (copied from /root/.bash_profile). +ENV GOPATH /root/go + +# /root/.go/bin is for the standard Go binaries (i.e. go, gofmt, etc). +# $GOPATH/bin is for the binaries from the dependencies installed via "go get". +ENV PATH $PATH:$GOPATH/bin +COPY gocoverage $GOPATH/gocoverage + +COPY install_go.sh / +RUN /install_go.sh && rm -rf /install_go.sh /root/.go + +# Install OpenJDK 15 and trim its size by removing unused components. +ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 +ENV JAVA_15_HOME=/usr/lib/jvm/java-15-openjdk-amd64 +ENV JVM_LD_LIBRARY_PATH=$JAVA_HOME/lib/server +ENV PATH=$PATH:$JAVA_HOME/bin + +COPY install_java.sh / +RUN /install_java.sh && rm /install_java.sh + +# Install JaCoCo for JVM coverage. +RUN wget https://repo1.maven.org/maven2/org/jacoco/org.jacoco.cli/0.8.7/org.jacoco.cli-0.8.7-nodeps.jar -O /opt/jacoco-cli.jar && \ + wget https://repo1.maven.org/maven2/org/jacoco/org.jacoco.agent/0.8.7/org.jacoco.agent-0.8.7-runtime.jar -O /opt/jacoco-agent.jar && \ + echo "37df187b76888101ecd745282e9cd1ad4ea508d6 /opt/jacoco-agent.jar" | shasum --check && \ + echo "c1814e7bba5fd8786224b09b43c84fd6156db690 /opt/jacoco-cli.jar" | shasum --check + +COPY install_javascript.sh / +RUN /install_javascript.sh && rm /install_javascript.sh + +# Copy built ruby and ruzzy from builder +COPY --from=base-ruby /usr/local/rvm /usr/local/rvm +COPY --from=base-ruby /install/ruzzy /install/ruzzy +COPY ruzzy /usr/bin/ruzzy +ENV PATH="$PATH:/usr/local/rvm/rubies/ruby-3.3.1/bin" +# RubyGems installation directory +ENV GEM_HOME="$OUT/fuzz-gem" +ENV GEM_PATH="/install/ruzzy" + +# Do this last to make developing these files easier/faster due to caching. +COPY bad_build_check \ + coverage \ + coverage_helper \ + download_corpus \ + jacoco_report_converter.py \ + nyc_report_converter.py \ + rcfilt \ + reproduce \ + run_fuzzer \ + parse_options.py \ + generate_differential_cov_report.py \ + profraw_update.py \ + targets_list \ + test_all.py \ + test_one.py \ + python_coverage_runner_help.py \ + /usr/local/bin/ diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/README.md b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e1e29e3802fc485f0a4df667baf89cea7fad5dfd --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/README.md @@ -0,0 +1,31 @@ +# base-runner +> Base image for fuzzer runners. + +```bash +docker run -ti ghcr.io/aixcc-finals/base-runner +``` + +## Commands + +| Command | Description | +|---------|-------------| +| `reproduce ` | build all fuzz targets and run specified one with testcase `/testcase` and given options. +| `run_fuzzer ` | runs specified fuzzer combining options with `.options` file | +| `test_all.py` | runs every binary in `/out` as a fuzzer for a while to ensure it works. | +| `coverage ` | generate a coverage report for the given fuzzer. | + +# Examples + +- *Reproduce using latest OSS-Fuzz build:* + +
+docker run --rm -ti -v <testcase_path>:/testcase gcr.io/oss-fuzz/$PROJECT_NAME reproduce <fuzzer_name>
+
+ +- *Reproduce using local source checkout:* + +
+docker run --rm -ti -v <source_path>:/src/$PROJECT_NAME \
+                    -v <testcase_path>:/testcase gcr.io/oss-fuzz/$PROJECT_NAME \
+                    reproduce <fuzzer_name>
+
diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/bad_build_check b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/bad_build_check new file mode 100644 index 0000000000000000000000000000000000000000..8aa901db6c654da365092f6764490b5f3e819668 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/bad_build_check @@ -0,0 +1,494 @@ +#!/bin/bash -u +# Copyright 2017 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +# A minimal number of runs to test fuzz target with a non-empty input. +MIN_NUMBER_OF_RUNS=4 + +# The "example" target has 73 with ASan, 65 with UBSan, and 6648 with MSan. +# Real world targets have greater values (arduinojson: 407, zlib: 664). +# Mercurial's bdiff_fuzzer has 116 PCs when built with ASan. +THRESHOLD_FOR_NUMBER_OF_EDGES=100 + +# A fuzz target is supposed to have at least two functions, such as +# LLVMFuzzerTestOneInput and an API that is being called from there. +THRESHOLD_FOR_NUMBER_OF_FUNCTIONS=2 + +# Threshold values for different sanitizers used by instrumentation checks. +ASAN_CALLS_THRESHOLD_FOR_ASAN_BUILD=1000 +ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD=0 + +# The value below can definitely be higher (like 500-1000), but avoid being too +# agressive here while still evaluating the DFT-based fuzzing approach. +DFSAN_CALLS_THRESHOLD_FOR_DFSAN_BUILD=100 +DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD=0 + +MSAN_CALLS_THRESHOLD_FOR_MSAN_BUILD=1000 +# Some engines (e.g. honggfuzz) may make a very small number of calls to msan +# for memory poisoning. +MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD=3 + +# Usually, a non UBSan build (e.g. ASan) has 165 calls to UBSan runtime. The +# majority of targets built with UBSan have 200+ UBSan calls, but there are +# some very small targets that may have < 200 UBSan calls even in a UBSan build. +# Use the threshold value of 168 (slightly > 165) for UBSan build. +UBSAN_CALLS_THRESHOLD_FOR_UBSAN_BUILD=168 + +# It would be risky to use the threshold value close to 165 for non UBSan build, +# as UBSan runtime may change any time and thus we could have different number +# of calls to UBSan runtime even in ASan build. With that, we use the threshold +# value of 200 that would detect unnecessary UBSan instrumentation in the vast +# majority of targets, except of a handful very small ones, which would not be +# a big concern either way as the overhead for them would not be significant. +UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD=200 + +# ASan builds on i386 generally have about 250 UBSan runtime calls. +if [[ $ARCHITECTURE == 'i386' ]] +then + UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD=280 +fi + + +# Verify that the given fuzz target is correctly built to run with a particular +# engine. +function check_engine { + local FUZZER=$1 + local FUZZER_NAME=$(basename $FUZZER) + local FUZZER_OUTPUT="/tmp/$FUZZER_NAME.output" + local CHECK_FAILED=0 + + if [[ "$FUZZING_ENGINE" == libfuzzer ]]; then + # Store fuzz target's output into a temp file to be used for further checks. + $FUZZER -seed=1337 -runs=$MIN_NUMBER_OF_RUNS &>$FUZZER_OUTPUT + CHECK_FAILED=$(egrep "ERROR: no interesting inputs were found. Is the code instrumented" -c $FUZZER_OUTPUT) + if (( $CHECK_FAILED > 0 )); then + echo "BAD BUILD: $FUZZER does not seem to have coverage instrumentation." + cat $FUZZER_OUTPUT + # Bail out as the further check does not make any sense, there are 0 PCs. + return 1 + fi + + local NUMBER_OF_EDGES=$(grep -Po "INFO: Loaded [[:digit:]]+ module.*\(.*(counters|guards)\):[[:space:]]+\K[[:digit:]]+" $FUZZER_OUTPUT) + + # If a fuzz target fails to start, grep won't find anything, so bail out early to let check_startup_crash deal with it. + [[ -z "$NUMBER_OF_EDGES" ]] && return + + if (( $NUMBER_OF_EDGES < $THRESHOLD_FOR_NUMBER_OF_EDGES )); then + echo "BAD BUILD: $FUZZER seems to have only partial coverage instrumentation." + fi + elif [[ "$FUZZING_ENGINE" == afl ]]; then + AFL_FORKSRV_INIT_TMOUT=30000 AFL_NO_UI=1 SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 35s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT + CHECK_PASSED=$(egrep "All set and ready to roll" -c $FUZZER_OUTPUT) + if (( $CHECK_PASSED == 0 )); then + echo "BAD BUILD: fuzzing $FUZZER with afl-fuzz failed." + cat $FUZZER_OUTPUT + return 1 + fi + elif [[ "$FUZZING_ENGINE" == honggfuzz ]]; then + SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 20s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT + CHECK_PASSED=$(egrep "^Sz:[0-9]+ Tm:[0-9]+" -c $FUZZER_OUTPUT) + if (( $CHECK_PASSED == 0 )); then + echo "BAD BUILD: fuzzing $FUZZER with honggfuzz failed." + cat $FUZZER_OUTPUT + return 1 + fi + elif [[ "$FUZZING_ENGINE" == dataflow ]]; then + $FUZZER &> $FUZZER_OUTPUT + local NUMBER_OF_FUNCTIONS=$(grep -Po "INFO:\s+\K[[:digit:]]+(?=\s+instrumented function.*)" $FUZZER_OUTPUT) + [[ -z "$NUMBER_OF_FUNCTIONS" ]] && NUMBER_OF_FUNCTIONS=0 + if (( $NUMBER_OF_FUNCTIONS < $THRESHOLD_FOR_NUMBER_OF_FUNCTIONS )); then + echo "BAD BUILD: $FUZZER does not seem to be properly built in 'dataflow' config." + cat $FUZZER_OUTPUT + return 1 + fi + elif [[ "$FUZZING_ENGINE" == centipede \ + && ("${HELPER:-}" == True || "$SANITIZER" == none ) ]]; then + # Performs run test on unsanitized binaries with auxiliary sanitized + # binaries if they are built with helper.py. + # Performs run test on unsanitized binaries without auxiliary sanitized + # binaries if they are from trial build and production build. + # TODO(Dongge): Support run test with sanitized binaries for trial and + # production build. + SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 20s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT + CHECK_PASSED=$(egrep "\[S0.0] begin-fuzz: ft: 0 corp: 0/0" -c $FUZZER_OUTPUT) + if (( $CHECK_PASSED == 0 )); then + echo "BAD BUILD: fuzzing $FUZZER with centipede failed." + cat $FUZZER_OUTPUT + return 1 + fi + fi + + return 0 +} + +# Verify that the given fuzz target has been built properly and works. +function check_startup_crash { + local FUZZER=$1 + local FUZZER_NAME=$(basename $FUZZER) + local FUZZER_OUTPUT="/tmp/$FUZZER_NAME.output" + local CHECK_PASSED=0 + + if [[ "$FUZZING_ENGINE" = libfuzzer ]]; then + # Skip seed corpus as there is another explicit check that uses seed corpora. + SKIP_SEED_CORPUS=1 run_fuzzer $FUZZER_NAME -seed=1337 -runs=$MIN_NUMBER_OF_RUNS &>$FUZZER_OUTPUT + CHECK_PASSED=$(egrep "Done $MIN_NUMBER_OF_RUNS runs" -c $FUZZER_OUTPUT) + elif [[ "$FUZZING_ENGINE" = afl ]]; then + AFL_FORKSRV_INIT_TMOUT=30000 AFL_NO_UI=1 SKIP_SEED_CORPUS=1 timeout --preserve-status -s INT 35s run_fuzzer $FUZZER_NAME &>$FUZZER_OUTPUT + if [ $(egrep "target binary (crashed|terminated)" -c $FUZZER_OUTPUT) -eq 0 ]; then + CHECK_PASSED=1 + fi + elif [[ "$FUZZING_ENGINE" = dataflow ]]; then + # TODO(https://github.com/google/oss-fuzz/issues/1632): add check for + # binaries compiled with dataflow engine when the interface becomes stable. + CHECK_PASSED=1 + else + # TODO: add checks for another fuzzing engines if possible. + CHECK_PASSED=1 + fi + + if [ "$CHECK_PASSED" -eq "0" ]; then + echo "BAD BUILD: $FUZZER seems to have either startup crash or exit:" + cat $FUZZER_OUTPUT + return 1 + fi + + return 0 +} + +# Mixed sanitizers check for ASan build. +function check_asan_build { + local FUZZER=$1 + local ASAN_CALLS=$2 + local DFSAN_CALLS=$3 + local MSAN_CALLS=$4 + local UBSAN_CALLS=$5 + + # Perform all the checks for more detailed error message. + if (( $ASAN_CALLS < $ASAN_CALLS_THRESHOLD_FOR_ASAN_BUILD )); then + echo "BAD BUILD: $FUZZER does not seem to be compiled with ASan." + return 1 + fi + + if (( $DFSAN_CALLS > $DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD )); then + echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with DFSan." + return 1 + fi + + if (( $MSAN_CALLS > $MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD )); then + echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with MSan." + return 1 + fi + + if (( $UBSAN_CALLS > $UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD )); then + echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with UBSan." + return 1 + fi + + return 0 +} + +# Mixed sanitizers check for DFSan build. +function check_dfsan_build { + local FUZZER=$1 + local ASAN_CALLS=$2 + local DFSAN_CALLS=$3 + local MSAN_CALLS=$4 + local UBSAN_CALLS=$5 + + # Perform all the checks for more detailed error message. + if (( $ASAN_CALLS > $ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD )); then + echo "BAD BUILD: DFSan build of $FUZZER seems to be compiled with ASan." + return 1 + fi + + if (( $DFSAN_CALLS < $DFSAN_CALLS_THRESHOLD_FOR_DFSAN_BUILD )); then + echo "BAD BUILD: $FUZZER does not seem to be compiled with DFSan." + return 1 + fi + + if (( $MSAN_CALLS > $MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD )); then + echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with MSan." + return 1 + fi + + if (( $UBSAN_CALLS > $UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD )); then + echo "BAD BUILD: ASan build of $FUZZER seems to be compiled with UBSan." + return 1 + fi + + return 0 +} + + +# Mixed sanitizers check for MSan build. +function check_msan_build { + local FUZZER=$1 + local ASAN_CALLS=$2 + local DFSAN_CALLS=$3 + local MSAN_CALLS=$4 + local UBSAN_CALLS=$5 + + # Perform all the checks for more detailed error message. + if (( $ASAN_CALLS > $ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD )); then + echo "BAD BUILD: MSan build of $FUZZER seems to be compiled with ASan." + return 1 + fi + + if (( $DFSAN_CALLS > $DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD )); then + echo "BAD BUILD: MSan build of $FUZZER seems to be compiled with DFSan." + return 1 + fi + + if (( $MSAN_CALLS < $MSAN_CALLS_THRESHOLD_FOR_MSAN_BUILD )); then + echo "BAD BUILD: $FUZZER does not seem to be compiled with MSan." + return 1 + fi + + if (( $UBSAN_CALLS > $UBSAN_CALLS_THRESHOLD_FOR_NON_UBSAN_BUILD )); then + echo "BAD BUILD: MSan build of $FUZZER seems to be compiled with UBSan." + return 1 + fi + + return 0 +} + +# Mixed sanitizers check for UBSan build. +function check_ubsan_build { + local FUZZER=$1 + local ASAN_CALLS=$2 + local DFSAN_CALLS=$3 + local MSAN_CALLS=$4 + local UBSAN_CALLS=$5 + + if [[ "$FUZZING_ENGINE" != libfuzzer ]]; then + # Ignore UBSan checks for fuzzing engines other than libFuzzer because: + # A) we (probably) are not going to use those with UBSan + # B) such builds show indistinguishable number of calls to UBSan + return 0 + fi + + # Perform all the checks for more detailed error message. + if (( $ASAN_CALLS > $ASAN_CALLS_THRESHOLD_FOR_NON_ASAN_BUILD )); then + echo "BAD BUILD: UBSan build of $FUZZER seems to be compiled with ASan." + return 1 + fi + + if (( $DFSAN_CALLS > $DFSAN_CALLS_THRESHOLD_FOR_NON_DFSAN_BUILD )); then + echo "BAD BUILD: UBSan build of $FUZZER seems to be compiled with DFSan." + return 1 + fi + + if (( $MSAN_CALLS > $MSAN_CALLS_THRESHOLD_FOR_NON_MSAN_BUILD )); then + echo "BAD BUILD: UBSan build of $FUZZER seems to be compiled with MSan." + return 1 + fi + + if (( $UBSAN_CALLS < $UBSAN_CALLS_THRESHOLD_FOR_UBSAN_BUILD )); then + echo "BAD BUILD: $FUZZER does not seem to be compiled with UBSan." + return 1 + fi +} + +# Verify that the given fuzz target is compiled with correct sanitizer. +function check_mixed_sanitizers { + local FUZZER=$1 + local result=0 + local CALL_INSN= + + if [ "${FUZZING_LANGUAGE:-}" = "jvm" ]; then + # Sanitizer runtime is linked into the Jazzer driver, so this check does not + # apply. + return 0 + fi + + if [ "${FUZZING_LANGUAGE:-}" = "javascript" ]; then + # Jazzer.js currently does not support using sanitizers with native Node.js addons. + # This is not relevant anyways since supporting this will be done by preloading + # the sanitizers in the wrapper script starting Jazzer.js. + return 0 + fi + + if [ "${FUZZING_LANGUAGE:-}" = "python" ]; then + # Sanitizer runtime is loaded via LD_PRELOAD, so this check does not apply. + return 0 + fi + + # For fuzztest fuzzers point to the binary instead of launcher script. + if [[ $FUZZER == *"@"* ]]; then + FUZZER=(${FUZZER//@/ }[0]) + fi + + CALL_INSN= + if [[ $ARCHITECTURE == "x86_64" ]] + then + CALL_INSN="callq?\s+[0-9a-f]+\s+<" + elif [[ $ARCHITECTURE == "i386" ]] + then + CALL_INSN="call\s+[0-9a-f]+\s+<" + elif [[ $ARCHITECTURE == "aarch64" ]] + then + CALL_INSN="bl\s+[0-9a-f]+\s+<" + else + echo "UNSUPPORTED ARCHITECTURE" + exit 1 + fi + local ASAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__asan" -c) + local DFSAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__dfsan" -c) + local MSAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__msan" -c) + local UBSAN_CALLS=$(objdump -dC $FUZZER | egrep "${CALL_INSN}__ubsan" -c) + + + if [[ "$SANITIZER" = address ]]; then + check_asan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS + result=$? + elif [[ "$SANITIZER" = dataflow ]]; then + check_dfsan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS + result=$? + elif [[ "$SANITIZER" = memory ]]; then + check_msan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS + result=$? + elif [[ "$SANITIZER" = undefined ]]; then + check_ubsan_build $FUZZER $ASAN_CALLS $DFSAN_CALLS $MSAN_CALLS $UBSAN_CALLS + result=$? + elif [[ "$SANITIZER" = thread ]]; then + # TODO(metzman): Implement this. + result=0 + fi + + return $result +} + +# Verify that the given fuzz target doesn't crash on the seed corpus. +function check_seed_corpus { + local FUZZER=$1 + local FUZZER_NAME="$(basename $FUZZER)" + local FUZZER_OUTPUT="/tmp/$FUZZER_NAME.output" + + if [[ "$FUZZING_ENGINE" != libfuzzer ]]; then + return 0 + fi + + # Set up common fuzzing arguments, otherwise "run_fuzzer" errors out. + if [ -z "$FUZZER_ARGS" ]; then + export FUZZER_ARGS="-rss_limit_mb=2560 -timeout=25" + fi + + bash -c "run_fuzzer $FUZZER_NAME -runs=0" &> $FUZZER_OUTPUT + + # Don't output anything if fuzz target hasn't crashed. + if [ $? -ne 0 ]; then + echo "BAD BUILD: $FUZZER has a crashing input in its seed corpus:" + cat $FUZZER_OUTPUT + return 1 + fi + + return 0 +} + +function check_architecture { + local FUZZER=$1 + local FUZZER_NAME=$(basename $FUZZER) + + if [ "${FUZZING_LANGUAGE:-}" = "jvm" ]; then + # The native dependencies of a JVM project are not packaged, but loaded + # dynamically at runtime and thus cannot be checked here. + return 0; + fi + + if [ "${FUZZING_LANGUAGE:-}" = "javascript" ]; then + # Jazzer.js fuzzers are wrapper scripts that start the fuzz target with + # the Jazzer.js CLI. + return 0; + fi + + if [ "${FUZZING_LANGUAGE:-}" = "python" ]; then + FUZZER=${FUZZER}.pkg + fi + + # For fuzztest fuzzers point to the binary instead of launcher script. + if [[ $FUZZER == *"@"* ]]; then + FUZZER=(${FUZZER//@/ }[0]) + fi + + FILE_OUTPUT=$(file $FUZZER) + if [[ $ARCHITECTURE == "x86_64" ]] + then + echo $FILE_OUTPUT | grep "x86-64" > /dev/null + elif [[ $ARCHITECTURE == "i386" ]] + then + echo $FILE_OUTPUT | grep "80386" > /dev/null + elif [[ $ARCHITECTURE == "aarch64" ]] + then + echo $FILE_OUTPUT | grep "aarch64" > /dev/null + else + echo "UNSUPPORTED ARCHITECTURE" + return 1 + fi + result=$? + if [[ $result != 0 ]] + then + echo "BAD BUILD $FUZZER is not built for architecture: $ARCHITECTURE" + echo "file command output: $FILE_OUTPUT" + echo "check_mixed_sanitizers test will fail." + fi + return $result +} + +function main { + local FUZZER=$1 + local AUXILIARY_FUZZER=${2:-} + local checks_failed=0 + local result=0 + + export RUN_FUZZER_MODE="batch" + check_engine $FUZZER + result=$? + checks_failed=$(( $checks_failed + $result )) + + check_architecture $FUZZER + result=$? + checks_failed=$(( $checks_failed + $result )) + + if [[ "$FUZZING_ENGINE" == centipede \ + && "$SANITIZER" != none && "${HELPER:-}" == True ]]; then + check_mixed_sanitizers $AUXILIARY_FUZZER + else + check_mixed_sanitizers $FUZZER + fi + result=$? + checks_failed=$(( $checks_failed + $result )) + + check_startup_crash $FUZZER + result=$? + checks_failed=$(( $checks_failed + $result )) + + # TODO: re-enable after introducing bug auto-filing for bad builds. + # check_seed_corpus $FUZZER + return $checks_failed +} + + +if [ $# -ne 1 -a $# -ne 2 ]; then + echo "Usage: $0 []" + exit 1 +fi + +# Fuzz target path. +FUZZER=$1 +AUXILIARY_FUZZER=${2:-} + +main $FUZZER $AUXILIARY_FUZZER +exit $? diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/coverage b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/coverage new file mode 100644 index 0000000000000000000000000000000000000000..585b4d457e753e12025344efd735c571b38fb580 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/coverage @@ -0,0 +1,549 @@ +#!/bin/bash -u +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +cd $OUT + +if (( $# > 0 )); then + FUZZ_TARGETS="$@" +else + FUZZ_TARGETS="$(find . -maxdepth 1 -type f -executable -printf '%P\n' | \ + grep -v -x -F \ + -e 'llvm-symbolizer' \ + -e 'jazzer_agent_deploy.jar' \ + -e 'jazzer_driver' \ + -e 'jazzer_driver_with_sanitizer' \ + -e 'sanitizer_with_fuzzer.so')" +fi + +COVERAGE_OUTPUT_DIR=${COVERAGE_OUTPUT_DIR:-$OUT} + +DUMPS_DIR="$COVERAGE_OUTPUT_DIR/dumps" +FUZZERS_COVERAGE_DUMPS_DIR="$DUMPS_DIR/fuzzers_coverage" +MERGED_COVERAGE_DIR="$COVERAGE_OUTPUT_DIR/merged_coverage" +FUZZER_STATS_DIR="$COVERAGE_OUTPUT_DIR/fuzzer_stats" +TEXTCOV_REPORT_DIR="$COVERAGE_OUTPUT_DIR/textcov_reports" +LOGS_DIR="$COVERAGE_OUTPUT_DIR/logs" +REPORT_ROOT_DIR="$COVERAGE_OUTPUT_DIR/report" +REPORT_BY_TARGET_ROOT_DIR="$COVERAGE_OUTPUT_DIR/report_target" +PLATFORM=linux +REPORT_PLATFORM_DIR="$COVERAGE_OUTPUT_DIR/report/$PLATFORM" + +for directory in $DUMPS_DIR $FUZZER_STATS_DIR $LOGS_DIR $REPORT_ROOT_DIR $TEXTCOV_REPORT_DIR\ + $REPORT_PLATFORM_DIR $REPORT_BY_TARGET_ROOT_DIR $FUZZERS_COVERAGE_DUMPS_DIR $MERGED_COVERAGE_DIR; do + rm -rf $directory + mkdir -p $directory +done + +PROFILE_FILE="$DUMPS_DIR/merged.profdata" +SUMMARY_FILE="$REPORT_PLATFORM_DIR/summary.json" +COVERAGE_TARGET_FILE="$FUZZER_STATS_DIR/coverage_targets.txt" + +# Use path mapping, as $SRC directory from the builder is copied into $OUT/$SRC. +PATH_EQUIVALENCE_ARGS="-path-equivalence=/,$OUT" + +# It's important to use $COVERAGE_EXTRA_ARGS as the last argument, because it +# can contain paths to source files / directories which are positional args. +LLVM_COV_COMMON_ARGS="$PATH_EQUIVALENCE_ARGS \ + -ignore-filename-regex=.*src/libfuzzer/.* $COVERAGE_EXTRA_ARGS" + +# Options to extract branch coverage. +BRANCH_COV_ARGS="--show-branches=count --show-expansions" + +# Timeout for running a single fuzz target. +TIMEOUT=1h + +# This will be used by llvm-cov command to generate the actual report. +objects="" + +# Number of CPUs available, this is needed for running tests in parallel. +# Set the max number of parallel jobs to be the CPU count and a max of 10. +NPROC=$(nproc) +MAX_PARALLEL_COUNT=10 + +CORPUS_DIR=${CORPUS_DIR:-"/corpus"} + +function run_fuzz_target { + local target=$1 + + # '%1m' will produce separate dump files for every object. For example, if a + # fuzz target loads a shared library, we will have dumps for both of them. + local profraw_file="$DUMPS_DIR/$target.%1m.profraw" + local profraw_file_mask="$DUMPS_DIR/$target.*.profraw" + local profdata_file="$DUMPS_DIR/$target.profdata" + local corpus_real="$CORPUS_DIR/${target}" + + # -merge=1 requires an output directory, create a new, empty dir for that. + local corpus_dummy="$OUT/dummy_corpus_dir_for_${target}" + rm -rf $corpus_dummy && mkdir -p $corpus_dummy + + # Use -merge=1 instead of -runs=0 because merge is crash resistant and would + # let to get coverage using all corpus files even if there are crash inputs. + # Merge should not introduce any significant overhead compared to -runs=0, + # because (A) corpuses are already minimized; (B) we do not use sancov, and so + # libFuzzer always finishes merge with an empty output dir. + # Use 100s timeout instead of 25s as code coverage builds can be very slow. + local args="-merge=1 -timeout=100 $corpus_dummy $corpus_real" + + export LLVM_PROFILE_FILE=$profraw_file + timeout $TIMEOUT $OUT/$target $args &> $LOGS_DIR/$target.log + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + rm -rf $corpus_dummy + if (( $(du -c $profraw_file_mask | tail -n 1 | cut -f 1) == 0 )); then + # Skip fuzz targets that failed to produce profile dumps. + return 0 + fi + + # If necessary translate to latest profraw version. + if [[ $target == *"@"* ]]; then + # Extract fuzztest binary name from fuzztest wrapper script. + target=(${target//@/ }[0]) + fi + profraw_update.py $OUT/$target -i $profraw_file_mask + llvm-profdata merge -j=1 -sparse $profraw_file_mask -o $profdata_file + + # Delete unnecessary and (potentially) large .profraw files. + rm $profraw_file_mask + + shared_libraries=$(coverage_helper shared_libs -build-dir=$OUT -object=$target) + + llvm-cov export -summary-only -instr-profile=$profdata_file -object=$target \ + $shared_libraries $LLVM_COV_COMMON_ARGS > $FUZZER_STATS_DIR/$target.json + + # For introspector. + llvm-cov show -instr-profile=$profdata_file -object=$target -line-coverage-gt=0 $shared_libraries $BRANCH_COV_ARGS $LLVM_COV_COMMON_ARGS > ${TEXTCOV_REPORT_DIR}/$target.covreport +} + +function run_go_fuzz_target { + local target=$1 + + echo "Running go target $target" + export FUZZ_CORPUS_DIR="$CORPUS_DIR/${target}/" + export FUZZ_PROFILE_NAME="$DUMPS_DIR/$target.perf" + + # setup for native go fuzzers + cd $OUT + mkdir -p "testdata/fuzz/${target}" + cp -r "${FUZZ_CORPUS_DIR}" "testdata/fuzz/" + + # rewrite libFuzzer corpus to Std Go corpus if native fuzzing + grep "TestFuzzCorpus" $target > /dev/null 2>&1 && $SYSGOPATH/bin/convertcorpus $target "testdata/fuzz/${target}" + cd - + + timeout $TIMEOUT $OUT/$target -test.coverprofile $DUMPS_DIR/$target.profdata &> $LOGS_DIR/$target.log + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + # cleanup after native go fuzzers + rm -r "${OUT}/testdata/fuzz/${target}" + + # The Go 1.18 fuzzers are renamed to "*_fuzz_.go" during "infra/helper.py build_fuzzers". + # They are are therefore refered to as "*_fuzz_.go" in the profdata files. + # Since the copies named "*_fuzz_.go" do not exist in the file tree during + # the coverage build, we change the references in the .profdata files + # to the original file names. + #sed -i "s/_test.go_fuzz_.go/_test.go/g" $DUMPS_DIR/$target.profdata + # translate from golangish paths to current absolute paths + cat $OUT/$target.gocovpath | while read i; do sed -i $i $DUMPS_DIR/$target.profdata; done + # cf PATH_EQUIVALENCE_ARGS + sed -i 's=/='$OUT'/=' $DUMPS_DIR/$target.profdata + $SYSGOPATH/bin/gocovsum $DUMPS_DIR/$target.profdata > $FUZZER_STATS_DIR/$target.json +} + +function run_python_fuzz_target { + local target=$1 + local zipped_sources="$DUMPS_DIR/$target.deps.zip" + local corpus_real="$CORPUS_DIR/${target}" + # Write dummy stats file + echo "{}" > "$FUZZER_STATS_DIR/$target.json" + + # Run fuzzer + $OUT/$target $corpus_real -atheris_runs=$(ls -la $corpus_real | wc -l) > $LOGS_DIR/$target.log 2>&1 + if (( $? != 0 )); then + echo "Error happened getting coverage of $target" + echo "This is likely because Atheris did not exit gracefully" + cat $LOGS_DIR/$target.log + return 0 + fi + mv .coverage $OUT/.coverage_$target +} + +function run_java_fuzz_target { + local target=$1 + + local exec_file="$DUMPS_DIR/$target.exec" + local class_dump_dir="$DUMPS_DIR/${target}_classes/" + mkdir "$class_dump_dir" + local corpus_real="$CORPUS_DIR/${target}" + + # -merge=1 requires an output directory, create a new, empty dir for that. + local corpus_dummy="$OUT/dummy_corpus_dir_for_${target}" + rm -rf $corpus_dummy && mkdir -p $corpus_dummy + + # Use 100s timeout instead of 25s as code coverage builds can be very slow. + local jacoco_args="destfile=$exec_file,classdumpdir=$class_dump_dir,excludes=com.code_intelligence.jazzer.*\\:com.sun.tools.attach.VirtualMachine" + local args="-merge=1 -timeout=100 --nohooks \ + --additional_jvm_args=-javaagent\\:/opt/jacoco-agent.jar=$jacoco_args \ + $corpus_dummy $corpus_real" + + timeout $TIMEOUT $OUT/$target $args &> $LOGS_DIR/$target.log + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + if (( $(du -c $exec_file | tail -n 1 | cut -f 1) == 0 )); then + # Skip fuzz targets that failed to produce .exec files. + echo "$target failed to produce .exec file." + return 0 + fi + + # Generate XML report only as input to jacoco_report_converter. + # Source files are not needed for the summary. + local xml_report="$DUMPS_DIR/${target}.xml" + local summary_file="$FUZZER_STATS_DIR/$target.json" + java -jar /opt/jacoco-cli.jar report $exec_file \ + --xml $xml_report \ + --classfiles $class_dump_dir + + # Write llvm-cov summary file. + jacoco_report_converter.py $xml_report $summary_file +} + +function run_javascript_fuzz_target { + local target=$1 + local corpus_real="$CORPUS_DIR/${target}" + + # -merge=1 requires an output directory, create a new, empty dir for that. + local corpus_dummy="$OUT/dummy_corpus_dir_for_${target}" + rm -rf $corpus_dummy && mkdir -p $corpus_dummy + + # IstanbulJS currently does not work when the tested program creates + # subprocesses. For this reason, we first minimize the corpus removing + # any crashing inputs so that we can report source-based code coverage + # with a single sweep over the minimized corpus + local merge_args="-merge=1 -timeout=100 $corpus_dummy $corpus_real" + timeout $TIMEOUT $OUT/$target $merge_args &> $LOGS_DIR/$target.log + + # nyc saves the coverage reports in a directory with the default name "coverage" + local coverage_dir="$DUMPS_DIR/coverage_dir_for_${target}" + rm -rf $coverage_dir && mkdir -p $coverage_dir + + local nyc_json_coverage_file="$coverage_dir/coverage-final.json" + local nyc_json_summary_file="$coverage_dir/coverage-summary.json" + + local args="-runs=0 $corpus_dummy" + local jazzerjs_args="--coverage --coverageDirectory $coverage_dir --coverageReporters json --coverageReporters json-summary" + + JAZZERJS_EXTRA_ARGS=$jazzerjs_args $OUT/$target $args &> $LOGS_DIR/$target.log + + if (( $? != 0 )); then + echo "Error occured while running $target:" + cat $LOGS_DIR/$target.log + fi + + if [ ! -s $nyc_json_coverage_file ]; then + # Skip fuzz targets that failed to produce coverage-final.json file. + echo "$target failed to produce coverage-final.json file." + return 0 + fi + + cp $nyc_json_coverage_file $FUZZERS_COVERAGE_DUMPS_DIR/$target.json + + local summary_file="$FUZZER_STATS_DIR/$target.json" + + nyc_report_converter.py $nyc_json_summary_file $summary_file +} + +function generate_html { + local profdata=$1 + local shared_libraries=$2 + local objects=$3 + local output_dir=$4 + + rm -rf "$output_dir" + mkdir -p "$output_dir/$PLATFORM" + + local llvm_cov_args="-instr-profile=$profdata $objects $LLVM_COV_COMMON_ARGS" + llvm-cov show -format=html -output-dir=$output_dir -Xdemangler rcfilt $llvm_cov_args + + # Export coverage summary in JSON format. + local summary_file=$output_dir/$PLATFORM/summary.json + + llvm-cov export -summary-only $llvm_cov_args > $summary_file + + coverage_helper -v post_process -src-root-dir=/ -summary-file=$summary_file \ + -output-dir=$output_dir $PATH_EQUIVALENCE_ARGS +} + +export SYSGOPATH=$GOPATH +export GOPATH=$OUT/$GOPATH +# Run each fuzz target, generate raw coverage dumps. +for fuzz_target in $FUZZ_TARGETS; do + # Test if fuzz target is a golang one. + if [[ $FUZZING_LANGUAGE == "go" ]]; then + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "FUZZ_CORPUS_DIR" $fuzz_target > /dev/null 2>&1 || grep "testing\.T" $fuzz_target > /dev/null 2>&1 || continue + fi + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_go_fuzz_target $fuzz_target & + elif [[ $FUZZING_LANGUAGE == "python" ]]; then + echo "Entering python fuzzing" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_python_fuzz_target $fuzz_target + elif [[ $FUZZING_LANGUAGE == "jvm" ]]; then + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "LLVMFuzzerTestOneInput" $fuzz_target > /dev/null 2>&1 || continue + fi + + echo "Running $fuzz_target" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_java_fuzz_target $fuzz_target & + elif [[ $FUZZING_LANGUAGE == "javascript" ]]; then + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "LLVMFuzzerTestOneInput" $fuzz_target > /dev/null 2>&1 || continue + fi + + echo "Running $fuzz_target" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_javascript_fuzz_target $fuzz_target & + else + # Continue if not a fuzz target. + if [[ $FUZZING_ENGINE != "none" ]]; then + grep "LLVMFuzzerTestOneInput" $fuzz_target > /dev/null 2>&1 || continue + fi + + echo "Running $fuzz_target" + # Log the target in the targets file. + echo ${fuzz_target} >> $COVERAGE_TARGET_FILE + + # Run the coverage collection. + run_fuzz_target $fuzz_target & + + # Rewrite object if its a FUZZTEST target + if [[ $fuzz_target == *"@"* ]]; then + # Extract fuzztest binary name from fuzztest wrapper script. + fuzz_target=(${fuzz_target//@/ }[0]) + fi + if [[ -z $objects ]]; then + # The first object needs to be passed without -object= flag. + objects="$fuzz_target" + else + objects="$objects -object=$fuzz_target" + fi + fi + + + # Limit the number of processes to be spawned. + n_child_proc=$(jobs -rp | wc -l) + while [[ "$n_child_proc" -eq "$NPROC" || "$n_child_proc" -gt "$MAX_PARALLEL_COUNT" ]]; do + sleep 4 + n_child_proc=$(jobs -rp | wc -l) + done +done + +# Wait for background processes to finish. +wait + +if [[ $FUZZING_LANGUAGE == "go" ]]; then + echo $DUMPS_DIR + $SYSGOPATH/bin/gocovmerge $DUMPS_DIR/*.profdata > fuzz.cov + gotoolcover -html=fuzz.cov -o $REPORT_ROOT_DIR/index.html + $SYSGOPATH/bin/gocovsum fuzz.cov > $SUMMARY_FILE + cp $REPORT_ROOT_DIR/index.html $REPORT_PLATFORM_DIR/index.html + $SYSGOPATH/bin/pprof-merge $DUMPS_DIR/*.perf.cpu.prof + mv merged.data $REPORT_ROOT_DIR/cpu.prof + $SYSGOPATH/bin/pprof-merge $DUMPS_DIR/*.perf.heap.prof + mv merged.data $REPORT_ROOT_DIR/heap.prof + #TODO some proxy for go tool pprof -http=127.0.0.1:8001 $DUMPS_DIR/cpu.prof + echo "Finished generating code coverage report for Go fuzz targets." +elif [[ $FUZZING_LANGUAGE == "python" ]]; then + # Extract source files from all dependency zip folders + mkdir -p /pythoncovmergedfiles/medio + PYCOVDIR=/pycovdir/ + mkdir $PYCOVDIR + for fuzzer in $FUZZ_TARGETS; do + fuzzer_deps=${fuzzer}.pkg.deps.zip + unzip $OUT/${fuzzer_deps} + rsync -r ./medio /pythoncovmergedfiles/medio + rm -rf ./medio + + # Translate paths in unzipped folders to paths that we can use + mv $OUT/.coverage_$fuzzer .coverage + python3 /usr/local/bin/python_coverage_runner_help.py translate /pythoncovmergedfiles/medio + cp .new_coverage $PYCOVDIR/.coverage_$fuzzer + cp .new_coverage $OUT/coverage_d_$fuzzer + done + + # Combine coverage + cd $PYCOVDIR + python3 /usr/local/bin/python_coverage_runner_help.py combine .coverage_* + python3 /usr/local/bin/python_coverage_runner_help.py html + # Produce all_cov file used by fuzz introspector. + python3 /usr/local/bin/python_coverage_runner_help.py json -o ${TEXTCOV_REPORT_DIR}/all_cov.json + + # Generate .json with similar format to llvm-cov output. + python3 /usr/local/bin/python_coverage_runner_help.py \ + convert-to-summary-json ${TEXTCOV_REPORT_DIR}/all_cov.json $SUMMARY_FILE + + # Copy coverage date out + cp htmlcov/status.json ${TEXTCOV_REPORT_DIR}/html_status.json + + mv htmlcov/* $REPORT_PLATFORM_DIR/ + mv .coverage_* $REPORT_PLATFORM_DIR/ +elif [[ $FUZZING_LANGUAGE == "jvm" ]]; then + + # From this point on the script does not tolerate any errors. + set -e + + # Merge .exec files from the individual targets. + jacoco_merged_exec=$DUMPS_DIR/jacoco.merged.exec + java -jar /opt/jacoco-cli.jar merge $DUMPS_DIR/*.exec \ + --destfile $jacoco_merged_exec + + # Prepare classes directory for jacoco process + classes_dir=$DUMPS_DIR/classes + mkdir $classes_dir + + # Only copy class files found in $OUT/$SRC to ensure they are + # lively compiled from the project, avoiding inclusion of + # dependency classes. This also includes the fuzzer classes. + find "$OUT/$SRC" -type f -name "*.class" | while read -r class_file; do + # Skip module-info.class + if [[ "$(basename "$class_file")" == "module-info.class" ]]; then + continue + fi + + # Use javap to extract the fully qualified name of the class and copy it to $classes_dir + fqn=$(javap -verbose "$class_file" 2>/dev/null | grep "this_class:" | grep -oP '(?<=// ).*') + if [ -n "$fqn" ]; then + mkdir -p $classes_dir/$(dirname $fqn) + cp $class_file $classes_dir/$fqn.class + fi + done + + # Heuristically determine source directories based on Maven structure. + # Always include the $SRC root as it likely contains the fuzzer sources. + sourcefiles_args=(--sourcefiles $OUT/$SRC) + source_dirs=$(find $OUT/$SRC -type d -name 'java') + for source_dir in $source_dirs; do + sourcefiles_args+=(--sourcefiles "$source_dir") + done + + # Generate HTML and XML reports. + xml_report=$REPORT_PLATFORM_DIR/index.xml + java -jar /opt/jacoco-cli.jar report $jacoco_merged_exec \ + --html $REPORT_PLATFORM_DIR \ + --xml $xml_report \ + --classfiles $classes_dir \ + "${sourcefiles_args[@]}" + + # Also serve the raw exec file and XML report, which can be useful for + # automated analysis. + cp $jacoco_merged_exec $REPORT_PLATFORM_DIR/jacoco.exec + cp $xml_report $REPORT_PLATFORM_DIR/jacoco.xml + cp $xml_report $TEXTCOV_REPORT_DIR/jacoco.xml + + # Write llvm-cov summary file. + jacoco_report_converter.py $xml_report $SUMMARY_FILE + + set +e +elif [[ $FUZZING_LANGUAGE == "javascript" ]]; then + + # From this point on the script does not tolerate any errors. + set -e + + json_report=$MERGED_COVERAGE_DIR/coverage.json + nyc merge $FUZZERS_COVERAGE_DUMPS_DIR $json_report + + nyc report -t $MERGED_COVERAGE_DIR --report-dir $REPORT_PLATFORM_DIR --reporter=html --reporter=json-summary + + nyc_json_summary_file=$REPORT_PLATFORM_DIR/coverage-summary.json + + # Write llvm-cov summary file. + nyc_report_converter.py $nyc_json_summary_file $SUMMARY_FILE + + set +e +else + + # From this point on the script does not tolerate any errors. + set -e + + # Merge all dumps from the individual targets. + rm -f $PROFILE_FILE + llvm-profdata merge -sparse $DUMPS_DIR/*.profdata -o $PROFILE_FILE + + # TODO(mmoroz): add script from Chromium for rendering directory view reports. + # The first path in $objects does not have -object= prefix (llvm-cov format). + shared_libraries=$(coverage_helper shared_libs -build-dir=$OUT -object=$objects) + objects="$objects $shared_libraries" + + generate_html $PROFILE_FILE "$shared_libraries" "$objects" "$REPORT_ROOT_DIR" + + # Per target reports. + for fuzz_target in $FUZZ_TARGETS; do + if [[ $fuzz_target == *"@"* ]]; then + profdata_path=$DUMPS_DIR/$fuzz_target.profdata + report_dir=$REPORT_BY_TARGET_ROOT_DIR/$fuzz_target + # Extract fuzztest binary name from fuzztest wrapper script. + fuzz_target=(${fuzz_target//@/ }[0]) + else + profdata_path=$DUMPS_DIR/$fuzz_target.profdata + report_dir=$REPORT_BY_TARGET_ROOT_DIR/$fuzz_target + fi + if [[ ! -f "$profdata_path" ]]; then + echo "WARNING: $fuzz_target has no profdata generated." + continue + fi + + generate_html $profdata_path "$shared_libraries" "$fuzz_target" "$report_dir" + done + + set +e +fi + +# Make sure report is readable. +chmod -R +r $REPORT_ROOT_DIR $REPORT_BY_TARGET_ROOT_DIR +find $REPORT_ROOT_DIR $REPORT_BY_TARGET_ROOT_DIR -type d -exec chmod +x {} + + +# HTTP_PORT is optional. +set +u +if [[ -n $HTTP_PORT ]]; then + # Serve the report locally. + echo "Serving the report on http://127.0.0.1:$HTTP_PORT/linux/index.html" + cd $REPORT_ROOT_DIR + python3 -m http.server $HTTP_PORT +fi diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/coverage_helper b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/coverage_helper new file mode 100644 index 0000000000000000000000000000000000000000..4d29ceac8f5d048a43a7ec6cc0524d7a23936781 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/coverage_helper @@ -0,0 +1,17 @@ +#!/bin/bash -u +# Copyright 2018 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +python3 $CODE_COVERAGE_SRC/coverage_utils.py $@ diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/generate_differential_cov_report.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/generate_differential_cov_report.py new file mode 100644 index 0000000000000000000000000000000000000000..3f9fc22230c71a5c7f01068a871d44942489aad0 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/generate_differential_cov_report.py @@ -0,0 +1,228 @@ +#!/usr/bin/env python3 +# +# 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. +# +################################################################################ +"""Script for generating differential coverage reports. +generate_differential_cov_report.py \ + +""" +import os +import shutil +import subprocess +import sys + + +class ProfData: + """Class representing a profdata file.""" + + def __init__(self, text): + self.function_profs = [] + for function_prof in text.split('\n\n'): + if not function_prof: + continue + self.function_profs.append(FunctionProf(function_prof)) + + def to_string(self): + """Convert back to a string.""" + return '\n'.join( + [function_prof.to_string() for function_prof in self.function_profs]) + + def find_function(self, function, idx=None): + """Find the same function in this profdata.""" + if idx is not None: + try: + possibility = self.function_profs[idx] + if function.func_hash == possibility.func_hash: + return possibility + except IndexError: + pass + for function_prof in self.function_profs: + if function_prof.func_hash == function.func_hash: + return function_prof + return None + + def subtract(self, subtrahend): + """Subtract subtrahend from this profdata.""" + for idx, function_prof in enumerate(self.function_profs): + subtrahend_function_prof = subtrahend.find_function(function_prof, idx) + function_prof.subtract(subtrahend_function_prof) + + +class FunctionProf: + """Profile of a function.""" + FUNC_HASH_COMMENT_LINE = '# Func Hash:' + NUM_COUNTERS_COMMENT_LINE = '# Num Counters:' + COUNTER_VALUES_COMMENT_LINE = '# Counter Values:' + + def __init__(self, text): + print(text) + lines = text.splitlines() + self.function = lines[0] + assert self.FUNC_HASH_COMMENT_LINE == lines[1] + self.func_hash = lines[2] + assert self.NUM_COUNTERS_COMMENT_LINE == lines[3] + self.num_counters = int(lines[4]) + assert self.COUNTER_VALUES_COMMENT_LINE == lines[5] + self.counter_values = [1 if int(line) else 0 for line in lines[6:]] + + def to_string(self): + """Convert back to text.""" + lines = [ + self.function, + self.FUNC_HASH_COMMENT_LINE, + self.func_hash, + self.NUM_COUNTERS_COMMENT_LINE, + str(self.num_counters), + self.COUNTER_VALUES_COMMENT_LINE, + ] + [str(num) for num in self.counter_values] + return '\n'.join(lines) + + def subtract(self, subtrahend_prof): + """Subtract this other function from this function.""" + if not subtrahend_prof: + print(self.function, 'has no subtrahend') + # Nothing to subtract. + return + self.counter_values = [ + max(counter1 - counter2, 0) for counter1, counter2 in zip( + self.counter_values, subtrahend_prof.counter_values) + ] + + +def get_profdata_files(directory): + """Returns profdata files in |directory|.""" + profdatas = [] + for filename in os.listdir(directory): + filename = os.path.join(directory, filename) + if filename.endswith('.profdata'): + profdatas.append(filename) + return profdatas + + +def convert_profdata_to_text(profdata): + """Convert a profdata binary file to a profdata text file.""" + profdata_text = f'{profdata}.txt' + if os.path.exists(profdata_text): + os.remove(profdata_text) + command = [ + 'llvm-profdata', 'merge', '-j=1', '-sparse', profdata, '--text', '-o', + profdata_text + ] + print(command) + subprocess.run(command, check=True) + return profdata_text + + +def convert_text_profdata_to_bin(profdata_text): + """Convert a profdata text file to a profdata binary file.""" + profdata = profdata_text.replace('.txt', '').replace('.profdata', + '') + '.profdata' + print('bin profdata', profdata) + if os.path.exists(profdata): + os.remove(profdata) + command = [ + 'llvm-profdata', 'merge', '-j=1', '-sparse', profdata_text, '-o', profdata + ] + print(command) + subprocess.run(command, check=True) + return profdata + + +def get_difference(minuend_filename, subtrahend_filename): + """Subtract subtrahend_filename from minuend_filename.""" + with open(minuend_filename, 'r', encoding='utf-8') as minuend_file: + print('minuend', minuend_filename) + minuend = ProfData(minuend_file.read()) + with open(subtrahend_filename, 'r', encoding='utf-8') as subtrahend_file: + print('subtrahend', subtrahend_filename) + subtrahend = ProfData(subtrahend_file.read()) + + minuend.subtract(subtrahend) + return minuend + + +def profdatas_to_objects(profdatas): + """Get the corresponding objects for each profdata.""" + return [ + os.path.splitext(os.path.basename(profdata))[0] for profdata in profdatas + ] + + +def generate_differential_cov_reports(minuend_profdatas, subtrahend_profdatas, + difference_dir): + """Calculate the differences between all profdatas and generate differential + coverage reports.""" + profdata_objects = profdatas_to_objects(minuend_profdatas) + real_profdata_objects = [ + binobject for binobject in profdata_objects if binobject != 'merged' + ] + for minuend, subtrahend, binobject in zip(minuend_profdatas, + subtrahend_profdatas, + profdata_objects): + minuend_text = convert_profdata_to_text(minuend) + subtrahend_text = convert_profdata_to_text(subtrahend) + difference = get_difference(minuend_text, subtrahend_text) + basename = os.path.basename(minuend_text) + difference_text = os.path.join(difference_dir, basename) + with open(difference_text, 'w', encoding='utf-8') as file_handle: + file_handle.write(difference.to_string()) + difference_profdata = convert_text_profdata_to_bin(difference_text) + if not difference_profdata.endswith('merged.profdata'): + generate_html_report(difference_profdata, [binobject], + os.path.join(difference_dir, binobject)) + else: + generate_html_report(difference_profdata, real_profdata_objects, + os.path.join(difference_dir, 'merged')) + + +def generate_html_report(profdata, objects, directory): + """Generate an HTML coverage report.""" + # TODO(metzman): Deal with shared libs. + html_dir = os.path.join(directory, 'reports') + if os.path.exists(html_dir): + os.remove(html_dir) + os.makedirs(html_dir) + out_dir = os.getenv('OUT', '/out') + command = [ + 'llvm-cov', 'show', f'-path-equivalence=/,{out_dir}', '-format=html', + '-Xdemangler', 'rcfilt', f'-instr-profile={profdata}' + ] + + objects = [os.path.join(out_dir, binobject) for binobject in objects] + command += objects + ['-o', html_dir] + print(' '.join(command)) + subprocess.run(command, check=True) + + +def main(): + """Generate differential coverage reports.""" + if len(sys.argv) != 4: + print( + f'Usage: {sys.argv[0]} ') + minuend_dir = sys.argv[1] + subtrahend_dir = sys.argv[2] + difference_dir = sys.argv[3] + if os.path.exists(difference_dir): + shutil.rmtree(difference_dir) + os.makedirs(difference_dir, exist_ok=True) + minuend_profdatas = get_profdata_files(minuend_dir) + subtrahend_profdatas = get_profdata_files(subtrahend_dir) + generate_differential_cov_reports(minuend_profdatas, subtrahend_profdatas, + difference_dir) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.sum b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..3279af3ba87d8613c26f6353bdbf8b2310affe13 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.sum @@ -0,0 +1,30 @@ +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5 h1:zIaiqGYDQwa4HVx5wGRTXbx38Pqxjemn4BP98wpzpXo= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/LICENSE b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..455fb10875ed00a441170736f454c383a80ad7b1 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2015, Wade Simmons +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_deps.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_deps.sh new file mode 100644 index 0000000000000000000000000000000000000000..fc0569b339add75ce09c0772fbaa938a4aca0db1 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_deps.sh @@ -0,0 +1,37 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ + +# Install dependencies in a platform-aware way. + +apt-get update && apt-get install -y \ + binutils \ + file \ + ca-certificates \ + fonts-dejavu \ + git \ + libcap2 \ + rsync \ + unzip \ + wget \ + zip --no-install-recommends + +case $(uname -m) in + x86_64) + # We only need to worry about i386 if we are on x86_64. + apt-get install -y lib32gcc1 libc6-i386 + ;; +esac diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_go.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_go.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d6066b0f0a8c868d34099204b18c9ce140f09e1 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_go.sh @@ -0,0 +1,41 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ + +# Install go on x86_64, don't do anything on ARM. + +case $(uname -m) in + x86_64) + # Download and install Go 1.19. + wget -q https://storage.googleapis.com/golang/getgo/installer_linux -O $SRC/installer_linux + chmod +x $SRC/installer_linux + SHELL="bash" $SRC/installer_linux -version 1.19 + rm $SRC/installer_linux + # Set up Golang coverage modules. + printf $(find . -name gocoverage) + cd $GOPATH/gocoverage && /root/.go/bin/go install ./... + cd convertcorpus && /root/.go/bin/go install . + cd /root/.go/src/cmd/cover && /root/.go/bin/go build && mv cover $GOPATH/bin/gotoolcover + ;; + aarch64) + # Don't install go because installer is not provided. + echo "Not installing go: aarch64." + ;; + *) + echo "Error: unsupported architecture: $(uname -m)" + exit 1 + ;; +esac diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_java.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_java.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cf3855265031837b0d64058de3e7742d9383934 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_java.sh @@ -0,0 +1,46 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ + +# Install java in a platform-aware way. + +ARCHITECTURE= +case $(uname -m) in + x86_64) + ARCHITECTURE=x64 + ;; + aarch64) + ARCHITECTURE=aarch64 + ;; + *) + echo "Error: unsupported architecture: $(uname -m)" + exit 1 + ;; +esac + +wget -q https://download.java.net/java/GA/jdk17.0.2/dfd4a8d0985749f896bed50d7138ee7f/8/GPL/openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz -O /tmp/openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +wget -q https://download.java.net/java/GA/jdk15.0.2/0d1cfde4252546c6931946de8db48ee2/7/GPL/openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz -O /tmp/openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +cd /tmp +mkdir -p $JAVA_HOME +tar -xz --strip-components=1 -f openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz --directory $JAVA_HOME +rm -f openjdk-17.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +rm -rf $JAVA_HOME/jmods $JAVA_HOME/lib/src.zip + +# Install OpenJDK 15 and trim its size by removing unused components. Some projects only run with Java 15. +mkdir -p $JAVA_15_HOME +tar -xz --strip-components=1 -f openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz --directory $JAVA_15_HOME +rm -f openjdk-15.0.2_linux-"$ARCHITECTURE"_bin.tar.gz +rm -rf $JAVA_15_HOME/jmods $JAVA_15_HOME/lib/src.zip diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_javascript.sh b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_javascript.sh new file mode 100644 index 0000000000000000000000000000000000000000..183cdb418569b281b83eb1130038ea47dd219020 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/install_javascript.sh @@ -0,0 +1,30 @@ +#!/bin/bash -eux +# 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. +# +################################################################################ +# see installation instructions: https://github.com/nodesource/distributions#available-architectures +apt-get update +apt-get install -y ca-certificates curl gnupg +mkdir -p /etc/apt/keyrings +curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg + +NODE_MAJOR=20 +echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list + +apt-get update +apt-get install nodejs -y + +# Install latest versions of nyc for source-based coverage reporting +npm install --global nyc diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/jacoco_report_converter.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/jacoco_report_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..bf9d89faf3a10fb1e7c3e4f7eb49538567bb8a00 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/jacoco_report_converter.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +# 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. +# +################################################################################ +"""Helper script for creating an llvm-cov style JSON summary from a JaCoCo XML +report.""" +import json +import os +import sys +import xml.etree.ElementTree as ET + + +def convert(xml): + """Turns a JaCoCo XML report into an llvm-cov JSON summary.""" + summary = { + 'type': 'oss-fuzz.java.coverage.json.export', + 'version': '1.0.0', + 'data': [{ + 'totals': {}, + 'files': [], + }], + } + + report = ET.fromstring(xml) + totals = make_element_summary(report) + summary['data'][0]['totals'] = totals + + # Since Java compilation does not track source file location, we match + # coverage info to source files via the full class name, e.g. we search for + # a path in /out/src ending in foo/bar/Baz.java for the class foo.bar.Baz. + # Under the assumptions that a given project only ever contains a single + # version of a class and that no class name appears as a suffix of another + # class name, we can assign coverage info to every source file matched in that + # way. + src_files = list_src_files() + + for class_element in report.findall('./package/class'): + # Skip fuzzer classes + if is_fuzzer_class(class_element): + continue + + # Skip non class elements + if 'sourcefilename' not in class_element.attrib: + continue + + class_name = class_element.attrib['name'] + package_name = os.path.dirname(class_name) + basename = class_element.attrib['sourcefilename'] + # This path is 'foo/Bar.java' for the class element + # . + canonical_path = os.path.join(package_name, basename) + + class_summary = make_element_summary(class_element) + for src_file in relative_to_src_path(src_files, canonical_path): + summary['data'][0]['files'].append({ + 'filename': src_file, + 'summary': class_summary, + }) + + return json.dumps(summary) + + +def list_src_files(): + """Returns a map from basename to full path for all files in $OUT/$SRC.""" + filename_to_paths = {} + out_path = os.environ['OUT'] + '/' + src_path = os.environ['SRC'] + src_in_out = out_path + src_path + for dirpath, _, filenames in os.walk(src_in_out): + for filename in filenames: + full_path = dirpath + '/' + filename + # Map /out//src/... to /src/... + file_path = full_path[len(out_path):] + filename_to_paths.setdefault(filename, []).append(file_path) + return filename_to_paths + + +def is_fuzzer_class(class_element): + """Check if the class is fuzzer class.""" + method_elements = class_element.find('./method[@name=\"fuzzerTestOneInput\"]') + if method_elements: + return True + + return False + + +def relative_to_src_path(src_files, canonical_path): + """Returns all paths in src_files ending in canonical_path.""" + basename = os.path.basename(canonical_path) + if basename not in src_files: + return [] + candidate_paths = src_files[basename] + return [ + path for path in candidate_paths if path.endswith("/" + canonical_path) + ] + + +def make_element_summary(element): + """Returns a coverage summary for an element in the XML report.""" + summary = {} + + function_counter = element.find('./counter[@type=\'METHOD\']') + summary['functions'] = make_counter_summary(function_counter) + + line_counter = element.find('./counter[@type=\'LINE\']') + summary['lines'] = make_counter_summary(line_counter) + + # JaCoCo tracks branch coverage, which counts the covered control-flow edges + # between llvm-cov's regions instead of the covered regions themselves. For + # non-trivial code parts, the difference is usually negligible. However, if + # all methods of a class consist of a single region only (no branches), + # JaCoCo does not report any branch coverage even if there is instruction + # coverage. Since this would give incorrect results for CI Fuzz purposes, we + # increase the regions counter by 1 if there is any amount of instruction + # coverage. + instruction_counter = element.find('./counter[@type=\'INSTRUCTION\']') + has_some_coverage = instruction_counter is not None and int( + instruction_counter.attrib["covered"]) > 0 + branch_covered_adjustment = 1 if has_some_coverage else 0 + region_counter = element.find('./counter[@type=\'BRANCH\']') + summary['regions'] = make_counter_summary( + region_counter, covered_adjustment=branch_covered_adjustment) + + return summary + + +def make_counter_summary(counter_element, covered_adjustment=0): + """Turns a JaCoCo element into an llvm-cov totals entry.""" + summary = {} + covered = covered_adjustment + missed = 0 + if counter_element is not None: + covered += int(counter_element.attrib['covered']) + missed += int(counter_element.attrib['missed']) + summary['covered'] = covered + summary['notcovered'] = missed + summary['count'] = summary['covered'] + summary['notcovered'] + if summary['count'] != 0: + summary['percent'] = (100.0 * summary['covered']) / summary['count'] + else: + summary['percent'] = 0 + return summary + + +def main(): + """Produces an llvm-cov style JSON summary from a JaCoCo XML report.""" + if len(sys.argv) != 3: + sys.stderr.write('Usage: %s \n' % + sys.argv[0]) + return 1 + + with open(sys.argv[1], 'r') as xml_file: + xml_report = xml_file.read() + json_summary = convert(xml_report) + with open(sys.argv[2], 'w') as json_file: + json_file.write(json_summary) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/nyc_report_converter.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/nyc_report_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..53044754c26b2a74a6b7afa7f5f22b52881767d1 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/nyc_report_converter.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +# 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. +# +################################################################################ +"""Helper script for creating a llvm-cov style JSON summary from a nyc +JSON summary.""" +import json +import sys + + +def convert(nyc_json_summary): + """Turns a nyc JSON report into a llvm-cov JSON summary.""" + summary = { + 'type': + 'oss-fuzz.javascript.coverage.json.export', + 'version': + '1.0.0', + 'data': [{ + 'totals': + file_summary(nyc_json_summary['total']), + 'files': [{ + 'filename': src_file, + 'summary': file_summary(nyc_json_summary[src_file]) + } for src_file in nyc_json_summary if src_file != 'total'], + }], + } + + return json.dumps(summary) + + +def file_summary(nyc_file_summary): + """Returns a summary for a given file in the nyc JSON summary report.""" + return { + 'functions': element_summary(nyc_file_summary['functions']), + 'lines': element_summary(nyc_file_summary['lines']), + 'regions': element_summary(nyc_file_summary['branches']) + } + + +def element_summary(element): + """Returns a summary of a coverage element in the nyc JSON summary + of the file""" + return { + 'count': element['total'], + 'covered': element['covered'], + 'notcovered': element['total'] - element['covered'] - element['skipped'], + 'percent': element['pct'] if element['pct'] != 'Unknown' else 0 + } + + +def main(): + """Produces a llvm-cov style JSON summary from a nyc JSON summary.""" + if len(sys.argv) != 3: + sys.stderr.write('Usage: %s \n' % + sys.argv[0]) + return 1 + + with open(sys.argv[1], 'r') as nyc_json_summary_file: + nyc_json_summary = json.load(nyc_json_summary_file) + json_summary = convert(nyc_json_summary) + with open(sys.argv[2], 'w') as json_output_file: + json_output_file.write(json_summary) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/parse_options.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/parse_options.py new file mode 100644 index 0000000000000000000000000000000000000000..6612a309587f82269f9af5f00d178940d6932e06 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/parse_options.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +# 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. +# +################################################################################ +"""Helper script for parsing custom fuzzing options.""" +import configparser +import sys + + +def parse_options(options_file_path, options_section): + """Parses the given file and returns options from the given section.""" + parser = configparser.ConfigParser() + parser.read(options_file_path) + + if not parser.has_section(options_section): + return None + + options = parser[options_section] + + if options_section == 'libfuzzer': + options_string = ' '.join( + '-%s=%s' % (key, value) for key, value in options.items()) + else: + # Sanitizer options. + options_string = ':'.join( + '%s=%s' % (key, value) for key, value in options.items()) + + return options_string + + +def main(): + """Processes the arguments and prints the options in the correct format.""" + if len(sys.argv) < 3: + sys.stderr.write('Usage: %s \n' % + sys.argv[0]) + return 1 + + options = parse_options(sys.argv[1], sys.argv[2]) + if options is not None: + print(options) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/profraw_update.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/profraw_update.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ce1fd86396ed02a03fbeb6a54de1d595c2855b --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/profraw_update.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +# 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. +# +################################################################################ +"""Helper script for upgrading a profraw file to latest version.""" + +from collections import namedtuple +import struct +import subprocess +import sys + +HeaderGeneric = namedtuple('HeaderGeneric', 'magic version') +HeaderVersion9 = namedtuple( + 'HeaderVersion9', + 'BinaryIdsSize DataSize PaddingBytesBeforeCounters CountersSize \ + PaddingBytesAfterCounters NumBitmapBytes PaddingBytesAfterBitmapBytes NamesSize CountersDelta BitmapDelta NamesDelta ValueKindLast' +) + +PROFRAW_MAGIC = 0xff6c70726f667281 + + +def relativize_address(data, offset, databegin, sect_prf_cnts, sect_prf_data): + """Turns an absolute offset into a relative one.""" + value = struct.unpack('Q', data[offset:offset + 8])[0] + if sect_prf_cnts <= value < sect_prf_data: + # If the value is an address in the right section, make it relative. + value = (value - databegin) & 0xffffffffffffffff + value = struct.pack('Q', value) + for i in range(8): + data[offset + i] = value[i] + # address was made relative + return True + # no changes done + return False + + +def upgrade(data, sect_prf_cnts, sect_prf_data): + """Upgrades profraw data, knowing the sections addresses.""" + generic_header = HeaderGeneric._make(struct.unpack('QQ', data[:16])) + if generic_header.magic != PROFRAW_MAGIC: + raise Exception('Bad magic.') + base_version = generic_header.version + + if base_version >= 9: + # Nothing to do. + return data + if base_version < 5 or base_version == 6: + raise Exception('Unhandled version.') + + if generic_header.version == 5: + generic_header = generic_header._replace(version=7) + # Upgrade from version 5 to 7 by adding binaryids field. + data = data[:8] + struct.pack('Q', generic_header.version) + struct.pack( + 'Q', 0) + data[16:] + if generic_header.version == 7: + # cf https://reviews.llvm.org/D111123 + generic_header = generic_header._replace(version=8) + data = data[:8] + struct.pack('Q', generic_header.version) + data[16:] + if generic_header.version == 8: + # see https://reviews.llvm.org/D138846 + generic_header = generic_header._replace(version=9) + # Upgrade from version 8 to 9 by adding NumBitmapBytes, PaddingBytesAfterBitmapBytes and BitmapDelta fields. + data = data[:8] + struct.pack( + 'Q', generic_header.version) + data[16:56] + struct.pack( + 'QQ', 0, 0) + data[56:72] + struct.pack('Q', 0) + data[72:] + + v9_header = HeaderVersion9._make(struct.unpack('QQQQQQQQQQQQ', data[16:112])) + + if base_version <= 8 and v9_header.BinaryIdsSize % 8 != 0: + # Adds padding for binary ids. + # cf commit b9f547e8e51182d32f1912f97a3e53f4899ea6be + # cf https://reviews.llvm.org/D110365 + padlen = 8 - (v9_header.BinaryIdsSize % 8) + v7_header = v9_header._replace(BinaryIdsSize=v9_header.BinaryIdsSize + + padlen) + data = data[:16] + struct.pack('Q', v9_header.BinaryIdsSize) + data[24:] + data = data[:112 + v9_header.BinaryIdsSize] + bytes( + padlen) + data[112 + v9_header.BinaryIdsSize:] + + if base_version <= 8: + offset = 112 + v9_header.BinaryIdsSize + for d in range(v9_header.DataSize): + # Add BitmapPtr and aligned u32(NumBitmapBytes) + data = data[:offset + 3 * 8] + struct.pack( + 'Q', 0) + data[offset + 3 * 8:offset + 6 * 8] + struct.pack( + 'Q', 0) + data[offset + 6 * 8:] + value = struct.unpack('Q', + data[offset + 2 * 8:offset + 3 * 8])[0] - 16 * d + data = data[:offset + 2 * 8] + struct.pack('Q', + value) + data[offset + 3 * 8:] + offset += 8 * 8 + + if base_version >= 8: + # Nothing more to do. + return data + + # Last changes are relaed to bump from 7 to version 8 making CountersPtr relative. + dataref = sect_prf_data + # 80 is offset of CountersDelta. + if not relativize_address(data, 80, dataref, sect_prf_cnts, sect_prf_data): + return data + + offset = 112 + v9_header.BinaryIdsSize + # This also works for C+Rust binaries compiled with + # clang-14/rust-nightly-clang-13. + for _ in range(v9_header.DataSize): + # 16 is the offset of CounterPtr in ProfrawData structure. + relativize_address(data, offset + 16, dataref, sect_prf_cnts, sect_prf_data) + # We need this because of CountersDelta -= sizeof(*SrcData); + # seen in __llvm_profile_merge_from_buffer. + dataref += 44 + 2 * (v9_header.ValueKindLast + 1) + if was8: + #profraw9 added RelativeBitmapPtr and NumBitmapBytes (8+4 rounded up to 16) + dataref -= 16 + # This is the size of one ProfrawData structure. + offset += 44 + 2 * (v9_header.ValueKindLast + 1) + + return data + + +def main(): + """Helper script for upgrading a profraw file to latest version.""" + if len(sys.argv) < 3: + sys.stderr.write('Usage: %s options? ...\n' % sys.argv[0]) + return 1 + + # First find llvm profile sections addresses in the elf, quick and dirty. + process = subprocess.Popen(['readelf', '-S', sys.argv[1]], + stdout=subprocess.PIPE) + output, err = process.communicate() + if err: + print('readelf failed') + return 2 + for line in iter(output.split(b'\n')): + if b'__llvm_prf_cnts' in line: + sect_prf_cnts = int(line.split()[3], 16) + elif b'__llvm_prf_data' in line: + sect_prf_data = int(line.split()[3], 16) + + out_name = "default.profup" + in_place = False + start = 2 + if sys.argv[2] == "-i": + in_place = True + start = start + 1 + elif sys.argv[2] == "-o": + out_name = sys.argv[3] + start = 4 + + if len(sys.argv) < start: + sys.stderr.write('Usage: %s options ...\n' % sys.argv[0]) + return 1 + + for i in range(start, len(sys.argv)): + # Then open and read the input profraw file. + with open(sys.argv[i], 'rb') as input_file: + profraw_base = bytearray(input_file.read()) + # Do the upgrade, returning a bytes object. + profraw_latest = upgrade(profraw_base, sect_prf_cnts, sect_prf_data) + # Write the output to the file given to the command line. + if in_place: + out_name = sys.argv[i] + with open(out_name, 'wb') as output_file: + output_file.write(profraw_latest) + + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/python_coverage_runner_help.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/python_coverage_runner_help.py new file mode 100644 index 0000000000000000000000000000000000000000..5d5f627128455ed4d5d70c166ef8c7fe218ace99 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/python_coverage_runner_help.py @@ -0,0 +1,181 @@ +# 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. +""" +Helper to manage coverage.py related operations. Does two main +things: (1) pass commands into the coverage.py library and (2) +translate .coverage created from a pyinstaller executable into +paths that match local files. This is needed for html report creation. +""" +import os +import re +import json +import sys +from coverage.cmdline import main as coverage_main +from coverage.data import CoverageData + + +def should_exclude_file(filepath): + """Returns whether the path should be excluded from the coverage report.""" + # Skip all atheris code + if "atheris" in filepath: + return True + + # Filter out all standard python libraries + if ('/usr/local/lib/python' in filepath and + 'site-packages' not in filepath and 'dist-packages' not in filepath): + return True + + # Avoid all PyInstaller modules. + if 'PyInstaller' in filepath: + return True + + return False + + +def translate_lines(cov_data, new_cov_data, all_file_paths): + """ + Translate lines in a .coverage file created by coverage.py such that + the file paths points to local files instead. This is needed when collecting + coverage from executables created by pyinstaller. + """ + for pyinstaller_file_path in cov_data.measured_files(): + stripped_py_file_path = pyinstaller_file_path + if stripped_py_file_path.startswith('/tmp/_MEI'): + stripped_py_file_path = '/'.join(stripped_py_file_path.split('/')[3:]) + if stripped_py_file_path.startswith('/out/'): + stripped_py_file_path = stripped_py_file_path.replace('/out/', '') + + # Check if this file exists in our file paths: + for local_file_path in all_file_paths: + if should_exclude_file(local_file_path): + continue + if local_file_path.endswith(stripped_py_file_path): + print('Found matching: %s' % (local_file_path)) + new_cov_data.add_lines( + {local_file_path: cov_data.lines(pyinstaller_file_path)}) + + +def translate_coverage(all_file_paths): + """ + Translate pyinstaller-generated file paths in .coverage (produced by + coverage.py) into local file paths. Place result in .new_coverage. + """ + covdata_pre_translation = CoverageData('.coverage') + covdata_post_translation = CoverageData('.new_coverage') + + covdata_pre_translation.read() + translate_lines(covdata_pre_translation, covdata_post_translation, + all_file_paths) + covdata_post_translation.write() + + +def convert_coveragepy_cov_to_summary_json(src, dst): + """ + Converts a json file produced by coveragepy into a summary.json file + similary to llvm-cov output. `src` is the source coveragepy json file, + `dst` is the destination json file, which will be overwritten. + """ + dst_dict = {'data': [{'files': {}}]} + lines_covered = 0 + lines_count = 0 + with open(src, "r") as src_f: + src_json = json.loads(src_f.read()) + if 'files' in src_json: + for elem in src_json.get('files'): + if 'summary' not in src_json['files'][elem]: + continue + src_dict = src_json['files'][elem]['summary'] + count = src_dict['covered_lines'] + src_dict['missing_lines'] + covered = src_dict['covered_lines'] + notcovered = src_dict['missing_lines'] + percent = src_dict['percent_covered'] + + # Accumulate line coverage + lines_covered += covered + lines_count += count + + dst_dict['data'][0]['files'][elem] = { + 'summary': { + 'lines': { + 'count': count, + 'covered': covered, + 'notcovered': notcovered, + 'percent': percent + } + } + } + if lines_count > 0: + lines_covered_percent = lines_covered / lines_count + else: + lines_covered_percent = 0.0 + dst_dict['data'][0]['totals'] = { + 'branches': { + 'count': 0, + 'covered': 0, + 'notcovered': 0, + 'percent': 0.0 + }, + 'functions': { + 'count': 0, + 'covered': 0, + 'percent': 0.0 + }, + 'instantiations': { + 'count': 0, + 'covered': 0, + 'percent': 0.0 + }, + 'lines': { + 'count': lines_count, + 'covered': lines_covered, + 'percent': lines_covered_percent + }, + 'regions': { + 'count': 0, + 'covered': 0, + 'notcovered': 0, + 'percent': 0.0 + } + } + + with open(dst, 'w') as dst_f: + dst_f.write(json.dumps(dst_dict)) + + +def main(): + """ + Main handler. + """ + if sys.argv[1] == 'translate': + print('Translating the coverage') + files_path = sys.argv[2] + all_file_paths = list() + for root, _, files in os.walk(files_path): + for relative_file_path in files: + abs_file_path = os.path.abspath(os.path.join(root, relative_file_path)) + all_file_paths.append(abs_file_path) + print('Done with path walk') + translate_coverage(all_file_paths) + elif sys.argv[1] == 'convert-to-summary-json': + src = sys.argv[2] + dst = sys.argv[3] + convert_coveragepy_cov_to_summary_json(src, dst) + else: + # Pass commands into coverage package + sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) + sys.exit(coverage_main()) + + +if __name__ == '__main__': + main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/rcfilt b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/rcfilt new file mode 100644 index 0000000000000000000000000000000000000000..1c621100c3be0ae4f50d0e4cf817120b8f169b5a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/rcfilt @@ -0,0 +1,21 @@ +#!/bin/bash -u +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Symbol demangling for both C++ and Rust +# +################################################################################ + +# simply pipe +rustfilt | c++filt -n diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/run_fuzzer b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/run_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..6e55917cb62bf43b524eed257f585f54154c3362 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/run_fuzzer @@ -0,0 +1,228 @@ +#!/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. +# +################################################################################ + +# Fuzzer runner. Appends .options arguments and seed corpus to users args. +# Usage: $0 + +sysctl -w vm.mmap_rnd_bits=28 + +export PATH=$OUT:$PATH +cd $OUT + +DEBUGGER=${DEBUGGER:-} + +FUZZER=$1 +shift + +# This env var is set by CIFuzz. CIFuzz fills this directory with the corpus +# from ClusterFuzz. +CORPUS_DIR=${CORPUS_DIR:-} +if [ -z "$CORPUS_DIR" ] +then + CORPUS_DIR="/tmp/${FUZZER}_corpus" + rm -rf $CORPUS_DIR && mkdir -p $CORPUS_DIR +fi + +SANITIZER=${SANITIZER:-} +if [ -z $SANITIZER ]; then + # If $SANITIZER is not specified (e.g. calling from `reproduce` command), it + # is not important and can be set to any value. + SANITIZER="default" +fi + +if [[ "$RUN_FUZZER_MODE" = interactive ]]; then + FUZZER_OUT="$OUT/${FUZZER}_${FUZZING_ENGINE}_${SANITIZER}_out" +else + FUZZER_OUT="/tmp/${FUZZER}_${FUZZING_ENGINE}_${SANITIZER}_out" +fi + +function get_dictionary() { + local options_file="$FUZZER.options" + local dict_file="$FUZZER.dict" + local dict="" + if [[ -f "$options_file" ]]; then + dict=$(sed -n 's/^\s*dict\s*=\s*\(.*\)/\1/p' "$options_file" | tail -1) + fi + if [[ -z "$dict" && -f "$dict_file" ]]; then + dict="$dict_file" + fi + [[ -z "$dict" ]] && return + if [[ "$FUZZING_ENGINE" = "libfuzzer" ]]; then + printf -- "-dict=%s" "$dict" + elif [[ "$FUZZING_ENGINE" = "afl" ]]; then + printf -- "-x %s" "$dict" + elif [[ "$FUZZING_ENGINE" = "honggfuzz" ]]; then + printf -- "--dict %s" "$dict" + elif [[ "$FUZZING_ENGINE" = "centipede" ]]; then + printf -- "--dictionary %s" "$dict" + else + printf "Unexpected FUZZING_ENGINE: $FUZZING_ENGINE, ignoring\n" >&2 + fi +} + +function get_extra_binaries() { + [[ "$FUZZING_ENGINE" != "centipede" ]] && return + + extra_binaries="$OUT/__centipede_${SANITIZER}/${FUZZER}" + if compgen -G "$extra_binaries" >> /dev/null; then + printf -- "--extra_binaries %s" \""$extra_binaries\"" + fi + +} + +rm -rf $FUZZER_OUT && mkdir -p $FUZZER_OUT + +SEED_CORPUS="${FUZZER}_seed_corpus.zip" + +# TODO: Investigate why this code block is skipped +# by all default fuzzers in bad_build_check. +# They all set SKIP_SEED_CORPUS=1. +if [ -f $SEED_CORPUS ] && [ -z ${SKIP_SEED_CORPUS:-} ]; then + echo "Using seed corpus: $SEED_CORPUS" + unzip -o -d ${CORPUS_DIR}/ $SEED_CORPUS > /dev/null +fi + +OPTIONS_FILE="${FUZZER}.options" +CUSTOM_LIBFUZZER_OPTIONS="" + +if [ -f $OPTIONS_FILE ]; then + custom_asan_options=$(parse_options.py $OPTIONS_FILE asan) + if [ ! -z $custom_asan_options ]; then + export ASAN_OPTIONS="$ASAN_OPTIONS:$custom_asan_options" + fi + + custom_msan_options=$(parse_options.py $OPTIONS_FILE msan) + if [ ! -z $custom_msan_options ]; then + export MSAN_OPTIONS="$MSAN_OPTIONS:$custom_msan_options" + fi + + custom_ubsan_options=$(parse_options.py $OPTIONS_FILE ubsan) + if [ ! -z $custom_ubsan_options ]; then + export UBSAN_OPTIONS="$UBSAN_OPTIONS:$custom_ubsan_options" + fi + + CUSTOM_LIBFUZZER_OPTIONS=$(parse_options.py $OPTIONS_FILE libfuzzer) +fi + +if [[ "$FUZZING_ENGINE" = afl ]]; then + + # Set afl++ environment options. + export ASAN_OPTIONS="$ASAN_OPTIONS:abort_on_error=1:symbolize=0:detect_odr_violation=0:" + export MSAN_OPTIONS="$MSAN_OPTIONS:exit_code=86:symbolize=0" + export UBSAN_OPTIONS="$UBSAN_OPTIONS:symbolize=0" + export AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES=1 + export AFL_SKIP_CPUFREQ=1 + export AFL_TRY_AFFINITY=1 + export AFL_FAST_CAL=1 + export AFL_CMPLOG_ONLY_NEW=1 + export AFL_FORKSRV_INIT_TMOUT=30000 + export AFL_IGNORE_PROBLEMS=1 + export AFL_IGNORE_UNKNOWN_ENVS=1 + + # If $OUT/afl_cmplog.txt is present this means the target was compiled for + # CMPLOG. So we have to add the proper parameters to afl-fuzz. + test -e "$OUT/afl_cmplog.txt" && AFL_FUZZER_ARGS="$AFL_FUZZER_ARGS -c $OUT/$FUZZER" + + # If $OUT/afl++.dict we load it as a dictionary for afl-fuzz. + test -e "$OUT/afl++.dict" && AFL_FUZZER_ARGS="$AFL_FUZZER_ARGS -x $OUT/afl++.dict" + + # Ensure timeout is a bit larger than 1sec as some of the OSS-Fuzz fuzzers + # are slower than this. + AFL_FUZZER_ARGS="$AFL_FUZZER_ARGS -t 5000+" + + # AFL expects at least 1 file in the input dir. + echo input > ${CORPUS_DIR}/input + + CMD_LINE="$OUT/afl-fuzz $AFL_FUZZER_ARGS -i $CORPUS_DIR -o $FUZZER_OUT $(get_dictionary) $* -- $OUT/$FUZZER" + + echo afl++ setup: + env|grep AFL_ + cat "$OUT/afl_options.txt" + +elif [[ "$FUZZING_ENGINE" = honggfuzz ]]; then + + # Honggfuzz expects at least 1 file in the input dir. + echo input > $CORPUS_DIR/input + # --exit_upon_crash: exit whith a first crash seen + # -V: verify crashes + # -R (report): save report file to this location + # -W (working dir): where the crashes go + # -v (verbose): don't use VTE UI, just stderr + # -z: use software-instrumentation of clang (trace-pc-guard....) + # -P: use persistent mode of fuzzing (i.e. LLVMFuzzerTestOneInput) + # -f: location of the initial (and destination) file corpus + # -n: number of fuzzing threads (and processes) + CMD_LINE="$OUT/honggfuzz -n 1 --exit_upon_crash -V -R /tmp/${FUZZER}_honggfuzz.report -W $FUZZER_OUT -v -z -P -f \"$CORPUS_DIR\" $(get_dictionary) $* -- \"$OUT/$FUZZER\"" + + if [[ $(LC_ALL=C grep -P "\x01_LIBHFUZZ_NETDRIVER_BINARY_SIGNATURE_\x02\xFF" "$FUZZER" ) ]]; then + # Honggfuzz Netdriver port. This must match the port in Clusterfuzz. + export HFND_TCP_PORT=8666 + fi +elif [[ "$FUZZING_ENGINE" = centipede ]]; then + + # Create the work and corpus directory for Centipede. + CENTIPEDE_WORKDIR="${CENTIPEDE_WORKDIR:-$OUT}" + + # Centipede only saves crashes to crashes/ in workdir. + rm -rf $FUZZER_OUT + + # --workdir: Dir that stores corpus&features in Centipede's own format. + # --corpus_dir: Location of the initial (and destination) file corpus. + # --fork_server: Execute the target(s) via the fork server. + # Run in fork mode to continue fuzzing indefinitely in case of + # OOMs, timeouts, and crashes. + # --exit_on_crash=0: Do not exit on crash. + # --timeout=1200: The process that executes target binary will abort + # if an input runs >= 1200s. + # --rss_limit_mb=0: Disable RSS limit. + # --address_space_limit_mb=0: No address space limit. + # --binary: The target binary under test without sanitizer. + # --extra_binary: The target binaries under test with sanitizers. + CMD_LINE="$OUT/centipede --workdir=$CENTIPEDE_WORKDIR --corpus_dir=\"$CORPUS_DIR\" --fork_server=1 --exit_on_crash=1 --timeout=1200 --rss_limit_mb=4096 --address_space_limit_mb=5120 $(get_dictionary) --binary=\"$OUT/${FUZZER}\" $(get_extra_binaries) $*" +else + + CMD_LINE="$OUT/$FUZZER $FUZZER_ARGS $*" + + if [ -z ${SKIP_SEED_CORPUS:-} ]; then + CMD_LINE="$CMD_LINE $CORPUS_DIR" + fi + + if [[ ! -z ${CUSTOM_LIBFUZZER_OPTIONS} ]]; then + CMD_LINE="$CMD_LINE $CUSTOM_LIBFUZZER_OPTIONS" + fi + + if [[ ! "$CMD_LINE" =~ "-dict=" ]]; then + if [ -f "$FUZZER.dict" ]; then + CMD_LINE="$CMD_LINE -dict=$FUZZER.dict" + fi + fi + + CMD_LINE="$CMD_LINE < /dev/null" + +fi + +echo $CMD_LINE + +# Unset OUT so the fuzz target can't rely on it. +unset OUT + +if [ ! -z "$DEBUGGER" ]; then + CMD_LINE="$DEBUGGER $CMD_LINE" +fi + +bash -c "$CMD_LINE" + diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/targets_list b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/targets_list new file mode 100644 index 0000000000000000000000000000000000000000..95615c81118c7991cea1c3e800ea9b5c304040ed --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/targets_list @@ -0,0 +1,10 @@ +#!/bin/bash + +for binary in $(find $OUT/ -executable -type f); do + [[ "$binary" != *.so ]] || continue + [[ $(basename "$binary") != jazzer_driver* ]] || continue + file "$binary" | grep -e ELF -e "shell script" > /dev/null 2>&1 || continue + grep "LLVMFuzzerTestOneInput" "$binary" > /dev/null 2>&1 || continue + + basename "$binary" +done diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_all.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_all.py new file mode 100644 index 0000000000000000000000000000000000000000..428e49ac0b6d7179dcab5003e6104e7a88c98906 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_all.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +# 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. +# +################################################################################ +"""Does bad_build_check on all fuzz targets in $OUT.""" + +import contextlib +import multiprocessing +import os +import re +import subprocess +import stat +import sys +import tempfile + +BASE_TMP_FUZZER_DIR = '/tmp/not-out' + +EXECUTABLE = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH + +IGNORED_TARGETS = [ + r'do_stuff_fuzzer', r'checksum_fuzzer', r'fuzz_dump', r'fuzz_keyring', + r'xmltest', r'fuzz_compression_sas_rle', r'ares_*_fuzzer' +] + +IGNORED_TARGETS_RE = re.compile('^' + r'$|^'.join(IGNORED_TARGETS) + '$') + + +def move_directory_contents(src_directory, dst_directory): + """Moves contents of |src_directory| to |dst_directory|.""" + # Use mv because mv preserves file permissions. If we don't preserve file + # permissions that can mess up CheckFuzzerBuildTest in cifuzz_test.py and + # other cases where one is calling test_all on files not in OSS-Fuzz's real + # out directory. + src_contents = [ + os.path.join(src_directory, filename) + for filename in os.listdir(src_directory) + ] + command = ['mv'] + src_contents + [dst_directory] + subprocess.check_call(command) + + +def is_elf(filepath): + """Returns True if |filepath| is an ELF file.""" + result = subprocess.run(['file', filepath], + stdout=subprocess.PIPE, + check=False) + return b'ELF' in result.stdout + + +def is_shell_script(filepath): + """Returns True if |filepath| is a shell script.""" + result = subprocess.run(['file', filepath], + stdout=subprocess.PIPE, + check=False) + return b'shell script' in result.stdout + + +def find_fuzz_targets(directory): + """Returns paths to fuzz targets in |directory|.""" + # TODO(https://github.com/google/oss-fuzz/issues/4585): Use libClusterFuzz for + # this. + fuzz_targets = [] + for filename in os.listdir(directory): + path = os.path.join(directory, filename) + if filename == 'llvm-symbolizer': + continue + if filename.startswith('afl-'): + continue + if filename.startswith('jazzer_'): + continue + if not os.path.isfile(path): + continue + if not os.stat(path).st_mode & EXECUTABLE: + continue + # Fuzz targets can either be ELF binaries or shell scripts (e.g. wrapper + # scripts for Python and JVM targets or rules_fuzzing builds with runfiles + # trees). + if not is_elf(path) and not is_shell_script(path): + continue + if os.getenv('FUZZING_ENGINE') not in {'none', 'wycheproof'}: + with open(path, 'rb') as file_handle: + binary_contents = file_handle.read() + if b'LLVMFuzzerTestOneInput' not in binary_contents: + continue + fuzz_targets.append(path) + return fuzz_targets + + +def do_bad_build_check(fuzz_target): + """Runs bad_build_check on |fuzz_target|. Returns a + Subprocess.ProcessResult.""" + print('INFO: performing bad build checks for', fuzz_target) + if centipede_needs_auxiliaries(): + print('INFO: Finding Centipede\'s auxiliary for target', fuzz_target) + auxiliary_path = find_centipede_auxiliary(fuzz_target) + print('INFO: Using auxiliary binary:', auxiliary_path) + auxiliary = [auxiliary_path] + else: + auxiliary = [] + + command = ['bad_build_check', fuzz_target] + auxiliary + with tempfile.TemporaryDirectory() as temp_centipede_workdir: + # Do this so that centipede doesn't fill up the disk during bad build check + env = os.environ.copy() + env['CENTIPEDE_WORKDIR'] = temp_centipede_workdir + return subprocess.run(command, + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, + env=env, + check=False) + + +def get_broken_fuzz_targets(bad_build_results, fuzz_targets): + """Returns a list of broken fuzz targets and their process results in + |fuzz_targets| where each item in |bad_build_results| is the result of + bad_build_check on the corresponding element in |fuzz_targets|.""" + broken = [] + for result, fuzz_target in zip(bad_build_results, fuzz_targets): + if result.returncode != 0: + broken.append((fuzz_target, result)) + return broken + + +def has_ignored_targets(out_dir): + """Returns True if |out_dir| has any fuzz targets we are supposed to ignore + bad build checks of.""" + out_files = set(os.listdir(out_dir)) + for filename in out_files: + if re.match(IGNORED_TARGETS_RE, filename): + return True + return False + + +@contextlib.contextmanager +def use_different_out_dir(): + """Context manager that moves OUT to subdirectory of BASE_TMP_FUZZER_DIR. This + is useful for catching hardcoding. Note that this sets the environment + variable OUT and therefore must be run before multiprocessing.Pool is created. + Resets OUT at the end.""" + # Use a fake OUT directory to catch path hardcoding that breaks on + # ClusterFuzz. + initial_out = os.getenv('OUT') + os.makedirs(BASE_TMP_FUZZER_DIR, exist_ok=True) + # Use a random subdirectory of BASE_TMP_FUZZER_DIR to allow running multiple + # instances of test_all in parallel (useful for integration testing). + with tempfile.TemporaryDirectory(dir=BASE_TMP_FUZZER_DIR) as out: + # Set this so that run_fuzzer which is called by bad_build_check works + # properly. + os.environ['OUT'] = out + # We move the contents of the directory because we can't move the + # directory itself because it is a mount. + move_directory_contents(initial_out, out) + try: + yield out + finally: + move_directory_contents(out, initial_out) + os.environ['OUT'] = initial_out + + +def test_all_outside_out(allowed_broken_targets_percentage): + """Wrapper around test_all that changes OUT and returns the result.""" + with use_different_out_dir() as out: + return test_all(out, allowed_broken_targets_percentage) + + +def centipede_needs_auxiliaries(): + """Checks if auxiliaries are needed for Centipede.""" + # Centipede always requires unsanitized binaries as the main fuzz targets, + # and separate sanitized binaries as auxiliaries. + # 1. Building sanitized binaries with helper.py (i.e., local or GitHub CI): + # Unsanitized ones will be built automatically into the same docker container. + # Script bad_build_check tests both + # a) If main fuzz targets can run with the auxiliaries, and + # b) If the auxiliaries are built with the correct sanitizers. + # 2. In Trial build and production build: + # Two kinds of binaries will be in separated buckets / docker containers. + # Script bad_build_check tests either + # a) If the unsanitized binaries can run without the sanitized ones, or + # b) If the sanitized binaries are built with the correct sanitizers. + return (os.getenv('FUZZING_ENGINE') == 'centipede' and + os.getenv('SANITIZER') != 'none' and os.getenv('HELPER') == 'True') + + +def find_centipede_auxiliary(main_fuzz_target_path): + """Finds the sanitized binary path that corresponds to |main_fuzz_target| for + bad_build_check.""" + target_dir, target_name = os.path.split(main_fuzz_target_path) + sanitized_binary_dir = os.path.join(target_dir, + f'__centipede_{os.getenv("SANITIZER")}') + sanitized_binary_path = os.path.join(sanitized_binary_dir, target_name) + + if os.path.isfile(sanitized_binary_path): + return sanitized_binary_path + + # Neither of the following two should ever happen, returns None to indicate + # an error. + if os.path.isdir(sanitized_binary_dir): + print('ERROR: Unable to identify Centipede\'s sanitized target' + f'{sanitized_binary_path} in {os.listdir(sanitized_binary_dir)}') + else: + print('ERROR: Unable to identify Centipede\'s sanitized target directory' + f'{sanitized_binary_dir} in {os.listdir(target_dir)}') + return None + + +def test_all(out, allowed_broken_targets_percentage): # pylint: disable=too-many-return-statements + """Do bad_build_check on all fuzz targets.""" + # TODO(metzman): Refactor so that we can convert test_one to python. + fuzz_targets = find_fuzz_targets(out) + if not fuzz_targets: + print('ERROR: No fuzz targets found.') + return False + + if centipede_needs_auxiliaries(): + for fuzz_target in fuzz_targets: + if not find_centipede_auxiliary(fuzz_target): + print(f'ERROR: Couldn\'t find auxiliary for {fuzz_target}.') + return False + + pool = multiprocessing.Pool() + bad_build_results = pool.map(do_bad_build_check, fuzz_targets) + pool.close() + pool.join() + broken_targets = get_broken_fuzz_targets(bad_build_results, fuzz_targets) + broken_targets_count = len(broken_targets) + if not broken_targets_count: + return True + + print('Retrying failed fuzz targets sequentially', broken_targets_count) + pool = multiprocessing.Pool(1) + retry_targets = [] + for broken_target, result in broken_targets: + retry_targets.append(broken_target) + bad_build_results = pool.map(do_bad_build_check, retry_targets) + pool.close() + pool.join() + broken_targets = get_broken_fuzz_targets(bad_build_results, broken_targets) + broken_targets_count = len(broken_targets) + if not broken_targets_count: + return True + + print('Broken fuzz targets', broken_targets_count) + total_targets_count = len(fuzz_targets) + broken_targets_percentage = 100 * broken_targets_count / total_targets_count + for broken_target, result in broken_targets: + print(broken_target) + # Use write because we can't print binary strings. + sys.stdout.buffer.write(result.stdout + result.stderr + b'\n') + + if broken_targets_percentage > allowed_broken_targets_percentage: + print('ERROR: {broken_targets_percentage}% of fuzz targets seem to be ' + 'broken. See the list above for a detailed information.'.format( + broken_targets_percentage=broken_targets_percentage)) + if has_ignored_targets(out): + print('Build check automatically passing because of ignored targets.') + return True + return False + print('{total_targets_count} fuzzers total, {broken_targets_count} ' + 'seem to be broken ({broken_targets_percentage}%).'.format( + total_targets_count=total_targets_count, + broken_targets_count=broken_targets_count, + broken_targets_percentage=broken_targets_percentage)) + return True + + +def get_allowed_broken_targets_percentage(): + """Returns the value of the environment value + 'ALLOWED_BROKEN_TARGETS_PERCENTAGE' as an int or returns a reasonable + default.""" + return int(os.getenv('ALLOWED_BROKEN_TARGETS_PERCENTAGE') or '10') + + +def main(): + """Does bad_build_check on all fuzz targets in parallel. Returns 0 on success. + Returns 1 on failure.""" + allowed_broken_targets_percentage = get_allowed_broken_targets_percentage() + if not test_all_outside_out(allowed_broken_targets_percentage): + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_all_test.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_all_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b3077ec1e4f6d1509b27caab141180a27202b872 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_all_test.py @@ -0,0 +1,38 @@ +# 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 test_all.py""" +import unittest +from unittest import mock + +import test_all + + +class TestTestAll(unittest.TestCase): + """Tests for the test_all_function.""" + + @mock.patch('test_all.find_fuzz_targets', return_value=[]) + @mock.patch('builtins.print') + def test_test_all_no_fuzz_targets(self, mock_print, _): + """Tests that test_all returns False when there are no fuzz targets.""" + outdir = '/out' + allowed_broken_targets_percentage = 0 + self.assertFalse( + test_all.test_all(outdir, allowed_broken_targets_percentage)) + mock_print.assert_called_with('ERROR: No fuzz targets found.') + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_one.py b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_one.py new file mode 100644 index 0000000000000000000000000000000000000000..e391ec96dcc3b9b74fd2049f88806c2578df5ff8 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_5/fuzz-tooling/infra/base-images/base-runner/test_one.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +# 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. +# +################################################################################ +"""Does bad_build_check on a fuzz target in $OUT.""" +import os +import sys + +import test_all + + +def test_one(fuzz_target): + """Does bad_build_check on one fuzz target. Returns True on success.""" + with test_all.use_different_out_dir(): + fuzz_target_path = os.path.join(os.environ['OUT'], fuzz_target) + result = test_all.do_bad_build_check(fuzz_target_path) + if result.returncode != 0: + sys.stdout.buffer.write(result.stdout + result.stderr + b'\n') + return False + return True + + +def main(): + """Does bad_build_check on one fuzz target. Returns 1 on failure, 0 on + success.""" + if len(sys.argv) != 2: + print('Usage: %d ', sys.argv[0]) + return 1 + + fuzz_target_binary = sys.argv[1] + return 0 if test_one(fuzz_target_binary) else 1 + + +if __name__ == '__main__': + sys.exit(main())