Implementujte program p2nprobe, který bude extrahovat informace o tocích ze souboru PCAP a bude je odesílat na kolektor ve formátu NetFlow v5. Nástroj bude na vstupu načítat pakety ze zadaného PCAP souboru, agregovat je do toků. Toky bude odesílat pomocí protokolu UDP na NetFlow v5 kolektor, kde budou přijaty a dále zpracovány. Vaším úkolem je implementovat pouze exportér a omezit se pouze na export záznamů o tocích TCP, ostatní provoz nezpracováváte.
code
Spuštění programu
./p2nprobe <host>:<port> <pcap_file_path> [-a <active_timeout> -i <inactive_timeout>]
Pořadí parametrů je libovolné. Popis parametrů:
<pcap_file_path> - zde bude uvedena cesta k souboru PCAP, který se má zpracovat;
<host> - IP adresa nebo doménové jméno kolektoru;
<port> - port kolektoru, kam budou zprávy odesílány;
-a <active_timout> - počet sekund pro nastavení aktivního timeoutu exportu flow (defaultní hodnota při nepoužití parametru 60);
-i <inactive_timeout> - počet sekund pro nastavení inaktivního timoutu exportu flow (defaultní hodnota při nepoužití parametru 60).
Další informace
Protokol NetFlow v5 je velmi rozšířený a známý, neexistuje pro něj však RFC. Informace k tomuto protokolu budete muset nalézt na internetu, například na stránkách společnosti CISCO, která za tímto protokolem stojí.
Při implementaci můžete využít program nfcapd jako příjemce NetFlow v5 zpráv (kolektor). Dále můžete použít programy existujících NetFlow v5 exportérů jako je například softflowd (přepínač -v 5 pro export NetFlow v5) a prostudovat zachycenou komunikaci pomocí programu Wireshark.
Při odesílání zpráv na kolektor se snažte být maximálně efektivní a využít počet exportovaných záznamů o tocích ve zprávě na maximum, pokud to bude možné.
Při hodnocení bude dbáno na korektní výstup zpracovaného souboru, tedy počet exportovaných toků a součet statistických informací z toků (správný počet paketů a bytů), korektní identifikátory (IP, port, protokol), časové značky toku a další. Políčka v záznamu o toku, která nebude možné vyplnit, jako například NextHop, SrcAS, DstAS a další, nechte prázdná, ostatní pole vypiště korektně.
Prostudujte rozdíly mezi aktivním a neaktivním timeoutem a jejich vlivem na činnost exportéru a výsledné záznamy o tocích. Tuto funcionalitu pak správně implementujte.
Implementační detaily
Program implementujte v jazyce C/C++ pro prostředí Unixových systémů. Referenční prostředí pro překlad bude server merlin.fit.vutbr.cz.
Je povoleno (a doporučeno) použít knihovnu libpcap. Dále můžete použít hlavičkové soubory pro práci se sokety a další obvyklé funkce používané v síťovém prostředí (jako je netinet/*, sys/*, arpa/* apod.), knihovnu pro práci s vlákny (pthread), signály, časem, stejně jako standardní knihovnu jazyka C (varianty ISO/ANSI i POSIX, všetně souvisejících hlavičkových souborů: ctype.h, string.h., aj), standardní knihovnu jazyka C++ a STL (včetně souvisejících hlaviček). Jiné knihovny nejsou povoleny, nestanoví-li vyučující jinak.
Příklad spuštění
./p2nprobe localhost:2055 muj_pcap.pcap -a 5 -i 30
./p2nprobe localhost:2055 muj_pcap.pcap
Program v případě hladkého běhu nebude vypisovat žádné hlášky na standardní výstup, pouze případné chyby na standardní chybový výstup, pokud nastanou.
explain in highly detailed steps how to do it
Creating a program, p2nprobe, to extract TCP flows from a PCAP file and send them to a NetFlow v5 collector requires several key steps. This task involves handling networking, packet analysis, and flow data aggregation. Below, I'll provide a detailed breakdown of the main steps required to implement this program.
Part 1: Environment Setup
Setup and Verify Development Environment:
Ensure you have a Unix-based system for development.
Install necessary tools if not already available: compilers for C/C++ (like gcc or g++), libpcap-dev for packet capture, and any related socket programming libraries.
Verify the installation and configuration by compiling a simple "Hello World" program using gcc or g++.
Part 2: Understanding NetFlow v5
Research NetFlow v5 Format:
Refer to Cisco documentation and other online resources to understand the structure of NetFlow v5 packets.
Key aspects to understand are what fields are mandatory, their sizes, and semantics (e.g., timestamps, packet counts, byte counts, source/destination IPs, ports).
Part 3: Design the Solution
Design the Program Flow:
Parse command-line arguments to extract the collector’s host and port, the path to the PCAP file, and optional timeouts.
Open and parse the provided PCAP file to capture network packets using libpcap.
Filter the packets to only process TCP flows.
Aggregate packets into flows, managing flow state with active and inactive timeouts.
Format these flows as NetFlow v5 records.
Send these records to the specified collector using UDP.
Part 4: Implement the Solution
Parse Command-Line Arguments:
Use standard C/C++ libraries or utilities like getopt to interpret command-line arguments.
Handle parsing errors and default timeout values (60 seconds if unspecified).
Open and Parse the PCAP File:
Use libpcap to open the specified PCAP file.
Set up packet filtering to capture only TCP packets. This can be done using a BPF filter.
Aggregate Packets into Flows:
Define a data structure to represent a flow, including fields like IP addresses, ports, protocol, byte/packet counts, and timestamps.
Set up a flow table that manages active flows, keyed by the tuple (src IP, dst IP, src port, dst port, and protocol).
Implement active and inactive timeouts to export flows at appropriate intervals. The active timeout triggers after a flow has been open too long. The inactive timeout triggers when there's been no activity for some time.
Format Flows as NetFlow v5 Records:
Construct NetFlow v5 records for each flow using the data collected, ensuring all the required fields are populated per protocol specifications.
Be prepared to handle records' batching and/or single record creation depending on collector capabilities/requirements.
Send Flows to the Collector:
Use sockets (sys/socket.h, netinet/in.h, arpa/inet.h) to create a UDP socket for sending data.
Format NetFlow v5 packets to include the header and multiple flow records.
Send the formatted packets to the specified host and port.
Part 5: Testing and Debugging
Testing:
Test your implementation against a local NetFlow collector like nfcapd.
Use Wireshark to observe and confirm the packets being constructed and sent correctly.
Debugging:
Log detailed error messages to standard error on failure conditions.
Develop tests for edge cases, such as no flows, large flow tables, and interaction of active/inactive timeouts.
Optimize and Document:
Ensure your code is optimized for processing large PCAP files efficiently.
Comment and document the code thoroughly to describe data structures, logic, and NetFlow packet creation.
By following these steps, you will implement a simple yet efficient tool that reads TCP traffic from PCAP files, aggregates them into flows, formats these flows according to the NetFlow v5 specification, and transmits them to a NetFlow collector via UDP.
Implementing p2nprobe involves several technical components, including network packet handling, flow aggregation, and protocol-specific formatting. Below is a detailed technical guide, broken into phases, to help you develop this program using C/C++.
Phase 1: Environment Setup and Preliminary Research
Install Required Software:
Ensure gcc/g++ is installed for C/C++ compilation.
Install libpcap-dev for packet capturing abilities (sudo apt-get install libpcap-dev on Ubuntu).
Understand NetFlow v5 Format:
NetFlow v5 consists of a header of fixed length and a series of flow records.
Each flow record contains source/destination IPs, ports, protocol, packet/byte counts, start/last timestamps, etc.
Refer to Cisco's NetFlow documentation for specifics on each field.
Phase 2: Implementation Plan
Parse Command-Line Arguments:
Use functions like getopt() for argument parsing.
Validate input to ensure host, port, and filepath are provided.
Handle optional arguments for active (-a) and inactive (-i) timeouts with default values set to 60 seconds.
Initialize and Open PCAP File:
Use pcap_open_offline() to open the PCAP file.
Select only TCP traffic by applying a BPF filter: tcp. This is done via pcap_compile() and pcap_setfilter().
Phase 3: Flow Aggregation
Define a Flow Data Structure:
c
struct Flow {
uint32_t src_ip;
uint32_t dst_ip;
uint16_t src_port;
uint16_t dst_port;
uint8_t protocol;
uint32_t packet_count;
uint32_t byte_count;
uint32_t first_seen;
uint32_t last_seen;
// Fields like NextHop, AS numbers can be initialized with zero.
};
Flow Management:
Use a data structure like a hashmap or balanced binary tree to store active flows.
The key for a flow would be the (src IP, dst IP, src port, dst port, protocol) tuple.
Packet Processing Loop:
Use pcap_loop() to iterate over each packet.
Extract fields from each packet to categorize it into a flow. Functions like pcap_offline-read() will help traverse packets.
Update flow information: increase packet/byte counters, and revise timestamps.
Periodically check and expire inactive flows (i.e., those that haven't seen packets in inactive_timeout seconds).
Phase 4: NetFlow Packet Construction
Construct NetFlow Packets:
Define structures for NetFlow v5 header and flow record.
For the header, maintain fields like sys_uptime, unix_secs, and flow_count.
c
struct NetFlowV5Header {
uint16_t version;
uint16_t count; // Number of flow entries
uint32_t sys_uptime;
uint32_t unix_secs;
uint32_t unix_nsecs;
uint32_t flow_sequence;
uint8_t engine_type;
uint8_t engine_id;
uint16_t sampling_interval;
};
struct NetFlowV5Record {
uint32_t src_ip;
uint32_t dst_ip;
uint32_t next_hop; // Set to zero
uint16_t input; // Interfance index, set to zero
uint16_t output; // Interface index, set to zero
uint32_t d_pkts;
uint32_t d_octets;
uint32_t first;
uint32_t last;
uint16_t src_port;
uint16_t dst_port;
uint16_t pad1;
uint8_t tcp_flags;
uint8_t prot;
uint8_t tos;
uint16_t src_as; // Set to zero
uint16_t dst_as; // Set to zero
uint8_t src_mask;
uint8_t dst_mask;
uint16_t pad2;
};
Prepare and Send UDP Packets:
Use socket.h and related libraries to establish a UDP socket.
Populate the NetFlow record array and header, batching multiple flows in one packet until the maximum record limit (typically 30).
Use sendto() to send the assembled packet to the collector's IP and port.
Phase 5: Testing and Optimization
Testing:
Use a tool like nfcapd to capture NetFlow data being sent by your program.
Inspect the output using nfdump to verify correctness.
Utilize Wireshark to look at the raw UDP packets and ensure they conform to NetFlow v5 specification.
Handling Errors and Edge Cases:
Implement checks for empty and full flow tables.
Implement logging for error conditions like socket issues or invalid packet formats, outputting errors to standard error (stderr).
Optimization:
Find a balance between memory usage and the number of active flows tracked.
Optimize packet capturing and processing loop for performance, especially for large PCAP files.
By meticulously following these steps, you can implement a robust C/C++ program that not only captures and processes network data efficiently but also effectively communicates this data in the NetFlow v5 format to a designated collector.
In C++, macros are a powerful preprocessor feature that can be used to define code snippets which can be inserted into your program. For debugging and informational output purposes, defining a macro for printing messages can save you time and make your code cleaner. Here's how you can define a macro for printing information:
#define PRINT_INFO(msg): This is the macro definition. It takes a single parameter msg.
std::cout << "[INFO] ": This part prints a tag to indicate the type of message. You can customize this tag to include different levels of logging, such as [DEBUG], [ERROR], etc.
__FILE__, __LINE__, and __FUNCTION__: These are predefined macros in C++:
__FILE__: Expands to the current file name as a string.
__LINE__: Expands to the current line number in the source file.
__FUNCTION__: Expands to the name of the current function (available in C++).
msg: The actual message you want to print.
std::endl: Ensures the output is flushed to the console immediately and moves to the next line.
Usage
Call PRINT_INFO("Your message here"); in your code wherever you need to log information or debug purpose.
Advanced Macro with Conditional Logging
For larger projects, you might want to include conditional compilation to enable or disable these messages without changing the source code much. Here's an enhanced version:
The #if defined(DEBUG) preprocessor directive ensures that the PRINT_INFO macro is only active when DEBUG is defined, which you can do by adding -DDEBUG to your compiler flags, e.g., g++ -DDEBUG your_program.cpp.
Otherwise, PRINT_INFO becomes a no-operation (no-op) macro that the preprocessor effectively removes from your compiled code, which can be useful for production builds where you do not want debug info printed.
This approach allows you to manage logging outputs efficiently throughout the development and production phases.