Skip to content

Patch for Nyx bug in afl-showmap #2 #2485

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 91 additions & 22 deletions afl-cmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import array
import base64
import collections
import ctypes
import glob
import hashlib
import itertools
Expand All @@ -27,10 +28,12 @@
import shutil
import subprocess
import sys
import uuid

# https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/recipes.html#batched
from sys import hexversion


def _batched(iterable, n, *, strict=False):
"""Batch data into tuples of length *n*. If the number of items in
*iterable* is not divisible by *n*:
Expand All @@ -43,18 +46,20 @@ def _batched(iterable, n, *, strict=False):
On Python 3.13 and above, this is an alias for :func:`itertools.batched`.
"""
if n < 1:
raise ValueError('n must be at least one')
raise ValueError("n must be at least one")
iterator = iter(iterable)
while batch := tuple(itertools.islice(iterator, n)):
if strict and len(batch) != n:
raise ValueError('batched(): incomplete batch')
raise ValueError("batched(): incomplete batch")
yield batch


if hexversion >= 0x30D00A2: # pragma: no cover
from itertools import batched as itertools_batched

def batched(iterable, n, *, strict=False):
return itertools_batched(iterable, n, strict=strict)

else:
batched = _batched

Expand Down Expand Up @@ -207,6 +212,23 @@ def update(self, *args):
file_index_type_code = None


def search_binary(name):
searches = [
None,
os.path.dirname(__file__),
os.getcwd(),
]
if os.environ.get("AFL_PATH"):
searches.append(os.environ["AFL_PATH"])

for search in searches:
binary = shutil.which(name, path=search)
if binary:
return binary
logger.fatal(f"cannot find {name}, please set AFL_PATH")
sys.exit(1)


def init():
global logger
log_level = logging.DEBUG if args.debug else logging.INFO
Expand All @@ -227,7 +249,7 @@ def init():
logger.error("dangerously low timeout")
sys.exit(1)

if not os.path.isfile(args.exe):
if not args.nyx_mode and not os.path.isfile(args.exe):
logger.error('binary "%s" not found or not regular file', args.exe)
sys.exit(1)

Expand All @@ -244,21 +266,7 @@ def init():
sys.exit(1)

global afl_showmap_bin
searches = [
None,
os.path.dirname(__file__),
os.getcwd(),
]
if os.environ.get("AFL_PATH"):
searches.append(os.environ["AFL_PATH"])

for search in searches:
afl_showmap_bin = shutil.which("afl-showmap", path=search)
if afl_showmap_bin:
break
if not afl_showmap_bin:
logger.fatal("cannot find afl-showmap, please set AFL_PATH")
sys.exit(1)
afl_showmap_bin = search_binary("afl-showmap")

trace_dir = os.path.join(args.output, ".traces")
shutil.rmtree(trace_dir, ignore_errors=True)
Expand All @@ -284,6 +292,55 @@ def detect_type_code(size):
return type_code


def get_nyx_map_size(target_dir):
libnyx_path = search_binary("libnyx.so")
libnyx = ctypes.CDLL(libnyx_path)

NYX_ROLE_StandAlone = 0

target_dir_c = target_dir.encode("utf-8")

dummy_workdir_path = "/tmp/_afl_cmin_nyx_work_dir_%s" % (str(uuid.uuid4()))
dummy_workdir_path_c = dummy_workdir_path.encode("utf-8")

# nyx_config_load
libnyx.nyx_config_load.argtypes = [ctypes.c_char_p]
libnyx.nyx_config_load.restype = ctypes.c_void_p
nyx_config = libnyx.nyx_config_load(target_dir_c)

# nyx_config_set_workdir_path
libnyx.nyx_config_set_workdir_path.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
libnyx.nyx_config_set_workdir_path.restype = None
libnyx.nyx_config_set_workdir_path(nyx_config, dummy_workdir_path_c)

# nyx_config_set_process_role
libnyx.nyx_config_set_process_role.argtypes = [ctypes.c_void_p, ctypes.c_int]
libnyx.nyx_config_set_process_role.restype = None
libnyx.nyx_config_set_process_role(nyx_config, NYX_ROLE_StandAlone)

# nyx_new
libnyx.nyx_new.argtypes = [ctypes.c_void_p, ctypes.c_int]
libnyx.nyx_new.restype = ctypes.c_void_p
nyx_runner = libnyx.nyx_new(nyx_config, 0)

# nyx_get_bitmap_buffer_size
libnyx.nyx_get_bitmap_buffer_size.argtypes = [ctypes.c_void_p]
libnyx.nyx_new.restype = ctypes.c_int
map_size = libnyx.nyx_get_bitmap_buffer_size(nyx_runner)

# nyx_shutdown
libnyx.nyx_shutdown.argtypes = [ctypes.c_void_p]
libnyx.nyx_shutdown.restype = None
libnyx.nyx_shutdown(nyx_runner)

# nyx_remove_work_dir
libnyx.nyx_remove_work_dir.argtypes = [ctypes.c_char_p]
libnyx.nyx_remove_work_dir.restype = None
libnyx.nyx_remove_work_dir(dummy_workdir_path_c)

return map_size


