Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
492 lines (438 loc) · 19 KB
/
Copy pathmain.cpp
File metadata and controls
492 lines (438 loc) · 19 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
/**
* PcapSplitter application
* ========================
* An application that splits a pcap file into smaller pcap files by a user-defined criteria:
*
* 1) File-size - splits the pcap file to smaller pcap files, each file with a certain size defined by the user
* 2) Packet-count - splits the pcap file to smaller pcap files, each with number of packets defined by the user
* 3) Client-IP - splits the pcap file to smaller pcap files so each file contains all TCP/UDP connections
* initiated by a certain client-ip, for example: file#1 will contain connections initiated by 1.1.1.1, file#2
* will contain connections initiated by 1.2.3.4, and so on. The user can limit the number of output files, in
* this case multiple client-ips will be written to the same file. If the user doesn't set such limit - each file
* will contain one client-ip
* 4) Server-IP - splits the pcap file to smaller pcap files so each file contains all TCP/UDP connections
* to a certain server-ip, for example: file#1 will contain connections to 8.8.8.8, file#2 will contain connections
* to 10.12.13.14, and so on. The user can limit the number of output files, in this case multiple server-ips will
* be written to the same file. If the user doesn't set such limit - each file will contain one server-ip
* 5) Server-port - splits the pcap file to smaller pcap files so each file contains all TCP/UDP connections
* to a certain server port, for example: file#1 will contain all port 80 connections (HTTP), file#2 will contain
* all port 25 (SMTP) connections, and so on. The user can limit the number of output files, in this case connections
* to multiple server ports will be written to the same file. If the user doesn't set such limit - each file will
* contain connection to one server port only
* 6) IP source and IP dest - splits the pcap file to smaller pcap files so each file contains all connections made
* between two IP addresses. The user can limit the number of output files, in this case multiple pairs of IP source
* and dest will be written to the same file. If the user doesn't set such limit - all connection of one pair of
* source and dest IP will be written to each file
* 7) Connection - splits a pcap file to smaller pcap files by TCP/UDP connection meaning each connection will be
* written to a certain file. The user can limit the number of output files, in this case an equal number of
* connections will be written to the same file. If the user doesn't set such limit - each file will contain one
* connection
* 8) BPF filter - splits the pcap file into two files: one that contains all packets matching the input BPF filter and
* the other one with the rest of the packets
*
* Remarks:
*
* - Options 3-7 supports both IPv4 and IPV6
* - Number of output files isn't limited, unless the user set such limit in options 3-7
* - There is no limit on the size of the input file, the number of packets it contains or the number of connections it
* contains
* - The user can also set a BPF filter to instruct the application to handle only packets filtered by the filter. The
* rest of the packets in the input file will be ignored
* - In options 3-5 & 7 all packets which aren't UDP or TCP (hence don't belong to any connection) will be written to
* one output file, separate from the other output files (usually file#0)
* - Works only on files of the pcap (TCPDUMP) format
*
*/
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <RawPacket.h>
#include <Packet.h>
#include <PcapFileDevice.h>
#include "SimpleSplitters.h"
#include "IPPortSplitters.h"
#include "ConnectionSplitters.h"
#include <getopt.h>
#include <SystemUtils.h>
#include <PcapPlusPlusVersion.h>
static struct option PcapSplitterOptions[] = {
{ "input-file", required_argument, nullptr, 'f' },
{ "output-file", required_argument, nullptr, 'o' },
{ "method", required_argument, nullptr, 'm' },
{ "param", required_argument, nullptr, 'p' },
{ "filter", required_argument, nullptr, 'i' },
{ "version", no_argument, nullptr, 'v' },
{ "help", no_argument, nullptr, 'h' },
{ nullptr, 0, nullptr, 0 }
};
#define EXIT_WITH_ERROR(reason) \
do \
{ \
printUsage(); \
std::cout << std::endl << "ERROR: " << reason << std::endl << std::endl; \
exit(1); \
} while (0)
#define SPLIT_BY_FILE_SIZE "file-size"
#define SPLIT_BY_PACKET_COUNT "packet-count"
#define SPLIT_BY_IP_CLIENT "client-ip"
#define SPLIT_BY_IP_SERVER "server-ip"
#define SPLIT_BY_SERVER_PORT "server-port"
#define SPLIT_BY_CLIENT_PORT "client-port"
#define SPLIT_BY_2_TUPLE "ip-src-dst"
#define SPLIT_BY_5_TUPLE "connection"
#define SPLIT_BY_BPF_FILTER "bpf-filter"
#define SPLIT_BY_ROUND_ROBIN "round-robin"
#if defined(_WIN32)
# define SEPARATOR '\\'
#else
# define SEPARATOR '/'
#endif
/**
* Print application usage
*/
void printUsage()
{
std::cout
<< std::endl
<< "Usage:" << std::endl
<< "------" << std::endl
<< pcpp::AppName::get() << " [-h] [-v] [-i filter] -f pcap_file -o output_dir -m split_method [-p split_param]"
<< std::endl
<< std::endl
<< "Options:" << std::endl
<< std::endl
<< " -f pcap_file : Input pcap file name" << std::endl
<< " -o output_dir : The directory where the output files shall be written" << std::endl
<< " -m split_method : The method to split with. Can take one of the following params:" << std::endl
<< " 'file-size' - split files by size in bytes" << std::endl
<< " 'packet-count' - split files by packet count" << std::endl
<< " 'client-ip' - split files by client IP, meaning all connections with" << std::endl
<< " the same client IP will be in the same file" << std::endl
<< " 'server-ip' - split files by server IP, meaning all connections with" << std::endl
<< " the same server IP will be in the same file" << std::endl
<< " 'server-port' - split files by server port, meaning all connections with"
<< std::endl
<< " the same server port will be in the same file" << std::endl
<< " 'client-port' - split files by client port, meaning all connections with"
<< std::endl
<< " the same client port will be in the same file" << std::endl
<< " 'ip-src-dst' - split files by IP src and dst (2-tuple), meaning all connections"
<< std::endl
<< " with the same IPs will be in the same file" << std::endl
<< " 'connection' - split files by connection (5-tuple), meaning all packets"
<< std::endl
<< " of a connection will be in the same file" << std::endl
<< " 'bpf-filter' - split file into two files: one that contains all packets"
<< std::endl
<< " matching the given BPF filter (file #0) and one that contains"
<< std::endl
<< " the rest of the packets (file #1)" << std::endl
<< " 'round-robin' - split the file in a round-robin manner - each packet to a"
<< std::endl
<< " different file" << std::endl
<< " -p split_param : The relevant parameter for the split method:" << std::endl
<< " 'method = file-size' => split_param is the max size per file (in bytes)."
<< std::endl
<< " split_param is required for this method" << std::endl
<< " 'method = packet-count' => split_param is the number of packet per file." << std::endl
<< " split_param is required for this method" << std::endl
<< " 'method = client-ip' => split_param is max number of files to open." << std::endl
<< " If not provided the default is unlimited number of files"
<< std::endl
<< " 'method = server-ip' => split_param is max number of files to open." << std::endl
<< " If not provided the default is unlimited number of files"
<< std::endl
<< " 'method = server-port' => split_param is max number of files to open." << std::endl
<< " If not provided the default is unlimited number of files"
<< std::endl
<< " 'method = ip-src-dst' => split_param is max number of files to open." << std::endl
<< " If not provided the default is unlimited number of files"
<< std::endl
<< " 'method = connection' => split_param is max number of files to open." << std::endl
<< " If not provided the default is unlimited number of files"
<< std::endl
<< " 'method = bpf-filter' => split_param is the BPF filter to match upon" << std::endl
<< " 'method = round-robin' => split_param is number of files to round-robin packets "
"between"
<< std::endl
<< " -i filter : Apply a BPF filter, meaning only filtered packets will be counted in the split"
<< std::endl
<< " -v : Displays the current version and exists" << std::endl
<< " -h : Displays this help message and exits" << 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);
}
/**
* An auxiliary method for extracting the file name without the extension from a file path,
* for example: for the input '/home/myuser/mypcap.pcap' -> return value will be 'mypcap'
*/
std::string getFileNameWithoutExtension(const std::string& path)
{
// if path is empty, return an empty string
if (path == "")
return "";
// find the last "\\" or "/" (depends on the os) - where path ends and filename starts
size_t i = path.rfind(SEPARATOR, path.length());
if (i != std::string::npos)
{
// extract filename from path
std::string fileNameWithExtension = path.substr(i + 1, path.length() - i);
// from the file name - remove the extension (the part after the ".")
i = fileNameWithExtension.rfind('.', fileNameWithExtension.length());
if (i != std::string::npos)
return fileNameWithExtension.substr(0, i);
return fileNameWithExtension;
}
// filename without a path
else
{
// from the file name - remove the extension (the part after the ".")
i = path.rfind('.', path.length());
if (i != std::string::npos)
return path.substr(0, i);
// filename doesn't have an extension
return path;
}
return ("");
}
/**
* main method of this utility
*/
int main(int argc, char* argv[])
{
pcpp::AppName::init(argc, argv);
std::string inputPcapFileName = "";
std::string outputPcapDir = "";
std::string filter = "";
std::string method = "";
char param[1000];
memset(param, 0, 1000);
bool paramWasSet = false;
int optionIndex = 0;
int opt = 0;
while ((opt = getopt_long(argc, argv, "f:o:m:p:i:vh", PcapSplitterOptions, &optionIndex)) != -1)
{
switch (opt)
{
case 0:
break;
case 'f':
inputPcapFileName = optarg;
break;
case 'o':
outputPcapDir = optarg;
break;
case 'm':
method = optarg;
break;
case 'p':
strncpy(param, optarg, 999);
paramWasSet = true;
break;
case 'i':
filter = optarg;
break;
case 'h':
printUsage();
exit(0);
case 'v':
printAppVersion();
break;
default:
printUsage();
exit(-1);
}
}
if (inputPcapFileName == "")
{
EXIT_WITH_ERROR("Input file name was not given");
}
if (outputPcapDir == "")
{
EXIT_WITH_ERROR("Output directory name was not given");
}
if (!pcpp::directoryExists(outputPcapDir))
{
EXIT_WITH_ERROR("Output directory doesn't exist");
}
if (method == "")
{
EXIT_WITH_ERROR("Split method was not given");
}
std::unique_ptr<Splitter> splitter;
// decide of the splitter to use, according to the user's choice
if (method == SPLIT_BY_FILE_SIZE)
{
uint64_t paramAsUint64 = (paramWasSet ? strtoull(param, nullptr, 10) : 0);
splitter.reset(new FileSizeSplitter(paramAsUint64));
}
else if (method == SPLIT_BY_PACKET_COUNT)
{
int paramAsInt = (paramWasSet ? atoi(param) : 0);
splitter.reset(new PacketCountSplitter(paramAsInt));
}
else if (method == SPLIT_BY_IP_CLIENT)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter.reset(new ClientIPSplitter(paramAsInt));
}
else if (method == SPLIT_BY_IP_SERVER)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter.reset(new ServerIPSplitter(paramAsInt));
}
else if (method == SPLIT_BY_SERVER_PORT)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter.reset(new ServerPortSplitter(paramAsInt));
}
else if (method == SPLIT_BY_CLIENT_PORT)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter.reset(new ClientPortSplitter(paramAsInt));
}
else if (method == SPLIT_BY_2_TUPLE)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter.reset(new TwoTupleSplitter(paramAsInt));
}
else if (method == SPLIT_BY_5_TUPLE)
{
int paramAsInt = (paramWasSet ? atoi(param) : SplitterWithMaxFiles::UNLIMITED_FILES_MAGIC_NUMBER);
splitter.reset(new FiveTupleSplitter(paramAsInt));
}
else if (method == SPLIT_BY_BPF_FILTER)
{
splitter.reset(new BpfCriteriaSplitter(std::string(param)));
}
else if (method == SPLIT_BY_ROUND_ROBIN)
{
int paramAsInt = (paramWasSet ? atoi(param) : 0);
splitter.reset(new RoundRobinSplitter(paramAsInt));
}
else
{
EXIT_WITH_ERROR("Unknown method '" << method << "'");
}
// verify splitter param is legal, otherwise return an error
std::string errorStr;
if (!splitter->isSplitterParamLegal(errorStr))
{
EXIT_WITH_ERROR(errorStr);
}
// prepare the output file format: /requested-path/original-file-name-[4-digit-number-starting-at-0000].pcap
std::string outputPcapFileName =
outputPcapDir + std::string(1, SEPARATOR) + getFileNameWithoutExtension(inputPcapFileName) + "-";
// open a pcap file for reading
std::unique_ptr<pcpp::IFileReaderDevice> reader(pcpp::IFileReaderDevice::getReader(inputPcapFileName));
bool isReaderPcapng = (dynamic_cast<pcpp::PcapNgFileReaderDevice*>(reader.get()) != nullptr);
if (reader == nullptr || !reader->open())
{
EXIT_WITH_ERROR("Error opening input pcap file");
}
// set a filter if provided
if (filter != "")
{
if (!reader->setFilter(filter))
EXIT_WITH_ERROR("Couldn't set filter '" << filter << "'");
}
std::cout << "Started..." << std::endl;
// determine output file extension
std::string outputFileExtenison = (isReaderPcapng ? ".pcapng" : ".pcap");
int packetCountSoFar = 0;
int numOfFiles = 0;
pcpp::RawPacket rawPacket;
// prepare a map of file number to IFileWriterDevice
std::unordered_map<int, std::unique_ptr<pcpp::IFileWriterDevice>> outputFiles;
// read all packets from input file, for each packet do:
while (reader->getNextPacket(rawPacket))
{
// parse the raw packet into a parsed packet
pcpp::Packet parsedPacket(&rawPacket);
std::vector<int> filesToClose;
// call the splitter to get the file number to write the current packet to
int fileNum = splitter->getFileNumber(parsedPacket, filesToClose);
// if file number is seen for the first time (meaning it's the first packet written to it)
if (outputFiles.find(fileNum) == outputFiles.end())
{
// get file name from the splitter and add the .pcap extension
std::string fileName =
splitter->getFileName(parsedPacket, outputPcapFileName, fileNum) + outputFileExtenison;
// create a new IFileWriterDevice for this file
if (isReaderPcapng)
{
// if reader is pcapng, create a pcapng writer
outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName));
}
else
{
// if reader is pcap, create a pcap writer
outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()));
}
// open the writer
if (!outputFiles[fileNum]->open())
break;
numOfFiles++;
}
// if file number exists in the map but PcapFileWriterDevice is null it means this file was open once and
// then closed. In this case we need to re-open the PcapFileWriterDevice in append mode
else if (outputFiles[fileNum] == nullptr)
{
// get file name from the splitter and add the .pcap extension
std::string fileName =
splitter->getFileName(parsedPacket, outputPcapFileName, fileNum) + outputFileExtenison;
// re-create the IFileWriterDevice object
if (isReaderPcapng)
{
// if reader is pcapng, create a pcapng writer
outputFiles[fileNum].reset(new pcpp::PcapNgFileWriterDevice(fileName));
}
else
{
// if reader is pcap, create a pcap writer
outputFiles[fileNum].reset(new pcpp::PcapFileWriterDevice(fileName, rawPacket.getLinkLayerType()));
}
// open the writer in __append__ mode
if (!outputFiles[fileNum]->open(true))
break;
}
// write the packet to the writer
outputFiles[fileNum]->writePacket(*parsedPacket.getRawPacket());
// if splitter wants us to close files - go over the file numbers and close them
for (const auto& fileId : filesToClose)
{
// check if that file number is in the map
if (outputFiles.find(fileId) != outputFiles.end())
{
// close the writer
outputFiles[fileId]->close();
// free the writer memory and put null in the map record
outputFiles[fileId].reset();
}
}
++packetCountSoFar;
}
std::cout << "Finished. Read and written " << packetCountSoFar << " packets to " << numOfFiles << " files"
<< std::endl;
// close the reader file
reader->close();
// close the writer files which are still open
for (const auto& it : outputFiles)
{
if (it.second != nullptr)
{
it.second->close();
}
}
return 0;
}