Advertisement
Guest User

Untitled

a guest
Jul 25th, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.63 KB | None | 0 0
  1. from scapy.all import *
  2. import datetime
  3. WIN_SIZE = 65535
  4.  
  5.  
  6. history_table=open("history_table.txt","r+")
  7.  
  8. def arp_req(IPadr):
  9. """ Returns MAC address of given IP - CHECKED """
  10. packet = ARP(pdst = IPadr)
  11. reply = sr1(packet).hwsrc
  12. return reply
  13.  
  14. def dns_req(URL):
  15. """ Returns IP from URL - CHECKED """
  16. packet = IP(dst="8.8.8.8")/UDP()/DNS(rd = 1, qd = DNSQR(qname = URL))
  17. try:
  18. reply = sr1(packet, verbose=0)[DNS].an[DNSRR].rdata
  19. except:
  20. print "IP does not exist."
  21. return None
  22. return reply
  23.  
  24. def ret_from_cache(URL):
  25. """ Returns IP from URL from the DNS table if exists, else returns 0 """
  26. DNS_Table = open("DNS_Table.txt", "w+")
  27. DNS_Table_Text = DNS_Table.read()
  28.  
  29. # If found
  30. if URL in DNS_Table_Text:
  31. tableLines = DNS_Table_Text.split("\n")
  32. for line in tableLines:
  33. if URL in line:
  34. currvaluelist = line.split(",")
  35. DNS_Table.close()
  36. return currvaluelist[1]
  37.  
  38. # If not found
  39. else:
  40. DNS_Table.close()
  41. return False
  42.  
  43. def dns_flush():
  44. """ Clears DNS Table file - UNCHECKED but most likely working """
  45. DNS_Table = open("DNS_Table.txt", "a+")
  46. DNS_Table.seek(0)
  47. DNS_Table.truncate()
  48. return 0
  49.  
  50. def update_history(url):
  51. """ Updates the history table file by adding the URL and time of visiting """
  52. time_now=datetime.datetime.now()
  53. history_table.write(str(url) + "," + str(time_now) + "\n")
  54. return 0
  55.  
  56. def clear_history():
  57. """ Removes all data from history table """
  58. history_table.seek(0)
  59. history_table.truncate()
  60. return 0
  61.  
  62. def remove_from_history(url):
  63. history_table.seek(0)
  64. lines=history_table.readlines()
  65. history_table.seek(0)
  66.  
  67. for x in lines:
  68. if url not in x:
  69. history_table.write(x)
  70. history_table.truncate()
  71. history_table.seek(0)
  72. return 0
  73.  
  74. def find_ip(URL):
  75. IPaddr = ret_from_cache(URL) # Looking for ip in table.
  76. if IPaddr is False: # If IP wasn't found in the table.
  77. IPaddr = dns_req(URL)
  78. if IPaddr == None: # If failed to get IP
  79. return None
  80.  
  81. update_cache(URL, IPaddr) # Updating cache file
  82. return IPaddr
  83. else: # If IP was found in the table
  84. return IPaddr
  85.  
  86. def menu():
  87. """ Prints menu and returns user's selection """
  88. choice=0
  89. print "Select one of the options:\n1. History\n2. Visit a site\n3. Exit\n"
  90. while True:
  91. try:
  92. choice = input("Selection:")
  93. except:
  94. print "Invalid choice!"
  95. continue
  96. if choice in range(1, 4):
  97. break
  98. else:
  99. print "Invalid input. Try again.\n"
  100. return choice
  101.  
  102. def history_menu():
  103. """ Prints menu and returns selection value """
  104. print " Menu"
  105. print "1. Show History"
  106. print "2. Clear history"
  107. print "3. Remove a specific record"
  108. while 1:
  109. try:
  110. selection = input("Selection: ")
  111. except:
  112. print "Invalid input. Try again.\n"
  113. continue
  114.  
  115. if selection in range(1,4):
  116. return selection
  117. else:
  118. print ("Invalid input. Try again.\n")
  119.  
  120. def make_get(URL):
  121. """ Create an HTTP GET message to the URL site, send it and save the data to an html file """
  122.  
  123. ''' Getting IP '''
  124. IPaddr = find_ip(URL)
  125. print IPaddr
  126. if IPaddr is None:
  127. return None
  128. update_history(URL)
  129.  
  130.  
  131. ''' Three way handshake '''
  132. # Syn
  133. sport = random.randint(10000, 16000)
  134. seq = random.randint(1000, 200000)
  135. syn_pack = IP(dst=IPaddr)/TCP(dport=80, seq=seq, flags='S', sport=sport)
  136.  
  137. # Syn Ack
  138. synack_pack = sr1(syn_pack, verbose=0, timeout=20)
  139. recv_seq = synack_pack[TCP].seq
  140. current_seq = seq+1
  141. current_ack = recv_seq+1
  142. print "Syn sent"
  143.  
  144. # Ack
  145. ack_pack = IP(dst=IPaddr) / TCP(dport=80, seq=current_seq, ack=current_ack, flags='A', sport=sport)
  146. synack_pack = send(ack_pack, verbose=0)
  147. print "Syn ack sent"
  148.  
  149.  
  150.  
  151. ''' HTTP GET Packet '''
  152. httpget = 'GET / HTTP/1.1\r\nHost: ' + URL + '\r\nConnection: keep-alive\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: \r\nAccept-Language: en-US,en;q=0.8\r\n\r\n'
  153. send_packet = IP(dst=IPaddr) / TCP(dport=80,window=WIN_SIZE, seq=current_seq, ack=current_ack, flags='AP', sport=sport) / Raw(httpget)
  154.  
  155.  
  156. ''' Output '''
  157. out = open("output.html","w")
  158. fin = False
  159. current_seq = current_seq + len(httpget)
  160.  
  161.  
  162. # Loop will recieve packets until it gets a FINISH flag, meaning the communication is done.
  163. while not fin:
  164. get_ans = sr(send_packet, verbose=0, timeout=1, multi=1) # Sending packet
  165. all_ans = get_ans[0]
  166. current_rcvd_len = 0
  167. print all_ans.show()
  168.  
  169. # loop through all answers and check which has a Raw part
  170. for ans in all_ans:
  171. packet = ans[1]
  172.  
  173. ''' Check if FIN flag was sent '''
  174. if TCP in packet:
  175. flags = packet.sprintf("%TCP.flags%") # Stores the TCP flags in a string
  176. if 'F' in flags: # Server has sent FIN flag
  177. print "Got FIN."
  178. fin = True
  179.  
  180. ''' Writing raw data '''
  181. if Raw in packet: # If packet contains raw.
  182. raw_data = str(packet[Raw]) # Raw string data in raw_data.
  183. current_rcvd_len = len(packet[Raw])
  184. print "Got raw, len: " + str(current_rcvd_len)
  185.  
  186. # Writing after headers
  187. end_of_http_headers = raw_data.find("\r\n\r\n") # Find the end of the packet's header.
  188. if end_of_http_headers > 1:
  189. start_offset = end_of_http_headers
  190. out.write(raw_data[start_offset:]) # Writing the data after the headers
  191.  
  192. ''' Ack to the server '''
  193. current_rcvd_seq = packet[TCP].seq # Current seq
  194. ack_to_send = current_rcvd_seq + current_rcvd_len # The ack that will be sent is the current length of the data plus the ack sent
  195. send_packet = IP(dst=IPaddr) / TCP(dport=80, window=WIN_SIZE, seq=current_seq, ack=ack_to_send, flags='A', sport=sport)
  196.  
  197. out.close()
  198.  
  199. def update_cache(URL, IPnew):
  200. """ Adds URL to the DNS_Table """
  201. time_now=datetime.datetime.now()
  202. DNS_Table = open("DNS_Table.txt", "a+")
  203. print str(URL) + "," + str(IPnew) + "," + str(time_now.hour)+":"+str(time_now.minute) + "\n" # Debug
  204.  
  205. DNS_Table.write(str(URL) + "," + str(IPnew) + "," + str(time_now.hour)+":"+str(time_now.minute) + "\n")
  206. DNS_Table.close()
  207. return 0
  208.  
  209. def main():
  210. selection = 0
  211. history_selection = 0
  212. while selection != 3:
  213. selection = menu()
  214.  
  215. if selection == 1: # History
  216. history_selection = history_menu()
  217. if history_selection == 1: # Read history
  218. history_table.seek(0)
  219. print history_table.read()
  220.  
  221. elif history_selection == 2: # Clear history
  222. clear_history()
  223.  
  224. elif history_selection == 3: # Remove a specific record
  225. remove_from_history(str(raw_input("Enter URL to remove: ")))
  226.  
  227. else:
  228. print "Invalid selection!"
  229.  
  230. elif selection == 2: # Visit a site
  231. make_get(raw_input("Enter URL to visit: "))
  232.  
  233. print "Goodbye!"
  234. history_table.close()
  235. return 0
  236.  
  237. main() # Calling main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement