1# Fuzzing 2 3Fuzz tests use [libFuzzer](http://llvm.org/docs/LibFuzzer.html) to test the SAPI 4`_Prepare` and `_Complete` functions. 5 6Building fuzz tests can be enabled using the `--with-fuzzing=` option. For which 7there are two possible values. 8 9- [libfuzzer](#libfuzzer) 10- [ossfuzz](#oss-fuzz) 11 12## libFuzzer 13 14libFuzzer tests can be built natively or using the docker `fuzzing` target. 15 16### Natively 17 18Build the fuzz tests by setting `--with-fuzzing=libfuzzer` and statically 19linking to the fuzzing TCTI. 20 21```console 22export GEN_FUZZ=1 23 24./bootstrap 25./configure \ 26 CC=clang \ 27 CXX=clang++ \ 28 --enable-debug \ 29 --with-fuzzing=libfuzzer \ 30 --enable-tcti-fuzzing \ 31 --enable-tcti-device=no \ 32 --enable-tcti-mssim=no \ 33 --with-maxloglevel=none \ 34 --disable-shared 35 36make -j $(nproc) check 37``` 38 39Run the fuzz tests by executing any binary ending in `.fuzz` in `test/fuzz/`. 40 41```console 42./test/fuzz/Tss2_Sys_ZGen_2Phase_Prepare.fuzz 43``` 44 45### Docker 46 47Build the fuzz targets and check that they work by building the `fuzzing` docker 48target. 49 50```console 51docker build --target fuzzing -t tpm2-tss:fuzzing . 52``` 53 54Run a fuzz target and mount a directory as a volume into the container where it 55should store its findings should it produce any. 56 57```console 58docker run --rm -ti tpm2-tss:fuzzing \ 59 -v "${PWD}/findings_dir":/artifacts \ 60 ./test/fuzz/Tss2_Sys_PolicyPhysicalPresence_Prepare.fuzz \ 61 -artifact_prefix=/artifacts 62``` 63 64## OSS Fuzz 65 66OSS fuzz integration can be found under the 67[tpm2-tss](https://github.com/google/oss-fuzz/tree/master/projects/tpm2-tss) 68project in OSS Fuzz. 69 70The `Dockerfile` there builds the dependencies. `build.sh` Runs the compilation 71as seen under the `fuzzing` target of the `Dockerfile` in this repo, only 72`--with-fuzzing=ossfuzz`. 73 74## Hacking 75 76Currently only fuzz targets for the System API have been implemented. 77 78### TCTI 79 80The fuzzing TCTI is used as a temporary storage location for the `Data` and 81`Size` arguments of `LLVMFuzzerTestOneInput`. 82 83For `_Complete` calls the TCTI uses `Data` and `Size` as the response buffer and 84response size for `TSS2_TCTI_RECEIVE`. 85 86### SAPI 87 88Fuzz tests are generated via `script/gen_fuzz.py`. 89 90Setting `GEN_FUZZ=1` when running `bootstrap` will run `script/gen_fuzz.py`. 91 92```console 93GEN_FUZZ=1 ./bootstrap 94``` 95 96`script/gen_fuzz.py` reads the SAPI header file and generates a fuzz target for 97each `_Prepare` and `_Complete` call using similar templates. 98 99For `_Prepare` calls the `fuzz_fill` function in the fuzzing TCTI will fill each 100TPM2 structure used can copy from `LLVMFuzzerTestOneInput`'s `Data` into it. 101