pcap_processor.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. #include "pcap_processor.h"
  2. using namespace Tins;
  3. /**
  4. * Creates a new pcap_processor object.
  5. * @param path The path where the PCAP to get analyzed is locatated.
  6. */
  7. pcap_processor::pcap_processor(std::string path, std::string extraTests, std::string resource_path, std::string database_path) : stats(resource_path) {
  8. filePath = path;
  9. resourcePath = resource_path;
  10. databasePath = database_path;
  11. hasUnrecognized = false;
  12. if(extraTests == "True")
  13. stats.setDoExtraTests(true);
  14. else stats.setDoExtraTests(false);
  15. }
  16. /**
  17. * Iterates over all packets, starting by packet no. 1, and stops if
  18. * after_packet_number equals the current packet number.
  19. * @param after_packet_number The packet position in the PCAP file whose timestamp is wanted.
  20. * @return The timestamp of the last processed packet plus 1 microsecond.
  21. */
  22. long double pcap_processor::get_timestamp_mu_sec(const int after_packet_number) {
  23. if (file_exists(filePath)) {
  24. FileSniffer sniffer(filePath);
  25. int current_packet = 1;
  26. for (SnifferIterator i = sniffer.begin(); i != sniffer.end(); i++) {
  27. if (after_packet_number == current_packet) {
  28. const Timestamp &ts = i->timestamp();
  29. return (long double) ((ts.seconds() * 1000000) + ts.microseconds() + 1);
  30. }
  31. current_packet++;
  32. }
  33. }
  34. return -1.0;
  35. }
  36. /**
  37. * Merges two PCAP files, given by paths in filePath and parameter pcap_path.
  38. * @param pcap_path The path to the file which should be merged with the loaded PCAP file.
  39. * @return The string containing the file path to the merged PCAP file.
  40. */
  41. std::string pcap_processor::merge_pcaps(const std::string pcap_path) {
  42. // Build new filename with timestamp
  43. // Build timestamp
  44. time_t curr_time = time(0);
  45. char buff[1024];
  46. struct tm *now = localtime(&curr_time);
  47. strftime(buff, sizeof(buff), "%Y%m%d-%H%M%S", now);
  48. std::string tstmp(buff);
  49. // Replace filename with 'timestamp_filename'
  50. std::string new_filepath = filePath;
  51. const std::string &newExt = "_" + tstmp + ".pcap";
  52. std::string::size_type h = new_filepath.rfind('.', new_filepath.length());
  53. if ((filePath.length() + newExt.length()) < 250) {
  54. if (h != std::string::npos) {
  55. new_filepath.replace(h, newExt.length(), newExt);
  56. } else {
  57. new_filepath.append(newExt);
  58. }
  59. }
  60. else {
  61. new_filepath = (new_filepath.substr(0, new_filepath.find('_'))).append(newExt);
  62. }
  63. FileSniffer sniffer_base(filePath);
  64. SnifferIterator iterator_base = sniffer_base.begin();
  65. FileSniffer sniffer_attack(pcap_path);
  66. SnifferIterator iterator_attack = sniffer_attack.begin();
  67. PacketWriter writer(new_filepath, PacketWriter::ETH2);
  68. bool all_attack_pkts_processed = false;
  69. // Go through base PCAP and merge packets by timestamp
  70. for (; iterator_base != sniffer_base.end();) {
  71. auto tstmp_base = (iterator_base->timestamp().seconds()) + (iterator_base->timestamp().microseconds()*1e-6);
  72. auto tstmp_attack = (iterator_attack->timestamp().seconds()) + (iterator_attack->timestamp().microseconds()*1e-6);
  73. if (!all_attack_pkts_processed && tstmp_attack <= tstmp_base) {
  74. try {
  75. writer.write(*iterator_attack);
  76. } catch (serialization_error&) {
  77. std::cerr << std::setprecision(15) << "Could not serialize attack packet with timestamp " << tstmp_attack << std::endl;
  78. }
  79. iterator_attack++;
  80. if (iterator_attack == sniffer_attack.end())
  81. all_attack_pkts_processed = true;
  82. } else {
  83. try {
  84. writer.write(*iterator_base);
  85. } catch (serialization_error&) {
  86. std::cerr << "Could not serialize base packet with timestamp " << std::setprecision(15) << tstmp_base << std::endl;
  87. }
  88. iterator_base++;
  89. }
  90. }
  91. // This may happen if the base PCAP is smaller than the attack PCAP
  92. // In this case append the remaining packets of the attack PCAP
  93. for (; iterator_attack != sniffer_attack.end(); iterator_attack++) {
  94. try {
  95. writer.write(*iterator_attack);
  96. } catch (serialization_error&) {
  97. auto tstmp_attack = (iterator_attack->timestamp().seconds()) + (iterator_attack->timestamp().microseconds()*1e-6);
  98. std::cerr << "Could not serialize attack packet with timestamp " << std::setprecision(15) << tstmp_attack << std::endl;
  99. }
  100. }
  101. return new_filepath;
  102. }
  103. bool pcap_processor::read_pcap_info(const std::string &filePath, std::size_t &totalPakets) {
  104. // libtins has a lot of overhead when just iterating through, so we use libpcap directly
  105. char errbuf[PCAP_ERRBUF_SIZE];
  106. pcap_t *pcap_handle = pcap_open_offline(filePath.c_str(), errbuf);
  107. if (pcap_handle == nullptr) {
  108. std::cerr << "ERROR: Could not open PCAP '" << filePath << "': " << errbuf << std::endl;
  109. return false;
  110. }
  111. const u_char *packet;
  112. pcap_pkthdr header;
  113. packet = pcap_next(pcap_handle, &header);
  114. if (packet == nullptr)
  115. {
  116. std::cerr << "ERROR: PCAP file is empty!" << std::endl;
  117. pcap_close(pcap_handle);
  118. return false;
  119. }
  120. // Extract first timestamp
  121. stats.setTimestampFirstPacket(Tins::Timestamp(header.ts));
  122. totalPakets = 0;
  123. timeval lv;
  124. while (packet != nullptr) {
  125. totalPakets++;
  126. // Extract last timestamp
  127. lv = header.ts;
  128. packet = pcap_next(pcap_handle, &header);
  129. }
  130. stats.setTimestampLastPacket(Tins::Timestamp(lv));
  131. pcap_close(pcap_handle);
  132. return true;
  133. }
  134. /**
  135. * Collect statistics of the loaded PCAP file. Calls for each packet the method process_packets.
  136. * param: user specified interval in seconds
  137. */
  138. void pcap_processor::collect_statistics(py::list& intervals) {
  139. // Only process PCAP if file exists
  140. if (file_exists(filePath)) {
  141. std::cout << "Loading pcap..." << std::endl;
  142. FileSniffer sniffer(filePath);
  143. SnifferIterator i = sniffer.begin();
  144. std::chrono::microseconds currentPktTimestamp;
  145. // Read PCAP file info
  146. std::size_t totalPackets = 0;
  147. if (!read_pcap_info(filePath, totalPackets)) return;
  148. // choose a suitable time interval
  149. int timeIntervalCounter = 1;
  150. long timeInterval_microsec = 0;
  151. std::vector<std::chrono::microseconds> intervalStartTimestamp;
  152. std::chrono::microseconds firstTimestamp = stats.getTimestampFirstPacket();
  153. std::vector<std::chrono::duration<int, std::micro>> timeIntervals;
  154. std::vector<std::chrono::microseconds> barriers;
  155. std::vector<double> intervals_vec;
  156. for (auto interval: intervals) {
  157. intervals_vec.push_back(interval.cast<double>());
  158. }
  159. if (intervals_vec.size() == 0 || intervals_vec[0] == 0) {
  160. int timeIntervalsNum = 100;
  161. std::chrono::microseconds lastTimestamp = stats.getTimestampLastPacket();
  162. std::chrono::microseconds captureDuration = lastTimestamp - firstTimestamp;
  163. if(captureDuration.count()<=0){
  164. std::cerr << "ERROR: PCAP file is empty!" << std::endl;
  165. return;
  166. }
  167. timeInterval_microsec = captureDuration.count() / timeIntervalsNum;
  168. stats.setDefaultInterval(static_cast<int>(timeInterval_microsec));
  169. intervalStartTimestamp.push_back(firstTimestamp);
  170. std::chrono::duration<int, std::micro> timeInterval(timeInterval_microsec);
  171. std::chrono::microseconds barrier = timeInterval;
  172. timeIntervals.push_back(timeInterval);
  173. barriers.push_back(barrier);
  174. } else {
  175. if (stats.getDoExtraTests()) {
  176. statistics_db stats_db(databasePath, resourcePath);
  177. stats_db.getNoneExtraTestsInveralStats(intervals_vec);
  178. }
  179. for (auto interval: intervals_vec) {
  180. timeInterval_microsec = static_cast<long>(interval * 1000000);
  181. intervalStartTimestamp.push_back(firstTimestamp);
  182. std::chrono::duration<int, std::micro> timeInterval(timeInterval_microsec);
  183. std::chrono::microseconds barrier = timeInterval;
  184. timeIntervals.push_back(timeInterval);
  185. barriers.push_back(barrier);
  186. }
  187. }
  188. std::sort(timeIntervals.begin(), timeIntervals.end());
  189. std::sort(barriers.begin(), barriers.end());
  190. std::cout << std::endl;
  191. std::chrono::system_clock::time_point lastPrinted = std::chrono::system_clock::now();
  192. int barrier_count = static_cast<int>(barriers.size());
  193. // Iterate over all packets and collect statistics
  194. for (; i != sniffer.end(); i++) {
  195. currentPktTimestamp = i->timestamp();
  196. std::chrono::microseconds currentDuration = currentPktTimestamp - firstTimestamp;
  197. // For each interval
  198. // drops last interval too small
  199. for (int j = 0; j < barrier_count; j++) {
  200. if(currentDuration>barriers[j]){
  201. stats.addIntervalStat(timeIntervals[j], intervalStartTimestamp[j], currentPktTimestamp);
  202. timeIntervalCounter++;
  203. barriers[j] = barriers[j] + timeIntervals[j];
  204. intervalStartTimestamp[j] = currentPktTimestamp;
  205. }
  206. }
  207. stats.incrementPacketCount();
  208. this->process_packets(*i);
  209. // Indicate progress once every second
  210. if (std::chrono::system_clock::now() - lastPrinted >= std::chrono::seconds(1)) {
  211. int packetCount = stats.getPacketCount();
  212. std::cout << "\rInspected packets: ";
  213. std::cout << std::fixed << std::setprecision(1) << (static_cast<float>(packetCount)*100/totalPackets) << "%";
  214. std::cout << " (" << packetCount << "/" << totalPackets << ")" << std::flush;
  215. lastPrinted = std::chrono::system_clock::now();
  216. if (PyErr_CheckSignals()) throw py::error_already_set();
  217. }
  218. }
  219. std::cout << "\rInspected packets: ";
  220. std::cout << "100.0% (" << totalPackets << "/" << totalPackets << ")" << std::endl;
  221. // Save timestamp of last packet into statistics
  222. stats.setTimestampLastPacket(currentPktTimestamp);
  223. // Create the communication interval statistics from the gathered communication intervals within every extended conversation statistic
  224. stats.createCommIntervalStats();
  225. if(hasUnrecognized) {
  226. std::cout << "Unrecognized PDUs detected: Check 'unrecognized_pdus' table!" << std::endl;
  227. }
  228. }
  229. }
  230. /**
  231. * Analyzes a given packet and collects statistical information.
  232. * @param pkt The packet to get analyzed.
  233. */
  234. void pcap_processor::process_packets(const Packet &pkt) {
  235. // Layer 2: Data Link Layer ------------------------
  236. std::string macAddressSender;
  237. std::string macAddressReceiver;
  238. const PDU *pdu_l2 = pkt.pdu();
  239. uint32_t sizeCurrentPacket = pdu_l2->size();
  240. if (pdu_l2->pdu_type() == PDU::ETHERNET_II) {
  241. const EthernetII &eth = (const EthernetII &) *pdu_l2;
  242. macAddressSender = eth.src_addr().to_string();
  243. macAddressReceiver = eth.dst_addr().to_string();
  244. sizeCurrentPacket = eth.size();
  245. }
  246. stats.addPacketSize(sizeCurrentPacket);
  247. // Layer 3 - Network -------------------------------
  248. const PDU *pdu_l3 = pkt.pdu()->inner_pdu();
  249. const PDU::PDUType pdu_l3_type = pdu_l3->pdu_type();
  250. std::string ipAddressSender;
  251. std::string ipAddressReceiver;
  252. // PDU is IPv4
  253. if (pdu_l3_type == PDU::PDUType::IP) {
  254. const IP &ipLayer = (const IP &) *pdu_l3;
  255. ipAddressSender = ipLayer.src_addr().to_string();
  256. ipAddressReceiver = ipLayer.dst_addr().to_string();
  257. // IP distribution
  258. stats.addIpStat_packetSent(ipAddressSender, ipAddressReceiver, sizeCurrentPacket, pkt.timestamp());
  259. // TTL distribution
  260. stats.incrementTTLcount(ipAddressSender, ipLayer.ttl());
  261. // ToS distribution
  262. stats.incrementToScount(ipAddressSender, ipLayer.tos());
  263. // Protocol distribution
  264. stats.incrementProtocolCount(ipAddressSender, "IPv4");
  265. stats.increaseProtocolByteCount(ipAddressSender, "IPv4", sizeCurrentPacket);
  266. // Assign IP Address to MAC Address
  267. stats.assignMacAddress(ipAddressSender, macAddressSender);
  268. stats.assignMacAddress(ipAddressReceiver, macAddressReceiver);
  269. } // PDU is IPv6
  270. // FIXME: IPv6 Workaround
  271. /*else if (pdu_l3_type == PDU::PDUType::IPv6) {
  272. return;
  273. const IPv6 &ipLayer = (const IPv6 &) *pdu_l3;
  274. ipAddressSender = ipLayer.src_addr().to_string();
  275. ipAddressReceiver = ipLayer.dst_addr().to_string();
  276. // IP distribution
  277. stats.addIpStat_packetSent(ipAddressSender, ipAddressReceiver, sizeCurrentPacket, pkt.timestamp());
  278. // TTL distribution
  279. stats.incrementTTLcount(ipAddressSender, ipLayer.hop_limit());
  280. // Protocol distribution
  281. stats.incrementProtocolCount(ipAddressSender, "IPv6");
  282. stats.increaseProtocolByteCount(ipAddressSender, "IPv6", sizeCurrentPacket);
  283. // Assign IP Address to MAC Address
  284. stats.assignMacAddress(ipAddressSender, macAddressSender);
  285. stats.assignMacAddress(ipAddressReceiver, macAddressReceiver);
  286. }*/ //PDU is unrecognized
  287. else {
  288. hasUnrecognized = true;
  289. const EthernetII &eth = (const EthernetII &) *pdu_l2;
  290. Tins::Timestamp ts = pkt.timestamp();
  291. std::string timestamp_pkt = stats.getFormattedTimestamp(ts.seconds(), ts.microseconds());
  292. stats.incrementUnrecognizedPDUCount(macAddressSender, macAddressReceiver, eth.payload_type(), timestamp_pkt);
  293. }
  294. // Layer 4 - Transport -------------------------------
  295. const PDU *pdu_l4 = pdu_l3->inner_pdu();
  296. if (pdu_l4 != 0) {
  297. // Protocol distribution - layer 4
  298. PDU::PDUType p = pdu_l4->pdu_type();
  299. // Check for IPv4: payload
  300. if (pdu_l3_type == PDU::PDUType::IP) {
  301. stats.checkPayload(pdu_l4);
  302. }
  303. if (p == PDU::PDUType::TCP) {
  304. const TCP &tcpPkt = (const TCP &) *pdu_l4;
  305. // Check TCP checksum
  306. if (pdu_l3_type == PDU::PDUType::IP) {
  307. stats.checkTCPChecksum(ipAddressSender, ipAddressReceiver, tcpPkt);
  308. }
  309. stats.incrementProtocolCount(ipAddressSender, "TCP");
  310. stats.increaseProtocolByteCount(ipAddressSender, "TCP", sizeCurrentPacket);
  311. // Conversation statistics
  312. stats.addConvStat(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), pkt.timestamp());
  313. stats.addConvStatExt(ipAddressSender,tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), "TCP", pkt.timestamp());
  314. // Window Size distribution
  315. int win = tcpPkt.window();
  316. stats.incrementWinCount(ipAddressSender, win);
  317. // MSS distribution
  318. auto mssOption = tcpPkt.search_option(TCP::MSS);
  319. if (mssOption != nullptr) {
  320. auto mss_value = mssOption->to<uint16_t>();
  321. stats.incrementMSScount(ipAddressSender, mss_value);
  322. }
  323. stats.incrementPortCount(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), "TCP");
  324. stats.increasePortByteCount(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), sizeCurrentPacket, "TCP");
  325. // UDP Packet
  326. } else if (p == PDU::PDUType::UDP) {
  327. const UDP &udpPkt = (const UDP &) *pdu_l4;
  328. stats.incrementProtocolCount(ipAddressSender, "UDP");
  329. stats.increaseProtocolByteCount(ipAddressSender, "UDP", sizeCurrentPacket);
  330. stats.incrementPortCount(ipAddressSender, udpPkt.sport(), ipAddressReceiver, udpPkt.dport(), "UDP");
  331. stats.increasePortByteCount(ipAddressSender, udpPkt.sport(), ipAddressReceiver, udpPkt.dport(), sizeCurrentPacket, "UDP");
  332. stats.addConvStatExt(ipAddressSender,udpPkt.sport(), ipAddressReceiver, udpPkt.dport(), "UDP", pkt.timestamp());
  333. } else if (p == PDU::PDUType::ICMP) {
  334. stats.incrementProtocolCount(ipAddressSender, "ICMP");
  335. stats.increaseProtocolByteCount(ipAddressSender, "ICMP", sizeCurrentPacket);
  336. } else if (p == PDU::PDUType::ICMPv6) {
  337. stats.incrementProtocolCount(ipAddressSender, "ICMPv6");
  338. stats.increaseProtocolByteCount(ipAddressSender, "ICMPv6", sizeCurrentPacket);
  339. }
  340. }
  341. }
  342. /**
  343. * Writes the collected statistic data into a SQLite3 database located at database_path. Uses an existing
  344. * database or, if not present, creates a new database.
  345. * @param database_path The path to the database file, ending with .sqlite3.
  346. */
  347. void pcap_processor::write_to_database(std::string database_path, const py::list& intervals, bool del) {
  348. std::vector<std::chrono::duration<int, std::micro>> timeIntervals;
  349. std::vector<double> intervals_vec;
  350. for (auto interval: intervals) {
  351. intervals_vec.push_back(interval.cast<double>());
  352. }
  353. if (stats.getDoExtraTests()) {
  354. statistics_db stats_db(databasePath, resourcePath);
  355. stats_db.getNoneExtraTestsInveralStats(intervals_vec);
  356. }
  357. for (auto interval: intervals_vec) {
  358. std::chrono::duration<int, std::micro> timeInterval(static_cast<long>(interval * 1000000));
  359. timeIntervals.push_back(timeInterval);
  360. }
  361. stats.writeToDatabase(database_path, timeIntervals, del);
  362. }
  363. void pcap_processor::write_new_interval_statistics(std::string database_path, const py::list& intervals) {
  364. std::vector<std::chrono::duration<int, std::micro>> timeIntervals;
  365. std::vector<double> intervals_vec;
  366. for (auto interval: intervals) {
  367. intervals_vec.push_back(interval.cast<double>());
  368. }
  369. if (stats.getDoExtraTests()) {
  370. statistics_db stats_db(databasePath, resourcePath);
  371. stats_db.getNoneExtraTestsInveralStats(intervals_vec);
  372. }
  373. for (auto interval: intervals_vec) {
  374. std::chrono::duration<int, std::micro> timeInterval(static_cast<long>(interval * 1000000));
  375. timeIntervals.push_back(timeInterval);
  376. }
  377. stats.writeIntervalsToDatabase(database_path, timeIntervals, false);
  378. }
  379. /**
  380. * Checks whether the file with the given file path exists.
  381. * @param filePath The path to the file to check.
  382. * @return True iff the file exists, otherweise False.
  383. */
  384. bool inline pcap_processor::file_exists(const std::string &filePath) {
  385. struct stat buffer;
  386. return stat(filePath.c_str(), &buffer) == 0;
  387. }
  388. /*
  389. * Comment in if executable should be build & run
  390. * Comment out if library should be build
  391. */
  392. //int main() {
  393. // std::cout << "Starting application." << std::endl;
  394. // pcap_processor pcap = pcap_processor("/home/anonymous/Downloads/ID2T-toolkit/captures/col/capture_1.pcap", "True");
  395. //
  396. // long double t = pcap.get_timestamp_mu_sec(87);
  397. // std::cout << t << std::endl;
  398. //
  399. // time_t start, end;
  400. // time(&start);
  401. // pcap.collect_statistics();
  402. // time(&end);
  403. // double dif = difftime(end, start);
  404. // printf("Elapsed time is %.2lf seconds.", dif);
  405. // pcap.stats.writeToDatabase("/home/anonymous/Downloads/myDB.sqlite3");
  406. //
  407. // //std::string path = pcap.merge_pcaps("/tmp/tmp0okkfdx_");
  408. // //std::cout << path << std::endl;
  409. //
  410. // return 0;
  411. //}
  412. /*
  413. * Comment out if executable should be build & run
  414. * Comment in if library should be build
  415. */
  416. PYBIND11_MODULE (libpcapreader, m) {
  417. py::class_<pcap_processor>(m, "pcap_processor")
  418. .def(py::init<std::string, std::string, std::string, std::string>())
  419. .def("merge_pcaps", &pcap_processor::merge_pcaps)
  420. .def("collect_statistics", &pcap_processor::collect_statistics)
  421. .def("get_timestamp_mu_sec", &pcap_processor::get_timestamp_mu_sec)
  422. .def("write_to_database", &pcap_processor::write_to_database)
  423. .def("write_new_interval_statistics", &pcap_processor::write_new_interval_statistics)
  424. .def_static("get_db_version", &pcap_processor::get_db_version);
  425. }