pcap_processor.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. if(extraTests == "True")
  10. stats.setDoExtraTests(true);
  11. else stats.setDoExtraTests(false);;
  12. }
  13. /**
  14. * Iterates over all packets, starting by packet no. 1, and stops if
  15. * after_packet_number equals the current packet number.
  16. * @param after_packet_number The packet position in the PCAP file whose timestamp is wanted.
  17. * @return The timestamp of the last processed packet plus 1 microsecond.
  18. */
  19. long double pcap_processor::get_timestamp_mu_sec(const int after_packet_number) {
  20. if (file_exists(filePath)) {
  21. FileSniffer sniffer(filePath);
  22. int current_packet = 1;
  23. for (SnifferIterator i = sniffer.begin(); i != sniffer.end(); i++) {
  24. if (after_packet_number == current_packet) {
  25. const Timestamp &ts = i->timestamp();
  26. return (long double) ((ts.seconds() * 1000000) + ts.microseconds() + 1);
  27. }
  28. current_packet++;
  29. }
  30. }
  31. return -1.0;
  32. }
  33. /**
  34. * Merges two PCAP files, given by paths in filePath and parameter pcap_path.
  35. * @param pcap_path The path to the file which should be merged with the loaded PCAP file.
  36. * @return The string containing the file path to the merged PCAP file.
  37. */
  38. std::string pcap_processor::merge_pcaps(const std::string pcap_path) {
  39. // Build new filename with timestamp
  40. // Build timestamp
  41. time_t curr_time = time(0);
  42. char buff[1024];
  43. struct tm *now = localtime(&curr_time);
  44. strftime(buff, sizeof(buff), "%Y%m%d-%H%M%S", now);
  45. std::string tstmp(buff);
  46. // Replace filename with 'timestamp_filename'
  47. std::string new_filepath = filePath;
  48. const std::string &newExt = "_" + tstmp + ".pcap";
  49. std::string::size_type h = new_filepath.rfind('.', new_filepath.length());
  50. if (h != std::string::npos) {
  51. new_filepath.replace(h, newExt.length(), newExt);
  52. } else {
  53. new_filepath.append(newExt);
  54. }
  55. FileSniffer sniffer_base(filePath);
  56. SnifferIterator iterator_base = sniffer_base.begin();
  57. FileSniffer sniffer_attack(pcap_path);
  58. SnifferIterator iterator_attack = sniffer_attack.begin();
  59. PacketWriter writer(new_filepath, PacketWriter::ETH2);
  60. bool all_attack_pkts_processed = false;
  61. // Go through base PCAP and merge packets by timestamp
  62. for (; iterator_base != sniffer_base.end();) {
  63. auto tstmp_base = (iterator_base->timestamp().seconds()) + (iterator_base->timestamp().microseconds()*1e-6);
  64. auto tstmp_attack = (iterator_attack->timestamp().seconds()) + (iterator_attack->timestamp().microseconds()*1e-6);
  65. if (!all_attack_pkts_processed && tstmp_attack <= tstmp_base) {
  66. try {
  67. writer.write(*iterator_attack);
  68. } catch (serialization_error) {
  69. std::cout << std::setprecision(15) << "Could not serialize attack packet with timestamp " << tstmp_attack << std::endl;
  70. }
  71. iterator_attack++;
  72. if (iterator_attack == sniffer_attack.end())
  73. all_attack_pkts_processed = true;
  74. } else {
  75. try {
  76. writer.write(*iterator_base);
  77. } catch (serialization_error) {
  78. std::cout << "Could not serialize base packet with timestamp " << std::setprecision(15) << tstmp_attack << std::endl;
  79. }
  80. iterator_base++;
  81. }
  82. }
  83. // This may happen if the base PCAP is smaller than the attack PCAP
  84. // In this case append the remaining packets of the attack PCAP
  85. for (; iterator_attack != sniffer_attack.end(); iterator_attack++) {
  86. try {
  87. writer.write(*iterator_attack);
  88. } catch (serialization_error) {
  89. auto tstmp_attack = (iterator_attack->timestamp().seconds()) + (iterator_attack->timestamp().microseconds()*1e-6);
  90. std::cout << "Could not serialize attack packet with timestamp " << std::setprecision(15) << tstmp_attack << std::endl;
  91. }
  92. }
  93. return new_filepath;
  94. }
  95. /**
  96. * Collect statistics of the loaded PCAP file. Calls for each packet the method process_packets.
  97. */
  98. void pcap_processor::collect_statistics() {
  99. // Only process PCAP if file exists
  100. if (file_exists(filePath)) {
  101. std::cout << "Loading pcap..." << std::endl;
  102. FileSniffer sniffer(filePath);
  103. FileSniffer snifferOverview(filePath);
  104. SnifferIterator i = sniffer.begin();
  105. Tins::Timestamp lastProcessedPacket;
  106. // Save timestamp of first packet
  107. stats.setTimestampFirstPacket(i->timestamp());
  108. int timeIntervalCounter = 1;
  109. int timeIntervalsNum = 100;
  110. std::chrono::microseconds intervalStartTimestamp = stats.getTimestampFirstPacket();
  111. std::chrono::microseconds firstTimestamp = stats.getTimestampFirstPacket();
  112. // An empty loop to know the capture duration, then choose a suitable time interval
  113. SnifferIterator lastpkt;
  114. for (SnifferIterator j = snifferOverview.begin(); j != snifferOverview.end(); snifferIteratorIncrement(j)) {lastpkt = j;}
  115. std::chrono::microseconds lastTimestamp = lastpkt->timestamp();
  116. std::chrono::microseconds captureDuration = lastTimestamp - firstTimestamp;
  117. if(captureDuration.count()<=0){
  118. std::cout<<"ERROR: PCAP file is empty!"<<"\n";
  119. return;
  120. }
  121. long timeInterval_microsec = captureDuration.count() / timeIntervalsNum;
  122. std::chrono::duration<int, std::micro> timeInterval(timeInterval_microsec);
  123. std::chrono::microseconds barrier = timeInterval;
  124. // Iterate over all packets and collect statistics
  125. for (; i != sniffer.end(); i++) {
  126. std::chrono::microseconds lastPktTimestamp = i->timestamp();
  127. std::chrono::microseconds currentCaptureDuration = lastPktTimestamp - firstTimestamp;
  128. // For each interval
  129. if(currentCaptureDuration>barrier){
  130. stats.addIntervalStat(timeInterval, intervalStartTimestamp, lastPktTimestamp);
  131. timeIntervalCounter++;
  132. barrier = barrier+timeInterval;
  133. intervalStartTimestamp = lastPktTimestamp;
  134. }
  135. stats.incrementPacketCount();
  136. this->process_packets(*i);
  137. lastProcessedPacket = i->timestamp();
  138. }
  139. // Save timestamp of last packet into statistics
  140. stats.setTimestampLastPacket(lastProcessedPacket);
  141. }
  142. }
  143. /**
  144. * Analyzes a given packet and collects statistical information.
  145. * @param pkt The packet to get analyzed.
  146. */
  147. void pcap_processor::process_packets(const Packet &pkt) {
  148. // Layer 2: Data Link Layer ------------------------
  149. std::string macAddressSender = "";
  150. std::string macAddressReceiver = "";
  151. const PDU *pdu_l2 = pkt.pdu();
  152. uint32_t sizeCurrentPacket = pdu_l2->size();
  153. if (pdu_l2->pdu_type() == PDU::ETHERNET_II) {
  154. EthernetII eth = (const EthernetII &) *pdu_l2;
  155. macAddressSender = eth.src_addr().to_string();
  156. macAddressReceiver = eth.dst_addr().to_string();
  157. sizeCurrentPacket = eth.size();
  158. }
  159. stats.addPacketSize(sizeCurrentPacket);
  160. // Layer 3 - Network -------------------------------
  161. const PDU *pdu_l3 = pkt.pdu()->inner_pdu();
  162. const PDU::PDUType pdu_l3_type = pdu_l3->pdu_type();
  163. std::string ipAddressSender;
  164. std::string ipAddressReceiver;
  165. // PDU is IPv4
  166. if (pdu_l3_type == PDU::PDUType::IP) {
  167. const IP &ipLayer = (const IP &) *pdu_l3;
  168. ipAddressSender = ipLayer.src_addr().to_string();
  169. ipAddressReceiver = ipLayer.dst_addr().to_string();
  170. // IP distribution
  171. stats.addIpStat_packetSent(filePath, ipAddressSender, ipLayer.dst_addr().to_string(), sizeCurrentPacket, pkt.timestamp());
  172. // TTL distribution
  173. stats.incrementTTLcount(ipAddressSender, ipLayer.ttl());
  174. // ToS distribution
  175. stats.incrementToScount(ipAddressSender, ipLayer.tos());
  176. // Protocol distribution
  177. stats.incrementProtocolCount(ipAddressSender, "IPv4");
  178. // Assign IP Address to MAC Address
  179. stats.assignMacAddress(ipAddressSender, macAddressSender);
  180. stats.assignMacAddress(ipAddressReceiver, macAddressReceiver);
  181. } // PDU is IPv6
  182. else if (pdu_l3_type == PDU::PDUType::IPv6) {
  183. const IPv6 &ipLayer = (const IPv6 &) *pdu_l3;
  184. ipAddressSender = ipLayer.src_addr().to_string();
  185. ipAddressReceiver = ipLayer.dst_addr().to_string();
  186. // IP distribution
  187. stats.addIpStat_packetSent(filePath, ipAddressSender, ipLayer.dst_addr().to_string(), sizeCurrentPacket, pkt.timestamp());
  188. // TTL distribution
  189. stats.incrementTTLcount(ipAddressSender, ipLayer.hop_limit());
  190. // Protocol distribution
  191. stats.incrementProtocolCount(ipAddressSender, "IPv6");
  192. // Assign IP Address to MAC Address
  193. stats.assignMacAddress(ipAddressSender, macAddressSender);
  194. stats.assignMacAddress(ipAddressReceiver, macAddressReceiver);
  195. } else {
  196. std::cout << "Unknown PDU Type on L3: " << pdu_l3_type << std::endl;
  197. }
  198. // Layer 4 - Transport -------------------------------
  199. const PDU *pdu_l4 = pdu_l3->inner_pdu();
  200. if (pdu_l4 != 0) {
  201. // Protocol distribution - layer 4
  202. PDU::PDUType p = pdu_l4->pdu_type();
  203. // Check for IPv4: payload
  204. if (pdu_l3_type == PDU::PDUType::IP) {
  205. stats.checkPayload(pdu_l4);
  206. }
  207. if (p == PDU::PDUType::TCP) {
  208. TCP tcpPkt = (const TCP &) *pdu_l4;
  209. // Check TCP checksum
  210. if (pdu_l3_type == PDU::PDUType::IP) {
  211. stats.checkTCPChecksum(ipAddressSender, ipAddressReceiver, tcpPkt);
  212. }
  213. stats.incrementProtocolCount(ipAddressSender, "TCP");
  214. // Conversation statistics
  215. stats.addConvStat(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport(), pkt.timestamp());
  216. // Window Size distribution
  217. int win = tcpPkt.window();
  218. stats.incrementWinCount(ipAddressSender, win);
  219. try {
  220. int val = tcpPkt.mss();
  221. // MSS distribution
  222. stats.incrementMSScount(ipAddressSender, val);
  223. } catch (Tins::option_not_found) {
  224. // Ignore MSS if option not set
  225. }
  226. stats.incrementPortCount(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport());
  227. // UDP Packet
  228. } else if (p == PDU::PDUType::UDP) {
  229. const UDP udpPkt = (const UDP &) *pdu_l4;
  230. stats.incrementProtocolCount(ipAddressSender, "UDP");
  231. stats.incrementPortCount(ipAddressSender, udpPkt.sport(), ipAddressReceiver, udpPkt.dport());
  232. } else if (p == PDU::PDUType::ICMP) {
  233. stats.incrementProtocolCount(ipAddressSender, "ICMP");
  234. } else if (p == PDU::PDUType::ICMPv6) {
  235. stats.incrementProtocolCount(ipAddressSender, "ICMPv6");
  236. }
  237. }
  238. }
  239. /**
  240. * Writes the collected statistic data into a SQLite3 database located at database_path. Uses an existing
  241. * database or, if not present, creates a new database.
  242. * @param database_path The path to the database file, ending with .sqlite3.
  243. */
  244. void pcap_processor::write_to_database(std::string database_path) {
  245. stats.writeToDatabase(database_path);
  246. }
  247. /**
  248. * Checks whether the file with the given file path exists.
  249. * @param filePath The path to the file to check.
  250. * @return True iff the file exists, otherweise False.
  251. */
  252. bool inline pcap_processor::file_exists(const std::string &filePath) {
  253. struct stat buffer;
  254. return stat(filePath.c_str(), &buffer) == 0;
  255. }
  256. /*
  257. * Comment in if executable should be build & run
  258. * Comment out if library should be build
  259. */
  260. //int main() {
  261. // std::cout << "Starting application." << std::endl;
  262. // pcap_processor pcap = pcap_processor("/home/anonymous/Downloads/ID2T-toolkit/captures/col/capture_3.pcap", "False");
  263. //
  264. // long double t = pcap.get_timestamp_mu_sec(87);
  265. // std::cout << t << std::endl;
  266. //
  267. // time_t start, end;
  268. // time(&start);
  269. // pcap.collect_statistics();
  270. // time(&end);
  271. // double dif = difftime(end, start);
  272. // printf("Elapsed time is %.2lf seconds.", dif);
  273. // pcap.stats.writeToDatabase("/home/anonymous/Downloads/myDB.sqlite3");
  274. //
  275. // //std::string path = pcap.merge_pcaps("/tmp/tmp0okkfdx_");
  276. // //std::cout << path << std::endl;
  277. //
  278. // return 0;
  279. //}
  280. /*
  281. * Comment out if executable should be build & run
  282. * Comment in if library should be build
  283. */
  284. #include <boost/python.hpp>
  285. using namespace boost::python;
  286. BOOST_PYTHON_MODULE (libpcapreader) {
  287. class_<pcap_processor>("pcap_processor", init<std::string, std::string>())
  288. .def("merge_pcaps", &pcap_processor::merge_pcaps)
  289. .def("collect_statistics", &pcap_processor::collect_statistics)
  290. .def("get_timestamp_mu_sec", &pcap_processor::get_timestamp_mu_sec)
  291. .def("write_to_database", &pcap_processor::write_to_database);
  292. }