def afl_showmap(input_path=None, batch=None, afl_map_size=None, first=False):
assert input_path or batch
# yapf: disable
Expand Down Expand Up @@ -385,7 +442,8 @@ def afl_showmap(input_path=None, batch=None, afl_map_size=None, first=False):
return result
else:
values = []
for line in out.split():
# split by newline to avoid issues with Nyx mode
for line in out.split(b'\n'):
if not line.isdigit():
continue
values.append(int(line))
Expand Down Expand Up @@ -545,8 +603,11 @@ def collect_files(input_paths):
for filename in filenames:
if filename.startswith("."):
continue
full_path = os.path.join(root, filename)
if not os.path.isfile(full_path):
continue
pbar.update(1)
files.append(os.path.join(root, filename))
files.append(full_path)
return files


Expand Down Expand Up @@ -577,13 +638,21 @@ def main():
hash_list = [hash_list[idx] for idx in idxes]

afl_map_size = None
if b"AFL_DUMP_MAP_SIZE" in open(args.exe, "rb").read():
if "AFL_MAP_SIZE" in os.environ:
afl_map_size = int(os.environ["AFL_MAP_SIZE"])
elif args.nyx_mode:
afl_map_size = get_nyx_map_size(args.exe)
logger.info("Setting AFL_MAP_SIZE=%d", afl_map_size)
elif b"AFL_DUMP_MAP_SIZE" in open(args.exe, "rb").read():
output = subprocess.run(
[args.exe], capture_output=True, env={"AFL_DUMP_MAP_SIZE": "1", "ASAN_OPTIONS": "detect_leaks=0"}
[args.exe],
capture_output=True,
env={"AFL_DUMP_MAP_SIZE": "1", "ASAN_OPTIONS": "detect_leaks=0"},
).stdout
afl_map_size = int(output)
logger.info("Setting AFL_MAP_SIZE=%d", afl_map_size)

if afl_map_size:
global tuple_index_type_code
tuple_index_type_code = detect_type_code(afl_map_size * 9)

Expand Down
2 changes: 1 addition & 1 deletion nyx_mode/LIBNYX_VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
f07a41f
f07a41fc
1 change: 1 addition & 0 deletions src/afl-forkserver.c
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,7 @@ void afl_fsrv_start(afl_forkserver_t *fsrv, char **argv,
}

fsrv->nyx_runner = fsrv->nyx_handlers->nyx_new(nyx_config, fsrv->nyx_id);
fsrv->nyx_handlers->nyx_config_free(nyx_config);

ck_free(workdir_path);
ck_free(outdir_path_absolute);
Expand Down
67 changes: 64 additions & 3 deletions src/afl-showmap.c
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/resource.h>
#ifdef __linux__
#include <poll.h>
#include <unistd.h>
#endif

static afl_state_t *afl;

Expand Down Expand Up @@ -537,10 +541,58 @@ static u32 read_file(u8 *in_file) {
}

#ifdef __linux__
/* Execute the target application with an empty input (in Nyx mode). */
#define NYX_STDIN_TMP_BUFFER_SIZE 256

size_t read_stdin_input(u8** out) {
size_t len = 0;
u8* input = NULL;

if (!isatty(STDIN_FILENO)) { /* only process input when passed via pipe */

struct pollfd pfd = { .fd = STDIN_FILENO, .events = POLLIN };
int ready = poll(&pfd, 1, 0);

if (ready == -1) {
FATAL("%s: poll failed\n", __func__);
}
else if (pfd.revents & POLLIN) { // check if there is any data on stdin

u8 tmp[NYX_STDIN_TMP_BUFFER_SIZE];
size_t capacity = NYX_STDIN_TMP_BUFFER_SIZE;
size_t bytes_read;
input = malloc(capacity);

/* copy input from stdin into a buffer to pass it to Nyx */
while ((bytes_read = read(STDIN_FILENO, tmp, NYX_STDIN_TMP_BUFFER_SIZE)) > 0) {
/* resize buffer if needed */
if (len + bytes_read > capacity) {
while (len + bytes_read > capacity)
capacity *= 2;

u8* new_input = realloc(input, capacity);
if (!new_input) {
free(input);
FATAL("%s: realloc failed\n", __func__);
}
input = new_input;
}

memcpy(input + len, tmp, bytes_read);
len += bytes_read;
}
*out = input;
}
}
return len;
}

/* Execute the target application in Nyx mode with piped input from stdin (passed as a buffer). */
static void showmap_run_target_nyx_mode(afl_forkserver_t *fsrv) {

afl_fsrv_write_to_testcase(fsrv, NULL, 0);
u8* input = NULL;
size_t len = read_stdin_input(&input);

afl_fsrv_write_to_testcase(fsrv, input, len);

if (afl_fsrv_run_target(fsrv, fsrv->exec_tmout, &stop_soon) ==
FSRV_RUN_ERROR) {
Expand All @@ -549,6 +601,9 @@ static void showmap_run_target_nyx_mode(afl_forkserver_t *fsrv) {

}

if (input != NULL) {
free(input);
}
}

#endif
Expand Down Expand Up @@ -1548,12 +1603,18 @@ int main(int argc, char **argv_orig, char **envp) {
if (!be_quiet)
ACTF("Acquired new map size for target: %u bytes\n", new_map_size);

#ifdef __linux__
/* no need to terminate the nyx runner */
if (!fsrv->nyx_mode) {
#endif
afl_shm_deinit(&shm);
afl_fsrv_kill(fsrv);
fsrv->map_size = new_map_size;
fsrv->trace_bits =
afl_shm_init(&shm, new_map_size, 0, DEFAULT_PERMISSION, -1);

#ifdef __linux__
}
#endif
}

map_size = new_map_size;
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy