Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
620 lines (560 loc) · 18.4 KB
/
Copy pathmain.cpp
File metadata and controls
620 lines (560 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/**
* Filter Traffic AF_XDP example application
* =========================================
*
* This application demonstrates PcapPlusPlus AF_XDP APIs.
* Please read the README.md file for more information.
*
* You can also run `XdpTrafficFilter -h` for modes of operation and parameters.
*/
#include "PacketMatchingEngine.h"
#include "SystemUtils.h"
#include "PcapPlusPlusVersion.h"
#include "PacketUtils.h"
#include "TablePrinter.h"
#include "XdpDevice.h"
#include "PcapFileDevice.h"
#include "PcapLiveDeviceList.h"
#include <getopt.h>
#include <unordered_map>
#include <future>
#include <iostream>
#include <thread>
#define EXIT_WITH_ERROR(reason) \
do \
{ \
std::cout << std::endl << "ERROR: " << reason << std::endl << std::endl; \
exit(1); \
} while (0)
#define EXIT_WITH_ERROR_AND_PRINT_USAGE(reason) \
do \
{ \
printUsage(); \
std::cout << std::endl << "ERROR: " << reason << std::endl << std::endl; \
exit(1); \
} while (0)
/**
* A struct to collect packet stats
*/
struct PacketStats
{
public:
int packetCount;
int ethCount;
int arpCount;
int ip4Count;
int ip6Count;
int tcpCount;
int udpCount;
int httpCount;
int dnsCount;
int sslCount;
int totalTcpFlows;
int totalUdpFlows;
int matchedTcpFlows;
int matchedUdpFlows;
int matchedPacketCount;
PacketStats()
: packetCount(0), ethCount(0), arpCount(0), ip4Count(0), ip6Count(0), tcpCount(0), udpCount(0), httpCount(0),
dnsCount(0), sslCount(0), totalTcpFlows(0), totalUdpFlows(0), matchedTcpFlows(0), matchedUdpFlows(0),
matchedPacketCount(0)
{}
/**
* Collect stats per packet
*/
void collectStats(pcpp::Packet& packet)
{
packetCount++;
if (packet.isPacketOfType(pcpp::Ethernet))
ethCount++;
if (packet.isPacketOfType(pcpp::ARP))
arpCount++;
if (packet.isPacketOfType(pcpp::IPv4))
ip4Count++;
if (packet.isPacketOfType(pcpp::IPv6))
ip6Count++;
if (packet.isPacketOfType(pcpp::TCP))
tcpCount++;
if (packet.isPacketOfType(pcpp::UDP))
udpCount++;
if (packet.isPacketOfType(pcpp::HTTP))
httpCount++;
if (packet.isPacketOfType(pcpp::DNS))
dnsCount++;
if (packet.isPacketOfType(pcpp::SSL))
sslCount++;
}
};
/**
* A struct that holds all arguments passed to the packet capture callback
*/
struct PacketCaptureArgs
{
PacketStats* packetStats;
PacketMatchingEngine* matchingEngine;
std::unordered_map<uint32_t, bool> flowTable;
pcpp::XdpDevice* sendPacketsTo;
pcpp::PcapFileWriterDevice* pcapWriter;
bool stopCapture;
PacketCaptureArgs()
: packetStats(nullptr), matchingEngine(nullptr), sendPacketsTo(nullptr), pcapWriter(nullptr), stopCapture(false)
{}
};
// clang-format off
static struct option XdpFilterTrafficOptions[] = {
{ "interface", required_argument, nullptr, 'n' },
{ "send-matched-packets", required_argument, nullptr, 's' },
{ "save-matched-packets", required_argument, nullptr, 'f' },
{ "match-source-ip", required_argument, nullptr, 'i' },
{ "match-dest-ip", required_argument, nullptr, 'I' },
{ "match-source-port", required_argument, nullptr, 'p' },
{ "match-dest-port", required_argument, nullptr, 'P' },
{ "match-protocol", required_argument, nullptr, 'r' },
{ "help", no_argument, nullptr, 'h' },
{ "version", no_argument, nullptr, 'v' },
{ "list-interfaces", no_argument, nullptr, 'l' }
};
// clang-format on
/**
* A callback to handle packets that were received on the AF_XDP socket
*/
void onPacketsArrive(pcpp::RawPacket packets[], uint32_t packetCount, pcpp::XdpDevice* device, void* userCookie)
{
auto args = reinterpret_cast<PacketCaptureArgs*>(userCookie);
// if the user asked to interrupt the app, stop receiving packets
if (args->stopCapture)
{
device->stopReceivePackets();
return;
}
pcpp::RawPacketVector packetsToSend;
// go over all received packets
for (uint32_t i = 0; i < packetCount; i++)
{
// parse packet
pcpp::Packet packet(&packets[i]);
// collect stats for packet
args->packetStats->collectStats(packet);
// hash the packet by 5-tuple and look in the flow table to see whether this packet belongs to an existing or
// new flow
uint32_t hash = pcpp::hash5Tuple(&packet);
auto iter = args->flowTable.find(hash);
bool packetMatched;
// if packet belongs to an already existing flow
if (iter != args->flowTable.end())
{
packetMatched = true;
}
else // packet belongs to a new flow
{
auto isTcpFlow = packet.isPacketOfType(pcpp::TCP);
auto isUdpFlow = packet.isPacketOfType(pcpp::UDP);
if (isTcpFlow)
{
args->packetStats->totalTcpFlows++;
}
else if (isUdpFlow)
{
args->packetStats->totalUdpFlows++;
}
packetMatched = args->matchingEngine->isMatched(packet);
if (packetMatched)
{
// put new flow in flow table
args->flowTable[hash] = true;
// collect stats
if (isTcpFlow)
{
args->packetStats->matchedTcpFlows++;
}
else if (isUdpFlow)
{
args->packetStats->matchedUdpFlows++;
}
}
}
if (packetMatched)
{
if (args->sendPacketsTo != nullptr)
{
// add packet to the vector of packets to send
packetsToSend.pushBack(new pcpp::RawPacket(packets[i]));
}
// save packet to file if needed
if (args->pcapWriter != nullptr)
{
args->pcapWriter->writePacket(packets[i]);
}
args->packetStats->matchedPacketCount++;
}
}
// send packets if there are packets to send and a send device was configured
if (args->sendPacketsTo != nullptr && packetsToSend.size() > 0)
{
args->sendPacketsTo->sendPackets(packetsToSend, true);
}
}
/**
* Print the stats in a table
*/
void printStats(PacketStats* packetStats, pcpp::XdpDevice::XdpDeviceStats* rxDeviceStats,
pcpp::XdpDevice::XdpDeviceStats* txDeviceStats)
{
std::vector<std::string> columnNames = { "Stat", "Count" };
std::vector<int> columnsWidths = { 21, 10 };
pcpp::TablePrinter printer(columnNames, columnsWidths);
printer.printRow("Eth count|" + std::to_string(packetStats->ethCount), '|');
printer.printRow("ARP count|" + std::to_string(packetStats->arpCount), '|');
printer.printRow("IPv4 count|" + std::to_string(packetStats->ip4Count), '|');
printer.printRow("IPv6 count|" + std::to_string(packetStats->ip6Count), '|');
printer.printRow("TCP count|" + std::to_string(packetStats->tcpCount), '|');
printer.printRow("UDP count|" + std::to_string(packetStats->udpCount), '|');
printer.printRow("HTTP count|" + std::to_string(packetStats->httpCount), '|');
printer.printRow("DNS count|" + std::to_string(packetStats->dnsCount), '|');
printer.printRow("SSL/TLS count|" + std::to_string(packetStats->sslCount), '|');
printer.printSeparator();
printer.printRow("Matched TCP flows|" + std::to_string(packetStats->matchedTcpFlows), '|');
printer.printRow("Matched UDP flows|" + std::to_string(packetStats->matchedUdpFlows), '|');
printer.printRow("Total TCP flows|" + std::to_string(packetStats->totalTcpFlows), '|');
printer.printRow("Total UDP flows|" + std::to_string(packetStats->totalUdpFlows), '|');
printer.printSeparator();
printer.printRow("Matched packet count|" + std::to_string(packetStats->matchedPacketCount), '|');
printer.printRow("Total packet count|" + std::to_string(packetStats->packetCount), '|');
printer.printSeparator();
printer.printRow("RX packets|" + std::to_string(rxDeviceStats->rxPackets), '|');
printer.printRow("RX packets/sec|" + std::to_string(rxDeviceStats->rxPacketsPerSec), '|');
printer.printRow("RX bytes|" + std::to_string(rxDeviceStats->rxBytes), '|');
printer.printRow("RX bytes/sec|" + std::to_string(rxDeviceStats->rxBytesPerSec), '|');
if (txDeviceStats)
{
printer.printRow("TX packets|" + std::to_string(txDeviceStats->txCompletedPackets), '|');
printer.printRow("TX packets/sec|" + std::to_string(txDeviceStats->txCompletedPacketsPerSec), '|');
printer.printRow("TX bytes|" + std::to_string(txDeviceStats->txSentBytes), '|');
printer.printRow("TX bytes/sec|" + std::to_string(txDeviceStats->txSentBytesPerSec), '|');
}
printer.closeTable();
}
/**
* Collect stats thread runner
*/
void collectStats(std::future<void> futureObj, PacketStats* packetStats, pcpp::XdpDevice* dev, pcpp::XdpDevice* sendDev)
{
// run in an endless loop until the signal is received and print stats every 1 sec
while (futureObj.wait_for(std::chrono::milliseconds(1000)) == std::future_status::timeout)
{
// collect RX stats
auto rxStats = dev->getStatistics();
pcpp::XdpDevice::XdpDeviceStats* txStats = nullptr;
if (sendDev)
{
// if send socket is different from receive socket, collect stats from the send socket
if (sendDev != dev)
{
txStats = new pcpp::XdpDevice::XdpDeviceStats(sendDev->getStatistics());
}
else // send and receive sockets are the same
{
txStats = &rxStats;
}
}
// print RX and (maybe) TX stats in a table
printStats(packetStats, &rxStats, txStats);
if (txStats != &rxStats)
{
delete txStats;
}
}
}
/**
* Print application usage
*/
void printUsage()
{
std::cout << std::endl
<< "Usage:" << std::endl
<< "------" << std::endl
<< pcpp::AppName::get()
<< " [-hvl] [-s INTERFACE_NAME] [-f FILENAME] [-i IPV4_ADDR] [-I IPV4_ADDR] [-p PORT] [-P PORT] [-r "
"PROTOCOL] -n INTERFACE_NAME"
<< std::endl
<< std::endl
<< "Options:" << std::endl
<< std::endl
<< " -h|--help : Displays this help message and exits" << std::endl
<< " -v|--version : Displays the current version and exits" << std::endl
<< " -l|--list : Print the list of network interfaces and exit"
<< std::endl
<< " -n|--interface-name INTERFACE_NAME : An interface name to open AF_XDP socket and receive "
"packets from."
<< std::endl
<< " To see all available interfaces use the -l switch"
<< std::endl
<< " -s|--send-matched-packets INTERFACE_NAME : Network interface name to send matched packets to."
<< std::endl
<< " The app will open another AF_XDP socket for sending "
"packets."
<< std::endl
<< " Note: this interface can be the same one used to "
"receive packets."
<< std::endl
<< " -f|--save-matched-packets FILEPATH : Save matched packets to pcap files under FILEPATH."
<< std::endl
<< " -i|--match-source-ip IPV4_ADDR : Match source IPv4 address" << std::endl
<< " -I|--match-dest-ip IPV4_ADDR : Match destination IPv4 address" << std::endl
<< " -p|--match-source-port PORT : Match source TCP/UDP port" << std::endl
<< " -P|--match-dest-port PORT : Match destination TCP/UDP port" << std::endl
<< " -r|--match-protocol PROTOCOL : Match protocol. Valid values are 'TCP' or 'UDP'"
<< std::endl
<< std::endl;
}
/**
* Print application version
*/
void printAppVersion()
{
std::cout << pcpp::AppName::get() << " " << pcpp::getPcapPlusPlusVersionFull() << std::endl
<< "Built: " << pcpp::getBuildDateTime() << std::endl
<< "Built from: " << pcpp::getGitInfo() << std::endl;
exit(0);
}
/**
* Go over all interfaces and output their names
*/
void listInterfaces()
{
std::cout << std::endl << "Network interfaces:" << std::endl;
for (const auto& device : pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDevicesList())
{
if (device->getIPv4Address() != pcpp::IPv4Address::Zero)
{
std::cout << " -> Name: '" << device->getName()
<< "' IP address: " << device->getIPv4Address().toString() << std::endl;
}
}
exit(0);
}
int main(int argc, char* argv[])
{
pcpp::AppName::init(argc, argv);
int optionIndex = 0;
int opt;
std::string interfaceName;
pcpp::IPv4Address srcIPToMatch = pcpp::IPv4Address::Zero;
pcpp::IPv4Address dstIPToMatch = pcpp::IPv4Address::Zero;
uint16_t srcPortToMatch = 0;
uint16_t dstPortToMatch = 0;
pcpp::ProtocolType protocolToMatch = pcpp::UnknownProtocol;
std::string writePacketsToFileName;
std::string sendInterfaceName;
while ((opt = getopt_long(argc, argv, "n:f:s:i:I:p:P:r:vhl", XdpFilterTrafficOptions, &optionIndex)) != -1)
{
switch (opt)
{
case 0:
{
break;
}
case 'n':
{
interfaceName = std::string(optarg);
break;
}
case 'f':
{
writePacketsToFileName = std::string(optarg);
break;
}
case 's':
{
sendInterfaceName = std::string(optarg);
break;
}
case 'i':
{
try
{
srcIPToMatch = pcpp::IPv4Address(optarg);
}
catch (const std::exception&)
{
EXIT_WITH_ERROR_AND_PRINT_USAGE("Source IP to match isn't a valid IP address");
}
break;
}
case 'I':
{
try
{
dstIPToMatch = pcpp::IPv4Address(optarg);
}
catch (const std::exception&)
{
EXIT_WITH_ERROR_AND_PRINT_USAGE("Destination IP to match isn't a valid IP address");
}
break;
}
case 'p':
{
int ret = std::stoi(optarg);
if (ret <= 0 || ret > 65535)
{
EXIT_WITH_ERROR_AND_PRINT_USAGE("Source port to match isn't a valid TCP/UDP port");
}
srcPortToMatch = ret;
break;
}
case 'P':
{
int ret = std::stoi(optarg);
if (ret <= 0 || ret > 65535)
{
EXIT_WITH_ERROR_AND_PRINT_USAGE("Destination port to match isn't a valid TCP/UDP port");
}
dstPortToMatch = ret;
break;
}
case 'r':
{
std::string protocol = std::string(optarg);
if (protocol == "TCP")
{
protocolToMatch = pcpp::TCP;
}
else if (protocol == "UDP")
{
protocolToMatch = pcpp::UDP;
}
else
{
EXIT_WITH_ERROR_AND_PRINT_USAGE("Protocol to match isn't TCP or UDP");
}
break;
}
case 'h':
{
printUsage();
exit(0);
}
case 'v':
{
printAppVersion();
break;
}
case 'l':
{
listInterfaces();
exit(0);
}
default:
{
printUsage();
exit(0);
}
}
}
if (interfaceName.empty())
{
EXIT_WITH_ERROR("Interface name was not provided");
}
// open the pcap writer if needed
pcpp::PcapFileWriterDevice* pcapWriter = nullptr;
if (!writePacketsToFileName.empty())
{
pcapWriter = new pcpp::PcapFileWriterDevice(writePacketsToFileName);
if (!pcapWriter->open())
{
delete pcapWriter;
EXIT_WITH_ERROR("Couldn't open pcap file to write packets");
}
}
// open the XDP device
pcpp::XdpDevice dev(interfaceName);
if (!dev.open())
{
EXIT_WITH_ERROR("Error opening the device");
}
// open the XDP device to send packets if needed
pcpp::XdpDevice* sendDev = nullptr;
if (!sendInterfaceName.empty())
{
// send and receive devices might be the same
if (sendInterfaceName == interfaceName)
{
sendDev = &dev;
}
else
{
// if they are not the same, open another AF_XDP socket for the send device
sendDev = new pcpp::XdpDevice(sendInterfaceName);
if (!sendDev->open())
{
dev.close();
delete sendDev;
EXIT_WITH_ERROR("Error opening send device");
}
}
}
// create the matching engine instance
PacketMatchingEngine matchingEngine(srcIPToMatch, dstIPToMatch, srcPortToMatch, dstPortToMatch, protocolToMatch);
PacketStats packetStats;
// prepare configuration
PacketCaptureArgs args;
args.packetStats = &packetStats;
args.matchingEngine = &matchingEngine;
args.sendPacketsTo = sendDev;
args.pcapWriter = pcapWriter;
// create future and promise instances to signal the stats collection threads when to stop
std::promise<void> exitSignal;
std::future<void> futureObj = exitSignal.get_future();
// create and run a stats collection thread
std::thread collectStatsThread(&collectStats, std::move(futureObj), &packetStats, &dev, sendDev);
// add an handler for app interrupted signal, i.e ctrl+c
pcpp::ApplicationEventHandler::getInstance().onApplicationInterrupted(
[](void* args) { reinterpret_cast<PacketCaptureArgs*>(args)->stopCapture = true; }, &args);
// start receiving packets on the AF_XDP socket
auto res = dev.receivePackets(onPacketsArrive, &args, -1);
// user clicked ctrl+c, prepare to shut the app down
// signal the stats collection thread to stop and wait for it to stop
exitSignal.set_value();
collectStatsThread.join();
// close the pcap writer if needed
std::vector<std::string> additionalStats;
if (pcapWriter)
{
pcpp::IPcapDevice::PcapStats stats;
pcapWriter->getStatistics(stats);
additionalStats.push_back("Wrote " + std::to_string(stats.packetsRecv) + " packets to '" +
pcapWriter->getFileName() + "'");
pcapWriter->close();
delete pcapWriter;
}
pcpp::XdpDevice::XdpDeviceStats* txStats = nullptr;
// close the send XDP device if needed
if (sendDev != nullptr)
{
// collect final TX stats
txStats = new pcpp::XdpDevice::XdpDeviceStats(sendDev->getStatistics());
// if the send and receive devices are the same - no need to close the device again
if (sendInterfaceName != interfaceName)
{
sendDev->close();
delete sendDev;
}
}
// collect final RX stats
pcpp::XdpDevice::XdpDeviceStats rxStats = dev.getStatistics();
// close the XDP device
dev.close();
// print final stats
printStats(&packetStats, &rxStats, txStats);
delete txStats;
for (const auto& additionalStat : additionalStats)
{
std::cout << additionalStat << std::endl;
}
// exit with an error if there was an error receiving packets
if (!res)
{
EXIT_WITH_ERROR("Something went wrong while receiving packets");
}
}