pcap_processor.cpp 17 KB

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