Apple,  Programming,  SQL

Simple sqlite3 Fuzzer

One of my favorite ways to find escape defects in code is to employ a generic fuzzer. I typically have 5-10 laptops running fuzzers for various projects at a time. I was recently doing some research on sqlite3 and so started to fuzz the implementation built into macOS. The fuzzer generates random SQL statements and executes them against a SQLite database file. If any errors are encountered, they will be printed to the console:

import random
import string

def generate_sql_statement():
  """Generates a random SQL statement."""
  statement = ""
  for i in range(random.randint(1, 10)):
    statement += random.choice(string.ascii_letters)
  return statement

def fuzz_sqlite(database_file):
  """Fuzzes the SQLite database file.

  Args:
    database_file: The path to the SQLite database file.
  """
  connection = sqlite3.connect(database_file)
  while True:
    sql_statement = generate_sql_statement()
    try:
      connection.execute(sql_statement)
    except sqlite3.Error as e:
      print(e)

if __name__ == "__main__":
  database_file = "test.sqlite"
  fuzz_sqlite(database_file)

There’s not much logic here. Add more complex tests to improve it. Like SQL grammar to generate valid SQL statements, or a genetic algorithm to evolve SQL statements that are more likely to find bugs. Use the fuzzer to dink around in other database engines as well by changing the connection string to point to the database engine to fuzz.