├── kAFL-Fuzzer ├── info │ ├── __init__.py │ └── core.py ├── common │ ├── __init__.py │ ├── color.py │ ├── execution_result.py │ ├── qemu_protocol.py │ └── debug.py ├── fuzzer │ ├── __init__.py │ ├── process │ │ └── __init__.py │ ├── technique │ │ ├── __init__.py │ │ ├── redqueen │ │ │ ├── __init__.py │ │ │ ├── workdir.py │ │ │ ├── hash_patch.py │ │ │ └── colorize.py │ │ ├── radamsa.py │ │ ├── havoc.py │ │ ├── trim.py │ │ └── interesting_values.py │ ├── native │ │ └── Makefile │ ├── core.py │ ├── communicator.py │ └── scheduler.py ├── tests │ ├── __init__.py │ └── helper.py ├── seed │ ├── kafl_vulntest │ │ └── seed_file │ ├── fat │ │ ├── fat_a │ │ ├── fat_b │ │ ├── fat_c │ │ ├── fat_d │ │ └── fat_e │ ├── ntfs │ │ └── ntfs64 │ ├── ext4 │ │ └── ext4.img │ └── ntfs_win │ │ └── ntfs_header_64k ├── .gitignore ├── dict │ └── vuln.dict ├── banner.txt ├── test.py ├── redqueen_mut.py ├── kafl_fuzz.py ├── kafl_debug.py └── kafl_info.py ├── targets ├── linux_x86_64 │ ├── .gitignore │ ├── compile.sh │ └── src │ │ ├── fuzzer │ │ ├── hprintf_test.c │ │ ├── kafl_vuln_test.c │ │ └── kafl_vuln_json.c │ │ ├── loader │ │ ├── stage2_loader.c │ │ └── loader.c │ │ └── info │ │ └── info.c ├── uefi_ovmf_64 │ ├── seeds │ │ └── seed │ ├── fake_hda │ │ └── startup.nsh │ ├── TestDecompressPkg │ │ ├── TestDecompress.efi │ │ ├── TestDecompressPkg.dec │ │ ├── TestDecompress.inf │ │ ├── TestDecompress.dsc │ │ └── TestDecompress.c │ ├── TestBMPPkg │ │ ├── TestBMPPkg.dec │ │ ├── TestBMP.inf │ │ ├── TestBMP.c │ │ └── TestBMP.dsc │ ├── kAFLAgentPkg │ │ ├── kAFLAgentPkg.dec │ │ ├── Library │ │ │ └── kAFLAgentLib │ │ │ │ ├── kAFLAgentLib.inf │ │ │ │ └── kAFLAgentLib.c │ │ └── Include │ │ │ └── Library │ │ │ └── kAFLAgentLib.h │ └── edk2_kafl.patch ├── zephyr_x86_32 │ ├── .gitignore │ ├── src │ │ ├── target.h │ │ ├── target_test.c │ │ ├── target_fs.c │ │ ├── target_json.c │ │ └── main.c │ ├── seeds │ │ └── test.json │ ├── CMakeLists.txt │ └── prj.conf ├── linux_x86_64-userspace │ ├── .gitignore │ ├── initrd │ │ ├── template │ │ │ ├── dev │ │ │ │ └── .gitkeep │ │ │ ├── lib64 │ │ │ │ └── .gitkeep │ │ │ ├── proc │ │ │ │ └── .gitkeep │ │ │ ├── sbin │ │ │ │ └── .gitkeep │ │ │ ├── sys │ │ │ │ └── .gitkeep │ │ │ ├── tmp │ │ │ │ └── .gitkeep │ │ │ ├── usr │ │ │ │ └── sbin │ │ │ │ │ └── .gitkeep │ │ │ ├── lib │ │ │ │ ├── i386-linux-gnu │ │ │ │ │ └── .gitkeep │ │ │ │ └── x86_64-linux-gnu │ │ │ │ │ └── .gitkeep │ │ │ ├── etc │ │ │ │ ├── passwd │ │ │ │ └── nsswitch.conf │ │ │ └── init │ │ ├── .gitignore │ │ ├── run_vm.sh │ │ └── pack.sh │ ├── src │ │ └── ld_preload_info.c │ └── compile.sh ├── macOS_x86_64 │ ├── compile.sh │ ├── fuzzer │ │ └── vuln_test.c │ └── loader │ │ └── loader.c ├── compile.sh ├── windows_x86_64-userspace │ ├── compile.sh │ └── src │ │ └── selffuzz_test.c └── windows_x86_64 │ ├── compile.sh │ └── src │ ├── fuzzer │ ├── packet_sender.c │ └── hprintf_test.c │ └── info │ └── info.cpp ├── tests ├── test_cases │ ├── asan │ │ └── linux_x86_64-userspace │ │ │ ├── .gitignore │ │ │ ├── compile.sh │ │ │ └── src │ │ │ ├── loop.c │ │ │ └── vuln.c │ ├── json │ │ ├── macOS_x86-64 │ │ │ ├── compile.sh │ │ │ ├── load.sh │ │ │ └── info.plist │ │ └── linux_x86-64 │ │ │ └── Makefile │ └── simple │ │ ├── macOS_x86-64 │ │ ├── compile.sh │ │ ├── load.sh │ │ ├── info.plist │ │ └── vuln.c │ │ └── linux_x86-64 │ │ ├── Makefile │ │ ├── load.sh │ │ └── kafl_vuln_test.c ├── user_bench │ ├── .gitignore │ ├── seeds │ │ └── uninformed_seed │ ├── README.md │ ├── build.sh │ └── run.sh ├── hard_cases │ ├── inputs │ │ ├── f_kasan │ │ ├── f_kafl │ │ ├── f_sergej │ │ ├── s_mult │ │ ├── l_loop │ │ ├── h_hash │ │ └── j_hash2 │ ├── linux_x86_64-userspace │ │ ├── .gitignore │ │ ├── Makefile │ │ └── main.c │ ├── linux_x86_64 │ │ ├── Makefile │ │ ├── .gitignore │ │ ├── load.sh │ │ └── kafl_vuln_test.c │ ├── README.md │ └── tests.h └── README.md ├── OVMF_CODE-pure-efi.fd ├── images └── Architecture.png ├── drivers ├── CPHarness │ ├── CPHarness │ │ ├── Globals.h │ │ ├── KernelModules.h │ │ ├── Driver.h │ │ ├── CPHarness.vcxproj.filters │ │ ├── cpharness.inf │ │ └── KernelModules.c │ └── CPHarness.sln └── CrashMonitoringDriver │ ├── CrashMonitoringDriver │ ├── hypercall.asm │ ├── CrashMonitoringDriver.vcxproj.filters │ ├── CrashMonitoringDriver.inf │ └── module.h │ └── CrashMonitoringDriver.sln ├── sha256sums.lst ├── copy_files_to_vm.sh ├── compile-kvm.sh ├── tools ├── mcat.py ├── gen_dict.sh ├── cov.plot ├── unique_edges.sh ├── ida_highlight_addrs.py ├── ghidra_cov_analysis.sh └── stats.plot ├── patches └── qemu │ └── v6.0.0 │ ├── 0002-Removed-libexplain-ioctl.h.patch │ └── 0003-Removed-SHUTDOWN-when-info-hypercall-is-called.patch ├── kAFL-LICENSES ├── MIT └── BSD-2-Clause └── LICENSE /kAFL-Fuzzer/info/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/common/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/process/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/seeds/seed: -------------------------------------------------------------------------------- 1 | ;-) 2 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/redqueen/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/dev/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/lib64/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/proc/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/sbin/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/sys/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/tmp/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/usr/sbin/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_cases/asan/linux_x86_64-userspace/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | -------------------------------------------------------------------------------- /tests/user_bench/.gitignore: -------------------------------------------------------------------------------- 1 | packed/* 2 | targets/* 3 | builds 4 | -------------------------------------------------------------------------------- /tests/hard_cases/inputs/f_kasan: -------------------------------------------------------------------------------- 1 | FKASAN______________________________ 2 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/.gitignore: -------------------------------------------------------------------------------- 1 | *.cpio.gz 2 | initrd/ 3 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/lib/i386-linux-gnu/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/lib/x86_64-linux-gnu/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/fake_hda/startup.nsh: -------------------------------------------------------------------------------- 1 | reconnect -r 2 | fs0:harness.efi 3 | -------------------------------------------------------------------------------- /tests/hard_cases/inputs/f_kafl: -------------------------------------------------------------------------------- 1 | FKERNELAFL______________________________ 2 | -------------------------------------------------------------------------------- /tests/hard_cases/inputs/f_sergej: -------------------------------------------------------------------------------- 1 | FSERGEJ______________________________ 2 | -------------------------------------------------------------------------------- /tests/hard_cases/inputs/s_mult: -------------------------------------------------------------------------------- 1 | SMAGICHDR1337___________________________________ -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64-userspace/.gitignore: -------------------------------------------------------------------------------- 1 | test_vuln_32 2 | test_vuln_64 3 | -------------------------------------------------------------------------------- /tests/test_cases/json/macOS_x86-64/compile.sh: -------------------------------------------------------------------------------- 1 | xcodebuild -project vuln.xcodeproj 2 | -------------------------------------------------------------------------------- /tests/test_cases/simple/macOS_x86-64/compile.sh: -------------------------------------------------------------------------------- 1 | xcodebuild -project vuln.xcodeproj 2 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/native/Makefile: -------------------------------------------------------------------------------- 1 | bitmap.so: bitmap.c 2 | $(CC) --shared -fPIC -O3 -o $@ $^ 3 | -------------------------------------------------------------------------------- /tests/hard_cases/inputs/l_loop: -------------------------------------------------------------------------------- 1 | LLOOPCHECK_________________________________________________ 2 | -------------------------------------------------------------------------------- /OVMF_CODE-pure-efi.fd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/OVMF_CODE-pure-efi.fd -------------------------------------------------------------------------------- /images/Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/images/Architecture.png -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/kafl_vulntest/seed_file: -------------------------------------------------------------------------------- 1 | AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | debug.log 3 | error.log 4 | kafl.ini 5 | fuzzer/native/bitmap.so 6 | tags 7 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/fat/fat_a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/fat/fat_a -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/fat/fat_b: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/fat/fat_b -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/fat/fat_c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/fat/fat_c -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/fat/fat_d: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/fat/fat_d -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/fat/fat_e: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/fat/fat_e -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/ntfs/ntfs64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/ntfs/ntfs64 -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/ext4/ext4.img: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/ext4/ext4.img -------------------------------------------------------------------------------- /tests/hard_cases/inputs/h_hash: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/tests/hard_cases/inputs/h_hash -------------------------------------------------------------------------------- /tests/user_bench/seeds/uninformed_seed: -------------------------------------------------------------------------------- 1 | ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!"$%'&/()={[]}\*+~ -------------------------------------------------------------------------------- /tests/hard_cases/inputs/j_hash2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/tests/hard_cases/inputs/j_hash2 -------------------------------------------------------------------------------- /kAFL-Fuzzer/seed/ntfs_win/ntfs_header_64k: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/kAFL-Fuzzer/seed/ntfs_win/ntfs_header_64k -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/etc/passwd: -------------------------------------------------------------------------------- 1 | root:x:0:0:root:/root:/bin/sh 2 | nobody:x:1000:1000:nobody:/nonexistent:/bin/sh 3 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness/Globals.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | 7 | #define DEBUG_LEVEL 0 8 | #define POOL_TAG 'MODs' -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestDecompressPkg/TestDecompress.efi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SafeBreach-Labs/hAFL2/HEAD/targets/uefi_ovmf_64/TestDecompressPkg/TestDecompress.efi -------------------------------------------------------------------------------- /sha256sums.lst: -------------------------------------------------------------------------------- 1 | 87bc1a471ca24b97e7005711066007d443423d19aacda3d442558ae032fa30b9 qemu-6.0.0.tar.xz 2 | 5322e9f0a8d55acc0aa7ec1f57756b126e3cce83399ebf01aa75e5f728cb2c47 linux-5.12.7.tar.xz -------------------------------------------------------------------------------- /tests/test_cases/json/macOS_x86-64/load.sh: -------------------------------------------------------------------------------- 1 | sudo chown -R root:wheel build/Release/vuln.kext 2 | sudo kextutil build/Release/vuln.kext 3 | sudo chown -R `id -un`:`id -gn` build/Release/vuln.kext 4 | -------------------------------------------------------------------------------- /tests/test_cases/simple/macOS_x86-64/load.sh: -------------------------------------------------------------------------------- 1 | sudo chown -R root:wheel build/Release/vuln.kext 2 | sudo kextutil build/Release/vuln.kext 3 | sudo chown -R `id -un`:`id -gn` build/Release/vuln.kext 4 | -------------------------------------------------------------------------------- /tests/test_cases/simple/linux_x86-64/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += kafl_vuln_test.o 2 | 3 | all: 4 | make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules 5 | 6 | clean: 7 | make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += kafl_vuln_test.o 2 | 3 | all: 4 | make -C /lib/modules/$(shell uname -r)/build M=$(CURDIR) modules 5 | 6 | clean: 7 | make -C /lib/modules/$(shell uname -r)/build M=$(CURDIR) clean 8 | -------------------------------------------------------------------------------- /tests/test_cases/json/linux_x86-64/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += kafl_vuln_test_json.o 2 | 3 | all: 4 | make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules 5 | 6 | clean: 7 | make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean 8 | -------------------------------------------------------------------------------- /tests/test_cases/simple/linux_x86-64/load.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | if [[ $UID != 0 ]]; then 3 | echo "Please run this script as root!" 4 | exit 1 5 | else 6 | make 7 | insmod kafl_vuln_test.ko 8 | echo "done" 9 | exit 0 10 | fi 11 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/dict/vuln.dict: -------------------------------------------------------------------------------- 1 | # 2 | # kAFL dictionary for Vuln Driver 3 | # ------------------------------------------- 4 | # 5 | # Created by Sergej Schumilo 6 | # 7 | 8 | tag_result1="SERGEJ" 9 | tag_result2="KASAN" 10 | tag_result3="KERNELAFL" 11 | -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64/.gitignore: -------------------------------------------------------------------------------- 1 | .kafl_vuln_test.ko.cmd 2 | .kafl_vuln_test.mod.o.cmd 3 | .kafl_vuln_test.o.cmd 4 | .tmp_versions/ 5 | Module.symvers 6 | kafl_vuln_test.ko 7 | kafl_vuln_test.mod.c 8 | kafl_vuln_test.mod.o 9 | kafl_vuln_test.o 10 | modules.order 11 | -------------------------------------------------------------------------------- /drivers/CrashMonitoringDriver/CrashMonitoringDriver/hypercall.asm: -------------------------------------------------------------------------------- 1 | PUBLIC kAFL_Hypercall 2 | .code _text 3 | 4 | kAFL_Hypercall PROC PUBLIC 5 | 6 | mov rax, 23h 7 | mov rbx, rcx 8 | mov rcx, rdx 9 | vmcall 10 | 11 | ret 12 | kAFL_Hypercall ENDP 13 | 14 | 15 | END -------------------------------------------------------------------------------- /kAFL-Fuzzer/banner.txt: -------------------------------------------------------------------------------- 1 | __ __ ___ ________ 2 | / /_____ _________ ___ / / / | / ____/ / 3 | / //_/ _ \/ ___/ __ \/ _ \/ / / /| | / /_ / / 4 | / ,< / __/ / / / / / __/ / / ___ |/ __/ / /___ 5 | /_/|_|\___/_/ /_/ /_/\___/_/ /_/ |_/_/ /_____/ 6 | =================================================== (C) 2020 7 | 8 | -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64/load.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | if [[ $UID != 0 ]]; then 3 | echo "Please run this script as root!" 4 | exit 1 5 | else 6 | make 7 | insmod kafl_guest_driver.ko 8 | insmod kafl_vuln_test.ko 9 | MN=$(dmesg | grep 'kAFL MN: ' | grep -Eo ' [0-9]{3}' | tail -n 1) 10 | mknod /dev/kafl c ${MN} 0 11 | echo "done" 12 | exit 0 13 | fi 14 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/src/target.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Intel Corporation 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | #ifndef _KAFL_VULN_TEST_H_ 7 | #define _KAFL_VULN_TEST_H_ 8 | 9 | #include 10 | 11 | void target_init(); 12 | 13 | ssize_t target_entry(const char *buf, size_t len); 14 | 15 | 16 | #endif /* _KAFL_VULN_TEST_H_ */ 17 | -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64-userspace/Makefile: -------------------------------------------------------------------------------- 1 | SRCS := main.c 2 | DEPS := ../tests.h 3 | BINS := test_vuln_32 test_vuln_64 4 | 5 | CFLAGS := -static -std=c99 6 | 7 | all: $(BINS) 8 | 9 | clean: 10 | $(RM) $(BINS) 11 | 12 | test_vuln_32: $(DEPS) $(SRCS) 13 | $(CC) $(CFLAGS) -m32 -o $@ $(SRCS) 14 | 15 | test_vuln_64: $(SRC) 16 | $(CC) $(CFLAGS) -m64 -o $@ $(SRCS) 17 | 18 | 19 | .PHONY: $(BINS) 20 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/tests/helper.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2020 Intel Corporation 2 | # SPDX-License-Identifier: AGPL-3.0-or-later 3 | 4 | """ 5 | Helper functions for kAFL tests 6 | """ 7 | 8 | def ham_weight(x): 9 | _x = bytearray(x) 10 | weight = 0 11 | for byte in _x: 12 | weight += bin(byte).count("1") 13 | return weight 14 | 15 | def ham_distance(a,b): 16 | return ham_weight(bytes(x ^ y for (x, y) in zip(a, b))) 17 | 18 | -------------------------------------------------------------------------------- /copy_files_to_vm.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | if [[ $# -eq 0 ]] 3 | then 4 | echo "Usage: ./copy_files_to_vm.sh SRC_FOLDER_PATH WINDOWS_VM_PATH" 5 | exit 1 6 | fi 7 | 8 | mkdir -p mnt && 9 | sudo modprobe nbd && 10 | sudo qemu-6.0.0/build/qemu-nbd --connect=/dev/nbd0 $2 && 11 | sleep 1 && 12 | sudo mount -o rw /dev/nbd0p3 ./mnt && 13 | cp -r $1/* ./mnt && 14 | umount ./mnt && 15 | sudo qemu-6.0.0/build/qemu-nbd --disconnect /dev/nbd0 && 16 | rm -rf ./mnt -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestBMPPkg/TestBMPPkg.dec: -------------------------------------------------------------------------------- 1 | ## @file TestBMPPkg.dec 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | DEC_SPECIFICATION = 0x00010005 10 | PACKAGE_NAME = TestBMPPkg 11 | PACKAGE_GUID = B66DACBB-080C-4DBE-90DD-59F0D9EF87A4 12 | PACKAGE_VERSION = 0.01 13 | 14 | [Includes] 15 | #Include 16 | -------------------------------------------------------------------------------- /tests/README.md: -------------------------------------------------------------------------------- 1 | Sample code containing known vulnerabilties. 2 | 3 | Unless declared otherwise inside the individual files, all code and scripts 4 | are distributed under MIT License (SPDX-License-Identifier: MIT). 5 | 6 | Contents: 7 | 8 | - test_cases/ 9 | Simple test cases for validating the overall harness/setup. 10 | 11 | - hard_cases/ 12 | Difficult fuzzing test cases, not all solved by kAFL 13 | 14 | - user_bench/ 15 | Streamlined fuzzing of typical/small userspace targets for benchmarking 16 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/seeds/test.json: -------------------------------------------------------------------------------- 1 | { 2 | "some_string" : "zephyr 123 uABCD456", 3 | "some_int": 42, 4 | "some_bool":true, 5 | "some_nested_struct": { 6 | "nested_int":-1234, 7 | "nested_bool":false, 8 | "nested_string":"this should be escaped:" 9 | }, 10 | "some_array":[11,22, 33,45,299], 11 | "another_b!@l":true, 12 | "if":false, 13 | "another-array":[2,3,5,7], 14 | "4nother_ne$+":{ 15 | "nested_int":1234, 16 | "nested_bool":true, 17 | "nested_string":"no escape necessary" 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /compile-kvm.sh: -------------------------------------------------------------------------------- 1 | if [ "$#" -ne 1 ]; then 2 | echo "Usage: ./compile.sh [LINUX_KERNEL_VERSION]" 3 | exit 1 4 | fi 5 | 6 | version=$1 7 | jobs=$(nproc) 8 | echo [+] Compiling... 9 | make -j $jobs -C . M=arch/x86/ 10 | cp arch/x86/kvm/kvm-intel.ko /lib/modules/$version-kAFL+/kernel/arch/x86/kvm/kvm-intel.ko 11 | cp arch/x86/kvm/kvm.ko /lib/modules/$version-kAFL+/kernel/arch/x86/kvm/kvm.ko 12 | echo [+] Removing mods... 13 | rmmod kvm-intel && rmmod kvm 14 | echo [+] Inserting mods... 15 | modprobe kvm && modprobe kvm-intel 16 | -------------------------------------------------------------------------------- /targets/macOS_x86_64/compile.sh: -------------------------------------------------------------------------------- 1 | if [[ "$OSTYPE" == "darwin"* ]]; then 2 | printf "\tCompiling info executable...\n" 3 | gcc -o info/info info/info.c 4 | printf "\tCompiling loader...\n" 5 | gcc -o loader/loader loader/loader.c # -D DEBUG_MODE 6 | printf "\tCompiling loader (autoreload)...\n" 7 | gcc -o loader/loader_autoreload loader/loader.c -D AUTORELOAD 8 | printf "\tCompiling vuln_driver fuzzer...\n" 9 | gcc -o fuzzer/vuln_test fuzzer/vuln_test.c # -D DEBUG_MODE 10 | else 11 | printf "\tError: Need to run MacOS to compile these components! Skipping..!\n" 12 | fi 13 | -------------------------------------------------------------------------------- /tests/hard_cases/README.md: -------------------------------------------------------------------------------- 1 | # Hard Fuzzing Roadblocks 2 | 3 | - feedback tests KERNELAFL/KASAN/SERGEJ should be solved within few minutes 4 | 5 | - LLOOPBACK is not solved in a targeted fashion but eventually (~10h) 6 | - it may be worth tuning the bitmap bucketing mechanism to address this 7 | 8 | - LLOOPBACK also has an implicit magic byte check at the very start, solved easily 9 | 10 | - HASH/checksum cases are not currently solved and deemed not worth solving. 11 | Redqueen v0.1 has some logic to find these, may be able to re-activate 12 | in Grimoire frontend (fix_hashes) 13 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | 3 | cmake_minimum_required(VERSION 3.13.1) 4 | 5 | include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE) 6 | 7 | project(kafl_agent) 8 | target_sources(app PRIVATE src/main.c) 9 | set_property(TARGET app PROPERTY C_STANDARD 99) 10 | 11 | # Select a fuzzing target at a time, e.g. ``cmake ../ -D KAFL_TEST=y'' 12 | target_sources_ifdef(KAFL_TEST app PRIVATE src/target_test.c) 13 | target_sources_ifdef(KAFL_FS app PRIVATE src/target_fs.c) 14 | target_sources_ifdef(KAFL_JSON app PRIVATE src/target_json.c) 15 | 16 | -------------------------------------------------------------------------------- /tools/mcat.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 4 | # Copyright 2020 Intel Corporation 5 | # 6 | # SPDX-License-Identifier: AGPL-3.0-or-later 7 | 8 | """ 9 | Pretty-Pring msgpack files produced by kAFL 10 | """ 11 | 12 | import os 13 | import sys 14 | 15 | import msgpack 16 | from pprint import pprint 17 | 18 | sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/../kAFL-Fuzzer/") 19 | from common.util import read_binary_file 20 | 21 | for arg in sys.argv[1:]: 22 | pprint(msgpack.unpackb(read_binary_file(arg), raw=False, strict_map_key=False)) 23 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/etc/nsswitch.conf: -------------------------------------------------------------------------------- 1 | # /etc/nsswitch.conf 2 | # 3 | # Example configuration of GNU Name Service Switch functionality. 4 | # If you have the `glibc-doc-reference' and `info' packages installed, try: 5 | # `info libc "Name Service Switch"' for information about this file. 6 | 7 | passwd: compat 8 | group: compat 9 | shadow: compat 10 | 11 | hosts: files mdns4_minimal [NOTFOUND=return] dns 12 | networks: files 13 | 14 | protocols: db files 15 | services: db files 16 | ethers: db files 17 | rpc: db files 18 | 19 | netgroup: nis 20 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness/KernelModules.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #pragma comment(lib, "aux_klib.lib") 5 | 6 | typedef struct _KernelModules 7 | { 8 | AUX_MODULE_EXTENDED_INFO* modules; 9 | ULONG numberOfModules; 10 | 11 | } KERNEL_MODULES, * PKERNEL_MODULES; 12 | 13 | NTSTATUS InitKernelModules(PKERNEL_MODULES pKernelModules); 14 | VOID DeinitKernelModules(PKERNEL_MODULES pKernelModules); 15 | ULONG GetKernelModulesCount(PKERNEL_MODULES pKernelModules); 16 | PCSZ GetKernelModuleNameByIndex(PKERNEL_MODULES pKernelModules, ULONG i); 17 | PVOID GetKernelModuleBaseAddressByIndex(PKERNEL_MODULES pKernelModules, ULONG i); 18 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/run_vm.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This file is part of Redqueen. 4 | # 5 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 6 | # SPDX-License-Identifier: MIT 7 | # 8 | 9 | # You can test the initramfs in Qemu like as shown below. 10 | # To run with the modified kAFL/Qemu, disable reload+snapshots. 11 | ./qemu-4.0.0/x86_64-softmmu/qemu-system-x86_64 \ 12 | -kernel /boot/vmlinuz-5.4.34-kAFL+ \ 13 | -initrd targets/linux_x86_64-initramfs/init_debug_shell.cpio.gz \ 14 | -serial mon:stdio -enable-kvm -m 500 -append "root=/dev/sda console=ttyS0" \ 15 | -nographic -device kafl,reload_mode=False,disable_snapshot=True 16 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright (C) 2019-2020 Intel Corporation 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | This file offers an alternative/standalone entry point to tests/, e.g. 8 | to launch some benchmarks contained there. 9 | 10 | To execute all regular tests, run pytest inside kAFL-Fuzzer/ directory. 11 | """ 12 | 13 | from tests.test_random import * 14 | from tests.test_deterministic import * 15 | from tests.test_havoc_handler import * 16 | 17 | if __name__ == '__main__': 18 | 19 | print("\nRunning tests...") 20 | 21 | rand_main() 22 | deter_main() 23 | havoc_main() 24 | 25 | print("\nDone!") 26 | -------------------------------------------------------------------------------- /patches/qemu/v6.0.0/0002-Removed-libexplain-ioctl.h.patch: -------------------------------------------------------------------------------- 1 | From 1e311b11b41cfb20faded05e0da14bab560265aa Mon Sep 17 00:00:00 2001 2 | From: Peleg Hadar 3 | Date: Sun, 25 Jul 2021 18:16:54 +0200 4 | Subject: [PATCH 2/2] Removed libexplain/ioctl.h 5 | 6 | --- 7 | pt.c | 1 - 8 | 1 file changed, 1 deletion(-) 9 | 10 | diff --git a/pt.c b/pt.c 11 | index f7b1340b2..07e9bfa99 100644 12 | --- a/pt.c 13 | +++ b/pt.c 14 | @@ -25,7 +25,6 @@ 15 | #include "pt/memory_access.h" 16 | #include "pt/interface.h" 17 | #include "pt/debug.h" 18 | -#include 19 | 20 | #ifdef CONFIG_REDQUEEN 21 | #include "pt/redqueen.h" 22 | -- 23 | 2.25.1 24 | 25 | -------------------------------------------------------------------------------- /tools/gen_dict.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2020 Intel Corporation 4 | # SPDX-License-Identifier: MIT 5 | # 6 | 7 | # Helper script to generate a kAFL dictionary from `strings` 8 | # 9 | # Usage: dict.sh 10 | # Output: kAFL dictionary file written to $CWD/dict/dict_$TARGET.txt 11 | 12 | fatal_usage() { 13 | echo 14 | echo "$1" 15 | echo "Usage: $0 " 16 | exit 17 | } 18 | 19 | TARGET="$1" 20 | 21 | test -f "$TARGET" || fatal_usage "Error: Missing target executable." 22 | test -d ./dict/ || fatal_usage "Error: $PWD/dict/ is missing or not a directory." 23 | 24 | strings -n3 -d "$TARGET" | grep -v "\%s" | sort | uniq > "dict/dict_$(basename "$TARGET").txt" 25 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/prj.conf: -------------------------------------------------------------------------------- 1 | #CONFIG_FLASH_BASE_ADDRESS=0x100000 2 | #CONFIG_SRAM_BASE_ADDRESS=0x500000 3 | # 4 | CONFIG_SRAM_SIZE=8192 5 | #CONFIG_FLASH_SIZE=2048 6 | 7 | # need to accomodate PAYLOAD_SIZE (~128kb) 8 | CONFIG_MAIN_STACK_SIZE=262144 9 | 10 | # enable available protections to help us catch bugs 11 | CONFIG_ASSERT=y 12 | CONFIG_HW_STACK_PROTECTION=y 13 | CONFIG_STACK_CANARIES=y 14 | 15 | # disable spectre/meltdown mitigations for kAFL build 16 | CONFIG_X86_KPTI=n 17 | 18 | # build with address sanitizer - only available for CONFIG_ARCH_POSIX 19 | #CONFIG_ASAN=y 20 | 21 | # UMODE test? 22 | CONFIG_USERSPACE=n 23 | 24 | # JSON test 25 | CONFIG_JSON_LIBRARY=y 26 | 27 | # FS test 28 | CONFIG_DISK_ACCESS=y 29 | CONFIG_FILE_SYSTEM=y 30 | CONFIG_FAT_FILESYSTEM_ELM=y 31 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/kAFLAgentPkg/kAFLAgentPkg.dec: -------------------------------------------------------------------------------- 1 | ## @file kAFLAgentPkg.dec 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | DEC_SPECIFICATION = 0x00010005 10 | PACKAGE_NAME = kAFLAgentPkg 11 | #PACKAGE_UNI_FILE = AFLPkg.uni 12 | PACKAGE_GUID = a636c575-4a18-45c6-b0a3-31bb0ae5e5ee 13 | PACKAGE_VERSION = 0.01 14 | 15 | [Includes] 16 | Include 17 | 18 | [LibraryClasses] 19 | AFLLib|Include/Library/kAFLAgentLib.h 20 | #CollectorLib|Include/Library/CollectorLib.h 21 | 22 | 23 | [Protocols] 24 | # Include/Protocol/ChipsecProt.h 25 | #gChipsecProtocolGuid = { 0x64a58468, 0xfb81, 0x4e17, { 0xa0, 0xa4, 0xff, 0x94, 0x3b, 0x1d, 0x43, 0x36 } } 26 | -------------------------------------------------------------------------------- /tests/user_bench/README.md: -------------------------------------------------------------------------------- 1 | # kAFL Userspace Fuzzing 2 | 3 | This directly contains sample scripts for launching Linux userspace binaries in kAFL. 4 | 5 | The selected target binary is packaged into an initrd and launched via `qemu -kernel -initrd`. 6 | An embedded `LD_PRELOAD` forkserver is used to map kAFL hypercalls to AFL-style I/O inside the guest. 7 | 8 | The scripts are sufficiently clever to launch typical AFL benchmark binaries 9 | such as those in the binutils package. The required shared libraries are 10 | automatically copied from the host system into the initrd. 11 | 12 | Example use: 13 | 14 | ``` 15 | # fetch, build, and pack it up for VM fuzzing 16 | $ ./tests/user_bench/build.sh help 17 | $ ./tests/user_bench/build.sh bison 18 | $ ./tests/user_bench/run.sh pack bison 19 | 20 | # actually fuzz it 21 | $ ./tests/user_bench/run.sh run bison -v 22 | ``` 23 | -------------------------------------------------------------------------------- /patches/qemu/v6.0.0/0003-Removed-SHUTDOWN-when-info-hypercall-is-called.patch: -------------------------------------------------------------------------------- 1 | From e8747cf1c841a49e9c5fdae4bceaa89061dc2077 Mon Sep 17 00:00:00 2001 2 | From: Peleg Hadar 3 | Date: Wed, 28 Jul 2021 16:42:39 +0200 4 | Subject: [PATCH] Removed SHUTDOWN when info hypercall is called 5 | 6 | --- 7 | pt/hypercall.c | 1 - 8 | 1 file changed, 1 deletion(-) 9 | 10 | diff --git a/pt/hypercall.c b/pt/hypercall.c 11 | index b6e0ece45..af14b69a7 100644 12 | --- a/pt/hypercall.c 13 | +++ b/pt/hypercall.c 14 | @@ -429,7 +429,6 @@ void handle_hypercall_kafl_info(struct kvm_run *run, CPUState *cpu){ 15 | if(hypercall_enabled){ 16 | hypercall_snd_char(KAFL_PROTO_INFO); 17 | } 18 | - qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_SIGNAL); 19 | } 20 | 21 | void handle_hypercall_kafl_crash_dump_size(struct kvm_run *run, CPUState *cpu){ 22 | -- 23 | 2.25.1 24 | 25 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestDecompressPkg/TestDecompressPkg.dec: -------------------------------------------------------------------------------- 1 | ## @file TestDecompressPkg.dec 2 | # 3 | # Copyright (c) 2020, Intel Corporation. All rights reserved. 4 | # 5 | # This program and the accompanying materials are licensed and made available under 6 | # the terms and conditions of the BSD License that accompanies this distribution. 7 | # The full text of the license may be found at 8 | # http://opensource.org/licenses/bsd-license.php. 9 | # 10 | # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. 12 | # 13 | ## 14 | 15 | [Defines] 16 | DEC_SPECIFICATION = 0x00010005 17 | PACKAGE_NAME = TestDecompressPkg 18 | PACKAGE_GUID = B66DACBB-080C-4DBE-90DD-59F0D9EF87A4 19 | PACKAGE_VERSION = 0.01 20 | 21 | [Includes] 22 | #Include 23 | -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64-userspace/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 3 | * 4 | * SPDX-License-Identifier: MIT 5 | */ 6 | 7 | #define _GNU_SOURCE 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | 16 | void test_panic(char* descr){ 17 | char* str = NULL; 18 | printf("Panic at: %s", descr); 19 | assert(0); 20 | } 21 | 22 | void* test_malloc(size_t size) { 23 | return malloc(size); 24 | } 25 | 26 | 27 | void test_free(void* data){ 28 | free(data); 29 | } 30 | 31 | #include "../tests.h" 32 | 33 | int main(int argc, char *argv[]) 34 | { 35 | char buffer[256]; 36 | int len = read(STDIN_FILENO, buffer, 256); 37 | if( len != -1){ 38 | test(buffer,len); 39 | } else { 40 | printf("failed to read input\n"); 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /tests/test_cases/asan/linux_x86_64-userspace/compile.sh: -------------------------------------------------------------------------------- 1 | # This file is part of Redqueen. 2 | # 3 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 4 | # 5 | # SPDX-License-Identifier: MIT 6 | # 7 | 8 | mkdir bin/ 2> /dev/null 9 | 10 | gcc src/vuln.c -m64 -D STDIN_INPUT -g -o bin/vuln_stdin_64 11 | gcc src/vuln.c -m32 -D STDIN_INPUT -g -o bin/vuln_stdin_32 12 | 13 | gcc src/vuln.c -m32 -D STDIN_INPUT -g -fsanitize=address -o bin/vuln_stdin_32_asan 14 | gcc src/vuln.c -m64 -D STDIN_INPUT -g -fsanitize=address -o bin/vuln_stdin_64_asan 15 | 16 | gcc src/vuln.c -m64 -D FILE_INPUT -g -o bin/vuln_file_64 17 | gcc src/vuln.c -m32 -D FILE_INPUT -g -o bin/vuln_file_32 18 | 19 | gcc src/loop.c -m64 -D STDIN_INPUT -g -o bin/loop_stdin_64 20 | gcc src/loop.c -m32 -D STDIN_INPUT -g -o bin/loop_stdin_32 21 | gcc src/loop.c -m64 -D FILE_INPUT -g -o bin/loop_file_64 22 | gcc src/loop.c -m32 -D FILE_INPUT -g -o bin/loop_file_32 23 | -------------------------------------------------------------------------------- /tools/cov.plot: -------------------------------------------------------------------------------- 1 | # 2 | # Plot coverage over time based on full trace outputs. 3 | # 4 | # Usage: 5 | # $ gnuplot -c $tools/cov.plot $workdir/traces/coverage.csv 6 | # 7 | 8 | indata1=ARG1 9 | 10 | #set terminal png size 900,800 enhanced 11 | #set output cov.png 12 | 13 | set terminal wxt size 900,800 enhanced persist 14 | 15 | 16 | set xlabel "Time" 17 | set ylabel "#BBs" 18 | set autoscale 19 | 20 | set grid xtics linetype 0 linecolor rgb '#e0e0e0' 21 | set grid ytics linetype 0 linecolor rgb '#e0e0e0' 22 | set border linecolor rgb '#50c0f0' 23 | set tics textcolor rgb '#000000' 24 | #set key outside 25 | 26 | #set xdata time 27 | #set timefmt "%S" 28 | #set xtics time format "%H:%M" 29 | set xtics time format "Day %d\n%H:%M" 30 | 31 | set datafile separator ';' 32 | 33 | plot indata1 using 1:2 with linespoints lw 2 title 'BBs', \ 34 | indata1 using 1:3 with linespoints lw 2 title 'edges' 35 | 36 | replot 37 | pause -1 38 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/redqueen_mut.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 4 | # Copyright (C) 2019-2020 Intel Corporation 5 | # 6 | # SPDX-License-Identifier: AGPL-3.0-or-later 7 | 8 | """ 9 | Validate Redqueen Input-to-State mutations 10 | """ 11 | 12 | import array 13 | import sys 14 | 15 | from fuzzer.technique.redqueen import parser 16 | from fuzzer.technique.redqueen.mod import RedqueenInfoGatherer 17 | 18 | info = RedqueenInfoGatherer() 19 | 20 | info.collected_infos_path = sys.argv[1] 21 | info.num_alternative_inputs = 2 22 | 23 | info.get_proposals() 24 | print("got %d mutations on %s" % (info.get_num_mutations(), sys.argv[1])) 25 | 26 | orig_input = open(sys.argv[1] + "/input_2.bin", "rb").read() 27 | print("Mutating : %s" % repr(orig_input)) 28 | 29 | 30 | def fake_execute(str, a, b): 31 | print("executing %s" % repr(str)) 32 | 33 | 34 | info.verbose = True 35 | default_info = {} 36 | info.run_mutate_redqueen(array.array("B", orig_input), fake_execute, default_info) 37 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/info/core.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | import os 7 | import time 8 | 9 | from common.debug import log_info, enable_logging 10 | from common.qemu import qemu 11 | from common.self_check import post_self_check 12 | 13 | def start(config): 14 | 15 | if not post_self_check(config): 16 | return -1 17 | 18 | if config.argument_values['v']: 19 | enable_logging(config.argument_values["work_dir"]) 20 | 21 | log_info("Dumping target addresses...") 22 | 23 | # TODO: use proper temp file or store to $work_dir 24 | if os.path.exists("/tmp/kAFL_info.txt"): 25 | os.remove("/tmp/kAFL_info.txt") 26 | 27 | q = qemu(0, config) 28 | q.start() 29 | q.shutdown() 30 | 31 | try: 32 | with open("/tmp/kAFL_info.txt", 'r') as f: 33 | print(f.read()) 34 | os.remove("/tmp/kAFL_info.txt") 35 | except: 36 | pass 37 | 38 | return 0 39 | -------------------------------------------------------------------------------- /targets/compile.sh: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of Redqueen. 3 | # 4 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 5 | # 6 | # SPDX-License-Identifier: MIT 7 | # 8 | 9 | # Build dependencies for Linux kernel/user targets 10 | sudo dpkg --add-architecture i386 11 | sudo apt-get update 12 | sudo apt-get install -y gcc gcc-multilib g++-multilib libc6-dev:i386 13 | sudo apt-get install -y busybox-static 14 | 15 | echo "Build samples for Linux kernel targets..." 16 | echo "-----------------------------------------" 17 | cd linux_x86_64 18 | bash compile.sh 19 | cd ../ 20 | 21 | echo "Build samples for Linux userspace targets..." 22 | echo "--------------------------------------------" 23 | cd linux_x86_64-userspace 24 | bash compile.sh 25 | cd ../ 26 | 27 | echo "Build samples MacOS kernel targets..." 28 | echo "-------------------------------------" 29 | cd macOS_x86_64 30 | bash compile.sh 31 | cd ../ 32 | 33 | echo "Build samples for Windows kernel targets..." 34 | echo "-------------------------------------------" 35 | cd windows_x86_64 36 | bash compile.sh 37 | cd ../ 38 | 39 | echo -e "\n[!] done" 40 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/redqueen/workdir.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | Redqueen workdir/Qemu interface 8 | """ 9 | 10 | import os 11 | import shutil 12 | 13 | 14 | class RedqueenWorkdir: 15 | def __init__(self, qemu_id, config): 16 | self.base_path = config.argument_values['work_dir'] + "/redqueen_workdir_" + str(qemu_id) 17 | 18 | def init_dir(self): 19 | if os.path.exists(self.base_path): 20 | shutil.rmtree(self.base_path) 21 | os.makedirs(self.base_path) 22 | 23 | def redqueen(self): 24 | return self.base_path + "/redqueen_results.txt" 25 | 26 | def patches(self): 27 | return self.base_path + "/redqueen_patches.txt" 28 | 29 | def whitelist(self): 30 | return self.base_path + "/breakpoint_white.txt" 31 | 32 | def blacklist(self): 33 | return self.base_path + "/breakpoint_black.txt" 34 | 35 | def code_dump(self): 36 | return self.base_path + "/target_code_dump.img" 37 | -------------------------------------------------------------------------------- /tests/test_cases/json/macOS_x86-64/info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | English 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | schumilo.${PRODUCT_NAME:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | KEXT 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | OSBundleLibraries 24 | 25 | com.apple.kpi.bsd 26 | 10.0 27 | com.apple.kpi.libkern 28 | 10.0 29 | com.apple.kpi.unsupported 30 | 10.0 31 | 32 | 33 | -------------------------------------------------------------------------------- /tests/test_cases/simple/macOS_x86-64/info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | English 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | schumilo.${PRODUCT_NAME:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | KEXT 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | OSBundleLibraries 24 | 25 | com.apple.kpi.bsd 26 | 10.0 27 | com.apple.kpi.libkern 28 | 10.0 29 | com.apple.kpi.unsupported 30 | 10.0 31 | 32 | 33 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/kAFLAgentPkg/Library/kAFLAgentLib/kAFLAgentLib.inf: -------------------------------------------------------------------------------- 1 | ## @file kAFLAgentLib.inf 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | INF_VERSION = 0x00010005 10 | BASE_NAME = kAFLAgentLib 11 | MODULE_UNI_FILE = kAFLAgentLib.uni 12 | FILE_GUID = A6020274-067D-40B2-B007-BE19B6EEF420 13 | VERSION_STRING = 1.0 14 | MODULE_TYPE = BASE 15 | LIBRARY_CLASS = kAFLAgentLib 16 | # 17 | # The following information is for reference only and not required by the build tools. 18 | # 19 | # VALID_ARCHITECTURES = IA32 X64 20 | # 21 | 22 | [Sources] 23 | kAFLAgentLib.c 24 | 25 | [Packages] 26 | MdePkg/MdePkg.dec 27 | MdeModulePkg/MdeModulePkg.dec 28 | kAFLAgentPkg/kAFLAgentPkg.dec 29 | 30 | 31 | [LibraryClasses] 32 | BaseLib 33 | PrintLib 34 | BaseMemoryLib 35 | MemoryAllocationLib 36 | UefiLib 37 | PcdLib 38 | DebugLib 39 | UefiBootServicesTableLib 40 | DevicePathLib 41 | UefiRuntimeServicesTableLib 42 | 43 | -------------------------------------------------------------------------------- /kAFL-LICENSES/MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a 6 | copy of this software and associated documentation files (the "Software"), 7 | to deal in the Software without restriction, including without limitation 8 | the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | and/or sell copies of the Software, and to permit persons to whom the 10 | Software is furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 21 | DEALINGS IN THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/kafl_fuzz.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 4 | # Copyright (C) 2019-2020 Intel Corporation 5 | # 6 | # SPDX-License-Identifier: AGPL-3.0-or-later 7 | 8 | """ 9 | Launcher for Fuzzing with kAFL. Check fuzzer/core.py for more. 10 | """ 11 | 12 | import os 13 | import sys 14 | 15 | import common.color 16 | from common.self_check import self_check 17 | from common.config import FuzzerConfiguration 18 | 19 | KAFL_ROOT = os.path.dirname(os.path.realpath(__file__)) + "/" 20 | KAFL_BANNER = KAFL_ROOT + "banner.txt" 21 | KAFL_CONFIG = KAFL_ROOT + "kafl.ini" 22 | 23 | def main(): 24 | 25 | with open(KAFL_BANNER) as f: 26 | for line in f: 27 | print(line.replace("\n", "")) 28 | 29 | print("<< " + common.color.BOLD + common.color.OKGREEN + 30 | sys.argv[0] + ": Kernel Fuzzer " + common.color.ENDC + ">>\n") 31 | 32 | if not self_check(KAFL_ROOT): 33 | return 1 34 | 35 | import fuzzer.core 36 | cfg = FuzzerConfiguration(KAFL_CONFIG) 37 | return fuzzer.core.start(cfg) 38 | 39 | 40 | if __name__ == "__main__": 41 | main() 42 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/common/color.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | HEADER = '\033[95m' 7 | OKBLUE = '\033[94m' 8 | OKGREEN = '\033[92m' 9 | WARNING = '\033[0;33m' 10 | FAIL = '\033[91m' 11 | ENDC = '\033[0m' 12 | CLRSCR = '\x1b[1;1H' 13 | REALCLRSCR = '\x1b[2J' 14 | BOLD = '\033[1m' 15 | FLUSH_LINE = '\r\x1b[K' 16 | 17 | 18 | def MOVE_CURSOR_UP(num): 19 | return "\033[" + str(num) + "A" 20 | 21 | 22 | def MOVE_CURSOR_DOWN(num): 23 | return "\033[" + str(num) + "B" 24 | 25 | 26 | def MOVE_CURSOR_LEFT(num): 27 | return "\033[" + str(num) + "C" 28 | 29 | 30 | def MOVE_CURSOR_RIGHT(num): 31 | return "\033[" + str(num) + "D" 32 | 33 | 34 | HLINE = chr(0x2500) 35 | VLINE = chr(0x2502) 36 | VLLINE = chr(0x2524) 37 | VRLINE = chr(0x251c) 38 | LBEDGE = chr(0x2514) 39 | RBEDGE = chr(0x2518) 40 | HULINE = chr(0x2534) 41 | HDLINE = chr(0x252c) 42 | LTEDGE = chr(0x250c) 43 | RTEDGE = chr(0x2510) 44 | 45 | INFO_PREFIX = "[INFO] " 46 | ERROR_PREFIX = "[ERROR] " 47 | WARNING_PREFIX = "[WARNING] " 48 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/kafl_debug.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 4 | # Copyright (C) 2019-2020 Intel Corporation 5 | # 6 | # SPDX-License-Identifier: AGPL-3.0-or-later 7 | 8 | """ 9 | Execute a given kAFL target with individual test inputs for purpose of debug/inspection. 10 | """ 11 | 12 | import os 13 | import sys 14 | 15 | import common.color 16 | from common.self_check import self_check 17 | from common.config import DebugConfiguration 18 | 19 | KAFL_ROOT = os.path.dirname(os.path.realpath(__file__)) + "/" 20 | KAFL_BANNER = KAFL_ROOT + "banner.txt" 21 | KAFL_CONFIG = KAFL_ROOT + "kafl.ini" 22 | 23 | def main(): 24 | 25 | with open(KAFL_BANNER) as f: 26 | for line in f: 27 | print(line.replace("\n", "")) 28 | 29 | print("<< " + common.color.BOLD + common.color.OKGREEN + 30 | sys.argv[0] + ": kAFL Debugger " + common.color.ENDC + ">>\n") 31 | 32 | if not self_check(KAFL_ROOT): 33 | return 1 34 | 35 | import debug.core 36 | cfg = DebugConfiguration(KAFL_CONFIG) 37 | return debug.core.start(cfg) 38 | 39 | 40 | if __name__ == "__main__": 41 | main() 42 | -------------------------------------------------------------------------------- /tests/test_cases/asan/linux_x86_64-userspace/src/loop.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of Redqueen. 3 | * 4 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 5 | * 6 | * SPDX-License-Identifier: MIT 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | int main(int argc, char** argv){ 17 | 18 | #ifdef STDIN_INPUT 19 | char input[256]; 20 | memset(input, 0x00, 256); 21 | size_t len = read(STDIN_FILENO, input, 256); 22 | #elif FILE_INPUT 23 | if(argc != 2){ 24 | return 0; 25 | } 26 | 27 | int fd = open(argv[1], O_RDONLY); 28 | 29 | char input[256]; 30 | memset(input, 0x00, 256); 31 | size_t len = read(fd, input, 256); 32 | #endif 33 | 34 | char* array = malloc(128); 35 | 36 | if(len >= 256){ 37 | return 0; 38 | } 39 | 40 | char* cmpval = "LOOPCHECK"; 41 | if(len >= strlen(cmpval)){ 42 | int counter = 0; 43 | for(int i = 0; i /dev/null 4 | 5 | if x86_64-w64-mingw32-gcc -v 2> /dev/null && x86_64-w64-mingw32-g++ -v 2> /dev/null; then 6 | printf "\tCompiling usermode fuzzer test...\n" 7 | x86_64-w64-mingw32-gcc src/selffuzz_test.c -I ../ -o bin/selffuzz_test.exe -mwindows -Wall 8 | printf "\tCompiling gdiplus fuzzer ...\n" 9 | x86_64-w64-mingw32-gcc src/gdiplus.cpp -I ../ -o bin/gdiplus.exe -lpsapi -lgdiplus -Wall -fno-exceptions -fno-rtti 10 | printf "\tCompiling gdiplus font fuzzer ...\n" 11 | x86_64-w64-mingw32-g++ src/gdiplus_loadfont.cpp -I ../ -o bin/gdiplus_loadfont.exe -lpsapi -lgdiplus -fno-exceptions -fno-rtti -Wall -static-libstdc++ -static-libgcc -static 12 | 13 | else 14 | printf "\tError: x86_64-w64-mingw32-gcc/g++ not found. Please install x86_64-w64-mingw32-gcc/g++ (sudo apt install gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64)!\n" 15 | fi 16 | else 17 | printf "\tError: Need to run Linux to compile these components! Skipping..!\n" 18 | fi 19 | 20 | 21 | # sudo apt install gcc-mingw-w64-x86-64 22 | # sudo apt install gcc-mingw-w64-x86-64 23 | # linux_x86-64-2$ x86_64-w64-mingw32-gcc -v 24 | -------------------------------------------------------------------------------- /tools/unique_edges.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Copyright 2020 Intel Corporation 4 | # SPDX-License-Identifier: MIT 5 | # 6 | 7 | # Given a workdir with per-payload trace files in traces/, grep and sort your 8 | # way through all the traces to obtain list of unique discovered edges. 9 | 10 | WORKDIR="$1"; shift 11 | 12 | function usage() { 13 | echo -e "Usage:\n\t$1 \n" 14 | exit 15 | } 16 | 17 | function fatal_exit() { 18 | echo "$1" 19 | exit 20 | } 21 | 22 | test -d "$WORKDIR" || usage "$0" 23 | test -d "$WORKDIR/traces/" || fatal_exit "Could not find $WORKDIR/traces/" 24 | 25 | which lz4cat || fatal_exit "Could not find lz4cat tool." 26 | which mktemp || fatal_exit "Could not find mktemp tool." 27 | 28 | TMPFILE=$(mktemp) 29 | OUTFILE="$WORKDIR/traces/edges_uniq.lst" 30 | 31 | pushd "$WORKDIR/traces/" 32 | 33 | # can be LOTS of traces, so do sort/uniq on individual files first.. 34 | for trace in ./payload_*.lz4; do 35 | echo "lz4cat $trace |grep edge|sort -u >> $TMPFILE" 36 | lz4cat $trace|grep edge|sort -u >> $TMPFILE 37 | done 38 | 39 | echo -n "Sorting final output..." 40 | sort -u $TMPFILE |sed -e 's/.*\[//' -e 's/\].*//' > $OUTFILE 41 | rm $TMPFILE 42 | echo -e "done!\nGot $(wc -l $OUTFILE) edges in $OUTFILE" 43 | 44 | popd 45 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestBMPPkg/TestBMP.inf: -------------------------------------------------------------------------------- 1 | ## @file TestBMP.inf 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | INF_VERSION = 0x00010005 10 | BASE_NAME = TestBMP 11 | FILE_GUID = E6020274-067D-40B2-B007-BE19B6EEF825 12 | MODULE_TYPE = UEFI_APPLICATION 13 | VERSION_STRING = 1.0 14 | ENTRY_POINT = UefiMain 15 | # 16 | # The following information is for reference only and not required by the build tools. 17 | # 18 | # VALID_ARCHITECTURES = IA32 X64 19 | # 20 | 21 | [Sources] 22 | TestBMP.c 23 | 24 | [Packages] 25 | MdePkg/MdePkg.dec 26 | MdeModulePkg/MdeModulePkg.dec 27 | kAFLAgentPkg/kAFLAgentPkg.dec 28 | 29 | [Protocols] 30 | gEfiShellParametersProtocolGuid 31 | gEfiShellProtocolGuid 32 | 33 | [LibraryClasses] 34 | 35 | kAFLAgentLib 36 | BaseLib 37 | PrintLib 38 | BmpSupportLib 39 | UefiApplicationEntryPoint 40 | BaseMemoryLib 41 | DebugLib 42 | MemoryAllocationLib 43 | SafeIntLib 44 | UefiBootServicesTableLib 45 | DebugLib 46 | SerialPortLib 47 | PcdLib 48 | DebugPrintErrorLevelLib 49 | UefiApplicationEntryPoint 50 | UefiLib 51 | CpuExceptionHandlerLib 52 | 53 | -------------------------------------------------------------------------------- /targets/windows_x86_64/compile.sh: -------------------------------------------------------------------------------- 1 | if [[ "$OSTYPE" == "linux-gnu" ]]; then 2 | 3 | mkdir bin/ 2> /dev/null 4 | mkdir bin/loader/ 2> /dev/null 5 | mkdir bin/fuzzer/ 2> /dev/null 6 | mkdir bin/info/ 2> /dev/null 7 | 8 | if x86_64-w64-mingw32-gcc -v 2> /dev/null && x86_64-w64-mingw32-g++ -v 2> /dev/null; then 9 | printf "\tCompiling info executable...\n" 10 | x86_64-w64-mingw32-g++ src/info/info.cpp -I ../ -o bin/info/info.exe -lntdll -lpsapi 11 | printf "\tCompiling loader...\n" 12 | x86_64-w64-mingw32-gcc src/loader/loader.c -I ../ -o bin/loader/loader.exe -Wall -lpsapi 13 | printf "\tCompiling packet_sender fuzzer...\n" 14 | x86_64-w64-mingw32-gcc src/fuzzer/packet_sender.c -I ../ -o bin/fuzzer/packet_sender.exe 15 | printf "\tCompiling hprintf test...\n" 16 | x86_64-w64-mingw32-gcc src/fuzzer/hprintf_test.c -I ../ -o bin/fuzzer/hprintf_test.exe -mwindows -Wall 17 | 18 | else 19 | printf "\tCould not find x86_64-w64-mingw32-gcc/g++! Skipping..\n\t(Try sudo apt install gcc-mingw-w64-x86-64 g++-mingw-w64-x86-64 to fix this)" 20 | fi 21 | else 22 | printf "\tError: Need to run Linux to compile these components! Skipping..!\n" 23 | fi 24 | 25 | 26 | # sudo apt install gcc-mingw-w64-x86-64 27 | # sudo apt install gcc-mingw-w64-x86-64 28 | # linux_x86-64-2$ x86_64-w64-mingw32-gcc -v 29 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestDecompressPkg/TestDecompress.inf: -------------------------------------------------------------------------------- 1 | ## @file TestDecompress.inf 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | INF_VERSION = 0x00010005 10 | BASE_NAME = TestDecompress 11 | FILE_GUID = E6020274-067D-40B2-B007-BE19B6EEF825 12 | MODULE_TYPE = UEFI_APPLICATION 13 | VERSION_STRING = 1.0 14 | ENTRY_POINT = UefiMain 15 | # 16 | # The following information is for reference only and not required by the build tools. 17 | # 18 | # VALID_ARCHITECTURES = IA32 X64 19 | # 20 | 21 | [Sources] 22 | TestDecompress.c 23 | 24 | [Packages] 25 | MdePkg/MdePkg.dec 26 | kAFLAgentPkg/kAFLAgentPkg.dec 27 | MdeModulePkg/MdeModulePkg.dec 28 | 29 | [Protocols] 30 | gEfiShellParametersProtocolGuid 31 | gEfiShellProtocolGuid 32 | 33 | [LibraryClasses] 34 | 35 | kAFLAgentLib 36 | BaseLib 37 | PrintLib 38 | UefiApplicationEntryPoint 39 | BaseMemoryLib 40 | DebugLib 41 | MemoryAllocationLib 42 | SafeIntLib 43 | UefiBootServicesTableLib 44 | DebugLib 45 | SerialPortLib 46 | PcdLib 47 | DebugPrintErrorLevelLib 48 | UefiApplicationEntryPoint 49 | UefiLib 50 | UefiDecompressLib 51 | CpuExceptionHandlerLib 52 | 53 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/kafl_info.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # 3 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 4 | # Copyright (C) 2019-2020 Intel Corporation 5 | # 6 | # SPDX-License-Identifier: AGPL-3.0-or-later 7 | 8 | """ 9 | Execute a kAFL target once, using a special "info" binary as agent. 10 | 11 | This is used in cases where we want to automatically extract some information 12 | from a target before proper fuzzing, e.g. the location of kernel modules in a VM 13 | snapshot. Perhaps this feature should be merged into kafl_debug.py. 14 | """ 15 | 16 | import os 17 | import sys 18 | 19 | import common.color 20 | from common.self_check import self_check 21 | from common.config import InfoConfiguration 22 | 23 | KAFL_ROOT = os.path.dirname(os.path.realpath(__file__)) + "/" 24 | KAFL_BANNER = KAFL_ROOT + "banner.txt" 25 | KAFL_CONFIG = KAFL_ROOT + "kafl.ini" 26 | 27 | def main(): 28 | 29 | with open(KAFL_BANNER) as f: 30 | for line in f: 31 | print(line.replace("\n", "")) 32 | 33 | print("<< " + common.color.BOLD + common.color.OKGREEN + 34 | sys.argv[0] + ": Agent Info Dumper " + common.color.ENDC + ">>\n") 35 | 36 | if not self_check(KAFL_ROOT): 37 | return 1 38 | 39 | import info.core 40 | cfg = InfoConfiguration(KAFL_CONFIG) 41 | return info.core.start(cfg) 42 | 43 | 44 | if __name__ == "__main__": 45 | main() 46 | -------------------------------------------------------------------------------- /tools/ida_highlight_addrs.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # SPDX-License-Identifier: AGPL-3.0-or-later 3 | 4 | import json 5 | from idaapi import * 6 | from idautils import * 7 | from idc import * 8 | 9 | print("=====================================") 10 | file = idc.AskFile(0, "*", "Select an address file") 11 | 12 | 13 | def color_instruction(ea, color): 14 | idc.SetColor(ea, idc.CIC_ITEM, color) 15 | 16 | 17 | colors = {} 18 | 19 | for line in open(file).readlines(): 20 | addr, color = json.loads(line) 21 | if not color in colors: 22 | colors[color] = set() 23 | colors[color].add(addr) 24 | color_instruction(addr, color) 25 | 26 | 27 | def each_funcea(): 28 | for segea in Segments(): 29 | for funcea in Functions(segea, SegEnd(segea)): 30 | yield funcea 31 | 32 | 33 | def each_instrea_for_func(funcea): 34 | for (startea, endea) in Chunks(funcea): 35 | for head in Heads(startea, endea): 36 | yield head 37 | 38 | 39 | def get_covered_bbs(funcea, color): 40 | instrs_found = 0 41 | for head in each_instrea_for_func(funcea): 42 | if head in colors[color]: 43 | instrs_found += 1 44 | return instrs_found 45 | 46 | 47 | funcs = [(addr, get_covered_bbs(addr, 0x76ffff)) for addr in each_funcea()] 48 | funcs = sorted(funcs, key=lambda (a, b): b) 49 | for (addr, bbs) in funcs: 50 | print 51 | "%x %d" % (addr, bbs) 52 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/src/ld_preload_info.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of Redqueen. 3 | * 4 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 5 | * 6 | * SPDX-License-Identifier: MIT 7 | */ 8 | 9 | #define _GNU_SOURCE 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | #include "../../kafl_user.h" 20 | 21 | int __libc_start_main(int (*main) (int,char **,char **), 22 | int argc,char **ubp_av, 23 | void (*init) (void), 24 | void (*fini)(void), 25 | void (*rtld_fini)(void), 26 | void (*stack_end)) { 27 | 28 | hprintf("LD_PRELOAD hprintf :)\n"); 29 | 30 | char filename[256]; 31 | void* info_buffer = mmap((void*)NULL, INFO_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 32 | memset(info_buffer, 0xff, INFO_SIZE); 33 | 34 | hprintf("LD_PRELOAD hprintf :)\n"); 35 | hprintf("Own pid is %d\n", getpid()); 36 | 37 | snprintf(filename, 256, "/proc/%d/maps", getpid()); 38 | hprintf("proc filename: %s\n", filename); 39 | 40 | FILE* f = fopen(filename, "r"); 41 | uint16_t len = fread(info_buffer, 1, INFO_SIZE, f); 42 | fclose(f); 43 | 44 | ((char*)info_buffer)[len] = '\0'; 45 | 46 | hprintf("Transfer data to hypervisor\n"); 47 | 48 | kAFL_hypercall(HYPERCALL_KAFL_INFO, (uintptr_t)info_buffer); 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/compile.sh: -------------------------------------------------------------------------------- 1 | # 2 | # This file is part of Redqueen. 3 | # 4 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 5 | # Copyright 2020 Intel Corporation 6 | # 7 | # SPDX-License-Identifier: MIT 8 | # 9 | set -e 10 | 11 | SCRIPT_ROOT="$(dirname ${PWD}/${0})" 12 | 13 | if [[ "$OSTYPE" != "linux-gnu" ]]; then 14 | printf "\tError: Cannont compile linux userspace components on this plattform!\n\tPlease use Linux instead!\n" 15 | fi 16 | 17 | pushd $SCRIPT_ROOT 18 | 19 | printf "\tPrecompiling executables...\n" 20 | mkdir -p bin/ 21 | mkdir -p bin/fuzzer/ 22 | mkdir -p bin/loader/ 23 | mkdir -p bin/info/ 24 | 25 | gcc -c -static -shared -O0 -m32 -Werror -fPIC src/ld_preload_info.c -o bin/ld_preload_info_32.o -ldl 26 | gcc -c -static -shared -O0 -m64 -Werror -fPIC src/ld_preload_info.c -o bin/ld_preload_info_64.o -ldl 27 | 28 | gcc -c -static -shared -O0 -m32 -Werror -fPIC src/ld_preload_fuzz.c -o bin/ld_preload_fuzz_32.o -ldl 29 | gcc -c -static -shared -O0 -m64 -Werror -fPIC src/ld_preload_fuzz.c -o bin/ld_preload_fuzz_64.o -ldl 30 | 31 | gcc -c -static -shared -O0 -m32 -Werror -fPIC -DASAN_BUILD src/ld_preload_fuzz.c -o bin/ld_preload_fuzz_32_asan.o -ldl 32 | gcc -c -static -shared -O0 -m64 -Werror -fPIC -DASAN_BUILD src/ld_preload_fuzz.c -o bin/ld_preload_fuzz_64_asan.o -ldl 33 | 34 | gcc -c -static -O0 -m32 -Werror src/userspace_loader.c -o bin/userspace_loader_32.o 35 | gcc -c -static -O0 -m64 -Werror src/userspace_loader.c -o bin/userspace_loader_64.o 36 | 37 | popd 38 | -------------------------------------------------------------------------------- /targets/linux_x86_64/compile.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This file is part of Redqueen. 4 | # 5 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 6 | # 7 | # SPDX-License-Identifier: MIT 8 | # 9 | if [[ "$OSTYPE" == "linux-gnu" ]]; then 10 | 11 | mkdir bin/ 2> /dev/null 12 | mkdir bin/loader/ 2> /dev/null 13 | mkdir bin/fuzzer/ 2> /dev/null 14 | mkdir bin/info/ 2> /dev/null 15 | 16 | printf "\tCompiling loader...\n" 17 | gcc src/loader/loader.c -static -I ../ -o bin/loader/loader 18 | printf "\tCompiling stage 2 loader...\n" 19 | gcc -c -O0 src/loader/stage2_loader.c -I ../ -o bin/loader/stage2_loader.o 20 | printf "\tCompiling info executable...\n" 21 | gcc -static src/info/info.c -I ../ -o bin/info/info 22 | printf "\tCompiling vuln_driver fuzzer...\n" 23 | gcc src/fuzzer/kafl_vuln_test.c -I ../ -o bin/fuzzer/kafl_vuln_test 24 | printf "\tCompiling kafl_vuln_json test...\n" 25 | gcc src/fuzzer/kafl_vuln_json.c -I ../ -o bin/fuzzer/kafl_vuln_json 26 | printf "\tCompiling hprintf test...\n" 27 | gcc src/fuzzer/hprintf_test.c -I ../ -o bin/fuzzer/hprintf_test 28 | printf "\tCompiling EXT4 fuzzer...\n" 29 | gcc src/fuzzer/fs_fuzzer.c -I ../ -o bin/fuzzer/ext4 -D EXT4 30 | printf "\tCompiling NTFS fuzzer...\n" 31 | gcc src/fuzzer/fs_fuzzer.c -I ../ -o bin/fuzzer/ntfs -D NTFS 32 | printf "\tCompiling VFAT fuzzer...\n" 33 | gcc src/fuzzer/fs_fuzzer.c -I ../ -o bin/fuzzer/vfat -D VFAT 34 | else 35 | printf "\tError: Need to run Linux to compile these components! Skipping..!\n" 36 | fi 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2021, SafeBreach Labs 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /tests/test_cases/asan/linux_x86_64-userspace/src/vuln.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of Redqueen. 3 | * 4 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 5 | * 6 | * SPDX-License-Identifier: MIT 7 | */ 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | int main(int argc, char** argv){ 17 | 18 | #ifdef STDIN_INPUT 19 | char input[256]; 20 | memset(input, 0x00, 256); 21 | size_t len = read(STDIN_FILENO, input, 256); 22 | #elif FILE_INPUT 23 | if(argc != 2){ 24 | return 0; 25 | } 26 | 27 | int fd = open(argv[1], O_RDONLY); 28 | 29 | char input[256]; 30 | memset(input, 0x00, 256); 31 | size_t len = read(fd, input, 256); 32 | #endif 33 | 34 | 35 | if(len >= 256){ 36 | return 0; 37 | } 38 | 39 | char* array = malloc(128); 40 | 41 | 42 | if(input[0] == 'K') 43 | if(input[1] == 'E') 44 | if(input[2] == 'R') 45 | if(input[3] == 'N') 46 | if(input[4] == 'E') 47 | if(input[5] == 'L') 48 | if(input[6] == 'A') 49 | if(input[7] == 'F') 50 | if(input[8] == 'L') 51 | assert(false); 52 | 53 | if(input[0] == 'S') 54 | if(input[1] == 'E') 55 | if(input[2] == 'R') 56 | if(input[3] == 'G') 57 | if(input[4] == 'E') 58 | if(input[5] == 'J') 59 | assert(false); 60 | 61 | if(input[0] == 'K'){ 62 | if(input[1] == 'A'){ 63 | if(input[2] == 'S'){ 64 | if(input[3] == 'A'){ 65 | if(input[4] == 'N'){ 66 | free(array); 67 | array[0] = 234; 68 | } 69 | } 70 | } 71 | } 72 | } 73 | free(array); 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /targets/macOS_x86_64/fuzzer/vuln_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Sergej Schumilo 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "../../kafl_user.h" 30 | 31 | int main(int argc, char** argv) 32 | { 33 | int kafl_vuln_fd; 34 | kAFL_payload* payload_buffer = mmap((void*)0xabcd0000, PAYLOAD_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 35 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 36 | kafl_vuln_fd = open("/dev/vuln", O_WRONLY, 0); 37 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (uint64_t)payload_buffer); 38 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 39 | while(1){ 40 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 41 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 42 | write(kafl_vuln_fd, payload_buffer->data, payload_buffer->size); 43 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 44 | } 45 | return 0; 46 | } -------------------------------------------------------------------------------- /tools/ghidra_cov_analysis.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Helper script to launch Ghidra coverage analysis with given kAFL traces and target ELF. 4 | # 5 | # Copyright 2020 Intel Corporation 6 | # SPDX-License-Identifier: MIT 7 | 8 | KAFL_ROOT=~/kafl 9 | GHIDRA_ROOT=~/ghidra_9.1.2_PUBLIC 10 | WORKDIR="$1" # kAFL work dir with traces/ folder 11 | TARGET="$2" # original target input (tested with basic ELF file loaded as -kernel) 12 | SCRIPT="$KAFL_ROOT/tools/ghidra_cov_analysis.py" 13 | 14 | BIN=$GHIDRA_ROOT/support/analyzeHeadless 15 | PROJDIR=$GHIDRA_ROOT/work 16 | PROJ=cov_analysis 17 | 18 | 19 | function fail { 20 | echo 21 | echo -e "$1" 22 | echo 23 | exit 24 | } 25 | 26 | test $# -eq 2 || fail "Missing arguments.\n\nUsage:\n\t$0 " 27 | 28 | test -f "$BIN" || fail "Missing ghidra executable $BIN" 29 | test -d "$PROJDIR" || fail "Missing ghidra workdir $PROJDIR" 30 | test -f "$TARGET" || fail "Could not find target binary at $TARGET" 31 | test -f "$SCRIPT" || fail "Could not find coverage anaylsis script at $SCRIPT" 32 | 33 | # Check if traces have been generated and optionally create unique edges file 34 | test -d "$WORKDIR/traces/" || fail "Could not find traces/ folder in workdir." 35 | test -f "$WORKDIR/traces/edges_uniq.lst" || $KAFL_ROOT/tools/unique_edges.sh $WORKDIR 36 | 37 | # TODO: how can we hand the file argument directly to ghidra script? 38 | ln -sf "$WORKDIR/traces/edges_uniq.lst" /tmp/edges_uniq.lst 39 | 40 | # create project and import binary - slow but only required once per binary 41 | $BIN $PROJDIR $PROJ -import $TARGET -overwrite 42 | # analyse coverage 43 | $BIN $PROJDIR $PROJ -process $(basename $TARGET) -scriptPath "$(dirname $SCRIPT)" -postscript "$(basename $SCRIPT)" 44 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness/Driver.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #pragma warning(push) 4 | #pragma warning(disable: 4201) /* nonstandard extension used: nameless struct/union */ 5 | #include 6 | #include 7 | #pragma warning(pop) 8 | #include 9 | 10 | #pragma comment(lib, "ndis.lib") 11 | 12 | typedef struct _FILTER_DEVICE_EXTENSION 13 | { 14 | IO_REMOVE_LOCK RemoveLock; 15 | VMBCHANNEL Channel; 16 | } FILTER_DEVICE_EXTENSION, * PFILTER_DEVICE_EXTENSION; 17 | 18 | typedef struct _SYSTEM_MODULE_ENTRY 19 | { 20 | HANDLE Section; 21 | PVOID MappedBase; 22 | PVOID ImageBase; 23 | ULONG ImageSize; 24 | ULONG Flags; 25 | USHORT LoadOrderIndex; 26 | USHORT InitOrderIndex; 27 | USHORT LoadCount; 28 | USHORT OffsetToFileName; 29 | UCHAR FullPathName[256]; 30 | } SYSTEM_MODULE_ENTRY, * PSYSTEM_MODULE_ENTRY; 31 | 32 | typedef struct _SYSTEM_MODULE_INFORMATION 33 | { 34 | ULONG Count; 35 | SYSTEM_MODULE_ENTRY Module[1]; 36 | } SYSTEM_MODULE_INFORMATION, * PSYSTEM_MODULE_INFORMATION; 37 | 38 | typedef enum _SYSTEM_INFORMATION_CLASS 39 | { 40 | SystemBasicInformation, 41 | SystemProcessorInformation, 42 | SystemPerformanceInformation, 43 | SystemTimeOfDayInformation, 44 | SystemPathInformation, 45 | SystemProcessInformation, 46 | SystemCallCountInformation, 47 | SystemDeviceInformation, 48 | SystemProcessorPerformanceInformation, 49 | SystemFlagsInformation, 50 | SystemCallTimeInformation, 51 | SystemModuleInformation 52 | } SYSTEM_INFORMATION_CLASS, * PSYSTEM_INFORMATION_CLASS; 53 | 54 | PVOID NTAPI RtlImageDirectoryEntryToData( 55 | PVOID ImageBase, 56 | BOOLEAN MappedAsImage, 57 | USHORT DirectoryEntry, 58 | PULONG Size); -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/template/init: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # This file is part of Redqueen. 4 | # 5 | # Sergej Schumilo, 2019 6 | # Cornelius Aschermann, 2019 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU Affero General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU Affero General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU Affero General Public License 19 | # along with Redqueen. If not, see . 20 | # 21 | 22 | mount -t proc none /proc 23 | mount -t sysfs none /sys 24 | mount -t debugfs none /sys/kernel/debug 25 | mount -t devtmpfs none /dev 26 | mount -t tmpfs none /tmp 27 | chmod 777 / /tmp 28 | 29 | echo "7" > /proc/sys/kernel/printk 30 | echo "0" > /proc/sys/kernel/printk_ratelimit 31 | echo "19999999" > /proc/sys/kernel/printk_ratelimit_burst 32 | echo "1" > /proc/sys/kernel/panic_on_oops 33 | 34 | 35 | # set cmdline as script arguments, then eval() anything we recognize 36 | set -- $(cat /proc/cmdline) 37 | for arg in "$@"; do 38 | case "$arg" in 39 | kafl_agent=*) 40 | eval "$arg" 41 | ;; 42 | esac 43 | done 44 | 45 | # if kafl_agent points to valid executable, assume this is the intended target 46 | test -x "$kafl_agent" && exec $kafl_agent 47 | 48 | # fallback: launch option set by pack.sh 49 | /default_agent 50 | 51 | -------------------------------------------------------------------------------- /kAFL-LICENSES/BSD-2-Clause: -------------------------------------------------------------------------------- 1 | Valid-License-Identifier: BSD-2-Clause 2 | SPDX-URL: https://spdx.org/licenses/BSD-2-Clause.html 3 | Usage-Guide: 4 | To use the BSD 2-clause "Simplified" License put the following SPDX 5 | tag/value pair into a comment according to the placement guidelines in 6 | the licensing rules documentation: 7 | SPDX-License-Identifier: BSD-2-Clause 8 | License-Text: 9 | 10 | Copyright (c) . All rights reserved. 11 | 12 | Redistribution and use in source and binary forms, with or without 13 | modification, are permitted provided that the following conditions are met: 14 | 15 | 1. Redistributions of source code must retain the above copyright notice, 16 | this list of conditions and the following disclaimer. 17 | 18 | 2. Redistributions in binary form must reproduce the above copyright 19 | notice, this list of conditions and the following disclaimer in the 20 | documentation and/or other materials provided with the distribution. 21 | 22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 26 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 27 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 28 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 29 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 30 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 31 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 32 | POSSIBILITY OF SUCH DAMAGE. 33 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/common/execution_result.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | import ctypes 7 | import mmh3 8 | 9 | from fuzzer.bitmap import GlobalBitmap 10 | 11 | 12 | class ExecutionResult: 13 | 14 | @staticmethod 15 | def bitmap_from_bytearray(bitmap, exitreason, performance): 16 | bitmap_size = len(bitmap) 17 | c_bitmap = (ctypes.c_uint8 * bitmap_size).from_buffer_copy(bitmap) 18 | return ExecutionResult(c_bitmap, bitmap_size, exitreason, performance) 19 | 20 | @staticmethod 21 | def get_null_hash(bitmap_size): 22 | return mmh3.hash(("\x00" * bitmap_size), signed=False) 23 | 24 | def __init__(self, cbuffer, bitmap_size, exit_reason, performance): 25 | self.bitmap_size = bitmap_size 26 | self.cbuffer = cbuffer 27 | self.lut_applied = False # By default we assume that the bucket lut has not yet been applied 28 | self.exit_reason = exit_reason 29 | self.performance = performance 30 | 31 | def invalidate(self): 32 | self.cbuffer = None 33 | return self 34 | 35 | def is_crash(self): 36 | return self.exit_reason != "regular" 37 | 38 | def is_regular(self): 39 | return not self.is_crash() 40 | 41 | def is_lut_applied(self): 42 | return self.lut_applied 43 | 44 | def copy_to_array(self): 45 | return bytearray(self.cbuffer) 46 | 47 | def hash(self): 48 | return mmh3.hash(self.cbuffer, signed=False) 49 | 50 | def apply_lut(self): 51 | assert not self.lut_applied 52 | GlobalBitmap.apply_lut(self) 53 | assert self.lut_applied 54 | return self 55 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/src/target_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Zephyr TEST fuzzing sample target 3 | * 4 | * Based on kAFL kafl_vuln_test module 5 | * 6 | * Copyright 2017 Sergej Schumilo 7 | * Copyright 2019-2020 Intel Corporation 8 | * 9 | * SPDX-License-Identifier: Apache-2.0 10 | */ 11 | 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | 18 | const size_t INPUT_LENGTH = 32; 19 | 20 | void target_init() {}; 21 | 22 | ssize_t target_entry(const char *buf, size_t len) 23 | { 24 | char input[INPUT_LENGTH]; 25 | 26 | if (len >= INPUT_LENGTH) { 27 | return -EFAULT; 28 | } 29 | 30 | memcpy(input, buf, len); 31 | 32 | if(input[0] == 'K') 33 | if(input[1] == 'E') 34 | if(input[2] == 'R') 35 | if(input[3] == 'N') 36 | if(input[4] == 'E') 37 | if(input[5] == 'L') 38 | if(input[6] == 'A') 39 | if(input[7] == 'F') 40 | if(input[8] == 'L') { 41 | printk("BUG: KERNELAFL\n"); 42 | k_panic(); /* boom! bug incoming... */ 43 | } 44 | 45 | if(input[0] == 'S') 46 | if(input[1] == 'E') 47 | if(input[2] == 'R') 48 | if(input[3] == 'G') 49 | if(input[4] == 'E') 50 | if(input[5] == 'J') { 51 | printk("BUG: SERGEJ\n"); 52 | k_oops(); 53 | } 54 | 55 | /* memory corruption */ 56 | if(input[0] == 'K'){ 57 | if(input[1] == 'A'){ 58 | if(input[2] == 'S'){ 59 | if(input[3] == 'A'){ 60 | if(input[4] == 'N') { 61 | printk("BUG: KASAN\n"); 62 | k_oops(); 63 | } 64 | } 65 | } 66 | } 67 | } 68 | 69 | if (0 == strncmp(input, "RedQueen", strlen("RedQueen"))) { 70 | printk("BUG: RedQueen\n"); 71 | k_oops(); 72 | } 73 | 74 | return len; 75 | } 76 | 77 | -------------------------------------------------------------------------------- /drivers/CrashMonitoringDriver/CrashMonitoringDriver/CrashMonitoringDriver.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | {8E41214B-6785-4CFE-B992-037D68949A14} 18 | inf;inv;inx;mof;mc; 19 | 20 | 21 | 22 | 23 | Driver Files 24 | 25 | 26 | 27 | 28 | Source Files 29 | 30 | 31 | Source Files 32 | 33 | 34 | 35 | 36 | Header Files 37 | 38 | 39 | 40 | 41 | Source Files 42 | 43 | 44 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness/CPHarness.vcxproj.filters: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | {8E41214B-6785-4CFE-B992-037D68949A14} 18 | inf;inv;inx;mof;mc; 19 | 20 | 21 | 22 | 23 | Driver Files 24 | 25 | 26 | 27 | 28 | Source Files 29 | 30 | 31 | Source Files 32 | 33 | 34 | 35 | 36 | Source Files 37 | 38 | 39 | Source Files 40 | 41 | 42 | Header Files 43 | 44 | 45 | -------------------------------------------------------------------------------- /tests/hard_cases/linux_x86_64/kafl_vuln_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 3 | * 4 | * SPDX-License-Identifier: MIT OR GPL-2.0 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | MODULE_LICENSE("Dual MIT/GPL"); 17 | MODULE_AUTHOR("Cornelius Aschermann"); 18 | MODULE_DESCRIPTION("kAFL Test Module"); 19 | 20 | #define NAME "kafl_vuln" 21 | 22 | void test_panic(char* descr){ 23 | panic(KERN_INFO" %s", descr); 24 | } 25 | 26 | void* test_malloc(size_t size) { 27 | return kmalloc(size, GFP_KERNEL); 28 | } 29 | 30 | 31 | void test_free(void* data){ 32 | kfree(data); 33 | } 34 | 35 | 36 | #include "../tests.h" 37 | 38 | ssize_t write_info(struct file *filp, const char __user *buff, size_t len, loff_t *data); 39 | 40 | struct proc_dir_entry *proc_file_entry; 41 | 42 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,6,0) 43 | static const struct proc_ops proc_file_fops = { 44 | .proc_write = write_info, 45 | }; 46 | #else 47 | static const struct file_operations proc_file_fops = { 48 | .owner = THIS_MODULE, 49 | .write = write_info, 50 | }; 51 | #endif 52 | 53 | int init_mod( void ) 54 | { 55 | proc_file_entry = proc_create(NAME, 0666, NULL, &proc_file_fops); 56 | if(proc_file_entry == NULL) 57 | return -ENOMEM; 58 | return 0; 59 | } 60 | 61 | void cleanup_mod( void ) 62 | { 63 | remove_proc_entry(NAME, NULL); 64 | printk(KERN_INFO "/proc/%s removed.\n", NAME); 65 | } 66 | 67 | module_init(init_mod); 68 | module_exit(cleanup_mod); 69 | 70 | ssize_t write_info(struct file *filp, const char __user *buff, size_t len, loff_t *data) { 71 | char input[256]; 72 | 73 | if (len >= 256){ 74 | return -EFAULT; 75 | } 76 | 77 | if (copy_from_user(input, buff, len)) { 78 | return -EFAULT; 79 | } 80 | test(input, len); 81 | return len; 82 | 83 | } 84 | 85 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/common/qemu_protocol.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | ACQUIRE = b'R' 7 | RELEASE = b'D' 8 | 9 | RELOAD = b'L' 10 | ENABLE_SAMPLING = b'S' 11 | DISABLE_SAMPLING = b'O' 12 | COMMIT_FILTER = b'T' 13 | FINALIZE = b'F' 14 | CONNECT = b'J' 15 | 16 | ENABLE_RQI_MODE = b'A' 17 | DISABLE_RQI_MODE = b'B' 18 | ENABLE_TRACE_MODE = b'E' 19 | DISABLE_TRACE_MODE = b'G' 20 | ENABLE_PATCHES = b'P' 21 | DISABLE_PATCHES = b'Q' 22 | REDQUEEN_SET_LIGHT_INSTRUMENTATION = b'U' 23 | REDQUEEN_SET_WHITELIST_INSTRUMENTATION = b'W' 24 | REDQUEEN_SET_BLACKLIST = b'X' 25 | 26 | CRASH = b'C' 27 | CRASH_DUMP = b'Y' 28 | KASAN = b'K' 29 | INFO = b'I' 30 | TIMEOUT = b't' 31 | 32 | PRINTF = b'X' 33 | 34 | PT_TRASHED = b'Z' 35 | PT_TRASHED_CRASH = b'M' 36 | PT_TRASHED_KASAN = b'N' 37 | 38 | ABORT = b'H' 39 | 40 | CMDS = { 41 | ACQUIRE: "ACQUIRE", 42 | RELEASE: "RELEASE", 43 | RELOAD: "RELOAD", 44 | 45 | ENABLE_SAMPLING: "ENABLE_SAMPLING", 46 | DISABLE_SAMPLING: "DISABLE_SAMPLING", 47 | COMMIT_FILTER: "COMMIT_FILTER", 48 | FINALIZE: "FINALIZE", 49 | CONNECT: "CONNECT", 50 | 51 | ENABLE_RQI_MODE: "ENABLE_RQI_MODE", 52 | DISABLE_RQI_MODE: "DISABLE_RQI_MODE", 53 | 54 | ENABLE_TRACE_MODE: "ENABLE_TRACE_MODE", 55 | DISABLE_TRACE_MODE: "DISABLE_TRACE_MODE", 56 | ENABLE_PATCHES: "ENABLE_PATCHES", 57 | DISABLE_PATCHES: "DISABLE_PATCHES", 58 | REDQUEEN_SET_LIGHT_INSTRUMENTATION: "REDQUEEN_SET_LIGHT_INSTRUMENTATION", 59 | REDQUEEN_SET_WHITELIST_INSTRUMENTATION: "REDQUEEN_SET_WHITELIST_INSTRUMENTATION", 60 | REDQUEEN_SET_BLACKLIST: "REDQUEEN_SET_BLACKLIST", 61 | 62 | CRASH: "CRASH", 63 | CRASH_DUMP: "CRASH_DUMP", 64 | KASAN: "KASAN", 65 | INFO: "INFO", 66 | 67 | PRINTF: "PRINTF", 68 | 69 | PT_TRASHED: "PT_TRASHED", 70 | PT_TRASHED_CRASH: "PT_TRASHED_CRASH", 71 | PT_TRASHED_KASAN: "PT_TRASHED_KASAN", 72 | 73 | ABORT: "ABORT", 74 | } 75 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/common/debug.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | import collections 7 | import sys 8 | import time 9 | from datetime import timedelta 10 | from common.util import strdump 11 | 12 | logging_is_enabled = False 13 | debug_file_path = None 14 | output_file = None 15 | init_time = 0.0 16 | 17 | def __init_logger(): 18 | global output_file, init_time, debug_file_path 19 | init_time = time.time() 20 | output_file = open(debug_file_path, 'w') 21 | 22 | 23 | def logger(msg): 24 | global logging_is_enabled, output_file, init_time, shared_list 25 | 26 | if logging_is_enabled: 27 | if not output_file: 28 | __init_logger() 29 | output_file.write("[" + str(timedelta(seconds=time.time() - init_time)) + "] " + msg + "\n") 30 | output_file.flush() 31 | 32 | 33 | def enable_logging(workdir): 34 | global logging_is_enabled, debug_file_path 35 | logging_is_enabled = True 36 | debug_file_path = workdir + "/debug.log" 37 | 38 | 39 | def log_master(msg): 40 | logger("[MASTR]\t" + msg) 41 | 42 | 43 | def log_mapserver(msg): 44 | logger("[MPSRV]\t" + msg) 45 | 46 | 47 | def log_update(msg): 48 | logger("[UPDAT]\t" + msg) 49 | 50 | 51 | def log_slave(msg, qid): 52 | logger("[SLAVE " + str(qid) + "]\t" + msg) 53 | 54 | 55 | def log_tree(msg): 56 | logger("[TREE] \t" + msg) 57 | 58 | 59 | def log_eval(msg): 60 | logger("[EVAL] \t" + msg) 61 | 62 | 63 | def log_redq(msg): 64 | logger("[RedQ] \t" + msg) 65 | 66 | 67 | def log_grimoire(msg): 68 | logger("[GRIM] \t" + msg) 69 | 70 | 71 | def log_radamsa(msg): 72 | logger("[RDMA] \t" + msg) 73 | 74 | 75 | def log_qemu(msg, qid): 76 | logger("[QEMU " + str(qid) + "]\t" + msg) 77 | 78 | 79 | def log_core(msg): 80 | logger("[CORE] \t" + msg) 81 | 82 | 83 | def log_info(msg): 84 | logger("[INFO] \t" + msg) 85 | 86 | def log_debug(msg): 87 | logger("[DEBUG]\t" + msg) 88 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/src/target_fs.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Zephyr FS fuzzing sample 3 | * 4 | * This is not really working. Can you fix it? 5 | * 6 | * lsdir() function and other snippets taken from Zephyr RTOS project 7 | * samples/subsys/fs/fat_fs/src/main.c 8 | * 9 | * Copyright 2019-2020 Intel Corporation 10 | * SPDX-License-Identifier: Apache-2.0 11 | */ 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | #include 19 | #include 20 | 21 | static FATFS fat_fs; 22 | static struct fs_mount_t mp = { 23 | .type = FS_FATFS, 24 | .fs_data = &fat_fs, 25 | }; 26 | 27 | static const char *disk_mount_pt = "/SD:"; 28 | 29 | void target_init() {}; 30 | 31 | static int lsdir(const char *path) 32 | { 33 | int res; 34 | struct fs_dir_t dirp; 35 | static struct fs_dirent entry; 36 | 37 | /* Verify fs_opendir() */ 38 | res = fs_opendir(&dirp, path); 39 | if (res) { 40 | printk("Error opening dir %s [%d]\n", path, res); 41 | return res; 42 | } 43 | 44 | printk("\nListing dir %s ...\n", path); 45 | for (;;) { 46 | /* Verify fs_readdir() */ 47 | res = fs_readdir(&dirp, &entry); 48 | 49 | /* entry.name[0] == 0 means end-of-dir */ 50 | if (res || entry.name[0] == 0) { 51 | break; 52 | } 53 | 54 | if (entry.type == FS_DIR_ENTRY_DIR) { 55 | printk("[DIR ] %s\n", entry.name); 56 | } else { 57 | printk("[FILE] %s (size = %zu)\n", 58 | entry.name, entry.size); 59 | } 60 | } 61 | 62 | /* Verify fs_closedir() */ 63 | res = fs_closedir(&dirp); 64 | 65 | return res; 66 | } 67 | 68 | ssize_t target_entry(void *buf, size_t len) 69 | { 70 | int rc = 0; 71 | 72 | mp.fs_data = buf; 73 | mp.mnt_point = disk_mount_pt; 74 | 75 | int res = fs_mount(&mp); 76 | 77 | if (res == FR_OK) { 78 | printk("Disk mounted.\n"); 79 | lsdir(disk_mount_pt); 80 | fs_unmount(&mp); 81 | } else { 82 | printk("Error mounting disk.\n"); 83 | } 84 | 85 | return rc; 86 | } 87 | 88 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/radamsa.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | Interface to Radamsa fuzzer (optional havoc stage) 8 | """ 9 | 10 | import glob 11 | import os 12 | import random 13 | import subprocess 14 | 15 | from common.config import FuzzerConfiguration 16 | from common.debug import log_radamsa 17 | from common.util import read_binary_file 18 | 19 | 20 | def init_radamsa(config, slave_id): 21 | global corpus_dir 22 | global input_dir 23 | global radamsa_path 24 | 25 | corpus_dir = config.argument_values['work_dir'] + "/corpus/" 26 | radamsa_path = config.config_values["RADAMSA_LOCATION"] 27 | input_dir = config.argument_values['work_dir'] + "/radamsa_%d/" % slave_id 28 | 29 | if not os.path.isdir(input_dir): 30 | os.makedirs(input_dir) 31 | 32 | def mutate_seq_radamsa_array(data, func, max_iterations): 33 | global corpus_dir 34 | global input_dir 35 | global radamsa_path 36 | 37 | log_radamsa("Radamsa amount: %d" % max_iterations) 38 | 39 | if max_iterations == 0: 40 | return 41 | 42 | last_n = 5 43 | rand_n = 10 44 | files = sorted(glob.glob(corpus_dir + "/regular/payload_*")) 45 | samples = files[-last_n:] + random.sample(files[:-last_n], max(0, min(rand_n, len(files) - last_n))) 46 | 47 | if not samples: 48 | return 49 | 50 | radamsa_cmd = [radamsa_path, 51 | "-o", input_dir + "input_%05n", 52 | "-n", str(max_iterations)] + samples 53 | 54 | #log_radamsa("Radamsa cmd: " + repr(radamsa_cmd)) 55 | p = subprocess.Popen(radamsa_cmd, stdin=subprocess.PIPE, shell=False) 56 | 57 | try: 58 | p.communicate(timeout=10) 59 | except subprocess.SubprocessError as e: 60 | log_radamsa("Radamsa exception %s" % str(e)) 61 | p.kill() 62 | p.communicate() 63 | 64 | for path in os.listdir(input_dir): 65 | #log_radamsa("Radamsa input %s" % path) 66 | func(read_binary_file(input_dir+path)) 67 | os.remove(input_dir+path) 68 | -------------------------------------------------------------------------------- /targets/linux_x86_64-userspace/initrd/pack.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # This file is part of Redqueen. 4 | # 5 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 6 | # Copyright 2020 Intel Corporation 7 | # 8 | # SPDX-License-Identifier: MIT 9 | # 10 | 11 | set -e 12 | 13 | SCRIPT_ROOT="$(dirname ${PWD}/${0})" 14 | DEST=${SCRIPT_ROOT}/initrd 15 | TEMP=${SCRIPT_ROOT}/template 16 | 17 | 18 | error_exit() { 19 | 20 | echo "Fatal error: $1" 21 | echo 22 | echo "Usage:" 23 | echo " $0 [other_agent]..." 24 | exit 25 | } 26 | 27 | test -d "$TEMP" || error_exit "Could not find initrd template in >>$TEMP<<" 28 | test -x "$DEST" && error_exit "Target directory >>$DEST<< already exists." 29 | 30 | # check arguments for optional output file 31 | OUTPUT_FILE="$1"; shift || error_exit "Missing argument " 32 | DEFAULT_AGENT="$1"; shift || error_exit "Missing argument " 33 | BUSYBOX=$(which busybox) || error_exit "Could not find busybox binary." 34 | 35 | touch -- "$OUTPUT_FILE" || error_exit "Failed accessing desired output file >>$OUTPUT_FILE<<." 36 | 37 | echo "[*] Creating target initrd at $DEST" 38 | cp -a "$TEMP" "$DEST" 39 | for lib in \ 40 | lib/ld-linux.so.2 \ 41 | lib64/ld-linux-x86-64.so.2 \ 42 | lib/x86_64-linux-gnu/libc.so.6 \ 43 | lib/x86_64-linux-gnu/libdl.so.2 \ 44 | lib/i386-linux-gnu/libc.so.6 \ 45 | lib/i386-linux-gnu/libdl.so.2; 46 | do 47 | cp -v "/$lib" "$DEST/$lib" 48 | done 49 | 50 | echo "[*] Adding desired agent(s)..." 51 | for agent in "$DEFAULT_AGENT" "$@"; do 52 | cp -v "$agent" "$DEST"/ || error_exit "Failed adding agent >>$agent<< to initrd." 53 | done 54 | 55 | TMPFILE=$(tempfile) 56 | 57 | pushd "$DEST" > /dev/null 58 | chmod 755 init 59 | chmod 755 $(basename $DEFAULT_AGENT) 60 | ln -s $(basename $DEFAULT_AGENT) default_agent 61 | cp $BUSYBOX bin/ && ./bin/busybox --install bin/ 62 | ln bin/busybox linuxrc 63 | find . -print0 | cpio --null -ov --format=newc 2> /dev/null | gzip -4 > "$TMPFILE" 2> /dev/null 64 | popd > /dev/null 65 | 66 | mv $TMPFILE $OUTPUT_FILE 67 | rm -f $TMPFILE 68 | 69 | [ -d "$DEST" ] && rm -rf "$DEST" 70 | 71 | echo "[*] Successfully created initrd at $OUTPUT_FILE" 72 | echo 73 | 74 | -------------------------------------------------------------------------------- /targets/linux_x86_64/src/fuzzer/hprintf_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Sergej Schumilo 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "kafl_user.h" 30 | 31 | int main(int argc, char** argv) 32 | { 33 | int kafl_vuln_fd; 34 | hprintf("Starting... %s\n", argv[0]); 35 | hprintf("Allocating buffer for kAFL_payload struct\n"); 36 | kAFL_payload* payload_buffer = mmap((void*)NULL, PAYLOAD_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 37 | hprintf("Memset kAFL_payload at address %lx (size %d)\n", (uint64_t) payload_buffer, PAYLOAD_SIZE); 38 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 39 | hprintf("Attempt to open vulnerable device file (%s)\n", "/proc/kafl_vuln"); 40 | kafl_vuln_fd = open("/proc/kafl_vuln", O_WRONLY | O_SYNC, 0); 41 | hprintf("Submitting buffer address to hypervisor...\n"); 42 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (uint64_t)payload_buffer); 43 | hprintf("Submitting current CR3 value to hypervisor...\n"); 44 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 45 | hprintf("Starting kAFL loop...\n"); 46 | while(1){ 47 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 48 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 49 | hprintf("Injecting data...\n"); 50 | write(kafl_vuln_fd, payload_buffer->data, payload_buffer->size); 51 | hprintf("Injection finished...\n"); 52 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 53 | } 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /tools/stats.plot: -------------------------------------------------------------------------------- 1 | # kAFL Status Plot 2 | # 3 | # Adopted from Redqueen kAFL-Fuzzer/common/evaluation.py 4 | # 5 | # Copyright 2019 Sergej Schumilo, Cornelius Aschermann 6 | # Copyright 2020 Intel Corporation 7 | # 8 | # SPDX-License-Identifier: AGPL-3.0-or-later 9 | # 10 | # Usage: 11 | # $ gnuplot -c $tools/stats.plot $workdir/stats.csv 12 | 13 | indata1=ARG1 14 | 15 | #set terminal png size 900,800 enhanced 16 | #set output stats.png 17 | set terminal wxt size 900,800 enhanced persist 18 | 19 | set multiplot 20 | 21 | set grid xtics linetype 0 linecolor rgb '#d0d0d0' 22 | set grid ytics linetype 0 linecolor rgb '#d0d0d0' 23 | set border linecolor rgb '#50c0f0' 24 | set tics textcolor rgb '#000000' 25 | set key outside 26 | set size 1, 0.30 27 | set datafile separator ';' 28 | 29 | 30 | # align plots 31 | set lmargin 10 32 | set rmargin 25 33 | 34 | # auto-scale y axis but avoid empty [0:0] yrange warning when no values yet 35 | set yrange [-0.1:*] 36 | set ytics nomirror 37 | set y2range [-0.1:*] 38 | set y2tics 39 | 40 | 41 | # plot over test cases or elapsed time? 42 | set xlabel "Cases" 43 | # set xlabel "Time" 44 | # set xdata time 45 | # set format x "%H:%M" 46 | # set timefmt "%s" 47 | 48 | # logscale? 49 | #set logscale x 50 | #set xrange [1:*] 51 | 52 | set style line 2 53 | set style data line 54 | 55 | ## plot #1 56 | #set ylabel "Execs" 57 | set y2label "Favs" 58 | set origin 0.0,0.66 59 | plot indata1 using 12:2 title 'Execs/s' with line linecolor rgb '#0090ff' linewidth 2 smooth bezier, \ 60 | '' using 12:2 with filledcurve x1 title '' linecolor rgb '#0090ff' fillstyle transparent solid 0.2 noborder, \ 61 | '' using 12:11 title 'Favs WIP' with lines linecolor rgb '#808080' linewidth 3 axes x1y2, \ 62 | '' using 12:5 title 'Favs Total' with lines linecolor rgb '#FF0000' linewidth 2 axes x1y2 63 | #'' using 12:10 title 'Cycles' with lines linecolor rgb '#C0C0C0' linewidth 2 axes x1y2 64 | 65 | 66 | ## plot #2 67 | unset y2tics 68 | unset y2label 69 | set origin 0.0,0.33 70 | plot indata1 \ 71 | using 12:13 title 'Edges' with lines linecolor rgb '#404040' linewidth 3 72 | 73 | ## plot #3 74 | set origin 0.0,0.0 75 | plot indata1 using 12:6 title 'Crashes' with lines linewidth 2, \ 76 | '' using 12:7 title 'kASan' with lines linewidth 2, \ 77 | '' using 12:8 title 'Timeout' with lines linewidth 2 78 | ## plot #4 79 | #set origin 0.0,0.0 80 | #plot indata1 using 0:15 title 'Blacklisted BB' with lines 81 | 82 | unset multiplot 83 | #pause 2 84 | #reset 85 | #reread 86 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestBMPPkg/TestBMP.c: -------------------------------------------------------------------------------- 1 | /* @file TestBMP.c 2 | * 3 | * Copyright 2020 Intel Corporation. All rights reserved. 4 | * SPDX-License-Identifier: BSD-2-Clause 5 | * 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | 24 | #define TOTAL_SIZE (512*1024) 25 | 26 | UINTN 27 | EFIAPI 28 | GetMaxBufferSize ( VOID ) 29 | { 30 | return TOTAL_SIZE; 31 | } 32 | 33 | VOID 34 | EFIAPI 35 | InitTestHarness (VOID) 36 | { 37 | /* kAFL debug info */ 38 | Print(L"Mapping info: TranslateBmpToGopBlt is at %x\n", (void*)TranslateBmpToGopBlt); 39 | Print(L"Mapping info: DumpCpuContext is at %x\n", (void*)DumpCpuContext); 40 | //Print(L"Mapping info: DumpModuleImageInfo is at %x\n", (void*)DumpModuleImageInfo); 41 | // 42 | /* Override target's word with autodetection 43 | * 44 | * Qemu log indicates the target is detected as 32bit even when OVMF+App are 45 | * compiled for X64. This overrides the auto-detection and makes Redqueen 46 | * actually find some bugs instead of just causing timeouts. 47 | */ 48 | #if defined(__x86_64__) 49 | kAFL_hypercall(HYPERCALL_KAFL_USER_SUBMIT_MODE, KAFL_MODE_64); 50 | #endif 51 | 52 | } 53 | 54 | EFI_STATUS 55 | EFIAPI 56 | RunTestHarness ( 57 | IN VOID *input, 58 | IN UINTN inputSize 59 | ) 60 | { 61 | EFI_STATUS Status; 62 | EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; 63 | UINTN BltSize; 64 | UINTN Height; 65 | UINTN Width; 66 | VOID *BmpBuffer; 67 | IN UINTN FileSize; 68 | 69 | // input params 70 | BmpBuffer = input; 71 | FileSize = inputSize; 72 | // output params 73 | Blt = NULL; 74 | Width = 0; 75 | Height = 0; 76 | Status = TranslateBmpToGopBlt ( 77 | BmpBuffer, 78 | FileSize, 79 | &Blt, 80 | &BltSize, 81 | &Height, 82 | &Width 83 | ); 84 | 85 | if (Blt) 86 | FreePool(Blt); 87 | 88 | return Status; 89 | } 90 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/src/target_json.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Zephyr json fuzzing sample 3 | * 4 | * This file is in part based on Zephyr RTOS project 5 | * tests/lib/json/src/main.c 6 | * 7 | * Copyright 2020 Intel Corporation 8 | * SPDX-License-Identifier: Apache-2.0 9 | */ 10 | 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | #include 17 | 18 | /* 19 | * Structs and description are part of Zephyr's test 20 | */ 21 | struct test_nested { 22 | int nested_int; 23 | bool nested_bool; 24 | const char *nested_string; 25 | }; 26 | 27 | struct test_struct { 28 | const char *some_string; 29 | int some_int; 30 | bool some_bool; 31 | struct test_nested some_nested_struct; 32 | int some_array[16]; 33 | size_t some_array_len; 34 | bool another_bxxl; /* JSON field: "another_b!@l" */ 35 | bool if_; /* JSON: "if" */ 36 | int another_array[10]; /* JSON: "another-array" */ 37 | size_t another_array_len; 38 | struct test_nested xnother_nexx; /* JSON: "4nother_ne$+" */ 39 | }; 40 | 41 | static const struct json_obj_descr nested_descr[] = { 42 | JSON_OBJ_DESCR_PRIM(struct test_nested, nested_int, JSON_TOK_NUMBER), 43 | JSON_OBJ_DESCR_PRIM(struct test_nested, nested_bool, JSON_TOK_TRUE), 44 | JSON_OBJ_DESCR_PRIM(struct test_nested, nested_string, 45 | JSON_TOK_STRING), 46 | }; 47 | 48 | static const struct json_obj_descr description[] = { 49 | JSON_OBJ_DESCR_PRIM(struct test_struct, some_string, JSON_TOK_STRING), 50 | JSON_OBJ_DESCR_PRIM(struct test_struct, some_int, JSON_TOK_NUMBER), 51 | JSON_OBJ_DESCR_PRIM(struct test_struct, some_bool, JSON_TOK_TRUE), 52 | JSON_OBJ_DESCR_OBJECT(struct test_struct, some_nested_struct, 53 | nested_descr), 54 | JSON_OBJ_DESCR_ARRAY(struct test_struct, some_array, 55 | 16, some_array_len, JSON_TOK_NUMBER), 56 | JSON_OBJ_DESCR_PRIM_NAMED(struct test_struct, "another_b!@l", 57 | another_bxxl, JSON_TOK_TRUE), 58 | JSON_OBJ_DESCR_PRIM_NAMED(struct test_struct, "if", 59 | if_, JSON_TOK_TRUE), 60 | JSON_OBJ_DESCR_ARRAY_NAMED(struct test_struct, "another-array", 61 | another_array, 10, another_array_len, 62 | JSON_TOK_NUMBER), 63 | JSON_OBJ_DESCR_OBJECT_NAMED(struct test_struct, "4nother_ne$+", 64 | xnother_nexx, nested_descr), 65 | }; 66 | 67 | void target_init() {}; 68 | 69 | ssize_t target_entry(const char *buf, size_t len) 70 | { 71 | int ret; 72 | struct test_struct desc; 73 | 74 | ret = json_obj_parse((char *)buf, len, description, 75 | ARRAY_SIZE(description), &desc); 76 | 77 | return (ssize_t)ret; 78 | } 79 | 80 | -------------------------------------------------------------------------------- /targets/linux_x86_64/src/fuzzer/kafl_vuln_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Sergej Schumilo 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "kafl_user.h" 30 | 31 | /* printk support */ 32 | static inline uint64_t get_address(char* identifier) { 33 | FILE * fp; 34 | char * line = NULL; 35 | ssize_t read; 36 | ssize_t len; 37 | char *tmp; 38 | uint64_t address = 0x0; 39 | uint8_t identifier_len = strlen(identifier); 40 | 41 | fp = fopen("/proc/kallsyms", "r"); 42 | if (fp == NULL){ 43 | return address; 44 | } 45 | 46 | while ((read = getline(&line, &len, fp)) != -1) { 47 | if(strlen(line) > identifier_len && !strcmp(line + strlen(line) - identifier_len, identifier)){ 48 | address = strtoull(strtok(line, " "), NULL, 16); 49 | break; 50 | } 51 | } 52 | 53 | fclose(fp); 54 | if (line){ 55 | free(line); 56 | } 57 | return address; 58 | } 59 | 60 | 61 | int main(int argc, char** argv) 62 | { 63 | int kafl_vuln_fd; 64 | kAFL_payload* payload_buffer = mmap((void*)NULL, PAYLOAD_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 65 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 66 | kafl_vuln_fd = open("/proc/kafl_vuln", O_WRONLY | O_SYNC, 0); 67 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (uint64_t)payload_buffer); 68 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 69 | 70 | hprintf("printk: %lx\n", get_address("T printk\n")); 71 | kAFL_hypercall(HYPERCALL_KAFL_PRINTK_ADDR, get_address("T printk\n")); 72 | 73 | while(1){ 74 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 75 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 76 | write(kafl_vuln_fd, payload_buffer->data, payload_buffer->size); 77 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 78 | } 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /targets/linux_x86_64/src/fuzzer/kafl_vuln_json.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Sergej Schumilo 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "kafl_user.h" 30 | 31 | /* printk support */ 32 | static inline uint64_t get_address(char* identifier) { 33 | FILE * fp; 34 | char * line = NULL; 35 | ssize_t read; 36 | ssize_t len; 37 | char *tmp; 38 | uint64_t address = 0x0; 39 | uint8_t identifier_len = strlen(identifier); 40 | 41 | fp = fopen("/proc/kallsyms", "r"); 42 | if (fp == NULL){ 43 | return address; 44 | } 45 | 46 | while ((read = getline(&line, &len, fp)) != -1) { 47 | if(strlen(line) > identifier_len && !strcmp(line + strlen(line) - identifier_len, identifier)){ 48 | address = strtoull(strtok(line, " "), NULL, 16); 49 | break; 50 | } 51 | } 52 | 53 | fclose(fp); 54 | if (line){ 55 | free(line); 56 | } 57 | return address; 58 | } 59 | 60 | 61 | int main(int argc, char** argv) 62 | { 63 | int kafl_vuln_fd; 64 | kAFL_payload* payload_buffer = mmap((void*)NULL, PAYLOAD_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 65 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 66 | kafl_vuln_fd = open("/proc/kafl_vuln_json", O_WRONLY | O_SYNC, 0); 67 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (uint64_t)payload_buffer); 68 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 69 | 70 | hprintf("printk: %lx\n", get_address("T printk\n")); 71 | kAFL_hypercall(HYPERCALL_KAFL_PRINTK_ADDR, get_address("T printk\n")); 72 | 73 | while(1){ 74 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 75 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 76 | write(kafl_vuln_fd, payload_buffer->data, payload_buffer->size); 77 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 78 | } 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /targets/linux_x86_64/src/loader/stage2_loader.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of kAFL. 3 | * 4 | * Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann 5 | * 6 | * SPDX-License-Identifier: MIT 7 | */ 8 | 9 | #define _GNU_SOURCE 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #include "kafl_user.h" 24 | 25 | extern uint8_t _binary_target_start; 26 | extern uint8_t _binary_target_end; 27 | extern uint8_t _binary_target_size; 28 | 29 | extern uint32_t modules; 30 | extern uint8_t* module_address_start[]; 31 | extern uint8_t* module_address_end[]; 32 | extern char* module_name[]; 33 | 34 | static void copy_binary(char* name, char* path, void* start_address, void* end_address, bool load){ 35 | char* load_cmd; 36 | int payload_file; 37 | char* full_path; 38 | hprintf("<<%s>>\n", name); 39 | uint64_t size = end_address-start_address; 40 | hprintf("[!] binary (%s) is %d bytes in size...\n", name, size); 41 | asprintf(&full_path, "%s/%s", path, name); 42 | hprintf("[!] writing to \"%s\"\n", full_path); 43 | payload_file = open(full_path, O_RDWR | O_CREAT | O_SYNC, 0777); 44 | write(payload_file, (void*)start_address, size); 45 | hprintf("[*] write: %s\n", strerror(errno)); 46 | close(payload_file); 47 | hprintf("[*] close: %s\n\n", strerror(errno)); 48 | if(load){ 49 | asprintf(&load_cmd, "insmod %s/%s", path, name); 50 | hprintf("[*] exec: %s => %d\n", load_cmd, system(load_cmd)); 51 | } 52 | } 53 | 54 | static inline void load_programm(void* filepath){ 55 | int payload_file; 56 | char* newenviron[] = {NULL}; 57 | char* newargv[] = {filepath, NULL}; 58 | 59 | payload_file = open(filepath, O_RDONLY); 60 | fexecve(payload_file, newargv, newenviron); 61 | hprintf("%s failed\n", __func__); 62 | } 63 | 64 | int main(int argc, char** argv){ 65 | char va_space_result; 66 | int pid, fd; 67 | 68 | /* check if uid == 0 */ 69 | if(getuid()){ 70 | hprintf("Oops...no root creds?\n"); 71 | return 1; 72 | } 73 | hprintf("[*] getuid() == 0\n"); 74 | 75 | copy_binary("fuzzer", "/tmp", (void*)&_binary_target_start, (void*)&_binary_target_end, false); 76 | 77 | hprintf("Modules: %d\n", modules); 78 | for(uint32_t i = 0; i < modules; i++){ 79 | hprintf("%s\n", module_name[i]); 80 | copy_binary(module_name[i], "/tmp", (void*)module_address_start[i], (void*)module_address_end[i], true); 81 | } 82 | 83 | hprintf("DONE\n"); 84 | 85 | load_programm("/tmp/fuzzer"); 86 | hprintf("ERROR\n"); 87 | 88 | while(1){}; 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness/cpharness.inf: -------------------------------------------------------------------------------- 1 | ; 2 | ; CPHarness.inf 3 | ; 4 | 5 | [Version] 6 | Signature="$WINDOWS NT$" 7 | Class=Harness ; TODO: edit Class 8 | ClassGuid={69015c15-6232-4062-a478-560c07bd4227} ; TODO: edit ClassGuid 9 | Provider=%ManufacturerName% 10 | CatalogFile=CPHarness.cat 11 | DriverVer= ; TODO: set DriverVer in stampinf property pages 12 | PnpLockDown=1 13 | 14 | [DestinationDirs] 15 | DefaultDestDir = 12 16 | CPHarness_Device_CoInstaller_CopyFiles = 11 17 | 18 | ; ================= Class section ===================== 19 | 20 | [ClassInstall32] 21 | Addreg=SampleClassReg 22 | 23 | [SampleClassReg] 24 | HKR,,,0,%ClassName% 25 | HKR,,Icon,,-5 26 | 27 | [SourceDisksNames] 28 | 1 = %DiskName%,,,"" 29 | 30 | [SourceDisksFiles] 31 | CPHarness.sys = 1,, 32 | WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll=1 ; make sure the number matches with SourceDisksNames 33 | 34 | ;***************************************** 35 | ; Install Section 36 | ;***************************************** 37 | 38 | [Manufacturer] 39 | %ManufacturerName%=Standard,NT$ARCH$ 40 | 41 | [Standard.NT$ARCH$] 42 | %CPHarness.DeviceDesc%=CPHarness_Device, Root\CPHarness ; TODO: edit hw-id 43 | 44 | [CPHarness_Device.NT] 45 | CopyFiles=Drivers_Dir 46 | 47 | [Drivers_Dir] 48 | CPHarness.sys 49 | 50 | ;-------------- Service installation 51 | [CPHarness_Device.NT.Services] 52 | AddService = CPHarness,%SPSVCINST_ASSOCSERVICE%, CPHarness_Service_Inst 53 | 54 | ; -------------- CPHarness driver install sections 55 | [CPHarness_Service_Inst] 56 | DisplayName = %CPHarness.SVCDESC% 57 | ServiceType = 1 ; SERVICE_KERNEL_DRIVER 58 | StartType = 3 ; SERVICE_DEMAND_START 59 | ErrorControl = 1 ; SERVICE_ERROR_NORMAL 60 | ServiceBinary = %12%\CPHarness.sys 61 | 62 | ; 63 | ;--- CPHarness_Device Coinstaller installation ------ 64 | ; 65 | 66 | [CPHarness_Device.NT.CoInstallers] 67 | AddReg=CPHarness_Device_CoInstaller_AddReg 68 | CopyFiles=CPHarness_Device_CoInstaller_CopyFiles 69 | 70 | [CPHarness_Device_CoInstaller_AddReg] 71 | HKR,,CoInstallers32,0x00010000, "WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll,WdfCoInstaller" 72 | 73 | [CPHarness_Device_CoInstaller_CopyFiles] 74 | WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll 75 | 76 | [CPHarness_Device.NT.Wdf] 77 | KmdfService = CPHarness, CPHarness_wdfsect 78 | [CPHarness_wdfsect] 79 | KmdfLibraryVersion = $KMDFVERSION$ 80 | 81 | [Strings] 82 | SPSVCINST_ASSOCSERVICE= 0x00000002 83 | ManufacturerName="" ;TODO: Replace with your manufacturer name 84 | ClassName="Samples" ; TODO: edit ClassName 85 | DiskName = "CPHarness Installation Disk" 86 | CPHarness.DeviceDesc = "CPHarness Device" 87 | CPHarness.SVCDESC = "CPHarness Service" 88 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/havoc.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | AFL-style havoc and splicing stage 8 | """ 9 | 10 | import glob 11 | 12 | from common.config import FuzzerConfiguration 13 | from fuzzer.technique.havoc_handler import * 14 | 15 | 16 | def load_dict(file_name): 17 | f = open(file_name) 18 | dict_entries = [] 19 | for line in f: 20 | if not line.startswith("#"): 21 | try: 22 | dict_entries.append((line.split("=\"")[1].split("\"\n")[0]).encode('latin1').decode('unicode-escape').encode('latin1')) 23 | except: 24 | pass 25 | f.close() 26 | return dict_entries 27 | 28 | 29 | def init_havoc(config): 30 | global location_corpus 31 | if config.argument_values["dict"]: 32 | set_dict(load_dict(FuzzerConfiguration().argument_values["dict"])) 33 | # AFL havoc adds these at runtime as soon as available dicts are non-empty 34 | if config.argument_values["dict"] or config.argument_values["redqueen"]: 35 | append_handler(havoc_dict_insert) 36 | append_handler(havoc_dict_replace) 37 | 38 | location_corpus = config.argument_values['work_dir'] + "/corpus/" 39 | 40 | 41 | def havoc_range(perf_score): 42 | max_iterations = int(2*perf_score) 43 | 44 | if max_iterations < AFL_HAVOC_MIN: 45 | max_iterations = AFL_HAVOC_MIN 46 | 47 | return max_iterations 48 | 49 | 50 | def mutate_seq_havoc_array(data, func, max_iterations, resize=False): 51 | if resize: 52 | data = data + data 53 | else: 54 | data = data 55 | 56 | for i in range(max_iterations): 57 | stacking = rand.int(AFL_HAVOC_STACK_POW2) 58 | 59 | for j in range(1 << (1 + stacking)): 60 | handler = rand.select(havoc_handler) 61 | data = handler(data) 62 | if len(data) >= KAFL_MAX_FILE: 63 | data = data[:KAFL_MAX_FILE] 64 | func(data) 65 | 66 | 67 | def mutate_seq_splice_array(data, func, max_iterations, resize=False): 68 | global location_corpus 69 | splice_rounds = 16 70 | files = glob.glob(location_corpus + "/regular/payload_*") 71 | for _ in range(splice_rounds): 72 | spliced_data = havoc_splicing(data, files) 73 | if spliced_data is None: 74 | return # could not find any suitable splice pair for this file 75 | mutate_seq_havoc_array(spliced_data, 76 | func, 77 | int(2*max_iterations/splice_rounds), 78 | resize=resize) 79 | -------------------------------------------------------------------------------- /tests/test_cases/simple/linux_x86-64/kafl_vuln_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 3 | * 4 | * SPDX-License-Identifier: MIT OR GPL-2.0 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | MODULE_LICENSE("Dual MIT/GPL"); 17 | MODULE_AUTHOR("Sergej Schumilo"); 18 | MODULE_DESCRIPTION("kAFL Test Module"); 19 | 20 | #define MAX_LEN 128 21 | #define NAME "kafl_vuln" 22 | 23 | ssize_t write_info(struct file *filp, const char __user *buff, size_t len, loff_t *data); 24 | 25 | struct proc_dir_entry *proc_file_entry; 26 | 27 | #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,6,0) 28 | static const struct proc_ops proc_file_fops = { 29 | .proc_write = write_info, 30 | }; 31 | #else 32 | static const struct file_operations proc_file_fops = { 33 | .owner = THIS_MODULE, 34 | .write = write_info, 35 | }; 36 | #endif 37 | 38 | int init_mod( void ) 39 | { 40 | proc_file_entry = proc_create(NAME, 0666, NULL, &proc_file_fops); 41 | if(proc_file_entry == NULL) 42 | return -ENOMEM; 43 | return 0; 44 | } 45 | 46 | void cleanup_mod( void ) 47 | { 48 | remove_proc_entry(NAME, NULL); 49 | printk(KERN_INFO "/proc/%s removed.\n", NAME); 50 | } 51 | 52 | module_init(init_mod); 53 | module_exit(cleanup_mod); 54 | 55 | ssize_t write_info(struct file *filp, const char __user *buff, size_t len, loff_t *data) { 56 | char input[256]; 57 | int *array = (int *)kmalloc(1332, GFP_KERNEL); 58 | 59 | if (len >= 256){ 60 | return -EFAULT; 61 | } 62 | 63 | if (copy_from_user(input, buff, len)) { 64 | return -EFAULT; 65 | } 66 | 67 | if(input[0] == 'K') 68 | if(input[1] == 'E') 69 | if(input[2] == 'R') 70 | if(input[3] == 'N') 71 | if(input[4] == 'E') 72 | if(input[5] == 'L') 73 | if(input[6] == 'A') 74 | if(input[7] == 'F') 75 | if(input[8] == 'L') 76 | panic(KERN_INFO "KAFL...\n"); /* boom! bug incoming... */ 77 | if(input[0] == 'S') 78 | if(input[1] == 'E') 79 | if(input[2] == 'R') 80 | if(input[3] == 'G') 81 | if(input[4] == 'E') 82 | if(input[5] == 'J') 83 | panic(KERN_INFO "SERGEJ...\n"); 84 | 85 | if(input[0] == 'K'){ 86 | if(input[1] == 'A'){ 87 | if(input[2] == 'S'){ 88 | if(input[3] == 'A'){ 89 | if(input[4] == 'N'){ 90 | kfree(array); 91 | array[0] = 1234; 92 | } 93 | } 94 | } 95 | } 96 | } 97 | kfree(array); 98 | return len; 99 | 100 | } 101 | 102 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness/KernelModules.c: -------------------------------------------------------------------------------- 1 | #include "Globals.h" 2 | #include "KernelModules.h" 3 | 4 | NTSTATUS InitKernelModules(PKERNEL_MODULES pKernelModules) 5 | { 6 | /* Based on https://github.com/thomhastings/mimikatz-en/blob/master/driver/modules.c */ 7 | 8 | NTSTATUS status = STATUS_SUCCESS; 9 | ULONG modulesSize = 0; 10 | ULONG numberOfModules = 0; 11 | PVOID getRequiredBufferSize = NULL; 12 | AUX_MODULE_EXTENDED_INFO* modules = NULL; 13 | 14 | status = AuxKlibInitialize(); 15 | if (!NT_SUCCESS(status)) 16 | { 17 | goto exit; 18 | } 19 | 20 | /* Get the size of the struct for requested information */ 21 | status = AuxKlibQueryModuleInformation( 22 | &modulesSize, 23 | sizeof(AUX_MODULE_EXTENDED_INFO), 24 | getRequiredBufferSize 25 | ); 26 | if (!NT_SUCCESS(status)) 27 | { 28 | DbgPrintEx(DPFLTR_IHVDRIVER_ID, DEBUG_LEVEL, "KmdfFuzzer: Failed to get kernel modules information\n"); 29 | goto exit; 30 | } 31 | 32 | /* Create a new buffer for the modules */ 33 | numberOfModules = modulesSize / sizeof(AUX_MODULE_EXTENDED_INFO); 34 | modules = (AUX_MODULE_EXTENDED_INFO*)ExAllocatePoolWithTag( 35 | PagedPool, 36 | modulesSize, 37 | POOL_TAG 38 | ); 39 | if (modules == NULL) 40 | { 41 | status = STATUS_INSUFFICIENT_RESOURCES; 42 | goto exit; 43 | } 44 | RtlZeroMemory(modules, modulesSize); 45 | 46 | /* Now get the actual information... */ 47 | status = AuxKlibQueryModuleInformation( 48 | &modulesSize, 49 | sizeof(AUX_MODULE_EXTENDED_INFO), 50 | modules 51 | ); 52 | if (!NT_SUCCESS(status)) 53 | { 54 | ExFreePoolWithTag(pKernelModules->modules, POOL_TAG); 55 | goto exit; 56 | } 57 | 58 | pKernelModules->modules = modules; 59 | pKernelModules->numberOfModules = numberOfModules; 60 | 61 | exit: 62 | return status; 63 | } 64 | 65 | VOID DeinitKernelModules(PKERNEL_MODULES pKernelModules) 66 | { 67 | ExFreePoolWithTag(pKernelModules->modules, POOL_TAG); 68 | } 69 | 70 | ULONG GetKernelModulesCount(PKERNEL_MODULES pKernelModules) 71 | { 72 | return pKernelModules->numberOfModules; 73 | } 74 | 75 | PCSZ GetKernelModuleNameByIndex(PKERNEL_MODULES pKernelModules, ULONG i) 76 | { 77 | if (i >= pKernelModules->numberOfModules) 78 | { 79 | return NULL; 80 | } 81 | return (PCSZ)(pKernelModules->modules[i].FullPathName); 82 | } 83 | 84 | PVOID GetKernelModuleBaseAddressByIndex(PKERNEL_MODULES pKernelModules, ULONG i) 85 | { 86 | if (i >= pKernelModules->numberOfModules) 87 | { 88 | return NULL; 89 | } 90 | return pKernelModules->modules[i].BasicInfo.ImageBase; 91 | } -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestDecompressPkg/TestDecompress.dsc: -------------------------------------------------------------------------------- 1 | ## @file TestDecompress.dsc 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | PLATFORM_NAME = TestDecompres 10 | PLATFORM_GUID = B66DACBB-080C-4DBE-90DD-59F0D9EF87A4 11 | PLATFORM_VERSION = 0.01 12 | DSC_SPECIFICATION = 0x00010005 13 | OUTPUT_DIRECTORY = Build/TestDecompressPkg 14 | SUPPORTED_ARCHITECTURES = IA32|X64 15 | BUILD_TARGETS = DEBUG|RELEASE|NOOPT 16 | SKUID_IDENTIFIER = DEFAULT 17 | 18 | [LibraryClasses] 19 | DisplayUpdateProgressLib|MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.inf 20 | kAFLAgentLib|kAFLAgentPkg/Library/kAFLAgentLib/kAFLAgentLib.inf 21 | BaseLib|MdePkg/Library/BaseLib/BaseLib.inf 22 | BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf 23 | DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf 24 | PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf 25 | BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf 26 | MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf 27 | SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf 28 | UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf 29 | DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf 30 | SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf 31 | PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf 32 | DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf 33 | UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf 34 | UefiLib|MdePkg/Library/UefiLib/UefiLib.inf 35 | UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf 36 | DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf 37 | UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf 38 | UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf 39 | 40 | CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf 41 | SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf 42 | LocalApicLib|UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf 43 | PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf 44 | TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf 45 | IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf 46 | 47 | 48 | [Components] 49 | TestDecompressPkg/TestDecompress.inf 50 | -------------------------------------------------------------------------------- /drivers/CPHarness/CPHarness.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30320.27 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CPHarness", "CPHarness\CPHarness.vcxproj", "{88BB179F-7EB6-4733-A250-1E1C3DDD5042}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|ARM = Debug|ARM 11 | Debug|ARM64 = Debug|ARM64 12 | Debug|x64 = Debug|x64 13 | Debug|x86 = Debug|x86 14 | Release|ARM = Release|ARM 15 | Release|ARM64 = Release|ARM64 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|ARM.ActiveCfg = Debug|ARM 21 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|ARM.Build.0 = Debug|ARM 22 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|ARM.Deploy.0 = Debug|ARM 23 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|ARM64.ActiveCfg = Debug|ARM64 24 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|ARM64.Build.0 = Debug|ARM64 25 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|ARM64.Deploy.0 = Debug|ARM64 26 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|x64.ActiveCfg = Debug|x64 27 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|x64.Build.0 = Debug|x64 28 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|x64.Deploy.0 = Debug|x64 29 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|x86.ActiveCfg = Debug|Win32 30 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|x86.Build.0 = Debug|Win32 31 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Debug|x86.Deploy.0 = Debug|Win32 32 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|ARM.ActiveCfg = Release|ARM 33 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|ARM.Build.0 = Release|ARM 34 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|ARM.Deploy.0 = Release|ARM 35 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|ARM64.ActiveCfg = Release|ARM64 36 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|ARM64.Build.0 = Release|ARM64 37 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|ARM64.Deploy.0 = Release|ARM64 38 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|x64.ActiveCfg = Release|x64 39 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|x64.Build.0 = Release|x64 40 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|x64.Deploy.0 = Release|x64 41 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|x86.ActiveCfg = Release|Win32 42 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|x86.Build.0 = Release|Win32 43 | {88BB179F-7EB6-4733-A250-1E1C3DDD5042}.Release|x86.Deploy.0 = Release|Win32 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {40FE0913-FB63-433F-9A70-F515481D2FCA} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /drivers/CrashMonitoringDriver/CrashMonitoringDriver.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30320.27 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CrashMonitoringDriver", "CrashMonitoringDriver\CrashMonitoringDriver.vcxproj", "{F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|ARM = Debug|ARM 11 | Debug|ARM64 = Debug|ARM64 12 | Debug|x64 = Debug|x64 13 | Debug|x86 = Debug|x86 14 | Release|ARM = Release|ARM 15 | Release|ARM64 = Release|ARM64 16 | Release|x64 = Release|x64 17 | Release|x86 = Release|x86 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|ARM.ActiveCfg = Debug|ARM 21 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|ARM.Build.0 = Debug|ARM 22 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|ARM.Deploy.0 = Debug|ARM 23 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|ARM64.ActiveCfg = Debug|ARM64 24 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|ARM64.Build.0 = Debug|ARM64 25 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|ARM64.Deploy.0 = Debug|ARM64 26 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|x64.ActiveCfg = Debug|x64 27 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|x64.Build.0 = Debug|x64 28 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|x64.Deploy.0 = Debug|x64 29 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|x86.ActiveCfg = Debug|Win32 30 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|x86.Build.0 = Debug|Win32 31 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Debug|x86.Deploy.0 = Debug|Win32 32 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|ARM.ActiveCfg = Release|ARM 33 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|ARM.Build.0 = Release|ARM 34 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|ARM.Deploy.0 = Release|ARM 35 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|ARM64.ActiveCfg = Release|ARM64 36 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|ARM64.Build.0 = Release|ARM64 37 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|ARM64.Deploy.0 = Release|ARM64 38 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|x64.ActiveCfg = Release|x64 39 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|x64.Build.0 = Release|x64 40 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|x64.Deploy.0 = Release|x64 41 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|x86.ActiveCfg = Release|Win32 42 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|x86.Build.0 = Release|Win32 43 | {F24C087E-7A7B-4EBD-AC8F-121BA2166DA1}.Release|x86.Deploy.0 = Release|Win32 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {76734214-FD64-4E72-96B5-4DD27D30EE40} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestBMPPkg/TestBMP.dsc: -------------------------------------------------------------------------------- 1 | ## @file TestBMP.dsc 2 | # 3 | # Copyright 2020 Intel Corporation. All rights reserved. 4 | # SPDX-License-Identifier: BSD-2-Clause 5 | # 6 | ## 7 | 8 | [Defines] 9 | PLATFORM_NAME = TestBMP 10 | PLATFORM_GUID = B66DACBB-080C-4DBE-90DD-59F0D9EF87A4 11 | PLATFORM_VERSION = 0.01 12 | DSC_SPECIFICATION = 0x00010005 13 | OUTPUT_DIRECTORY = Build/TestBMPPkg 14 | SUPPORTED_ARCHITECTURES = IA32|X64 15 | BUILD_TARGETS = DEBUG|RELEASE|NOOPT 16 | SKUID_IDENTIFIER = DEFAULT 17 | 18 | [LibraryClasses] 19 | DisplayUpdateProgressLib|MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.inf 20 | kAFLAgentLib|kAFLAgentPkg/Library/kAFLAgentLib/kAFLAgentLib.inf 21 | BaseLib|MdePkg/Library/BaseLib/BaseLib.inf 22 | BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf 23 | DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf 24 | PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf 25 | BmpSupportLib|MdeModulePkg/Library/BaseBmpSupportLib/BaseBmpSupportLib.inf 26 | MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf 27 | SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf 28 | UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf 29 | DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf 30 | SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf 31 | PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf 32 | DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf 33 | UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf 34 | UefiLib|MdePkg/Library/UefiLib/UefiLib.inf 35 | UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf 36 | DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf 37 | UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf 38 | 39 | CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf 40 | SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf 41 | LocalApicLib|UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf 42 | PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf 43 | TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf 44 | IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf 45 | 46 | DxeCapsuleLib|MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.inf 47 | DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf 48 | ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf 49 | HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf 50 | 51 | [Components] 52 | TestBMPPkg/TestBMP.inf 53 | -------------------------------------------------------------------------------- /tests/test_cases/simple/macOS_x86-64/vuln.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 3 | * 4 | * SPDX-License-Identifier: MIT 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | #include 16 | 17 | #define BUFFERSIZE 255 18 | #define PANIC *((char*)(0x0)) = '0' 19 | 20 | static const char *device_name = "vuln"; 21 | static int device_major; 22 | static void *device_handle; 23 | 24 | kern_return_t vuln_start(kmod_info_t *ki, void *d); 25 | kern_return_t vuln_stop(kmod_info_t *ki, void *d); 26 | static int vuln_open(dev_t dev, int flags, int type, struct proc *p); 27 | static int vuln_close(dev_t dev, int flags, int type, struct proc *p); 28 | static int vuln_write(dev_t dev, uio_t uio, int flags); 29 | 30 | static int vuln_open(dev_t dev, int flags, int type, struct proc *p) 31 | { 32 | return KERN_SUCCESS; 33 | } 34 | 35 | static int vuln_close(dev_t dev, int flags, int type, struct proc *p) 36 | { 37 | return KERN_SUCCESS; 38 | } 39 | 40 | static int vuln_write(dev_t dev, uio_t uio, int flags){ 41 | 42 | char buffer[BUFFERSIZE+1]; 43 | user_addr_t ioaddr = uio_curriovbase(uio); 44 | user_size_t iosize = uio_curriovlen(uio); 45 | 46 | //printf("KERNEL DRIVER!!!!!\n"); 47 | 48 | if(iosize >= BUFFERSIZE){ 49 | //printf("truncating input...\n"); 50 | iosize = BUFFERSIZE; 51 | } 52 | 53 | if(copyin(ioaddr, buffer, iosize)){ 54 | //printf("copyin failed!\n"); 55 | return -1; 56 | } 57 | 58 | if(buffer[0] == 'K'){ 59 | if(buffer[1] == 'E'){ 60 | if(buffer[2] == 'R'){ 61 | if(buffer[3] == 'N'){ 62 | if(buffer[4] == 'E'){ 63 | if(buffer[5] == 'L'){ 64 | if(buffer[6] == 'A'){ 65 | if(buffer[7] == 'F'){ 66 | if(buffer[8] == 'L'){ 67 | PANIC; 68 | }}}}}}}}} 69 | 70 | if(buffer[0] == 'm'){ 71 | if(buffer[1] == 'a'){ 72 | if(buffer[2] == 'c'){ 73 | if(buffer[3] == 'O'){ 74 | if(buffer[4] == 'S'){ 75 | if(buffer[5] == '!'){ 76 | PANIC; 77 | }}}}}} 78 | 79 | //printf("It works! \n"); 80 | return 0; 81 | } 82 | 83 | static struct cdevsw device_fops = { 84 | .d_open = vuln_open, 85 | .d_close = vuln_close, 86 | .d_write = vuln_write, 87 | }; 88 | 89 | kern_return_t vuln_start(kmod_info_t *ki, void *d) 90 | { 91 | device_major = cdevsw_add(-1, &device_fops); 92 | if (device_major < 0) { 93 | printf("cdevsw_add failed\n"); 94 | return KERN_FAILURE; 95 | } 96 | device_handle = devfs_make_node(makedev(device_major, 0), DEVFS_CHAR, 0, 0, 0660, "%s", device_name); 97 | if (device_handle == NULL) { 98 | printf("devfs_make_node failed\n"); 99 | return KERN_FAILURE; 100 | } 101 | return KERN_SUCCESS; 102 | } 103 | 104 | kern_return_t vuln_stop(kmod_info_t *ki, void *d) 105 | { 106 | devfs_remove(device_handle); 107 | cdevsw_remove(device_major, &device_fops); 108 | return KERN_SUCCESS; 109 | } 110 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/kAFLAgentPkg/Library/kAFLAgentLib/kAFLAgentLib.c: -------------------------------------------------------------------------------- 1 | /* 2 | * kAFL Agent Lib for UEFI OVMF 3 | * 4 | * Implements fuzzing harness based on kAFL hypercall API 5 | * 6 | * Copyright 2020 Intel Corporation 7 | * SPDX-License-Identifier: BSD-2-Clause 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include 17 | 18 | #if defined(__i386__) 19 | void kAFL_hypercall(uint32_t rbx, uint32_t rcx) 20 | { 21 | uint32_t rax = HYPERCALL_KAFL_RAX_ID; 22 | asm volatile("movl %0, %%ecx;" 23 | "movl %1, %%ebx;" 24 | "movl %2, %%eax;" 25 | "vmcall" 26 | : 27 | : "r" (rcx), "r" (rbx), "r" (rax) 28 | : "eax", "ecx", "ebx" 29 | ); 30 | } 31 | #elif defined(__x86_64__) 32 | void kAFL_hypercall(uint64_t rbx, uint64_t rcx) 33 | { 34 | uint64_t rax = HYPERCALL_KAFL_RAX_ID; 35 | asm volatile("movq %0, %%rcx;" 36 | "movq %1, %%rbx;" 37 | "movq %2, %%rax;" 38 | "vmcall" 39 | : 40 | : "r" (rcx), "r" (rbx), "r" (rax) 41 | : "rax", "rcx", "rbx" 42 | ); 43 | } 44 | #endif 45 | 46 | void agent_init(void *panic_handler, void *kasan_handler) 47 | { 48 | Print(L"Initiate fuzzer handshake...\n"); 49 | 50 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 51 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 52 | 53 | /* submit panic and optionally kasan handlers for qemu 54 | * override */ 55 | if (panic_handler) { 56 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_PANIC, (uint_ptr)panic_handler); 57 | } 58 | 59 | if (kasan_handler) { 60 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_KASAN, (uint_ptr)kasan_handler); 61 | } 62 | 63 | /* target-specific initialization, if any */ 64 | InitTestHarness(); 65 | } 66 | 67 | void agent_run() 68 | { 69 | uint8_t buffer[PAYLOAD_SIZE]; 70 | kAFL_payload* payload_buffer = (kAFL_payload*)buffer; 71 | 72 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (uint_ptr)payload_buffer); 73 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 74 | 75 | while (1) { 76 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 77 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 78 | 79 | RunTestHarness(payload_buffer->data, payload_buffer->size); 80 | 81 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 82 | } 83 | return; 84 | } 85 | 86 | EFI_STATUS 87 | EFIAPI 88 | UefiMain ( 89 | IN EFI_HANDLE ImageHandle, 90 | IN EFI_SYSTEM_TABLE *SystemTable 91 | ) 92 | { 93 | /* 94 | * TODO find a function that kAFL can hook to detect protection faults / crashes. 95 | * Hooking the exception handler or DumpCpuContext helper does not seem to work.. 96 | * 97 | * As a workaround, we currently require a patch to EDK2 to inject these hypercalls. 98 | */ 99 | //agent_init(DumpCpuContext, 0); 100 | agent_init(NULL, NULL); 101 | agent_run(); 102 | 103 | return EFI_SUCCESS; 104 | } 105 | 106 | -------------------------------------------------------------------------------- /drivers/CrashMonitoringDriver/CrashMonitoringDriver/CrashMonitoringDriver.inf: -------------------------------------------------------------------------------- 1 | ; 2 | ; CrashMonitoringDriver.inf 3 | ; 4 | 5 | [Version] 6 | Signature="$WINDOWS NT$" 7 | Class=Sample ; TODO: edit Class 8 | ClassGuid={78A1C341-4539-11d3-B88D-00C04FAD5171} ; TODO: edit ClassGuid 9 | Provider=%ManufacturerName% 10 | CatalogFile=CrashMonitoringDriver.cat 11 | DriverVer= ; TODO: set DriverVer in stampinf property pages 12 | PnpLockDown=1 13 | 14 | [DestinationDirs] 15 | DefaultDestDir = 12 16 | CrashMonitoringDriver_Device_CoInstaller_CopyFiles = 11 17 | 18 | ; ================= Class section ===================== 19 | 20 | [ClassInstall32] 21 | Addreg=SampleClassReg 22 | 23 | [SampleClassReg] 24 | HKR,,,0,%ClassName% 25 | HKR,,Icon,,-5 26 | 27 | [SourceDisksNames] 28 | 1 = %DiskName%,,,"" 29 | 30 | [SourceDisksFiles] 31 | CrashMonitoringDriver.sys = 1,, 32 | WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll=1 ; make sure the number matches with SourceDisksNames 33 | 34 | ;***************************************** 35 | ; Install Section 36 | ;***************************************** 37 | 38 | [Manufacturer] 39 | %ManufacturerName%=Standard,NT$ARCH$ 40 | 41 | [Standard.NT$ARCH$] 42 | %CrashMonitoringDriver.DeviceDesc%=CrashMonitoringDriver_Device, Root\CrashMonitoringDriver ; TODO: edit hw-id 43 | 44 | [CrashMonitoringDriver_Device.NT] 45 | CopyFiles=Drivers_Dir 46 | 47 | [Drivers_Dir] 48 | CrashMonitoringDriver.sys 49 | 50 | ;-------------- Service installation 51 | [CrashMonitoringDriver_Device.NT.Services] 52 | AddService = CrashMonitoringDriver,%SPSVCINST_ASSOCSERVICE%, CrashMonitoringDriver_Service_Inst 53 | 54 | ; -------------- CrashMonitoringDriver driver install sections 55 | [CrashMonitoringDriver_Service_Inst] 56 | DisplayName = %CrashMonitoringDriver.SVCDESC% 57 | ServiceType = 1 ; SERVICE_KERNEL_DRIVER 58 | StartType = 3 ; SERVICE_DEMAND_START 59 | ErrorControl = 1 ; SERVICE_ERROR_NORMAL 60 | ServiceBinary = %12%\CrashMonitoringDriver.sys 61 | 62 | ; 63 | ;--- CrashMonitoringDriver_Device Coinstaller installation ------ 64 | ; 65 | 66 | [CrashMonitoringDriver_Device.NT.CoInstallers] 67 | AddReg=CrashMonitoringDriver_Device_CoInstaller_AddReg 68 | CopyFiles=CrashMonitoringDriver_Device_CoInstaller_CopyFiles 69 | 70 | [CrashMonitoringDriver_Device_CoInstaller_AddReg] 71 | HKR,,CoInstallers32,0x00010000, "WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll,WdfCoInstaller" 72 | 73 | [CrashMonitoringDriver_Device_CoInstaller_CopyFiles] 74 | WdfCoInstaller$KMDFCOINSTALLERVERSION$.dll 75 | 76 | [CrashMonitoringDriver_Device.NT.Wdf] 77 | KmdfService = CrashMonitoringDriver, CrashMonitoringDriver_wdfsect 78 | [CrashMonitoringDriver_wdfsect] 79 | KmdfLibraryVersion = $KMDFVERSION$ 80 | 81 | [Strings] 82 | SPSVCINST_ASSOCSERVICE= 0x00000002 83 | ManufacturerName="" ;TODO: Replace with your manufacturer name 84 | ClassName="Samples" ; TODO: edit ClassName 85 | DiskName = "CrashMonitoringDriver Installation Disk" 86 | CrashMonitoringDriver.DeviceDesc = "CrashMonitoringDriver Device" 87 | CrashMonitoringDriver.SVCDESC = "CrashMonitoringDriver Service" 88 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/core.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | Startup routines for kAFL Fuzzer. 8 | 9 | Spawn a Master and one or more Slave processes, where Master implements the 10 | global fuzzing queue and scheduler and Slaves implement mutation stages and 11 | Qemu/KVM execution. 12 | 13 | Prepare the kAFL workdir and copy any provided seeds to be picked up by the scheduler. 14 | """ 15 | 16 | import multiprocessing 17 | import time 18 | import pgrep 19 | import sys 20 | 21 | from common.debug import enable_logging 22 | from common.self_check import post_self_check 23 | from common.util import prepare_working_dir, print_fail, print_note, print_warning, copy_seed_files 24 | from fuzzer.process.master import MasterProcess 25 | from fuzzer.process.slave import slave_loader 26 | 27 | 28 | def qemu_sweep(): 29 | pids = pgrep.pgrep("qemu") 30 | 31 | if (len(pids) > 0): 32 | print_warning("Detected potential qemu zombies, please kill -9: " + repr(pids)) 33 | 34 | 35 | def graceful_exit(slaves): 36 | for s in slaves: 37 | s.terminate() 38 | 39 | print("Waiting for Slave instances to shutdown...") 40 | time.sleep(1) 41 | 42 | while len(slaves) > 0: 43 | for s in slaves: 44 | if s and s.exitcode is None: 45 | print("Still waiting on %s (pid=%d).. [hit Ctrl-c to abort..]" % (s.name,s.pid)) 46 | s.join(timeout=1) 47 | else: 48 | slaves.remove(s) 49 | 50 | 51 | def start(config): 52 | 53 | if not post_self_check(config): 54 | return -1 55 | 56 | work_dir = config.argument_values["work_dir"] 57 | seed_dir = config.argument_values["seed_dir"] 58 | num_slaves = config.argument_values['p'] 59 | 60 | if config.argument_values['v'] or config.argument_values['debug']: 61 | enable_logging(work_dir) 62 | 63 | if not prepare_working_dir(config): 64 | print_fail("Refuse to operate on existing work directory. Use --purge to override.") 65 | return 1 66 | 67 | if seed_dir and not copy_seed_files(work_dir, seed_dir): 68 | print_fail("Error when importing seeds. Exit.") 69 | return 1 70 | 71 | # Without -ip0, Qemu will not active PT tracing and we turn into a blind fuzzer 72 | if not config.argument_values['ip0']: 73 | print_warning("No trace region configured! PT feedback disabled!") 74 | 75 | master = MasterProcess(config) 76 | 77 | slaves = [] 78 | for i in range(num_slaves): 79 | slaves.append(multiprocessing.Process(name="Slave " + str(i), target=slave_loader, args=(i,))) 80 | slaves[i].start() 81 | 82 | try: 83 | master.loop() 84 | except KeyboardInterrupt: 85 | print_note("Received Ctrl-C, killing slaves...") 86 | except SystemExit as e: 87 | print_fail("Master exit: " + str(e)) 88 | finally: 89 | graceful_exit(slaves) 90 | 91 | time.sleep(0.2) 92 | qemu_sweep() 93 | sys.exit(0) 94 | -------------------------------------------------------------------------------- /targets/windows_x86_64/src/fuzzer/packet_sender.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Robert Gawlik 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include "kafl_user.h" 25 | 26 | #define IOCTL_SEND_PACKET CTL_CODE(FILE_DEVICE_UNKNOWN, 0x1, METHOD_BUFFERED, FILE_WRITE_ACCESS) 27 | 28 | 29 | int main(int argc, char** argv) 30 | { 31 | kAFL_payload* payload_buffer = (kAFL_payload*)VirtualAlloc(0, PAYLOAD_SIZE, MEM_COMMIT, PAGE_READWRITE); 32 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 33 | 34 | /* open vulnerable driver */ 35 | HANDLE hHarness = NULL; 36 | BOOL status = -1; 37 | 38 | hHarness = CreateFile((LPCSTR)"\\\\.\\CPHarness", 39 | GENERIC_WRITE, 40 | 0, 41 | NULL, 42 | OPEN_EXISTING, 43 | 0, 44 | NULL 45 | ); 46 | 47 | if (hHarness == INVALID_HANDLE_VALUE) { 48 | hprintf("[-] hAFL2 harness: Cannot get device handle: 0x%X\n", GetLastError()); 49 | ExitProcess(0); 50 | } 51 | 52 | /* submit the guest virtual address of the payload buffer */ 53 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (UINT64)payload_buffer); 54 | 55 | /* Warning: This part won't work well unless you'll patch the VMSwitch packet signal mechanism. 56 | For more information, read the "VMSwitch Harness Gaps" section within the README.md file of hAFL2. */ 57 | while(1){ 58 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 59 | /* request new payload (*blocking*) */ 60 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 61 | /* kernel fuzzing */ 62 | hprintf("Sending payload with size: 0x%x", payload_buffer->size); 63 | DeviceIoControl(hHarness, 64 | IOCTL_SEND_PACKET, 65 | (LPVOID)(payload_buffer->data), 66 | (DWORD)payload_buffer->size, 67 | NULL, 68 | 0, 69 | NULL, 70 | NULL 71 | ); 72 | 73 | /* Harness will provide partial code coverage, read README.md, a temporary workaround is to add this loop but it's not a complete solution */ 74 | // volatile unsigned long long t; 75 | // for (t = 0; t < 1000000000ull; ++t) {} // 1000*1000*1000 76 | 77 | 78 | /* inform fuzzer about finished fuzzing iteration */ 79 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 80 | } 81 | 82 | return 0; 83 | } 84 | 85 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/edk2_kafl.patch: -------------------------------------------------------------------------------- 1 | ## Automatic binary patch by kAFL does not work - inject manual hypercall here. 2 | ## Also remove the delay to launch the target binary via startup.nsh 3 | 4 | diff --git a/ShellPkg/Application/Shell/Shell.c b/ShellPkg/Application/Shell/Shell.c 5 | index d16adae0ea..f20b023969 100644 6 | --- a/ShellPkg/Application/Shell/Shell.c 7 | +++ b/ShellPkg/Application/Shell/Shell.c 8 | @@ -923,7 +923,7 @@ ProcessCommandLine( 9 | ShellInfoObject.ShellInitSettings.BitUnion.Bits.Delay = FALSE; 10 | ShellInfoObject.ShellInitSettings.BitUnion.Bits.Exit = FALSE; 11 | ShellInfoObject.ShellInitSettings.BitUnion.Bits.NoNest = FALSE; 12 | - ShellInfoObject.ShellInitSettings.Delay = 5; 13 | + ShellInfoObject.ShellInitSettings.Delay = 0; 14 | 15 | // 16 | // Start LoopVar at 0 to parse only optional arguments at Argv[0] 17 | diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c 18 | index 1aafb7dac1..cb3bdcc941 100644 19 | --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c 20 | +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/Ia32/ArchExceptionHandler.c 21 | @@ -398,6 +398,22 @@ DumpCpuContext ( 22 | ); 23 | } 24 | 25 | +#ifndef uint32_t 26 | +#define uint32_t UINT32 27 | +#endif 28 | + 29 | +#define HYPERCALL_KAFL_RAX_ID 0x01f 30 | +#define HYPERCALL_KAFL_PANIC 8 31 | + 32 | +static void kAFL_hypercall(uint32_t rbx, uint32_t rcx) 33 | +{ 34 | + uint32_t rax = HYPERCALL_KAFL_RAX_ID; 35 | + asm ("movl %0, %%ecx;" : : "r"(rcx)); 36 | + asm ("movl %0, %%ebx;" : : "r"(rbx)); 37 | + asm ("movl %0, %%eax;" : : "r"(rax)); 38 | + asm ("vmcall"); 39 | +} 40 | + 41 | /** 42 | Display CPU information. 43 | 44 | @@ -424,4 +440,6 @@ DumpImageAndCpuContent ( 45 | } else { 46 | DumpModuleImageInfo (SystemContext.SystemContextIa32->Eip); 47 | } 48 | + 49 | + kAFL_hypercall(HYPERCALL_KAFL_PANIC, 0); 50 | } 51 | diff --git a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c 52 | index 894c1cfb75..409116bcf2 100644 53 | --- a/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c 54 | +++ b/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c 55 | @@ -398,6 +398,22 @@ DumpCpuContext ( 56 | ); 57 | } 58 | 59 | +#ifndef uint64_t 60 | +#define uint64_t UINT64 61 | +#endif 62 | + 63 | +#define HYPERCALL_KAFL_RAX_ID 0x01f 64 | +#define HYPERCALL_KAFL_PANIC 8 65 | + 66 | +static inline void kAFL_hypercall(uint64_t rbx, uint64_t rcx) 67 | +{ 68 | + uint64_t rax = HYPERCALL_KAFL_RAX_ID; 69 | + asm ("movq %0, %%rcx;" : : "r"(rcx)); 70 | + asm ("movq %0, %%rbx;" : : "r"(rbx)); 71 | + asm ("movq %0, %%rax;" : : "r"(rax)); 72 | + asm ("vmcall"); 73 | +} 74 | + 75 | /** 76 | Display CPU information. 77 | 78 | @@ -424,4 +440,7 @@ DumpImageAndCpuContent ( 79 | } else { 80 | DumpModuleImageInfo (SystemContext.SystemContextX64->Rip); 81 | } 82 | + 83 | + kAFL_hypercall(HYPERCALL_KAFL_PANIC, 0); 84 | + 85 | } 86 | -------------------------------------------------------------------------------- /drivers/CrashMonitoringDriver/CrashMonitoringDriver/module.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning(disable : 4201) 3 | 4 | #include 5 | #include 6 | 7 | NTSTATUS 8 | ModuleInitialize( 9 | VOID); 10 | 11 | VOID 12 | ModuleTeardown( 13 | VOID 14 | ); 15 | 16 | VOID 17 | ModuleLookup( 18 | IN ULONG_PTR Address, 19 | OUT PCHAR* Name, 20 | OUT PULONG_PTR Offset 21 | ); 22 | 23 | 24 | typedef struct _RUNTIME_FUNCTION { 25 | ULONG BeginAddress; 26 | ULONG EndAddress; 27 | ULONG UnwindData; 28 | } RUNTIME_FUNCTION, * PRUNTIME_FUNCTION; 29 | 30 | #define UNWIND_HISTORY_TABLE_SIZE 12 31 | 32 | typedef struct _UNWIND_HISTORY_TABLE_ENTRY { 33 | ULONG64 ImageBase; 34 | PRUNTIME_FUNCTION FunctionEntry; 35 | } UNWIND_HISTORY_TABLE_ENTRY, * PUNWIND_HISTORY_TABLE_ENTRY; 36 | 37 | #define UNWIND_HISTORY_TABLE_NONE 0 38 | #define UNWIND_HISTORY_TABLE_GLOBAL 1 39 | #define UNWIND_HISTORY_TABLE_LOCAL 2 40 | 41 | typedef struct _UNWIND_HISTORY_TABLE { 42 | ULONG Count; 43 | UCHAR Search; 44 | UCHAR RaiseStatusIndex; 45 | BOOLEAN Unwind; 46 | BOOLEAN Exception; 47 | ULONG64 LowAddress; 48 | ULONG64 HighAddress; 49 | UNWIND_HISTORY_TABLE_ENTRY Entry[UNWIND_HISTORY_TABLE_SIZE]; 50 | } UNWIND_HISTORY_TABLE, * PUNWIND_HISTORY_TABLE; 51 | 52 | extern PRUNTIME_FUNCTION 53 | RtlLookupFunctionEntry( 54 | __in ULONG64 ControlPc, 55 | __out PULONG64 ImageBase, 56 | __inout_opt PUNWIND_HISTORY_TABLE HistoryTable OPTIONAL 57 | ); 58 | 59 | typedef struct _KNONVOLATILE_CONTEXT_POINTERS { 60 | union { 61 | PM128A FloatingContext[16]; 62 | struct { 63 | PM128A Xmm0; 64 | PM128A Xmm1; 65 | PM128A Xmm2; 66 | PM128A Xmm3; 67 | PM128A Xmm4; 68 | PM128A Xmm5; 69 | PM128A Xmm6; 70 | PM128A Xmm7; 71 | PM128A Xmm8; 72 | PM128A Xmm9; 73 | PM128A Xmm10; 74 | PM128A Xmm11; 75 | PM128A Xmm12; 76 | PM128A Xmm13; 77 | PM128A Xmm14; 78 | PM128A Xmm15; 79 | }; 80 | }; 81 | 82 | union { 83 | PULONG64 IntegerContext[16]; 84 | struct { 85 | PULONG64 Rax; 86 | PULONG64 Rcx; 87 | PULONG64 Rdx; 88 | PULONG64 Rbx; 89 | PULONG64 Rsp; 90 | PULONG64 Rbp; 91 | PULONG64 Rsi; 92 | PULONG64 Rdi; 93 | PULONG64 R8; 94 | PULONG64 R9; 95 | PULONG64 R10; 96 | PULONG64 R11; 97 | PULONG64 R12; 98 | PULONG64 R13; 99 | PULONG64 R14; 100 | PULONG64 R15; 101 | }; 102 | }; 103 | } KNONVOLATILE_CONTEXT_POINTERS, * PKNONVOLATILE_CONTEXT_POINTERS; 104 | 105 | extern PEXCEPTION_ROUTINE 106 | RtlVirtualUnwind( 107 | __in ULONG HandlerType, 108 | __in ULONG64 ImageBase, 109 | __in ULONG64 ControlPc, 110 | __in PRUNTIME_FUNCTION FunctionEntry, 111 | __inout PCONTEXT ContextRecord, 112 | __out PVOID* HandlerData, 113 | __out PULONG64 EstablisherFrame, 114 | __inout_opt PKNONVOLATILE_CONTEXT_POINTERS ContextPointers OPTIONAL 115 | ); 116 | -------------------------------------------------------------------------------- /targets/windows_x86_64/src/fuzzer/hprintf_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Robert Gawlik 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include "kafl_user.h" 25 | 26 | #define IOCTL_KAFL_INPUT (ULONG) CTL_CODE(FILE_DEVICE_UNKNOWN, 0x800, METHOD_NEITHER, FILE_ANY_ACCESS) 27 | 28 | int main(int argc, char** argv){ 29 | hprintf("[+] Starting... %s\n", argv[0]); 30 | 31 | hprintf("[+] Allocating buffer for kAFL_payload struct\n"); 32 | kAFL_payload* payload_buffer = (kAFL_payload*)VirtualAlloc(0, PAYLOAD_SIZE, MEM_COMMIT, PAGE_READWRITE); 33 | 34 | hprintf("[+] Memset kAFL_payload at address %lx (size %d)\n", (uint64_t) payload_buffer, PAYLOAD_SIZE); 35 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 36 | 37 | /* open vulnerable driver */ 38 | HANDLE kafl_vuln_handle = INVALID_HANDLE_VALUE; 39 | hprintf("[+] Attempting to open vulnerable device file (%s)\n", "\\\\.\\testKafl"); 40 | kafl_vuln_handle = CreateFile((LPCSTR)"\\\\.\\testKafl", 41 | GENERIC_READ | GENERIC_WRITE, 42 | FILE_SHARE_READ | FILE_SHARE_WRITE, 43 | NULL, 44 | OPEN_EXISTING, 45 | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, 46 | NULL 47 | ); 48 | 49 | if (kafl_vuln_handle == INVALID_HANDLE_VALUE) { 50 | hprintf("[-] Cannot get device handle: 0x%X\n", GetLastError()); 51 | ExitProcess(0); 52 | } 53 | 54 | /* submit the guest virtual address of the payload buffer */ 55 | hprintf("[+] Submitting buffer address to hypervisor...\n"); 56 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (UINT64)payload_buffer); 57 | 58 | /* this hypercall submits the current CR3 value */ 59 | hprintf("[+] Submitting current CR3 value to hypervisor...\n"); 60 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 61 | 62 | while(1){ 63 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 64 | /* request new payload (*blocking*) */ 65 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 66 | 67 | /* kernel fuzzing */ 68 | hprintf("[+] Injecting data...\n"); 69 | DeviceIoControl(kafl_vuln_handle, 70 | IOCTL_KAFL_INPUT, 71 | (LPVOID)(payload_buffer->data), 72 | (DWORD)payload_buffer->size, 73 | NULL, 74 | 0, 75 | NULL, 76 | NULL 77 | ); 78 | 79 | /* inform fuzzer about finished fuzzing iteration */ 80 | hprintf("[+] Injection finished...\n"); 81 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 82 | } 83 | return 0; 84 | } 85 | 86 | -------------------------------------------------------------------------------- /targets/linux_x86_64/src/info/info.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Sergej Schumilo 4 | 5 | This file is part of QEMU-PT (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "kafl_user.h" 28 | 29 | #ifndef SIZE_MAX 30 | #define SIZE_MAX ((size_t) - 1) 31 | #endif 32 | 33 | #define LINE_SIZE (1024) 34 | #define MOD_NAME_SIZE (256) 35 | 36 | static inline uint64_t get_address(char* identifier) 37 | { 38 | FILE * fp; 39 | char * line = NULL; 40 | ssize_t read; 41 | ssize_t len; 42 | char *tmp; 43 | uint64_t address = 0x0; 44 | uint8_t identifier_len = strlen(identifier); 45 | 46 | fp = fopen("/proc/kallsyms", "r"); 47 | if (fp == NULL){ 48 | return address; 49 | } 50 | 51 | while ((read = getline(&line, &len, fp)) != -1) { 52 | if(strlen(line) > identifier_len && !strcmp(line + strlen(line) - identifier_len, identifier)){ 53 | address = strtoull(strtok(line, " "), NULL, 16); 54 | break; 55 | } 56 | } 57 | 58 | fclose(fp); 59 | if (line){ 60 | free(line); 61 | } 62 | return address; 63 | } 64 | 65 | int main(int argc, char** argv){ 66 | char line[LINE_SIZE]; 67 | char module_name[MOD_NAME_SIZE]; 68 | uint64_t start; 69 | uint64_t offset; 70 | char * pch; 71 | int counter; 72 | int pos = 0; 73 | int tokens = 1; 74 | int errno = 0; 75 | 76 | void* info_buffer = mmap((void*)NULL, INFO_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 77 | memset(info_buffer, 0xff, INFO_SIZE); 78 | 79 | 80 | pos += sprintf(info_buffer + pos, "kAFL Linux x86-64 Kernel Addresses (%d Modules)\n\n", counter); 81 | pos += sprintf(info_buffer + pos, "START-ADDRESS END-ADDRESS\t\tDRIVER\n"); 82 | 83 | FILE* f = fopen("/proc/modules", "r"); 84 | 85 | while (fgets(line, LINE_SIZE, f)) { 86 | tokens = sscanf(line, "%s %Lu %*u %*s %*s %Lx %*s", module_name, &offset, &start); 87 | if (tokens==3) 88 | pos += sprintf(info_buffer + pos, "0x%016lx-0x%016lx\t%s\n", start, start+offset, module_name); 89 | else 90 | //printf("got %d tokens, error: %d\n", n, errno); 91 | continue; 92 | } 93 | 94 | fclose(f); 95 | 96 | pos += sprintf(info_buffer + pos, "0x%016lx-0x%016lx\t%s\n\n", 97 | get_address("T startup_64\n"), 98 | get_address("r __param_str_debug\n"), "Kernel Core"); 99 | 100 | //printf(">>>\n%s\n<<<\n", info_buffer); 101 | kAFL_hypercall(HYPERCALL_KAFL_INFO, (uint64_t)info_buffer); 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/communicator.py: -------------------------------------------------------------------------------- 1 | # Copyright 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | Abstractions for kAFL Master/Slave communicaton. 8 | """ 9 | 10 | import msgpack 11 | import select 12 | from multiprocessing.connection import Listener, Client 13 | from common.util import print_fail 14 | 15 | MSG_READY = 0 16 | MSG_IMPORT = 1 17 | MSG_RUN_NODE = 2 18 | MSG_NODE_DONE = 3 19 | MSG_NEW_INPUT = 4 20 | MSG_BUSY = 5 21 | 22 | 23 | class ServerConnection: 24 | def __init__(self, config): 25 | Listener.fileno = lambda self: self._listener._socket.fileno() 26 | self.address = config.argument_values["work_dir"] + "/slave_socket" 27 | self.listener = Listener(self.address, 'AF_UNIX', backlog=1000) 28 | self.clients = [self.listener] 29 | 30 | def wait(self, timeout=None): 31 | results = [] 32 | r, w, e = select.select(self.clients, (), (), timeout) 33 | for sock_ready in r: 34 | if sock_ready == self.listener: 35 | c = self.listener.accept() 36 | self.clients.append(c) 37 | else: 38 | try: 39 | msg = sock_ready.recv_bytes() 40 | msg = msgpack.unpackb(msg, raw=False, strict_map_key=False) 41 | results.append((sock_ready, msg)) 42 | except (EOFError, IOError): 43 | print_fail("Slave has died - check logs!") 44 | sock_ready.close() 45 | self.clients.remove(sock_ready) 46 | if len(self.clients) == 1: 47 | raise SystemExit("All slaves have died.") 48 | return results 49 | 50 | def send_import(self, client, task_data): 51 | client.send_bytes(msgpack.packb({"type": MSG_IMPORT, "task": task_data}, use_bin_type=True)) 52 | 53 | def send_node(self, client, task_data): 54 | client.send_bytes(msgpack.packb({"type": MSG_RUN_NODE, "task": task_data}, use_bin_type=True)) 55 | 56 | def send_busy(self, client): 57 | client.send_bytes(msgpack.packb({"type": MSG_BUSY}, use_bin_type=True)) 58 | 59 | 60 | class ClientConnection: 61 | def __init__(self, id, config): 62 | self.id = id 63 | self.address = config.argument_values["work_dir"] + "/slave_socket" 64 | self.sock = self.connect() 65 | self.send_ready() 66 | 67 | def connect(self): 68 | sock = Client(self.address, 'AF_UNIX') 69 | return sock 70 | 71 | def recv(self): 72 | data = self.sock.recv_bytes() 73 | return msgpack.unpackb(data, raw=False, strict_map_key=False) 74 | 75 | def send_ready(self): 76 | self.sock.send_bytes(msgpack.packb({"type": MSG_READY, "client_id": self.id}, use_bin_type=True)) 77 | 78 | def send_new_input(self, data, bitmap, info): 79 | self.sock.send_bytes( 80 | msgpack.packb({"type": MSG_NEW_INPUT, "input": {"payload": data, "bitmap": bitmap, "info": info}}, use_bin_type=True)) 81 | 82 | def send_node_done(self, node_id, results, new_payload): 83 | self.sock.send_bytes(msgpack.packb( 84 | {"type": MSG_NODE_DONE, "node_id": node_id, "results": results, "new_payload": new_payload}, use_bin_type=True)) 85 | -------------------------------------------------------------------------------- /targets/zephyr_x86_32/src/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Intel Corporation 3 | * 4 | * SPDX-License-Identifier: Apache-2.0 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #define _GNU_SOURCE 18 | #include "kafl_user.h" 19 | #include "target.h" 20 | 21 | #ifdef DEBUG 22 | static void test_panic(void) 23 | { 24 | printk("kAFL test_panic()\n"); 25 | 26 | /* panic hook captures all of the following */ 27 | k_panic(); 28 | //k_oops(); 29 | //__ASSERT(0 == 1, "0 == 1"); 30 | //target_entry("KERNELAFLAA", strlen("KERNELAFLAA")); 31 | //target_entry("SERGEJABC", strlen("SERGEJABC")); 32 | 33 | printk("Warning - this code should not be reached!\n"); 34 | } 35 | #endif 36 | 37 | static void agent_init(void *panic_handler, void *kasan_handler) 38 | { 39 | printk("Initiate fuzzer handshake...\n"); 40 | 41 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 42 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 43 | 44 | /* submit panic and optionally kasan handlers for qemu override */ 45 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_PANIC, panic_handler); 46 | 47 | if (kasan_handler) { 48 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_KASAN, kasan_handler); 49 | } 50 | } 51 | 52 | static void agent_run(void) 53 | { 54 | /* 55 | * Heap allocation causes an interesting bug where agent crashes without proper 56 | * detection/handling by the fuzzer..would be good to fix/report any such issues 57 | * to make porting to new targets easier and don't waste cpu on broken threads.. 58 | */ 59 | #ifdef PAYLOAD_ON_HEAP 60 | kAFL_payload* payload_buffer = k_malloc(PAYLOAD_SIZE); 61 | if (!payload_buffer) 62 | return; 63 | #else 64 | uint8_t buffer[PAYLOAD_SIZE]; 65 | kAFL_payload* payload_buffer = (kAFL_payload*)buffer; 66 | #endif 67 | 68 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, payload_buffer); 69 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_CR3, 0); 70 | 71 | target_init(); 72 | 73 | while (1) { 74 | kAFL_hypercall(HYPERCALL_KAFL_NEXT_PAYLOAD, 0); 75 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 76 | #ifdef DEBUG 77 | test_panic(); 78 | #endif 79 | target_entry(payload_buffer->data, payload_buffer->size); 80 | 81 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 82 | } 83 | } 84 | 85 | /* 86 | * That function is weak symbol on Zephyr, just override it with our 87 | * function to notify KVM through hypercall. 88 | */ 89 | void k_sys_fatal_error_handler(unsigned int reason, const z_arch_esf_t *esf) 90 | { 91 | switch (reason) { 92 | case K_ERR_CPU_EXCEPTION: 93 | case K_ERR_KERNEL_OOPS: 94 | case K_ERR_KERNEL_PANIC: 95 | kAFL_hypercall(HYPERCALL_KAFL_PANIC, 0); 96 | break; 97 | default: 98 | kAFL_hypercall(HYPERCALL_KAFL_KASAN, 0); 99 | break; 100 | } 101 | 102 | k_fatal_halt(reason); 103 | } 104 | 105 | void main(void) 106 | { 107 | printk("kAFL Hello World! %s\n\n", CONFIG_BOARD); 108 | 109 | // skip rewrite in favor of custom k_sys_fatal_error_handler() 110 | void* panic_handler = NULL; 111 | void* kasan_handler = NULL; 112 | 113 | printk("Kernel Panic Handler Address:\t%p\n", panic_handler); 114 | 115 | if (kasan_handler){ 116 | printk("Kernel KASAN Handler Address:\t%p\n", kasan_handler); 117 | } 118 | 119 | agent_init(panic_handler, kasan_handler); 120 | agent_run(); 121 | } 122 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/TestDecompressPkg/TestDecompress.c: -------------------------------------------------------------------------------- 1 | /* @file TestDecompress.c 2 | * 3 | * Copyright 2020 Intel Corporation. All rights reserved. 4 | * SPDX-License-Identifier: BSD-2-Clause 5 | * 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | #include 25 | 26 | #define KAFL_VERBOSE 27 | #ifndef KAFL_VERBOSE 28 | #define KAFL_PRINT(...) 29 | #else 30 | #define KAFL_PRINT Print 31 | #endif 32 | 33 | EFI_STATUS EFIAPI RunTestHarness(IN VOID *InputBuffer, IN UINTN InputLength) 34 | { 35 | EFI_STATUS Status; 36 | CHAR8 *Scratch = NULL; 37 | UINT32 ScratchSize; 38 | VOID *Destination = NULL; 39 | UINT32 DestinationSize; 40 | 41 | KAFL_PRINT (L"Start->"); 42 | Status = UefiDecompressGetInfo ( 43 | (CHAR8*)InputBuffer, 44 | InputLength, 45 | &DestinationSize, 46 | &ScratchSize 47 | ); 48 | 49 | if (EFI_ERROR (Status)) { 50 | KAFL_PRINT (L"Error G%d\n", Status); 51 | goto ERROR; 52 | } 53 | 54 | // Allocate scratch buffer 55 | Scratch = AllocateZeroPool (ScratchSize); 56 | if (Scratch == NULL) { 57 | KAFL_PRINT (L"Error A%d\n", Status); 58 | goto ERROR; 59 | } 60 | 61 | /* terribly complicated way of incrementing DestingationSize...who needs this? 62 | Status = SafeUint32Add(DestinationSize, 1, &DestinationSize); 63 | if (EFI_ERROR (Status)) { 64 | KAFL_PRINT (L"Error S%d\n", Status); 65 | goto ERROR; 66 | } 67 | */ 68 | 69 | // Allocate destination buffer, adding an extra page for security! 70 | // Surely this cannot overflow, can it..?! 71 | Destination = AllocateZeroPool (DestinationSize + 1); 72 | if (Destination == NULL) { 73 | KAFL_PRINT (L"Error A%d\n", Status); 74 | goto ERROR; 75 | } 76 | 77 | // Call decompress function 78 | Status = UefiDecompress ( 79 | (CHAR8*)InputBuffer, 80 | Destination, 81 | Scratch 82 | ); 83 | 84 | if (EFI_ERROR (Status)) { 85 | KAFL_PRINT (L"Error D%d\n", Status); 86 | goto ERROR; 87 | } 88 | 89 | KAFL_PRINT (L"Success! %d\n", Status); 90 | ERROR: 91 | if (Scratch != NULL) 92 | FreePool(Scratch); 93 | if (Destination != NULL) 94 | FreePool(Destination); 95 | 96 | return Status; 97 | } 98 | 99 | VOID EFIAPI InitTestHarness(VOID) 100 | { 101 | Print(L"Mapping info: UefiDecompressGetInfo is at %x\n", (void*)(UefiDecompressGetInfo)); 102 | Print(L"Mapping info: DumpCpuContext is at %x\n", (void*)DumpCpuContext); 103 | //Print(L"Mapping info: DumpModuleImageInfo is at %x\n", (void*)DumpModuleImageInfo); 104 | 105 | /* Override target's word with autodetection 106 | * 107 | * Qemu log indicates the target is detected as 32bit even when OVMF+App are 108 | * compiled for X64. This overrides the auto-detection and makes Redqueen 109 | * actually find some bugs instead of just causing timeouts. 110 | */ 111 | #if defined(__x86_64__) 112 | kAFL_hypercall(HYPERCALL_KAFL_USER_SUBMIT_MODE, KAFL_MODE_64); 113 | #endif 114 | } 115 | 116 | -------------------------------------------------------------------------------- /targets/linux_x86_64/src/loader/loader.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of kAFL. 3 | * 4 | * Copyright 2017 Sergej Schumilo 5 | * SPDX-License-Identifier: MIT 6 | */ 7 | 8 | #define _GNU_SOURCE 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include "kafl_user.h" 17 | 18 | static inline uint64_t get_address(char* identifier) 19 | { 20 | FILE * fp; 21 | char * line = NULL; 22 | ssize_t read; 23 | ssize_t len; 24 | char *tmp; 25 | uint64_t address = 0x0; 26 | uint8_t identifier_len = strlen(identifier); 27 | 28 | fp = fopen("/proc/kallsyms", "r"); 29 | if (fp == NULL){ 30 | return address; 31 | } 32 | 33 | while ((read = getline(&line, &len, fp)) != -1) { 34 | if(strlen(line) > identifier_len && !strcmp(line + strlen(line) - identifier_len, identifier)){ 35 | address = strtoull(strtok(line, " "), NULL, 16); 36 | break; 37 | } 38 | } 39 | 40 | fclose(fp); 41 | if (line){ 42 | free(line); 43 | } 44 | return address; 45 | } 46 | 47 | 48 | static inline void load_programm(void* buf){ 49 | int payload_file; 50 | char* newenviron[] = {NULL}; 51 | char* newargv[] = {TARGET_FILE, NULL}; 52 | 53 | payload_file = open(TARGET_FILE, O_RDWR | O_CREAT | O_SYNC, 0777); 54 | write(payload_file, buf, PROGRAM_SIZE); 55 | close(payload_file); 56 | payload_file = open(TARGET_FILE, O_RDONLY); 57 | fexecve(payload_file, newargv, newenviron); 58 | } 59 | 60 | int main(int argc, char** argv) 61 | { 62 | uint64_t panic_handler = 0x0; 63 | uint64_t kasan_handler = 0x0; 64 | void* program_buffer; 65 | 66 | printf("<< kAFL Usermode Load for Linux x86-64 >>\n"); 67 | 68 | if(geteuid()){ 69 | printf("Loader requires root privileges...\n"); 70 | return 1; 71 | } 72 | 73 | panic_handler = get_address("T panic\n"); 74 | printf("Kernel Panic Handler Address:\t%lx\n", panic_handler); 75 | 76 | kasan_handler = get_address("t kasan_report_error\n"); 77 | if (kasan_handler){ 78 | printf("Kernel KASAN Handler Address:\t%lx\n", kasan_handler); 79 | } 80 | 81 | /* allocate 4MB contiguous virtual memory to hold fuzzer program; data is provided by the fuzzer */ 82 | program_buffer = mmap((void*)0xabcd0000, PROGRAM_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 83 | 84 | if (!program_buffer) { 85 | printf("Loader could not mmap() program buffer..\n"); 86 | return 1; 87 | } 88 | 89 | /* ensure that the virtual memory is *really* present in physical memory... */ 90 | memset(program_buffer, 0xff, PROGRAM_SIZE); 91 | 92 | /* this hypercall will generate a VM snapshot for the fuzzer and subsequently terminate QEMU */ 93 | kAFL_hypercall(HYPERCALL_KAFL_LOCK, 0); 94 | 95 | 96 | /***** Fuzzer Entrypoint *****/ 97 | 98 | 99 | /* initial fuzzer handshake */ 100 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 101 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 102 | /* submit panic address */ 103 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_PANIC, panic_handler); 104 | /* submit KASan address */ 105 | if (kasan_handler){ 106 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_KASAN, kasan_handler); 107 | } 108 | /* submit virtual address of program buffer and wait for data (*blocking*) */ 109 | kAFL_hypercall(HYPERCALL_KAFL_GET_PROGRAM, (uint64_t)program_buffer); 110 | /* execute fuzzer program */ 111 | load_programm(program_buffer); 112 | /* bye */ 113 | return 0; 114 | } 115 | -------------------------------------------------------------------------------- /targets/windows_x86_64-userspace/src/selffuzz_test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "kafl_user.h" 3 | 4 | void fuzzme(uint8_t*, int); 5 | void end(); 6 | 7 | 8 | static inline void panic(void){ 9 | kAFL_hypercall(HYPERCALL_KAFL_PANIC, (uintptr_t)0x1); 10 | while(1){}; /* halt */ 11 | } 12 | 13 | 14 | int main(int argc, char** argv){ 15 | hprintf("[+] Starting... %s\n", argv[0]); 16 | 17 | hprintf("[+] Allocating buffer for kAFL_payload struct\n"); 18 | kAFL_payload* payload_buffer = (kAFL_payload*)VirtualAlloc(0, PAYLOAD_SIZE, MEM_COMMIT, PAGE_READWRITE); 19 | 20 | if (!VirtualLock(payload_buffer, PAYLOAD_SIZE)){ 21 | hprintf("[+] WARNING: Virtuallock failed on payload buffer %lp...\n", payload_buffer); 22 | kAFL_hypercall(HYPERCALL_KAFL_USER_ABORT, 0); 23 | } 24 | 25 | hprintf("[+] Memset kAFL_payload at address %lx (size %d)\n", (uint64_t) payload_buffer, PAYLOAD_SIZE); 26 | memset(payload_buffer, 0xff, PAYLOAD_SIZE); 27 | 28 | hprintf("[+] Submitting buffer address to hypervisor...\n"); 29 | kAFL_hypercall(HYPERCALL_KAFL_GET_PAYLOAD, (UINT64)payload_buffer); 30 | 31 | kAFL_ranges* range_buffer = (kAFL_ranges*)VirtualAlloc(NULL, 0x1000, MEM_COMMIT, PAGE_READWRITE); 32 | memset(range_buffer, 0xff, 0x1000); 33 | 34 | hprintf("[+] range buffer %lx...\n", (UINT64)range_buffer); 35 | kAFL_hypercall(HYPERCALL_KAFL_USER_RANGE_ADVISE, (UINT64)range_buffer); 36 | 37 | hprintf("[+] Locking fuzzing ranges...\n"); 38 | for(int i = 0; i < 4; i++){ 39 | hprintf("[+] Range %d enabled: %x\t(%p-%p)\n", i, (uint8_t)range_buffer->enabled[i], range_buffer->ip[i], range_buffer->size[i]); 40 | if (range_buffer->ip[i] != 0){ 41 | if (!VirtualLock((LPVOID)range_buffer->ip[i], range_buffer->size[i])){ 42 | hprintf("[+] WARNING: VirtualLock failed on range %d...\n", (uint8_t)range_buffer->enabled[i]); 43 | kAFL_hypercall(HYPERCALL_KAFL_USER_ABORT, 0); 44 | } 45 | else{ 46 | hprintf("[+] Range %d locked\n", (uint8_t)range_buffer->enabled[i]); 47 | } 48 | } 49 | } 50 | 51 | kAFL_hypercall(HYPERCALL_KAFL_USER_SUBMIT_MODE, KAFL_MODE_64); 52 | 53 | hprintf("[+] Range: 0x%p-0x%p\n", fuzzme, end); 54 | 55 | while(1){ 56 | kAFL_hypercall(HYPERCALL_KAFL_USER_FAST_ACQUIRE, 0); 57 | fuzzme(payload_buffer->data, payload_buffer->size); 58 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 59 | } 60 | return 0; 61 | } 62 | 63 | 64 | void fuzzme(uint8_t* input, int size){ 65 | if (size > 0x11){ 66 | if(input[0] == 'K') 67 | if(input[1] == '3') 68 | if(input[2] == 'r') 69 | if(input[3] == 'N') 70 | if(input[4] == '3') 71 | if(input[5] == 'l') 72 | if(input[6] == 'A') 73 | if(input[7] == 'F') 74 | if(input[8] == 'L') 75 | if(input[9] == '#') 76 | panic(); 77 | 78 | if(input[0] == 'P') 79 | if(input[1] == 'w') 80 | if(input[2] == 'n') 81 | if(input[3] == 'T') 82 | if(input[4] == '0') 83 | if(input[5] == 'w') 84 | if(input[6] == 'n') 85 | if(input[7] == '!') 86 | panic(); 87 | 88 | } 89 | }; 90 | 91 | void end(){} 92 | 93 | -------------------------------------------------------------------------------- /targets/uefi_ovmf_64/kAFLAgentPkg/Include/Library/kAFLAgentLib.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2019 Sergej Schumilo, Cornelius Aschermann 3 | * Copyright 2020 Intel Corporation 4 | * 5 | * SPDX-License-Identifier: BSD-2-Clause 6 | */ 7 | 8 | #ifndef _KAFL_AGENT_LIB_H_ 9 | #define _KAFL_AGENT_LIB_H_ 10 | 11 | /****************************************************************************** 12 | * High-level Harness API 13 | *****************************************************************************/ 14 | 15 | /* 16 | * One-time initialization function 17 | * 18 | * Called once after fuzzing handshake to check/initialize any dependencies 19 | */ 20 | VOID 21 | EFIAPI 22 | InitTestHarness (VOID); 23 | 24 | /* 25 | * Execute on a single fuzzing input 26 | * 27 | * In persistent fuzzing, this is called many thousand times. 28 | * Any side-effects/context must be reset on re-entry. 29 | */ 30 | EFI_STATUS 31 | EFIAPI 32 | RunTestHarness ( 33 | IN VOID *TestBuffer, 34 | IN UINTN TestBufferSize 35 | ); 36 | 37 | /****************************************************************************** 38 | * Low-level kAFL API 39 | *****************************************************************************/ 40 | #include 41 | #include 42 | 43 | #ifndef uint64_t 44 | #define uint64_t UINT64 45 | #endif 46 | #ifndef uint32_t 47 | #define uint32_t UINT32 48 | #endif 49 | #ifndef int32_t 50 | #define int32_t INT32 51 | #endif 52 | #ifndef uint8_t 53 | #define uint8_t UINT8 54 | #endif 55 | #ifndef u_long 56 | #define u_long UINT64 57 | #endif 58 | 59 | #ifndef uint_ptr 60 | #if defined(__i386__) 61 | #define uint_ptr uint32_t 62 | #elif defined(__x86_64__) 63 | #define uint_ptr uint64_t 64 | #endif 65 | #endif 66 | 67 | #define HYPERCALL_KAFL_RAX_ID 0x01f 68 | #define HYPERCALL_KAFL_ACQUIRE 0 69 | #define HYPERCALL_KAFL_GET_PAYLOAD 1 70 | #define HYPERCALL_KAFL_GET_PROGRAM 2 71 | #define HYPERCALL_KAFL_GET_ARGV 3 72 | #define HYPERCALL_KAFL_RELEASE 4 73 | #define HYPERCALL_KAFL_SUBMIT_CR3 5 74 | #define HYPERCALL_KAFL_SUBMIT_PANIC 6 75 | #define HYPERCALL_KAFL_SUBMIT_KASAN 7 76 | #define HYPERCALL_KAFL_PANIC 8 77 | #define HYPERCALL_KAFL_KASAN 9 78 | #define HYPERCALL_KAFL_LOCK 10 79 | #define HYPERCALL_KAFL_INFO 11 80 | #define HYPERCALL_KAFL_NEXT_PAYLOAD 12 81 | #define HYPERCALL_KAFL_PRINTF 13 82 | #define HYPERCALL_KAFL_PRINTK_ADDR 14 83 | #define HYPERCALL_KAFL_PRINTK 15 84 | 85 | /* user space only hypercalls */ 86 | #define HYPERCALL_KAFL_USER_RANGE_ADVISE 16 87 | #define HYPERCALL_KAFL_USER_SUBMIT_MODE 17 88 | #define HYPERCALL_KAFL_USER_FAST_ACQUIRE 18 89 | /* 19 is already used for exit reason KVM_EXIT_KAFL_TOPA_MAIN_FULL */ 90 | #define HYPERCALL_KAFL_USER_ABORT 20 91 | #define HYPERCALL_KAFL_TIMEOUT 21 92 | 93 | #define PAYLOAD_SIZE (128 << 10) /* up to 128KB payloads */ 94 | #define PROGRAM_SIZE (128 << 20) /* kAFL supports 128MB programm data */ 95 | #define INFO_SIZE (128 << 10) /* 128KB info string */ 96 | 97 | typedef struct{ 98 | int32_t size; 99 | uint8_t data[PAYLOAD_SIZE-sizeof(int32_t)-sizeof(uint8_t)]; 100 | uint8_t redqueen_mode; 101 | } kAFL_payload; 102 | 103 | typedef struct{ 104 | uint64_t ip[4]; 105 | uint64_t size[4]; 106 | uint8_t enabled[4]; 107 | } kAFL_ranges; 108 | 109 | #define KAFL_MODE_64 0 110 | #define KAFL_MODE_32 1 111 | #define KAFL_MODE_16 2 112 | 113 | #if defined(__i386__) 114 | void kAFL_hypercall(uint32_t rbx, uint32_t rcx); 115 | #elif defined(__x86_64__) 116 | void kAFL_hypercall(uint64_t rbx, uint64_t rcx); 117 | #endif 118 | 119 | #endif /* _KAFL_AGENT_LIB_H_ */ 120 | -------------------------------------------------------------------------------- /targets/windows_x86_64/src/info/info.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "kafl_user.h" 7 | 8 | #define ARRAY_SIZE 1024 9 | #define INFO_SIZE (128 << 10) 10 | 11 | PCSTR ntoskrnl = "C:\\Windows\\System32\\ntoskrnl.exe"; 12 | PCSTR kernel_func = "PsCreateSystemThread"; 13 | 14 | typedef NTSTATUS(NTAPI* _NtQuerySystemInformation)( 15 | ULONG SystemInformationClass, 16 | PVOID SystemInformation, 17 | ULONG SystemInformationLength, 18 | PULONG ReturnLength 19 | ); 20 | 21 | FARPROC KernGetProcAddress(HMODULE kern_base, LPCSTR function) { 22 | HMODULE kernel_base_in_user_mode = LoadLibraryA(ntoskrnl); 23 | return (FARPROC)((PUCHAR)GetProcAddress(kernel_base_in_user_mode, function) - (PUCHAR)kernel_base_in_user_mode + (PUCHAR)kern_base); 24 | } 25 | 26 | typedef struct _RTL_PROCESS_MODULE_INFORMATION 27 | { 28 | HANDLE Section; 29 | PVOID MappedBase; 30 | PVOID ImageBase; 31 | ULONG ImageSize; 32 | ULONG Flags; 33 | USHORT LoadOrderIndex; 34 | USHORT InitOrderIndex; 35 | USHORT LoadCount; 36 | USHORT OffsetToFileName; 37 | UCHAR FullPathName[256]; 38 | } RTL_PROCESS_MODULE_INFORMATION, * PRTL_PROCESS_MODULE_INFORMATION; 39 | 40 | typedef struct _RTL_PROCESS_MODULES 41 | { 42 | ULONG NumberOfModules; 43 | RTL_PROCESS_MODULE_INFORMATION Modules[1]; 44 | } RTL_PROCESS_MODULES, * PRTL_PROCESS_MODULES; 45 | 46 | int main(void) { 47 | HMODULE hNtdll = LoadLibraryA("c:\\windows\\system32\\ntdll.dll"); 48 | _NtQuerySystemInformation NtQuerySystemInformation = (_NtQuerySystemInformation)(GetProcAddress(hNtdll, "NtQuerySystemInformation")); 49 | 50 | char* info_buffer = (char*)VirtualAlloc(0, INFO_SIZE, MEM_COMMIT, PAGE_READWRITE); 51 | memset(info_buffer, 0xff, INFO_SIZE); 52 | memset(info_buffer, 0x00, INFO_SIZE); 53 | int pos = 0; 54 | 55 | LPVOID drivers[ARRAY_SIZE]; 56 | DWORD cbNeeded; 57 | int cDrivers, i; 58 | NTSTATUS status; 59 | 60 | if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers)) 61 | { 62 | TCHAR szDriver[ARRAY_SIZE]; 63 | 64 | cDrivers = cbNeeded / sizeof(drivers[0]); 65 | PRTL_PROCESS_MODULES ModuleInfo; 66 | 67 | ModuleInfo = (PRTL_PROCESS_MODULES)VirtualAlloc(NULL, 1024 * 1024, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); 68 | 69 | if (!ModuleInfo) { 70 | goto fail; 71 | } 72 | 73 | if (!NT_SUCCESS(status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)11, ModuleInfo, 1024 * 1024, NULL))) { 74 | VirtualFree(ModuleInfo, 0, MEM_RELEASE); 75 | goto fail; 76 | } 77 | 78 | pos += sprintf(info_buffer + pos, "kAFL Windows x86-64 Kernel Addresses (%d Drivers)\n\n", cDrivers); 79 | //_tprintf(TEXT("kAFL Windows x86-64 Kernel Addresses (%d Drivers)\n\n"), cDrivers); 80 | pos += sprintf(info_buffer + pos, "START-ADDRESS\t\tEND-ADDRESS\t\tDRIVER\n"); 81 | //_tprintf(TEXT("START-ADDRESS\t\tEND-ADDRESS\t\tDRIVER\n")); 82 | for (i = 0; i < cDrivers; i++) { 83 | pos += sprintf(info_buffer + pos, "0x%p\t0x%p\t%s\n", drivers[i], ((UINT64)drivers[i]) + ModuleInfo->Modules[i].ImageSize, ModuleInfo->Modules[i].FullPathName + ModuleInfo->Modules[i].OffsetToFileName); 84 | //_tprintf(TEXT("0x%p\t0x%p\t%s\n"), drivers[i], drivers[i]+ModuleInfo->Modules[i].ImageSize, ModuleInfo->Modules[i].FullPathName+ModuleInfo->Modules[i].OffsetToFileName); 85 | } 86 | } 87 | else { 88 | goto fail; 89 | } 90 | 91 | fail: 92 | kAFL_hypercall(HYPERCALL_KAFL_INFO, (UINT64)info_buffer); 93 | 94 | printf(info_buffer); 95 | return 0; 96 | } 97 | 98 | -------------------------------------------------------------------------------- /tests/user_bench/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Helper script to fetch / build a couple sample targets 4 | # 5 | # Copyright 2019-2020 Intel Corporation 6 | # SPDX-License-Identifier: MIT 7 | # 8 | 9 | set -e 10 | 11 | TARGET_ROOT="$(dirname ${PWD}/${0})" 12 | [ -n "$KAFL_ROOT" ] || KAFL_ROOT=${PWD} 13 | 14 | PACKAGES="$TARGET_ROOT/builds" 15 | BIN_DIR="$TARGET_ROOT/targets" 16 | JOBS=$((2*`nproc`)) 17 | 18 | test -d "$PACKAGES" || mkdir -p "$PACKAGES" || echo "Failed creating target workdir $PACKAGES. Exit" 19 | 20 | build_confmake() 21 | { 22 | URL="$1" 23 | TARBALL="$(basename $URL)" 24 | SRC_DIR=$(echo $TARBALL|sed "s/.tar.*//") 25 | 26 | test -f $TARBALL || wget -O $TARBALL "$URL" 27 | test -d $SRC_DIR || tar -xf $TARBALL 28 | 29 | test -d $SRC_DIR || echo "Error: Extracting $TARBALL did not yield expected dir $SRC_DIR. Exit" 30 | test -d $SRC_DIR || exit 31 | 32 | pushd $SRC_DIR > /dev/null 33 | echo "Performing configure/make for $SRC_DIR. This may take a moment.." 34 | ./configure --without-threads --disable-shared > /dev/null 35 | make -j $JOBS > /dev/null 36 | popd > /dev/null 37 | 38 | echo "Done compiling, copying target binaries..." 39 | } 40 | 41 | build_cmake() 42 | { 43 | URL="$1" 44 | TARBALL="$(basename $URL)" 45 | SRC_DIR=$(echo $TARBALL|sed "s/.tar.*//") 46 | 47 | test -f $TARBALL || wget -O $TARBALL "$URL" 48 | test -d $SRC_DIR || tar -xf $TARBALL 49 | 50 | test -d $SRC_DIR || echo "Error: Extracting $TARBALL did not yield expected dir $SRC_DIR. Exit" 51 | test -d $SRC_DIR || exit 52 | 53 | pushd $SRC_DIR > /dev/null 54 | echo "Performing configure/make for $SRC_DIR. This may take a moment.." 55 | cmake . -DENABLE_SHARED=0 > /dev/null 56 | make -j $JOBS 57 | popd > /dev/null 58 | } 59 | 60 | fetch_lava() 61 | { 62 | # fetch precompiled version of LAVA-M 63 | # http://moyix.blogspot.com/2016/10/the-lava-synthetic-bug-corpora.html 64 | URL="https://sites.google.com/site/steelix2017/home/lava/lava.zip" 65 | ZIPFILE="$(basename $URL)" 66 | SRC_DIR=$(echo $ZIPFILE|sed "s/.zip.*//") 67 | 68 | test -f $ZIPFILE || wget -O $ZIPFILE "$URL" 69 | test -d $SRC_DIR || unzip $ZIPFILE lava/* 70 | 71 | test -d $SRC_DIR || echo "Error: Extracting $ZIPFILE did not yield expected dir $SRC_DIR. Exit" 72 | test -d $SRC_DIR || exit 73 | } 74 | 75 | pushd "$PACKAGES" > /dev/null 76 | TARGET="$1" 77 | case $TARGET in 78 | "nasm") 79 | build_confmake "https://www.nasm.us/pub/nasm/releasebuilds/2.14.02/nasm-2.14.02.tar.xz" 80 | cp -v $SRC_DIR/$TARGET $BIN_DIR 81 | ;; 82 | "bison") 83 | build_confmake "https://ftp.gnu.org/gnu/bison/bison-3.5.tar.xz" 84 | cp -v $SRC_DIR/src/$TARGET $BIN_DIR 85 | ;; 86 | "binutils") 87 | sudo apt-get install texinfo 88 | build_confmake "https://ftp.gnu.org/gnu/binutils/binutils-2.34.tar.xz" 89 | cp -v $SRC_DIR/binutils/{cxxfilt,size,readelf,objdump,ar} $BIN_DIR 90 | cp -v $SRC_DIR/binutils/nm-new $BIN_DIR 91 | ;; 92 | "djpeg") 93 | build_cmake "https://sourceforge.net/projects/libjpeg-turbo/files/2.0.4/libjpeg-turbo-2.0.4.tar.gz" 94 | cp -v $SRC_DIR/djpeg-static $BIN_DIR/djpeg 95 | ;; 96 | "pngtest") 97 | build_confmake "https://download.sourceforge.net/libpng/libpng-1.6.37.tar.xz" 98 | cp -v $SRC_DIR/pngtest $BIN_DIR 99 | ;; 100 | "xmllint") 101 | build_confmake "http://xmlsoft.org/sources/libxml2-2.9.9.tar.gz" 102 | cp -v $SRC_DIR/xmllint $BIN_DIR 103 | ;; 104 | "lava") 105 | fetch_lava 106 | for bin in base64 who md5sum uniq; do 107 | cp -v $SRC_DIR/bins/$bin $BIN_DIR/lava_$bin 108 | done 109 | ;; 110 | *) 111 | echo "Usage: $0 " 112 | echo 113 | echo "Currently enabled targets: nasm, bison, binutils, djpeg, lava." 114 | echo 115 | ;; 116 | esac 117 | 118 | popd > /dev/null 119 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/trim.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | AFL-style trim algorithms (init stage) 8 | """ 9 | 10 | from fuzzer.bitmap import GlobalBitmap 11 | 12 | MAX_EXECS = 16 13 | MAX_ROUNDS = 32 14 | MIN_SIZE = 32 15 | APPEND_VALUE = 0.1 16 | 17 | APPEND_BYTES = 16 18 | 19 | pow2_values = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768] 20 | 21 | 22 | def get_pow2_value(value): 23 | for pow2_value in reversed(pow2_values): 24 | if pow2_value <= value: 25 | return pow2_value 26 | return 1 27 | 28 | 29 | def check_trim_still_valid(old_node, old_res, new_res): 30 | # non-det input 31 | if not new_res: 32 | return False 33 | if not new_res.is_lut_applied(): 34 | new_res.apply_lut() 35 | trim_simple = False 36 | if trim_simple: 37 | assert False # todo fixme wrt to bitmaps, == doesnt work on bitmap_wrapper 38 | return old_res == new_res 39 | else: 40 | old_bits = old_node["new_bytes"].copy() 41 | old_bits.update(old_node["new_bits"]) 42 | return GlobalBitmap.all_new_bits_still_set(old_bits, new_res) 43 | 44 | 45 | def perform_center_trim(payload, old_node, send_handler, trimming_bytes): 46 | index = 0 47 | 48 | old_res, _ = send_handler(payload, label="center_trim_funky") 49 | if old_res.is_crash(): 50 | return payload 51 | 52 | while index < len(payload): 53 | test_payload = payload[0: index] + payload[index + trimming_bytes:] 54 | exec_res, _ = send_handler(test_payload, label="center_trim") 55 | 56 | if check_trim_still_valid(old_node, old_res, exec_res): 57 | payload = test_payload[:] 58 | else: 59 | index += trimming_bytes 60 | 61 | return payload 62 | 63 | 64 | def perform_trim(payload, old_node, send_handler): 65 | global MAX_ROUNDS, MAX_EXECS, MIN_SIZE, APPEND_BYTES 66 | if len(payload) <= MIN_SIZE: 67 | return payload 68 | 69 | old_res, _ = send_handler(payload, label="trim_funky") 70 | if old_res.is_crash(): 71 | return payload 72 | 73 | execs = 0 74 | new_size = len(payload) 75 | 76 | for _ in range(MAX_ROUNDS): 77 | abort = True 78 | for i in reversed(range(0, pow2_values.index(get_pow2_value(new_size)) + 1)): 79 | if pow2_values[i] < new_size: 80 | 81 | execs += 1 82 | if execs == MAX_EXECS: 83 | abort = True 84 | break 85 | 86 | new_res, _ = send_handler(payload[0:new_size - pow2_values[i]], label="trim") 87 | 88 | if new_res.is_crash(): 89 | return payload[0:new_size] 90 | 91 | if check_trim_still_valid(old_node, old_res, new_res): 92 | new_size -= pow2_values[i] 93 | abort = False 94 | break 95 | 96 | if new_size <= MIN_SIZE: 97 | break 98 | 99 | if abort: 100 | break 101 | 102 | new_size_backup = new_size 103 | if new_size < MIN_SIZE: 104 | new_size = MIN_SIZE 105 | elif (new_size + int(new_size * APPEND_VALUE)) < len(payload): 106 | new_size += int(new_size * APPEND_VALUE) 107 | 108 | new_size += APPEND_BYTES 109 | 110 | new_res, _ = send_handler(payload[0:new_size], label="trim") 111 | if not check_trim_still_valid(old_node, old_res, new_res): 112 | return payload[0:min(new_size_backup, len(payload))] 113 | 114 | return payload[0:min(new_size, len(payload))] 115 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/interesting_values.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | AFL-style 'interesting values' mutations (deterministic stage). 8 | """ 9 | 10 | from fuzzer.technique.helper import * 11 | from binascii import hexlify 12 | 13 | 14 | def mutate_seq_8_bit_interesting(data, func, skip_null=False, effector_map=None, verbose=False): 15 | 16 | label="afl_int_1" 17 | for i in range(0, len(data)): 18 | if effector_map: 19 | if not effector_map[i]: 20 | continue 21 | 22 | orig = data[i] 23 | 24 | if skip_null and orig == 0: 25 | continue 26 | 27 | for j in range(len(interesting_8_Bit)): 28 | value = in_range_8(interesting_8_Bit[j]) 29 | if (is_not_bitflip(orig ^ value) and 30 | is_not_arithmetic(orig, value, 1)): 31 | data[i] = value 32 | func(data, label=label) 33 | 34 | data[i] = orig 35 | 36 | 37 | def mutate_seq_16_bit_interesting(data, func, skip_null=False, effector_map=None, arith_max=AFL_ARITH_MAX, verbose=False): 38 | 39 | label="afl_int_2" 40 | for i in range(len(data) - 1): 41 | if effector_map: 42 | if not (effector_map[i] or effector_map[i + 1]): 43 | continue 44 | 45 | orig = data[i:i+2] 46 | oval = struct.unpack('H", num1) 66 | func(data, label=label) 67 | 68 | data[i:i+2] = orig 69 | 70 | 71 | def mutate_seq_32_bit_interesting(data, func, skip_null=False, effector_map=None, arith_max=AFL_ARITH_MAX, verbose=False): 72 | 73 | label="afl_int_4" 74 | for i in range(len(data) - 3): 75 | if effector_map: 76 | if effector_map[i:i+4] == b'\x00\x00\x00\x00': 77 | continue 78 | 79 | orig = data[i:i+4] 80 | oval = struct.unpack('= 32 ){ 23 | int counter = 0; 24 | int i = 0; 25 | for(i = 0; i= 32 ){ 39 | if( as_u64(input) == calc_hash( (uint8_t*)input+8, len-8 ) ){ 40 | if(input[8] == 'H'){ 41 | if(input[9] == 'A'){ 42 | if(input[10] == 'S'){ 43 | if(input[11] == 'H'){ 44 | test_panic("HASH CHECK...\n"); /* boom! bug incoming... */ 45 | }}}}}} 46 | return 0; 47 | } 48 | 49 | char test_hash2(char* input, size_t len){ 50 | if(len >= 32 ){ 51 | if( as_u64(input) == calc_hash( (uint8_t*)input+8, len-8 ) ){ 52 | if( as_u64(input+8) == calc_hash( (uint8_t*)input+16, len-16 ) ){ 53 | if(input[16] == 'H'){ 54 | if(input[17] == 'A'){ 55 | if(input[18] == 'S'){ 56 | if(input[19] == 'H'){ 57 | if(input[20] == '2'){ 58 | test_panic("HASH2 CHECK...\n"); /* boom! bug incoming... */ 59 | }}}}}}}} 60 | return 0; 61 | } 62 | 63 | char test_se(char* input, size_t len){ 64 | char* data = "0123456789abcdef"; 65 | if(len >= 32 ){ 66 | if(as_u64(input)==as_u64("MAGICHDR")){ 67 | if(as_u64(input+8) * as_u64(input+8) == 857665508961587041ULL){ // "1337\0\0\0\0".unpack ** 2 68 | if(as_u64(input+16)<=32){ 69 | return data[as_u64(input+16)]; 70 | } else { 71 | test_panic("SE MULT INVERSION...\n"); /* boom! bug incoming... */ 72 | } 73 | } 74 | } 75 | } 76 | return 0; 77 | } 78 | 79 | char test_feedback(char* input, size_t len){ 80 | int *array = (int *)test_malloc(1332); 81 | //int *array = (int *)kmalloc(1332, GFP_KERNEL); 82 | if(len >= 32){ 83 | if(input[0] == 'K') 84 | if(input[1] == 'E') 85 | if(input[2] == 'R') 86 | if(input[3] == 'N') 87 | if(input[4] == 'E') 88 | if(input[5] == 'L') 89 | if(input[6] == 'A') 90 | if(input[7] == 'F') 91 | if(input[8] == 'L') 92 | test_panic("KAFL...\n"); /* boom! bug incoming... */ 93 | if(input[0] == 'S') 94 | if(input[1] == 'E') 95 | if(input[2] == 'R') 96 | if(input[3] == 'G') 97 | if(input[4] == 'E') 98 | if(input[5] == 'J') 99 | test_panic("SERGEJ...\n"); 100 | 101 | if(input[0] == 'K'){ 102 | if(input[1] == 'A'){ 103 | if(input[2] == 'S'){ 104 | if(input[3] == 'A'){ 105 | if(input[4] == 'N'){ 106 | test_free(array); 107 | array[0] = 1234; 108 | } 109 | } 110 | } 111 | } 112 | } 113 | } 114 | test_free(array); 115 | return 0; 116 | } 117 | 118 | void test(char* input, size_t len){ 119 | if(len >= 32){ 120 | switch(input[0]){ 121 | case('F'): test_feedback(input+1,len-1); break; 122 | case('S'): test_se(input+1,len-1); break; 123 | case('H'): test_hash(input+1,len-1); break; 124 | case('J'): test_hash2(input+1,len-1); break; 125 | case('L'): test_loop(input+1,len-1); break; 126 | case('X'): return; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/scheduler.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2020 Intel Corporation 2 | # SPDX-License-Identifier: AGPL-3.0-or-later 3 | 4 | """ 5 | Funny Experimental Scheduler. Appears better than original kAFL 6 | scheduler especially for slow targets. 7 | 8 | Idea is to favorize nodes based on speed, depth, number of new edges. Weights 9 | are tuned such that initial/redq/grim stages are processed first for all fav 10 | nodes, then non-favs start getting processed while at the same time the 11 | high-scoring fav nodes will also go through deterministic stages. Particularly 12 | strong fav nodes may overcome the stage buff and go all the way to havoc before 13 | others are done. 14 | 15 | Queue sorting can become a bottleneck on large queues or very fast 16 | execution/finding rate. 17 | 18 | """ 19 | 20 | 21 | from fuzzer.technique.helper import rand 22 | from math import log, log2, ceil 23 | 24 | # scale arbitrarily large / small inputs down to interval [1,scale] 25 | # supply alternative log to get a better fit 26 | def log_scale(value, scale=1, base=2): 27 | 28 | if value <= base: 29 | return 1 30 | 31 | if base == 2: 32 | val = log2(value) 33 | else: 34 | val = log(value, base) 35 | 36 | return ceil(scale*val-scale+1) 37 | 38 | 39 | class Scheduler: 40 | 41 | def __init__(self): 42 | pass 43 | 44 | # TODO: node skipping by p(x) conflicts with queue sorting.. 45 | def should_be_scheduled(self, queue, node): 46 | SKIP_CRASHING_PROB = 80 47 | SKIP_NONFAV_PROB = 50 48 | 49 | if node.get_exit_reason() != "regular": 50 | if rand.int(100) < SKIP_CRASHING_PROB: 51 | return False 52 | 53 | if node.get_state() == "final": 54 | if not node.is_favorite() and rand.int(100) < SKIP_NONFAV_PROB: 55 | return False 56 | return True 57 | 58 | def score_impact(self, node): 59 | # each fav bit counts 8 times the depth level 60 | impact = 8*len(node.get_fav_bits()) + node.get_level() 61 | return log_scale(impact, scale=5) 62 | 63 | def score_speed(self, node): 64 | p_len = node.get_payload_len() 65 | p_len = 1 if p_len == 0 else p_len 66 | return log_scale(10000/(node.get_performance()*p_len), scale=6, base=256) 67 | 68 | def score_priority_favs(self, node): 69 | score = node.get_fav_factor() # score_speed() 70 | 71 | # below stage buffs are invalid for busy nodes. 72 | # sort in with nodes as these are the only ones we can process in parallel 73 | if node.is_busy() or node.get_exit_reason() != "regular": 74 | return (1, score) 75 | 76 | # boost nodes deeper in the tree 77 | if node.get_level() > 0: 78 | score += node.get_level()//5 79 | 80 | # boost nodes with many fav bits 81 | if node.is_favorite(): 82 | score += 2*len(node.get_fav_bits()) 83 | 84 | # TODO: only actually have to compute all this for new nodes and fav bit changes... 85 | node.set_score(score) 86 | 87 | if node.get_state() in ["initial", "redq/grim"]: 88 | phase = 256 89 | elif node.get_state() in ["deterministic"]: 90 | phase = 8 91 | elif node.get_state() in ["havoc"]: 92 | phase = 1 93 | elif node.get_state() in ["final"]: 94 | # promote later discovered nodes by compensating for total time spend in havoc. 95 | # TODO some nodes are buffed on purpose - should only promote based on relative 96 | # time or cycles rather than total face time 97 | time_spent = node.node_struct.get("state_time_havoc",1) 98 | score = score/log_scale(time_spent) 99 | return (1, score) 100 | else: 101 | assert(False), "unknown state" 102 | 103 | # first solve all initial phases, and highest-ranking score/impact there 104 | return (score*phase, score) 105 | 106 | -------------------------------------------------------------------------------- /tests/user_bench/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Helper script to package and launch Linux userspace binaries. 4 | # Targets are packed in a Linux initrd and launched via Qemu -kernel -initrd 5 | # 6 | # This script assumes a binary and corresponding .env file in bins/. 7 | # Basic shared libraries are automatically copied from the host system into the initrd. 8 | # 9 | # Copyright 2019-2020 Intel Corporation 10 | # SPDX-License-Identifier: MIT 11 | # 12 | 13 | set -e 14 | 15 | TARGET_ROOT="$(dirname ${PWD}/${0})" 16 | [ -n "$KAFL_ROOT" ] || KAFL_ROOT=${PWD} 17 | 18 | # Grab a Linux kernel to boot... current running image will do.. 19 | LINUX_KERNEL="/boot/vmlinuz-5.6.0-1-amd64" 20 | LINUX_KERNEL="/boot/vmlinuz-$(uname -r)" 21 | KAFL_FUZZ_OPTIONS="-p $(nproc) -forkserver" 22 | 23 | target_pack() 24 | { 25 | echo "[*] Packing target >>$TARGET<<" 26 | 27 | rm -rf "$PACKDIR" 28 | mkdir -p "$PACKDIR" 29 | 30 | bash ./targets/linux_x86_64-userspace/compile.sh 31 | 32 | # default env - input file as single argument 33 | TARGET_ARGS="/input.bin" 34 | TARGET_FILE="/input.bin" 35 | test -f "$BIN_DIR/$TARGET.env" && source "$BIN_DIR/$TARGET.env" 36 | 37 | readelf -h $BIN_DIR/$TARGET |grep -q ELF64 && TARGET_ARCH=m64 38 | readelf -h $BIN_DIR/$TARGET |grep -q ELF32 && TARGET_ARCH=m32 39 | 40 | # TODO: shell script would be much easier than python? 41 | python3 kAFL-Fuzzer/kafl_user_prepare.py \ 42 | --recompile \ 43 | -args="$TARGET_ARGS" \ 44 | -file="$TARGET_FILE" \ 45 | "$BIN_DIR/$TARGET" \ 46 | "$PACKDIR/" $TARGET_ARCH 47 | 48 | bash targets/linux_x86_64-userspace/initrd/pack.sh \ 49 | "$PACKDIR/${TARGET}_info_initrd.gz" \ 50 | "$PACKDIR/${TARGET}_info" 51 | 52 | bash targets/linux_x86_64-userspace/initrd/pack.sh \ 53 | "$PACKDIR/${TARGET}_fuzz_initrd.gz" \ 54 | "$PACKDIR/${TARGET}_fuzz" 55 | } 56 | 57 | target_run() 58 | { 59 | echo "[*] Get info on target $TARGET" 60 | 61 | rm -rf "$WORKDIR" 62 | mkdir -p "$WORKDIR" 63 | 64 | python3 kAFL-Fuzzer/kafl_info.py \ 65 | -kernel "$LINUX_KERNEL" \ 66 | -initrd "$PACKDIR/${TARGET}_info_initrd.gz" \ 67 | -mem 512 \ 68 | -work_dir "$WORKDIR" \ 69 | -v |tee $WORKDIR/info.log 70 | 71 | IP_RANGE="$(cat $WORKDIR/info.log|grep target_executable|grep -- r-xp |head -1|cut -d\ -f 1|sed -e 's/^0/0x/' -e 's/\-0/-0x/')" 72 | 73 | echo "[*] Start fuzzing with range $IP_RANGE, args $KAFL_FUZZ_OPTIONS $*" 74 | 75 | python3 kAFL-Fuzzer/kafl_fuzz.py \ 76 | -kernel "$LINUX_KERNEL" \ 77 | -initrd "$PACKDIR/${TARGET}_fuzz_initrd.gz" \ 78 | -mem 512 \ 79 | -work_dir "$WORKDIR" \ 80 | -seed_dir "$TARGET_ROOT/seeds/" \ 81 | --purge \ 82 | -ip0 $IP_RANGE $KAFL_FUZZ_OPTIONS $* 83 | } 84 | 85 | target_cov() 86 | { 87 | echo "[*] Get trace & coverage data on target $TARGET" 88 | TMP_WORKDIR="/dev/shm/kafl_tmp_$TARGET/" 89 | TARGET_DIR=$1; shift 90 | mkdir -p "$TMP_WORKDIR" 91 | 92 | python3 kAFL-Fuzzer/kafl_info.py \ 93 | -kernel "$LINUX_KERNEL" \ 94 | -initrd "$PACKDIR/${TARGET}_info_initrd.gz" \ 95 | -mem 512 \ 96 | -work_dir "$TMP_WORKDIR" \ 97 | -v |tee $TMP_WORKDIR/info.log 98 | 99 | IP_RANGE="$(cat $TMP_WORKDIR/info.log|grep target_executable|grep xp\ |cut -d\ -f 1|sed -e 's/^0/0x/' -e 's/\-0/-0x/')" 100 | 101 | echo "[*] Start tracing with range $IP_RANGE, args $KAFL_FUZZ_OPTIONS" 102 | 103 | python3 kAFL-Fuzzer/kafl_cov.py \ 104 | -kernel "$LINUX_KERNEL" \ 105 | -initrd "$PACKDIR/${TARGET}_fuzz_initrd.gz" \ 106 | -mem 512 \ 107 | -work_dir "$TMP_WORKDIR" \ 108 | -input $TARGET_DIR \ 109 | --purge \ 110 | -ip0 $IP_RANGE $* 111 | } 112 | 113 | CMD="$1" 114 | TARGET="$2" 115 | 116 | BIN_DIR="$TARGET_ROOT/targets/" 117 | PACKDIR="$TARGET_ROOT/packed/$TARGET/" 118 | WORKDIR="/dev/shm/kafl_$TARGET/" 119 | 120 | cd "$KAFL_ROOT" 121 | 122 | case $CMD in 123 | "pack") 124 | target_pack 125 | ;; 126 | "run") 127 | shift 2 128 | target_run $* 129 | ;; 130 | "cov") 131 | shift 2 132 | test -d "$1" || exit 133 | target_cov $* 134 | ;; 135 | *) 136 | echo "$0 " 137 | ;; 138 | esac 139 | -------------------------------------------------------------------------------- /kAFL-Fuzzer/fuzzer/technique/redqueen/colorize.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2017-2019 Sergej Schumilo, Cornelius Aschermann, Tim Blazytko 2 | # Copyright (C) 2019-2020 Intel Corporation 3 | # 4 | # SPDX-License-Identifier: AGPL-3.0-or-later 5 | 6 | """ 7 | Redqueen Input Colorizer 8 | """ 9 | 10 | import array 11 | from fuzzer.technique.helper import rand 12 | 13 | 14 | # definition of range indicies: 15 | # array = [a,b,c,d] 16 | # the range (0,0) contains no element 17 | # the range (0,1) contains exactly the element a 18 | # the amount of elements in a range is max_-min_ 19 | 20 | class ColorizerStrategy: 21 | COLORABLE = 1 22 | UNKNOWN = 0 23 | FIXED = -1 24 | 25 | def __init__(self, data_length, checker): 26 | self.color_info = array.array('b', [self.UNKNOWN for _ in range(0, data_length)]) 27 | self.unknown_ranges = set() 28 | if data_length > 0: 29 | self.add_unknown_range(0, data_length) 30 | self.checker = checker 31 | 32 | def is_range_colorable(self, min_, max_): 33 | if self.checker(min_, max_): 34 | for i in range(min_, max_): 35 | self.color_info[i] = self.COLORABLE 36 | return True 37 | else: 38 | if min_ + 1 == max_: 39 | self.color_info[min_] = self.FIXED 40 | return False 41 | 42 | def bin_search(self, min_, max_): 43 | if self.is_range_colorable(min_, max_) or min_ + 1 == max_: 44 | return 45 | center = int(min_ + (max_ - min_) / 2) 46 | self.add_unknown_range(min_, center) 47 | self.add_unknown_range(center, max_) 48 | 49 | def colorize_step(self): 50 | (min_i, max_i) = max(self.unknown_ranges, key=lambda mi_ma: mi_ma[1] - mi_ma[0]) 51 | self.unknown_ranges.remove((min_i, max_i)) 52 | self.bin_search(min_i, max_i) 53 | 54 | def add_unknown_range(self, min_, max_): 55 | assert (min_ < max_) 56 | self.unknown_ranges.add((min_, max_)) 57 | 58 | 59 | import unittest 60 | import random 61 | 62 | def check(min_, max_, array): 63 | res = all([array[i] == 0 for i in range(min_, max_)]) 64 | return res 65 | 66 | 67 | def check_nondet(min_, max_, array): 68 | res = all([array[i] == 0 for i in range(min_, max_)]) 69 | if random.randint(0, 100) < 10: 70 | return False 71 | return res 72 | 73 | 74 | class TestColorizer(unittest.TestCase): 75 | 76 | def check_fuzz_result(self, i, testcase): 77 | color_info = [0] * len(testcase) 78 | c = ColorizerStrategy(len(testcase), lambda min_, max_: check(min_, max_, testcase)) 79 | while len(c.unknown_ranges) > 0: 80 | # print c.unknown_ranges 81 | c.colorize_step() 82 | print("det:", c.color_info) 83 | self.assertEqual([(0 if x == 1 else 1) for x in c.color_info], testcase) 84 | assert (all([x != 0 for x in c.color_info])) 85 | 86 | def check_nondet_fuzz_result(self, i, testcase): 87 | color_info = [0] * len(testcase) 88 | c = ColorizerStrategy(len(testcase), lambda min_, max_: check_nondet(min_, max_, testcase)) 89 | while len(c.unknown_ranges) > 0: 90 | offset = c.colorize_step() 91 | print("nondet:", c.color_info) 92 | if not all([x != 0 for x in c.color_info]): 93 | assert (False) 94 | 95 | def test_colorize_step_fuzzed(self): 96 | self.check_fuzz_result(1, [0]) 97 | self.check_fuzz_result(1, [0, 0, 1, 0]) 98 | self.check_fuzz_result(0, [0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1]) 99 | 100 | def test_fuzz_colorize_step(self): 101 | for i in range(0, 1000): 102 | random.seed(i) 103 | tlen = random.randint(1, 40) 104 | testcase = [0] * tlen 105 | num_ones = random.randint(0, (tlen - 1)) 106 | while num_ones > 0: 107 | r = random.randint(0, tlen - 1) 108 | if testcase[r] == 0: 109 | testcase[r] = 1 110 | num_ones -= 1 111 | print("testcase", testcase) 112 | self.check_fuzz_result(i, testcase) 113 | self.check_nondet_fuzz_result(i, testcase) 114 | 115 | 116 | if __name__ == '__main__': 117 | unittest.main() 118 | -------------------------------------------------------------------------------- /targets/macOS_x86_64/loader/loader.c: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright (C) 2017 Sergej Schumilo 4 | 5 | This file is part of kAFL Fuzzer (kAFL). 6 | 7 | QEMU-PT is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 2 of the License, or 10 | (at your option) any later version. 11 | 12 | QEMU-PT is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with QEMU-PT. If not, see . 19 | 20 | */ 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include "../../kafl_user.h" 31 | 32 | static inline void execute_program(){ 33 | char* newenviron[] = {NULL}; 34 | char* newargv[] = {TARGET_FILE, NULL}; 35 | #ifndef AUTORELOAD 36 | pid_t cpid; 37 | int status; 38 | cpid = fork(); 39 | while(1){ 40 | if (!cpid){ 41 | execve(TARGET_FILE, newargv, newenviron); 42 | } 43 | else{ 44 | waitpid(-1, &status, 0); 45 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 46 | cpid = fork(); 47 | } 48 | } 49 | #else 50 | execve(TARGET_FILE, newargv, newenviron); 51 | #endif 52 | } 53 | 54 | static inline void load_program(void* buf){ 55 | int payload_file; 56 | #ifdef DEBUG_MODE 57 | fflush(stdout); 58 | #endif 59 | payload_file = open(TARGET_FILE, O_RDWR | O_CREAT | O_SYNC, 0777); 60 | write(payload_file, buf, PROGRAM_SIZE); 61 | close(payload_file); 62 | 63 | execute_program(); 64 | } 65 | 66 | #ifdef DEBUG_MODE 67 | void readfile(void* buffer){ 68 | FILE *fileptr; 69 | long filelen; 70 | 71 | fileptr = fopen("test", "rb"); 72 | fseek(fileptr, 0, SEEK_END); 73 | filelen = ftell(fileptr); 74 | rewind(fileptr); 75 | 76 | fread(buffer, filelen, 1, fileptr); 77 | fclose(fileptr); 78 | } 79 | #endif 80 | 81 | static inline uint64_t get_kernel_symbol_addr(char* target){ 82 | char cmd[256]; 83 | FILE *fp = NULL; 84 | char addr[17]; 85 | 86 | /* classy cmd-injection...hell yeah! */ 87 | snprintf(cmd, 256, "nm /System/Library/Kernels/kernel | grep \"%s\"$", target); 88 | 89 | fp = popen(cmd, "r"); 90 | fgets(addr, 17, fp); 91 | pclose(fp); 92 | return (uint64_t)strtoull(addr, NULL, 16); 93 | } 94 | 95 | int main(int argc, char** argv) 96 | { 97 | uint64_t panic_handler = 0x0; 98 | uint64_t panic_handler64 = 0x0; 99 | void* program_buffer; 100 | 101 | printf("<< kAFL Usermode Loader for macOS x86-64 >>\n"); 102 | 103 | panic_handler = get_kernel_symbol_addr("T _panic"); 104 | panic_handler64 = get_kernel_symbol_addr("T _panic_64"); 105 | 106 | printf("panic_handler\t%llx\n", panic_handler); 107 | printf("panic_handler64\t%llx\n", panic_handler64); 108 | 109 | /* allocate 4MB contiguous virtual memory to hold fuzzer program; data is provided by the fuzzer */ 110 | program_buffer = mmap((void*)0xabcd0000, PROGRAM_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 111 | /* ensure that the virtual memory is *really* present in physical memory... */ 112 | 113 | memset(program_buffer, 0xff, PROGRAM_SIZE); 114 | 115 | #ifdef DEBUG_MODE 116 | readfile(program_buffer); 117 | load_program(program_buffer); 118 | return 0; 119 | #endif 120 | 121 | /* this hypercall will generate a VM snapshot for the fuzzer and subsequently terminate QEMU */ 122 | kAFL_hypercall(HYPERCALL_KAFL_LOCK, 0); 123 | 124 | 125 | /***** Fuzzer Entrypoint *****/ 126 | 127 | 128 | /* initial fuzzer handshake */ 129 | kAFL_hypercall(HYPERCALL_KAFL_ACQUIRE, 0); 130 | kAFL_hypercall(HYPERCALL_KAFL_RELEASE, 0); 131 | 132 | /* submit panic addresses */ 133 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_PANIC, panic_handler); 134 | kAFL_hypercall(HYPERCALL_KAFL_SUBMIT_PANIC, panic_handler64); 135 | 136 | /* submit virtual address of program buffer and wait for data (*blocking*) */ 137 | kAFL_hypercall(HYPERCALL_KAFL_GET_PROGRAM, (uint64_t)program_buffer); 138 | /* execute fuzzer program */ 139 | load_program(program_buffer); 140 | /* bye */ 141 | return 0; 142 | } 143 | --------------------------------------------------------------------------------