diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/base-images/base-builder-javascript/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder-jvm/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder-ruby/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder-ruby/ruzzy-build b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder-rust/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/README.md b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/bazel.bazelrc b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/bazel_build_fuzz_tests b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/bisect_clang.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/bisect_clang_test.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/cargo b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_afl b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_centipede b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_fuzztests.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_go_fuzzer b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_honggfuzz b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_javascript_fuzzer b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_libfuzzer b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_native_go_fuzzer b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/compile_python_fuzzer b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/debug_afl b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/detect_repo.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/detect_repo_test.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_deps.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_go.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_java.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_javascript.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_python.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_ruby.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_rust.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/install_swift.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/build_jcc.bash b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/go.mod b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/jcc.go b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/jcc2.go b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/jcc_test.go b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/.gitignore b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cfile.c b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/cpp.cc b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/jcc/testdata/path/to/header.h b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/llvmsymbol.diff b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/ossfuzz_coverage_runner.go b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/precompile_afl b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/precompile_centipede b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/precompile_honggfuzz b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/python_coverage_helper.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/LICENSE b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/README.md b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pyproject.toml b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/sanlib.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/yaml_deserialization.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/os_command_injection.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/os_command_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..9493aa51cca777e876c12e40e75a7036d4e4f46a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/os_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 os.system.""" + +import os +import sys +import atheris +import pysecsan + + +def list_files_perhaps(param, magicval): + """Pass fuzzer data into os.system.""" + if 'B' not in param: + return + if magicval == 1338: + os.system('exec-san') + elif magicval == 1339: + os.system('ls -la FROMFUZZ') + else: + os.system('ls -la ./') + + +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.""" + 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_1/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_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/yaml_deserialization_general.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/srcmap b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-builder/test_data/culprit-commit.txt b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-clang/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-clang/checkout_build_install_llvm.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-image/Dockerfile b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-runner/README.md b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-runner/bad_build_check b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-runner/install_java.sh b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-runner/parse_options.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-runner/test_all.py b/local-test-commons-compress-full-01-vuln_1/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_1/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_1/fuzz-tooling/infra/base-images/base-runner/test_one.py b/local-test-commons-compress-full-01-vuln_1/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_1/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()) diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3197ebbf1ae89dd327a2d4ea191f082360165389 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/affected_fuzz_targets_test.py @@ -0,0 +1,113 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for affected_fuzz_targets.py""" +import os +import shutil +import tempfile +import unittest +from unittest import mock + +import parameterized + +import affected_fuzz_targets +import clusterfuzz_deployment +import get_coverage +import test_helpers +import workspace_utils + +# pylint: disable=protected-access + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +EXAMPLE_FILE_CHANGED = 'test.txt' + +TEST_DATA_OUT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'test_data', 'build-out') + + +class RemoveUnaffectedFuzzTargetsTest(unittest.TestCase): + """Tests remove_unaffected_fuzzers.""" + + TEST_FUZZER_1 = os.path.join(TEST_DATA_OUT_PATH, 'example_crash_fuzzer') + TEST_FUZZER_2 = os.path.join(TEST_DATA_OUT_PATH, 'example_nocrash_fuzzer') + + # yapf: disable + @parameterized.parameterized.expand([ + # Tests specific affected fuzzers are kept. + ([[EXAMPLE_FILE_CHANGED], None], 2,), + + # Tests specific affected fuzzer is kept. + ([[EXAMPLE_FILE_CHANGED], ['not/a/real/file']], 1), + + # Tests all fuzzers are kept if none are deemed affected. + ([None, None], 2), + + # Tests that multiple fuzzers are kept if multiple fuzzers are affected. + ([[EXAMPLE_FILE_CHANGED], [EXAMPLE_FILE_CHANGED]], 2), + ]) + # yapf: enable + def test_remove_unaffected_fuzz_targets(self, side_effect, expected_dir_len): + """Tests that remove_unaffected_fuzzers has the intended effect.""" + config = test_helpers.create_run_config( + cfl_platform='github', + oss_fuzz_project_name=EXAMPLE_PROJECT, + workspace='/workspace') + workspace = workspace_utils.Workspace(config) + deployment = clusterfuzz_deployment.get_clusterfuzz_deployment( + config, workspace) + # We can't use fakefs in this test because this test executes + # utils.is_fuzz_target_local. This function relies on the executable bit + # being set, which doesn't work properly in fakefs. + with tempfile.TemporaryDirectory() as tmp_dir, mock.patch( + 'get_coverage.OSSFuzzCoverage.get_files_covered_by_target' + ) as mock_get_files: + with mock.patch('get_coverage._get_oss_fuzz_fuzzer_stats_dir_url', + return_value=1): + mock_get_files.side_effect = side_effect + shutil.copy(self.TEST_FUZZER_1, tmp_dir) + shutil.copy(self.TEST_FUZZER_2, tmp_dir) + + affected_fuzz_targets.remove_unaffected_fuzz_targets( + deployment, tmp_dir, [EXAMPLE_FILE_CHANGED], '') + self.assertEqual(expected_dir_len, len(os.listdir(tmp_dir))) + + +class IsFuzzTargetAffectedTest(unittest.TestCase): + """Tests for is_fuzz_target_affected.""" + + def setUp(self): + self.fuzz_target_path = '/fuzz_target' + + def test_relative_paths(self): + """Tests that is_fuzz_target_affected works as intended when the covered + files are relative paths.""" + with mock.patch.object( + get_coverage.FilesystemCoverage, + 'get_files_covered_by_target', + ) as get_files_covered_by_target: + get_files_covered_by_target.return_value = [ + '/work/build/../../src/systemd/src/basic/alloc-util.c' + ] + coverage = get_coverage.FilesystemCoverage('/', '/') + + self.assertTrue( + affected_fuzz_targets.is_fuzz_target_affected( + coverage, self.fuzz_target_path, + ['/src/systemd/src/basic/alloc-util.c'])) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers.py new file mode 100644 index 0000000000000000000000000000000000000000..fd15642e8d88c44f3ea82ba64108a8994d160ef0 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/build_fuzzers.py @@ -0,0 +1,217 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module used by CI tools in order to interact with fuzzers. This module helps +CI tools to build fuzzers.""" + +import logging +import os +import sys + +import affected_fuzz_targets +import base_runner_utils +import clusterfuzz_deployment +import continuous_integration +import docker +import logs +import workspace_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import helper +import utils + +logs.init() + + +def check_project_src_path(project_src_path): + """Returns True if |project_src_path| exists.""" + if not os.path.exists(project_src_path): + logging.error( + 'PROJECT_SRC_PATH: %s does not exist. ' + 'Are you mounting it correctly?', project_src_path) + return False + return True + + +# pylint: disable=too-many-arguments + + +class Builder: # pylint: disable=too-many-instance-attributes + """Class for fuzzer builders.""" + + def __init__(self, config, ci_system): + self.config = config + self.ci_system = ci_system + self.workspace = workspace_utils.Workspace(config) + self.workspace.initialize_dir(self.workspace.out) + self.workspace.initialize_dir(self.workspace.work) + self.clusterfuzz_deployment = ( + clusterfuzz_deployment.get_clusterfuzz_deployment( + self.config, self.workspace)) + self.image_repo_path = None + self.host_repo_path = None + self.repo_manager = None + + def build_image_and_checkout_src(self): + """Builds the project builder image and checkout source code for the patch + we want to fuzz (if necessary). Returns True on success.""" + result = self.ci_system.prepare_for_fuzzer_build() + if not result.success: + return False + self.image_repo_path = result.image_repo_path + self.repo_manager = result.repo_manager + if self.config.output_sarif: + self.workspace.make_repo_for_sarif(self.repo_manager) + logging.info('repo_dir: %s.', self.repo_manager.repo_dir) + self.host_repo_path = self.repo_manager.repo_dir + return True + + def build_fuzzers(self): + """Moves the source code we want to fuzz into the project builder and builds + the fuzzers from that source code. Returns True on success.""" + docker_args, docker_container = docker.get_base_docker_run_args( + self.workspace, self.config.sanitizer, self.config.language, + self.config.architecture, self.config.docker_in_docker) + if not docker_container: + docker_args.extend( + _get_docker_build_fuzzers_args_not_container(self.host_repo_path)) + + build_command = self.ci_system.get_build_command(self.host_repo_path, + self.image_repo_path) + + # Set extra environment variables so that they are visible to the build. + for key in self.config.extra_environment_variables: + # Don't specify their value in case they get echoed. + docker_args.extend(['-e', key]) + + docker_args.extend([ + docker.get_project_image_name(self.config.oss_fuzz_project_name), + '/bin/bash', + '-c', + build_command, + ]) + logging.info('Building with %s sanitizer.', self.config.sanitizer) + + # TODO(metzman): Stop using helper.docker_run so we can get rid of + # docker.get_base_docker_run_args and merge its contents into + # docker.get_base_docker_run_command. + if not helper.docker_run(docker_args): + logging.error('Building fuzzers failed.') + return False + + return True + + def upload_build(self): + """Upload build.""" + if self.config.upload_build: + self.clusterfuzz_deployment.upload_build( + self.repo_manager.get_current_commit()) + + return True + + def check_fuzzer_build(self): + """Checks the fuzzer build. Returns True on success or if config specifies + to skip check.""" + if not self.config.bad_build_check: + return True + + return check_fuzzer_build(self.config) + + def build(self): + """Builds the image, checkouts the source (if needed), builds the fuzzers + and then removes the unaffectted fuzzers. Returns True on success.""" + methods = [ + self.build_image_and_checkout_src, + self.build_fuzzers, + self.remove_unaffected_fuzz_targets, + self.upload_build, + self.check_fuzzer_build, + ] + for method in methods: + if not method(): + return False + return True + + def remove_unaffected_fuzz_targets(self): + """Removes the fuzzers unaffected by the patch.""" + if self.config.keep_unaffected_fuzz_targets: + logging.info('Not removing unaffected fuzz targets.') + return True + + logging.info('Removing unaffected fuzz targets.') + changed_files = self.ci_system.get_changed_code_under_test( + self.repo_manager) + affected_fuzz_targets.remove_unaffected_fuzz_targets( + self.clusterfuzz_deployment, self.workspace.out, changed_files, + self.image_repo_path) + return True + + +def build_fuzzers(config): + """Builds all of the fuzzers for a specific OSS-Fuzz project. + + Args: + config: The configuration object for building fuzzers. + + Returns: + True if build succeeded. + """ + # Do some quick validation. + if config.project_src_path and not check_project_src_path( + config.project_src_path): + return False + + # Get the builder and then build the fuzzers. + ci_system = continuous_integration.get_ci(config) + logging.info('ci_system: %s.', ci_system) + builder = Builder(config, ci_system) + return builder.build() + + +def check_fuzzer_build(config): + """Checks the integrity of the built fuzzers. + + Args: + config: The config object. + + Returns: + True if fuzzers pass OSS-Fuzz's build check. + """ + workspace = workspace_utils.Workspace(config) + if not os.path.exists(workspace.out): + logging.error('Invalid out directory: %s.', workspace.out) + return False + if not os.listdir(workspace.out): + logging.error('No fuzzers found in out directory: %s.', workspace.out) + return False + + env = base_runner_utils.get_env(config, workspace) + if config.allowed_broken_targets_percentage is not None: + env['ALLOWED_BROKEN_TARGETS_PERCENTAGE'] = ( + config.allowed_broken_targets_percentage) + + stdout, stderr, retcode = utils.execute('test_all.py', env=env) + print(f'Build check: stdout: {stdout}\nstderr: {stderr}') + if retcode == 0: + logging.info('Build check passed.') + return True + logging.error('Build check failed.') + return False + + +def _get_docker_build_fuzzers_args_not_container(host_repo_path): + """Returns arguments to the docker build arguments that are needed to use + |host_repo_path| when the host of the OSS-Fuzz builder container is not + another container.""" + return ['-v', f'{host_repo_path}:{host_repo_path}'] diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py new file mode 100644 index 0000000000000000000000000000000000000000..30e28beda330c621ac3a0f5b9d1ee2dc11a5e463 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/cifuzz_end_to_end_test.py @@ -0,0 +1,48 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""End-to-End tests for CIFuzz.""" +import os +import unittest + +import run_cifuzz +import test_helpers + +CIFUZZ_DIR = os.path.dirname(os.path.abspath(__file__)) +EXTERNAL_PROJECT_PATH = os.path.join(CIFUZZ_DIR, 'test_data', + 'external-project') + + +# This test will fail if not run as root because the fuzzer build process +# creates binaries that only root can write to. +# Use a seperate env var to keep this seperate from integration tests which +# don't have this annoying property. +@unittest.skipIf(not os.getenv('END_TO_END_TESTS'), + 'END_TO_END_TESTS=1 not set') +class EndToEndTest(unittest.TestCase): + """End-to-End tests for CIFuzz.""" + + def setUp(self): + test_helpers.patch_environ(self, runner=True) + + def test_simple(self): + """Simple end-to-end test using run_cifuzz.main().""" + os.environ['REPOSITORY'] = 'external-project' + os.environ['PROJECT_SRC_PATH'] = EXTERNAL_PROJECT_PATH + os.environ['FILESTORE'] = 'no_filestore' + os.environ['NO_CLUSTERFUZZ_DEPLOYMENT'] = 'True' + + with test_helpers.docker_temp_dir() as temp_dir: + os.environ['WORKSPACE'] = temp_dir + # TODO(metzman): Verify the crash, affected fuzzers, and other things. + self.assertEqual(run_cifuzz.main(), 1) diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/cloudbuild.yaml b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/cloudbuild.yaml new file mode 100644 index 0000000000000000000000000000000000000000..03b1961e50ff9c701133753e918179177323726e --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/cloudbuild.yaml @@ -0,0 +1,52 @@ +# TODO(metzman): Get rid of cifuzz-build-fuzzers and cifuzz-run-fuzzers. +steps: +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - '-t' + - ghcr.io/aixcc-finals/cifuzz-base + - '-t' + - ghcr.io/aixcc-finals/cifuzz-base:v1 + - '-f' + - infra/cifuzz/cifuzz-base/Dockerfile + - . +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - '-t' + - ghcr.io/aixcc-finals/cifuzz-build-fuzzers + - '-t' + - ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1 + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 + - '-f' + - infra/build_fuzzers.Dockerfile + - infra +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - '-t' + - ghcr.io/aixcc-finals/cifuzz-run-fuzzers + - '-t' + - ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1 + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers + - '-t' + - ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 + - '-f' + - infra/run_fuzzers.Dockerfile + - infra +images: +- ghcr.io/aixcc-finals/cifuzz-base +- ghcr.io/aixcc-finals/cifuzz-base:v1 +- ghcr.io/aixcc-finals/cifuzz-run-fuzzers +- ghcr.io/aixcc-finals/cifuzz-run-fuzzers:v1 +- ghcr.io/aixcc-finals/cifuzz-build-fuzzers +- ghcr.io/aixcc-finals/cifuzz-build-fuzzers:v1 +- ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers +- ghcr.io/aixcc-finals/clusterfuzzlite-build-fuzzers:v1 +- ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers +- ghcr.io/aixcc-finals/clusterfuzzlite-run-fuzzers:v1 +timeout: 1800s diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a3cb8f7ad9265f3eaaac9af4a810d412e3fc00 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils.py @@ -0,0 +1,283 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for getting the configuration CIFuzz needs to run.""" + +import enum +import importlib +import logging +import os +import sys + +import environment + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import platform_config +import constants + +SANITIZERS = ['address', 'memory', 'undefined', 'coverage'] + +# TODO(metzman): Set these on config objects so there's one source of truth. +DEFAULT_ENGINE = 'libfuzzer' + +# This module deals a lot with env variables. Many of these will be set by users +# and others beyond CIFuzz's control. Thus, you should be careful about using +# the environment.py helpers for getting env vars, since it can cause values +# that should be interpreted as strings to be returned as other types (bools or +# ints for example). The environment.py helpers should not be used for values +# that are supposed to be strings. + + +def _get_sanitizer(): + return os.getenv('SANITIZER', constants.DEFAULT_SANITIZER).lower() + + +def _get_architecture(): + return os.getenv('ARCHITECTURE', constants.DEFAULT_ARCHITECTURE).lower() + + +def _is_dry_run(): + """Returns True if configured to do a dry run.""" + return environment.get_bool('DRY_RUN', False) + + +def _get_language(): + """Returns the project language.""" + # Get language from environment. We took this approach because the convenience + # given to OSS-Fuzz users by not making them specify the language again (and + # getting it from the project.yaml) is outweighed by the complexity in + # implementing this. A lot of the complexity comes from our unittests not + # setting a proper projet at this point. + return os.getenv('LANGUAGE', constants.DEFAULT_LANGUAGE) + + +def _get_extra_environment_variables(): + """Gets extra environment variables specified by the user with + CFL_EXTRA_$NAME=$VALUE.""" + return [key for key in os.environ if key.startswith('CFL_EXTRA_')] + + +# pylint: disable=too-many-instance-attributes + + +class ConfigError(Exception): + """Error for invalid configuration.""" + + +class BaseConfig: + """Object containing constant configuration for CIFuzz.""" + + class Platform(enum.Enum): + """Enum representing the different platforms CIFuzz runs on.""" + EXTERNAL_GITHUB = 0 # Non-OSS-Fuzz on GitHub actions. + INTERNAL_GITHUB = 1 # OSS-Fuzz on GitHub actions. + INTERNAL_GENERIC_CI = 2 # OSS-Fuzz on any CI. + EXTERNAL_GENERIC_CI = 3 # Non-OSS-Fuzz on any CI. + + @property + def is_github(self): + """Returns True if running on GitHub.""" + return self.cfl_platform == 'github' + + def __init__(self): + # Need to set these before calling self.platform. + self.oss_fuzz_project_name = os.getenv('OSS_FUZZ_PROJECT_NAME') + self.cfl_platform = os.getenv('CFL_PLATFORM') + logging.debug('Is github: %s.', self.is_github) + + self.platform_conf = _get_platform_config(self.cfl_platform) + self.base_commit = self.platform_conf.base_commit + self.base_ref = self.platform_conf.base_ref + self.pr_ref = self.platform_conf.pr_ref + self.workspace = self.platform_conf.workspace + self.project_src_path = self.platform_conf.project_src_path + self.actor = self.platform_conf.actor + self.token = self.platform_conf.token + self.project_repo_owner = self.platform_conf.project_repo_owner + self.project_repo_name = self.platform_conf.project_repo_name + self.filestore = self.platform_conf.filestore + + # This determines if builds are done using docker in docker + # rather than the normal method which is sibling containers. + self.docker_in_docker = self.platform_conf.docker_in_docker + + self.dry_run = _is_dry_run() # Check if failures should not be reported. + self.sanitizer = _get_sanitizer() + self.architecture = _get_architecture() + self.language = _get_language() + self.low_disk_space = environment.get_bool('LOW_DISK_SPACE', False) + + self.git_store_repo = os.environ.get('GIT_STORE_REPO') + self.git_store_branch = os.environ.get('GIT_STORE_BRANCH') + self.git_store_branch_coverage = os.environ.get('GIT_STORE_BRANCH_COVERAGE', + self.git_store_branch) + self.cloud_bucket = os.environ.get('CLOUD_BUCKET') + self.no_clusterfuzz_deployment = environment.get_bool( + 'NO_CLUSTERFUZZ_DEPLOYMENT', False) + self.build_integration_path = ( + constants.DEFAULT_EXTERNAL_BUILD_INTEGRATION_PATH) + + self.parallel_fuzzing = environment.get_bool('PARALLEL_FUZZING', False) + self.extra_environment_variables = _get_extra_environment_variables() + self.output_sarif = environment.get_bool('OUTPUT_SARIF', False) + + # TODO(metzman): Fix tests to create valid configurations and get rid of + # CIFUZZ_TEST here and in presubmit.py. + if not os.getenv('CIFUZZ_TEST') and not self.validate(): + raise ConfigError('Invalid Configuration.') + + def validate(self): + """Returns False if the configuration is invalid.""" + # Do validation here so that unittests don't need to make a fully-valid + # config. + # pylint: disable=too-many-return-statements + if not self.workspace: + logging.error('Must set WORKSPACE.') + return False + + if self.sanitizer not in SANITIZERS: + logging.error('Invalid SANITIZER: %s. Must be one of: %s.', + self.sanitizer, SANITIZERS) + return False + + if self.architecture not in constants.ARCHITECTURES: + logging.error('Invalid ARCHITECTURE: %s. Must be one of: %s.', + self.architecture, constants.ARCHITECTURES) + return False + + if self.architecture == 'i386' and self.sanitizer != 'address': + logging.error( + 'ARCHITECTURE=i386 can be used with SANITIZER=address only.') + return False + + if self.language not in constants.LANGUAGES: + logging.error('Invalid LANGUAGE: %s. Must be one of: %s.', self.language, + constants.LANGUAGES) + return False + + if not self.project_repo_name: + logging.error('Must set REPOSITORY.') + return False + + return True + + @property + def is_internal(self): + """Returns True if this is an OSS-Fuzz project.""" + return bool(self.oss_fuzz_project_name) + + @property + def platform(self): + """Returns the platform CIFuzz is runnning on.""" + if not self.is_internal: + if not self.is_github: + return self.Platform.EXTERNAL_GENERIC_CI + return self.Platform.EXTERNAL_GITHUB + + if self.is_github: + return self.Platform.INTERNAL_GITHUB + return self.Platform.INTERNAL_GENERIC_CI + + @property + def is_coverage(self): + """Returns True if this CIFuzz run (building fuzzers and running them) for + generating a coverage report.""" + return self.sanitizer == 'coverage' + + +def _get_platform_config(cfl_platform): + """Returns the CI environment object for |cfl_platform|.""" + module_name = f'platform_config.{cfl_platform}' + try: + cls = importlib.import_module(module_name).PlatformConfig + except ImportError: + cls = platform_config.BasePlatformConfig + return cls() + + +class RunFuzzersConfig(BaseConfig): + """Class containing constant configuration for running fuzzers in CIFuzz.""" + + MODES = ['batch', 'code-change', 'coverage', 'prune'] + + def __init__(self): + super().__init__() + # TODO(metzman): Pick a better default for pruning. + self.fuzz_seconds = int(os.environ.get('FUZZ_SECONDS', 600)) + self.mode = os.environ.get('MODE', 'code-change').lower() + if self.is_coverage: + self.mode = 'coverage' + + self.report_unreproducible_crashes = environment.get_bool( + 'REPORT_UNREPRODUCIBLE_CRASHES', False) + + self.minimize_crashes = environment.get_bool('MINIMIZE_CRASHES', False) + if self.mode == 'batch': + logging.warning( + 'Minimizing crashes reduces fuzzing time in batch fuzzing.') + self.report_timeouts = environment.get_bool('REPORT_TIMEOUTS', False) + self.report_ooms = environment.get_bool('REPORT_OOMS', True) + self.upload_all_crashes = environment.get_bool('UPLOAD_ALL_CRASHES', False) + + # TODO(metzman): Fix tests to create valid configurations and get rid of + # CIFUZZ_TEST here and in presubmit.py. + if not os.getenv('CIFUZZ_TEST') and not self._run_config_validate(): + raise ConfigError('Invalid Run Configuration.') + + def _run_config_validate(self): + """Do extra validation on RunFuzzersConfig.__init__(). Do not name this + validate or else it will be called when using the parent's __init__ and will + fail. Returns True if valid.""" + if self.mode not in self.MODES: + logging.error('Invalid MODE: %s. Must be one of %s.', self.mode, + self.MODES) + return False + + return True + + +class BuildFuzzersConfig(BaseConfig): + """Class containing constant configuration for building fuzzers in CIFuzz.""" + + def __init__(self): + """Get the configuration from CIFuzz from the environment. These variables + are set by GitHub or the user.""" + super().__init__() + self.git_sha = self.platform_conf.git_sha + self.git_url = self.platform_conf.git_url + + self.allowed_broken_targets_percentage = os.getenv( + 'ALLOWED_BROKEN_TARGETS_PERCENTAGE') + self.bad_build_check = environment.get_bool('BAD_BUILD_CHECK', True) + + self.keep_unaffected_fuzz_targets = environment.get_bool( + 'KEEP_UNAFFECTED_FUZZ_TARGETS') + + self.upload_build = environment.get_bool('UPLOAD_BUILD', False) + if not self.keep_unaffected_fuzz_targets: + has_base_for_diff = (self.base_ref or self.base_commit) + if not has_base_for_diff: + logging.info( + 'Keeping all fuzzers because there is nothing to diff against.') + self.keep_unaffected_fuzz_targets = True + elif self.upload_build: + logging.info('Keeping all fuzzers because we are uploading build.') + self.keep_unaffected_fuzz_targets = True + elif self.sanitizer == 'coverage': + logging.info('Keeping all fuzzers because we are doing coverage.') + self.keep_unaffected_fuzz_targets = True + + if self.sanitizer == 'coverage': + self.bad_build_check = False diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..cb82dee44026532eb0b0127a6bb565e25e965f1e --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/config_utils_test.py @@ -0,0 +1,200 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for config_utils.""" +import os +import unittest +from unittest import mock + +import config_utils +import constants +import test_helpers + +# pylint: disable=no-self-use,protected-access + + +class BaseConfigTest(unittest.TestCase): + """Tests for BaseConfig.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def _create_config(self): + return config_utils.BuildFuzzersConfig() + + def test_language_default(self): + """Tests that the correct default language is set.""" + config = self._create_config() + self.assertEqual(config.language, 'c++') + + def test_language(self): + """Tests that the correct language is set.""" + language = 'python' + os.environ['LANGUAGE'] = language + config = self._create_config() + self.assertEqual(config.language, language) + + def test_is_coverage(self): + """Tests that is_coverage is set correctly.""" + # Test it is set when it is supposed to be. + os.environ['SANITIZER'] = 'coverage' + config = self._create_config() + self.assertTrue(config.is_coverage) + + # Test it is not set when it is not supposed to be. + os.environ['SANITIZER'] = 'address' + config = self._create_config() + self.assertFalse(config.is_coverage) + + @mock.patch('logging.error') + def test_validate_no_workspace(self, mock_error): + """Tests that validate returns False if GITHUB_WORKSPACE isn't set.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + config = self._create_config() + self.assertFalse(config.validate()) + mock_error.assert_called_with('Must set WORKSPACE.') + + @mock.patch('logging.error') + def test_validate_invalid_language(self, mock_error): + """Tests that validate returns False if GITHUB_WORKSPACE isn't set.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + os.environ['WORKSPACE'] = '/workspace' + os.environ['LANGUAGE'] = 'invalid-language' + config = self._create_config() + self.assertFalse(config.validate()) + mock_error.assert_called_with('Invalid LANGUAGE: %s. Must be one of: %s.', + os.environ['LANGUAGE'], constants.LANGUAGES) + + @mock.patch('logging.error') + def test_validate_invalid_sanitizer(self, mock_error): + """Tests that validate returns False if GITHUB_WORKSPACE isn't set.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + os.environ['WORKSPACE'] = '/workspace' + os.environ['SANITIZER'] = 'invalid-sanitizer' + config = self._create_config() + self.assertFalse(config.validate()) + mock_error.assert_called_with('Invalid SANITIZER: %s. Must be one of: %s.', + os.environ['SANITIZER'], + config_utils.SANITIZERS) + + def test_validate(self): + """Tests that validate returns True if config is valid.""" + os.environ['OSS_FUZZ_PROJECT_NAME'] = 'example' + os.environ['WORKSPACE'] = '/workspace' + os.environ['REPOSITORY'] = 'repo' + config = self._create_config() + self.assertTrue(config.validate()) + + +class BuildFuzzersConfigTest(unittest.TestCase): + """Tests for BuildFuzzersConfig.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def _create_config(self): + return config_utils.BuildFuzzersConfig() + + @mock.patch('platform_config.github._get_event_data', return_value={}) + def test_github_base_ref(self, _): + """Tests that base_ref is set properly.""" + expected_base_ref = 'expected_base_ref' + os.environ['GITHUB_BASE_REF'] = expected_base_ref + os.environ['CFL_PLATFORM'] = 'github' + os.environ['GITHUB_REPOSITORY'] = 'owner/repo' + config = self._create_config() + self.assertEqual(config.base_ref, expected_base_ref) + + def test_base_ref(self): + """Tests that base_ref is set properly.""" + expected_base_ref = 'expected_base_ref' + os.environ['GIT_BASE_REF'] = expected_base_ref + config = self._create_config() + self.assertEqual(config.base_ref, expected_base_ref) + + def test_keep_unaffected_defaults_to_true(self): + """Tests that keep_unaffected_fuzz_targets defaults to true.""" + config = self._create_config() + self.assertTrue(config.keep_unaffected_fuzz_targets) + + def test_keep_unaffected_defaults_to_false_when_pr(self): + """Tests that keep_unaffected_fuzz_targets defaults to false when from a + pr.""" + os.environ['GIT_BASE_REF'] = 'base-ref' + config = self._create_config() + self.assertFalse(config.keep_unaffected_fuzz_targets) + + +class RunFuzzersConfigTest(unittest.TestCase): + """Tests for RunFuzzersConfig.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def _create_config(self): + return config_utils.RunFuzzersConfig() + + def test_coverage(self): + """Tests that mode is overriden properly based on is_coverage.""" + # Test that it is overriden when it is supposed to be. + os.environ['SANITIZER'] = 'coverage' + os.environ['MODE'] = 'code-change' + config = self._create_config() + self.assertEqual(config.mode, 'coverage') + + # Test that it isn't overriden when it isn't supposed to be. + os.environ['SANITIZER'] = 'address' + mode = 'code-change' + os.environ['MODE'] = mode + config = self._create_config() + self.assertEqual(config.mode, mode) + + def test_run_config_validate(self): + """Tests that _run_config_validate returns True when the config is valid.""" + self.assertTrue(self._create_config()._run_config_validate()) + + @mock.patch('logging.error') + def test_run_config_invalid_mode(self, mock_error): + """Tests that _run_config_validate returns False when mode is invalid.""" + fake_mode = 'fake-mode' + os.environ['MODE'] = fake_mode + self.assertFalse(self._create_config()._run_config_validate()) + mock_error.assert_called_with('Invalid MODE: %s. Must be one of %s.', + fake_mode, + config_utils.RunFuzzersConfig.MODES) + + +class GetSanitizerTest(unittest.TestCase): + """Tests for _get_sanitizer.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.sanitizer = 'memory' + + def test_default_value(self): + """Tests that the default value returned by _get_sanitizer is correct.""" + self.assertEqual(config_utils._get_sanitizer(), 'address') + + def test_normal_case(self): + """Tests that _get_sanitizer returns the correct value in normal cases.""" + os.environ['SANITIZER'] = self.sanitizer + self.assertEqual(config_utils._get_sanitizer(), self.sanitizer) + + def test_capitalization(self): + """Tests that that _get_sanitizer handles capitalization properly.""" + os.environ['SANITIZER'] = self.sanitizer.upper() + self.assertEqual(config_utils._get_sanitizer(), self.sanitizer) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker.py new file mode 100644 index 0000000000000000000000000000000000000000..36e4d7c572cccc0faa3638439193af5973f0e65e --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker.py @@ -0,0 +1,127 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for dealing with docker.""" +import logging +import os +import sys +import uuid + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +import constants +import utils +import environment + +BASE_BUILDER_TAG = 'ghcr.io/aixcc-finals/base-builder' +PROJECT_TAG_PREFIX = 'gcr.io/oss-fuzz/' + +# Default fuzz configuration. +_DEFAULT_DOCKER_RUN_ARGS = [ + '-e', 'FUZZING_ENGINE=' + constants.DEFAULT_ENGINE, '-e', 'CIFUZZ=True' +] + +UNIQUE_ID_SUFFIX = '-' + uuid.uuid4().hex + +# TODO(metzman): Make run_fuzzers able to delete this image. +EXTERNAL_PROJECT_IMAGE = 'external-cfl-project' + UNIQUE_ID_SUFFIX + +_DEFAULT_DOCKER_RUN_COMMAND = [ + 'docker', + 'run', + '--rm', + '--privileged', +] + + +def get_docker_env_vars(env_mapping): + """Returns a list of docker arguments that sets each key in |env_mapping| as + an env var and the value of that key in |env_mapping| as the value.""" + env_var_args = [] + for env_var, env_var_val in env_mapping.items(): + env_var_args.extend(['-e', f'{env_var}={env_var_val}']) + return env_var_args + + +def get_project_image_name(project): + """Returns the name of the project builder image for |project_name|.""" + # TODO(jonathanmetzman): We may need unique names to support parallel fuzzing + # for CIFuzz (like CFL supports). Don't do this for now because no one has + # asked for it and build_specified_commit would need to be modified to support + # this. + if project: + return PROJECT_TAG_PREFIX + project + + return EXTERNAL_PROJECT_IMAGE + + +def delete_images(images): + """Deletes |images|.""" + command = ['docker', 'rmi', '-f'] + images + utils.execute(command) + utils.execute(['docker', 'builder', 'prune', '-f']) + + +def get_base_docker_run_args(workspace, + sanitizer=constants.DEFAULT_SANITIZER, + language=constants.DEFAULT_LANGUAGE, + architecture=constants.DEFAULT_ARCHITECTURE, + docker_in_docker=False): + """Returns arguments that should be passed to every invocation of 'docker + run'.""" + docker_args = _DEFAULT_DOCKER_RUN_ARGS.copy() + env_mapping = { + 'SANITIZER': sanitizer, + 'ARCHITECTURE': architecture, + 'FUZZING_LANGUAGE': language, + 'OUT': workspace.out + } + docker_args += get_docker_env_vars(env_mapping) + docker_container = environment.get('CFL_CONTAINER_ID', + utils.get_container_name()) + logging.info('Docker container: %s.', docker_container) + if docker_container and not docker_in_docker: + # Don't map specific volumes if in a docker container, it breaks when + # running a sibling container. + docker_args += ['--volumes-from', docker_container] + else: + docker_args += _get_args_mapping_host_path_to_container(workspace.workspace) + return docker_args, docker_container + + +def get_base_docker_run_command(workspace, + sanitizer=constants.DEFAULT_SANITIZER, + language=constants.DEFAULT_LANGUAGE, + architecture=constants.DEFAULT_ARCHITECTURE, + docker_in_docker=False): + """Returns part of the command that should be used everytime 'docker run' is + invoked.""" + docker_args, docker_container = get_base_docker_run_args( + workspace, + sanitizer, + language, + architecture, + docker_in_docker=docker_in_docker) + command = _DEFAULT_DOCKER_RUN_COMMAND.copy() + docker_args + return command, docker_container + + +def _get_args_mapping_host_path_to_container(host_path, container_path=None): + """Get arguments to docker run that will map |host_path| a path on the host to + a path in the container. If |container_path| is specified, that path is mapped + to. If not, then |host_path| is mapped to itself in the container.""" + # WARNING: Do not use this function when running in production (and + # --volumes-from) is used for mapping volumes. It will break production. + container_path = host_path if container_path is None else container_path + return ['-v', f'{host_path}:{container_path}'] diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker_test.py new file mode 100644 index 0000000000000000000000000000000000000000..045131c10c5b94ed7739769890a243c2776dc999 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/docker_test.py @@ -0,0 +1,119 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests the functionality of the docker module.""" +import unittest +from unittest import mock + +import docker +import test_helpers +import workspace_utils + +CONTAINER_NAME = 'example-container' +config = test_helpers.create_run_config(oss_fuzz_project_name='project', + workspace='/workspace') +config.workspace = '/workspace' +WORKSPACE = workspace_utils.Workspace(config) +SANITIZER = 'example-sanitizer' +LANGUAGE = 'example-language' + + +class GetProjectImageTest(unittest.TestCase): + """Tests for get_project_image.""" + + def test_get_project_image(self): + """Tests that get_project_image_name works as intended.""" + project = 'my-project' + self.assertEqual(docker.get_project_image_name(project), + 'gcr.io/oss-fuzz/my-project') + + +class GetDeleteImagesTest(unittest.TestCase): + """Tests for delete_images.""" + + @mock.patch('utils.execute') + def test_delete_images(self, mock_execute): # pylint: disable=no-self-use + """Tests that get_project_image_name works as intended.""" + images = ['image'] + docker.delete_images(images) + expected_calls = [ + mock.call(['docker', 'rmi', '-f'] + images), + mock.call(['docker', 'builder', 'prune', '-f']) + ] + + mock_execute.assert_has_calls(expected_calls) + + +class GetBaseDockerRunArgsTest(unittest.TestCase): + """Tests get_base_docker_run_args.""" + + @mock.patch('utils.get_container_name', return_value=CONTAINER_NAME) + def test_get_base_docker_run_args_container(self, _): + """Tests that get_base_docker_run_args works as intended when inside a + container.""" + docker_args, docker_container = docker.get_base_docker_run_args( + WORKSPACE, SANITIZER, LANGUAGE) + self.assertEqual(docker_container, CONTAINER_NAME) + expected_docker_args = [] + expected_docker_args = [ + '-e', + 'FUZZING_ENGINE=libfuzzer', + '-e', + 'CIFUZZ=True', + '-e', + f'SANITIZER={SANITIZER}', + '-e', + 'ARCHITECTURE=x86_64', + '-e', + f'FUZZING_LANGUAGE={LANGUAGE}', + '-e', + f'OUT={WORKSPACE.out}', + '--volumes-from', + CONTAINER_NAME, + ] + self.assertEqual(docker_args, expected_docker_args) + + @mock.patch('utils.get_container_name', return_value=None) + def test_get_base_docker_run_args_no_container(self, _): + """Tests that get_base_docker_run_args works as intended when not inside a + container.""" + docker_args, docker_container = docker.get_base_docker_run_args( + WORKSPACE, SANITIZER, LANGUAGE) + self.assertEqual(docker_container, None) + expected_docker_args = [ + '-e', 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e', + f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e', + f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v', + f'{WORKSPACE.workspace}:{WORKSPACE.workspace}' + ] + self.assertEqual(docker_args, expected_docker_args) + + +class GetBaseDockerRunCommandTest(unittest.TestCase): + """Tests get_base_docker_run_args.""" + + @mock.patch('utils.get_container_name', return_value=None) + def test_get_base_docker_run_command_no_container(self, _): + """Tests that get_base_docker_run_args works as intended when not inside a + container.""" + docker_args, docker_container = docker.get_base_docker_run_command( + WORKSPACE, SANITIZER, LANGUAGE) + self.assertEqual(docker_container, None) + expected_docker_command = [ + 'docker', 'run', '--rm', '--privileged', '-e', + 'FUZZING_ENGINE=libfuzzer', '-e', 'CIFUZZ=True', '-e', + f'SANITIZER={SANITIZER}', '-e', 'ARCHITECTURE=x86_64', '-e', + f'FUZZING_LANGUAGE={LANGUAGE}', '-e', f'OUT={WORKSPACE.out}', '-v', + f'{WORKSPACE.workspace}:{WORKSPACE.workspace}' + ] + self.assertEqual(docker_args, expected_docker_command) diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/filestore_utils_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/filestore_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e1307376548252e0633cb2c2343feee2c0f745 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/filestore_utils_test.py @@ -0,0 +1,50 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for filestore_utils.""" +import unittest +from unittest import mock + +import parameterized + +import platform_config +import filestore +from filestore import github_actions +import filestore_utils +import test_helpers + + +class GetFilestoreTest(unittest.TestCase): + """Tests for get_filestore.""" + + @parameterized.parameterized.expand([ + ({ + 'cfl_platform': 'github', + }, github_actions.GithubActionsFilestore), + ]) + def test_get_filestore(self, config_kwargs, filestore_cls): + """Tests that get_filestore returns the right filestore given a certain + platform.""" + run_config = test_helpers.create_run_config(**config_kwargs) + filestore_impl = filestore_utils.get_filestore(run_config) + self.assertIsInstance(filestore_impl, filestore_cls) + + @mock.patch('config_utils.BaseConfig.platform', return_value='other') + @mock.patch('config_utils._get_platform_config', + return_value=platform_config.BasePlatformConfig()) + def test_get_filestore_unsupported_platform(self, _, __): + """Tests that get_filestore exceptions given a platform it doesn't + support.""" + run_config = test_helpers.create_run_config() + with self.assertRaises(filestore.FilestoreError): + filestore_utils.get_filestore(run_config) diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/fuzz_target_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/fuzz_target_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e553a25aecacfebc1a15e920fc54f19388d396d6 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/fuzz_target_test.py @@ -0,0 +1,298 @@ +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests the functionality of the fuzz_target module.""" + +import os +import shutil +import tempfile +import unittest +from unittest import mock + +import certifi +# Importing this later causes import failures with pytest for some reason. +# TODO(ochang): Figure out why. +import parameterized +import google.cloud.ndb # pylint: disable=unused-import +from pyfakefs import fake_filesystem_unittest +from clusterfuzz.fuzz import engine + +import clusterfuzz_deployment +import fuzz_target +import test_helpers +import workspace_utils + +# NOTE: This integration test relies on +# https://github.com/google/oss-fuzz/tree/master/projects/example project. +EXAMPLE_PROJECT = 'example' + +# An example fuzzer that triggers an error. +EXAMPLE_FUZZER = 'example_crash_fuzzer' + +# Mock return values for engine_impl.reproduce. +EXECUTE_SUCCESS_RESULT = engine.ReproduceResult([], 0, 0, '') +EXECUTE_FAILURE_RESULT = engine.ReproduceResult([], 1, 0, '') + +TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'test_data') + + +def _create_config(**kwargs): + """Creates a config object and then sets every attribute that is a key in + |kwargs| to the corresponding value. Asserts that each key in |kwargs| is an + attribute of Config.""" + defaults = { + 'cfl_platform': 'github', + 'oss_fuzz_project_name': EXAMPLE_PROJECT, + 'workspace': '/workspace' + } + for default_key, default_value in defaults.items(): + if default_key not in kwargs: + kwargs[default_key] = default_value + + return test_helpers.create_run_config(**kwargs) + + +def _create_deployment(**kwargs): + config = _create_config(**kwargs) + workspace = workspace_utils.Workspace(config) + return clusterfuzz_deployment.get_clusterfuzz_deployment(config, workspace) + + +@mock.patch('utils.get_container_name', return_value='container') +class IsReproducibleTest(fake_filesystem_unittest.TestCase): + """Tests the is_reproducible method in the fuzz_target.FuzzTarget class.""" + + def setUp(self): + """Sets up example fuzz target to test is_reproducible method.""" + self.fuzz_target_name = 'fuzz-target' + deployment = _create_deployment() + self.config = deployment.config + self.workspace = deployment.workspace + self.fuzz_target_path = os.path.join(self.workspace.out, + self.fuzz_target_name) + self.setUpPyfakefs() + self.fs.create_file(self.fuzz_target_path) + self.testcase_path = '/testcase' + self.fs.create_file(self.testcase_path) + + self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, + fuzz_target.REPRODUCE_ATTEMPTS, + self.workspace, deployment, + deployment.config) + + # ClusterFuzz requires ROOT_DIR. + root_dir = os.environ['ROOT_DIR'] + test_helpers.patch_environ(self, empty=True) + os.environ['ROOT_DIR'] = root_dir + + # There's an extremely bad issue that happens if this test is run: Other tests + # in this file fail in CI with stacktraces using referencing fakefs even if + # the tests do not use fakefs. + # TODO(metzman): Stop using fakefs. + @mock.patch('os.chmod') + @unittest.skip('Skip because of weird failures.') + def test_repro_timed_out(self, mock_chmod, mock_get_container_name): + """Tests that is_reproducible behaves correctly when reproduction times + out.""" + del mock_get_container_name + del mock_chmod + + with mock.patch( + 'clusterfuzz._internal.bot.fuzzers.libFuzzer.engine.LibFuzzerEngine.' + 'reproduce', + side_effect=TimeoutError): + self.assertFalse( + self.target.is_reproducible('/testcase', self.target.target_path, [])) + + def test_reproducible(self, _): + """Tests that is_reproducible returns True if crash is detected and that + is_reproducible uses the correct command to reproduce a crash.""" + all_repro = [EXECUTE_FAILURE_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = all_repro + + result = self.target.is_reproducible(self.testcase_path, + self.fuzz_target_path, []) + mock_get_engine().reproduce.assert_called_once_with( + '/workspace/build-out/fuzz-target', + '/testcase', + arguments=[], + max_time=30) + self.assertTrue(result) + self.assertEqual(1, mock_get_engine().reproduce.call_count) + + def test_flaky(self, _): + """Tests that is_reproducible returns True if crash is detected on the last + attempt.""" + last_time_repro = [EXECUTE_SUCCESS_RESULT] * 9 + [EXECUTE_FAILURE_RESULT] + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = last_time_repro + self.assertTrue( + self.target.is_reproducible(self.testcase_path, self.fuzz_target_path, + [])) + self.assertEqual(fuzz_target.REPRODUCE_ATTEMPTS, + mock_get_engine().reproduce.call_count) + + def test_nonexistent_fuzzer(self, _): + """Tests that is_reproducible raises an error if it could not attempt + reproduction because the fuzzer doesn't exist.""" + with self.assertRaises(fuzz_target.ReproduceError): + self.target.is_reproducible(self.testcase_path, '/non-existent-path', []) + + def test_unreproducible(self, _): + """Tests that is_reproducible returns False for a crash that did not + reproduce.""" + all_unrepro = [EXECUTE_SUCCESS_RESULT] * fuzz_target.REPRODUCE_ATTEMPTS + with mock.patch('clusterfuzz.fuzz.get_engine') as mock_get_engine: + mock_get_engine().reproduce.side_effect = all_unrepro + result = self.target.is_reproducible(self.testcase_path, + self.fuzz_target_path, []) + self.assertFalse(result) + + +class IsCrashReportableTest(fake_filesystem_unittest.TestCase): + """Tests the is_crash_reportable method of FuzzTarget.""" + + def setUp(self): + """Sets up example fuzz target to test is_crash_reportable method.""" + self.setUpPyfakefs() + self.fuzz_target_path = '/example/do_stuff_fuzzer' + deployment = _create_deployment() + self.target = fuzz_target.FuzzTarget(self.fuzz_target_path, 100, + deployment.workspace, deployment, + deployment.config) + self.oss_fuzz_build_path = '/oss-fuzz-build' + self.fs.create_file(self.fuzz_target_path) + self.oss_fuzz_target_path = os.path.join( + self.oss_fuzz_build_path, os.path.basename(self.fuzz_target_path)) + self.fs.create_file(self.oss_fuzz_target_path) + self.testcase_path = '/testcase' + self.fs.create_file(self.testcase_path, contents='') + + # Do this to prevent pyfakefs from messing with requests. + self.fs.add_real_directory(os.path.dirname(certifi.__file__)) + + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=[True, False]) + @mock.patch('logging.info') + def test_new_reproducible_crash(self, mock_info, _): + """Tests that a new reproducible crash returns True.""" + with tempfile.TemporaryDirectory() as tmp_dir: + self.target.out_dir = tmp_dir + self.assertTrue(self.target.is_crash_reportable(self.testcase_path, [])) + mock_info.assert_called_with( + 'The crash is not reproducible on previous build. ' + 'Code change (pr/commit) introduced crash.') + + # yapf: disable + @parameterized.parameterized.expand([ + # Reproducible on PR build, but also reproducible on OSS-Fuzz. + ([True, True],), + + # Not reproducible on PR build, but somehow reproducible on OSS-Fuzz. + # Unlikely to happen in real world except if test is flaky. + ([False, True],), + + # Not reproducible on PR build, and not reproducible on OSS-Fuzz. + ([False, False],), + ]) + # yapf: enable + def test_invalid_crash(self, is_reproducible_retvals): + """Tests that a nonreportable crash causes the method to return False.""" + with mock.patch('fuzz_target.FuzzTarget.is_reproducible', + side_effect=is_reproducible_retvals): + with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build', + return_value=self.oss_fuzz_build_path): + self.assertFalse(self.target.is_crash_reportable( + self.testcase_path, [])) + + @mock.patch('logging.info') + @mock.patch('fuzz_target.FuzzTarget.is_reproducible', return_value=[True]) + def test_reproducible_no_oss_fuzz_target(self, _, mock_info): + """Tests that is_crash_reportable returns True when a crash reproduces on + the PR build but the target is not in the OSS-Fuzz build (usually because it + is new).""" + os.remove(self.oss_fuzz_target_path) + + def is_reproducible_side_effect(testcase, target_path, reproduce_arguments): + del testcase + del reproduce_arguments + if os.path.dirname(target_path) == self.oss_fuzz_build_path: + raise fuzz_target.ReproduceError() + return True + + with mock.patch( + 'fuzz_target.FuzzTarget.is_reproducible', + side_effect=is_reproducible_side_effect) as mock_is_reproducible: + with mock.patch('clusterfuzz_deployment.OSSFuzz.download_latest_build', + return_value=self.oss_fuzz_build_path): + self.assertTrue(self.target.is_crash_reportable(self.testcase_path, [])) + mock_is_reproducible.assert_any_call(self.testcase_path, + self.oss_fuzz_target_path, []) + mock_info.assert_called_with( + 'Could not run previous build of target to determine if this code ' + 'change (pr/commit) introduced crash. Assuming crash was newly ' + 'introduced.') + + +class FuzzTest(fake_filesystem_unittest.TestCase): + """Fuzz test.""" + + def setUp(self): + """Sets up example fuzz target.""" + self.setUpPyfakefs() + deployment = _create_deployment() + config = deployment.config + workspace = deployment.workspace + self.fuzz_target = fuzz_target.FuzzTarget('/path/fuzz-target', 10, + workspace, deployment, config) + + def test_get_fuzz_target_artifact(self): + """Tests that get_fuzz_target_artifact works as intended.""" + # pylint: disable=protected-access + fuzz_target_artifact = self.fuzz_target._target_artifact_path() + self.assertEqual('/workspace/out/artifacts/fuzz-target/address', + fuzz_target_artifact) + + +class TimeoutIntegrationTest(unittest.TestCase): + """Tests handling of fuzzer timeout (timeout crashes reported by + libFuzzer).""" + TIMEOUT_FUZZER_NAME = 'timeout_fuzzer' + + @parameterized.parameterized.expand([(True, True), (False, False)]) + def test_timeout_reported(self, report_timeouts, expect_crash): + """Tests that timeouts are not reported.""" + with test_helpers.temp_dir_copy(TEST_DATA_PATH) as temp_dir: + fuzz_target_path = os.path.join(temp_dir, 'build-out', + self.TIMEOUT_FUZZER_NAME) + shutil.copy(os.path.join(temp_dir, self.TIMEOUT_FUZZER_NAME), + fuzz_target_path) + deployment = _create_deployment(workspace=temp_dir, + report_timeouts=report_timeouts) + config = deployment.config + fuzz_target_obj = fuzz_target.FuzzTarget(fuzz_target_path, + fuzz_target.REPRODUCE_ATTEMPTS, + deployment.workspace, deployment, + config) + with mock.patch('clusterfuzz._internal.bot.fuzzers.libfuzzer.' + 'fix_timeout_argument_for_reproduction') as _: + with mock.patch( + 'clusterfuzz._internal.bot.fuzzers.libFuzzer.fuzzer.get_arguments', + return_value=['-timeout=1', '-rss_limit_mb=2560']): + fuzz_result = fuzz_target_obj.fuzz() + self.assertEqual(bool(fuzz_result.testcase), expect_crash) + + +if __name__ == '__main__': + unittest.main() diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report.py new file mode 100644 index 0000000000000000000000000000000000000000..9901c452a0fe536670e5ec6da68b73a902d985e5 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report.py @@ -0,0 +1,48 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for generating coverage reports.""" +import os + +import base_runner_utils +import fuzz_target +import utils + + +def run_coverage_command(config, workspace): + """Runs the coverage command in base-runner to generate a coverage report.""" + env = base_runner_utils.get_env(config, workspace) + env['HTTP_PORT'] = '' + env['COVERAGE_EXTRA_ARGS'] = '' + env['CORPUS_DIR'] = workspace.corpora + env['COVERAGE_OUTPUT_DIR'] = workspace.coverage_report + command = 'coverage' + return utils.execute(command, env=env) + + +def download_corpora(fuzz_target_paths, clusterfuzz_deployment): + """Downloads corpora for fuzz targets in |fuzz_target_paths| using + |clusterfuzz_deployment| to download corpora from ClusterFuzz/OSS-Fuzz.""" + for target_path in fuzz_target_paths: + target_name = os.path.basename(target_path) + corpus_dir = fuzz_target.get_fuzz_target_corpus_dir( + clusterfuzz_deployment.workspace, target_name) + clusterfuzz_deployment.download_corpus(target_name, corpus_dir) + + +def generate_coverage_report(fuzz_target_paths, workspace, + clusterfuzz_deployment, config): + """Generates a coverage report using Clang's source based coverage.""" + download_corpora(fuzz_target_paths, clusterfuzz_deployment) + run_coverage_command(config, workspace) + clusterfuzz_deployment.upload_coverage() diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py new file mode 100644 index 0000000000000000000000000000000000000000..df2c9b206b84cdc92b5304f2669ea4cadcc71cae --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/generate_coverage_report_test.py @@ -0,0 +1,71 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for generate_coverage_report.""" + +import unittest +from unittest import mock + +import generate_coverage_report +import test_helpers + +OUT_DIR = '/outdir' +PROJECT = 'example-project' +SANITIZER = 'coverage' + + +class TestRunCoverageCommand(unittest.TestCase): + """Tests run_coverage_command""" + + def setUp(self): + test_helpers.patch_environ(self, empty=True) + + @mock.patch('utils.execute') + def test_run_coverage_command(self, mock_execute): # pylint: disable=no-self-use + """Tests that run_coverage_command works as intended.""" + config = test_helpers.create_run_config(oss_fuzz_project_name=PROJECT, + sanitizer=SANITIZER) + workspace = test_helpers.create_workspace() + generate_coverage_report.run_coverage_command(config, workspace) + expected_command = 'coverage' + expected_env = { + 'SANITIZER': config.sanitizer, + 'FUZZING_LANGUAGE': config.language, + 'OUT': workspace.out, + 'CIFUZZ': 'True', + 'FUZZING_ENGINE': 'libfuzzer', + 'ARCHITECTURE': 'x86_64', + 'FUZZER_ARGS': '-rss_limit_mb=2560 -timeout=25', + 'HTTP_PORT': '', + 'COVERAGE_EXTRA_ARGS': '', + 'CORPUS_DIR': workspace.corpora, + 'COVERAGE_OUTPUT_DIR': workspace.coverage_report + } + mock_execute.assert_called_with(expected_command, env=expected_env) + + +class DownloadCorporaTest(unittest.TestCase): + """Tests for download_corpora.""" + + def test_download_corpora(self): # pylint: disable=no-self-use + """Tests that download_corpora works as intended.""" + clusterfuzz_deployment = mock.Mock() + clusterfuzz_deployment.workspace = test_helpers.create_workspace() + fuzz_target_paths = ['/path/to/fuzzer1', '/path/to/fuzzer2'] + expected_calls = [ + mock.call('fuzzer1', '/workspace/cifuzz-corpus/fuzzer1'), + mock.call('fuzzer2', '/workspace/cifuzz-corpus/fuzzer2') + ] + generate_coverage_report.download_corpora(fuzz_target_paths, + clusterfuzz_deployment) + clusterfuzz_deployment.download_corpus.assert_has_calls(expected_calls) diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/get_coverage.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/get_coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..762de7928cb93f074b73b51a37514e3807104d37 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/get_coverage.py @@ -0,0 +1,208 @@ +# Copyright 2021 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Module for determining coverage of fuzz targets.""" +import json +import logging +import os +import sys + +import http_utils + +# pylint: disable=wrong-import-position,import-error +sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import utils + +# The path to get OSS-Fuzz project's latest report json file.` +OSS_FUZZ_LATEST_COVERAGE_INFO_PATH = 'oss-fuzz-coverage/latest_report_info/' + + +# pylint: disable=too-few-public-methods +class CoverageError(Exception): + """Exceptions for project coverage.""" + + +class BaseCoverage: + """Gets coverage data for a project.""" + + def __init__(self, repo_path): + self.repo_path = _normalize_repo_path(repo_path) + + def get_files_covered_by_target(self, target): + """Returns a list of source files covered by the specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + A list of files that the fuzz target covers or None. + """ + target_cov = self.get_target_coverage(target) + if not target_cov: + logging.info('No coverage available for %s.', target) + return None + + coverage_per_file = get_coverage_per_file(target_cov) + if not coverage_per_file: + logging.info('No files found in coverage report.') + return None + + affected_file_list = [] + for file_cov in coverage_per_file: + norm_file_path = os.path.normpath(file_cov['filename']) + if not norm_file_path.startswith(self.repo_path): + # Exclude files outside of the main repo. + continue + + if not is_file_covered(file_cov): + # Don't consider a file affected if code in it is never executed. + continue + + # TODO(metzman): It's weird to me that we access file_cov['filename'] + # again and not norm_file_path, figure out if this makes sense. + relative_path = utils.remove_prefix(file_cov['filename'], self.repo_path) + affected_file_list.append(relative_path) + + return affected_file_list + + def get_target_coverage(self, target): + """Get the coverage report for a specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + The target's coverage json dict or None on failure. + """ + raise NotImplementedError('Child class must implement method.') + + +class OSSFuzzCoverage(BaseCoverage): + """Gets coverage data for a project from OSS-Fuzz.""" + + def __init__(self, repo_path, oss_fuzz_project_name): + """Constructor for OSSFuzzCoverage.""" + super().__init__(repo_path) + self.oss_fuzz_project_name = oss_fuzz_project_name + self.fuzzer_stats_url = _get_oss_fuzz_fuzzer_stats_dir_url( + self.oss_fuzz_project_name) + if self.fuzzer_stats_url is None: + raise CoverageError('Could not get latest coverage.') + + def get_target_coverage(self, target): + """Get the coverage report for a specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + The target's coverage json dict or None on failure. + """ + if not self.fuzzer_stats_url: + return None + + target_url = utils.url_join(self.fuzzer_stats_url, target + '.json') + return http_utils.get_json_from_url(target_url) + + +def _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name): + """Gets and returns a dictionary containing the latest coverage report info + for |project|.""" + latest_report_info_url = utils.url_join(utils.GCS_BASE_URL, + OSS_FUZZ_LATEST_COVERAGE_INFO_PATH, + oss_fuzz_project_name + '.json') + latest_cov_info = http_utils.get_json_from_url(latest_report_info_url) + if latest_cov_info is None: + logging.error('Could not get the coverage report json from url: %s.', + latest_report_info_url) + return None + return latest_cov_info + + +def _get_oss_fuzz_fuzzer_stats_dir_url(oss_fuzz_project_name): + """Gets latest coverage report info for a specific OSS-Fuzz project from + GCS. + + Args: + oss_fuzz_project_name: The name of the project. + + Returns: + The projects coverage report info in json dict or None on failure. + """ + latest_cov_info = _get_oss_fuzz_latest_cov_report_info(oss_fuzz_project_name) + + if not latest_cov_info: + return None + + if 'fuzzer_stats_dir' not in latest_cov_info: + logging.error('fuzzer_stats_dir not in latest coverage info.') + return None + + fuzzer_stats_dir_gs_url = latest_cov_info['fuzzer_stats_dir'] + fuzzer_stats_dir_url = utils.gs_url_to_https(fuzzer_stats_dir_gs_url) + return fuzzer_stats_dir_url + + +class FilesystemCoverage(BaseCoverage): + """Class that gets a project's coverage from the filesystem.""" + + def __init__(self, repo_path, project_coverage_dir): + super().__init__(repo_path) + self.project_coverage_dir = project_coverage_dir + + def get_target_coverage(self, target): + """Get the coverage report for a specific fuzz target. + + Args: + target: The name of the fuzz target whose coverage is requested. + + Returns: + The target's coverage json dict or None on failure. + """ + logging.info('Getting coverage for %s from filesystem.', target) + fuzzer_stats_json_path = os.path.join(self.project_coverage_dir, + 'fuzzer_stats', target + '.json') + if not os.path.exists(fuzzer_stats_json_path): + logging.warning('%s does not exist.', fuzzer_stats_json_path) + return None + + with open(fuzzer_stats_json_path) as fuzzer_stats_json_file_handle: + try: + return json.load(fuzzer_stats_json_file_handle) + except json.decoder.JSONDecodeError as err: + logging.error('Could not decode: %s. Error: %s.', + fuzzer_stats_json_path, err) + return None + + +def is_file_covered(file_cov): + """Returns whether the file is covered.""" + return file_cov['summary']['regions']['covered'] + + +def get_coverage_per_file(target_cov): + """Returns the coverage per file within |target_cov|.""" + try: + return target_cov['data'][0]['files'] + except (IndexError, TypeError, KeyError): + logging.error('target_cov: %s is malformed.', target_cov) + return None + + +def _normalize_repo_path(repo_path): + """Normalizes and returns |repo_path| to make sure cases like /src/curl and + /src/curl/ are both handled.""" + repo_path = os.path.normpath(repo_path) + if not repo_path.endswith('/'): + repo_path += '/' + return repo_path diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/sarif_utils_test.py b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/sarif_utils_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e8870887c071e4694a6550af0a4f432ad3838a8f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/cifuzz/sarif_utils_test.py @@ -0,0 +1,128 @@ +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Tests for sarif_utils.py""" +import os +import unittest +from unittest import mock + +import sarif_utils + +CRASH_INFO_FILELINE = 403 + +TEST_DATA = os.path.join(os.path.dirname(__file__), 'test_data') + + +class GetSarifDataTest(unittest.TestCase): + """Tests for get_sarif_data.""" + + def setUp(self): + self.maxDiff = None # pylint: disable=invalid-name + + def test_get_sarif_data_none(self): + """Tests get_sarif_data when there was no crash.""" + self.assertEqual(sarif_utils.get_sarif_data(None, '/root/target'), + sarif_utils.SARIF_DATA) + + def test_ordinary_case(self): + stacktrace_filename = os.path.join(TEST_DATA, + 'sarif_utils_systemd_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + expected_result = { + 'level': 'error', + 'message': { + 'text': 'Heap-buffer-overflow\nREAD 4' + }, + 'locations': [{ + 'physicalLocation': { + 'artifactLocation': { + 'uri': 'src/core/fuzz-unit-file.c', + 'index': 0 + }, + 'region': { + 'startLine': 30, + # We don't have this granualarity fuzzing. + 'startColumn': 1, + } + } + }], + 'ruleId': 'heap-buffer-overflow', + 'ruleIndex': 2 + } + actual_result = sarif_utils.get_sarif_data( + stacktrace, '/root/target')['runs'][0]['results'][0] + self.assertEqual(actual_result, expected_result) + + def test_llvmfuzzertestoneinput_case(self): + stacktrace_filename = os.path.join(TEST_DATA, + 'sarif_utils_only_llvmfuzzer_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + actual_result = sarif_utils.get_sarif_data( + stacktrace, '/root/target')['runs'][0]['results'] + self.assertEqual(actual_result, []) + + def test_msan(self): + """Tests that MSAN stacktraces don't exception.""" + stacktrace_filename = os.path.join(TEST_DATA, 'sarif_utils_msan_stack.txt') + with open(stacktrace_filename, 'r') as fp: + stacktrace = fp.read() + + actual_result = sarif_utils.get_sarif_data(stacktrace, '/root/target') + + +class RedactSrcPathTest(unittest.TestCase): + """Tests for redact_src_path.""" + + def test_redact_src_path(self): + """Tests redact_src_path.""" + path = '/src/src-repo/subdir/file' + self.assertEqual(sarif_utils.redact_src_path(path), 'subdir/file') + + +def _get_mock_crash_info(): + """Returns a mock crash_info to be used in tests.""" + stack_frame = mock.MagicMock() + stack_frame.filename = '/src/repo-dir/sub/vuln.cc' + stack_frame.function_name = 'vuln_func' + stack_frame.fileline = CRASH_INFO_FILELINE + crash1_frames = [stack_frame, stack_frame] + frames = [crash1_frames] + crash_info = mock.MagicMock() + crash_info.frames = frames + crash_info.crash_state = 'vuln_func\nvuln_func0\nvuln_func1' + return crash_info + + +class GetErrorSourceInfoTest(unittest.TestCase): + """Tests for get_error_source_info.""" + + def test_redact_src_path(self): + """Tests that get_error_source_info finds the right source info.""" + crash_info = _get_mock_crash_info() + source_info = sarif_utils.get_error_source_info(crash_info) + expected_source_info = ('sub/vuln.cc', CRASH_INFO_FILELINE) + self.assertEqual(source_info, expected_source_info) + + +class GetRuleIndexTest(unittest.TestCase): + """Tests for get_rule_index.""" + CRASH_INFO_CRASH_TYPE = 'Heap-use-after-free READ 8' + + def test_get_rule_index(self): + """Tests that get_rule_index finds the right rule index.""" + index = sarif_utils.get_rule_index(self.CRASH_INFO_CRASH_TYPE) + self.assertEqual(sarif_utils.SARIF_RULES[index]['id'], + 'heap-use-after-free') + self.assertEqual(sarif_utils.get_rule_index('no-crashes'), 0) diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/Makefile b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..04db9976eac198bd430650da656998169912dc2f --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/Makefile @@ -0,0 +1,41 @@ +.POSIX: +CXX = clang++ +CFLAGS = -std=c++17 -Wall -Wextra -O3 -g3 -Werror + +all: SystemSan target target_file target_dns + +SystemSan: SystemSan.cpp inspect_dns.cpp inspect_utils.cpp + $(CXX) $(CFLAGS) -lpthread -o $@ $^ + +# Needs atheris. +python-test: all + ./SystemSan python shell_injection_poc_fuzzer.py + +target: target.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +target_file: target_file.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +target_dns: target_dns.cpp + $(CXX) $(CFLAGS) -fsanitize=address,fuzzer -o $@ $^ + +test: all vuln.dict + ./SystemSan ./target -dict=vuln.dict + ./SystemSan ./target_file -dict=vuln.dict + ./SystemSan ./target_dns -dict=vuln.dict + +pytorch-lightning-1.5.10: + cp SystemSan.cpp PoEs/pytorch-lightning-1.5.10/; \ + cd PoEs/pytorch-lightning-1.5.10/; \ + docker build . --tag syssan_pytorch-lightning; \ + docker run -t systemsan_pytorch-lightning:latest; + +node-shell-quote-v1.7.3: + cp SystemSan.cpp PoEs/node-shell-quote-v1.7.3/; \ + cd PoEs/node-shell-quote-v1.7.3/; \ + docker build . --tag systemsan_node-shell-quote; \ + docker run -t systemsan_node-shell-quote:latest; + +clean: + rm -f SystemSan /tmp/tripwire target target_file target_dns diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..0d19aa407357659d0beb8487443c65eead7dab6a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/PoEs/pytorch-lightning-1.5.10/vuln.dict @@ -0,0 +1 @@ +"os.system('/tmp/tripwire')" diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/README.md b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..48e111d1abc6d96661659f9a19dd7fc6f969baad --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/README.md @@ -0,0 +1,66 @@ +# System Sanitizers + +We use `ptrace` to instrument system calls made by the target program to detect +various vulnerabilities. + +## Command injection + +This detector currently works by + +- Checking if `execve` is called with `/tmp/tripwire` (which comes from our dictionary). +- Checking if `execve` is invoking a shell with invalid syntax. This is likely + caused by our input. + +## Arbitrary file open + +TODO: documentation. + +## Proof of concept + +### Cleanup +Note this will delete /tmp/tripwire if it exists. +```shell +make clean +``` + +### Run test +Note this will overwrite /tmp/tripwire if it exists. +```shell +make test +``` + +Look for one of the following lines: + +> ===BUG DETECTED: Shell injection=== + +which indicates the detection of executing the planted `/tmp/tripwire`. + + +> ===BUG DETECTED: Shell corruption=== + +which indicates the detection of executing a syntactic erroneous command. + + +### Command injection PoC in Python with `pytorch-lightning` +With `SystemSan`, [`Artheris`](https://github.com/google/atheris) can detect a shell injection bug in [version v1.5.10 of `pytorch-lightning`](https://github.com/PyTorchLightning/pytorch-lightning/tree/1.5.0). +```shell +make pytorch-lightning-1.5.10 +``` + +### Command injection PoC in JavaScript with `shell-quote` +With `SystemSan`, [`Jsfuzz`](https://gitlab.com/gitlab-org/security-products/analyzers/fuzzers/jsfuzz) can detect a shell corrpution bug in [the latest version (v1.7.3) of `shell-quote`](https://github.com/substack/node-shell-quote) without any seed. +```shell +make node-shell-quote-v1.7.3 +``` +This is based on [a shell injection exploit report](https://wh0.github.io/2021/10/28/shell-quote-rce-exploiting.html) of [version v1.7.2 of `shell-quote`](https://github.com/substack/node-shell-quote/tree/v1.7.2). +`SystemSan` can also discover the same shell injection bug with a corpus file containing: +``` +`:`/tmp/tripwire``:` +``` + +## Trophies + +- +- + + diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27e8795c55df12d3c17399eda52c738c1b914240 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/SystemSan.cpp @@ -0,0 +1,493 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify shell injection vulnerabilities. */ + +/* C standard library */ +#include +#include +#include +#include + +/* POSIX */ +#include +#include +#include +#include + +/* Linux */ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "inspect_utils.h" +#include "inspect_dns.h" + +#define DEBUG_LOGS 0 + +#if DEBUG_LOGS +#define debug_log(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fflush(stdout); \ + fputc('\n', stderr); \ + } while (0) +#else +#define debug_log(...) +#endif + +#define fatal_log(...) \ + do { \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + exit(EXIT_FAILURE); \ + } while (0) + +// The magic string that we'll use to detect full control over the command +// executed. +const std::string kTripWire = "/tmp/tripwire"; +// Shell injection bug confirmed with /tmp/tripwire. +const std::string kInjectionError = "Shell injection"; +// Shell corruption bug detected based on syntax error. +const std::string kCorruptionError = "Shell corruption"; +// The magic string that we'll use to detect arbitrary file open +const std::string kFzAbsoluteDirectory = "/fz/"; +// Arbitrary file open in /fz/ +const std::string kArbitraryFileOpenError = "Arbitrary file open"; +// Assuming only shorter (than this constant) top dir are legitly used. +constexpr int kRootDirMaxLength = 16; + +// The PID of the root process we're fuzzing. +pid_t g_root_pid; + +// Map of a PID/TID its PID/TID creator and wether it ran exec. +std::map root_pids; + +// Assuming the longest pathname is "/bin/bash". +constexpr int kShellPathnameLength = 20; + +// Syntax error messages of each shell. +const std::map> kShellSyntaxErrors = { + {"bash", + { + ": command not found", // General + ": syntax error", // Unfinished " or ' or ` or if, leading | or ; + ": missing `]'", // Unfinished [ + ": event not found", // ! leads large numbers + ": No such file or directory", // Leading < or / + }}, + {"csh", + { + ": Command not found.", // General + ": Missing }.", // Unfinished { + "Too many ('s.", // Unfinished ( + "Invalid null command.", // Leading | or < or > + "Missing name for redirect.", // Single < or > + ": No match.", // Leading ? or [ or * + "Modifier failed.", // Leading ^ + "No previous left hand side.", // A ^ + ": No such job.", // Leading % + ": No current job.", // A % + ": Undefined variable.", // Containing $ + ": Event not found.", // ! leads large numbers + // TODO: Make this more specific. + "Unmatched", // Unfinished " or ' or `, leading ; + }}, + {"dash", + { + "not found", // General + "Syntax error", // Unfinished " or ' or ` or if, leading | or ; or & + "missing ]", // Unfinished [ + "No such file", // Leading < + }}, + {"zsh", + { + ": command not found", // General + ": syntax error", // Unfinished " or ' or ` + ": ']' expected", // Unfinished [ + ": no such file or directory", // Leading < or / + ": parse error near", // Leading |, or & + ": no such user or named directory", // Leading ~ + }}, +}; + +// Shells used by Processes. +std::map g_shell_pids; + +struct Tracee { + pid_t pid; + bool syscall_enter = true; + + Tracee(pid_t pid) : pid(pid) {} +}; + +pid_t run_child(char **argv) { + // Run the program under test with its args as a child process + pid_t pid = fork(); + switch (pid) { + case -1: + fatal_log("Fork failed: %s", strerror(errno)); + case 0: + raise(SIGSTOP); + execvp(argv[0], argv); + fatal_log("execvp: %s", strerror(errno)); + } + return pid; +} + +// Construct a string with the memory specified in a register. +std::string read_string(pid_t pid, unsigned long reg, unsigned long length) { + auto memory = read_memory(pid, reg, length); + if (!memory.size()) { + return ""; + } + + std::string content(reinterpret_cast(memory.data()), + std::min(memory.size(), length)); + return content; +} + +void inspect_for_injection(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's registers for the sign of shell injection. + std::string path = read_string(pid, regs.rdi, kTripWire.length()); + if (!path.length()) { + return; + } + debug_log("inspecting"); + if (path == kTripWire) { + report_bug(kInjectionError, pid); + } +} + +std::string get_pathname(pid_t pid, const user_regs_struct ®s) { + // Parse the pathname from the memory specified in the RDI register. + std::string pathname = read_string(pid, regs.rdi, kShellPathnameLength); + debug_log("Pathname is %s (len %lu)\n", pathname.c_str(), pathname.length()); + return pathname; +} + +std::string match_shell(std::string binary_pathname); + +// Identify the exact shell behind sh +std::string identify_sh(std::string path) { + char shell_pathname[kShellPathnameLength]; + auto written = readlink(path.c_str(), shell_pathname, kShellPathnameLength - 1); + if (written == -1) { + std::cerr << "Cannot query which shell is behind sh: readlink failed on " + << path << ": " + << strerror(errno) << "\n"; + std::cerr << "Assuming the shell is dash\n"; + return "dash"; + } + shell_pathname[written] = '\0'; + + debug_log("sh links to %s\n", shell_pathname); + std::string shell_pathname_str(shell_pathname); + + return match_shell(shell_pathname_str); +} + +std::string match_shell(std::string binary_pathname) { + // Identify the name of the shell used in the pathname. + if (!binary_pathname.length()) { + return ""; + } + + // We use c_str() to accept only the null terminated string. + std::string binary_name = binary_pathname.substr( + binary_pathname.find_last_of("/") + 1).c_str(); + + debug_log("Binary is %s (%lu)\n", binary_name.c_str(), + binary_name.length()); + + for (const auto &item : kShellSyntaxErrors) { + std::string known_shell = item.first; + if (binary_name == "sh") { + debug_log("Matched sh: Needs to identify which specific shell it is.\n"); + return identify_sh(binary_pathname); + } + if (binary_name == known_shell) { + debug_log("Matched %s\n", binary_name.c_str()); + return known_shell; + } + } + return ""; +} + +std::string get_shell(pid_t pid, const user_regs_struct ®s) { + // Get shell name used in a process. + std::string binary_pathname = get_pathname(pid, regs); + return match_shell(binary_pathname); +} + +void match_error_pattern(std::string buffer, std::string shell, pid_t pid) { + auto error_patterns = kShellSyntaxErrors.at(shell); + for (const auto &pattern : error_patterns) { + if (buffer.find(pattern) != std::string::npos) { + std::cerr << "--- Found a sign of shell corruption ---\n" + << buffer.c_str() + << "\n----------------------------------------\n"; + // If a shell corruption error happens, kill its parent. + auto parent = root_pids[pid]; + while (!parent.ran_exec) { + if (parent.parent_tid == g_root_pid) { + break; + } + parent = root_pids[parent.parent_tid]; + } + report_bug(kCorruptionError, parent.parent_tid); + } + } +} + +void inspect_for_corruption(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's registers for shell corruption. + std::string buffer = read_string(pid, regs.rsi, regs.rdx); + debug_log("Write buffer: %s\n", buffer.c_str()); + match_error_pattern(buffer, g_shell_pids[pid], pid); +} + +void log_file_open(std::string path, int flags, pid_t pid) { + report_bug(kArbitraryFileOpenError, pid); + std::cerr << "===File opened: " << path.c_str() << ", flags = " << flags << ","; + switch (flags & 3) { + case O_RDONLY: + std::cerr << "O_RDONLY"; + break; + case O_WRONLY: + std::cerr << "O_WRONLY"; + break; + case O_RDWR: + std::cerr << "O_RDWR"; + break; + default: + std::cerr << "unknown"; + } + std::cerr << "===\n"; +} + +bool has_unprintable(const std::string &value) { + for (size_t i = 0; i < value.length(); i++) { + if (value[i] & 0x80) { + return true; + } + } + return false; +} + +void inspect_for_arbitrary_file_open(pid_t pid, const user_regs_struct ®s) { + // Inspect a PID's register for the sign of arbitrary file open. + std::string path = read_string(pid, regs.rsi, kRootDirMaxLength); + if (!path.length()) { + return; + } + if (path.substr(0, kFzAbsoluteDirectory.length()) == kFzAbsoluteDirectory) { + log_file_open(path, regs.rdx, pid); + return; + } + if (path[0] == '/' && path.length() > 1) { + std::string path_absolute_topdir = path; + size_t root_dir_end = path.find('/', 1); + if (root_dir_end != std::string::npos) { + path_absolute_topdir = path.substr(0, root_dir_end); + } + if (has_unprintable(path_absolute_topdir)) { + struct stat dirstat; + if (stat(path_absolute_topdir.c_str(), &dirstat) != 0) { + log_file_open(path, regs.rdx, pid); + } + } + } +} + +int trace(std::map pids) { + unsigned long exit_status = 0; + while (!pids.empty()) { + std::vector new_pids; + + auto it = pids.begin(); + + while (it != pids.end()) { + auto pid = it->first; + auto &tracee = it->second; + int status = 0; + + int result = waitpid(pid, &status, __WALL | WNOHANG); + if (result == -1) { + it = pids.erase(it); + continue; + } + + if (result == 0) { + // Nothing to report yet. + ++it; + continue; + } + + if (WIFEXITED(status) || WIFSIGNALED(status)) { + debug_log("%d exited", pid); + it = pids.erase(it); + // Remove pid from the watchlist when it exits + g_shell_pids.erase(pid); + root_pids.erase(pid); + continue; + } + + // ptrace sets 0x80 for syscalls (with PTRACE_O_TRACESYSGOOD set). + bool is_syscall = + WIFSTOPPED(status) && WSTOPSIG(status) == (SIGTRAP | 0x80); + int sig = 0; + if (!is_syscall) { + // Handle generic signal. + siginfo_t siginfo; + if (ptrace(PTRACE_GETSIGINFO, pid, nullptr, &siginfo) == -1) { + debug_log("ptrace(PTRACE_GETSIGINFO, %d): %s", pid, strerror(errno)); + continue; + } + sig = siginfo.si_signo; + debug_log("forwarding signal %d to %d", sig, pid); + } + + if ((status >> 8 == (SIGTRAP | (PTRACE_EVENT_EXIT << 8)))) { + debug_log("%d exiting", pid); + if (pid == g_root_pid) { + if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &exit_status) == -1) { + debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno)); + } + debug_log("got exit status from root process: %lu", exit_status); + } + + if (ptrace(PTRACE_DETACH, pid, 0, 0) == -1) { + debug_log("ptrace(PTRACE_DETACH, %d): %s", pid, strerror(errno)); + } + continue; + } + + if (WIFSTOPPED(status) && + (status >> 8 == (SIGTRAP | (PTRACE_EVENT_CLONE << 8)) || + status >> 8 == (SIGTRAP | (PTRACE_EVENT_FORK << 8)) || + status >> 8 == (SIGTRAP | (PTRACE_EVENT_VFORK << 8)))) { + long new_pid; + if (ptrace(PTRACE_GETEVENTMSG, pid, 0, &new_pid) == -1) { + debug_log("ptrace(PTRACE_GETEVENTMSG, %d): %s", pid, strerror(errno)); + continue; + } + debug_log("forked %ld", new_pid); + new_pids.push_back(new_pid); + root_pids.emplace(new_pid, ThreadParent(pid)); + } + + if (is_syscall) { + user_regs_struct regs; + if (ptrace(PTRACE_GETREGS, pid, 0, ®s) == -1) { + debug_log("ptrace(PTRACE_GETREGS, %d): %s", pid, strerror(errno)); + continue; + } + + if (tracee.syscall_enter) { + if (regs.orig_rax == __NR_execve) { + // This is a new process. + auto parent = root_pids[pid]; + parent.ran_exec = true; + root_pids[pid] = parent; + inspect_for_injection(pid, regs); + std::string shell = get_shell(pid, regs); + if (shell != "") { + debug_log("Shell parsed: %s", shell.c_str()); + g_shell_pids.insert(std::make_pair(pid, shell)); + } + } + + inspect_dns_syscalls(pid, regs); + + if (regs.orig_rax == __NR_openat) { + // TODO(metzman): Re-enable this once we have config/flag support. + // inspect_for_arbitrary_file_open(pid, regs); + } + + if (regs.orig_rax == __NR_write && + g_shell_pids.find(pid) != g_shell_pids.end()) { + debug_log("Inspecting the `write` buffer of shell process %d.", + pid); + inspect_for_corruption(pid, regs); + } + } + + // TODO: Check for commands with invalid syntax passed to /bin/sh and + // other shells. + // TODO: It's possible the process we're fuzzing can communicate with + // another process to execute code. Our check wouldn't catch this + // currently. + tracee.syscall_enter = !tracee.syscall_enter; + } + + if (ptrace(PTRACE_SYSCALL, pid, nullptr, sig) == -1) { + debug_log("ptrace(PTRACE_SYSCALL, %d): %s", pid, strerror(errno)); + continue; + } + + ++it; + } + + for (const auto &pid : new_pids) { + pids.emplace(pid, Tracee(pid)); + } + } + return static_cast(exit_status >> 8); +} + +int main(int argc, char **argv) { + if (argc <= 1) { + fatal_log("Expecting at least one arguments, received %d", argc - 1); + } + + // Create an executable tripwire file, as programs may check for existence + // before actually calling exec. + std::ofstream tripwire(kTripWire); + tripwire.close(); + chmod(kTripWire.c_str(), 0755); + + pid_t pid = run_child(argv + 1); + + long options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK | + PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE | + PTRACE_O_TRACEEXIT; + + if (ptrace(PTRACE_SEIZE, pid, nullptr, options) == -1) { + fatal_log("ptrace(PTRACE_SEIZE): %s", strerror(errno)); + } + + if (waitpid(pid, nullptr, __WALL) == -1) { + fatal_log("waitpid: %s", strerror(errno)); + } + + if (ptrace(PTRACE_SYSCALL, pid, 0, 0) == -1) { + fatal_log("ptrace(PTRACE_SYSCALL): %s", strerror(errno)); + } + + g_root_pid = pid; + std::map pids; + pids.emplace(pid, Tracee(pid)); + root_pids.emplace(pid, ThreadParent(pid)); + return trace(pids); +} diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030446345096fedc53fe7ea5826a36982a460c42 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.cpp @@ -0,0 +1,236 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify shell injection vulnerabilities. */ + +/* POSIX */ +#include +#include + +/* Linux */ +#include +#include +#include + +#include + +#include "inspect_utils.h" + + +// Arbitrary domain name resolution. +const std::string kArbitraryDomainNameResolution = "Arbitrary domain name resolution"; + +// Global constant for one file descriptor about of a DNS socket +int kFdDns = 0; +const size_t kDnsHeaderLen = 12; + + +void inspect_for_arbitrary_dns_connect(pid_t pid, const user_regs_struct ®s) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct sockaddr_in)); + if (memory.size()) { + struct sockaddr_in * sa = reinterpret_cast(memory.data()); + if (sa->sin_family == AF_INET && htons(sa->sin_port) == 53) { + // save file descriptor for later sendmmsg + kFdDns = regs.rdi; + } + } +} + +struct DnsHeader { + uint16_t tx_id; + uint16_t flags; + uint16_t questions; + uint16_t answers; + uint16_t nameservers; + uint16_t additional; +}; + +struct DnsHeader parse_dns_header(std::vector data) { + struct DnsHeader h; + h.tx_id = (((uint16_t) data[0]) << 8) | ((uint16_t) data[1]); + h.flags = (((uint16_t) data[2]) << 8) | ((uint16_t) data[3]); + h.questions = (((uint16_t) data[4]) << 8) | ((uint16_t) data[5]); + h.answers = (((uint16_t) data[6]) << 8) | ((uint16_t) data[7]); + h.nameservers = (((uint16_t) data[8]) << 8) | ((uint16_t) data[9]); + h.additional = (((uint16_t) data[10]) << 8) | ((uint16_t) data[11]); + return h; +} + +bool dns_flags_standard_query(uint16_t flags) { + if ((flags & 0x8000) == 0) { + // Query, not response. + if (((flags & 0x7800) >> 11) == 0) { + // Opcode 0 is standard query. + if ((flags & 0x0200) == 0) { + // Message is not truncated. + if ((flags & 0x0040) == 0) { + // Z-bit reserved flag is unset. + return true; + } + } + } + } + return false; +} + +struct DnsRequest { + // Start of name in the byte vector. + size_t offset; + // End of name in the byte vector. + size_t end; + // Length of top level domain. + uint8_t tld_size; + // Number of levels/dots in domain name. + size_t nb_levels; + // DNS type like A is 1. + uint16_t dns_type; + // DNS class like IN is 1. + uint16_t dns_class; +}; + +struct DnsRequest parse_dns_request(std::vector data, size_t offset) { + struct DnsRequest r; + r.offset = offset; + r.tld_size = 0; + r.nb_levels = 0; + while(offset < data.size()) { + uint8_t rlen = uint8_t(data[offset]); + if (rlen == 0) { + offset++; + break; + } + r.nb_levels++; + offset += rlen+1; + r.tld_size = rlen; + } + if (offset <= 4 + data.size()) { + r.end = offset; + r.dns_type = (((uint16_t) data[offset]) << 8) | ((uint16_t) data[offset+1]); + r.dns_class = (((uint16_t) data[offset+2]) << 8) | ((uint16_t) data[offset+3]); + } else { + r.end = data.size(); + } + return r; +} + +void log_dns_request(struct DnsRequest r, std::vector data) { + size_t offset = r.offset; + std::cerr << "===Domain resolved: "; + while(offset < r.end) { + uint8_t rlen = uint8_t(data[offset]); + if (rlen == 0) { + break; + } + std::cerr << '.'; + for (uint8_t i = 1; i < rlen+1; i++) { + std::cerr << (char) data[offset + i]; + } + offset += rlen+1; + } + std::cerr << "===\n"; + std::cerr << "===DNS request type: " << r.dns_type << ", class: " << r.dns_class << "===\n"; +} + +void inspect_for_arbitrary_dns_pkt(std::vector data, pid_t pid) { + if (data.size() < kDnsHeaderLen + 1) { + return; + } + struct DnsHeader h = parse_dns_header(data); + if (h.questions != 1) { + return; + } + if (h.answers != 0 || h.nameservers != 0) { + return; + } + if (!dns_flags_standard_query(h.flags)) { + return; + } + + struct DnsRequest req = parse_dns_request(data, kDnsHeaderLen); + // Alert if the top level domain is only one character and + // if there is more than just the TLD. + if (req.tld_size == 1 && req.nb_levels > 1 && req.end < data.size()) { + report_bug(kArbitraryDomainNameResolution, pid); + log_dns_request(req, data); + } +} + +void inspect_for_arbitrary_dns_fdbuffer(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, regs.rdx); + if (memory.size()) { + inspect_for_arbitrary_dns_pkt(memory, pid); + } + } +} + +void inspect_for_arbitrary_dns_iov(pid_t pid, unsigned long iov) { + auto memory = read_memory(pid, iov, sizeof(struct iovec)); + if (memory.size()) { + struct iovec * iovec = reinterpret_cast(memory.data()); + memory = read_memory(pid, (unsigned long) iovec->iov_base, iovec->iov_len); + if (memory.size()) { + inspect_for_arbitrary_dns_pkt(memory, pid); + } + } +} + +void inspect_for_arbitrary_dns_sendmsg(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct msghdr)); + if (memory.size()) { + struct msghdr * msg = reinterpret_cast(memory.data()); + if (msg->msg_iovlen == 1) { + inspect_for_arbitrary_dns_iov(pid, (unsigned long) msg->msg_iov); + } + } + } +} + +void inspect_for_arbitrary_dns_sendmmsg(pid_t pid, const user_regs_struct ®s) { + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + auto memory = read_memory(pid, regs.rsi, sizeof(struct mmsghdr)); + if (memory.size()) { + struct mmsghdr * msg = reinterpret_cast(memory.data()); + if (msg->msg_hdr.msg_iovlen == 1) { + inspect_for_arbitrary_dns_iov(pid, (unsigned long) msg->msg_hdr.msg_iov); + } + } + } +} + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s) { + switch (regs.orig_rax) { + case __NR_connect: + inspect_for_arbitrary_dns_connect(pid, regs); + break; + case __NR_close: + if (kFdDns > 0 && kFdDns == (int) regs.rdi) { + // reset DNS file descriptor on close + kFdDns = 0; + } + break; + case __NR_sendmmsg: + inspect_for_arbitrary_dns_sendmmsg(pid, regs); + break; + case __NR_sendmsg: + inspect_for_arbitrary_dns_sendmsg(pid, regs); + break; + case __NR_sendto: + // fallthrough + case __NR_write: + inspect_for_arbitrary_dns_fdbuffer(pid, regs); + } +} diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h new file mode 100644 index 0000000000000000000000000000000000000000..849af4e980679c3b8cbbd875216a06ba7b909f3a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_dns.h @@ -0,0 +1,26 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +/* Linux */ +#include + + +void inspect_dns_syscalls(pid_t pid, const user_regs_struct ®s); diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..713d61d757c0c135271591bf17d9a1c108f37c27 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.cpp @@ -0,0 +1,73 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + +/* C standard library */ +#include + +/* POSIX */ +#include + +/* Linux */ +#include + +#include +#include +#include +#include + +#include "inspect_utils.h" + +extern pid_t g_root_pid; +extern std::map root_pids; + +std::vector read_memory(pid_t pid, unsigned long long address, + size_t size) { + std::vector memory; + + for (size_t i = 0; i < size; i += sizeof(long)) { + long word = ptrace(PTRACE_PEEKTEXT, pid, address + i, 0); + if (word == -1) { + return memory; + } + + std::byte *word_bytes = reinterpret_cast(&word); + memory.insert(memory.end(), word_bytes, word_bytes + sizeof(long)); + } + + return memory; +} + +void report_bug(std::string bug_type, pid_t tid) { + // Report the bug found based on the bug code. + std::cerr << "===BUG DETECTED: " << bug_type.c_str() << "===\n"; + // Rely on sanitizers/libFuzzer to produce a stacktrace by sending SIGABRT + // to the root process. + // Note: this may not be reliable or consistent if shell injection happens + // in an async way. + // Find the thread group id, that is the pid. + pid_t pid = tid; + auto parent = root_pids[tid]; + while (!parent.ran_exec) { + // Find the first parent which ran exec syscall. + if (parent.parent_tid == g_root_pid) { + break; + } + pid = parent.parent_tid; + parent = root_pids[parent.parent_tid]; + } + tgkill(pid, tid, SIGABRT); +} diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..a0737f28b1ae8de07b002f03d56fdab471674723 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/inspect_utils.h @@ -0,0 +1,39 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* A detector that uses ptrace to identify DNS arbitrary resolutions. */ + + +/* POSIX */ +#include + +#include +#include + +// Structure to know which thread id triggered the bug. +struct ThreadParent { + // Parent thread ID, ie creator. + pid_t parent_tid; + // Current thread ID ran exec to become another process. + bool ran_exec = false; + + ThreadParent() : parent_tid(0) {} + ThreadParent(pid_t tid) : parent_tid(tid) {} +}; + +std::vector read_memory(pid_t pid, unsigned long long address, + size_t size); + +void report_bug(std::string bug_type, pid_t tid); diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target.cpp b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target.cpp new file mode 100644 index 0000000000000000000000000000000000000000..eb1b1dd0c2488c39f2d6de94f861dd1a96775b3a --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target.cpp @@ -0,0 +1,28 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* A sample target program under test, + * /tmp/tripwire or other commands will be injected into its shell command */ + +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + system(str.c_str()); + return 0; +} diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d7ef1ceef23bcb5ab7bca9a1933f6742fb054b7 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target_dns.cpp @@ -0,0 +1,39 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +#include +#include +#include +#include + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + + struct addrinfo *result = NULL; + + getaddrinfo(str.c_str(), NULL, NULL, &result); + if (result) { + freeaddrinfo(result); + } + + return 0; +} diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc55eb7f4c3e9778b378c16355a5f0fafeefbaf6 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/target_file.cpp @@ -0,0 +1,32 @@ +/* + * Copyright 2022 Google LLC + + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + + * http://www.apache.org/licenses/LICENSE-2.0 + + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* A sample target program under test, + * /tmp/tripwire or other commands will be injected into its shell command */ + +#include +#include +#include +#include + +extern "C" int LLVMFuzzerTestOneInput(char* data, size_t size) { + std::string str(data, size); + std::cout << "INPUT" << str << std::endl; + FILE *fp = fopen(str.c_str(), "r"); + if (fp) { + fclose(fp); + } + return 0; +} diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/vuln.dict b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/vuln.dict new file mode 100644 index 0000000000000000000000000000000000000000..bf066ea4829f64c1138ed1021f857e2e4d8bd5fc --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/SystemSan/vuln.dict @@ -0,0 +1,3 @@ +"/tmp/tripwire" +"/fz/" +"f.z" \ No newline at end of file diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f3f20804f4ef9e9dbedd3275286bb4353ef422d --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/build_cache_local.sh @@ -0,0 +1,163 @@ +#!/bin/bash -eu +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +_PROJECT=$1 +_FUZZING_LANGUAGE=$2 +_SANITIZER=${3:-address} + +BASE=$PWD + +# Final image is either ccache or replay script, depending on which worked. +FINAL_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-cached-${_SANITIZER} + +# Always build an image with ccache. +CCACHE_IMAGE_NAME=us-central1-docker.pkg.dev/oss-fuzz/oss-fuzz-gen/${_PROJECT}-ofg-ccache-${_SANITIZER} + +# Step 1: build the base image +cd projects/${_PROJECT} +docker build -t gcr.io/oss-fuzz/${_PROJECT} . + + +# Step 2: create a container where `compile` has run which enables ccaching +# and also generates a replay build script. +cd ${BASE} +mkdir -p ccaches/${_PROJECT} +mkdir -p build/out/${_PROJECT} +B_START=$SECONDS + +docker container rm -f ${_PROJECT}-origin-${_SANITIZER} + +docker run \ + --env=SANITIZER=${_SANITIZER} \ + --env=CCACHE_DIR=/workspace/ccache \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --env=CAPTURE_REPLAY_SCRIPT=1 \ + --name=${_PROJECT}-origin-${_SANITIZER} \ + -v=$PWD/ccaches/${_PROJECT}/ccache:/workspace/ccache \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + gcr.io/oss-fuzz/${_PROJECT} \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && compile" +B_TIME=$(($SECONDS - $B_START)) + +# Step 3: save (commit, locally) the cached container as an image +docker container commit -c "ENV REPLAY_ENABLED=1" -c "ENV CAPTURE_REPLAY_SCRIPT=" ${_PROJECT}-origin-${_SANITIZER} $FINAL_IMAGE_NAME + +# Step 4: save the list of executables created from a vanilla build. This is +# needed for validating if replay and ccaching works. +# notes: run a shell the container with e.g. +# `docker run --entrypoint /bin/bash -it local/ossfuzz/htslib-origin-address` +executables_vanilla="$(find ./build/out/${_PROJECT} -executable -type f | sort)" + + +# Step 5: Build with replay enabled, and validate the executables are the same +# in terms of naming. +# Note that an important step is removing everything in $OUT/ which is done +# in the docker command. +R_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + --name=${_PROJECT}-origin-${_SANITIZER}-replay-recached \ + $FINAL_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +R_TIME=$(($SECONDS - $R_START)) + +# Step 6: Extract the newly build executables +executables_replay="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + +echo "Executables vanilla: " +echo ${executables_vanilla} + +echo "------------------------------------------------------" +echo "Executables replay: " +echo ${executables_replay} + +REPLAY_WORKED= + +# Step 7: match executables from vanilla builds and replay builds. +# If this step is successful, then the process can exit as it's ready. +if [[ "$executables_replay" == "$executables_vanilla" ]] +then + REPLAY_WORKED=1 + + if [ -z "${RUN_ALL+1}" ]; then + echo "${_PROJECT}: Replay worked." + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME};" + exit 0 + fi +else + echo "${_PROJECT}: Replay did not work" + R_TIME="N/A" +fi + +# Step 8: prepare Dockerfile for ccache +cp -rf ccaches/${_PROJECT}/ccache ./projects/${_PROJECT}/ccache-cache + +infra/experimental/chronos/prepare-ccache ${_PROJECT} + +cd projects/${_PROJECT} + +# Step 9: Build an image with CCache's new items (modifications are done on the +# dockerfile) +docker build -t $CCACHE_IMAGE_NAME . + +cd ${BASE} + +# Step 10: Run a `compile` with ccache's image. +# Run the ccache build +A_START=$SECONDS +docker run \ + --rm \ + --env=SANITIZER=${_SANITIZER} \ + --env=FUZZING_LANGUAGE=${_FUZZING_LANGUAGE} \ + --name=${_PROJECT}-origin-${_SANITIZER}-recached \ + -v=$PWD/build/out/${_PROJECT}/:/out/ \ + $CCACHE_IMAGE_NAME \ + /bin/bash -c \ + "export PATH=/ccache/bin:\$PATH && rm -rf /out/* && compile" +A_TIME=$(($SECONDS - $A_START)) + +# Step 11: extract the executables from the ccache build +executables_ccache="$(find ./build/out/${_PROJECT}/ -executable -type f | sort)" + + +# Step 12: validate the ccache builds are successful +if [[ "$executables_ccache" == "$executables_vanilla" ]] +then + echo "${_PROJECT}: Compile times: Vanilla=${B_TIME}; Replay=${R_TIME}; CCache=${A_TIME};" + + if [[ -z "${REPLAY_WORKED}" || ${R_TIME} -gt ${A_TIME} ]]; then + if [ ${R_TIME} -gt ${A_TIME} ]; then + echo "Replay was slower than ccache." + fi + + # Replay didn't work or was slower, so make the default "cached" image use the ccache one. + docker image tag \ + $CCACHE_IMAGE_NAME \ + $FINAL_IMAGE_NAME + fi + + exit 0 +else + echo "${_PROJECT}: Replay and ccaching did not work." + exit 1 +fi + diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e336525bedafd2843b82f45f5cc92721375362c3 --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/cloudbuild_all.yaml @@ -0,0 +1,34 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ +# CloudBuild for generating Chronos-cached images. +steps: +- name: 'gcr.io/cloud-builders/docker' + args: + - build + - -t + - gcloud + - . + dir: infra/experimental/chronos +- name: 'gcloud' + args: + - infra/experimental/chronos/build_all.sh + entrypoint: /bin/bash +timeout: 1800s +serviceAccount: 'projects/oss-fuzz/serviceAccounts/llm-eval@oss-fuzz.iam.gserviceaccount.com' +options: + logging: CLOUD_LOGGING_ONLY +tags: +- chronos-all \ No newline at end of file diff --git a/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/prepare-ccache b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/prepare-ccache new file mode 100644 index 0000000000000000000000000000000000000000..3b0f56719680dc7cbda30a7ab2b18b61365de5bb --- /dev/null +++ b/local-test-commons-compress-full-01-vuln_1/fuzz-tooling/infra/experimental/chronos/prepare-ccache @@ -0,0 +1,22 @@ +#!/usr/bin/bash +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +################################################################################ + +PROJECT=$1 +{ + echo "COPY ccache-cache/ /ccache/cache"; + echo "ENV PATH=\"/ccache/bin:\$PATH\"" +} >> "projects/$PROJECT/Dockerfile"