pcap_processor.cpp 15 KB

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