friTap ships a stable, SemVer-guaranteed Python API for driving captures, consuming live events, and working with .tap files offline. The public surface is everything exported from the friTap package __all__ (59 symbols); removing or breaking any of them requires a friTap MAJOR bump (see RELEASING.md).
This page leads with the modern API:
the FriTap builder for configuring and starting captures,
the EventBus and typed events for consuming data programmatically,
The legacy SSL_Logger class is documented last, in a deprecated section.
CI-runnable vs. live-device examples
Examples in this page are labelled either live / device (they attach to or spawn a real process and cannot run in CI) or offline / CI-runnable (they operate on .tap files or in-memory objects and run anywhere friTap imports).
FriTap(...).start() attaches to or spawns a real target through Frida. This cannot run in CI — it needs a device and the target app/process.
fromfriTapimportFriTapsession=(FriTap("com.example.app").mobile()# target a USB device.keylog("keys.log")# write an SSLKEYLOGFILE.pcap("cap.pcapng")# write decrypted traffic (pcapng → embedded DSB).start()# returns a FriTapSession)session.wait()# block until the target exits; or call session.stop()
build_config() is the offline-safe half of the builder — it returns a FriTapConfig without touching a device, which is useful for tests and for inspecting/serializing configuration:
Every method below returns self, so calls chain. Names are verbatim from friTap.api.FriTap. The builder is hand-documented (chained APIs render poorly under autodoc).
Write decrypted traffic to a PCAP file. The extension decides (--pcap-format auto): .pcapng writes pcapng (with embedded DSB when keys are extracted), anything else classic libpcap. Resets a prior pcapng() call.
pcapng(path)
Write self-decrypting PCAPNG whatever the extension (--pcap-format pcapng): pcapng("out.bin") writes pcapng; a contradicting .pcap name is written as pcapng with a warning.
keylog(path)
Write key material in Wireshark-loadable form for the active protocol (NSS SSLKEYLOGFILE for TLS). With --protocol all/auto, the path is split per protocol as <stem>.<proto><ext>.
json_output(path)
Write session metadata as JSON. Key material is redacted unless keylog() or json_keys() is also set.
json_keys(enable=True)
Include raw key material (key_data) in the JSON output, like --json-keys.
verbose(enable=True)
Enable verbose console output.
live(enable=True)
Stream to Wireshark via a named pipe.
full_capture(enable=True)
Capture the full network stream, not just decrypted payload.
Use pattern-based (symbol-less) hooking from a JSON file.
offsets(path)
Use offset-based hooking from a JSON file.
experimental(enable=True)
Enable experimental features.
anti_root(enable=True)
Enable anti-root-detection hooks (Android).
payload_modification(enable=True)
Enable payload-modification capability.
force_scan(name)
Force-scan a module that Cronet-split-topology suppression would otherwise skip. Accepts a literal name, a stem prefix (name*) or a regex (re:...). May be called multiple times.
Enable debug mode with Chrome Inspector (also turns on debug output).
debug_output(enable=True)
Enable debug output only (no inspector).
custom_script(path)
Load a custom Frida script before friTap's hooks.
add_script_plugin(plugin)
Register a ScriptPlugin to load when the session starts.
environment(path)
Provide an environment-variables JSON for spawn.
signal_handler(enable=True)
Opt in to friTap handling SIGINT/SIGTERM for the session (default off: the embedding program owns its signals and calls FriTapSession.stop()). When on and start() runs on the main thread, Ctrl+C/SIGTERM stop the session like stop() (outputs finalized, the host process keeps running) and the previous handlers are restored afterwards.
proxy(address)
Redirect connections to a host:port proxy and bypass cert pinning (requires fritap-proxy).
Embedded/API mode never calls os._exit: if the target dies, friTap finalizes the outputs and ends the session, leaving the host interpreter running. Only the CLI exits the process.
friTap dispatches typed events through a thread-safe publish-subscribe EventBus. Output handlers, the TUI, plugins, and your own callbacks all subscribe to event classes.
bus.subscribe(KeylogEvent, handler) / bus.emit(KeylogEvent(...)). Higher priority runs first; plugins use PLUGIN_PRIORITY to run before built-in outputs.
classEventBus:"""Thread-safe publish-subscribe event bus. ``bus.subscribe(KeylogEvent, handler)`` / ``bus.emit(KeylogEvent(...))``. Higher *priority* runs first; plugins use ``PLUGIN_PRIORITY`` to run before built-in outputs. """MAX_HANDLER_FAILURES=10PLUGIN_PRIORITY=100def__init__(self,on_handler_error:Optional[Callable]=None)->None:self._subscribers:Dict[Type[FriTapEvent],List[Tuple[int,Callable]]]={}self._lock=threading.RLock()self._logger=logging.getLogger("friTap.events")self._failure_counts:Dict[str,int]={}self._on_handler_error=on_handler_errordefsubscribe(self,event_type:Type[FriTapEvent],callback:Callable,*,priority:int=0)->None:"""Call *callback* whenever *event_type* is emitted; higher *priority* (default 0) runs first."""withself._lock:subs=self._subscribers.setdefault(event_type,[])subs.append((priority,callback))subs.sort(key=lambdat:t[0],reverse=True)defunsubscribe(self,event_type:Type[FriTapEvent],callback:Callable)->None:"""Remove a previously registered callback."""withself._lock:subs=self._subscribers.get(event_type,[])fori,(_,cb)inenumerate(subs):ifcb==callback:subs.pop(i)breakdefemit(self,event:FriTapEvent)->None:"""Dispatch *event* to its type's subscribers and to ``FriTapEvent`` catch-alls, by descending priority."""withself._lock:specific=self._subscribers.get(type(event),[])iftype(event)isnotFriTapEvent:catch_all=self._subscribers.get(FriTapEvent,[])ifnotcatch_all:# fast pathhandlers=list(specific)else:# Merge two pre-sorted (descending priority) listshandlers=[]i,j=0,0whilei<len(specific)andj<len(catch_all):ifspecific[i][0]>=catch_all[j][0]:handlers.append(specific[i])i+=1else:handlers.append(catch_all[j])j+=1handlers.extend(specific[i:])handlers.extend(catch_all[j:])else:handlers=list(specific)for_prio,cbinhandlers:try:cb(event)exceptExceptionasexc:handler_name=getattr(cb,"__qualname__",repr(cb))self._logger.exception("Error in event subscriber %s for %s",handler_name,type(event).__name__,)count=self._failure_counts.get(handler_name,0)+1self._failure_counts[handler_name]=countifself._on_handler_errorisnotNone:try:self._on_handler_error(cb,event,exc)exceptException:pass# Guard against recursion on ErrorEvent handlers.ifnotisinstance(event,ErrorEvent):try:self.emit(ErrorEvent(error=f"Handler {handler_name} failed",description=str(exc),severity=ERROR_SEVERITY_ERROR,))exceptException:passifcount>=self.MAX_HANDLER_FAILURES:self._logger.warning("Auto-unsubscribing handler %s after %d failures",handler_name,count,)self._remove_handler(cb)def_remove_handler(self,cb:Callable)->None:"""Remove *cb* from every subscriber list."""withself._lock:forsubsinself._subscribers.values():fori,(_p,c)inenumerate(subs):ifciscb:subs.pop(i)break@propertydefhandler_failures(self)->Dict[str,int]:"""Copy of the handler failure counts."""returndict(self._failure_counts)defclear(self)->None:"""Remove all subscribers."""withself._lock:self._subscribers.clear()
defunsubscribe(self,event_type:Type[FriTapEvent],callback:Callable)->None:"""Remove a previously registered callback."""withself._lock:subs=self._subscribers.get(event_type,[])fori,(_,cb)inenumerate(subs):ifcb==callback:subs.pop(i)break
defemit(self,event:FriTapEvent)->None:"""Dispatch *event* to its type's subscribers and to ``FriTapEvent`` catch-alls, by descending priority."""withself._lock:specific=self._subscribers.get(type(event),[])iftype(event)isnotFriTapEvent:catch_all=self._subscribers.get(FriTapEvent,[])ifnotcatch_all:# fast pathhandlers=list(specific)else:# Merge two pre-sorted (descending priority) listshandlers=[]i,j=0,0whilei<len(specific)andj<len(catch_all):ifspecific[i][0]>=catch_all[j][0]:handlers.append(specific[i])i+=1else:handlers.append(catch_all[j])j+=1handlers.extend(specific[i:])handlers.extend(catch_all[j:])else:handlers=list(specific)for_prio,cbinhandlers:try:cb(event)exceptExceptionasexc:handler_name=getattr(cb,"__qualname__",repr(cb))self._logger.exception("Error in event subscriber %s for %s",handler_name,type(event).__name__,)count=self._failure_counts.get(handler_name,0)+1self._failure_counts[handler_name]=countifself._on_handler_errorisnotNone:try:self._on_handler_error(cb,event,exc)exceptException:pass# Guard against recursion on ErrorEvent handlers.ifnotisinstance(event,ErrorEvent):try:self.emit(ErrorEvent(error=f"Handler {handler_name} failed",description=str(exc),severity=ERROR_SEVERITY_ERROR,))exceptException:passifcount>=self.MAX_HANDLER_FAILURES:self._logger.warning("Auto-unsubscribing handler %s after %d failures",handler_name,count,)self._remove_handler(cb)
defclear(self)->None:"""Remove all subscribers."""withself._lock:self._subscribers.clear()
The bus also exposes the class constant PLUGIN_PRIORITY = 100; plugins should pass priority=EventBus.PLUGIN_PRIORITY to subscribe() so they run before the built-in output handlers.
A standalone bus can be created, subscribed to, and emitted into without any device — useful for testing handlers:
@dataclassclassFriTapConfig:""" Top-level configuration for a friTap session. Usage: config = FriTapConfig( target="com.example.app", device=DeviceConfig(mobile=True, spawn=True), output=OutputConfig(pcap="capture.pcap", keylog="keys.log"), ) """target:str# Original argv tokens for spawn mode (e.g. ["wine", "/p/My Game/app.exe"]).# Kept separate from `target` (which stays a single string for attach-by-name# / display) so spawn passes the real argv to device.spawn() instead of# re-splitting the joined string on spaces, which corrupts paths containing# spaces. None for attach mode / programmatic configs.target_argv:Optional[List[str]]=Nonedevice:DeviceConfig=field(default_factory=DeviceConfig)output:OutputConfig=field(default_factory=OutputConfig)hooking:HookingConfig=field(default_factory=HookingConfig)protocol:str="tls"# `protocols` is the canonical selection: an ordered, de-duplicated list# (e.g. ["tls", "rc4"]). `protocol` mirrors its first element for callers that# read a single string; __post_init__ keeps the two in sync.protocols:List[str]=field(default_factory=list)backend:str=BackendName.FRIDA# True when the user explicitly passed --backend (vs. the default). In "auto"# Wine mode an explicit `--backend frida` suppresses the GDB Wine route so the# experimental Frida Wine agent stays reachable.backend_explicit:bool=Falsedebug:bool=Falsedebug_output:bool=Falsecustom_hook_script:Optional[str]=Noneenvironment_file:Optional[str]=Noneinstall_lsass_hook:bool=Trueproxy:Optional[str]=None# "host:port" or "[ipv6]:port" formatdef__post_init__(self):ifself.debug:self.debug_output=True# Whichever of `protocols`/`protocol` the caller supplied, keep both# consistent: derive the list from `protocol` when only that was set,# otherwise `protocol` becomes the list's first element.ifnotself.protocols:self.protocols=[self.protocol]else:self.protocol=self.protocols[0]self._resolve_pcap_container()def_resolve_pcap_container(self)->None:"""Resolve the -p container once for this config and warn about a conflict. A helper session sharing another session's -p file (LSASS, ``auxiliary_session``) stays silent: the target session already warned. """from.pcap_utilityimportwarn_pcap_format_conflictself.output.resolve_pcap_container()ifnotself.output.auxiliary_session:warn_pcap_format_conflict(self.output.pcap,self.output.output_format)defvalidate_protocol_backend(self,protocol_handler=None,protocol_name=None)->None:"""Validate that the selected backend supports a configured protocol. Parameters ---------- protocol_handler A ProtocolHandler instance. If None, validation is skipped. protocol_name The name of the protocol being validated (used in the skip check and error message). Defaults to the primary ``self.protocol`` so existing single-handler callers are unchanged; multi-protocol callers pass one name per selected handler so each selection is validated in turn. Raises ------ UnsupportedProtocolBackendError When the backend support level is STUB or UNSUPPORTED. """name=protocol_nameorself.protocolifnamein("auto","all"):return# auto/all always start with the Frida defaultifprotocol_handlerisNone:returnfrom.protocols.baseimportBackendSupportlevel=protocol_handler.get_backend_support_level(self.backend)iflevel!=BackendSupport.FULL:supported=[nameforname,lvlinprotocol_handler.supported_backends.items()iflvl==BackendSupport.FULL]raiseUnsupportedProtocolBackendError(f"Protocol '{name}' does not fully support the "f"'{self.backend}' backend (level: {level}). "f"Supported backends: {', '.join(supported)}")@classmethoddeffrom_legacy_params(cls,app:str,pcap_name:Optional[str]=None,spawn_argv:Optional[List[str]]=None,verbose:bool=False,spawn:bool=False,keylog:bool|str=False,enable_spawn_gating:bool=False,spawn_gating_all:bool=False,enable_child_gating:bool=False,follow_exec:Optional[bool]=None,mobile:bool|str=False,live:bool=False,environment_file:Optional[str]=None,debug_mode:bool=False,full_capture:bool=False,socket_trace:bool|str=False,owner_capture:bool=False,owner_strict:bool=False,owner_no_dns:bool=False,owner_nflog_group:int=30,host:bool|str=False,offsets:Optional[str]=None,debug_output:bool=False,experimental:bool=False,wine_mode:str="auto",backend_explicit:bool=False,anti_root:bool=False,payload_modification:bool=False,library_scan:bool=False,enable_default_fd:bool=False,patterns:Optional[str]=None,custom_hook_script:Optional[str]=None,json_output:Optional[str]=None,json_keys:bool=False,output_format:str="auto",install_lsass_hook:bool=True,timeout:Optional[int]=None,script_load_timeout:float=20.0,backend:str=BackendName.FRIDA,protocol:str="tls",protocols:Optional[List[str]]=None,proxy:Optional[str]=None,filter_expression:Optional[str]=None,filter_infrastructure:bool=True,include_loopback:bool=False,auto_relabel:bool=True,force_scan_modules:Optional[List[str]]=None,quic_capture_mode:str="stream",quic_only:bool=False,no_loader_hook:bool=False,stealth_loader:bool=False,pairip_safe:bool=False,probe:bool=False,force_anchor_locator:bool=False,attribute_sdk:bool=False,quic_egress_headers_layer:str="auto",scan_keys_region:Optional[str]=None,memory_scan:bool=False,memory_scan_patterns:Optional[str]=None,memory_scan_interval:float=2.0,memory_scan_emit_unconfirmed:bool=False,memory_scan_rc4_known_plaintext:Optional[str]=None,memory_scan_rc4_ciphertext:Optional[str]=None,scan:Optional[str]=None,scan_report:str="table",scan_report_out:Optional[str]=None,scan_min_severity:str="info",scan_min_confidence:float=0.0,scan_source:Optional[str]=None,scan_category:Optional[str]=None,scan_show_pii:bool=False,scan_analyzer_path:Optional[List[str]]=None,)->"FriTapConfig":"""Build a FriTapConfig from the legacy SSL_Logger constructor parameters."""params=dict(locals())returncls(target=app,target_argv=spawn_argv,device=_legacy_device_config(params),output=_legacy_output_config(params),hooking=_legacy_hooking_config(params),protocol=protocol,protocols=list(protocols)ifprotocolselse[protocol],backend=backend,backend_explicit=backend_explicit,debug=debug_mode,debug_output=debug_output,custom_hook_script=custom_hook_script,environment_file=environment_file,install_lsass_hook=install_lsass_hook,proxy=proxy,)
@dataclassclassDeviceConfig:"""Configuration for target device connection."""device_id:Optional[str]=None# Frida device ID (from TUI enumeration)mobile:bool|str=Falsehost:Optional[str]=Nonespawn:bool=Falseenable_spawn_gating:bool=Falsespawn_gating_all:bool=Falseenable_child_gating:bool=False# Follow every instrumented process across exec() (e.g. Homebrew's python3# launcher exec()ing the real binary), in spawn and attach mode. It needs# Frida child gating, which costs ~40-50 ms per fork. Tri-state: None =# auto (off everywhere), True = --follow-exec, False =# --no-follow-exec. Read it through :func:`resolve_follow_exec`.follow_exec:Optional[bool]=Nonetimeout:Optional[int]=None# Upper bound (seconds) for the agent's blocking ``script.load()``. Without# it a wedged agent hangs the session silently. ``0`` disables the bound.script_load_timeout:float=20.0# Android multi-process capture (--profile / --discover / --also-package):# a tlsLibHunter discovery profile names the delegate and sibling processes# that carry the target's traffic; they are spawn-gated and instrumented too.profile_path:Optional[str]=Nonediscover_seconds:Optional[float]=None# --discover-baseline: idle seconds sampled first (new sockets afterwards rank first).discover_baseline:float=0.0# --discover-probe: tlsLibHunter's binder probe before discovery (finds more delegates).discover_probe:bool=Falsealso_packages:List[str]=field(default_factory=list)# --include-shared-delegates: also attach the profile's shared system processes;# their keys go to <keylog>.shared (not attributable to the target).include_shared_delegates:bool=False@propertydefprofile_capture_requested(self)->bool:"""Whether --profile, --discover or --also-package asked for a multi-process capture."""returnbool(self.profile_pathorself.discover_secondsorself.also_packages)
@dataclassclassOutputConfig:"""Configuration for output destinations and formats."""pcap:Optional[str]=Nonekeylog:Optional[str]=None# -j <file>: JSON (or *.jsonl) output file. ``-j -`` is normalized away at# construction: it sets ``json_stream`` and leaves this None, so nothing# downstream ever has to recognise the "-" sentinel.json_output:Optional[str]=None# -j -: stream JSONL events to stdout (see friTap.output.stdout_stream).json_stream:bool=False# --json-keys: put raw key material into the -j JSON/JSONL output even# without -k. Off by default: JSON output is often handed to scripts and AI# agents, so without -k/--json-keys keylog records are redacted.json_keys:bool=False# --tap <file>: write a .tap capture (decrypted flows) from a CLI session.tap_output:Optional[str]=None# Forces plaintext hooks off even when a selected handler consumes# plaintext (the LSASS helper session of a -f full-capture run).plaintext_hooks_disabled:bool=False# Requested -p container: "auto" (by extension), "pcap" or "pcapng"# (--pcap-format). Writers read the resolved ``pcap_container`` instead.output_format:str="auto"# The resolved -p container ("pcap" or "pcapng"), set by# resolve_pcap_container() when the config is built.pcap_container:str=field(default="pcap",init=False)live:bool=Falselive_mode:str=""# "", "wireshark", "live_pcapng"verbose:bool=Falsefull_capture:bool=Falsesocket_trace:bool|str=False# --owner-capture (Android/Linux). Delegate full capture to the AppTap library# to acquire an *app-scoped* pcap (kernel UID-scoped: NFLOG where supported,# else a socket-table filter) instead of capturing the whole device and# post-filtering via the Frida socket trace. owner_strict / owner_no_dns narrow# the capture breadth; owner_nflog_group selects the Tier-2 NFLOG group.owner_capture:bool=Falseowner_strict:bool=Falseowner_no_dns:bool=Falseowner_nflog_group:int=30filter_expression:Optional[str]=None# Wireshark-like display filter# Drop frida/adb infrastructure traffic (ports 5037/5555/27042/27043) by defaultfilter_infrastructure:bool=True# Include loopback/localhost traffic (e.g. a client talking to a local server,# Firefox NSS IPC). OFF by default; opt-in via --loopback, which makes a full# capture (-f) also sniff the loopback adapter and the pipeline keep loopback traffic.include_loopback:bool=False# Auto-relabel a Windows SChannel/lsass keylog by trial decryption against the# full capture at teardown (fixes TLS 1.3 label swaps + ??? client_randoms so the# keylog loads directly in Wireshark). ON by default; disable with --no-auto-relabel.auto_relabel:bool=True# A helper session that contributes to ANOTHER session's outputs: the Windows# LSASS worker (``hook_lsass`` in friTap.py) shares the target session's -p,# -k and --json paths. Its JSON session_info is recorded under# "auxiliary_sessions" so "session_info" stays the target session's.auxiliary_session:bool=False# Live passive-analysis ("scan") of observed traffic during capture.# ``scan`` is an analyzer spec (None disables; "all" / comma-list selects).scan:Optional[str]=Nonescan_report:str="table"scan_report_out:Optional[str]=Nonescan_min_severity:str="info"scan_min_confidence:float=0.0scan_source:Optional[str]=Nonescan_category:Optional[str]=Nonescan_show_pii:bool=False# External analyzer references ("module" or "module:Class") to load for the# live scan, mirroring offline ``analyze --analyzer-path``. Repeatable.scan_analyzer_path:Optional[List[str]]=Nonedef__post_init__(self)->None:ifself.json_outputisnotNone:self.set_json_target(self.json_output)self.resolve_pcap_container()defresolve_pcap_container(self)->str:"""Resolve ``pcap_container`` from ``pcap`` + ``output_format`` and return it. :class:`FriTapConfig` calls it again when it is built, so builder changes made after construction (``FriTap.pcapng()``) are picked up. """from.pcap_utilityimportresolve_pcap_formatself.pcap_container=resolve_pcap_format(self.pcap,self.output_format)returnself.pcap_containerdefset_json_target(self,path:Optional[str])->None:"""Select the -j target: a file path, or ``-`` for the stdout stream."""from.output.stdout_streamimportis_stdout_targetself.json_stream=is_stdout_target(path)self.json_output=Noneifself.json_streamelsepath@propertydefwants_json(self)->bool:"""Any -j output (file or the stdout stream) was requested."""returnbool(self.json_outputorself.json_stream)
@dataclassclassHookingConfig:"""Configuration for hooking strategies."""offsets:Optional[str]=Nonepatterns:Optional[str]=Noneexperimental:bool=False# Wine GDB key-extraction route (Linux): "auto" detects Wine targets and uses# the GDB extractor, "on" forces it on a local Linux target, "off" never uses# it (falls through to the normal Frida flow). See SSL_Logger._should_use_wine_gdb.wine_mode:str="auto"enable_default_fd:bool=Falseanti_root:bool=Falsepayload_modification:bool=Falselibrary_scan:bool=False# QUIC plaintext capture boundary: "stream" (default lower-boundary# stream-level Readv hooks) or "app-api" (Boundary-4 decoded HTTP/3# headers; Chrome/Android Google QUICHE only).quic_capture_mode:str="stream"# When True, the agent installs ONLY the Google QUICHE hooks and skips every# TLS-library hook (BoringSSL, Conscrypt, NSS, …), the Java hooks, OHTTP,# and the keylog scan-result hooks. Useful when the user only wants HTTP/3# capture: attach is dramatically lighter (no multi-megabyte Memory.scanSync# passes, no Java VM safepoint sync), which also helps fritap attach to a# target that is already in the middle of active QUIC traffic.quic_only:bool=False# When True, the agent skips the inline android_dlopen_ext loader hook. This# is the hook PairIP / anti-tamper runtimes detect and SIGSEGV on during a# spawn-time integrity scan. Only already-loaded /# explicitly-selected TLS libraries are then hooked. The agent also auto-# skips it in spawn mode when an anti-tamper library is detected.no_loader_hook:bool=False# EXPERIMENTAL (Android). Watch android_dlopen_ext via a hardware breakpoint# (ARM64 debug registers, no linker code patch) instead of the inline# trampoline, so late-loaded TLS libs can be hooked on PairIP-protected apps# without tripping the anti-tamper scan. Unvalidated on-device; default OFF.stealth_loader:bool=False# --pairip-safe (Android; attach and spawn). Minimal, scan-free capture mode# for PairIP-protected apps: hook only a curated TLS-library allowlist# (libssl.so, libhttpengine.so, libjavacrypto.so, libconscrypt*,# libcommerce_http_client.so, offset-based libwebviewchromium.so; libunity.so# is opt-in via --offsets), resolved WITHOUT any Memory.scan (exports -># symbols -> offsets). Skips the loader hook, WebView/Cronet pattern scan,# Java hooks, OHTTP and the library-scan pass: the broad footprint that trips# PairIP's periodic integrity check (an in-process SIGSEGV). Keys persist via# "blink" (hooks toggled so .text stays pristine between scans). Default OFF.pairip_safe:bool=False# --probe. Dry-run diagnostic: the agent reports which platform branch it# selected and then stops BEFORE installing any hook. Exists because a# target that dies during instrumentation leaves the user with no way to# learn how far friTap got. Boolean on purpose: staged verbosity# levels would duplicate -v/-do.probe:bool=False# --boringssl-anchor-only (Android arm64; debugging aid). Force friTap's# last-resort BoringSSL keylog tier (the "anchor locator") by skipping the# byte-pattern tier, so a fully-stripped BoringSSL lib (Chrome libchrome.so,# libhttpengine.so) routes straight to onAllKeylogTiersMissed -> tier 4. Lets# the anchor locator be exercised on modules a pattern would otherwise win.# Still honours --pairip-safe (tier 4 is a memory scan). Default OFF.force_anchor_locator:bool=False# --attribute-sdk: capture the calling thread's backtrace once per connection# at the first TLS plaintext hook and emit it as a `caller_stack` message for# SDK / app attribution. Metadata only; never alters captured traffic.attribute_sdk:bool=False# Override which layer of the HTTP/3 egress-headers fallback chain the# agent actually attaches to. "auto" (default) keeps the winner-takes-all# logic: quiche-internal QuicSpdyStream::WriteHeaders preferred, then# net::QuicChromiumClientStream::WriteHeaders, then# quic::QuicSpdySession::WriteHeadersOnHeadersStream as a last-resort gQUIC# fallback. Set to "chrome-shim" or "session-level" to FORCE a fallback# layer for testing, e.g. to validate the chain on builds where# the quiche-internal layer still resolves. Only effective in app-api mode.quic_egress_headers_layer:str="auto"# Generic memory-region key-scan target (--scan-keys-region). None disables# the scan. Passed through to the agent via config_batch.extensions.scan_region;# protocol-agnostic (the public scan engine and any private scan binding both# read it). See agent/shared/scan/.scan_keys_region:Optional[str]=None# Heap secret-scanner (--memory-scan / -ms). When True, friTap loads a# separate, independently-injected agent (friTap/fritap_memscan.js) that# recovers TLS secrets by scanning process heap memory instead of hooking# the TLS library. It is complementary to the normal capture: passed alone,# it is the ONLY thing loaded (the main TLS-hooking agent is skipped);# combined with -k/-p/-c it runs alongside them. memory_scan_patterns is the# optional -ms value: either a path to a user profile file that# overrides/extends the shipped friTap/memory_scanning/patterns.json,# OR a targeted engine name (boringssl | schannel | rc4) / profile id.# The resolver (memory_scanning.loader.select_profiles) disambiguates by# resolution order: an existing file wins, then a known engine/id, so this# single field carries both meanings. memory_scan_interval is the poll# cadence (seconds) at which the host drives the scanner's scanOnce().memory_scan:bool=Falsememory_scan_patterns:Optional[str]=Nonememory_scan_interval:float=2.0# Opt-in (--ms-emit-unconfirmed): also write memory-scan key candidates the# confirmation oracle could not verify (MTProto auth/E2E) to the keylog. OFF# by default; harmless offline since a wrong candidate matches no record.memory_scan_emit_unconfirmed:bool=False# RC4 memory-scanner oracles (--ms-rc4-known-plaintext / --ms-rc4-ciphertext).# There is no SSPI oracle on Android, so these inject a known-plaintext prefix# (an exact, zero-false-accept key test) and/or a ciphertext sample (for# trial-decrypt scoring) into the rc4 profile's params via# memory_scanning.loader.apply_rc4_param_overrides. Each accepts hex or plain# text; None (the default) leaves the profile untouched.memory_scan_rc4_known_plaintext:Optional[str]=Nonememory_scan_rc4_ciphertext:Optional[str]=None# Whether the main hooking agent (interception) runs at all. The TUI's# "Key Extraction Method" step sets this False for a memory-scan-only run;# see memory_scan_only(). The CLI leaves it True and relies on inference.intercept:bool=Trueencapsulated_protocols:Dict[str,bool]=field(default_factory=lambda:{"ohttp":True})# Module names that should bypass the Cronet-split-topology suppression# check, even when friTap would otherwise treat them as covered by a# sibling library. Accepts literal names, prefixes (a value ending in '*'# is treated as a stem prefix), or regexes prefixed with "re:".force_scan_modules:List[str]=field(default_factory=list)@propertydefohttp_enabled(self)->bool:returnself.encapsulated_protocols.get("ohttp",True)def__post_init__(self)->None:env_value=os.environ.get("FRITAP_FORCE_SCAN")ifenv_value:extra=[item.strip()foriteminenv_value.split(",")ifitem.strip()]foriteminextra:ifitemnotinself.force_scan_modules:self.force_scan_modules.append(item)
HookingConfig exposes the encapsulated-protocol toggle ohttp_enabled (OHTTP is on by default within --protocol tls) and the QUIC knobs quic_capture_mode, quic_only, and quic_egress_headers_layer.
FriTapConfig.from_legacy_params(...) bridges the old flat SSL_Logger keyword arguments (app, pcap_name, keylog, mobile, patterns, …) into the structured dataclasses, so existing code can move incrementally:
A Flow is friTap's reconstructed picture of one connection: endpoints, timing, parsed request/response, a protocol layer stack, and any attached findings. Flows are produced live (via on_flow) and read back from .tap files (see Reading .tap).
@dataclassclassFlow:# Identityflow_id:str=""connection_id:str=""src_addr:str=""src_port:int=0dst_addr:str=""dst_port:int=0ssl_session_id:str=""# Transport of the connection: "tls" (default) or "quic"; stamped from ``event.protocol``# at creation (FlowCollector._stamp_metadata). LayerPipeline reads it to pick TlsLayer vs QuicLayer.transport:str="tls"# Statestate:FlowState=FlowState.ACTIVEstarted:float=field(default_factory=time.time)ended:float=0.0# Parsed (from parsers module)request:Optional[ParseResult]=Noneresponse:Optional[ParseResult]=None# OHTTP inner payloads (decrypted bhttp, from NSS HPKE hooks)ohttp_inner_request:Optional[ParseResult]=Noneohttp_inner_response:Optional[ParseResult]=None# Trailing data (unconsumed bytes after valid WebSocket/protocol frames)trailing_bytes:Optional[bytes]=Nonetrailing_protocol:str=""trailing_parse:Optional[ParseResult]=None# Trailing data left in the READ (response) direction; the trailing_* slot above keeps# write-direction / direction-less leftovers so direction-less parsers are unchanged.response_trailing_bytes:Optional[bytes]=Noneresponse_trailing_protocol:str=""response_trailing_parse:Optional[ParseResult]=None# Rawchunks:list[FlowChunk]=field(default_factory=list)# Cached byte total (incremented by FlowCollector when appending chunks)._total_bytes:int=0# True once the flow exceeded the per-flow retained-payload cap (MAX_FLOW_CHUNK_BYTES):# ``_total_bytes`` keeps counting but later chunks are not retained.truncated:bool=False# Protocol detected by the parser registry even without a request/response yet; display fallback before "unknown".detected_protocol:str=""# Schema v2 additive enrichment fields (all optional).# Role labels for the endpoints: ``src_*``/``dst_*`` stay the canonical transport endpoints;# these name the same ends as local (instrumented process) / remote (peer). Stored fields# (set by tap_format.decode_flow and the collector, persisted as their own meta keys),# derived from src/dst in ONE place, FlowCollector._enrich_flow; everything else only reads them.local_addr:str=""local_port:int=0remote_addr:str=""remote_port:int=0# Process / package identity (from the capture target / agent).process_name:str=""package_name:str=""# Origin of the flow's first event when friTap follows several processes# (FriTapEvent.process_origin): pid and role ("target", "child", "spawn").# Persisted into the .tap meta only when set.pid:Optional[int]=Noneprocess_role:str=""# Resolved SDK attribution (``--attribute-sdk``): the trusted ``{"sdk", "vendor", "category"}``# dict from the bundled signature table (friTap/analysis/attribution/sdk.py), or ``None``.# Persisted into the .tap meta only when set.sdk:Optional[dict]=None# Compact caller stack of the flow's connection (``--attribute-sdk``), stored whether or not it# matched an SDK: ``{transport_module, thread_name, tid, pid, native_frames[:8], java_frames[:8]}``,# strings escaped and capped at 80 chars (friTap/caller_stack_shapes.py). Target-controlled# text; ``None`` when no stack was joined. Persisted only when set.caller_stack:Optional[dict]=None# Transport vs originator attribution (friTap/flow/attribution.py): ``{"transport": {module, kind},# "originator": {sdk, vendor, category}, "confidence", "source", "bucket", "mixed": True}``, every# key optional. Transport is stamped on every TLS/QUIC flow with a known library; originator only# when a classified caller stack joined.attribution:Optional[dict]=None# True while src/dst (and local/remote) are a synthetic 198.18.0.0/15 pin for an fd-less# connection (option 5, friTap/endpoint_pinner.py); cleared when the real tuple is observed.# Persisted only when True.endpoints_synthetic:bool=False# Ordered layer stack (outermost transport -> innermost), e.g. [tls, http2]; per-flow LINEAR# (HTTP/2-3 streams are separate flows). ``flow.tls`` / ``flow.quic`` / ``flow.ssh`` resolve# by name via __getattr__ (lazily created empty, so ``flow.tls.sni`` is never None). Whole-layer# writes go through add_layer/set_layer; field mutation works on the cached instance.layers:list[ProtocolLayer]=field(default_factory=list,repr=False)# Hook origin: ``hook_function`` mirrors the dominant chunk.function; ``hook_stack`` is reserved.hook_function:str=""hook_stack:str=""# Mutable analyst annotations.tags:list[str]=field(default_factory=list)notes:str=""# Attached findings, typed loosely to avoid importing ``friTap.analysis`` here (it imports models under TYPE_CHECKING).findings:list=field(default_factory=list)# (chunks list, scanned length, id so far or _MIXED_STREAMS) backing# ``stream_id``._stream_id_cache:Optional[tuple]=field(default=None,init=False,repr=False,compare=False)@propertydefstream_id(self)->Optional[int]:"""Real transport stream id when every id-carrying chunk agrees (None if none or mixed). Chunks are append-only, so the cache is keyed on the list object (held, so its id cannot be reused) and only the new tail is scanned. """chunks=self.chunks# Snapshot the length first: chunks appended concurrently after this# point stay unscanned for the next call.end=len(chunks)cache=self._stream_id_cacheifcacheisnotNoneandcache[0]ischunksandcache[1]<=end:scanned,found=cache[1],cache[2]else:scanned,found=0,Noneiffoundisnot_MIXED_STREAMS:forindexinrange(scanned,end):sid=chunks[index].stream_idifsidisNone:continueiffoundisNone:found=sidelifsid!=found:found=_MIXED_STREAMSbreakifend!=scanned:self._stream_id_cache=(chunks,end,found)returnNoneiffoundis_MIXED_STREAMSelsefound# ------------------------------------------------------------------# Protocol layer access (flow.<protocol> -> typed ProtocolLayer)# ------------------------------------------------------------------def__getattr__(self,name:str):# Only invoked when normal lookup fails. Resolves a registered protocol name to its# layer, lazily creating an empty one (so flow.tls/flow.quic are never None); anything# else raises AttributeError so getattr(flow, x, default) (filter engine, copy/pickle# probing) keeps working. This attaches by design (``flow.tls.version = ...`` persists):# PURE-READ probes (serializers, snapshots) must use the non-mutating :meth:`layer`.ifname.startswith("_"):raiseAttributeError(name)layers=self.__dict__.get("layers")iflayersisNone:# Half-constructed (e.g. during copy/unpickle before fields set).raiseAttributeError(name)desc=get_registry().get(name)ifdescisNone:raiseAttributeError(name)forlyinlayers:ifly.name==name:returnlyreturnself._create_layer(name,desc)def_create_layer(self,name:str,desc)->ProtocolLayer:layer=desc.layer_cls()# Per-instance name so generic layers (AppLayer, one class under several names) report the right ``name``.layer._name=namelayer.depth=len(self.layers)layer._flow=selfifdesc.data_source=="chunks":layer.data=LayerData(data_source="chunks",_owner=self)self.layers.append(layer)returnlayerdeflayer(self,name:str)->Optional[ProtocolLayer]:"""Return the layer named *name*, or None if not present."""forlyinself.layers:ifly.name==name:returnlyreturnNonedefadd_layer(self,layer:ProtocolLayer)->ProtocolLayer:"""Append *layer* to the stack, linking parent/child + binding data."""layer.depth=len(self.layers)ifself.layers:parent=self.layers[-1]parent.child=layerlayer.parent=parentlayer._flow=selfiflayer.data.data_source=="chunks"andlayer.data._ownerisNone:layer.data._owner=selfself.layers.append(layer)returnlayerdefset_layer(self,layer:ProtocolLayer)->ProtocolLayer:"""Replace an existing same-name layer in place, else append it."""fori,existinginenumerate(self.layers):ifexisting.name==layer.name:layer.depth=existing.depthlayer.parent,layer.child=existing.parent,existing.childlayer._flow=selfiflayer.data.data_source=="chunks"andlayer.data._ownerisNone:layer.data._owner=selfself.layers[i]=layerreturnlayerreturnself.add_layer(layer)def__copy__(self)->"Flow":# Shallow copy that re-lists the mutable containers (chunks, layers) so appends to a live# flow do not mutate a snapshot; elements are shared.new=Flow.__new__(Flow)new.__dict__.update(self.__dict__)new.chunks=list(self.chunks)new.layers=list(self.layers)returnnew@propertydefhas_trailing_data(self)->bool:returnself.trailing_bytesisnotNone@propertydefhas_response_trailing_data(self)->bool:returnself.response_trailing_bytesisnotNone@propertydefsegments(self)->list[dict]:"""Segment descriptors for multi-protocol rendering. Each is a dict with keys type ('parsed'|'raw'), protocol, parse_result (or None), data (raw bytes for 'raw'), source. The response-direction trailing segment (source ``"response_trailing"``) is last. The TUI addresses segments PER PANE: segment 1 is that pane's own trailing segment (see ``pane_segments``). """segs:list[dict]=[]ifself.requestisnotNone:segs.append({"type":"parsed","protocol":self.display_protocol,"parse_result":self.request,"source":"primary",})segs.extend(self._trailing_segments(self.trailing_bytes,self.trailing_protocol,self.trailing_parse,"trailing"))segs.extend(self._trailing_segments(self.response_trailing_bytes,self.response_trailing_protocol,self.response_trailing_parse,"response_trailing"))returnsegsdefpane_segments(self,pane:str)->list[dict]:"""Segments shown on one detail pane: primary plus that pane's trailing. *pane* is ``"request"`` or ``"response"``; index 0 is the primary message, index 1 (when present) the pane's trailing segment. """trailing_source="response_trailing"ifpane=="response"else"trailing"return[sforsinself.segmentsifs["source"]in("primary",trailing_source)]@staticmethoddef_trailing_segments(data:Optional[bytes],protocol:str,parse:Optional[ParseResult],source:str)->list[dict]:"""0 or 1 segment descriptor for one trailing slot."""ifparseisnotNone:return[{"type":"parsed","protocol":protocol,"parse_result":parse,"source":source}]ifdata:return[{"type":"raw","protocol":protocolor"unknown","data":data,"source":source}]return[]@propertydefduration(self)->float:ifself.ended>0:returnself.ended-self.startedreturntime.time()-self.started@propertydefdisplay_method(self)->str:return_display.display_method_layered(self)@propertydefdisplay_host(self)->str:return_display.display_host(self.request,self.dst_addr,self.dst_port)@propertydefdisplay_status(self)->str:return_display.display_status(self.response)@propertydefdisplay_size(self)->str:total_bytes=self._total_bytesiftotal_bytes==0andself.chunks:total_bytes=sum(len(c.data)forcinself.chunks)return_display.display_size(self.response,total_bytes)@propertydefdisplay_protocol(self)->str:return_display.display_protocol(self)@propertydefhas_request_data(self)->bool:ifself.requestisnotNone:returnTruereturnany(c.direction=="write"forcinself.chunks)@propertydefhas_response_data(self)->bool:ifself.responseisnotNone:returnTruereturnany(c.direction=="read"forcinself.chunks)defget_direction_bytes(self,direction:str,max_bytes:int=0)->bytes:"""Get concatenated raw bytes for a given direction ('read' or 'write'). If *max_bytes* > 0, stop accumulating after that many bytes. """ifmax_bytes<=0:returnb"".join(c.dataforcinself.chunksifc.direction==direction)parts:list[bytes]=[]total=0forcinself.chunks:ifc.direction!=direction:continueparts.append(c.data)total+=len(c.data)iftotal>=max_bytes:breakreturnb"".join(parts)@propertydefdisplay_source(self)->str:return_display.display_source(self.src_addr,self.src_port)@propertydefdisplay_connection(self)->str:"""Directional connection string: src -> dst, src <- dst, or src <-> dst."""return_display.display_connection(self.requestifself.has_request_dataelseNone,self.responseifself.has_response_dataelseNone,self.src_addr,self.src_port,self.dst_addr,self.dst_port,literal_direction=_display.is_message_transport(self),)defto_dict(self,include_bodies:bool=False)->dict:"""Return a JSON-safe dict view of this flow for API/web consumers. Covers identity, transport/timing, parsed request/response, layer names, annotations and findings. Chunk bytes are never included; bodies only (hex) when *include_bodies*. Uses the non-mutating :meth:`layer` so serializing never grows the layer stack. """tls=self.layer("tls")total_bytes=self._total_bytesorsum(len(c.data)forcinself.chunks)out={"flow_id":self.flow_id,"connection_id":self.connection_id,"src_addr":self.src_addr,"src_port":self.src_port,"dst_addr":self.dst_addr,"dst_port":self.dst_port,"ssl_session_id":self.ssl_session_id,"transport":self.transport,"state":self.state.valueifisinstance(self.state,FlowState)elsestr(self.state),"started":self.started,"ended":self.ended,# Deterministic: avoid the wall-clock ``duration`` for in-progress flows."duration":(self.ended-self.started)ifself.ended>0else0.0,"protocol":self.display_protocol,"detected_protocol":self.detected_protocol,"total_bytes":total_bytes,"process_name":self.process_name,"package_name":self.package_name,"tls_sni":tls.sniiftlsisnotNoneelse"","tls_alpn":tls.alpniftlsisnotNoneelse"","layers":[ly.nameforlyinself.layers],"tags":list(self.tags),"notes":self.notes,"request":self.request.to_dict(include_body=include_bodies)ifself.requestelseNone,"response":self.response.to_dict(include_body=include_bodies)ifself.responseelseNone,"findings":[f.to_dict()forfinself.findings],}returnput_stream_id(out,self.stream_id)# Cache for reconstructed bodies: {direction: bytes}._body_cache:dict=field(default_factory=dict,repr=False)defreconstruct_body(self,direction:str)->bytes:"""Reconstruct the body for *direction* from raw chunks, cached per direction."""ifdirectioninself._body_cache:returnself._body_cache[direction]proto=self.display_protocol.lower()if"http/2"inproto:body=self._extract_h2_body(direction)elif"http/3"inproto:body=self._extract_h3_body(direction)elif"http/1"inproto:body=self._extract_h1_body(direction)elif"websocket"inproto:body=self._extract_ws_body(direction)else:body=b""self._body_cache[direction]=bodyreturnbodydefinvalidate_body_cache(self)->None:"""Clear cached body data (call when chunks change)."""self._body_cache.clear()def_extract_h1_body(self,direction:str)->bytes:"""Extract HTTP/1 body by re-parsing raw bytes with h11."""try:importh11exceptImportError:returnb""raw=self.get_direction_bytes(direction)ifnotraw:returnb""conn=h11.Connection(h11.CLIENTifdirection=="read"elseh11.SERVER)conn.receive_data(raw)body_parts:list[bytes]=[]whileTrue:try:event=conn.next_event()excepth11.ProtocolError:# Malformed (attacker-controlled) framing: keep what parsed.breakifeventish11.NEED_DATAoreventish11.PAUSED:breakifisinstance(event,h11.Data):body_parts.append(bytes(event.data))elifisinstance(event,h11.EndOfMessage):breakreturnb"".join(body_parts)def_extract_h2_body(self,direction:str)->bytes:"""Extract HTTP/2 DATA payloads from raw chunks (stateless scan, no HPACK). Without a parsed message the flow's own stream is used; stream id 0 (unknown) keeps every stream's DATA. """fromfriTap.parsers.http2_dataframeimporthttp2_data_for_streammsg=self.requestifdirection=="write"elseself.responseifmsgisnotNone:stream_id=msg.stream_idelse:stream_id=self.stream_idor0body,_degraded=http2_data_for_stream(self.get_direction_bytes(direction),stream_id)returnbodydef_extract_h3_body(self,direction:str)->bytes:"""Extract HTTP/3 DATA frame payloads using varint framing."""fromfriTap.parsers.http3importiter_h3_data_framesreturnb"".join(iter_h3_data_frames(self.get_direction_bytes(direction)))def_extract_ws_body(self,direction:str)->bytes:"""Extract WebSocket payload — body is already in ParseResult for WS."""msg=self.requestifdirection=="write"elseself.responseifmsgisnotNoneandmsg.body:returnmsg.bodyreturnb""@staticmethoddef_get_header(msg:"Optional[ParseResult]",name:str,default:str="")->str:ifmsgisNone:returndefaultlower_name=name.lower()forkey,valueinmsg.headers.items():ifkey.lower()==lower_name:returnvaluereturndefaultdef_get_decompressed_body(self,msg:"Optional[ParseResult]",direction:str,encoding_override:str="",max_out:Optional[int]=None,)->bytes:"""Decompressed body of *msg*, output bounded by *max_out*. Defaults to ``MAX_DECOMPRESSED_BODY`` (explicit saves); the automatic paths pass the smaller ``MAX_AUTO_DECOMPRESS``. Cached in ``_body_cache`` per (direction, encoding, max_out). """ifmsgisNone:returnb""body=msg.bodyifmsg.bodyelseself.reconstruct_body(direction)ifnotbody:returnb""encoding=encoding_overrideormsg.content_encodingorself._content_encoding_header(msg)ifnotencoding:returnbodyfromfriTap.parsers.decompressimportMAX_DECOMPRESSED_BODY,decompress_bodylimit=MAX_DECOMPRESSED_BODYifmax_outisNoneelsemax_outkey=("decompressed",direction,encoding,limit)cached=self._body_cache.get(key)ifcachedisnotNoneandcached[0]ismsgandcached[1]isbody:returncached[2]data,_err=decompress_body(body,encoding,limit)self._body_cache[key]=(msg,body,data)returndata@staticmethoddef_content_encoding_header(msg:"ParseResult")->str:"""The message's Content-Encoding header value, or ``""``."""forkey,valueinmsg.headers.items():ifkey.lower()=="content-encoding":returnvaluereturn""defget_request_header(self,name:str,default:str="")->str:"""Get a request header value by name (case-insensitive)."""returnself._get_header(self.request,name,default)defget_response_header(self,name:str,default:str="")->str:"""Get a response header value by name (case-insensitive)."""returnself._get_header(self.response,name,default)@propertydefrequest_body(self)->bytes:"""The request body (possibly compressed), or ``b""``."""ifself.requestandself.request.body:returnself.request.bodyreturnself.reconstruct_body("write")@propertydefresponse_body(self)->bytes:"""The response body (possibly compressed), or ``b""``."""ifself.responseandself.response.body:returnself.response.bodyreturnself.reconstruct_body("read")defget_decompressed_request_body(self)->bytes:"""Return the request body after decompressing (gzip/br/zstd/deflate)."""fromfriTap.parsers.decompressimportMAX_AUTO_DECOMPRESSreturnself._get_decompressed_body(self.request,"write",max_out=MAX_AUTO_DECOMPRESS)defget_decompressed_response_body(self)->bytes:"""Return the response body after decompressing (gzip/br/zstd/deflate)."""fromfriTap.parsers.decompressimportMAX_AUTO_DECOMPRESSreturnself._get_decompressed_body(self.response,"read",max_out=MAX_AUTO_DECOMPRESS)@propertydefresponse_content_type(self)->str:"""The response Content-Type, or ``""`` if unavailable."""ifself.responseisnotNoneandself.response.content_type:returnself.response.content_typereturnself.get_response_header("content-type")@propertydefrequest_content_type(self)->str:"""The request Content-Type, or ``""`` if unavailable."""ifself.requestisnotNoneandself.request.content_type:returnself.request.content_typereturnself.get_request_header("content-type")defdecode_request_protobuf(self,schema_path:Optional[str]=None,force:bool=False,message_type:Optional[str]=None,)->Optional["ProtobufView"]:"""Decode the request body as protobuf (gRPC framing auto-detected). Returns a :class:`~friTap.parsers.protobuf.view.ProtobufView`, or ``None`` when the body is empty or not protobuf-like. A view may hold no decoded message: check ``view.ok``, ``view.notes`` / ``view.error``. Args: schema_path: Optional ``.proto`` or compiled ``.desc`` descriptor set, used with *message_type*. Without both, the wire decoder runs and a note says why. force: If ``True``, decode regardless of content type. message_type: Fully qualified message type for *schema_path*. """returnself._decode_protobuf(self.get_decompressed_request_body(),self.request_content_type,self.get_request_header("grpc-encoding"),schema_path=schema_path,force=force,message_type=message_type,)defdecode_response_protobuf(self,schema_path:Optional[str]=None,force:bool=False,message_type:Optional[str]=None,)->Optional["ProtobufView"]:"""Decode the response body as protobuf (gRPC framing auto-detected). Same contract as :meth:`decode_request_protobuf`, for the response. """returnself._decode_protobuf(self.get_decompressed_response_body(),self.response_content_type,self.get_response_header("grpc-encoding"),schema_path=schema_path,force=force,message_type=message_type,)@staticmethoddef_decode_protobuf(body:bytes,content_type:str,grpc_encoding:str,schema_path:Optional[str]=None,force:bool=False,message_type:Optional[str]=None,)->Optional["ProtobufView"]:"""Internal: gate on content type, then delegate to the shared view decoder."""ifnotbody:returnNonefromfriTap.parsers.protobufimport(decode_protobuf_view,is_grpc_content_type,is_likely_protobuf,is_protobuf_content_type,)is_proto_ct=is_grpc_content_type(content_type)oris_protobuf_content_type(content_type)ifnotforceandnotis_proto_ctandnotis_likely_protobuf(body):returnNonereturndecode_protobuf_view(body,content_type=content_type,grpc_encoding=grpc_encoding,schema_path=schema_pathor"",message_type=message_typeor"",)
Return a JSON-safe dict view of this flow for API/web consumers.
Covers identity, transport/timing, parsed request/response, layer names, annotations and findings. Chunk bytes are never included; bodies only (hex) when include_bodies. Uses the non-mutating :meth:layer so serializing never grows the layer stack.
defto_dict(self,include_bodies:bool=False)->dict:"""Return a JSON-safe dict view of this flow for API/web consumers. Covers identity, transport/timing, parsed request/response, layer names, annotations and findings. Chunk bytes are never included; bodies only (hex) when *include_bodies*. Uses the non-mutating :meth:`layer` so serializing never grows the layer stack. """tls=self.layer("tls")total_bytes=self._total_bytesorsum(len(c.data)forcinself.chunks)out={"flow_id":self.flow_id,"connection_id":self.connection_id,"src_addr":self.src_addr,"src_port":self.src_port,"dst_addr":self.dst_addr,"dst_port":self.dst_port,"ssl_session_id":self.ssl_session_id,"transport":self.transport,"state":self.state.valueifisinstance(self.state,FlowState)elsestr(self.state),"started":self.started,"ended":self.ended,# Deterministic: avoid the wall-clock ``duration`` for in-progress flows."duration":(self.ended-self.started)ifself.ended>0else0.0,"protocol":self.display_protocol,"detected_protocol":self.detected_protocol,"total_bytes":total_bytes,"process_name":self.process_name,"package_name":self.package_name,"tls_sni":tls.sniiftlsisnotNoneelse"","tls_alpn":tls.alpniftlsisnotNoneelse"","layers":[ly.nameforlyinself.layers],"tags":list(self.tags),"notes":self.notes,"request":self.request.to_dict(include_body=include_bodies)ifself.requestelseNone,"response":self.response.to_dict(include_body=include_bodies)ifself.responseelseNone,"findings":[f.to_dict()forfinself.findings],}returnput_stream_id(out,self.stream_id)
deflayer(self,name:str)->Optional[ProtocolLayer]:"""Return the layer named *name*, or None if not present."""forlyinself.layers:ifly.name==name:returnlyreturnNone
defreconstruct_body(self,direction:str)->bytes:"""Reconstruct the body for *direction* from raw chunks, cached per direction."""ifdirectioninself._body_cache:returnself._body_cache[direction]proto=self.display_protocol.lower()if"http/2"inproto:body=self._extract_h2_body(direction)elif"http/3"inproto:body=self._extract_h3_body(direction)elif"http/1"inproto:body=self._extract_h1_body(direction)elif"websocket"inproto:body=self._extract_ws_body(direction)else:body=b""self._body_cache[direction]=bodyreturnbody
Each FlowChunk has a stream_id (int | None): the real transport stream id the chunk travelled on (HTTP/2 stream id, QUIC stream id), or None when it is unknown. Flow.stream_id is the one id shared by all id-carrying chunks of the flow, and None when there is none or more than one. Flow.to_dict() and FlowSummary.to_dict() include stream_id only when it is set. The stream_id of an HTTP/3 flow.request / flow.response is a collector-internal remapped id, not the QUIC stream id.
flow.stream_id# e.g. 4, or None[ch.stream_idforchinflow.chunks]# per chunk
Flow.to_dict(include_bodies=False) returns a JSON-safe view: identity, transport/timing, parsed request/response, layer names, tags/notes and findings. Raw chunk bytes are never included; request/response bodies are included (hex-encoded) only when include_bodies=True.
Each flow carries a stack of protocol layers. Access them two ways:
Attribute access — flow.tls, flow.quic, flow.ssh lazily materialize a typed layer if that protocol is registered (raises AttributeError for an unregistered name). Typed layers expose fields such as flow.tls.sni and flow.tls.alpn.
flow.layer(name) — a non-mutating lookup returning the existing layer or None. Use this in serialization paths so reading never grows the stack: flow.layer("http2"), then inspect .parsed / .data.
sni=flow.tls.sni# typed accessorhttp2=flow.layer("http2")# None if absentifhttp2isnotNone:parsed=http2.parsed
Bodies are not accumulated in the parser's ParseResult anymore — to keep .tap files small, identical/large bodies are reconstructed on demand from the flow's raw chunks. So a ParseResult (flow.request / flow.response) can have an empty .body even when data was captured. To get the bytes, reconstruct from the flow:
FlowSummary is the lightweight index entry used when listing flows without reading their full bodies (returned by read_flow_summaries() / get_summaries()).
@dataclass(frozen=True,slots=True)classFlowSummary:"""Lightweight scalar snapshot of a Flow (~200 bytes, no chunks/bodies) for list display and filtering. ``request``/``response`` stubs use ParseResult's attribute names for the filter engine. """flow_id:str=""connection_id:str=""src_addr:str=""src_port:int=0dst_addr:str=""dst_port:int=0ssl_session_id:str=""state:FlowState=FlowState.ACTIVEstarted:float=0.0ended:float=0.0# Mirrors Flow.transport ("tls", "quic", "signal", ...) for grouping without the full Flow.transport:str="tls"request:Optional[_ParseStub]=Noneresponse:Optional[_ParseStub]=Nonehas_ohttp:bool=Falsehas_trailing_data:bool=Falsetrailing_protocol:str=""has_response_trailing_data:bool=Falseresponse_trailing_protocol:str=""total_bytes:int=0detected_protocol:str=""# Schema v2 additive enrichment scalars (cheap to surface in list/filter views)process_name:str=""tls_sni:str=""tls_alpn:str=""tag_count:int=0finding_count:int=0has_notes:bool=False# Layered protocol-display scalars (display.display_protocol_layered).outer_app_protocol:str=""inner_e2e_protocol:str=""inner_summary:str=""# Primary TL operation from message-bearing layers (display.method_from_messages), shown in the Method column.flow_method:str=""# Real transport stream id of a single-stream flow (see Flow.stream_id).stream_id:Optional[int]=None# Precomputed display-filter inputs so filtering matches on a live flow and on a row rebuilt# from a .tap (no layer stack): ``filter_attrs`` maps per-protocol fields (friTap.filter.layer_fields)# to values, ``protocols`` holds canonical names (friTap.filter.protocols). Plain dict (pickles,# survives asdict) and READ-ONLY; unhashable, so excluded from hash().filter_attrs:Mapping[str,tuple]=field(default_factory=dict,hash=False)protocols:frozenset[str]=frozenset()@propertydefduration(self)->float:ifself.ended>0:returnself.ended-self.startedreturntime.time()-self.started@propertydefdisplay_protocol(self)->str:return_display.display_protocol(self)@propertydefdisplay_protocol_layered(self)->str:return_display.display_protocol_layered(self)@propertydefdisplay_method(self)->str:return_display.display_method_layered(self)@propertydefdisplay_host(self)->str:return_display.display_host(self.request,self.dst_addr,self.dst_port)@propertydefdisplay_status(self)->str:return_display.display_status(self.response)@propertydefdisplay_size(self)->str:return_display.display_size(self.response,self.total_bytes)@propertydefdisplay_source(self)->str:return_display.display_source(self.src_addr,self.src_port)@propertydefdisplay_connection(self)->str:return_display.display_connection(self.request,self.response,self.src_addr,self.src_port,self.dst_addr,self.dst_port,literal_direction=_display.is_message_transport(self),)# Aliases for filter engine compatibility@propertydef_total_bytes(self)->int:returnself.total_bytes@propertydefohttp_inner_request(self):# Filter engine only checks `is not None`: return a truthy sentinel.return_OHTTP_SENTINELifself.has_ohttpelseNone@propertydefohttp_inner_response(self):return_OHTTP_SENTINELifself.has_ohttpelseNone@staticmethoddeffrom_flow(flow:"Flow",filter_attrs:Optional[Mapping[str,tuple]]=None,)->"FlowSummary":"""Summary snapshot of a full Flow; *filter_attrs* reuses attributes already extracted for an unchanged layer stack (live rebuilds)."""fields=shared_summary_fields(flow,filter_attrs)# Prefer a scalar already set on the flow (a layerless flow rebuilt from a .tap summary),# since layered_scalars_from_flow returns "" without a layer stack.fornamein("outer_app_protocol","inner_e2e_protocol","inner_summary"):fields[name]=getattr(flow,name,"")orfields[name]returnFlowSummary(**fields,state=flow.state,request=_parse_stub(flow.request),response=_parse_stub(flow.response),has_trailing_data=flow.trailing_bytesisnotNone,trailing_protocol=flow.trailing_protocol,has_response_trailing_data=flow.response_trailing_bytesisnotNone,response_trailing_protocol=flow.response_trailing_protocol,total_bytes=flow._total_bytes,detected_protocol=flow.detected_protocol,process_name=flow.process_name,)@staticmethoddeffrom_tap_summary(tap_summary:Any,flow:"Flow")->"FlowSummary":"""Summary for a replay row: *flow* is the layerless synthetic Flow rebuilt from *tap_summary*. It has no layer stack or OHTTP payloads, so the filter inputs decoded from the tap's ``meta["layers"]`` are taken over; only protocols of a re-parsed request/response are added. """summary=FlowSummary.from_flow(flow,filter_attrs=tap_summary.filter_attrs)returnreplace(summary,protocols=tap_summary.protocols|summary.protocols,has_ohttp=summary.has_ohttportap_summary.has_ohttp,# The synthetic flow has no chunks to derive the stream id from.stream_id=(summary.stream_idifsummary.stream_idisnotNoneelsetap_summary.stream_id),)defto_dict(self)->dict:"""Return a JSON-safe, body-free overview dict. Same key set as :meth:`friTap.flow.tap_format.FlowSummary.to_dict`, so live and offline summaries render identically. """req,resp=self.request,self.responseout={"flow_id":self.flow_id,"connection_id":self.connection_id,"src_addr":self.src_addr,"src_port":self.src_port,"dst_addr":self.dst_addr,"dst_port":self.dst_port,"ssl_session_id":self.ssl_session_id,"state":self.state.valueifisinstance(self.state,FlowState)elsestr(self.state),"started":self.started,"ended":self.ended,"transport":self.transport,# Deterministic, parity with the offline shape: the ``duration`` property uses# wall-clock time for in-progress flows, so a snapshot uses 0.0 until completion."duration":(self.ended-self.started)ifself.ended>0else0.0,"protocol":(self.detected_protocolor(req.protocolifreqelse"")or(resp.protocolifrespelse"")or"unknown"),"method":req.methodifreqelse"","url":req.urlifreqelse"","host":req.hostifreqelse"","status_code":resp.status_codeifrespelse0,"total_bytes":self.total_bytes,"detected_protocol":self.detected_protocol,"process_name":self.process_name,"tls_sni":self.tls_sni,"tls_alpn":self.tls_alpn,"tag_count":self.tag_count,"finding_count":self.finding_count,"has_notes":self.has_notes,"outer_app_protocol":self.outer_app_protocol,"inner_e2e_protocol":self.inner_e2e_protocol,"inner_summary":self.inner_summary,"flow_method":self.flow_method,}# Omitted when unknown, in parity with tap_format.FlowSummary.to_dict.returnput_stream_id(out,self.stream_id)
Reconstruct a .tap file from an existing packet capture plus its key material — no device, no live capture.
Requires Wireshark / tshark ≥ 4.x
pcap_to_tap() (and the --from-pcap CLI) shell out to tshark for dissection. If tshark is not on PATH, set tshark_path= (or the $FRITAP_TSHARK environment variable). The example below is offline but needs tshark installed.
fromfriTapimportpcap_to_tapresult=pcap_to_tap("chrome.pcap",keylog_path="chromekeys.log",# SSLKEYLOGFILE; raises NoDecryptionKeysError if given but unusabletap_path="out.tap",run_scan=True,# also run analyzers and embed findings)print(result.to_dict())
Import path
pcap_to_tap is importable from the package root (from friTap import pcap_to_tap), but not from friTap.offline — re-exporting it there would shadow the friTap.offline.pcap_to_tapmodule. The no-manifest core is friTap.convert_pcap_to_tap(...).
pcap_to_tap() reads a manifest sidecar <pcap>.fritap.json (keys keylog/tls_ports/quic_ports) when use_manifest=True; explicit arguments win over the manifest, which wins over defaults.
Keylogs for friTap's own offline decryptors go in protocol_keylogs, a {protocol_name: keylog_path} map. It covers the built-in decryptors (mtproto, telegram, signal, rc4, schannel) and registered plugins:
The older <protocol>_keylog= keywords (e.g. mtproto_keylog=) still work and are folded into protocol_keylogs; an explicit protocol_keylogs entry wins. resync_search_depth= is forwarded only to decryptors whose OfflineDecryptorEntry names the receiving keyword in resync_param (MTProto and Telegram: obf_max_blocks). An offline-decryptor plugin whose emitter takes **kwargs therefore no longer receives obf_max_blocks unless its entry sets resync_param.
@dataclassclassConvertResult:"""Summary of a pcap-to-tap conversion."""tap_path:strflow_count:int=0decrypted_packet_count:int=0stream_count:int=0# QUIC per-packet drops (e.g. misaligned id/payload lists), distinct from dropped TLS streams.dropped_packet_count:int=0# TLS streams that could not be followed/decoded (whole-stream drops).dropped_stream_count:int=0findings_count:int=0# Encrypted streams skipped by a keyless conversion; drives the CLI's "pass --keylog" hint.encrypted_streams_skipped:int=0# ``{counter_prefix: {"messages": 6, ...}}`` via :meth:`record_protocol`; the frozen v1 flat counters are read-only views of it.per_protocol:dict=field(default_factory=dict)defrecord_protocol(self,prefix:str,**counters)->None:"""Accumulate one decryptor's counters into ``per_protocol[prefix]``. A new bucket starts as a deep copy of the frozen v1 defaults (:data:`~friTap.offline.result_schema.V1_BUCKET_DEFAULTS`). Counters merge by type (:func:`_merge_counter`): booleans OR, numbers add, mappings merge-add, ``None`` is skipped, anything else raises :class:`TypeError`. Unknown names become new bucket keys."""bucket=self.per_protocol.get(prefix)ifbucketisNone:bucket=self.per_protocol[prefix]=copy.deepcopy(V1_BUCKET_DEFAULTS)forname,valueincounters.items():_merge_counter(bucket,name,value)defto_dict(self)->dict:"""JSON-safe dict in the frozen v1 key order: fields, flat counters just before ``per_protocol``."""data=asdict(self)per_protocol=data.pop("per_protocol")forflat_name,_prefix,_keyinV1_FLAT_COUNTERS:data[flat_name]=getattr(self,flat_name)data["per_protocol"]=per_protocolreturndata
defto_dict(self)->dict:"""JSON-safe dict in the frozen v1 key order: fields, flat counters just before ``per_protocol``."""data=asdict(self)per_protocol=data.pop("per_protocol")forflat_name,_prefix,_keyinV1_FLAT_COUNTERS:data[flat_name]=getattr(self,flat_name)data["per_protocol"]=per_protocolreturndata
Key fields: tap_path, flow_count, decrypted_packet_count, stream_count, dropped_packet_count, dropped_stream_count, findings_count, and encrypted_streams_skipped (streams that could not be decrypted and were tallied rather than emitted).
per_protocol holds the per-protocol counters, keyed by protocol prefix ("mtproto", "telegram", "signal", "rc4", or a plugin's prefix). Each bucket has the same keys (messages, streams, undecryptable, degraded, partial, short, unknown_key_ids, …):
The flat mtproto_messages, mtproto_streams, mtproto_records_undecryptable and mtproto_streams_degraded keys are deprecated. They are read-only aliases of per_protocol["mtproto"] and stay in to_dict() for compatibility.
Flow ids are <connection id>:<sequence>. A connection id is cr:<protocol>:<client_random> or sid:<protocol>:<token> when either is known. Otherwise it is the endpoint pair: net:<4-tuple> for TLS, and net:<protocol>:<canonical 4-tuple> for every other protocol (e.g. net:mtproto:…, net:quic:…, net:rc4:…, net:signal:…). See offline pcap → tap for details.
Caveats
Keyless 1-RTT-only QUIC captures are undetectable without keys. Encrypted streams that cannot be decrypted are skipped and counted in encrypted_streams_skipped. SSH banners and HTTP/2 control frames become synthetic, metadata-only flows. NoDecryptionKeysError is raised when keylog_path is given but no usable keys (and no embedded DSB) are found.
classTapReader:"""Indexed reader for .tap capture files. Usage: ``reader = TapReader(path); reader.open(); reader.read_flow_summaries()`` (fast, metadata only); ``reader.read_flow(flow_id)`` (full, on demand); ``reader.close()``. """def__init__(self,path:str)->None:self._path=str(Path(path).resolve())self._file=Noneself._header:Optional[TapHeader]=Noneself._meta:Optional[TapMeta]=Noneself._data_start:int=0# byte offset where records begin# Index: flow_id -> file_offset of the FLOW record envelopeself._flow_offsets:dict[str,int]={}# Lazily-built findings index: flow_id -> list[Finding]. None = not built.self._findings_index:Optional[dict[str,list]]=None# Finding presence, determined cheaply at open(): None = undetermined (the footer-index path# does not walk records), False = the open-time scan saw no REC_FINDING (read_findings# returns [] without a second scan), True = seen; offsets are captured below.self._saw_finding_record:Optional[bool]=None# Byte offsets of REC_FINDING envelopes from the open-time scan, so read_findings can seek to them.self._finding_offsets:list[int]=[]self._opened:bool=False# Serializes every seek+read on the shared file handle: get_flow runs on the UI thread,# the analyzer worker and the filter content index, and an interleaved seek would read the# wrong bytes (CRC mismatch). Re-entrant: open() and the findings-index build nest record reads.self._io_lock=threading.RLock()@propertydefpath(self)->str:returnself._path@propertydefheader(self)->Optional[TapHeader]:returnself._header@propertydefmeta(self)->Optional[TapMeta]:returnself._meta@propertydefflow_count(self)->int:returnlen(self._flow_offsets)defopen(self)->TapMeta:"""Open the .tap file, parse the header, build the flow index and return the file-level TapMeta."""withself._io_lock:self._file=open(self._path,"rb")self._opened=Truetry:# Read headerheader_raw=self._file.read(_HEADER_STRUCT.size+4096)# read extra for extself._header,self._data_start=decode_header(header_raw)# Try to read META record (should be the first record)self._file.seek(self._data_start)self._meta=self._try_read_meta()# Build flow indexifself._header.flags&FLAG_HAS_INDEX:self._build_index_from_footer()else:logger.info("No index in .tap file, performing linear scan")self._build_index_linear_scan()exceptException:self.close()raiselogger.info("TapReader opened: %s (%d flows)",self._path,len(self._flow_offsets),)returnself._metaorTapMeta()defread_flow_summaries(self)->list[FlowSummary]:"""Read lightweight flow metadata for all flows (no chunks/bodies), sorted by start timestamp."""self._ensure_open()summaries=[]forflow_id,offsetinself._flow_offsets.items():try:payload=self._read_record_payload_at(offset)ifpayloadisnotNone:summary=decode_flow_summary(payload,file_offset=offset)summaries.append(summary)exceptException:logger.debug("Failed to read flow summary at offset %d",offset,exc_info=True)# Enrich finding_count: findings live in separate REC_FINDING records, so decode_flow_summary# leaves it 0. has_findings() is a cheap no-op for findings-free captures; only captures with# findings pay for the (cached) index build.ifself.has_findings():forsummaryinsummaries:summary.finding_count=len(self.read_findings(summary.flow_id))summaries.sort(key=lambdas:s.started)returnsummariesdefiter_flows(self)->Iterator[tuple[int,FlowSummary,"Flow"]]:"""Yield ``(ordinal, summary, flow)`` for every decodable flow, in summary order. ``ordinal`` is the 1-based position in :meth:`read_flow_summaries` (the ``f<N>`` flow-ref numbering), counted even for flows that cannot be decoded (skipped). """# Each FLOW meta is parsed twice (summaries, then read_flow) on purpose: holding all parsed metas would raise# peak memory ~10x on large taps (12.7 MB -> 142.5 MB on a 68 MB tap), and avoiding it needs a .tap format change.forordinal,summaryinenumerate(self.read_flow_summaries(),start=1):flow=self.read_flow(summary.flow_id)ifflowisnotNone:yieldordinal,summary,flowdefread_flow(self,flow_id:str)->Optional["Flow"]:"""Read a full Flow (with chunks/bodies) by flow_id; None if not in the index."""self._ensure_open()offset=self._flow_offsets.get(flow_id)ifoffsetisNone:returnNonetry:payload=self._read_record_payload_at(offset)ifpayloadisNone:returnNoneflow=decode_flow(payload)exceptException:logger.error("Failed to read flow %s at offset %d",flow_id,offset,exc_info=True)returnNone# Findings are best-effort: a corrupt findings index must NEVER suppress an already-decoded valid flow.try:findings=self.read_findings(flow_id)iffindings:flow.findings=list(findings)exceptException:logger.warning("Failed to read findings for flow %s; returning flow without findings",flow_id,exc_info=True,)returnflowdefread_all_flows(self)->list["Flow"]:"""Read all flows fully (large captures: prefer summaries + :meth:`read_flow`)."""self._ensure_open()flows=[]forflow_id,offsetinself._flow_offsets.items():try:payload=self._read_record_payload_at(offset)ifpayloadisNone:continueflow=decode_flow(payload)exceptException:logger.debug("Failed to read flow at offset %d",offset,exc_info=True)continue# Best-effort findings: a corrupt index must NEVER drop a decoded valid flow.try:findings=self.read_findings(flow.flow_id)iffindings:flow.findings=list(findings)exceptException:logger.warning("Failed to read findings for flow %s; flow kept without findings",flow.flow_id,exc_info=True,)flows.append(flow)flows.sort(key=lambdaf:f.started)returnflowsdefread_findings(self,flow_id:str)->list:"""Return analysis findings persisted for *flow_id*; the index is built lazily (one linear pass) and cached."""self._ensure_open()returnself._ensure_findings_index().get(flow_id,[])defiter_keylogs(self)->Iterator[tuple[str,float]]:"""Yield ``(key_data, timestamp)`` for every intact REC_KEYLOG record. Key material: callers must gate this behind an explicit secrets opt-in. Records are read in file order under the I/O lock before the first item is yielded; bad-CRC/undecodable ones are skipped. """self._ensure_open()forpayloadinself._intact_payloads(_KEYLOG_ONLY):try:key_data,timestamp=decode_keylog(payload)except(ValueError,AttributeError,RecursionError):# bad/deep JSON, not an objectlogger.debug("Skipping undecodable KEYLOG record")continueifnotisinstance(key_data,str):# untrusted file: callers expect textlogger.debug("Skipping KEYLOG record whose key_data is not a string")continueyieldkey_data,timestampifisinstance(timestamp,(int,float))else0.0defiter_request_contexts(self)->Iterator[dict]:"""Yield intact REC_REQUEST_CONTEXT records, re-bounded; skipped for a closed file without FLAG_HAS_REQUEST_CONTEXTS."""self._ensure_open()ifnotself._may_hold_request_contexts():returnforpayloadinself._intact_payloads(_REQUEST_CONTEXT_ONLY):record=decode_request_context(payload)ifrecordisNone:logger.debug("Skipping undecodable REQUEST_CONTEXT record")continueyieldrecorddef_intact_payloads(self,rec_types:frozenset)->list[bytes]:"""CRC-valid payloads of *rec_types*, read in one pass under the I/O lock."""withself._io_lock:return[payloadfor_offset,_rec_type,payload,stored_crcinself._iter_records(self._data_start,rec_types=rec_types)ifverify_payload_crc(payload,stored_crc)]def_may_hold_request_contexts(self)->bool:"""False only for an indexed file written without request contexts."""flags=self._header.flagsifself._headerisnotNoneelse0returnnot(flags&FLAG_HAS_INDEX)orbool(flags&FLAG_HAS_REQUEST_CONTEXTS)defhas_findings(self)->bool:"""True if the file contains any persisted findings."""self._ensure_open()returnbool(self._ensure_findings_index())def_ensure_findings_index(self)->dict:"""Build the findings index once under the I/O lock; returns the index itself so a concurrent ``close()`` (resetting ``_findings_index`` to None) cannot turn the caller's lookup into ``None.get``."""index=self._findings_indexifindexisnotNone:returnindexwithself._io_lock:ifself._findings_indexisNone:self._build_findings_index()returnself._findings_indexor{}defclose(self)->None:"""Close the file. Safe to call multiple times."""withself._io_lock:ifself._fileisnotNone:try:self._file.close()exceptException:passself._file=Noneself._opened=Falseself._flow_offsets.clear()self._findings_index=Noneself._saw_finding_record=Noneself._finding_offsets=[]def__enter__(self)->"TapReader":self.open()returnselfdef__exit__(self,*args)->None:self.close()def_build_index_from_footer(self)->None:"""Read the FLOW_INDEX from the footer pointer."""assertself._fileisnotNone# Findings presence is in the header flags: a closed/indexed file (FLAG_HAS_INDEX, this path)# without FLAG_HAS_FINDINGS provably has no REC_FINDING records.ifself._headerisnotNoneandself._header.flags&FLAG_HAS_FINDINGS:# Findings exist; offsets unknown on this path, so _build_findings_index scans once, lazily.self._saw_finding_record=Trueelse:self._saw_finding_record=False# Read footer (last 16 bytes)self._file.seek(0,2)# seek to endfile_size=self._file.tell()iffile_size<_HEADER_STRUCT.size+_FOOTER_STRUCT.size:logger.warning("File too small for footer, falling back to linear scan")self._build_index_linear_scan()returnself._file.seek(file_size-_FOOTER_STRUCT.size)footer_raw=self._file.read(_FOOTER_STRUCT.size)try:footer_magic,index_offset=_FOOTER_STRUCT.unpack(footer_raw)exceptException:logger.warning("Footer unpack failed, falling back to linear scan")self._build_index_linear_scan()returniffooter_magic!=FOOTER_MAGIC:logger.warning("Footer magic mismatch, falling back to linear scan")self._build_index_linear_scan()return# Read FLOW_INDEX record at index_offsetpayload=self._read_record_payload_at(index_offset)ifpayloadisNone:logger.warning("Failed to read FLOW_INDEX, falling back to linear scan")self._build_index_linear_scan()returnentries=decode_flow_index(payload)forentryinentries:self._flow_offsets[entry["flow_id"]]=entry["offset"]def_build_index_linear_scan(self)->None:"""Scan all records sequentially to build the flow index (FLOW_INDEX missing: partial capture / crash); keeps the last FLOW record per flow_id."""assertself._fileisnotNone# This pass visits every record, so capture finding presence/offsets here: afterwards the# flag is authoritative (False if none seen) and _build_findings_index skips a second scan.self._saw_finding_record=Falseself._finding_offsets=[]foroffset,rec_type,payload,stored_crcinself._iter_records(self._data_start):# Record finding presence/offset only; the payload is decoded lazily on first read_findings.ifrec_type==REC_FINDING:self._saw_finding_record=Trueself._finding_offsets.append(offset)continueifrec_type==REC_FLOW:ifverify_payload_crc(payload,stored_crc):try:summary=decode_flow_summary(payload)self._flow_offsets[summary.flow_id]=offsetexceptException:logger.debug("Skipping corrupt FLOW at offset %d",offset)else:logger.debug("CRC mismatch for FLOW at offset %d, skipping",offset)elifrec_type==REC_METAandself._metaisNone:ifverify_payload_crc(payload,stored_crc):try:self._meta=decode_meta(payload)exceptException:passdef_build_findings_index(self)->None:"""Build the lazy flow_id -> [Finding] index from REC_FINDING records, cached in ``_findings_index``. Performance gate on the open-time scan results: * ``_saw_finding_record is False``: no findings seen, short-circuit to an empty index without re-reading the (potentially large) file (the common case). * ``_finding_offsets`` populated: seek directly to each known finding record. * ``_saw_finding_record is None``: undetermined (footer-index path), fall back to a full linear pass. """assertself._fileisnotNone# Short-circuit: open-time scan proved there are no findings.ifself._saw_finding_recordisFalse:self._findings_index={}returnindex:dict[str,list]={}# Lazy import to avoid an import cycle (analysis imports flow.models).try:fromfriTap.analysisimportFindingexceptException:Finding=None# type: ignoredefadd_record(payload:bytes,stored_crc:int,offset:int)->None:ifnotverify_payload_crc(payload,stored_crc):logger.debug("CRC mismatch for REC_FINDING at offset %d, skipping",offset)returntry:flow_id,finding_dicts=decode_finding_record(payload)exceptException:logger.debug("Skipping corrupt REC_FINDING at offset %d",offset)returnbucket=index.setdefault(flow_id,[])forfdinfinding_dicts:bucket.append(Finding.from_dict(fd)ifFindingisnotNoneelsefd)# Fast path: seek directly to the offsets captured at open() time.ifself._saw_finding_recordisTrueandself._finding_offsets:foroffsetinself._finding_offsets:self._file.seek(offset)envelope_raw=self._file.read(_RECORD_ENVELOPE.size)iflen(envelope_raw)<_RECORD_ENVELOPE.size:continuetry:rec_type,payload_len,stored_crc,_=decode_record_envelope(envelope_raw)exceptValueError:continueifrec_type!=REC_FINDINGorpayload_len==0:continuetry:payload=self._read_payload(payload_len)exceptBoundsError:logger.debug("Skipping REC_FINDING at offset %d: bad length",offset)continueadd_record(payload,stored_crc,offset)self._findings_index=indexreturn# Fallback (presence undetermined, e.g. footer-index path): full scan.foroffset,rec_type,payload,stored_crcinself._iter_records(self._data_start):ifrec_type!=REC_FINDING:continueadd_record(payload,stored_crc,offset)self._findings_index=indexdef_iter_records(self,start_offset:int,rec_types:Optional[frozenset]=None):"""Yield ``(offset, rec_type, payload, stored_crc)`` for every record. With *rec_types*, other records' payloads are seeked past unread (same bounds/truncation checks, so the scan ends at the same point). Shared by ``_build_index_linear_scan`` and the findings fallback; recovers via sync marker on a corrupt envelope and skips zero-length records. The CRC is yielded unverified so each caller applies its own policy. """assertself._fileisnotNoneself._file.seek(start_offset)whileTrue:offset=self._file.tell()envelope_raw=self._file.read(_RECORD_ENVELOPE.size)iflen(envelope_raw)<_RECORD_ENVELOPE.size:break# EOF or truncatedtry:rec_type,payload_len,stored_crc,_=decode_record_envelope(envelope_raw)exceptValueError:# Try to find next sync marker for recoveryrecovered=self._recover_from(offset+1)ifrecovered<0:breakcontinueifpayload_len==0:continuewanted=rec_typesisNoneorrec_typeinrec_typestry:ifnotwanted:self._skip_payload(payload_len)continuepayload=self._read_payload(payload_len)exceptBoundsErrorasexc:# Truncated payload at EOF, or a length no record can have.logger.debug("Ending record scan at offset %d: %s",offset,exc)breakyieldoffset,rec_type,payload,stored_crcdef_recover_from(self,start_offset:int)->int:"""Scan forward from start_offset for the next valid sync marker; its offset, or -1."""assertself._fileisnotNoneself._file.seek(start_offset)# Read in 4KB chunks to find sync markerwhileTrue:chunk_start=self._file.tell()chunk=self._file.read(4096)ifnotchunk:return-1idx=find_sync_marker(chunk)ifidx>=0:recovered_offset=chunk_start+idxself._file.seek(recovered_offset)returnrecovered_offsetdef_read_record_payload_at(self,offset:int)->Optional[bytes]:"""Read and verify one record's payload at *offset*; None if invalid. Thread-safe (seek+read under ``_io_lock``)."""withself._io_lock:raw=self._read_record_raw_at(offset)ifrawisNone:returnNonepayload,stored_crc=rawifnotverify_payload_crc(payload,stored_crc):logger.warning("CRC mismatch at offset %d",offset)returnNonereturnpayloaddef_read_record_raw_at(self,offset:int)->Optional[tuple[bytes,int]]:"""Seek to *offset* and read ``(payload, stored_crc)``; caller holds the lock."""ifself._fileisNone:returnNoneself._file.seek(offset)envelope_raw=self._file.read(_RECORD_ENVELOPE.size)iflen(envelope_raw)<_RECORD_ENVELOPE.size:returnNonetry:_,payload_len,stored_crc,_=decode_record_envelope(envelope_raw)payload=self._read_payload(payload_len)exceptValueError:# bad envelope, or BoundsError on the payload lengthreturnNonereturnpayload,stored_crcdef_read_payload(self,payload_len:int)->bytes:"""Read a *payload_len*-byte payload at the current position. Length is checked against :data:`MAX_RECORD_PAYLOAD` and the bytes left in the file *before* allocating, so a crafted u32 cannot trigger a multi-GiB ``read()``. Raises :class:`~friTap.binary_bounds.BoundsError` (a ``ValueError``) on an implausible or truncated payload. """assertself._fileisnotNonereturnread_bounded(self._file,payload_len,"tap record payload",MAX_RECORD_PAYLOAD)def_skip_payload(self,payload_len:int)->None:"""Advance past a payload without reading it, with :meth:`_read_payload`'s bounds checks (bounded read fallback when the file size is unknown)."""assertself._fileisnotNoneremaining=remaining_bytes(self._file)ifremainingisNone:self._read_payload(payload_len)returncheck_length(payload_len,"tap record payload",MAX_RECORD_PAYLOAD,remaining)self._file.seek(payload_len,1)def_try_read_meta(self)->Optional[TapMeta]:"""Try to read a META record at the current position."""assertself._fileisnotNonepos=self._file.tell()envelope_raw=self._file.read(_RECORD_ENVELOPE.size)iflen(envelope_raw)<_RECORD_ENVELOPE.size:self._file.seek(pos)returnNonetry:rec_type,payload_len,stored_crc,_=decode_record_envelope(envelope_raw)exceptValueError:self._file.seek(pos)returnNoneifrec_type!=REC_META:self._file.seek(pos)returnNonetry:payload=self._read_payload(payload_len)exceptBoundsError:self._file.seek(pos)returnNoneifnotverify_payload_crc(payload,stored_crc):self._file.seek(pos)returnNonereturndecode_meta(payload)def_ensure_open(self)->None:ifnotself._openedorself._fileisNone:raiseRuntimeError("TapReader is not open. Call open() first.")
defopen(self)->TapMeta:"""Open the .tap file, parse the header, build the flow index and return the file-level TapMeta."""withself._io_lock:self._file=open(self._path,"rb")self._opened=Truetry:# Read headerheader_raw=self._file.read(_HEADER_STRUCT.size+4096)# read extra for extself._header,self._data_start=decode_header(header_raw)# Try to read META record (should be the first record)self._file.seek(self._data_start)self._meta=self._try_read_meta()# Build flow indexifself._header.flags&FLAG_HAS_INDEX:self._build_index_from_footer()else:logger.info("No index in .tap file, performing linear scan")self._build_index_linear_scan()exceptException:self.close()raiselogger.info("TapReader opened: %s (%d flows)",self._path,len(self._flow_offsets),)returnself._metaorTapMeta()
defread_flow_summaries(self)->list[FlowSummary]:"""Read lightweight flow metadata for all flows (no chunks/bodies), sorted by start timestamp."""self._ensure_open()summaries=[]forflow_id,offsetinself._flow_offsets.items():try:payload=self._read_record_payload_at(offset)ifpayloadisnotNone:summary=decode_flow_summary(payload,file_offset=offset)summaries.append(summary)exceptException:logger.debug("Failed to read flow summary at offset %d",offset,exc_info=True)# Enrich finding_count: findings live in separate REC_FINDING records, so decode_flow_summary# leaves it 0. has_findings() is a cheap no-op for findings-free captures; only captures with# findings pay for the (cached) index build.ifself.has_findings():forsummaryinsummaries:summary.finding_count=len(self.read_findings(summary.flow_id))summaries.sort(key=lambdas:s.started)returnsummaries
defread_flow(self,flow_id:str)->Optional["Flow"]:"""Read a full Flow (with chunks/bodies) by flow_id; None if not in the index."""self._ensure_open()offset=self._flow_offsets.get(flow_id)ifoffsetisNone:returnNonetry:payload=self._read_record_payload_at(offset)ifpayloadisNone:returnNoneflow=decode_flow(payload)exceptException:logger.error("Failed to read flow %s at offset %d",flow_id,offset,exc_info=True)returnNone# Findings are best-effort: a corrupt findings index must NEVER suppress an already-decoded valid flow.try:findings=self.read_findings(flow_id)iffindings:flow.findings=list(findings)exceptException:logger.warning("Failed to read findings for flow %s; returning flow without findings",flow_id,exc_info=True,)returnflow
defread_all_flows(self)->list["Flow"]:"""Read all flows fully (large captures: prefer summaries + :meth:`read_flow`)."""self._ensure_open()flows=[]forflow_id,offsetinself._flow_offsets.items():try:payload=self._read_record_payload_at(offset)ifpayloadisNone:continueflow=decode_flow(payload)exceptException:logger.debug("Failed to read flow at offset %d",offset,exc_info=True)continue# Best-effort findings: a corrupt index must NEVER drop a decoded valid flow.try:findings=self.read_findings(flow.flow_id)iffindings:flow.findings=list(findings)exceptException:logger.warning("Failed to read findings for flow %s; flow kept without findings",flow.flow_id,exc_info=True,)flows.append(flow)flows.sort(key=lambdaf:f.started)returnflows
defclose(self)->None:"""Close the file. Safe to call multiple times."""withself._io_lock:ifself._fileisnotNone:try:self._file.close()exceptException:passself._file=Noneself._opened=Falseself._flow_offsets.clear()self._findings_index=Noneself._saw_finding_record=Noneself._finding_offsets=[]
ReplayController is the higher-level facade used by the TUI replay view. It adds an LRU cache (128 flows), a context-manager interface, and convenience properties. It implements IFlowSource (get_flows() / get_flow(id)).
classReplayController:"""Loads and serves flows from a .tap file for replay mode (satisfies :class:`IFlowSource`)."""def__init__(self,path:str)->None:self._path=pathself._reader:Optional[TapReader]=Noneself._meta:Optional[TapMeta]=Noneself._summaries:list[FlowSummary]=[]self._flow_cache:_LRUCache=_LRUCache(maxsize=128)self._reparse_results:dict[str,tuple[Optional["ParseResult"],Optional["ParseResult"]]]={}# Flow ids whose stale trailing-data segments are dropped on every (re)load# (e.g. decrypted TL flows once mis-parsed as WebSocket).self._clear_trailing_ids:set[str]=set()@propertydefreplay_file(self)->str:returnself._path@propertydefflow_count(self)->int:returnlen(self._summaries)@propertydefmeta(self)->Optional[TapMeta]:returnself._meta@propertydefheader(self):returnself._reader.headerifself._readerelseNonedefload(self)->TapMeta:"""Open the .tap file, load flow summaries and return the file-level TapMeta."""self._reader=TapReader(self._path)self._meta=self._reader.open()self._summaries=self._reader.read_flow_summaries()logger.info("Replay loaded: %s (%d flows)",self._path,len(self._summaries))returnself._metadefget_summaries(self)->list[FlowSummary]:"""Return all flow summaries (lightweight, no chunk/body data)."""returnlist(self._summaries)defget_flows(self)->list["Flow"]:"""Return all flows as full Flow objects (loads everything; prefer summaries + :meth:`get_flow`)."""ifself._readerisNone:return[]returnself._reader.read_all_flows()defget_flow(self,flow_id:str)->Optional["Flow"]:"""Load a full Flow by ID (on-demand from disk, LRU-cached)."""flow=self._flow_cache.get(flow_id)ifflowisNone:ifself._readerisNone:returnNoneflow=self._reader.read_flow(flow_id)ifflowisNone:returnNoneself._flow_cache[flow_id]=flow# Re-apply reparse results that survive cache eviction.ifflow_idinself._reparse_results:req,resp=self._reparse_results[flow_id]ifreqisnotNone:flow.request=reqifrespisnotNone:flow.response=respifflow_idinself._clear_trailing_ids:fromfriTap.flow.reparseimportclear_trailing_dataclear_trailing_data(flow)returnflowdefstore_reparse(self,flow_id:str,request:Optional["ParseResult"],response:Optional["ParseResult"],clear_trailing:bool=False,)->None:"""Store reparse results so they survive cache eviction. With *clear_trailing*, every later :meth:`get_flow` also drops trailing-data state. """self._reparse_results[flow_id]=(request,response)ifclear_trailing:self._clear_trailing_ids.add(flow_id)defread_all_findings(self)->list:"""Return persisted findings (dicts) across all flows (REC_FINDING records); empty if none."""ifself._readerisNone:return[]findings:list=[]forsummaryinself._summaries:findings.extend(self._reader.read_findings(summary.flow_id))returnfindingsdefread_request_contexts(self)->list:"""Return the persisted Java request contexts (REC_REQUEST_CONTEXT dicts); empty when none or not loaded."""ifself._readerisNone:return[]returnlist(self._reader.iter_request_contexts())defhas_findings(self)->bool:"""True if the .tap file contains any persisted findings."""ifself._readerisNone:returnFalsereturnself._reader.has_findings()defclose(self)->None:"""Close the reader and release resources."""ifself._readerisnotNone:self._reader.close()self._reader=Noneself._flow_cache.clear()self._reparse_results.clear()self._clear_trailing_ids.clear()self._summaries.clear()def__enter__(self)->"ReplayController":self.load()returnselfdef__exit__(self,*args)->None:self.close()
defget_flows(self)->list["Flow"]:"""Return all flows as full Flow objects (loads everything; prefer summaries + :meth:`get_flow`)."""ifself._readerisNone:return[]returnself._reader.read_all_flows()
defget_flow(self,flow_id:str)->Optional["Flow"]:"""Load a full Flow by ID (on-demand from disk, LRU-cached)."""flow=self._flow_cache.get(flow_id)ifflowisNone:ifself._readerisNone:returnNoneflow=self._reader.read_flow(flow_id)ifflowisNone:returnNoneself._flow_cache[flow_id]=flow# Re-apply reparse results that survive cache eviction.ifflow_idinself._reparse_results:req,resp=self._reparse_results[flow_id]ifreqisnotNone:flow.request=reqifrespisnotNone:flow.response=respifflow_idinself._clear_trailing_ids:fromfriTap.flow.reparseimportclear_trailing_dataclear_trailing_data(flow)returnflow
defclose(self)->None:"""Close the reader and release resources."""ifself._readerisnotNone:self._reader.close()self._reader=Noneself._flow_cache.clear()self._reparse_results.clear()self._clear_trailing_ids.clear()self._summaries.clear()
friTap can run its analyzers (credentials, ioc, privacy, protobuf, plus custom ones) over a captured .tap file — passive analysis, no network activity. Use analyze_tap_report() for programmatic access; it performs no I/O beyond reading the .tap and never calls sys.exit.
Run analyzers over tap_file and return findings + a rendered report.
Pure orchestration shared by the CLI and external tools: resolve analyzers (scanners is a comma-separated name list, or None/"all" for the built-ins) → run them → filter (severity/confidence/source/category) → render in report_format (one of :func:list_report_formats). Performs no stdout, no sidecar write and never calls sys.exit — callers decide how to surface the result.
The filter arguments are all additive and default to no-ops, so existing callers are unaffected:
min_confidence — keep findings with confidence at or above this value.
source — comma-separated analyzer source names to keep (which findings show; distinct from scanners, which selects analyzers that run).
category — comma-separated finding categories to keep (secret/pii/network/protocol).
show_pii — reveal PII/secret values instead of redacting them (forwarded to analyzers as reveal_pii; default redacts).
masvs — add the OWASP MASVS v2.1 controls each finding maps to (a column/field in the report); default off leaves the report unchanged.
applovin_sdk_keys / applovin_salts (hex) / app_bundles (APK/IPA paths) — key material for the applovin_mediate analyzer, merged with the FRITAP_APPLOVIN_* environment variables.
Raises ValueError for an unknown report_format or an unresolvable analyzer spec, ImportError for a bad analyzer_path; any .tap read/analyze failure propagates.
defanalyze_tap_report(tap_file:str,*,scanners:str|None=None,analyzer_path:str|None=None,min_severity:str="info",report_format:str="table",include_private_ips:bool=False,protobuf_schema:str|None=None,min_confidence:float=0.0,source:str|None=None,category:str|None=None,show_pii:bool=False,masvs:bool=False,applovin_sdk_keys:"list[str] | None"=None,applovin_salts:"list[str] | None"=None,app_bundles:"list[str] | None"=None,)->AnalyzeReport:"""Run analyzers over *tap_file* and return findings + a rendered report. Pure orchestration shared by the CLI and external tools: resolve analyzers (``scanners`` is a comma-separated name list, or ``None``/``"all"`` for the built-ins) → run them → filter (severity/confidence/source/category) → render in *report_format* (one of :func:`list_report_formats`). Performs no stdout, no sidecar write and never calls ``sys.exit`` — callers decide how to surface the result. The filter arguments are all additive and default to no-ops, so existing callers are unaffected: * ``min_confidence`` — keep findings with confidence at or above this value. * ``source`` — comma-separated analyzer source names to keep (which findings *show*; distinct from ``scanners``, which selects analyzers that *run*). * ``category`` — comma-separated finding categories to keep (``secret``/``pii``/``network``/``protocol``). * ``show_pii`` — reveal PII/secret values instead of redacting them (forwarded to analyzers as ``reveal_pii``; default redacts). * ``masvs`` — add the OWASP MASVS v2.1 controls each finding maps to (a column/field in the report); default off leaves the report unchanged. * ``applovin_sdk_keys`` / ``applovin_salts`` (hex) / ``app_bundles`` (APK/IPA paths) — key material for the ``applovin_mediate`` analyzer, merged with the ``FRITAP_APPLOVIN_*`` environment variables. Raises ``ValueError`` for an unknown *report_format* or an unresolvable analyzer spec, ``ImportError`` for a bad ``analyzer_path``; any .tap read/analyze failure propagates. """fromfriTap.analysis.filteringimportFindingFilter,apply,split_csvifreport_formatnotin_REPORTER_REGISTRY:raiseValueError(f"unknown report format {report_format!r}; "f"choose from {', '.join(sorted(_REPORTER_REGISTRY))}")analyzers=resolve_analyzers(scanners,analyzer_path=analyzer_path,include_private_ips=include_private_ips,protobuf_schema=protobuf_schema,reveal_pii=show_pii,applovin_sdk_keys=applovin_sdk_keys,applovin_salts=applovin_salts,app_bundles=app_bundles,)findings=analyze_tap_multi(analyzers,tap_file)normalized_severity=min_severityifmin_severityin_SEVERITY_ORDERelse"info"finding_filter=FindingFilter(min_severity=normalized_severity,sources=split_csv(source),categories=split_csv(category),min_confidence=min_confidenceifmin_confidence>0.0elseNone,)filtered=apply(findings,finding_filter)analyzer_names=[a.nameforainanalyzers]meta={"tap_file":tap_file,"analyzers":analyzer_names}# AnalyzeReport.findings keep full fidelity; only the rendered report is# redacted (unless show_pii). The reporter is the redaction enforcement point.rendered=_REPORTER_REGISTRY[report_format](redact_pii=notshow_pii,masvs=masvs).report(filtered,meta)returnAnalyzeReport(findings=filtered,rendered=rendered,report_format=report_format,analyzer_names=analyzer_names,meta=meta,)
Carries both the structured (already severity-filtered) findings and the report rendered in the requested format, so web / TUI / CLI callers can use whichever they need without re-running the analyzers. Returned by :func:analyze_tap_report.
@dataclass(frozen=True)classAnalyzeReport:"""Result of a programmatic ``.tap`` analysis. Carries both the structured (already severity-filtered) findings and the report rendered in the requested format, so web / TUI / CLI callers can use whichever they need without re-running the analyzers. Returned by :func:`analyze_tap_report`. """findings:list["Finding"]rendered:strreport_format:stranalyzer_names:list[str]=field(default_factory=list)meta:dict[str,Any]=field(default_factory=dict)gate_severity:str=_GATE_SEVERITY@propertydefgate_tripped(self)->bool:"""True iff any finding is at or above :attr:`gate_severity`. Mirrors the condition under which :func:`run_analyze_cli` returns the non-zero CI-gate exit code. """returnbool(_filter_min_severity(self.findings,self.gate_severity))@propertydefexit_code(self)->int:"""CLI-parity exit code: 2 when :attr:`gate_tripped`, else 0."""return2ifself.gate_trippedelse0
CLI-parity exit code: 2 when :attr:gate_tripped, else 0.
fromfriTapimportanalyze_tap_reportreport=analyze_tap_report("capture_20260507_153933.tap",# offline / CI-runnablescanners="credentials,ioc",# None or "all" → built-ins (which analyzers RUN)min_severity="info",report_format="table",# report-side filters (additive, keyword-only; all default to no-op):min_confidence=0.0,# drop findings below this confidence (0.0–1.0)source=None,# comma-separated source names to SHOW (e.g. "credentials,privacy")category=None,# "secret,pii,network,protocol" to SHOWshow_pii=False,# reveal PII/secret values instead of redacting)forfindinginreport.findings:print(finding.severity.name,finding.category,finding.title,finding.flow_id)print(report.rendered)# the rendered table/json/csv/mdraiseSystemExit(report.exit_code)# 2 if any finding ≥ medium, else 0 (CI gate)
min_confidence, source, category, and show_pii are additive, keyword-only parameters — older calls that omit them keep working unchanged. scanners chooses which analyzers run; source/category filter which of the resulting findings are shown.
Each Finding has: severity (a Severity enum), title, description, source, flow_id, confidence (default 1.0), timestamp, and the dicts evidence and metadata. Severity is CRITICAL/HIGH/MEDIUM/LOW/INFO (rank 0 is most severe).
Every finding now carries a category in metadata["category"], surfaced as the Finding.category property: secret (credentials), pii (privacy), network (IOC), or protocol (protobuf). PII findings additionally carry metadata["compliance"] (e.g. GDPR, CCPA, PCI-DSS, HIPAA).
FindingFilter (exported from the top-level friTap package) is the reusable filter behind the CLI's --source/--category/--min-confidence flags. Apply it to any iterable of Finding objects:
fromfriTapimportFindingFilterflt=FindingFilter(min_severity="info",# floor: this severity and abovemin_confidence=0.8,sources={"credentials","privacy"},categories={"secret","pii"},)kept=[fforfinreport.findingsifflt.matches(f)]
Use severities for an exact-bucket match instead of the min_severity floor — FindingFilter(severities={"high"}) keeps only high findings (this is what the TUI's per-severity dashboard chips use, so a chip's count matches its result):
The built-in analyzer classes are available under friTap.analysis.* — the privacy analyzer is from friTap.analysis.privacy import PrivacyAnalyzer (not re-exported from the top-level friTap package). Select it by name via scanners="privacy" rather than importing it directly.
AnalyzeReport.gate_tripped is True when any finding is at or above the gate severity (medium), and exit_code returns 2 in that case (else 0) — mirroring the fritap analyze CLI exit code. Use it to fail a pipeline when a capture contains sensitive findings.
list_analyzers() → analyzer names (built-in plus any discovered).
list_analyzers_detailed() → richer AnalyzerInfo records (name, source/origin, description) for every analyzer, including discovered ones. Use this to render an analyzer catalog in your own tooling.
list_report_formats() → available report formats (json, csv, md, table).
Custom analyzers can be loaded via the CLI --analyzer-path module:Class (the module:Class form skips the is_fritap_analyzer marker requirement), or made ambiently discoverable through the drop-in directory, the fritap.analyzers entry-points group, or a plugin's register_analyzers() hook — see Traffic Analysis → Ship it everywhere.
Discovery executes code
Discovered analyzers (drop-in directory, fritap.analyzers entry points, plugin bridge) execute as soon as list_analyzers()/list_analyzers_detailed() or any resolution runs. Set FRITAP_DISABLE_ANALYZER_DISCOVERY=1 to disable ambient discovery; explicit --analyzer-path / .analyzer_path() references still work.
The FriTap builder exposes live passive analysis directly. scan() enables it, analyzer_path() is repeatable, and scan_report(), scan_min_severity(), and scan_show_pii() set the corresponding --scan-* options:
fromfriTapimportFriTapsession=(FriTap("com.example.app").mobile().scan("all")# or "credentials,ioc".analyzer_path("my_analyzer:InternalHostAnalyzer").scan_report("table").scan_min_severity("medium").start())
Recursively attempts sub-message parsing for LENGTH_DELIMITED fields.
Parameters:
Name
Type
Description
Default
data
bytes
Raw protobuf bytes.
required
max_depth
int
Maximum nesting depth (default 16).
16
Returns:
Name
Type
Description
A
ProtobufMessage
class:ProtobufMessage tree.
Fields nested deeper than max_depth are kept as raw bytes, and decoding stops gracefully after :data:MAX_FIELDS_PER_DECODE fields (the result then has truncated=True).
Raises:
Type
Description
ValueError
If the data is malformed (or max_depth is not positive).
defdecode_raw(data:bytes,max_depth:int=16)->ProtobufMessage:"""Decode raw protobuf wire format without a schema. Recursively attempts sub-message parsing for ``LENGTH_DELIMITED`` fields. Args: data: Raw protobuf bytes. max_depth: Maximum nesting depth (default 16). Returns: A :class:`ProtobufMessage` tree. Fields nested deeper than *max_depth* are kept as raw bytes, and decoding stops gracefully after :data:`MAX_FIELDS_PER_DECODE` fields (the result then has ``truncated=True``). Raises: ValueError: If the data is malformed (or *max_depth* is not positive). """ifnotdata:returnProtobufMessage()return_decode_raw_impl(data,max_depth)
decode_raw(data, max_depth=16) returns a ProtobufMessage (a tree of ProtobufField objects); format_message(msg, indent=0) renders it as human-readable text. ProtobufProcessor provides higher-level, schema-aware processing.
Decoding a captured body (gRPC, schema, backends)¶
decode_protobuf_view is the decoder the TUI uses for every protobuf view (flow detail, body-processing preview, explorer). It validates gRPC framing instead of dropping five bytes blindly, decompresses compressed gRPC messages (grpc-encoding gzip/deflate/zstd), applies a schema when given one, and never raises on malformed input: problems become notes / error strings, and a truncated tail still yields the fields decoded before it.
The grpc-encoding header, used for compressed gRPC messages.
schema_path, message_type
A .proto (compiled with protoc --include_imports, which must be on PATH) or .desc schema plus the fully qualified message type. Falls back to the raw wire decode with a note.
backend
"wire" (built in, default) or "blackbox" (opt-in; falls back to "wire" with a note when not installed).
max_input_bytes
Decode only a leading prefix (a preview cap).
The result's text() is plain text. Escape it before writing it into Rich markup.
Flow.decode_request_protobuf() and Flow.decode_response_protobuf() run the same decoder on a flow's (decompressed) request or response body. They pass on the flow's content type and grpc-encoding header:
view=flow.decode_response_protobuf(schema_path="api.proto",# optional .proto or compiled .descmessage_type="pkg.Reply",# needed together with schema_pathforce=False,# True: decode whatever the content type)ifviewisnotNoneandview.ok:print(view.text())
They return None when the body is empty, or when it neither has a protobuf/gRPC content type nor looks like protobuf (unless force=True). Otherwise they return a ProtobufView (from friTap.parsers.protobuf import ProtobufView):
Member
Meaning
mode
Decoder actually used: wire, blackbox or schema.
framing
none, grpc, or grpc-invalid (gRPC was expected but the bytes are not gRPC framed, so they were decoded as bare protobuf).
messages
One DecodedProtobufMessage per gRPC frame (or one for a bare body), with index, size, compressed, truncated, text, error, notes and ok.
notes, error
Why something was not decoded, or why a schema was not applied.
ok
True when at least one message decoded. A returned view can still have ok == False.
lines(), text()
The rendered output, tagged by line kind or as plain text.
Breaking change in friTap 2.3.0
Before 2.3.0 these methods returned a list of ProtobufMessage trees (one per gRPC frame) or None, and ignored schema_path. They now return a ProtobufView and apply schema_path together with the new message_type argument. There is no compatibility shim. To get the old raw field tree, call decode_raw() on the body yourself.
Optional protobuf extras
The wire decoder has no dependencies. Schema decoding needs google.protobuf, and the alternative blackboxprotobuf backend needs the bbpb package. Install both with:
pipinstall"fritap[proto]"
In the TUI the "blackboxprotobuf backend" switch of the protobuf decoder dialog becomes available once bbpb is installed.