diff --git a/scripts/fuzz/fuzz_rtp_flow.c b/scripts/fuzz/fuzz_rtp_flow.c new file mode 100644 index 000000000..716680ec4 --- /dev/null +++ b/scripts/fuzz/fuzz_rtp_flow.c @@ -0,0 +1,239 @@ +/* + * Fuzzer for rtpproxy RTP relay flow machinery with the resizer engaged. + * + * Threat model: rtpproxy relays attacker-supplied RTP between endpoints; each + * relayed packet's header (sequence, timestamp, SSRC, payload type, padding, + * CSRC) and UDP source address are fully attacker-controlled. When a session + * is created with the "z" command modifier (repacketization ptime), relayed + * packets additionally flow through the resizer (rtp_resizer.c), a heap-based + * jitter buffer that re-times packets -- a state machine driven entirely by + * the attacker's sequence/timestamp/payload-size choices. + * + * No existing fuzz target ever enables the resizer (the z modifier is absent + * from all harness setup scripts), so rtp_resizer.c and the surrounding + * stream/proc paths are dark in production coverage (2026-11-26 report: + * rtp_resizer.c 238/268 lines dark, rtp.c 99/184, rtp_analyze.c 89/384, + * rtpp_stream.c 493/863 best-dark, rtpp_proc.c 83/103, rtpp_sessinfo.c 92 + * best-dark). This target creates sessions with Uz/Lz modifiers (ptime 10, + * 20 and 40ms, including asymmetric 10 -> 40) plus one plain session, then + * injects attacker-controlled RTP packets with attacker-controlled source + * addresses into both streams of every session, exercising: + * - src/rtp_resizer.c: enqueue, repacketization and drain state machine; + * - src/rtpp_stream.c: relay path, resizer hooks, per-stream stats; + * - src/rtp.c / src/rtp_analyze.c: packet parse validation, sequence and + * timestamp tracking (dups, loss, reorder, probation); + * - src/rtpp_proc.c and src/rtpp_sessinfo.c: server-side per-tick + * processing and session statistics; + * - src/rtpp_hash_table.c: session hash table walk under relay load. + * + * Input format is identical to fuzz_rtp_session: a leading op byte (bit0: + * reseed RNGs) followed by rfz_get_chunk()-delimited chunks, each holding a + * 16-byte sockaddr_in source address followed by the raw RTP packet bytes. + * The seed corpus generator (gen_rtp_flow_seeds.py) constructs valid RTP + * streams with real-world header variants; libFuzzer mutates from there. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fuzz_standalone.h" + +#define HAVE_CONFIG_H 1 +#include "config_pp.h" + +#include "rtpp_types.h" +#include "rtpp_cfg.h" +#include "rtp.h" +#include "rtpp_time.h" +#include "rtpp_codeptr.h" +#include "rtp_packet.h" +#include "rtpp_session.h" +#include "rtpp_pipe.h" +#include "rtpp_proc.h" +#include "rtpp_network.h" +#include "rtpp_stream.h" +#include "rtpp_ttl.h" +#include "rtpp_codeptr.h" +#include "rtpp_refcnt.h" +#include "rtpp_command.h" +#include "rtpp_weakref.h" +#include "rtpp_hash_table.h" +#include "advanced/packet_processor.h" +#include "advanced/pproc_manager.h" + +#include "rfz_chunk.h" +#include "rfz_utils.h" +#include "rfz_command.h" + +static struct { + sem_t wi_proc_done; +} fuzz_ctx; + +static void +fuzz_ctx_dtor(void) +{ + ExecuteRTPPCommand(&gconf, "X", 1, 0); + sem_destroy(&fuzz_ctx.wi_proc_done); +} + +static const char * const setup_script[] = { + #include "fuzz_rtp_flow.setup" + NULL +}; + +static int +ExecuteScript(void) +{ + char line[RTPP_CMD_BUFLEN]; + + for (int i = 0; setup_script[i] != NULL; i++) { + const char *cp = setup_script[i]; + int size = strlen(cp); + memcpy(line, cp, size + 1); + int r = ExecuteRTPPCommand(&gconf, line, size, 0); + if (r != 0) + return (-1); + } + return (0); +} + +int +LLVMFuzzerInitialize(int *_argc, char ***_argv) +{ + RTPPInitializeParams.ttl = "60"; + int r = RTPPInitialize(); + + if (r != 0) + goto e0; + if (sem_init(&fuzz_ctx.wi_proc_done, 0, 0) != 0) + goto e0; + if (ExecuteScript() != 0) + goto e1; + if (ExecuteRTPPCommand(&gconf, "X", 1, 0) != 0) + goto e1; + atexit(fuzz_ctx_dtor); + return (0); +e1: + sem_destroy(&fuzz_ctx.wi_proc_done); +e0: + return (-1); +} + +struct foreach_args { + const char *data; + size_t size; + struct rtpp_proc_rstats *rsp; + int nwait; +}; + +static void +wi_proc_complete(void *arg) +{ + sem_post(&fuzz_ctx.wi_proc_done); +} + +static int +proc_foreach(void *dp, void *ap) +{ + struct foreach_args *fap; + const struct rtpp_session *sp; + rtpp_refcnt_dtor_t wpd_f = (rtpp_refcnt_dtor_t)&wi_proc_complete; + + fap = (struct foreach_args *)ap; + /* + * This method does not need us to bump ref, since we are in the + * locked context of the rtpp_hash_table, which holds its own ref. + */ + sp = (const struct rtpp_session *)dp; + + for (int i=0; i < 2; i++) { + struct sockaddr *rap; + struct rtp_packet *pktp = rtp_packet_alloc(); + assert (pktp != NULL); + void *olddata = CALL_SMETHOD(pktp->rcnt, getdata); + RTPP_OBJ_DTOR_ATTACH_s(pktp, wpd_f, olddata); + rap = sstosa(&pktp->raddr); + memcpy(rap, fap->data, sizeof(struct sockaddr_in)); + rap->sa_family = AF_INET; + pktp->size = fap->size - sizeof(struct sockaddr_in); + memcpy(pktp->data.buf, fap->data + sizeof(struct sockaddr_in), pktp->size); + struct rtpp_stream *istp = sp->rtp->stream[i], + *ostp = sp->rtp->stream[i ^ 1]; + struct pkt_proc_ctx pktx = {.strmp_in = istp, + .strmp_out = ostp, + .rsp = fap->rsp, + .pktp = pktp}; + CALL_SMETHOD(istp->pproc_manager, handleat, &pktx, _PPROC_ORD_EMPTY); + fap->nwait += 1; + } + return (RTPP_HT_MATCH_CONT); +} + +int +LLVMFuzzerTestOneInput(const char *data, size_t size) +{ + static struct rtpp_proc_rstats rs = {0}; + sem_t *wpdp = &fuzz_ctx.wi_proc_done; + struct { + union { + struct { + uint8_t reseed:1; + }; + uint8_t value; + }; + } op_flags; + + if (size < 2) + return (0); + + op_flags.value = data[0]; + data += 1; + size -= 1; + + if (op_flags.reseed) { + SeedRNGs(); + } + + assert(ExecuteScript() == 0); + + struct rfz_chunk chunk = {.rem_size = size, .rem_data = data}; + struct foreach_args fa = {.rsp = &rs}; + + do { + chunk = rfz_get_chunk(chunk.rem_data, chunk.rem_size); + if (chunk.size < sizeof(struct sockaddr_in)) + break; + if (chunk.size > sizeof(struct sockaddr_in) + MAX_RPKT_LEN) + break; + fa.data = chunk.data; + fa.size = chunk.size; + CALL_SMETHOD(gconf.cfsp->sessions_ht, foreach, proc_foreach, (void *)&fa, NULL); + } while (chunk.rem_size > 1); + + /* Resizer-held packets only return to the free queue at session + * teardown, so tear the sessions down BEFORE waiting and bound each + * wait: unbounded sem_wait() would hang the target on packets the + * resizer keeps queued past the 25s libFuzzer timeout. */ + assert(ExecuteRTPPCommand(&gconf, "X", 1, 0) == 0); + for (int i = 0; i < fa.nwait; i++) { + struct timespec dl; + clock_gettime(CLOCK_REALTIME, &dl); + dl.tv_nsec += 100 * 1000 * 1000; + if (dl.tv_nsec >= 1000 * 1000 * 1000) { + dl.tv_sec += 1; + dl.tv_nsec -= 1000 * 1000 * 1000; + } + if (sem_timedwait(wpdp, &dl) == -1 && errno == ETIMEDOUT) + break; + } + return (0); +} diff --git a/scripts/fuzz/fuzz_rtp_flow.dict b/scripts/fuzz/fuzz_rtp_flow.dict new file mode 100644 index 000000000..3c133b5b1 --- /dev/null +++ b/scripts/fuzz/fuzz_rtp_flow.dict @@ -0,0 +1,117 @@ +addr1="\x01\x02\x03\x04" +# port1=1234 +port1="\x04\xd2" + +addr2="\x05\x06\x07\x08" +# port2=5678 +port2="\x2e\x16" + +# AFL dictionary for RTP/RTCP packets +# ----------------------------------- +# +# Basic sections derived from standard RTP/RTCP headers and payloads. +# Does not include vendor-specific extensions. +# +# Created by [Your Name] +# + +# RTP header fields +header_vpxt="10000000" +header_vpxc="10010000" +header_vpxt_mark="10000001" +header_vpxc_mark="10010001" + +# RTP payload types +payload_pcmu="\x00" +payload_pcma="\x08" +payload_gsm="\x03" +payload_g723="\x04" +payload_dvi4_8k="\x05" +payload_dvi4_16k="\x06" +payload_lpc="\x07" +payload_g722="\x09" +payload_l16_stereo="\x0a" +payload_l16_mono="\x0b" +payload_qcelp="\x0c" +payload_cn="\x13" +payload_mpeg="\x0e" +payload_g729="\x12" + +# RTCP packet types +# Sender Report +rtcp_sr="\xc8" +# Receiver Report +rtcp_rr="\xc9" +# Source Description +rtcp_sdes="\xca" +# Goodbye +rtcp_bye="\xcb" +# Application-defined +rtcp_app="\xcc" + +# RTCP SDES item types +sdes_cname="\x01" +sdes_name="\x02" +sdes_email="\x03" +sdes_phone="\x04" +sdes_loc="\x05" +sdes_tool="\x06" +sdes_note="\x07" +sdes_priv="\x08" + +# Common RTP/RTCP extensions +# Extended Sequence Number +ext_trans_seq="\xbe\xde" +# Media Identifier +ext_mid="\xbe\xde\x02" +# RTP Stream Identifier +ext_rtp_stream_id="\xbe\xde\x0d" + +# AFL dictionary for STUN/ICE packets +# ----------------------------------- +# +# Basic sections derived from standard STUN/ICE headers and attributes. +# Does not include vendor-specific extensions. +# +# Created by [Your Name] +# + +# STUN message types +stun_binding_request="\x00\x01" +stun_binding_response="\x01\x01" +stun_binding_error_response="\x01\x11" +stun_binding_indication="\x00\x11" + +# STUN message headers +stun_magic_cookie="\x21\x12\xa4\x42" + +# STUN attributes +attr_mapped_address="\x00\x01" +attr_response_address="\x00\x02" +attr_change_request="\x00\x03" +attr_source_address="\x00\x04" +attr_changed_address="\x00\x05" +attr_username="\x00\x06" +attr_password="\x00\x07" +attr_message_integrity="\x00\x08" +attr_error_code="\x00\x09" +attr_unknown_attributes="\x00\x0a" +attr_reflected_from="\x00\x0b" +attr_realm="\x00\x14" +attr_nonce="\x00\x15" +attr_xor_mapped_address="\x00\x20" +attr_software="\x80\x22" +attr_alternate_server="\x80\x23" +attr_fingerprint="\x80\x28" + +# ICE-specific attributes +attr_priority="\x00\x24" +attr_use_candidate="\x00\x25" +attr_ice_controlled="\x80\x29" +attr_ice_controlling="\x80\x2a" + +# Common STUN message header extensions +# Example length field (32 bytes) +header_length="\x00\x20" +# Example transaction ID +header_transaction_id="\x63\x1a\x1f\x80\x39\x4d\x41\x50\x4c\x65\x75" diff --git a/scripts/fuzz/fuzz_rtp_flow.options b/scripts/fuzz/fuzz_rtp_flow.options new file mode 100644 index 000000000..ab1f3fb12 --- /dev/null +++ b/scripts/fuzz/fuzz_rtp_flow.options @@ -0,0 +1,5 @@ +[libfuzzer] +detect_leaks=0 +max_len=8192 +print_final_stats=1 +use_value_profile=1 diff --git a/scripts/fuzz/fuzz_rtp_flow.setup b/scripts/fuzz/fuzz_rtp_flow.setup new file mode 100644 index 000000000..97e09355b --- /dev/null +++ b/scripts/fuzz/fuzz_rtp_flow.setup @@ -0,0 +1,6 @@ +"Uz20 callid_1 1.2.3.4 1234 from_tag_1", +"Lz20 callid_1 5.6.7.8 5678 from_tag_1 to_tag_1", +"Uz10 callid_2 1.2.3.4 1234 from_tag_2 && " \ + "Lz40 callid_2 5.6.7.8 5678 from_tag_2 to_tag_2", +"U callid_3 1.2.3.4 1234 from_tag_3", +"L callid_3 5.6.7.8 5678 from_tag_3 to_tag_3", diff --git a/scripts/fuzz/gen_rtp_flow_seeds.py b/scripts/fuzz/gen_rtp_flow_seeds.py new file mode 100644 index 000000000..328c5300f --- /dev/null +++ b/scripts/fuzz/gen_rtp_flow_seeds.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +""" +Seed corpus generator for fuzz_rtp_flow. + +Constructs structurally valid inputs for the rtpproxy RTP relay flow fuzzer. +Each input is a concatenation of rfz_get_chunk()-delimited chunks: + [length byte(s)][16-byte sockaddr_in][RTP packet bytes] +where the length prefix stores (chunk_len - 1) in base-255 continuation +encoding (0xff continuation bytes). libFuzzer mutates these into malformed +variants; without valid seeds the fuzzer rarely produces packets that pass +RTP header validation (version field, minimum length), leaving the relay, +analyzer and resizer logic dark. + +The generator emits: + - clean 20-packet PCMU streams (20ms ptime) with incrementing seq/ts; + - the same flow with a mid-stream source-address change (NAT path); + - marker-bit flips, payload-type changes, padding, CSRC variants; + - sequence-number dup/reorder/huge-jump patterns (analyzer probation); + - truncated and oversized packets; + - a multi-flow input mixing all of the above. +""" +import os +import struct +import sys + + +def chunk(payload: bytes) -> bytes: + """Encode one rfz_get_chunk() chunk around a length prefix.""" + n = len(payload) - 1 + if n < 255: + return bytes([n]) + payload + # base-255 continuation: each 0xff byte adds 255 + parts = [] + while n >= 255: + parts.append(255) + n -= 255 + parts.append(n) + return bytes(parts) + payload + + +def addr(port: int, ip: bytes = b"\x01\x02\x03\x04") -> bytes: + # struct sockaddr_in layout as built by the harness; family is reset to + # AF_INET by the harness itself, port is network byte order. + return ip + struct.pack(">H", port) + b"\x00" * 10 + + +def rtp_packet(seq: int, ts: int, ssrc: int, pt: int = 0, marker: int = 0, + payload: bytes = b"\x00" * 160, csrc_count: int = 0, + padding: int = 0) -> bytes: + b0 = 0x80 | (padding << 5) | (csrc_count & 0x0F) + b1 = (marker << 7) | (pt & 0x7F) + hdr = struct.pack(">BBHII", b0, b1, seq & 0xFFFF, ts & 0xFFFFFFFF, ssrc) + hdr += b"\x00\x00\x00\x00" * csrc_count + if padding: + payload = payload + b"\x00" * 4 + bytes([4]) + return hdr + payload + + +def flow(npackets, out, port=1234, ip=b"\x01\x02\x03\x04", ssrc=0xDEADBEEF, + pt=0, start_seq=0, start_ts=0, ts_inc=160): + data = b"\x01" # op byte: reseed RNGs for determinism + for i in range(npackets): + pkt = rtp_packet(start_seq + i, start_ts + i * ts_inc, ssrc, pt=pt, + marker=1 if (i + 1) == npackets else 0) + data += chunk(addr(port, ip) + pkt) + return data + + +def main(): + outdir = sys.argv[1] if len(sys.argv) > 1 else "rtp_flow_seed_corpus" + os.makedirs(outdir, exist_ok=True) + + def put(name, blob): + with open(os.path.join(outdir, name), "wb") as f: + f.write(blob) + + # 1. Clean 20-packet PCMU stream. + put("clean_stream", flow(20, outdir)) + + # 2. Mid-stream source address change (NAT rebind path). + data = b"\x01" + for i in range(10): + data += chunk(addr(1234) + rtp_packet(i, i * 160, 0xDEADBEEF)) + for i in range(10, 20): + data += chunk(addr(4321, ip=b"\x05\x06\x07\x08") + rtp_packet(i, i * 160, 0xDEADBEEF)) + put("nat_change", data) + + # 3. Payload-type change and marker flips mid-stream. + data = b"\x00" + for i in range(8): + data += chunk(addr(1234) + rtp_packet(i, i * 160, 0x11111111, pt=0)) + for i in range(8, 16): + data += chunk(addr(1234) + rtp_packet(i, i * 160, 0x11111111, pt=8, marker=1)) + put("pt_change", data) + + # 4. Sequence anomalies: dup, reorder, huge jump, loss burst. + data = b"\x00" + seqs = [0, 1, 1, 2, 3, 5, 4, 5, 30000, 30001, 7, 8, 9] + for i, s in enumerate(seqs): + data += chunk(addr(1234) + rtp_packet(s, i * 160, 0x22222222)) + put("seq_anomalies", data) + + # 5. Padding and CSRC-bearing packets. + data = b"\x00" + data += chunk(addr(1234) + rtp_packet(0, 0, 0x33333333, padding=1)) + data += chunk(addr(1234) + rtp_packet(1, 160, 0x33333333, csrc_count=1)) + data += chunk(addr(1234) + rtp_packet(2, 320, 0x33333333, csrc_count=4)) + put("pad_csrc", data) + + # 6. Truncated and oversized packets. + data = b"\x00" + data += chunk(addr(1234) + rtp_packet(0, 0, 0x44444444)[:10]) + data += chunk(addr(1234) + rtp_packet(1, 160, 0x44444444, payload=b"\x41" * 1100)) + data += chunk(addr(1234) + rtp_packet(2, 320, 0x44444444, payload=b"\x42" * 800)) + put("sizes", data) + + # 7. Asymmetric flows into both ptime sessions (10 -> 40 repacketization). + data = b"\x01" + for i in range(30): + data += chunk(addr(5678, ip=b"\x05\x06\x07\x08") + rtp_packet(i, i * 80, 0x55555555)) + put("asym_10_40", data) + + print(f"wrote seeds to {outdir}") + + +if __name__ == "__main__": + main() diff --git a/scripts/fuzz/oss-fuzz-build.sh b/scripts/fuzz/oss-fuzz-build.sh index 347b760c6..7fc20c325 100755 --- a/scripts/fuzz/oss-fuzz-build.sh +++ b/scripts/fuzz/oss-fuzz-build.sh @@ -116,7 +116,7 @@ do OBJS="${OBJS} ${obj}" done -ALL="command_parser rtp_parser rtcp_parser rtp_session config_file" +ALL="command_parser rtp_parser rtcp_parser rtp_session config_file rtp_flow" OBJS0="${OBJS}" for fz in ${ALL} do @@ -168,6 +168,18 @@ then rm -rf "${SEEDTMP}" fi +# fuzz_rtp_flow support: pack a seed corpus of structurally valid RTP streams +# (valid headers, NAT address changes, seq/ts anomalies, padding/CSRC +# variants) so that the relay, analyzer and resizer logic is reachable from +# the first fuzzing iteration instead of staying behind RTP header validation. +if [ -e scripts/fuzz/gen_rtp_flow_seeds.py ] +then + SEEDTMP="`mktemp -d ${OUT}/flow_seed_corpus.XXXXXXXX`" + python3 scripts/fuzz/gen_rtp_flow_seeds.py "${SEEDTMP}" + (cd "${SEEDTMP}" && zip -q -r "${OUT}/fuzz_rtp_flow_seed_corpus.zip" .) + rm -rf "${SEEDTMP}" +fi + if [ "${OUT}" != "." ] then cp -Rp ${OUT} build-out