pcap_processor.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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) : filePath(path) {
  8. }
  9. /**
  10. * Iterates over all packets, starting by packet no. 1, and stops if
  11. * after_packet_number equals the current packet number.
  12. * @param after_packet_number The packet position in the PCAP file whose timestamp is wanted.
  13. * @return The timestamp of the last processed packet plus 1 microsecond.
  14. */
  15. long double pcap_processor::get_timestamp_mu_sec(const int after_packet_number) {
  16. if (file_exists(filePath)) {
  17. FileSniffer sniffer(filePath);
  18. int current_packet = 1;
  19. for (SnifferIterator i = sniffer.begin(); i != sniffer.end(); i++) {
  20. if (after_packet_number == current_packet) {
  21. const Timestamp &ts = i->timestamp();
  22. return (long double) ((ts.seconds() * 1000000) + ts.microseconds() + 1);
  23. }
  24. current_packet++;
  25. }
  26. }
  27. return -1.0;
  28. }
  29. /**
  30. * Merges two PCAP files, given by paths in filePath and parameter pcap_path.
  31. * @param pcap_path The path to the file which should be merged with the loaded PCAP file.
  32. * @return The string containing the file path to the merged PCAP file.
  33. */
  34. std::string pcap_processor::merge_pcaps(const std::string pcap_path) {
  35. // Build new filename with timestamp
  36. // Build timestamp
  37. time_t curr_time = time(0);
  38. char buff[1024];
  39. struct tm *now = localtime(&curr_time);
  40. strftime(buff, sizeof(buff), "%Y%m%d-%H%M%S", now);
  41. std::string tstmp(buff);
  42. // Replace filename with 'timestamp_filename'
  43. std::string new_filepath = filePath;
  44. const std::string &newExt = "_" + tstmp + ".pcap";
  45. std::string::size_type h = new_filepath.rfind('.', new_filepath.length());
  46. if (h != std::string::npos) {
  47. new_filepath.replace(h, newExt.length(), newExt);
  48. }
  49. FileSniffer sniffer_base(filePath);
  50. SnifferIterator iterator_base = sniffer_base.begin();
  51. FileSniffer sniffer_attack(pcap_path);
  52. SnifferIterator iterator_attack = sniffer_attack.begin();
  53. PacketWriter writer(new_filepath, PacketWriter::ETH2);
  54. bool all_attack_pkts_processed = false;
  55. // Go through base PCAP and merge packets by timestamp
  56. for (; iterator_base != sniffer_base.end();) {
  57. auto tstmp_base = iterator_base->timestamp().seconds();
  58. auto tstmp_attack = iterator_attack->timestamp().seconds();
  59. if (!all_attack_pkts_processed && tstmp_attack <= tstmp_base) {
  60. writer.write(*iterator_attack);
  61. iterator_attack++;
  62. if (iterator_attack == sniffer_attack.end())
  63. all_attack_pkts_processed = true;
  64. } else {
  65. writer.write(*iterator_base);
  66. iterator_base++;
  67. }
  68. }
  69. // This may happen if the base PCAP is smaller than the attack PCAP
  70. // In this case append the remaining packets of the attack PCAP
  71. for (; iterator_attack != sniffer_attack.end(); iterator_attack++) {
  72. writer.write(*iterator_attack->pdu());
  73. }
  74. return new_filepath;
  75. }
  76. /**
  77. * Collect statistics of the loaded PCAP file. Calls for each packet the method process_packets.
  78. */
  79. void pcap_processor::collect_statistics() {
  80. // Only process PCAP if file exists
  81. if (file_exists(filePath)) {
  82. std::cout << "Loading pcap..." << std::endl;
  83. FileSniffer sniffer(filePath);
  84. SnifferIterator i = sniffer.begin();
  85. Tins::Timestamp lastProcessedPacket;
  86. // Save timestamp of first packet
  87. stats.setTimestampFirstPacket(i->timestamp());
  88. // Iterate over all packets and collect statistics
  89. for (; i != sniffer.end(); i++) {
  90. stats.incrementPacketCount();
  91. this->process_packets(*i);
  92. lastProcessedPacket = i->timestamp();
  93. }
  94. // Save timestamp of last packet into statistics
  95. stats.setTimestampLastPacket(lastProcessedPacket);
  96. }
  97. }
  98. /**
  99. * Analyzes a given packet and collects statistical information.
  100. * @param pkt The packet to get analyzed.
  101. */
  102. void pcap_processor::process_packets(const Packet &pkt) {
  103. // Layer 2: Data Link Layer ------------------------
  104. std::string mac_address = "";
  105. const PDU *pdu_l2 = pkt.pdu();
  106. uint32_t sizeCurrentPacket = pdu_l2->size();
  107. if (pdu_l2->pdu_type() == PDU::ETHERNET_II) {
  108. EthernetII eth = (const EthernetII &) *pdu_l2;
  109. mac_address = eth.src_addr().to_string();
  110. sizeCurrentPacket = eth.size();
  111. }
  112. stats.addPacketSize(sizeCurrentPacket);
  113. // Layer 3 - Network -------------------------------
  114. const PDU *pdu_l3 = pkt.pdu()->inner_pdu();
  115. const PDU::PDUType pdu_l3_type = pdu_l3->pdu_type();
  116. std::string ipAddressSender;
  117. std::string ipAddressReceiver;
  118. // PDU is IPv4
  119. if (pdu_l3_type == PDU::PDUType::IP) {
  120. const IP &ipLayer = (const IP &) *pdu_l3;
  121. ipAddressSender = ipLayer.src_addr().to_string();
  122. ipAddressReceiver = ipLayer.dst_addr().to_string();
  123. // IP distribution
  124. stats.addIpStat_packetSent(ipAddressSender, ipLayer.dst_addr().to_string(), sizeCurrentPacket);
  125. // TTL distribution
  126. stats.incrementTTLcount(ipAddressSender, ipLayer.ttl());
  127. // Protocol distribution
  128. stats.incrementProtocolCount(ipAddressSender, "IPv4");
  129. // Assign IP Address to MAC Address
  130. stats.assign_mac_address(ipAddressSender, mac_address);
  131. } // PDU is IPv6
  132. else if (pdu_l3_type == PDU::PDUType::IPv6) {
  133. const IPv6 &ipLayer = (const IPv6 &) *pdu_l3;
  134. ipAddressSender = ipLayer.src_addr().to_string();
  135. ipAddressReceiver = ipLayer.dst_addr().to_string();
  136. // IP distribution
  137. stats.addIpStat_packetSent(ipAddressSender, ipLayer.dst_addr().to_string(), sizeCurrentPacket);
  138. // TTL distribution
  139. stats.incrementTTLcount(ipAddressSender, ipLayer.hop_limit());
  140. // Protocol distribution
  141. stats.incrementProtocolCount(ipAddressSender, "IPv6");
  142. // Assign IP Address to MAC Address
  143. stats.assign_mac_address(ipAddressSender, mac_address);
  144. } else {
  145. std::cout << "Unknown PDU Type on L3: " << pdu_l3_type << std::endl;
  146. }
  147. // Layer 4 - Transport -------------------------------
  148. const PDU *pdu_l4 = pdu_l3->inner_pdu();
  149. if (pdu_l4 != 0) {
  150. // Protocol distribution - layer 4
  151. PDU::PDUType p = pdu_l4->pdu_type();
  152. if (p == PDU::PDUType::TCP) {
  153. TCP tcpPkt = (const TCP &) *pdu_l4;
  154. stats.incrementProtocolCount(ipAddressSender, "TCP");
  155. try {
  156. int val = tcpPkt.mss();
  157. stats.addMSS(ipAddressSender, val);
  158. } catch (Tins::option_not_found) {
  159. // Ignore MSS if option not set
  160. }
  161. stats.incrementPortCount(ipAddressSender, tcpPkt.sport(), ipAddressReceiver, tcpPkt.dport());
  162. } else if (p == PDU::PDUType::UDP) {
  163. const UDP udpPkt = (const UDP &) *pdu_l4;
  164. stats.incrementProtocolCount(ipAddressSender, "UDP");
  165. stats.incrementPortCount(ipAddressSender, udpPkt.sport(), ipAddressReceiver, udpPkt.dport());
  166. } else if (p == PDU::PDUType::ICMP) {
  167. stats.incrementProtocolCount(ipAddressSender, "ICMP");
  168. } else if (p == PDU::PDUType::ICMPv6) {
  169. stats.incrementProtocolCount(ipAddressSender, "ICMPv6");
  170. }
  171. }
  172. }
  173. /**
  174. * Writes the collected statistic data into a SQLite3 database located at database_path. Uses an existing
  175. * database or, if not present, creates a new database.
  176. * @param database_path The path to the database file, ending with .sqlite3.
  177. */
  178. void pcap_processor::write_to_database(std::string database_path) {
  179. stats.writeToDatabase(database_path);
  180. }
  181. /**
  182. * Checks whether the file with the given file path exists.
  183. * @param filePath The path to the file to check.
  184. * @return True iff the file exists, otherweise False.
  185. */
  186. bool inline pcap_processor::file_exists(const std::string &filePath) {
  187. struct stat buffer;
  188. return stat(filePath.c_str(), &buffer) == 0;
  189. }
  190. /*
  191. * Comment in if executable should be build & run
  192. * Comment out if library should be build
  193. */
  194. //int main() {
  195. // std::cout << "Starting application." << std::endl;
  196. // pcap_processor pcap = pcap_processor("/mnt/hgfs/datasets/95M.pcap");
  197. // long double t = pcap.get_timestamp_mu_sec(87);
  198. // std::cout << t << std::endl;
  199. //
  200. //// time_t start, end;
  201. //// time(&start);
  202. //// pcap.collect_statistics();
  203. //// time(&end);
  204. //// double dif = difftime(end, start);
  205. //// printf("Elapsed time is %.2lf seconds.", dif);
  206. //// pcap.stats.writeToDatabase("/home/pjattke/myDB.sqlite3");
  207. //
  208. // return 0;
  209. //}
  210. /*
  211. * Comment out if executable should be build & run
  212. * Comment in if library should be build
  213. */
  214. #include <boost/python.hpp>
  215. using namespace boost::python;
  216. BOOST_PYTHON_MODULE (libpcapreader) {
  217. class_<pcap_processor>("pcap_processor", init<std::string>())
  218. .def("merge_pcaps", &pcap_processor::merge_pcaps)
  219. .def("collect_statistics", &pcap_processor::collect_statistics)
  220. .def("get_timestamp_mu_sec", &pcap_processor::get_timestamp_mu_sec)
  221. .def("write_to_database", &pcap_processor::write_to_database);
  222. }