antonin

Fuzzing Pillow with Frelatage to find bugs and vulnerabilities

How I used Frelatage to fuzz one of the most used Python libraries and found bugs.

What is fuzzing?

Fuzzing, or fuzz testing, is an effective way to find bugs and vulnerabilities in software. The program doing the testing is the fuzzer (for example AFL, honggfuzz or wfuzz) and the program being tested is the target. A fuzzer feeds random inputs to the target while observing its behavior. Whenever the target crashes, the fuzzer reports the input that caused it as a bug or a crash.

This method has proven its value many times in vulnerability research, as these articles and videos show:

A few weeks ago, I immersed myself in this new world. After spending a lot of time playing with AFL++, honggfuzz and Atheris, I felt like writing my own fuzzer, first to learn, then to find vulnerabilities. A few nights of code later, Frelatage was born.

Frelatage

Frelatage is a coverage-based fuzzing library for Python code.

Influences

Frelatage was inspired by other fuzzers, including AFL/AFL++, Atheris and PythonFuzz. Its purpose is to gather their best features into a new tool to efficiently fuzz Python applications and libraries.

Table of contents:

  1. How it works
  2. Setting up our fuzzing environment
  3. Writing the fuzzing harness
  4. Running the fuzzer
  5. Triaging the crash reports
  6. Upcoming features

How it works

Frelatage uses a genetic algorithm to generate mutations that cover as much code as possible. A fuzzing cycle can be roughly summarized as follows:

Cycle mutationsMutation 1Mutation 2Mutation ...Mutation ninputFuzzed functionGenerate reportsRank reportsSelect n best reportsmutateNext cycle mutationsMutation 1Mutation 2Mutation ...Mutation n

Setting up our fuzzing environment

Installing Frelatage

The package is available on PyPI and can be installed with pip:

pip3 install frelatage

The project structure

# Create the main folder
mkdir pillow_fuzz
cd pillow_fuzz

# Create the input file folder
mkdir in
# Create the dictionary folder
mkdir dict
# Create the fuzzing harness file
touch pillow_fuzzer.py

We now have the following tree:

pillow_fuzz
├── dict
├── in
└── pillow_fuzzer.py

Creating a corpus

A corpus is a set of inputs for a fuzz target. In most contexts, it refers to a set of minimal test inputs that generate maximal code coverage.

Since Pillow is an image processing library, we need a corpus of images to reach satisfactory code coverage and help the fuzzer find interesting paths. According to the official documentation, the following formats are fully supported: BMP, DDS, DIB, EPS, GIF, ICNS, ICO, IM, JPEG, JPEG 2000, MSP, PCX, PNG, PPM, SGI, SPIDER, TGA, TIFF, WebP and XBM.

A fuzzing harness is a test case or a particular test target.

To make fuzzing more efficient, it may be worth writing a separate harness for each format, with its own corpus and dictionary.

In this article, we will focus on JPEG: it is one of the most widespread formats and, along with PNG and GIF, one of the easiest to find a corpus for. Pre-made corpora are freely available; we will use this one:

# Download the corpus
git clone --depth 1 https://github.com/strongcourage/fuzzing-corpus

