### Build and Install python-nflog Source: https://github.com/luttermann/python-nflog/blob/master/README.md Standard procedure for building and installing the module from source. ```sh python setup.py build python setup.py install ``` -------------------------------- ### Install python-nflog dependencies and module Source: https://context7.com/luttermann/python-nflog/llms.txt Build and install the module from source after installing the required libnetfilter-log development headers. ```bash # Install dependencies (Debian/Ubuntu) sudo apt-get install libnetfilter-log-dev # Build and install the module python setup.py build python setup.py install ``` -------------------------------- ### nflog.start() Source: https://context7.com/luttermann/python-nflog/llms.txt Initializes and starts the NFLOG listener. ```APIDOC ## nflog.start() ### Description Initializes and starts the NFLOG listener. Opens a netfilter log handle, binds to AF_INET, and registers the internal callback. Requires root privileges or CAP_NET_ADMIN capability. ``` -------------------------------- ### Start NFLOG listener Source: https://context7.com/luttermann/python-nflog/llms.txt Initialize the listener. Requires root privileges or CAP_NET_ADMIN capability. ```python import nflog def my_callback(indev, outdev, ifname, proto, payload_len, payload, hw_hdr_len, hw_hdr): print(f"Received {payload_len} bytes on {ifname}") nflog.setgroup(1) nflog.setcb(my_callback) try: nflog.start() print("NFLOG listener started successfully") except PermissionError as e: print(f"Permission denied: {e}") print("Run with sudo or grant CAP_NET_ADMIN capability") except LookupError as e: print(f"Group error: {e}") ``` -------------------------------- ### Define Packet Handler and Start nflog Source: https://github.com/luttermann/python-nflog/blob/master/README.md Defines a callback function for packet processing and initializes the nflog handle. Ensure nflog rules are configured in the packet filter before starting. ```python def nf_callback_packet_handler( indev, # (int) Inbound network device number outdev, # (int) Outbound network device number ifname, # (str) Network device name proto, # (int) Ethertype, see net/ethernet.h payload_len, # (int) Length of payload payload, # (bytes) Payload hw_hdr_len, # (int) Length of hardware link-layer header hw_hdr, # (bytes) Hardware header ): pass import nflog nflog.setgroup(1) nflog.setcb( nf_callback_packet_handler ) nflog.start() n = nflog.handle() ``` -------------------------------- ### Complete Packet Capture with Hex Dump Source: https://context7.com/luttermann/python-nflog/llms.txt A full example demonstrating packet capture with formatted hex output of packet contents. Includes a hexdump utility and a callback to process and display packet details. ```python #!/usr/bin/env python3 import nflog import select import time def hexdump(data, prefix=""): """Print data in hex dump format.""" for i in range(0, len(data), 16): hex_part = " ".join(f"{b:02x}" for b in data[i:i+16]) ascii_part = "".join(chr(b) if 32 <= b < 127 else "." for b in data[i:i+16]) print(f"{prefix}{i:04x} {hex_part:<48} {ascii_part}") def packet_callback(indev, outdev, ifname, proto, payload_len, payload, hw_hdr_len, hw_hdr): """Process each captured packet.""" print("=" * 60) print(f"Interface: {ifname} (in={indev}, out={outdev})") print(f"Ethertype: 0x{proto:04x}", end="") # Decode common ethertypes ethertypes = {0x0800: "IPv4", 0x0806: "ARP", 0x86DD: "IPv6"} if proto in ethertypes: print(f" ({ethertypes[proto]})") else: print() # Print hardware header if present if hw_hdr_len > 0: print(f"\nHardware Header ({hw_hdr_len} bytes):") hexdump(hw_hdr, " ") # Print packet payload print(f"\nPayload ({payload_len} bytes):") hexdump(payload, " ") print() # Configure iptables rule first: # sudo iptables -A INPUT -p icmp -j NFLOG --nflog-group 1 # sudo iptables -A OUTPUT -p icmp -j NFLOG --nflog-group 1 nflog.setgroup(1) nflog.setcb(packet_callback) nflog.start() fd = nflog.getfd() poll_handle = select.poll() poll_handle.register(fd, select.POLLIN) print("Listening for NFLOG packets on group 1...") print("Test with: ping localhost") print("Press Ctrl+C to stop\n") timeout_ms = 5000 duration = 600 # Run for 10 minutes start_time = time.time() try: while time.time() < (start_time + duration): events = poll_handle.poll(timeout_ms) if events: nflog.handle() except KeyboardInterrupt: print("\nStopping...") finally: nflog.stop() ``` -------------------------------- ### Configure iptables for NFLOG Source: https://context7.com/luttermann/python-nflog/llms.txt Examples of iptables rules to direct network traffic to the NFLOG target for logging. These rules specify the packet criteria and the NFLOG group to which they should be sent. ```bash # Log all incoming ICMP packets to NFLOG group 1 sudo iptables -A INPUT -p icmp -j NFLOG --nflog-group 1 # Log all TCP packets on port 80 to NFLOG group 2 sudo iptables -A INPUT -p tcp --dport 80 -j NFLOG --nflog-group 2 # Log all packets from a specific subnet sudo iptables -A FORWARD -s 192.168.1.0/24 -j NFLOG --nflog-group 1 # List current rules sudo iptables -L -n -v # Remove NFLOG rules when done sudo iptables -D INPUT -p icmp -j NFLOG --nflog-group 1 ``` -------------------------------- ### Configure NFLOG group Source: https://context7.com/luttermann/python-nflog/llms.txt Set the NFLOG group number to listen on. This must be called before start() and matches the iptables --nflog-group parameter. ```python import nflog # Set to listen on NFLOG group 1 # This must match your iptables rule: iptables -A INPUT -j NFLOG --nflog-group 1 nflog.setgroup(1) # Attempting to change group after start() raises RuntimeError nflog.start() try: nflog.setgroup(2) # Raises: RuntimeError: Can not change group when started. except RuntimeError as e: print(f"Error: {e}") ``` -------------------------------- ### nflog.setgroup(group_id) Source: https://context7.com/luttermann/python-nflog/llms.txt Sets the NFLOG group number to listen on. Must be called before start(). ```APIDOC ## nflog.setgroup(group_id) ### Description Sets the NFLOG group number to listen on. This corresponds to the --nflog-group parameter in iptables rules. The group cannot be changed once the listener has started. ### Parameters #### Arguments - **group_id** (int) - Required - The NFLOG group number to listen on. ``` -------------------------------- ### Get socket file descriptor Source: https://context7.com/luttermann/python-nflog/llms.txt Retrieve the netfilter socket file descriptor for use with select or poll. ```python import nflog import select def my_callback(indev, outdev, ifname, proto, payload_len, payload, hw_hdr_len, hw_hdr): print(f"Packet: {payload_len} bytes") nflog.setgroup(1) nflog.setcb(my_callback) # Before start(), getfd() returns None fd_before = nflog.getfd() print(f"FD before start: {fd_before}") # Output: FD before start: None nflog.start() # After start(), getfd() returns the socket fd fd = nflog.getfd() print(f"FD after start: {fd}") # Output: FD after start: 3 (or similar) ``` -------------------------------- ### Retrieve current NFLOG group Source: https://context7.com/luttermann/python-nflog/llms.txt Get the currently configured NFLOG group number as an integer. ```python import nflog nflog.setgroup(5) group = nflog.getgroup() print(f"Listening on NFLOG group: {group}") # Output: Listening on NFLOG group: 5 ``` -------------------------------- ### nflog.handle() Source: https://context7.com/luttermann/python-nflog/llms.txt Reads pending packets from the netfilter socket buffer and invokes the registered callback for each packet. ```APIDOC ## nflog.handle() ### Description Reads pending packets from the netfilter socket buffer and invokes the registered callback for each packet. This function should be called when select() or poll() indicates the file descriptor is readable. ### Response - **bytes_read** (int) - The number of bytes read from the socket, or a negative value on error. ``` -------------------------------- ### nflog.getfd() Source: https://context7.com/luttermann/python-nflog/llms.txt Returns the netfilter socket file descriptor. ```APIDOC ## nflog.getfd() ### Description Returns the netfilter socket file descriptor as an integer, or None if called before start(). Useful for event-driven processing with select.select(). ### Response - **Return Value** (int|None) - The socket file descriptor or None. ``` -------------------------------- ### Read Pending Packets with nflog.handle() Source: https://context7.com/luttermann/python-nflog/llms.txt Reads pending packets from the netfilter socket buffer and invokes a registered callback for each. This function should be called when `select()` or `poll()` indicates the file descriptor is readable. Returns the number of bytes read or a negative value on error. ```python import nflog import select def my_callback(indev, outdev, ifname, proto, payload_len, payload, hw_hdr_len, hw_hdr): print(f"[{ifname}] {payload_len} bytes, ethertype=0x{proto:04x}") nflog.setgroup(1) nflog.setcb(my_callback) nflog.start() fd = nflog.getfd() poll_obj = select.poll() poll_obj.register(fd, select.POLLIN) # Process packets for 60 seconds import time end_time = time.time() + 60 while time.time() < end_time: events = poll_obj.poll(1000) # 1 second timeout if events: bytes_read = nflog.handle() print(f"Processed {bytes_read} bytes from socket") ``` -------------------------------- ### nflog.setcb(callback_function) Source: https://context7.com/luttermann/python-nflog/llms.txt Registers a callback function to be invoked for each captured packet. ```APIDOC ## nflog.setcb(callback_function) ### Description Registers a callback function that will be invoked for each captured packet. The callback must accept 8 parameters. ### Parameters #### Arguments - **callback_function** (callable) - Required - A function accepting: indev (int), outdev (int), ifname (str), proto (int), payload_len (int), payload (bytes), hw_hdr_len (int), hw_hdr (bytes). ``` -------------------------------- ### Register packet callback function Source: https://context7.com/luttermann/python-nflog/llms.txt Define and register a callback function that receives packet metadata and raw payload data. ```python import nflog def packet_handler( indev, # (int) Inbound network device index (0 if not applicable) outdev, # (int) Outbound network device index (0 if not applicable) ifname, # (str) Network interface name (e.g., "eth0", "wlan0") proto, # (int) Ethertype protocol number (0x0800=IPv4, 0x0806=ARP, 0x86DD=IPv6) payload_len, # (int) Length of the packet payload in bytes payload, # (bytes) Raw packet payload starting from IP header hw_hdr_len, # (int) Length of hardware link-layer header hw_hdr # (bytes) Hardware header (Ethernet header when applicable) ): print(f"Packet on {ifname}: {payload_len} bytes, proto=0x{proto:04x}") # Parse IPv4 header if this is an IP packet if proto == 0x0800 and payload_len >= 20: src_ip = ".".join(str(b) for b in payload[12:16]) dst_ip = ".".join(str(b) for b in payload[16:20]) print(f" IPv4: {src_ip} -> {dst_ip}") # Register the callback nflog.setcb(packet_handler) ``` -------------------------------- ### nflog.getgroup() Source: https://context7.com/luttermann/python-nflog/llms.txt Retrieves the currently configured NFLOG group number. ```APIDOC ## nflog.getgroup() ### Description Returns the currently configured NFLOG group number as an integer. ### Response - **Return Value** (int) - The configured NFLOG group number. ``` -------------------------------- ### Stop NFLOG Listener with nflog.stop() Source: https://context7.com/luttermann/python-nflog/llms.txt Stops the NFLOG listener by unbinding from the group and closing the netfilter handle. This should be called for a clean shutdown, typically in response to an interrupt signal. ```python import nflog import signal import sys def my_callback(indev, outdev, ifname, proto, payload_len, payload, hw_hdr_len, hw_hdr): print(f"Packet: {payload_len} bytes") def signal_handler(sig, frame): print("\nShutting down...") nflog.stop() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) nflog.setgroup(1) nflog.setcb(my_callback) nflog.start() fd = nflog.getfd() import select poll_obj = select.poll() poll_obj.register(fd, select.POLLIN) print("Capturing packets (Ctrl+C to stop)...") while True: if poll_obj.poll(1000): nflog.handle() ``` -------------------------------- ### nflog.stop() Source: https://context7.com/luttermann/python-nflog/llms.txt Stops the NFLOG listener by unbinding from the group and closing the netfilter handle. ```APIDOC ## nflog.stop() ### Description Stops the NFLOG listener by unbinding from the group and closing the netfilter handle. Should be called for clean shutdown. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.