pcap_processor.cpp 13 KB

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