Skip to content
37 changes: 27 additions & 10 deletions fuzz/fuzz_go.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
# Copyright (C) 2023 Intel Corporation
# SPDX-License-Identifier: GPL-3.0-or-later

"""
This module contains fuzz testing for the GoParser's handling of go.mod files.
"""

import os
import shutil
import sys
import tempfile
from pathlib import Path

import atheris
import atheris_libprotobuf_mutator
Expand All @@ -24,12 +23,13 @@
logger = LOGGER.getChild("Fuzz")


def GoModBuilder(data):
def GoModBuilder(data, file_path):
"""
This function converts the given data into a go.mod file.

Args:
data (protobuf message): The protobuf message to convert to a go.mod file.
file_path: The path of the file to build.
"""
json_data = MessageToDict(
data, preserving_proto_field_name=True, including_default_value_fields=True
Expand Down Expand Up @@ -66,13 +66,17 @@ def GoModBuilder(data):
f.write(")\n")


def TestParseData(data):
def TestParseData(data, cve_db, logger, tmpdir):
"""
Fuzz test the GoParser's handling of go.mod files.
Fuzz testing function for the GoParser's handling of go.mod files.

Args:
data (protobuf message): The protobuf message to convert to a go.mod file.
cve_db: The CVE-Bin-tool Database object.
logger: Logger object.
tmpdir: Temporary Directory reference.
"""
file_path = os.path.join(tmpdir, "go.mod")
try:
GoModBuilder(data)

Expand All @@ -83,7 +87,20 @@ def TestParseData(data):
return


file_path = str(Path(tempfile.mkdtemp(prefix="cve-bin-tool-")) / "go.mod")

atheris_libprotobuf_mutator.Setup(sys.argv, TestParseData, proto=go_mod_pb2.GoModFile)
atheris.Fuzz()
def main():
"""Main Function to Run Fuzzing and Facilitate Tempfile cleanup."""
tmpdir = tempfile.mkdtemp(prefix="cve-bin-tool-")
try:
atheris_libprotobuf_mutator.Setup(
sys.argv,
lambda data: TestParseData(data, cve_db, logger, tmpdir),
proto=go_mod_pb2.GoModFile,
)
atheris.Fuzz()
finally:
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)


if __name__ == "__main__":
main()