pcap_processor.cpp 15 KB

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