tcpliveplay.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. /*
  2. * Main Author & Publisher: Yazan H. Siam (tcpliveplay@gmail.com)
  3. * File: tcpliveplay.c
  4. * Started as a Senior Design project @ North Carolina State University
  5. * Last Updated Date: September 5, 2012
  6. *
  7. */
  8. /**
  9. * Program Description:
  10. * This program, 'tcpliveplay' replays a captured set of packets using new TCP connections with the
  11. * captured TCP payloads against a remote host in order to do comprehensive vulnerability testings.
  12. * This program takes in a "*.pcap" file that contains only one tcp flow connection and replays it
  13. * against a live host exactly how the captured packets are laid out. At the beginning, the program
  14. * establishes who the 'client' is and the 'server' is based on who initiates the SYN compares each
  15. * packet's source ip against the ip of the 'client' (which is named local in the code) and the 'server'
  16. * (remote) to correctly determine the expected seqs & acks. This also extracts the MACs of both local
  17. * and remote clients. The program is also capable of rewriting the local and remote MAC & IP so that
  18. * the packets are properly replayed when used on live networks. The current state of the program is that
  19. * it takes in a pcap file on command line and writes a new file called "newfile.pcap" which is used thereafter
  20. * for the rest of the program's calculations and set expectations. The program prints out a summary of the
  21. * new file on the command prompt. Once the program is done, "newfile.pcap" is cleaned up.
  22. * Program Design Overview:
  23. * Before replaying the packets, the program reads in the pcap file that contains one tcp flow,
  24. * and takes the SEQ/ACK #s.
  25. * Based on the number of packets, a struct schedule of events are is set up. Based on
  26. * the SEQ/ACK numbers read in, the schedule is setup to be relative numbers rather than
  27. * absolute. This is done by starting with local packets, subtracting the first SEQ (which
  28. * is that of the first SYN packet) from all the SEQs of the local packets then by subtracting
  29. * the first remote sequence (which is that of the SYN-ACK packet) from all the local packet's
  30. * ACKs. After the local side SEQ/ACK numbers are fixed to relative numbers, 'lseq_adjust'
  31. * the locally generated random number for the SYN packet gets added to all the local SEQs
  32. * to adjust the schedule to absolute number configuration. Then doing the remote side is similar
  33. * except we only fix the remote ACKs based on our locally generated random number because
  34. * we do not yet know the remote random number of the SYN-ACK packet. This means that at this
  35. * point the entire schedule of local packets and remote packets are set in such a way that
  36. * the local packets' SEQ's are absolute, but ACKs are relative and the remote packets' SEQ's are
  37. * relative but ACKs as absolute. Once this is set, the replay starts by sending first SYN packet.
  38. * If the remote host's acks with the SYN packet_SEQ+1 then we save their remote SEQ and adjust
  39. * the local ACKs and remote SEQs in the struct schedule to be absolute based this remote SEQ.
  40. * From this point on forward, we know or 'expect' what the remote host's ACKs and SEQs are exactly.
  41. * If the remote host responds correctly as we expect (checking the schedule position expectation
  42. * as packets are received) then we proceed in the schedule whether the next event is to send a local
  43. * packet or wait for a remote packet to arrive.
  44. *
  45. * Usage: tcpliveplay <eth0/eth1> <file.pcap> <Destinatin IP [1.2.3.4]> <Destination mac [0a:1b:2c:3d:4e:5f]> <'random' dst port OR specify dport #>
  46. *
  47. * Example:
  48. * yhsiam@yhsiam-VirtualBox:~$ tcpliveplay eth0 test1.pcap 192.168.1.4 52:57:01:11:31:92 random
  49. *
  50. * NOTE: This program may not completely replay the packets due to the remote host responding in an unexpected
  51. * fashion such as responding with packets never seen in the given *.pcap file or coupling packets together, etc.
  52. * if you have any suggestion on improving this software or if you find any bugs, please let me know at my
  53. * email: tcpliveplay@gmail.com
  54. *
  55. * Past Contributors (Last contributed May 4, 2012): Andrew Leonard & Beau Luck
  56. *
  57. */
  58. #include "config.h"
  59. #include "defines.h"
  60. #include "common.h"
  61. #include <signal.h>
  62. #include <time.h>
  63. #include <utime.h>
  64. #include <ctype.h>
  65. #include <fcntl.h>
  66. #include <stdio.h>
  67. #include <stdlib.h>
  68. #include <string.h>
  69. #include <sys/types.h>
  70. #include <unistd.h>
  71. #include <errno.h>
  72. #include <stdbool.h>
  73. #include <sys/ioctl.h>
  74. #include <sys/types.h>
  75. #include <sys/socket.h>
  76. #include <net/if.h>
  77. #include <string.h>
  78. #include <sys/ioctl.h>
  79. #include <netinet/in.h>
  80. #include <net/if.h>
  81. #include <arpa/inet.h>
  82. #include "tcpliveplay.h"
  83. #include "tcpliveplay_opts.h"
  84. #include "common/sendpacket.h"
  85. #include "common/utils.h"
  86. #include "send_packets.h"
  87. volatile int didsig;
  88. #ifdef DEBUG /* set -DDEBUG=1 */
  89. int debug = 0;
  90. #endif
  91. pcap_t *set_live_filter(char *dev, input_addr* hostip, unsigned int port);
  92. pcap_t *set_offline_filter(char* file);
  93. pcap_t *live_handle;
  94. u_char *recvd_pkt_data = NULL;
  95. unsigned int buf_write_index = 0;
  96. unsigned int sched_index = 0;
  97. unsigned int initial_rseq=0;
  98. sendpacket_t *sp;
  99. unsigned int seed = 0;
  100. const u_char *packet_keeper_rprev = NULL;
  101. ether_hdr *etherhdr_rprev = NULL; /*g for Global header pointers used in pcap_loop callback*/
  102. tcp_hdr *tcphdr_rprev = NULL;
  103. ipv4_hdr *iphdr_rprev = NULL;
  104. unsigned int size_payload_prev = 0;
  105. unsigned int finack_rindex = 0;
  106. unsigned int acked_index = 0;
  107. unsigned int diff_payload_index = 0;
  108. bool different_payload = false;
  109. volatile sig_atomic_t keep_going = 1;
  110. int random_port();
  111. unsigned int pkts_scheduled=0; /* packet counter */
  112. struct tcp_sched* sched = NULL;
  113. void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);
  114. void catch_alarm (int sig);
  115. int iface_addrs(char* iface, input_addr* ip, struct mac_addr* mac);
  116. int extmac(char* new_rmac_ptr, struct mac_addr* new_remotemac);
  117. int extip(char *ip_string, input_addr* new_remoteip);
  118. int rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* myip, struct mac_addr* mymac, char* file, unsigned int new_src_port);
  119. int setup_sched(struct tcp_sched* sched);
  120. int relative_sched(struct tcp_sched* sched, u_int32_t first_rseq, int num_packets);
  121. int fix_all_checksum_liveplay(ipv4_hdr *iphdr);
  122. int compip(input_addr* lip, input_addr* rip, input_addr* pkgip);
  123. int do_checksum_liveplay(u_int8_t *data, int proto, int len);
  124. int do_checksum_math_liveplay(u_int16_t *data, int len);
  125. /**
  126. * This is the main function of the program that handles calling other
  127. * functions to implemented the needed operations of the replay functionaily.
  128. */
  129. int
  130. main(int argc, char **argv)
  131. {
  132. unsigned int k;
  133. int num_packets = 0;
  134. static const char random_strg[] = "random";
  135. char* iface = argv[1];
  136. char* new_rmac_ptr;
  137. char* new_rip_ptr;
  138. input_addr new_remoteip;
  139. struct mac_addr new_remotemac;
  140. input_addr myip;
  141. struct mac_addr mymac;
  142. int new_src_port = 0;
  143. unsigned int retransmissions = 0;
  144. pcap_t *local_handle;
  145. char errbuf[PCAP_ERRBUF_SIZE];
  146. char ebuf[SENDPACKET_ERRBUF_SIZE];
  147. optionProcess(&tcpliveplayOptions, argc, argv); /*Process AutoOpts for manpage options*/
  148. if((argc < 5) || (argv[1]==NULL) || (argv[2]==NULL) || (argv[3]==NULL) || (argv[4]==NULL) || (argv[5]==NULL)){
  149. printf("ERROR: Incorrect Usage!\n");
  150. printf("Usage: tcpliveplay <eth0/eth1> <file.pcap> <Destinatin IP [1.2.3.4]> <Destination mac [0a:1b:2c:3d:4e:5f]> <specify 'random' or specific port#>\n");
  151. printf("Example:\n yhsiam@yhsiam-VirtualBox:~$ sudo tcpliveplay eth0 test1.pcap 192.168.1.4 52:57:01:11:31:92 random\n\n");
  152. exit(0);
  153. }
  154. if (strlen(iface) > IFNAMSIZ - 1)
  155. errx(-1, "Invalid interface name %s\n", iface);
  156. if (iface_addrs(iface, &myip, &mymac) < 0) /* Extract MAC of interface replay is being request on */
  157. errx(-1, "Failed to access interface %s\n", iface);
  158. /* open send function socket*/
  159. if ((sp = sendpacket_open(iface, ebuf, TCPR_DIR_C2S, SP_TYPE_NONE, NULL)) == NULL)
  160. errx(-1, "Can't open %s: %s", argv[1], ebuf);
  161. /*for(int i = 0; i<10; i++) tolower(port_mode[i]);*/
  162. if(strcmp(argv[5], random_strg)==0)
  163. new_src_port = random_port();
  164. else
  165. new_src_port = atoi(argv[5]);
  166. if (new_src_port < 0 || new_src_port > 65535)
  167. errx(new_src_port, "Cannot use source port %d", new_src_port);
  168. printf("new source port:: %d\n", new_src_port);
  169. /* Establish a handler for SIGALRM signals. */
  170. /* This is used as timeout for unresponsive remote hosts */
  171. signal (SIGALRM, catch_alarm);
  172. /* Extract new Remote MAC & IP inputed at command line */
  173. new_rmac_ptr= argv[4];
  174. new_rip_ptr = argv[3];
  175. /* These function setup the MAC & IP addresses in the mac_addr & in_addr structs */
  176. if (extmac(new_rmac_ptr, &new_remotemac) == ERROR)
  177. errx(-1, "failed to parse mac address %s\n", new_rmac_ptr);
  178. if (extip(new_rip_ptr, &new_remoteip) == ERROR)
  179. errx(-1, "failed to parse IP address %s\n", new_rip_ptr);
  180. /* Rewrites the given "*.pcap" file with all the new parameters and returns the number of packets */
  181. /* that need to be replayed */
  182. num_packets = rewrite(&new_remoteip, &new_remotemac, &myip, &mymac, argv[2], new_src_port);
  183. if (num_packets < 0)
  184. errx(-1, "Unable to rewrite PCAP file %s\n",argv[2]);
  185. /* create schedule & set it up */
  186. sched = (struct tcp_sched*) malloc(num_packets*sizeof(struct tcp_sched));
  187. if (!sched)
  188. err(-1, "out of memory\n");
  189. pkts_scheduled = setup_sched(sched); /* Returns number of packets in schedule*/
  190. /* Set up the schedule struct to be relative numbers rather than absolute*/
  191. relative_sched(sched, sched[1].exp_rseq, num_packets);
  192. printf("Packets Scheduled %d\n", pkts_scheduled);
  193. /* Open socket for savedfile traffic to be sent*/
  194. local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/
  195. if (local_handle == NULL) {
  196. fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf);
  197. free(sched);
  198. return(2);
  199. }
  200. /* Open socket for live traffic to be listed to*/
  201. live_handle = set_live_filter(iface, &myip, new_src_port); /* returns a pcap_t that filters out traffic other than TCP*/
  202. if (live_handle == NULL) {
  203. fprintf(stderr,"Error occurred while listing on traffic: %s\n", errbuf);
  204. free(sched);
  205. return(2);
  206. }
  207. /* Printout when no packets are scheduled */
  208. if(pkts_scheduled==0){
  209. printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
  210. printf("+ ERROR:: There are no TCP packets to send +\n");
  211. printf("+ Closing replay... +\n");
  212. printf("+ Thank you for Playing, Play again! +\n");
  213. printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
  214. free(sched);
  215. return ERROR;
  216. }
  217. /* Start replay by sending the first packet, the SYN, from the schedule */
  218. else if(sched[0].local){ /* Send first packet*/
  219. sendpacket(sp, sched[sched_index].packet_ptr, sched[sched_index].pkthdr.len, &sched[sched_index].pkthdr);
  220. printf("Sending Local Packet............... [%d]\n",sched_index+1);
  221. sched_index++; /* Proceed in the schedule */
  222. }
  223. /* Main while loop that handles the decision making and the replay oprations */
  224. while(sched_index<pkts_scheduled){
  225. if(!keep_going) { /*Check the timeout variable */
  226. printf("\n======================================================================\n");
  227. printf("= TIMEOUT:: Remote host is not responding. You may have crashed =\n");
  228. printf("= the host you replayed these packets against OR the packet sequence =\n");
  229. printf("= changed since the capture was taken resulting in differing =\n");
  230. printf("= expectations. Closing replay... =\n");
  231. printf("======================================================================\n\n");
  232. break;
  233. }
  234. /* tcphdr_rprev carries the last remote tcp header */
  235. if(tcphdr_rprev == NULL) {
  236. //printf("FIRST PASS!\n");
  237. }
  238. /* Check if received RST or RST-ACK flagged packets*/
  239. else if((tcphdr_rprev->th_flags==TH_RST) || (tcphdr_rprev->th_flags==(TH_RST|TH_ACK))){
  240. printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
  241. printf("+ ERROR:: Remote host has requested to RESET the connection. +\n");
  242. printf("+ Closing replay... +\n");
  243. printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
  244. break;
  245. }
  246. /*Check if received earlier FIN-ACK than expected
  247. else if((sched_index-1 < finack_rindex) && (tcphdr_rprev->th_flags==(TH_FIN|TH_ACK))){
  248. printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
  249. printf("+ ERROR:: Remote host sent an earlier FIN-ACK than expected. +\n");
  250. printf("+ Closing replay... +\n");
  251. printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
  252. return;
  253. } */
  254. /* Do the following if we receive a packet that ACKs for the same ACKing of next packet */
  255. else if((tcphdr_rprev->th_seq==htonl(sched[sched_index].exp_rseq)) && (tcphdr_rprev->th_ack==htonl(sched[sched_index].exp_rack)) && (size_payload_prev>0)){
  256. printf("Received Remote Packet............... [%d]\n",sched_index+1);
  257. printf("Skipping Packet...................... [%d] to Packet [%d]\n",sched_index+1, sched_index+2);
  258. printf("Next Remote Packet Expectation met.\nProceeding in replay...\n");
  259. sched_index++;
  260. }
  261. /* Do the following if payload does not meet expectation and re-attempt with the remote host for 3 tries*/
  262. else if(different_payload){
  263. printf("\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
  264. printf("+ WARNING: Remote host is not meeting packet size expectations. +\n");
  265. printf("+ for packet %-d. Application layer data differs from capture being replayed. +\n", diff_payload_index+1);
  266. printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
  267. printf("Requesting retransmission.\n Proceeding...\n");
  268. different_payload = false;
  269. }
  270. /* Local Packets */
  271. if(sched[sched_index].local) {
  272. /*Reset alarm timeout*/
  273. alarm (ALARM_TIMEOUT);
  274. printf("Sending Local Packet............... [%d]\n",sched_index+1);
  275. /* edit each packet tcphdr before sending based on the schedule*/
  276. if(sched_index>0){
  277. sched[sched_index].tcphdr->th_ack = htonl(sched[sched_index].curr_lack);
  278. fix_all_checksum_liveplay(sched[sched_index].iphdr);
  279. }
  280. /* If 3 attempts of resending was made, then error out to the user */
  281. if(sched[sched_index].sent_counter==3){
  282. printf("\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
  283. printf("+ ERROR: Re-sent packet [%-d] 3 times, but remote host is not +\n", sched_index+1);
  284. printf("+ responding as expected. 3 resend attempts are a maximum. +\n");
  285. printf("+ Closing replay... +\n");
  286. printf("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n");
  287. break;
  288. }
  289. /* If nothing goes wrong, then send the packet scheduled to be sent, then proceed in the schedule */
  290. sendpacket(sp, sched[sched_index].packet_ptr, sched[sched_index].pkthdr.len, &sched[sched_index].pkthdr);
  291. sched[sched_index].sent_counter++; /* Keep track of how many times this specific packet was attempted */
  292. sched_index++; /* proceed */
  293. }
  294. /* Remote Packets */
  295. else if(sched[sched_index].remote){
  296. alarm (ALARM_TIMEOUT);
  297. printf("Receiving Packets from remote host...\n");
  298. pcap_dispatch(live_handle, 1, got_packet, NULL); /* Listen in on NIC for tcp packets */
  299. //printf("pcap_loop returned\n");
  300. }
  301. } /* end of main while loop*/
  302. pcap_breakloop(live_handle);
  303. pcap_close(live_handle);
  304. sendpacket_close(sp); /* Close Send socket*/
  305. remove("newfile.pcap"); /* Remote the rewritten file that was created*/
  306. for(k=0; k<pkts_scheduled; k++){
  307. retransmissions+=sched[k].sent_counter;
  308. }
  309. /* User Debug Result Printouts*/
  310. if(sched_index==pkts_scheduled){
  311. printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
  312. printf("~ CONGRATS!!! You have successfully Replayed your pcap file '%s' \n", argv[2]);
  313. printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n");
  314. }
  315. else {
  316. printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
  317. printf("~ Unfortunately an error has occurred halting the replay of \n");
  318. printf("~ the pcap file '%s'. Please see error above for details... \n", argv[2]);
  319. printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n");
  320. }
  321. printf("----------------TCP Live Play Summary----------------\n");
  322. printf("- Packets Scheduled to be Sent & Received: %-d \n", pkts_scheduled);
  323. printf("- Actual Packets Sent & Received: %-d \n", sched_index);
  324. printf("- Total Local Packet Re-Transmissions due to packet \n");
  325. printf("- loss and/or differing payload size than expected: %-d \n", retransmissions);
  326. printf("- Thank you for Playing, Play again! \n");
  327. printf("----------------------------------------------------------\n\n");
  328. free(sched);
  329. return 0;
  330. }
  331. /*end of main() function*/
  332. /**
  333. * This function serves as a timer alarm
  334. */
  335. void
  336. catch_alarm (int sig){
  337. keep_going = 0;
  338. signal (sig, catch_alarm);
  339. }
  340. static int tcplp_rand(void)
  341. {
  342. struct timeval tv;
  343. if (!seed) {
  344. gettimeofday(&tv, NULL);
  345. seed = (unsigned int)tv.tv_sec ^ (unsigned int)tv.tv_usec;
  346. }
  347. return tcpr_random(&seed);
  348. }
  349. /**
  350. * This function returns a random number between 49152 and 65535
  351. */
  352. int
  353. random_port()
  354. {
  355. int random = tcplp_rand();
  356. return (49152 + (random % 16383));
  357. }
  358. /**
  359. * This function sets up the scheduled local ACK and Remote SEQ to be relative numbers,
  360. * While it sets up the local SEQs and remote ACKs to be absolute within the schedule.
  361. */
  362. int
  363. relative_sched(struct tcp_sched* sched, u_int32_t first_rseq, int num_packets){
  364. int i;
  365. u_int32_t lseq_adjust = tcplp_rand();
  366. printf("Random Local SEQ: %u\n",lseq_adjust);
  367. u_int32_t first_lseq = sched[0].curr_lseq; /* SYN Packet SEQ number */
  368. /* Fix schedule to relative and absolute */
  369. for(i = 0; i < num_packets; i++){
  370. if(sched[i].local){
  371. sched[i].curr_lseq = sched[i].curr_lseq - first_lseq; /* Fix current local SEQ to relative */
  372. sched[i].curr_lseq = sched[i].curr_lseq + lseq_adjust; /* Make absolute. lseq_adjust is the locally generated random number */
  373. sched[i].curr_lack = sched[i].curr_lack - first_rseq; /* Fix current local ACK to relative */
  374. if (sched[i].tcphdr)
  375. sched[i].tcphdr->th_seq = htonl(sched[i].curr_lseq); /* Edit the actual packet header data */
  376. fix_all_checksum_liveplay(sched[i].iphdr); /* Fix the checksum */
  377. sched[i].exp_rseq = sched[i].exp_rseq - first_rseq;
  378. sched[i].exp_rack = sched[i].exp_rack - first_lseq;
  379. sched[i].exp_rack = sched[i].exp_rack + lseq_adjust;
  380. }
  381. else if(sched[i].remote){
  382. sched[i].exp_rseq = sched[i].exp_rseq - first_rseq; /* Fix expected remote SEQ to be relative */
  383. sched[i].exp_rack = sched[i].exp_rack - first_lseq; /* Fix expected remote ACK to be relative*/
  384. sched[i].exp_rack = sched[i].exp_rack + lseq_adjust; /* Fix expeted remote ACK to be absolute */
  385. }
  386. }
  387. return SUCCESS;
  388. }
  389. /**
  390. * This function sets up the schedule for the rest of the program
  391. * extracting all the needed information from the given pcap file
  392. * and coping into memory (into a struct format)
  393. *
  394. */
  395. int
  396. setup_sched(struct tcp_sched* sched){
  397. input_addr sip, dip; /* Source & Destination IP */
  398. input_addr local_ip, remote_ip; /* ip address of client and server*/
  399. /*temporary packet buffers*/
  400. struct pcap_pkthdr header; // The header that pcap gives us
  401. const u_char *packet; // The actual packet
  402. pcap_t *local_handle;
  403. unsigned int pkt_counter=0;
  404. ether_hdr *etherhdr = NULL;
  405. tcp_hdr *tcphdr = NULL;
  406. ipv4_hdr *iphdr = NULL;
  407. local_ip.byte1=0;
  408. local_ip.byte2=0;
  409. local_ip.byte3=0;
  410. local_ip.byte4=0;
  411. remote_ip.byte1=0;
  412. remote_ip.byte2=0;
  413. remote_ip.byte3=0;
  414. remote_ip.byte4=0;
  415. unsigned int size_ip, i = 0;
  416. unsigned int size_tcp;
  417. unsigned int size_payload;
  418. char errbuf[PCAP_ERRBUF_SIZE];
  419. unsigned int flags=0;
  420. bool remote = false; /* flags to test if data is from 'cleint'=local or 'server'=remote */
  421. bool local = false;
  422. local_handle = pcap_open_offline("newfile.pcap", errbuf); /*call pcap library function*/
  423. if (local_handle == NULL) {
  424. fprintf(stderr,"Couldn't open pcap file %s: %s\n", "newfile.pcap", errbuf);
  425. return(2);
  426. }
  427. /*Before sending any packet, setup the schedule with the proper parameters*/
  428. while((packet = pcap_next(local_handle,&header))) {
  429. pkt_counter++; /*increment number of packets seen*/
  430. memcpy(&sched[i].pkthdr, &header, sizeof(struct pcap_pkthdr));
  431. //sched[i].len = header.len;
  432. //sched[i].caplen = header.caplen;
  433. sched[i].packet_ptr = safe_malloc(sched[i].pkthdr.len);
  434. memcpy(sched[i].packet_ptr, packet, sched[i].pkthdr.len);
  435. /* extract necessary data */
  436. etherhdr = (ether_hdr*)(sched[i].packet_ptr);
  437. iphdr = (ipv4_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET);
  438. size_ip = iphdr->ip_hl << 2;
  439. if (size_ip < 20) {
  440. printf("ERROR: Invalid IP header length: %u bytes\n", size_ip);
  441. return 0;
  442. }
  443. tcphdr = (tcp_hdr *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip);
  444. size_tcp = tcphdr->th_off*4;
  445. if (size_tcp < 20) {
  446. printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp);
  447. return 0;
  448. }
  449. /* payload = (u_char *)(sched[i].packet_ptr + SIZE_ETHERNET + size_ip + size_tcp); */
  450. size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp));
  451. /* Source IP and Destination IP */
  452. sip = iphdr->ip_src;
  453. dip = iphdr->ip_dst;
  454. flags = tcphdr->th_flags;
  455. if (flags == TH_SYN){ /* set IPs who's local and who's remote based on the SYN flag */
  456. local_ip = sip;
  457. remote_ip = dip;
  458. }
  459. /*Compare IPs to see which packet is this comming from*/
  460. if(compip(&local_ip, &remote_ip, &sip)==LOCAL_IP_MATCH){
  461. local = true;
  462. remote = false;
  463. }
  464. if(compip(&local_ip, &remote_ip, &sip)==REMOTE_IP_MATCH){
  465. local = false;
  466. remote = true;
  467. }
  468. /* Setup rest of Schedule, parameter by parameter */
  469. /* Refer to header file for details on each of the parameters */
  470. sched[i].etherhdr = etherhdr;
  471. sched[i].iphdr = iphdr;
  472. sched[i].tcphdr = tcphdr;
  473. sched[i].size_ip = size_ip;
  474. sched[i].size_tcp = size_tcp;
  475. sched[i].size_payload = size_payload;
  476. sched[i].sent_counter = 0;
  477. /* Do the following only for the first packet (SYN)*/
  478. if(i==0){
  479. sched[i].length_last_ldata = 0;
  480. sched[i].length_curr_ldata = 0;
  481. sched[i].length_last_rdata = 0;
  482. sched[i].length_curr_rdata = 0;
  483. sched[i].local = true;
  484. sched[i].remote = false;
  485. sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq);
  486. sched[i].curr_lack = 0;
  487. sched[i].exp_rseq = 0; /* Keep track of previous remote seq & ack #s*/
  488. sched[i].exp_rack = 0;
  489. }
  490. /* Local Packet operations */
  491. else if(local){
  492. sched[i].length_last_ldata = sched[i-1].length_curr_ldata;
  493. sched[i].length_curr_ldata = size_payload;
  494. sched[i].length_last_rdata = sched[i-1].length_curr_rdata;
  495. sched[i].length_curr_rdata = 0;
  496. sched[i].local = true;
  497. sched[i].remote = false;
  498. sched[i].curr_lseq = ntohl(sched[i].tcphdr->th_seq);
  499. sched[i].curr_lack = ntohl(sched[i].tcphdr->th_ack);
  500. sched[i].exp_rseq = sched[i-1].exp_rseq; /* Keep track of previous remote seq & ack #s*/
  501. sched[i].exp_rack = sched[i-1].exp_rack;
  502. }
  503. /* Remote Packet operations */
  504. else if(remote){
  505. sched[i].length_last_ldata = sched[i-1].length_curr_ldata;
  506. sched[i].length_curr_ldata = 0;
  507. sched[i].length_last_rdata = sched[i-1].length_curr_rdata;
  508. sched[i].length_curr_rdata = size_payload;
  509. sched[i].local = false;
  510. sched[i].remote = true;
  511. sched[i].curr_lseq = sched[i-1].curr_lseq;
  512. sched[i].curr_lack = sched[i-1].curr_lack;
  513. sched[i].exp_rseq = ntohl(sched[i].tcphdr->th_seq); /* Keep track of previous remote seq & ack #s*/
  514. sched[i].exp_rack = ntohl(sched[i].tcphdr->th_ack);
  515. /* Setup global variable where remote FIN-ACK exists*/
  516. if(flags == (TH_FIN|TH_ACK)) finack_rindex = i;
  517. //printf("REMOTE --------%d\n",i+1);
  518. }
  519. i++; /* increment schedule index */
  520. } /*end internal loop for reading packets (all in one file)*/
  521. pcap_close(local_handle); /*close the pcap file*/
  522. return pkt_counter; /* Return number of packets scheduled */
  523. }
  524. /**
  525. * This function returns a pcap_t for the live traffic handler which
  526. * filters out traffic other than TCP
  527. *
  528. */
  529. pcap_t*
  530. set_live_filter(char *dev, input_addr* hostip, unsigned int port)
  531. {
  532. pcap_t *handle = NULL; /* Session handle */
  533. char errbuf[PCAP_ERRBUF_SIZE]; /* Error string buffer */
  534. struct bpf_program fp; /* The compiled filter */
  535. char filter_exp[52];
  536. sprintf(filter_exp,"tcp and dst host %d.%d.%d.%d and dst port %u",
  537. hostip->byte1, hostip->byte2, hostip->byte3, hostip->byte4, port); /* The filter expression */
  538. bpf_u_int32 mask; /* Our network mask */
  539. bpf_u_int32 net; /* Our IP */
  540. /* Define the device */
  541. if (dev == NULL) {
  542. fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
  543. return handle;
  544. }
  545. /* Find the properties for the device */
  546. if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
  547. fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
  548. net = 0;
  549. mask = 0;
  550. }
  551. /* Open the session in promiscuous mode */
  552. handle = pcap_open_live(dev, BUFSIZ_PLUS, PROMISC_OFF, TIMEOUT_ms, errbuf);
  553. if (handle == NULL) {
  554. fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
  555. return handle;
  556. }
  557. /* Compile and apply the filter */
  558. if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
  559. fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
  560. return handle;
  561. }
  562. if (pcap_setfilter(handle, &fp) == -1) {
  563. fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
  564. return handle;
  565. }
  566. return handle;
  567. }
  568. /**
  569. * This function returns a pcap_t for the savedfile traffic handler which
  570. * filters out traffic other than TCP
  571. *
  572. */
  573. pcap_t*
  574. set_offline_filter(char* file)
  575. {
  576. pcap_t *handle; /* Session handle */
  577. char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
  578. struct bpf_program fp; /* The compiled filter */
  579. char filter_exp[] = "tcp";
  580. bpf_u_int32 net=0; /* Our IP */
  581. /* Open savedfile */
  582. handle = pcap_open_offline(file, errbuf);
  583. if (handle == NULL) {
  584. fprintf(stderr, "Couldn't open file %s\n", errbuf);
  585. return handle;
  586. }
  587. /* Compile and apply the filter */
  588. if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
  589. fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
  590. return handle;
  591. }
  592. if (pcap_setfilter(handle, &fp) == -1) {
  593. fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
  594. return handle;
  595. }
  596. return handle;
  597. }
  598. /**
  599. * This is the callback function for pcap_loop
  600. * This function is called every time we receive a remote packet
  601. */
  602. void
  603. got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet){
  604. ether_hdr *etherhdr = NULL;
  605. tcp_hdr *tcphdr = NULL;
  606. ipv4_hdr *iphdr = NULL;
  607. unsigned int size_ip, size_tcp, size_payload;
  608. unsigned int flags = 0;
  609. /* This is to get rid of the warning */
  610. args = NULL;
  611. if(args == NULL) header = NULL;
  612. if(header == NULL) args = NULL;
  613. /* Extract and examine recieved packet headers */
  614. etherhdr = (ether_hdr*)(packet);
  615. iphdr = (ipv4_hdr *)(packet + SIZE_ETHERNET);
  616. size_ip = iphdr->ip_hl << 2;
  617. if (size_ip < 20) {
  618. printf("ERROR: Invalid IP header length: %u bytes\n", size_ip);
  619. return;
  620. }
  621. tcphdr = (tcp_hdr *)(packet + SIZE_ETHERNET + size_ip);
  622. size_tcp = tcphdr->th_off*4;
  623. if (size_tcp < 20) {
  624. printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp);
  625. return;
  626. }
  627. size_payload = ntohs(iphdr->ip_len) - (size_ip + (size_tcp));
  628. flags = tcphdr->th_flags;
  629. /* Check correct SYN-ACK expecation, if so then proceed in fixing entire schedule from relative to absolute SEQs+ACKs */
  630. if((flags == (TH_SYN|TH_ACK)) && (sched_index==1) && (tcphdr->th_ack==htonl(sched[sched_index-1].curr_lseq + 1))){
  631. unsigned int j;
  632. printf("Received Remote Packet............... [%d]\n",sched_index+1);
  633. printf("Remote Pakcet Expectation met.\nProceeding in replay....\n");
  634. //printf("SYN-ACKed Random SEQ set!\n");
  635. initial_rseq = ntohl(tcphdr->th_seq);
  636. //printf("initial_rseq: %u\n", initial_rseq);
  637. /* After we receiving the first SYN-ACK, then adjust the entire sched to be absolute rather than relative #s*/
  638. sched[1].exp_rseq = sched[1].exp_rseq + initial_rseq;
  639. for(j = 2; j<pkts_scheduled; j++){ /* Based on correctly recieving the random SEQ from the SYN-ACK packet, do the following:*/
  640. if(sched[j].local){ /* Set local ACKs for entire sched to be absolute #s*/
  641. sched[j].curr_lack = sched[j].curr_lack + initial_rseq;
  642. }
  643. else if(sched[j].remote){ /* Set remote SEQs for entire sched to be absolute #s*/
  644. sched[j].exp_rseq = sched[j].exp_rseq + initial_rseq;
  645. }
  646. }
  647. sched_index++; /* Proceed in the schedule*/
  648. return;
  649. }
  650. printf(">Received a Remote Packet\n");
  651. printf(">>Checking Expectations\n");
  652. /* Handle Remote Packet Loss */
  653. if(sched[sched_index].exp_rack > ntohl(tcphdr->th_ack)) {
  654. //printf("Remote Packet Loss! Resending Lost packet\n");
  655. sched_index=acked_index; /* Reset the schedule index back to the last correctly ACKed packet */
  656. //printf("ACKED Index = %d\n", acked_index);
  657. while(!sched[sched_index].local){
  658. sched_index++;
  659. }
  660. return;
  661. }
  662. /* Handle Local Packet Loss <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<COME BACK TO THIS<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
  663. else if((sched[sched_index].exp_rseq < ntohl(tcphdr->th_seq)) && sched[sched_index].remote){
  664. /* Resend immediate previous LOCAL packet */
  665. printf("Local Packet Loss! Resending Lost packet >> DupACK Issued!\n");
  666. sched_index=acked_index; /* Reset the schedule index back to the last correctly ACKed packet */
  667. /*sched[sched_index].sent_counter=0; Reset the re-transmission counter for this ACKed packet?*/
  668. //printf("ACKED Index = %d\n", acked_index);
  669. while(!sched[sched_index].local){
  670. sched_index++;
  671. }
  672. return;
  673. }
  674. /* No Packet Loss... Proceed Normally (if expectations are met!) */
  675. else if((tcphdr->th_seq==htonl(sched[sched_index].exp_rseq)) &&
  676. (tcphdr->th_ack==htonl(sched[sched_index].exp_rack))){
  677. printf("Received Remote Packet............... [%d]\n",sched_index+1);
  678. /* Handles differing payload size and does not trigger on unnecessary ACK + window update issues*/
  679. if((sched[sched_index].size_payload!=size_payload) && (size_payload!=0)){
  680. printf("Payload size of received packet does not meet expectations\n");
  681. /* Resent last local packet, maybe remote host behaves this time*/
  682. different_payload=true;
  683. /* Set global variable of where differing payload size is not meeting expectations*/
  684. diff_payload_index = sched_index;
  685. /*Treat this as packet loss, and attempt resetting index to resend packets where*/
  686. /* packets were received matching expectation*/
  687. sched_index=acked_index; /* Reset the schedule index back to the last correctly ACKed packet */
  688. //printf("ACKED Index = %d\n", acked_index);
  689. while(!sched[sched_index].local){
  690. sched_index++;
  691. }
  692. return;
  693. }
  694. printf("Remote Packet Expectation met.\nProceeding in replay....\n");
  695. sched_index++;
  696. acked_index = sched_index; /*Keep track correctly ACKed packet index*/
  697. }
  698. /* Global variable to keep tack of last recieved packet info */
  699. packet_keeper_rprev = packet;
  700. etherhdr_rprev = etherhdr;
  701. tcphdr_rprev = tcphdr;
  702. iphdr_rprev = iphdr;
  703. size_payload_prev = size_payload;
  704. return;
  705. }
  706. /**
  707. * This function prints out the ip address, given an in_addr struct pointer
  708. *
  709. */
  710. void
  711. printip(input_addr* IP)
  712. {
  713. printf("[%d.%d.%d.%d]\n", IP->byte1, IP->byte2, IP->byte3, IP->byte4);
  714. return;
  715. }
  716. /**
  717. * This function prints out the mac address, given a mac_addr struct pointer
  718. *
  719. */
  720. void
  721. printmac(struct mac_addr* MAC)
  722. {
  723. printf("[%x:%x:%x:%x:%x:%x]\n", MAC->byte1, MAC->byte2, MAC->byte3, MAC->byte4, MAC->byte5, MAC->byte6);
  724. return;
  725. }
  726. /**
  727. * This function compares two IPs,
  728. * returns 1 if match with local ip
  729. * returns 2 if matches with remote ip
  730. * returns 0 if no match
  731. *
  732. */
  733. int
  734. compip(input_addr* lip, input_addr* rip, input_addr* pkgip)
  735. {
  736. if((lip->byte1==pkgip->byte1)&&(lip->byte2==pkgip->byte2)&&(lip->byte3==pkgip->byte3)&&(lip->byte4==pkgip->byte4))
  737. return LOCAL_IP_MATCH;
  738. else if((rip->byte1==pkgip->byte1)&&(rip->byte2==pkgip->byte2)&&(rip->byte3==pkgip->byte3)&&(rip->byte4==pkgip->byte4))
  739. return REMOTE_IP_MATCH;
  740. else
  741. return NO_MATCH;
  742. }
  743. /**
  744. * This function sets the IP and MAC of a given interface (i.e. eth0)
  745. * into in_addr & mac_addr struct pointers
  746. *
  747. */
  748. int iface_addrs(char* iface, input_addr* ip, struct mac_addr* mac)
  749. {
  750. int s;
  751. struct ifreq buffer;
  752. s = socket(PF_INET, SOCK_DGRAM, 0);
  753. if (s < 0)
  754. return -1;
  755. memset(&buffer, 0x00, sizeof(buffer));
  756. strncpy(buffer.ifr_name, iface, sizeof(buffer.ifr_name)-1);
  757. int res;
  758. if ((res = ioctl(s, SIOCGIFADDR, &buffer)) < 0)
  759. goto done;
  760. struct in_addr localip = ((struct sockaddr_in *)&buffer.ifr_addr)->sin_addr;
  761. #if defined( WORDS_BIGENDIAN )
  762. ip->byte1 = (localip.s_addr)>>24;
  763. ip->byte2 = ((localip.s_addr)>>16)&255;
  764. ip->byte3 = ((localip.s_addr)>>8)&255;
  765. ip->byte4 = (localip.s_addr)&255;
  766. #else
  767. ip->byte4 = (localip.s_addr)>>24;
  768. ip->byte3 = ((localip.s_addr)>>16)&255;
  769. ip->byte2 = ((localip.s_addr)>>8)&255;
  770. ip->byte1 = (localip.s_addr)&255;
  771. #endif
  772. if ((res = ioctl(s, SIOCGIFHWADDR, &buffer)) < 0)
  773. goto done;
  774. mac->byte1 = buffer.ifr_hwaddr.sa_data[0];
  775. mac->byte2 = buffer.ifr_hwaddr.sa_data[1];
  776. mac->byte3 = buffer.ifr_hwaddr.sa_data[2];
  777. mac->byte4 = buffer.ifr_hwaddr.sa_data[3];
  778. mac->byte5 = buffer.ifr_hwaddr.sa_data[4];
  779. mac->byte6 = buffer.ifr_hwaddr.sa_data[5];
  780. done:
  781. close(s);
  782. return res;
  783. }
  784. /**
  785. * This function rewrites the IPs and MACs of a given packet,
  786. * creates a newfile.pcap. It returns the number of packets of the newfile.
  787. * This function only starts rewriting the newfile once it sees the first
  788. * SYN packet. This is so that the first packet in the newfile is always
  789. * the first packet to be sent.
  790. */
  791. int
  792. rewrite(input_addr* new_remoteip, struct mac_addr* new_remotemac, input_addr* myip, struct mac_addr* mymac, char* file, unsigned int new_src_port)
  793. {
  794. ether_hdr* etherhdr;
  795. ipv4_hdr *iphdr;
  796. tcp_hdr *tcphdr;
  797. input_addr local_ip;
  798. input_addr remote_ip;
  799. unsigned int size_ip;
  800. unsigned int size_tcp;
  801. char* newfile = "newfile.pcap";
  802. char ErrBuff [1024];
  803. int pkt_counter;
  804. const u_char *packet;
  805. struct pcap_pkthdr *header;
  806. pcap_dumper_t *dumpfile;
  807. input_addr sip; /* Source IP */
  808. unsigned int flags;
  809. int local_packets = 0;
  810. bool initstep1 = false; /* keep track of successful handshake step */
  811. bool warned = false;
  812. local_ip.byte1=0;
  813. local_ip.byte2=0;
  814. local_ip.byte3=0;
  815. local_ip.byte4=0;
  816. remote_ip.byte1=0;
  817. remote_ip.byte2=0;
  818. remote_ip.byte3=0;
  819. remote_ip.byte4=0;
  820. pcap_t *pcap = set_offline_filter(file);
  821. if (!pcap){
  822. fprintf (stderr, "Cannot open PCAP file '%s' for reading\n", file);
  823. fprintf(stderr, "%s\n",ErrBuff);
  824. return PCAP_OPEN_ERROR;
  825. }
  826. dumpfile = pcap_dump_open(pcap, newfile);
  827. if (!dumpfile) {
  828. fprintf (stderr, "Cannot open PCAP file '%s' for writing\n", newfile);
  829. return PCAP_OPEN_ERROR;
  830. }
  831. /*Modify each packet's IP & MAC based on the passed args then do a checksum of each packet*/
  832. for (pkt_counter = 0; pcap_next_ex(pcap, &header, &packet) > 0; pkt_counter++){
  833. if (!warned && header->len > header->caplen) {
  834. fprintf(stderr, "warning: packet capture truncated to %d byte packets\n",
  835. header->caplen);
  836. warned = true;
  837. }
  838. etherhdr = (ether_hdr*)(packet);
  839. iphdr = (ipv4_hdr *)(packet + SIZE_ETHERNET);
  840. size_ip = iphdr->ip_hl << 2;
  841. if (size_ip < 20) {
  842. printf("ERROR: Invalid IP header length: %u bytes\n", size_ip);
  843. return ERROR;
  844. }
  845. tcphdr = (tcp_hdr *)(packet + SIZE_ETHERNET + size_ip);
  846. size_tcp = tcphdr->th_off*4;
  847. if (size_tcp < 20) {
  848. printf("ERROR: Invalid TCP header length: %u bytes\n", size_tcp);
  849. return ERROR;
  850. }
  851. /* payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp); */
  852. sip = iphdr->ip_src;
  853. flags = tcphdr->th_flags;
  854. /* set IPs who's local and who's remote based on the SYN flag */
  855. if(flags == TH_SYN){
  856. local_ip = iphdr->ip_src;
  857. remote_ip = iphdr->ip_dst;
  858. initstep1 = true; /* This flag is set to signify the first encounter of the SYN within the pacp*/
  859. }
  860. if(compip(&local_ip, &remote_ip, &sip)==LOCAL_IP_MATCH){
  861. /* Set the source MAC */
  862. etherhdr->ether_shost[0] = mymac->byte1;
  863. etherhdr->ether_shost[1] = mymac->byte2;
  864. etherhdr->ether_shost[2] = mymac->byte3;
  865. etherhdr->ether_shost[3] = mymac->byte4;
  866. etherhdr->ether_shost[4] = mymac->byte5;
  867. etherhdr->ether_shost[5] = mymac->byte6;
  868. /* Set the source IP */
  869. iphdr->ip_src = *myip;
  870. /* Set the destination IP */
  871. iphdr->ip_dst = *new_remoteip;
  872. /* Set the destination MAC */
  873. etherhdr->ether_dhost[0] = new_remotemac->byte1;
  874. etherhdr->ether_dhost[1] = new_remotemac->byte2;
  875. etherhdr->ether_dhost[2] = new_remotemac->byte3;
  876. etherhdr->ether_dhost[3] = new_remotemac->byte4;
  877. etherhdr->ether_dhost[4] = new_remotemac->byte5;
  878. etherhdr->ether_dhost[5] = new_remotemac->byte6;
  879. /* This is to change the source port, whether it is specified as random or as a port # by the user */
  880. tcphdr->th_sport = htons(new_src_port);
  881. }
  882. else if(compip(&local_ip, &remote_ip, &sip)==REMOTE_IP_MATCH){
  883. /* Set the destination MAC */
  884. etherhdr->ether_dhost[0] = mymac->byte1;
  885. etherhdr->ether_dhost[1] = mymac->byte2;
  886. etherhdr->ether_dhost[2] = mymac->byte3;
  887. etherhdr->ether_dhost[3] = mymac->byte4;
  888. etherhdr->ether_dhost[4] = mymac->byte5;
  889. etherhdr->ether_dhost[5] = mymac->byte6;
  890. /* Set the destination IP */
  891. iphdr->ip_dst = *myip;
  892. /* Set the source IP */
  893. iphdr->ip_src = *new_remoteip;
  894. /* Set the source MAC */
  895. etherhdr->ether_shost[0] = new_remotemac->byte1;
  896. etherhdr->ether_shost[1] = new_remotemac->byte2;
  897. etherhdr->ether_shost[2] = new_remotemac->byte3;
  898. etherhdr->ether_shost[3] = new_remotemac->byte4;
  899. etherhdr->ether_shost[4] = new_remotemac->byte5;
  900. etherhdr->ether_shost[5] = new_remotemac->byte6;
  901. /* This is to change the source port, whether it is specified as random or as a port # by the user */
  902. tcphdr->th_dport = htons(new_src_port);
  903. }
  904. /*Calculate & fix checksum for newly edited-packet*/
  905. fix_all_checksum_liveplay(iphdr);
  906. if(initstep1){ /*only start rewriting new pcap with SYN packets on wards*/
  907. local_packets ++;
  908. pcap_dump((u_char *)dumpfile, header, packet);
  909. }
  910. } /* end of while loop */
  911. pcap_close (pcap);
  912. pcap_dump_close(dumpfile);
  913. return local_packets;
  914. }
  915. /**
  916. * This function extracts the MAC address (from command line format
  917. * and sets the mac_addr struct)
  918. *
  919. */
  920. int
  921. extmac(char* new_rmac_ptr, struct mac_addr* new_remotemac)
  922. {
  923. u_int8_t new_rmac[6];
  924. if (sscanf (new_rmac_ptr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &new_rmac[0], &new_rmac[1],
  925. &new_rmac[2], &new_rmac[3], &new_rmac[4], &new_rmac[5]) != 6)
  926. return ERROR;
  927. new_remotemac->byte1 = (unsigned char)new_rmac[0];
  928. new_remotemac->byte2 = (unsigned char)new_rmac[1];
  929. new_remotemac->byte3 = (unsigned char)new_rmac[2];
  930. new_remotemac->byte4 = (unsigned char)new_rmac[3];
  931. new_remotemac->byte5 = (unsigned char)new_rmac[4];
  932. new_remotemac->byte6 = (unsigned char)new_rmac[5];
  933. return SUCCESS;
  934. }
  935. /**
  936. * This function extracts the IP address (from command line format
  937. * and sets the in_addr struct)
  938. *
  939. */
  940. int
  941. extip(char *ip_string, input_addr* new_remoteip)
  942. {
  943. struct in_addr addr;
  944. if (inet_aton(ip_string, &addr) == 0)
  945. return ERROR;
  946. #if defined( WORDS_BIGENDIAN )
  947. new_remoteip->byte4 = (unsigned char)addr.s_addr & 0xff;
  948. new_remoteip->byte3 = (unsigned char)(addr.s_addr >> 8) & 0xff;
  949. new_remoteip->byte2 = (unsigned char)(addr.s_addr >> 16) & 0xff;
  950. new_remoteip->byte1 = (unsigned char)(addr.s_addr >> 24) & 0xff;
  951. #else
  952. new_remoteip->byte1 = (unsigned char)addr.s_addr & 0xff;
  953. new_remoteip->byte2 = (unsigned char)(addr.s_addr >> 8) & 0xff;
  954. new_remoteip->byte3 = (unsigned char)(addr.s_addr >> 16) & 0xff;
  955. new_remoteip->byte4 = (unsigned char)(addr.s_addr >> 24) & 0xff;
  956. #endif
  957. return SUCCESS;
  958. }
  959. /**
  960. * This function calls all the checksum function given the IP Header
  961. * and edits the checksums fixing them appropriately
  962. *
  963. */
  964. int
  965. fix_all_checksum_liveplay(ipv4_hdr *iphdr){
  966. int ret1 = 0, ret2 = 0;
  967. /*Calculate TCP Checksum*/
  968. ret2 = do_checksum_liveplay((u_char *) iphdr,iphdr->ip_p, ntohs(iphdr->ip_len) - (iphdr->ip_hl << 2));
  969. if(ret2==-1){
  970. printf("*******An Error Occurred calculating TCP Checksum*******\n");
  971. return -1;
  972. }
  973. /*Calculate IP Checksum*/
  974. ret1 = do_checksum_liveplay((u_char *) iphdr, IPPROTO_IP, ntohs(iphdr->ip_len));
  975. if(ret1==-1){
  976. printf("*******An Error Occurred calculating IP Checksum*******\n");
  977. return -1;
  978. }
  979. return 0;
  980. }
  981. /************************************************************************************/
  982. /*[copied from Aaron Turnor's checksum.c, but ommitting tcpedit_t structs] */
  983. /*[The following functions have been slightly modified to be integrated with tcpliveplay code structure] */
  984. /**
  985. * This code re-calcs the IP and Layer 4 checksums
  986. * the IMPORTANT THING is that the Layer 4 header
  987. * is contiguious in memory after *ip_hdr we're actually
  988. * writing to the layer 4 header via the ip_hdr ptr.
  989. * (Yes, this sucks, but that's the way libnet works, and
  990. * I was too lazy to re-invent the wheel.
  991. * Returns 0 on sucess, -1 on error
  992. */
  993. /**
  994. * Returns -1 on error and 0 on success, 1 on warn
  995. */
  996. int
  997. do_checksum_liveplay(u_int8_t *data, int proto, int len) {
  998. ipv4_hdr *ipv4;
  999. tcp_hdr *tcp;
  1000. int ip_hl;
  1001. volatile int sum; // <-- volatile works around a PPC g++ bug
  1002. sum = 0;
  1003. ipv4 = NULL;
  1004. ipv4 = (ipv4_hdr *)data;
  1005. ip_hl = ipv4->ip_hl << 2;
  1006. switch (proto) {
  1007. case IPPROTO_TCP:
  1008. tcp = (tcp_hdr *)(data + ip_hl);
  1009. #ifdef STUPID_SOLARIS_CHECKSUM_BUG
  1010. tcp->th_sum = tcp->th_off << 2;
  1011. return (TCPEDIT_OK);
  1012. #endif
  1013. tcp->th_sum = 0;
  1014. /* Note, we do both src & dst IP's at the same time, that's why the
  1015. * length is 2x a single IP
  1016. */
  1017. sum = do_checksum_math_liveplay((u_int16_t *)&ipv4->ip_src, 8);
  1018. sum += ntohs(IPPROTO_TCP + len);
  1019. sum += do_checksum_math_liveplay((u_int16_t *)tcp, len);
  1020. tcp->th_sum = CHECKSUM_CARRY(sum);
  1021. break;
  1022. case IPPROTO_IP:
  1023. ipv4->ip_sum = 0;
  1024. sum = do_checksum_math_liveplay((u_int16_t *)data, ip_hl);
  1025. ipv4->ip_sum = CHECKSUM_CARRY(sum);
  1026. break;
  1027. default:
  1028. printf("Unsupported protocol for checksum:\n");
  1029. return TCPEDIT_WARN;
  1030. }
  1031. return TCPEDIT_OK;
  1032. }
  1033. /**
  1034. * code to do a ones-compliment checksum
  1035. */
  1036. int
  1037. do_checksum_math_liveplay(u_int16_t *data, int len)
  1038. {
  1039. int sum = 0;
  1040. union {
  1041. u_int16_t s;
  1042. u_int8_t b[2];
  1043. } pad;
  1044. while (len > 1) {
  1045. sum += *data++;
  1046. len -= 2;
  1047. }
  1048. if (len == 1) {
  1049. pad.b[0] = *(u_int8_t *)data;
  1050. pad.b[1] = 0;
  1051. sum += pad.s;
  1052. }
  1053. return (sum);
  1054. }