# Merge all subfolders into the ./in folder
cp fuzzing-corpus/jpg/*/* ./in
rm -rf fuzzing-corpus

Dictionary-based optimization

A JPEG image is a sequence of segments, each beginning with a marker: a 0xFF byte followed by a byte indicating the kind of marker.

Structure of a JPEG file
Structure of a JPEG file

We will use this dictionary, written for AFL by Michal Zalewski, and save it in ./dict, the default dictionary folder:

#
# AFL dictionary for JPEG images
# ------------------------------
#
# Created by Michal Zalewski
#

header_jfif="JFIF\x00"
header_jfxx="JFXX\x00"

section_ffc0="\xff\xc0"
section_ffc2="\xff\xc2"
section_ffc4="\xff\xc4"
section_ffd0="\xff\xd0"
section_ffd8="\xff\xd8"
section_ffd9="\xff\xd9"
section_ffda="\xff\xda"
section_ffdb="\xff\xdb"
section_ffdd="\xff\xdd"
section_ffe0="\xff\xe0"
section_ffe1="\xff\xe1"
section_fffe="\xff\xfe"

Writing the fuzzing harness

Our fuzzing harness goes in pillow_fuzzer.py:

import frelatage
from PIL import Image
from PIL import ImageFile

# Allow PIL to load truncated images
ImageFile.LOAD_TRUNCATED_IMAGES = True

# The function we want to fuzz
def jpeg_fuzz_pillow(image):
    # Open and decode the image (open() alone only reads the header)
    Image.open(image).load()
    return

# Load the corpus
jpeg_corpus = frelatage.load_corpus(directory="./")
# Initialize the fuzzer
f = frelatage.Fuzzer(jpeg_fuzz_pillow, [jpeg_corpus])
# Launch the fuzzing process
f.fuzz()

Running the fuzzer

I designed Frelatage to be highly configurable, so several settings can be changed through environment variables:

FRELATAGE_DICTIONARY_ENABLE
Enable the use of mutations based on dictionary elements. Values: 1 to enable, 0 otherwise. Default: 1.
FRELATAGE_TIMEOUT_DELAY
Delay in seconds after which a function will return a TimeoutError. Values: 1 to 20. Default: 2.
FRELATAGE_INPUT_FILE_TMP_DIR
Temporary folder where input files are stored. Values: absolute path to a folder, e.g. /tmp/custom_dir. Default: /tmp/frelatage.
FRELATAGE_INPUT_MAX_LEN
Maximum size of an input variable in bytes. Values: 4 to 1000000. Default: 4094.
FRELATAGE_MAX_THREADS
Maximum number of simultaneous threads. Values: 8 to 50. Default: 8.
FRELATAGE_MAX_CYCLES_WITHOUT_NEW_PATHS
Number of cycles without new paths found after which we go to the next stage. Values: 10 to 50000. Default: 5000.
FRELATAGE_INPUT_DIR
Directory containing the initial input files. Must be relative to the path of the fuzzing file. Values: relative path to a folder, e.g. ./in. Default: ./in.
FRELATAGE_DICTIONARY_DIR
Default directory for dictionaries. Must be relative to the path of the fuzzing file. Values: relative path to a folder, e.g. ./dict. Default: ./dict.

We start by configuring our fuzzer:

export FRELATAGE_DICTIONARY_ENABLE=1
export FRELATAGE_TIMEOUT_DELAY=2
export FRELATAGE_INPUT_FILE_TMP_DIR="/tmp/frelatage"
export FRELATAGE_INPUT_MAX_LEN=4096
export FRELATAGE_MAX_THREADS=8
export FRELATAGE_MAX_CYCLES_WITHOUT_NEW_PATHS=5000
export FRELATAGE_INPUT_DIR="./in"
export FRELATAGE_DICTIONARY_DIR="./dict"

Then we launch it:

python3 pillow_fuzzer.py
Frelatage fuzzing Pillow
Frelatage fuzzing Pillow

Fuzzing can take from a few hours to several days, depending on the new paths found along the way.

Triaging the crash reports

Now comes the less pleasant part: triaging the crashes.

Crash triage means examining each crash found by Frelatage to determine whether it is worth investigating (for security researchers, whether it is likely due to a vulnerability) and, if so, what its root cause is. This can be very time-consuming if the fuzzer has found dozens or hundreds of crashes, which is likely after several hours or days.

Each crash is saved in the output folder (./out by default), in a folder named id:<crash ID>,err:<error type>,err_file:<error file>,err_pos:<err_pos>, where:

The report directory contains the files passed as arguments, and looks like this:

out
├── id:<crash ID>,err:<error type>,err_file:<error file>,err_pos:<err_pos>
│   ├── input
│   ├── 0
│   │   └── <inputfile1>
│   └── ...
└── ...

Expect a lot of noise: Pillow raises exceptions such as UnidentifiedImageError or OSError by design when it receives an invalid image. These are not bugs, so filter them out first and focus on unexpected exceptions, hangs and crashes of the interpreter itself.

Examples of reports generated by Frelatage
Examples of reports generated by Frelatage

Reading a report

Inputs are serialized with the pickle module before being saved in <report_folder>/input, so they must be deserialized to be read. This script does it:

./read_report.py input

{'input': [{'value': '/tmp/frelatage/0/0/0e8ef3773a13824c42f021c1af856c351effa6a2-2', 'file': True}]}

Upcoming features

Frelatage is still in active development, so what is written above may (will?) change as I work on making it even more effective. Here is what I plan to implement in the next few weeks:

The best way to keep up with Frelatage is to follow the GitHub repo.

Thanks for reading!

For more information or suggestions, you can contact me at r0g3r5@protonmail.com, or on X.