pcap_processor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. #include <pybind11/pybind11.h>
  2. namespace py = pybind11;
  3. #include "pcap_processor.h"
  4. using namespace Tins;
  5. /**
  6. * Creates a new pcap_processor object.
  7. * @param path The path where the PCAP to get analyzed is locatated.
  8. */
  9. pcap_processor::pcap_processor(std::string path, std::string extraTests, std::string resourcePath) : stats(resourcePath) {
  10. filePath = 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(const 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. if (intervals.size() == 0) {
  156. int timeIntervalsNum = 100;
  157. std::chrono::microseconds lastTimestamp = stats.getTimestampLastPacket();
  158. std::chrono::microseconds captureDuration = lastTimestamp - firstTimestamp;
  159. if(captureDuration.count()<=0){
  160. std::cerr << "ERROR: PCAP file is empty!" << std::endl;
  161. return;
  162. }
  163. timeInterval_microsec = captureDuration.count() / timeIntervalsNum;
  164. stats.setDefaultInterval(static_cast<double>(timeInterval_microsec));
  165. intervalStartTimestamp.push_back(firstTimestamp);
  166. std::chrono::duration<int, std::micro> timeInterval(timeInterval_microsec);
  167. std::chrono::microseconds barrier = timeInterval;
  168. timeIntervals.push_back(timeInterval);
  169. barriers.push_back(barrier);
  170. } else {
  171. for (auto interval: intervals) {
  172. double interval_double = interval.cast<double>();
  173. timeInterval_microsec = static_cast<long>(interval_double * 1000000);
  174. intervalStartTimestamp.push_back(firstTimestamp);
  175. std::chrono::duration<int, std::micro> timeInterval(timeInterval_microsec);
  176. std::chrono::microseconds barrier = timeInterval;
  177. timeIntervals.push_back(timeInterval);
  178. barriers.push_back(barrier);
  179. }
  180. }
  181. std::sort(timeIntervals.begin(), timeIntervals.end());
  182. std::sort(barriers.begin(), barriers.end());
  183. std::cout << std::endl;
  184. std::chrono::system_clock::time_point lastPrinted = std::chrono::system_clock::now();
  185. int barrier_count = static_cast<int>(barriers.size());
  186. // Iterate over all packets and collect statistics
  187. for (; i != sniffer.end(); i++) {
  188. currentPktTimestamp = i->timestamp();
  189. std::chrono::microseconds currentDuration = currentPktTimestamp - firstTimestamp;
  190. // For each interval
  191. // drops last interval too small
  192. for (int j = 0; j < barrier_count; j++) {
  193. if(currentDuration>barriers[j]){
  194. stats.addIntervalStat(timeIntervals[j], intervalStartTimestamp[j], currentPktTimestamp);
  195. timeIntervalCounter++;
  196. barriers[j] = barriers[j] + timeIntervals[j];
  197. intervalStartTimestamp[j] = currentPktTimestamp;
  198. }
  199. }
  200. stats.incrementPacketCount();
  201. this->process_packets(*i);
  202. // Indicate progress once every second
  203. if (std::chrono::system_clock::now() - lastPrinted >= std::chrono::seconds(1)) {
  204. int packetCount = stats.getPacketCount();
  205. std::cout << "\rInspected packets: ";
  206. std::cout << std::fixed << std::setprecision(1) << (static_cast<float>(packetCount)*100/totalPackets) << "%";
  207. std::cout << " (" << packetCount << "/" << totalPackets << ")" << std::flush;
  208. lastPrinted = std::chrono::system_clock::now();
  209. if (PyErr_CheckSignals()) throw py::error_already_set();
  210. }
  211. }
  212. std::cout << "\rInspected packets: ";
  213. std::cout << "100.0% (" << totalPackets << "/" << totalPackets << ")" << std::endl;
  214. // Save timestamp of last packet into statistics
  215. stats.setTimestampLastPacket(currentPktTimestamp);
  216. // Create the communication interval statistics from the gathered communication intervals within every extended conversation statistic
  217. stats.createCommIntervalStats();
  218. if(hasUnrecognized) {
  219. std::cout << "Unrecognized PDUs detected: Check 'unrecognized_pdus' table!" << std::endl;
  220. }
  221. }
  222. }
  223. /**
  224. * Analyzes a given packet and collects statistical information.
  225. * @param pkt The packet to get analyzed.
  226. */
  227. void pcap_processor::process_packets(const Packet &pkt) {
  228. // Layer 2: Data Link Layer ------------------------
  229. std::string macAddressSender;
  230. std::string macAddressReceiver;
  231. const PDU *pdu_l2 = pkt.pdu();
  232. uint32_t sizeCurrentPacket = pdu_l2->size();
  233. if (pdu_l2->pdu_type() == PDU::ETHERNET_II) {
  234. const EthernetII &eth = (const EthernetII &) *pdu_l2;
  235. macAddressSender = eth.src_addr().to_string();
  236. macAddressReceiver = eth.dst_addr().to_string();
  237. sizeCurrentPacket = eth.size();
  238. }
  239. stats.addPacketSize(sizeCurrentPacket);
  240. // Layer 3 - Network -------------------------------
  241. const PDU *pdu_l3 = pkt.pdu()->inner_pdu();
  242. const PDU::PDUType pdu_l3_type = pdu_l3->pdu_type();
  243. std::string ipAddressSender;
  244. std::string ipAddressReceiver;
  245. // PDU is IPv4
  246. if (pdu_l3_type == PDU::PDUType::IP) {
  247. const IP &ipLayer = (const IP &) *pdu_l3;
  248. ipAddressSender = ipLayer.src_addr().to_string();
  249. ipAddressReceiver = ipLayer.dst_addr().to_string();
  250. // IP distribution
  251. stats.addIpStat_packetSent(ipAddressSender, ipAddressReceiver, sizeCurrentPacket, pkt.timestamp());
  252. // TTL distribution
  253. stats.incrementTTLcount(ipAddressSender, ipLayer.ttl());
  254. // ToS distribution
  255. stats.incrementToScount(ipAddressSender, ipLayer.tos());
  256. // Protocol distribution
  257. stats.incrementProtocolCount(ipAddressSender, "IPv4");
  258. stats.increaseProtocolByteCount(ipAddressSender, "IPv4", sizeCurrentPacket);
  259. // Assign IP Address to MAC Address
  260. stats.assignMacAddress(ipAddressSender, macAddressSender);
  261. stats.assignMacAddress(ipAddressReceiver, macAddressReceiver);
  262. } // PDU is IPv6
  263. // FIXME: IPv6 Workaround
  264. /*else if (pdu_l3_type == PDU::PDUType::IPv6) {
  265. return;
  266. const IPv6 &ipLayer = (const IPv6 &) *pdu_l3;
  267. ipAddressSender = ipLayer.src_addr().to_string();
  268. ipAddressReceiver = ipLayer.dst_addr().to_string();
  269. // IP distribution
  270. stats.addIpStat_packetSent(ipAddressSender, ipAddressReceiver, sizeCurrentPacket, pkt.timestamp());
  271. // TTL distribution
  272. stats.incrementTTLcount(ipAddressSender, ipLayer.hop_limit());
  273. // Protocol distribution
  274. stats.incrementProtocolCount(ipAddressSender, "IPv6");
  275. stats.increaseProtocolByteCount(ipAddressSender, "IPv6", sizeCurrentPacket);
  276. // Assign IP Address to MAC Address
  277. stats.assignMacAddress(ipAddressSender, macAddressSender);
  278. stats.assignMacAddress(ipAddressReceiver, macAddressReceiver);
  279. }*/ //PDU is unrecognized
  280. else {
  281. hasUnrecognized = true;
  282. const EthernetII &eth = (const EthernetII &) *pdu_l2;
  283. Tins::Timestamp ts = pkt.timestamp();
  284. std::string timestamp_pkt = stats.getFormattedTimestamp(ts.seconds(), ts.microseconds());
  285. stats.incrementUnrecognizedPDUCount(macAddressSender, macAddressReceiver, eth.payload_type(), timestamp_pkt);
  286. }
  287. // Layer 4 - Transport -------------------------------
  288. const PDU *pdu_l4 = pdu_l3->inner_pdu();
  289. if (pdu_l4 != 0) {
  290. // Protocol distribution - layer 4
  291. PDU::PDUType p = pdu_l4->pdu_type();
  292. // Check for IPv4: payload
  293. if (pdu_l3_type == PDU::PDUType::IP) {
  294. stats.checkPayload(pdu_l4);
  295. }
  296. if (p == PDU::PDUType::TCP) {
  297. const TCP &tcpPkt = (const TCP &) *pdu_l4;
  298. // Check TCP checksum
  299. if (pdu_l3_type == PDU::PDUType::IP) {
  300. stats.checkTCPChecksum(ipAddressSender, ipAddressReceiver, tcpPkt);
  301. }
  302. stats.incrementProtocolCount(ipAddressSender, "TCP");
  303. stats.increaseProtocolByteCount(ipAddressSender, "TCP", sizeCurrentPacket);
  304. // Conversation statistics
  305. stats.addConvStat(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), pkt.timestamp());
  306. stats.addConvStatExt(ipAddressSender,tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), "TCP", pkt.timestamp());
  307. // Window Size distribution
  308. int win = tcpPkt.window();
  309. stats.incrementWinCount(ipAddressSender, win);
  310. // MSS distribution
  311. auto mssOption = tcpPkt.search_option(TCP::MSS);
  312. if (mssOption != nullptr) {
  313. auto mss_value = mssOption->to<uint16_t>();
  314. stats.incrementMSScount(ipAddressSender, mss_value);
  315. }
  316. stats.incrementPortCount(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), "TCP");
  317. stats.increasePortByteCount(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), sizeCurrentPacket, "TCP");
  318. // UDP Packet
  319. } else if (p == PDU::PDUType::UDP) {
  320. const UDP &udpPkt = (const UDP &) *pdu_l4;
  321. stats.incrementProtocolCount(ipAddressSender, "UDP");
  322. stats.increaseProtocolByteCount(ipAddressSender, "UDP", sizeCurrentPacket);
  323. stats.incrementPortCount(ipAddressSender, udpPkt.sport(), ipAddressReceiver, udpPkt.dport(), "UDP");
  324. stats.increasePortByteCount(ipAddressSender, udpPkt.sport(), ipAddressReceiver, udpPkt.dport(), sizeCurrentPacket, "UDP");
  325. stats.addConvStatExt(ipAddressSender,udpPkt.sport(), ipAddressReceiver, udpPkt.dport(), "UDP", pkt.timestamp());
  326. } else if (p == PDU::PDUType::ICMP) {
  327. stats.incrementProtocolCount(ipAddressSender, "ICMP");
  328. stats.increaseProtocolByteCount(ipAddressSender, "ICMP", sizeCurrentPacket);
  329. } else if (p == PDU::PDUType::ICMPv6) {
  330. stats.incrementProtocolCount(ipAddressSender, "ICMPv6");
  331. stats.increaseProtocolByteCount(ipAddressSender, "ICMPv6", sizeCurrentPacket);
  332. }
  333. }
  334. }
  335. /**
  336. * Writes the collected statistic data into a SQLite3 database located at database_path. Uses an existing
  337. * database or, if not present, creates a new database.
  338. * @param database_path The path to the database file, ending with .sqlite3.
  339. */
  340. void pcap_processor::write_to_database(std::string database_path, const py::list& intervals, bool del) {
  341. std::vector<std::chrono::duration<int, std::micro>> timeIntervals;
  342. for (auto interval: intervals) {
  343. double interval_double = interval.cast<double>();
  344. std::chrono::duration<int, std::micro> timeInterval(static_cast<long>(interval_double * 1000000));
  345. timeIntervals.push_back(timeInterval);
  346. }
  347. stats.writeToDatabase(database_path, timeIntervals, del);
  348. }
  349. void pcap_processor::write_new_interval_statistics(std::string database_path, const py::list& intervals) {
  350. std::vector<std::chrono::duration<int, std::micro>> timeIntervals;
  351. for (auto interval: intervals) {
  352. double interval_double = interval.cast<double>();
  353. std::chrono::duration<int, std::micro> timeInterval(static_cast<long>(interval_double * 1000000));
  354. timeIntervals.push_back(timeInterval);
  355. }
  356. stats.writeIntervalsToDatabase(database_path, timeIntervals, false);
  357. }
  358. /**
  359. * Checks whether the file with the given file path exists.
  360. * @param filePath The path to the file to check.
  361. * @return True iff the file exists, otherweise False.
  362. */
  363. bool inline pcap_processor::file_exists(const std::string &filePath) {
  364. struct stat buffer;
  365. return stat(filePath.c_str(), &buffer) == 0;
  366. }
  367. /*
  368. * Comment in if executable should be build & run
  369. * Comment out if library should be build
  370. */
  371. //int main() {
  372. // std::cout << "Starting application." << std::endl;
  373. // pcap_processor pcap = pcap_processor("/home/anonymous/Downloads/ID2T-toolkit/captures/col/capture_1.pcap", "True");
  374. //
  375. // long double t = pcap.get_timestamp_mu_sec(87);
  376. // std::cout << t << std::endl;
  377. //
  378. // time_t start, end;
  379. // time(&start);
  380. // pcap.collect_statistics();
  381. // time(&end);
  382. // double dif = difftime(end, start);
  383. // printf("Elapsed time is %.2lf seconds.", dif);
  384. // pcap.stats.writeToDatabase("/home/anonymous/Downloads/myDB.sqlite3");
  385. //
  386. // //std::string path = pcap.merge_pcaps("/tmp/tmp0okkfdx_");
  387. // //std::cout << path << std::endl;
  388. //
  389. // return 0;
  390. //}
  391. /*
  392. * Comment out if executable should be build & run
  393. * Comment in if library should be build
  394. */
  395. PYBIND11_MODULE (libpcapreader, m) {
  396. py::class_<pcap_processor>(m, "pcap_processor")
  397. .def(py::init<std::string, std::string, std::string>())
  398. .def("merge_pcaps", &pcap_processor::merge_pcaps)
  399. .def("collect_statistics", &pcap_processor::collect_statistics)
  400. .def("get_timestamp_mu_sec", &pcap_processor::get_timestamp_mu_sec)
  401. .def("write_to_database", &pcap_processor::write_to_database)
  402. .def("write_new_interval_statistics", &pcap_processor::write_new_interval_statistics)
  403. .def_static("get_db_version", &pcap_processor::get_db_version);
  404. }