github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/docs/darwin/README.md (about)

     1  # Darwin/XNU
     2  
     3  It turned out to be unreasonably hard to bootstrap a VM image usable for fuzzing from the XNU source drops without using any of the proprietary kernel extensions shipped with macOS. This guide is therefore based on a normal macOS installation. Unfortunately Apples macOS EULA makes this unsuitable for fuzzing XNU on Google Cloud Platform.
     4  
     5  ## Prepare a macOS installation disk image
     6  
     7  Nowadays Apple mainly distributes macOS updates via the Mac App Store. This will however only give us the latest builds. Luckily the Munki people are kind enough to maintain a script, allowing us to fetch a macOS build of our choice from the shell.
     8  
     9  We'll need a macOS build that has a kernel version close to the one we will be building. You can [see Apples most recent source drops on this page](https://opensource.apple.com/). At the time of writing the most recent version is macOS 11.5 containing kernel xnu-7195.141.2. The Munki download script can only tell the macOS version and build number, but not the XNU version. Unfortunately you might occasionally download a matching macOS release, but the kernel you build won't boot anyway. Among many other reasons this can be caused by this mismatch in kernel and bootloader versions. Some trial and error can be involved in getting the correct build. Sometimes the correct build might no longer be available. At the time of writing 11.5 build 20G71 was available and worked with the 11.5 xnu source drop.
    10  
    11  In the instructions below I will assume you have VMware Fusion installed on your host macOS for creating the VM disk image. This is for convenience sake as Fusion allows us to simply drag and drop in the macOS installer App we downloaded. If you want to use another tool like Qemu for this, [take note of Apples own process for creating a bootable install media](https://support.apple.com/en-us/HT201372). I had trouble generating bootable ISOs from certain macOS builds using Apples method, hence I just always let Fusion create the installation medium for me.
    12  
    13  Additionally the below instructions ask you to disable System Integrity Protection and Authenticated Root inside the VM. We need to do this in order to run the DIY kernel we will build in a bit. Executive Summary on these features:
    14  - In OS X 10.11 Apple introduced System Integrity Protection, a feature that (among other things) limits even root from writing to certain critical system directories during normal operations. We need to disable it to write our kernel to disk
    15  - In macOS 11 Apple introduced Authenticated Root. Starting with this version only a cryptographically signed read only snapshot of the root filesystem is mounted during boot. We need to disable it in order to remount a writable version and take a new snapshot to boot from later
    16  
    17  **Tl;Dr: To create the VM image:**
    18  - [Clone Munkis macadmin-script repo](https://github.com/munki/macadmin-scripts)
    19  - Run `installinstallmacos.py` and choose a version matching the last kernel source drop
    20  - Mount and open the downloaded `Install_macOS_<version>-<build>.dmg`
    21  - Open VMware Fusion and create a new VM via the File menu
    22  - Drag and Drop the `Install macOS <name>` App from the mounted disk image into the `Select the Installation Method` Fusion dialog
    23  - I suggest cranking up the VMs CPU and Memory at this point
    24  - After picking your language in the macOS installer open `Utilities -> Terminal`
    25  - Enter `csrutil disable` to disable System Integrity Protection
    26  - Enter `csrutil authenticated-root disable` to disable Authenticated Root
    27  - Quit the Terminal app via Cmd+Q
    28  - Follow through with the macOS installation, creating a user called `user`. If you don’t have any disk available to install to, you might need to use the Disk Utility to format the virtual disk first
    29  - Go to `System Preferences -> Software Update -> Advanced…` and uncheck `Check for updates`
    30  - Go to `System Preferences -> Energy Saver` and check `Prevent computer from sleeping automatically when the display is off`
    31  - Go to `System Preferences -> Sharing` and check `Remote Login` to enable sshd
    32  - Add your ssh pubkey to both your users and roots authorized_keys files
    33  - Optionally disable WindowServer and other non-essential services via launchd. Note that you will obviously loose the GUI: `sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.WindowServer.plist`
    34  
    35  
    36  Check that everything looks alright:
    37  ![screenshot showing clean macos 11.5 build 20G71 installation with xnu-7195.141.2~5/RELEASE_X86_64 and disabled System Integrity Protection, as well as disabled Authenticated Root](https://i.imgur.com/xYJ7XgF.png)
    38  
    39  
    40  ## Prepare a Kernel optimized for fuzzing
    41  
    42  You might be wondering why we aren’t using one of the precompiled kernels available in Apples Kernel Development Kits. However those don’t include any kernel built with the KSANCOV feature flag. KSANCOV is Apples take on an API that allows userspace to request the kernel to start tracing which kernel code a given thread touched and exposing that information to userspace. This information is required by Syzkaller to be really effective at fuzzing.
    43  
    44  Luckily [afrojer@](https://twitter.com/afrojer) is releasing semi-regularly updated instructions on building XNU from source and installing it on macOS on his blog. At the time of writing he is lagging three minor source drop versions behind. The [most recent instructions are for macOS 11.2](https://web.archive.org/web/20210524205524/https://kernelshaman.blogspot.com/2021/02/building-xnu-for-macos-112-intel-apple.html). We’ll cover some additional required changes in this text.
    45  
    46  Building and testing a XNU useful for fuzzing:
    47  - Download a somewhat recent Xcode from [Apples Xcode versions archive (Apple ID login required)](https://developer.apple.com/download/all/?q=xcode) to your VM. I’m using Xcode 12.5. I had issues with 12.5.1 and 13 beta 4
    48  - Open the `Xcode_<version>.xip` to extract. Make a coffee ⏳
    49  - Drag and Drop the extracted Xcode app into your VMs Applications folder
    50  - Start Xcode, agree to the license and quit it after it finishes installation
    51  - Create and join a directory named `kernel` in the users home dir and cd into it
    52  - Downloading afrojer@s Makefile: `curl https://jeremya.com/sw/Makefile.xnudeps > Makefile.xnudeps` Note this file is not versioned, but always updated in place. [Here is an archive link to the version at the time of writing.](https://web.archive.org/web/20210210224511/https://jeremya.com/sw/Makefile.xnudeps)
    53  - `make -f Makefile.xnudeps macos_version=11.5 xnudeps` This will get the dependencies for building the 11.5 XNU. [Check out the original blog post for details on how to fetch dependencies for a specific version](https://kernelshaman.blogspot.com/2021/02/building-xnu-for-macos-112-intel-apple.html)
    54  - cd into `~/kernel/xnu-<version>/`
    55  - Apply [required XNU patches](0001-fuzzing.patch) manually or via `git am`. Applying via git requires you to init the repo and commit all files first. That's probably a good idea anyway to track further changes you might make
    56      - The patches for `MakeInc.def` and `kasan.c` are required for the KASAN kernel to build. KASAN is short for KernelAddressSANitizer - a feature to detect a bunch of memory safety issues inside the kernel during runtime
    57      - The `ksancov.h` patch is required for building syzkallers executor. Executor is C++ and hence doesn't like the void pointer casting
    58      - Finally the `cpuid.c` and `cpu_threads.c` patches are required for our kernel to boot on Qemu
    59  
    60  - Run `mount` and look for the roots mount device. On my VM it looks like this `/dev/disk2s5s1 on / (apfs, sealed, local, read-only, journaled)`. Now remember the devices name, ignoring the last sN part. So I note down `/dev/disk2s5`
    61  - Cd into `~/kernel/xnu-<version>/` and run the following, replacing `<your_disk>` to build and install your kernel
    62  
    63  ```
    64  mkdir -p BUILD/mnt
    65  sudo mount -o nobrowse -t apfs /dev/<your_disk> $PWD/BUILD/mnt
    66  
    67  make SDKROOT=macosx TARGET_CONFIGS="KASAN X86_64 NONE" KSANCOV=1
    68  
    69  kmutil create -a x86_64 -Z -n boot sys \
    70  -B BUILD/BootKernelExtensions.kc.kasan \
    71  -S BUILD/SystemKernelExtensions.kc.kasan \
    72  -k BUILD/obj/kernel.kasan \
    73  --elide-identifier com.apple.driver.AppleIntelTGLGraphicsFramebuffer
    74  
    75  sudo ditto BUILD/BootKernelExtensions.kc.kasan "$PWD/BUILD/mnt/System/Library/KernelCollections/"
    76  sudo ditto BUILD/SystemKernelExtensions.kc.kasan "$PWD/BUILD/mnt/System/Library/KernelCollections/"
    77  sudo ditto BUILD/obj/kernel.kasan "$PWD/BUILD/mnt/System/Library/Kernels/"
    78  
    79  sudo bless --folder $PWD/BUILD/mnt/System/Library/CoreServices --bootefi --create-snapshot
    80  sudo nvram boot-args="-v kcsuffix=kasan wlan.skywalk.enable=0"
    81  ```
    82  
    83  After rebooting you should see your shiny new kernel when running `uname -a`: `Darwin users-Mac.local 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug  9 16:12:43 PDT 2021; user:xnu-7195.141.2/BUILD/obj/KASAN_X86_64 x86_64`
    84  
    85  
    86  For effective fuzzing we'll need the kernels binary, symbols and source on the host. Copy them like this:
    87  
    88  ```
    89  mkdir -p ~/115/src/Users/user/kernel/ ~/115/obj
    90  rsync -r mac:/Users/user/kernel/xnu-7195.141.2 ~/115/src/Users/user/kernel/
    91  mv ~/115/src/Users/user/kernel/xnu-7195.141.2/BUILD/obj/KASAN_X86_64/kernel.kasan ~/115/obj/
    92  mv ~/115/src/Users/user/kernel/xnu-7195.141.2/BUILD/obj/KASAN_X86_64/kernel.kasan.dSYM/ ~/115/obj/
    93  ```
    94  
    95  ## Preparing VM for Qemu
    96  
    97  Even though Macs are AMD64 machines with EFIs (at least the once we care about here), they aren't exactly IBM PC compatible. So far VMWare Fusion did all the trickery necessary to virtualize macOS for us, but qemu-system-x86_64 does not.
    98  
    99  To make macOS boot we'll first start Qemu with OVMF (tianocore based UEFI for qemu). Next we boot OpenCore, which will do some trickery making it possible to chainload Apples stock AMD64 EFI bootloader. It also does some binary kernel patching, making it possible to load the RELEASE kernel shipped with macOS, should we want that.
   100  
   101  OpenCore is rather configurable, but we don't care about real hardware. [I'm using this version prebuild and configured to work inside Qemu](https://github.com/thenickdude/KVM-Opencore/releases). We can simply overwrite the EFI partition on our VMs disk with the EFI partition from one of the images from this repo.
   102  
   103  Let's first find out which partition we will overwrite in a minute. From the following output from within the macOS VM (still booted via Fusion for now) we can see that in my case the EFI partition is at `/dev/disk0s1`:
   104  
   105  ```
   106  user@users-Mac ~ % diskutil list
   107  /dev/disk0 (internal, physical):
   108     #:                       TYPE NAME                    SIZE       IDENTIFIER
   109     0:      GUID_partition_scheme                        *69.8 GB    disk0
   110     1:                        EFI EFI                     209.7 MB   disk0s1
   111     2:                 Apple_APFS Container disk1         69.6 GB    disk0s2
   112  
   113  /dev/disk1 (synthesized):
   114     #:                       TYPE NAME                    SIZE       IDENTIFIER
   115     0:      APFS Container Scheme -                      +69.6 GB    disk1
   116                                   Physical Store disk0s2
   117     1:                APFS Volume macos - Data            43.2 GB    disk1s1
   118     2:                APFS Volume Preboot                 385.6 MB   disk1s2
   119     3:                APFS Volume Recovery                623.2 MB   disk1s3
   120     4:                APFS Volume VM                      1.1 MB     disk1s4
   121     5:                APFS Volume macos                   16.0 GB    disk1s5
   122     6:              APFS Snapshot com.apple.bless.4099... 16.0 GB    disk1s5s1
   123  ```
   124  
   125  Now download [OpenCore-v13.iso.gz](https://github.com/thenickdude/KVM-Opencore/releases/download/v13/OpenCore-v13.iso.gz) and extract the image via `gzip -d OpenCore-v13.iso.gz`. Display the partition map to find out the images blocksize and the EFI partitions offset and size.
   126  
   127  
   128  ```
   129  user@users-Mac ~ % hdiutil pmap ./OpenCore-v13.iso
   130  
   131  MEDIA: ""; Size 150 MB [307200 x 512]; Max Transfer Blocks 2048
   132  SCHEME: 1 GPT, "GPT Partition Scheme" [16]
   133  SECTION: 1 Type:'MAP'; Size 150 MB [307200 x 512]; Offset 34 Blocks (307133 + 67) x 512
   134  ID Type                 Offset       Size         Name                      (1)
   135  -- -------------------- ------------ ------------ -------------------- --------
   136   1 EFI                            40       307120 disk image
   137  ```
   138  
   139  Now put all those values together in a dd command like so: `sudo dd if=./OpenCore-v13.iso of=/dev/disk0s1 bs=512 iseek=40 count=307120`
   140  
   141  Now let's mount the EFI disk via `sudo mount -t msdos /dev/disk0s1 ~/mnt/`. We have to edit OpenCores config file a tiny bit. We disable the boot device selector, as that will prevent us from starting the VMs during fuzzing completely automatically. Additionally note how we set boot-args here. In VMware Fusion we were able to use the normal macOS tools like nvram and csrutil. In OpenCore we need to set these settings in the config.plist instead.
   142  
   143  Edit `~/mnt/EFI/OC/config.plist` like so:
   144  
   145  ```diff
   146  index 8537ca8..a46de97 100755
   147  --- a/Users/user/mnt/EFI/OC/config.plist
   148  +++ b/Users/user/mnt/EFI/OC/config.plist
   149  @@ -799,7 +799,7 @@
   150   			<key>PollAppleHotKeys</key>
   151   			<true/>
   152   			<key>ShowPicker</key>
   153  -			<true/>
   154  +			<false/>
   155   			<key>TakeoffDelay</key>
   156   			<integer>0</integer>
   157   			<key>Timeout</key>
   158  @@ -944,7 +944,7 @@
   159   				<key>SystemAudioVolume</key>
   160   				<data>Rg==</data>
   161   				<key>boot-args</key>
   162  -				<string>keepsyms=1</string>
   163  +				<string>-v kcsuffix=kasan wlan.skywalk.enable=0 keepsyms=1 debug=0x100008 kasan.checks=4294967295</string>
   164   				<key>csr-active-config</key>
   165   				<data>Jg8=</data>
   166   				<key>prev-lang:kbd</key>
   167  
   168  ```
   169  
   170  At this point you should still be able to (re)boot the VM in Fusion. It will just ignore OpenCore however. That's fine.
   171  
   172  ## Prepare isa-applesmc
   173  
   174  On boot macOS checks whether it is booted on a proper Mac by reading a value from its System Management Controller and comparing it with the value it expects. We'll retrieve this value now and pass it to qemu later. To retrieve the value:
   175  - [Download the smc_read.c source from this site.](https://web.archive.org/web/20200603015401/http://www.osxbook.com/book/bonus/chapter7/tpmdrmmyth/)
   176  - `gcc -Wall -o smc_read smc_read.c -framework IOKit`
   177  `./smc_read`
   178  
   179  That will produce a single line of text which you will later have to substitute in for a place marked `<YOUR_APPLE_SMC_HERE>`.
   180  
   181  
   182  ## Booting macOS via Qemu
   183  
   184  - Setup [Homebrew](https://brew.sh/) on your host macOS
   185  - Install `qemu` via homebrew
   186  - Your VMs disk should be somewhere like this on your host `~/Virtual\ Machines.localized/macOS-11.5-20G71.vmwarevm/Virtual\ Disk.vmdk`. Convert it to qcow2 via something like this `qemu-img convert -U ./Virtual\ Disk.vmdk -O qcow2 ~/115/mac_hdd.qcow`
   187  - Unfortunately OVMF is currently not packaged in Homebrew. Download the [`ovmf` package from ubuntu](https://packages.ubuntu.com/hirsute/ovmf). Extract it via `ar -xv ./ovmf_2020.11-4_all.deb` and `tar -xvf ./data.tar.xz`. Finally `mv ./usr/share/OVMF /usr/local/share/OVMF`
   188  
   189  That's pretty much all you should need in order to boot the VM image we build. Start Qemu like so. Remember to substitute `<YOUR_APPLE_SMC_HERE>` and the username in the disk image path:
   190  ```
   191  qemu-system-x86_64 \
   192    -device isa-applesmc,osk="<YOUR_APPLE_SMC_HERE>" \
   193    -accel hvf -machine q35 -smp "2",cores="2",sockets="1" -m "4096" \
   194    -cpu Penryn,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on,"+pcid,+ssse3,+sse4.2,+popcnt,+avx,+aes,+xsave,+xsaveopt,check" \
   195    -drive if=pflash,format=raw,readonly=on,file="/usr/local/share/OVMF/OVMF_CODE.fd" \
   196    -drive if=pflash,format=raw,readonly=on,file="/usr/local/share/OVMF/OVMF_VARS.fd" \
   197    -device ich9-intel-hda -device hda-duplex -device ich9-ahci,id=sata \
   198    -device ide-hd,bus=sata.4,drive=MacHDD \
   199    -drive id=MacHDD,if=none,file="/Users/user/115/macos_11_5.qcow",format=qcow2 \
   200    -netdev user,id=net0,hostfwd=tcp::1042-:22, -device e1000-82545em,netdev=net0,id=net0 \
   201    -device usb-ehci,id=ehci -usb -device usb-kbd -device usb-tablet \
   202    -monitor stdio -vga vmware
   203  ```
   204  
   205  You should both see the macOS UI and be able to `ssh user@localhost -p 1042`. Confirm we are booted into your KASAN kernel:
   206  
   207  ```
   208  user@users-Mac ~ % uname -a
   209  Darwin users-Mac.local 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug  9 16:12:43 PDT 2021; user:xnu-7195.141.2/BUILD/obj/KASAN_X86_64 x86_64
   210  ```
   211  
   212  Shut down your VM now. We'll let syzkaller boot it back up soon.
   213  
   214  ## Building Syzkaller
   215  
   216  - Install `go` via homebrew
   217  - Add something like this to your .zshrc:
   218  ```
   219  export GOPATH=/Users/user/go
   220  export PATH=$GOPATH/bin:$PATH
   221  ```
   222  - Relogin and build syzkaller like this:
   223  ```
   224  git clone https://github.com/google/syzkaller
   225  cd syzkaller
   226  make HOSTOS=darwin HOSTARCH=amd64 TARGETOS=darwin TARGETARCH=amd64 SOURCEDIR=/Users/user/115/src/Users/user/kernel/xnu-7195.141.2
   227  ```
   228  
   229  ## Fuzzing with Syzkaller
   230  
   231  - We need g++ to make C reproducers work. Install `gcc@11` via homebrew
   232  - We need addr2line from binutils to make the `/cover` endpoint work. Install `binutils` via homebrew
   233  - Add something like this to your .zshrc `export PATH="/usr/local/opt/binutils/bin:$PATH"`. Restart your shell
   234  - Save the following to `~/115/syzkaller.cfg`. Remember to substitute `<YOUR_APPLE_SMC_HERE>`:
   235  ```
   236  {
   237      "target": "darwin/amd64",
   238      "http": "127.0.0.1:56741",
   239      "sshkey": "/Users/user/.ssh/id_macos115",
   240      "workdir": "/Users/user/sk_darwin/",
   241      "kernel_obj": "/Users/user/115/obj/",
   242      "kernel_src": "/Users/user/115/src/",
   243      "syzkaller": "/Users/user/go/src/github.com/google/syzkaller",
   244      "procs": 2,
   245      "type": "qemu",
   246      "cover": true,
   247      "image": "/Users/user/115/macos_11_5.qcow",
   248      "vm": {
   249          "count": 2,
   250          "cpu": 2,
   251          "mem": 4096,
   252          "efi_code_device": "/usr/local/share/OVMF/OVMF_CODE.fd",
   253          "efi_vars_device": "/usr/local/share/OVMF/OVMF_VARS.fd",
   254          "apple_smc_osk": "<YOUR_APPLE_SMC_HERE>"
   255      }
   256  }
   257  ```
   258  
   259  Start syzkaller via `~/115/bin/syz-manager -config=/root/115/syzkaller.cfg` and open http://localhost:56741 in your browser.