Fuzz the public `ndpi_asn1_ber_decode_*()` functions, walking all the
(nested) TLVs and checking some basic invariants on the decoded values.
The initial corpus has real messages extracted from the test pcaps
(SNMP, Kerberos, LDAP), a X.509 certificate and some hand-crafted
edge cases (length/tag encodings, integers, deep nesting).
Update .gitignore with some missing fuzzing artifacts.
ndpi_private_deserializer shares its layout with ndpi_private_serializer, and
ndpi_init_deserializer_buf() set only buffer.data/size/fmt before calling
ndpi_reset_serializer(). When the (attacker-controlled) format byte selects a
non-TLV format, reset_serializer() takes its JSON/CSV path and reads
serializer-only fields (multiline_json_array, inner_json) that a deserializer
never initializes. On a caller-provided, uninitialized deserializer this is a
use-of-uninitialized-value.
Found by OSS-Fuzz (MemorySanitizer)
The TLV deserializer (`ndpi_serializer.c`) could be driven into out-of-bounds
reads, an adjacent-heap info leak, a NULL-pointer crash and an infinite loop
by a malformed/truncated byte stream. These paths are reachable whenever an
embedder deserializes untrusted input (e.g. a collector reading nDPI TLV
records off a socket); nDPI itself only serializes, so no in-tree packet path
is affected.
Reported issues (GHSA-mmp7-3vgp-v8mg):
1. `ndpi_deserialize_get_single_size()`: return type widened u_int16_t -> int
so the -2 truncation sentinel survives for string/block/list types.
2. `ndpi_deserialize_get_single_size()`: bounds-check each fixed-width numeric
field (uint8..double) against the bytes remaining before returning a size.
3. `ndpi_deserialize_get_single_string_size()`: guard `offset > buffer.size`
before computing buff_diff, so it can no longer underflow.
4. 'expected' accumulators widened u_int16_t -> u_int32_t across the
deserialize paths, so two field sizes can no longer wrap mod 2^16.
5. `ndpi_deserialize_clone_item()`: re-check the source holds 'expected' bytes
before the memcpy, closing the heap over-read / info leak.
Additional issues found while fuzzing the fixed code (new `fuzz_deserialization`
target, see below), all in `ndpi_deserialize_clone_all()` on untrusted input:
6. Infinite-loop DoS: the return value of `ndpi_deserialize_next()` was
ignored, so a record that cannot advance the cursor looped forever.
`clone_all()` now validates the whole record is present before reading it
and breaks when `next()` reports an error.
7. NULL / out-of-bounds string reads: `ndpi_deserialize_single_string()` now
bounds the on-wire length to the buffer (returns {NULL,0} otherwise), and
`ndpi_deserialize_key_string()` verifies the key subtype is a string before
reading it (the guard `ndpi_deserialize_value_string()` already had).
8. `atoi(NULL)` crash: ndpi_is_number() now treats NULL/empty as "not a
number", so a NULL key can no longer reach `atoi()`.
9. `atoi()` over-read on a numeric key: the `ndpi_serialize_binary_*()` helpers
called `atoi()` on a counted, non-NUL-terminated key, reading past its
length when the buffer continued with more digits. A bounded `ndpi_atoi_n()`
now converts exactly key_len digits.
A new libFuzzer harness (`fuzz/fuzz_deserialization.cpp`) feeds untrusted bytes
directly to ndpi_init_deserializer_buf() + the clone/iterate APIs, with a seed
corpus reproducing every issue above.
Original report by Mike Myers (Apple).
fix: avoid unaligned reads in DNS and serializers
---------
Co-authored-by: RajaMuhammadAwais <1.19938988e+08+RajaMuhammadAwais@users.noreply.github.com>
Some malware families (e.g. Emotet) encode DGA-generated tokens directly in
the HTTP URL path instead of the hostname, bypassing the existing hostname-
based DGA checks. This commit adds ndpi_check_dga_url_path(), which applies a
refined version of the DGA heuristic to URL path segments:
- Segments are stripped of file extensions, split into sub-tokens by
'_', '-' and '.', and empty sub-tokens are ignored.
- Structured identifiers are excluded: hex hashes/numeric IDs, short
alphanumeric resource IDs (alpha prefix followed by hex body), short
tokens (at most two non-hex letters plus digits, a single letter group
after up to four leading digits, and ASIN-style digit pairs followed by
letters), and purely letter-based names.
- Remaining segments are flagged as DGA-like when they contain at least
eight alphabetic characters with at most two vowels, or an identical-
character run of eight or more, consistent with the hostname checks in
ndpi_check_dga_name().
The check is invoked from the HTTP dissector when validating URLs and
emits the NDPI_SUSPICIOUS_DGA_DOMAIN risk with a descriptive info string.
Add a new fuzzer about it.
Close: #2089
Co-authored-by: RajaMuhammadAwais <1.19938988e+08+RajaMuhammadAwais@users.noreply.github.com>
Co-authored-by: Ivan Nardi <nardi.ivan@gmail.com>
* WIP
* Fix compilation of fuzzing
* Fix fuzzing compilation
* Cleaned up old quic contributed code (#3222)
Recode commits 713cdd0, 26df140
* QUIC: refactoring
* WIP
* WIP
* Revert "QUIC: refactoring"
This reverts commit 50afd07f28.
* QUIC: refactoring original Wireshark code (#3224)
* Added ability to specify in protocol definition, when a (partial) protocol
can change. This can be queries using a new APi call
named ndpi_can_partial_proto_classification_change()
* TLS: minor changes and remove same stale comments
* Fix out-of-bounds read of TLS certificate dates (#3225)
notBefore and notAfter are u_int32_t, but ndpi_tls2json() passed their
address to ndpi_gmtime_r() as a time_t *. Wherever time_t is 8 bytes this
reads 4 bytes past the field, picking up the adjacent member, so the value
handed to gmtime_r() is notBefore | (notAfter << 32) on little-endian.
gmtime_r() then fails on that out-of-range value and returns NULL, leaving
before/after NULL, so the "notbefore" and "notafter" fields are silently
dropped from the JSON output. On architectures that require aligned access
the 8-byte load traps instead of merely being wrong.
Convert to a real time_t instead of casting the address. The temporaries
are named not_before/not_after because notBefore/notAfter are already
char[32] buffers in the same function.
* WIP
* fuzz: fix compilation
---------
Co-authored-by: Luca Deri <lucaderi@users.noreply.github.com>
Co-authored-by: Luca Deri <deri@ntop.org>
Co-authored-by: shalseth <33956011+shalseth@users.noreply.github.com>
```
==57403==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x5020000fc031 at pc 0x59c71d94f6c7 bp 0x7ffff45f54f0 sp 0x7ffff45f4ca8
WRITE of size 4294967295 at 0x5020000fc031 thread T0
#0 0x59c71d94f6c6 in strncpy (/mnt/11a40362-265c-4ec3-8d95-2c65dbe1df34/builds/nDPI/build-fuzz/fuzz/fuzz_ndpi_reader_pl7m_simplest+0x94a6c6) (BuildId: 02db45bde4aa162f8fd4ed895ebf91307bbb6f4a)
#1 0x59c71de540d8 in concat_hash_string /home/ivan/svnrepos/nDPI/src/lib/protocols/ssh.c:515:9
#2 0x59c71de4a571 in ndpi_search_ssh_tcp /home/ivan/svnrepos/nDPI/src/lib/protocols/ssh.c:660:12
#3 0x59c71de54df7 in search_ssh_again /home/ivan/svnrepos/nDPI/src/lib/protocols/ssh.c:219:3
#4 0x59c71db95c84 in process_extra_packet /home/ivan/svnrepos/nDPI/src/lib/ndpi_main.c:9752:9
#5 0x59c71db4572c in ndpi_internal_detection_process_packet /home/ivan/svnrepos/nDPI/src/lib/ndpi_main.c:10559:5
#6 0x59c71db4486f in ndpi_detection_process_packet /home/ivan/svnrepos/nDPI/src/lib/ndpi_main.c:10773:3
```
Found by oss-fuzz
Fix three issues in the STUN fuzzer that reduce fuzzing effectiveness:
1. ndpi_flow is static and never reset between calls, causing stale
state from previous inputs to affect subsequent ones. This makes
fuzzing results non-reproducible and prevents proper per-input
isolation. Fix: memset flow to zero at the start of each call and
call ndpi_free_flow_data() at the end for cleanup.
2. iph (IP header) is all zeros, meaning version=0, ihl=0, protocol=0.
This is not a valid IPv4 header and causes is_stun() to skip
protocol-specific code paths. Fix: set version=4, ihl=5, and
protocol=17 (UDP) or 6 (TCP) depending on the build variant.
3. udph/tcph (transport headers) are all zeros, meaning port=0.
STUN-related code paths check for specific ports. Fix: set source
and destination ports to 3478 (STUN default).
Since fuzz_is_stun_tcp.c is a symlink to fuzz_is_stun.c, this fix
applies to both UDP and TCP variants via the existing STUN_TCP ifdef.
```
../../fuzz/fuzz_alg_crc32_md5.c:61:7: error: assigning to 'char *' from 'u_char *' (aka 'unsigned char *') converts between pointers to integer types where one is of the unique plain 'char' type and the other is not [-Werror,-Wpointer-sign]
61 | enc = ndpi_hex_encode(data, size);
| ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
Five fuzzers (fuzz_process_packet, fuzz_ndpi_reader, fuzz_ndpi_reader_alloc_fail,
fuzz_ndpi_reader_payload_analyzer, and fuzz_tls_certificate) were not rebuilding
when libndpi.a changed because their explicit DEPENDENCIES declarations only
included dictionary files.
In Automake, when prog_DEPENDENCIES is explicitly set, it overrides the automatic
dependency generation from LDADD. This caused these fuzzers to miss the library
dependency that the other 55 fuzzers correctly inherited.
This commit adds $(top_builddir)/src/lib/libndpi.a to the DEPENDENCIES for all
5 affected fuzzers, ensuring they rebuild whenever the library changes.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
- Added the ability to exclude TCP fingerprint via metadata.ndpi_fingerprint_ignore_tcp_fp configuration
- TLS blocks not include the block lenght only for Client and Server hello, ignored for all other blocks
* Added --cfg "tls,max_num_blocks_to_analyze,X" where if X > 0 TLS blocks are analyzed
Example --cfg "tls,max_num_blocks_to_analyze,8"
* TLS blocks now include a time-delta (msec) with respect to the previous TLS block.
The format is @<msec delta>. Example:
"tls_blocks": [
"22:1=232@191",
"22:2=-122@5,20=-1@5,21=-23@5,21=-905@5,21=-281@5",
"21=-53@0",
"20=1@3,21=53@3",
"21=-218@119,21=-218@119",
]
Commit e49e93cc17 broke coverage
instrumentation for fuzzing targets due to two issues with how
AM_LDFLAGS and target-specific CFLAGS/CXXFLAGS interact.
Problems:
---------
1. Missing AM_LDFLAGS in link command:
The commit changed LIB_FUZZING_ENGINE from being added to LDFLAGS
to being added to AM_LDFLAGS (line 26):
Before: `LDFLAGS += $(LIB_FUZZING_ENGINE)`
After: `AM_LDFLAGS += $(LIB_FUZZING_ENGINE)`
However, FUZZ_LINK_COMMAND (line 34) was not updated to include
`$(AM_LDFLAGS)`, so `-fsanitize=fuzzer` was missing from link commands.
2. Target-specific CFLAGS/CXXFLAGS override AM_CFLAGS/AM_CXXFLAGS:
When automake sees target-specific CFLAGS (like fuzz_ndpi_reader_CFLAGS),
it COMPLETELY REPLACES AM_CFLAGS instead of adding to it. Even empty
assignments like `fuzz_process_packet_CFLAGS =` mean "use nothing"
rather than "use AM_CFLAGS". This means `-fsanitize=fuzzer` from
AM_CFLAGS was not being used during compilation.
Example:
`AM_CFLAGS = @NDPI_CFLAGS@ -fsanitize=fuzzer`
`fuzz_ndpi_reader_CFLAGS = -I$(top_srcdir)/example/`
Result: Only `-I$(top_srcdir)/example/` is used, AM_CFLAGS is ignored!
Without `-fsanitize=fuzzer` during both compilation and linking:
- No coverage instrumentation is generated
- LibFuzzer cannot collect coverage information
- Fuzzer warns: "WARNING: no interesting inputs were found so far.
Is the code instrumented for coverage?"
Solutions:
----------
1. Add `$(AM_LDFLAGS)` to FUZZ_LINK_COMMAND (line 34) before
`$(LDFLAGS)`
This ensures LIB_FUZZING_ENGINE is included during linking.
2. For targets with non-empty CFLAGS/CXXFLAGS, prefix with `$(AM_CFLAGS)/$(AM_CXXFLAGS)`:
Changed: `fuzz_*_CFLAGS = -DFOO`
To: `fuzz_*_CFLAGS = $(AM_CFLAGS) -DFOO`
3. For targets with empty CFLAGS/CXXFLAGS, remove the assignments entirely:
Removed: `fuzz_*_CFLAGS =`
This allows automake to automatically use AM_CFLAGS/AM_CXXFLAGS.
The flag ordering (package flags before user flags) is maintained.
Testing:
--------
Before fix:
$ ./fuzz_ndpi_reader -runs=10
INFO: Seed: 437565050
WARNING: no interesting inputs were found so far. Is the code instrumented for coverage?
After fix:
$ ./fuzz_ndpi_reader -runs=10
INFO: Loaded 1 modules (4802 inline 8-bit counters)
INFO: Loaded 1 PC tables (4802 PCs)
#2 INITED cov: 4 ft: 5 corp: 1/1b exec/s: 0 rss: 81Mb
#10 DONE cov: 4 ft: 5 corp: 1/1b lim: 4 exec/s: 0 rss: 81Mb
$ ./fuzz_process_packet -runs=10
INFO: Loaded 1 modules (25 inline 8-bit counters)
INFO: Loaded 1 PC tables (25 PCs)
#2 INITED cov: 2 ft: 2 corp: 1/1b exec/s: 0 rss: 65Mb
#10 DONE cov: 2 ft: 2 corp: 1/1b lim: 4 exec/s: 0 rss: 65Mb
Verified with:
CC=clang CXX=clang++ ./configure --enable-fuzztargets --with-sanitizer
make -j4
./fuzz/fuzz_ndpi_reader -runs=10
./fuzz/fuzz_process_packet -runs=10
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
Replace relative path references (../) with $(top_srcdir) in
fuzz/Makefile.am to properly support out-of-tree builds (VPATH builds).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <noreply@anthropic.com>
Fix improper handling of CFLAGS and LDFLAGS throughout the build system.
Also remove hardcoded debug flags that prevented production builds
without symbols.
Problems:
---------
1. CFLAGS/LDFLAGS handling:
The build system was using `CFLAGS +=` and `LDFLAGS +=` to append
package-specific flags, which modifies the user's environment variables
instead of keeping package and user flags separate. This caused:
- User-specified optimization levels being overridden by package defaults
- Inability to properly override flags at configure or make time
- Problems with cross-compilation and embedded toolchains
2. Hardcoded -g flags:
Debug symbols (-g) were hardcoded in several Makefiles, forcing debug
symbols in all builds including production. This caused:
- Larger binary sizes (library and tools)
- No way to build without debug symbols
- Conflicts with user's debug level preferences (-g1, -g2, -g3)
- Redundancy with configure options (--enable-debug-build)
Solutions:
----------
1. Implement proper CFLAGS/LDFLAGS separation using AM_CFLAGS/AM_LDFLAGS:
- Added `CFLAGS = @CFLAGS@` to preserve configure-time flags
- Added `LDFLAGS = @LDFLAGS@` to preserve configure-time flags
- Changed `CFLAGS +=` to `AM_CFLAGS =` and `AM_CFLAGS +=`
- Changed `LDFLAGS +=` to `AM_LDFLAGS =` and `AM_LDFLAGS +=`
- Updated compilation rules: $(CC) $(AM_CFLAGS) $(CFLAGS) ...
- Updated linking rules: $(CC) ... $(AM_LDFLAGS) $(LDFLAGS) ...
2. Remove all hardcoded -g flags from Makefiles:
- Debug symbols now controlled via configure (--enable-debug-build)
or user CFLAGS (e.g., CFLAGS="-g3")
Flag ordering ensures:
- Package flags come first (e.g., -O2, -fPIC)
- User flags come after and can override (e.g., -O3)
- Last flag wins for conflicting options
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <noreply@anthropic.com>
This commit implements comprehensive improvements to the nDPI build system
to enhance portability, enable parallel testing, and ensure reliable
out-of-tree (VPATH) builds across all platforms.
Changes:
1. Optimize library linking order (configure.ac, all Makefiles)
- Reorder ADDITIONAL_LIBS to follow proper dependency hierarchy
- Move low-level libraries (libm) to end of link line
- Ensures compatibility with --as-needed linker flag
- Improves LTO and static linking support
2. Fix VPATH build dependencies (all Makefiles)
- Add explicit dependencies on generated headers (ndpi_config.h, ndpi_define.h)
- Prevents race conditions in parallel builds (make -j)
- Ensures headers exist before compilation starts
3. Replace mkdir -p with portable $(MKDIR_P) macro
4. Enable parallel test execution (configure.ac)
- Add 'parallel-tests' option to AM_INIT_AUTOMAKE
- Allows test suites to run concurrently during 'make check'
5. Add defensive .NOTPARALLEL directive (Makefile.am)
- Prevents race conditions if 'make -j clean distclean' is run
6. Fix clean target completeness (src/lib/Makefile.in)
- Remove all .so symlinks (libndpi.so, libndpi.so.N)
- Add cleanup for Windows DLL files (*.dll)
- Explicitly remove versioned shared libraries
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Ivan Nardi <nardi.ivan@gmail.com>
- Fixed some typos and inconsistent option names in error messages
- Improved Git Detection in configure script
- Added informative warnings when optional dependencies are missing
- Improve error handling on autogen.sh script
- Simplify fuzzing Makefile, creating common FUZZ_LINK_COMMAND template for all fuzz targets
- Added *_DEPENDENCIES declarations for fuzz targets with dictionaries
- Implemented incremental corpus building to avoid unnecessary rebuilds
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <noreply@anthropic.com>