pcap_processor.cpp 17 KB

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