Advertisement
JamieTheTrainie

Untitled

Jun 22nd, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.28 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import socket,sys
  3. import time
  4. from struct import *
  5. from collections import OrderedDict
  6. import os
  7. import commands
  8. import signal
  9. import optparse
  10. #define ETH_P_ALL 0x0003
  11.  
  12.  
  13. class bgcolors:
  14. HEADER = '\033[95m'
  15. OKBLUE = '\033[94m'
  16. OKGREEN = '\033[92m'
  17. WARNING = '\033[93m'
  18. FAIL = '\033[91m'
  19. ENDC = '\033[0m'
  20. BOLD = '\033[1m'
  21. UNDERLINE = '\033[4m'
  22.  
  23. header = bgcolors.BOLD+bgcolors.OKGREEN+"""
  24. ------ ----- -------- -----------
  25. | | | | | | | |
  26. | 0 | | ___ | | 0 | | ~ |
  27. | __| || || |------| -----||----
  28. | | || || | | \ \ ||
  29. | | ||___|| | | \ \ ||
  30. |__| |_____| | | \ \ ||
  31. -- -- ||
  32. |____ _____ ______
  33. | ) | | | -----
  34. | 0 ) | --- | |
  35. | ) | | | | |--|
  36. | ) | --- | | |------
  37. __| |_____| |__|_____|
  38. """+"\n"+"-"*55+"\n"+bgcolors.ENDC
  39. parser = optparse.OptionParser(header+"usage: %prog -t <time for sniff in minutes>")
  40. parser.add_option('-t','--time',dest='usertime',type='int', help='Time to sniff network in minutes (Use 0 for infinite wait)')
  41. (options,args) = parser.parse_args()
  42.  
  43.  
  44. if(options.usertime == None):
  45. print parser.usage
  46. sys.exit(0)
  47.  
  48.  
  49. timeforsniff=options.usertime
  50.  
  51. global threewayhandshake,waiting,fullscandb,halfscandb,xmasscandb,nullscandb,finscandb,scannedports,blacklist
  52.  
  53. blacklist = []
  54. fullscandb = {}
  55. halfscandb = {}
  56. xmasscandb = {}
  57. nullscandb = {}
  58. finscandb = {}
  59. waiting = []
  60. threewayhandshake = []
  61. scannedports = {}
  62.  
  63. LANip = commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
  64.  
  65.  
  66. def convert(dec):
  67. final = []
  68. flags = OrderedDict([("128","CWR"),("64","ECE"),("32","URG"),("16","ACK"),("8","PSH"),("4","RST"),("2","SYN"),("1","FIN")])
  69. for i in flags.keys():
  70. if(dec>=int(i)):
  71. dec = dec-int(i)
  72. final.append(flags[i])
  73. return final
  74.  
  75. def eth_addr (a) :
  76. b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5]))
  77. return b
  78.  
  79. def time_diff(outside,vaxt=5):
  80. netice = (time.time()-int(outside))/60
  81. if(netice>=vaxt):
  82. return True
  83. def show_ports(signum,frm):
  84. for ips in scannedports:
  85. for single in scannedports[ips]:
  86. while(scannedports[ips].count(single)!=1):
  87. scannedports[ips].remove(single)
  88. print "\n\n"
  89.  
  90. for ip in blacklist:
  91. if(scannedports.has_key(str(ip)) and ip!=LANip):
  92. print "Attacker from ip "+ip+" scanned ["+ ",".join(scannedports[ip])+"] ports."
  93.  
  94.  
  95. def threewaycheck(sip,dip,sport,dport,seqnum,acknum,flags):
  96. data = sip+":"+str(sport)+"->"+dip+":"+str(dport)+"_"+str(seqnum)+"_"+str(acknum)+"_"+"/".join(flags)
  97. if("SYN" in flags and len(flags)==1):
  98. if(seqnum>0 and acknum==0):
  99. waiting.append(str(seqnum)+"_"+str(acknum)+"_"+sip+":"+str(sport)+"->"+dip+":"+str(dport))
  100. elif("SYN" in flags and "ACK" in flags and len(flags)==2):
  101. for i in waiting:
  102. pieces = i.split("_")
  103. ack_old = pieces[1]
  104. seq_old = pieces[0]
  105. if(acknum==int(seq_old)+1):
  106. del waiting[waiting.index(i)]
  107. waiting.append(str(seqnum)+"_"+str(acknum)+"_"+sip+":"+str(sport)+"->"+dip+":"+str(dport))
  108. break
  109.  
  110. elif("ACK" in flags and len(flags)==1):
  111. for i in waiting:
  112. pieces = i.split("_")
  113. ack_old = pieces[1]
  114. seq_old = pieces[0]
  115. if(seqnum==int(ack_old) and acknum==int(seq_old)+1):
  116. index_i = waiting.index(i)
  117. del waiting[index_i]
  118. threewayhandshake.append(sip+":"+str(sport)+"->"+dip+":"+str(dport))
  119. break
  120.  
  121. def scancheck(sip,dip,sport,dport,seqnum,acknum,flags):
  122. global data,dataforthreewaycheck,dbdata,reverse
  123. data = sip+":"+str(sport)+"->"+dip+":"+str(dport)+"_"+str(seqnum)+"_"+str(acknum)+"_"+"/".join(flags)
  124. dataforthreewaycheck = sip+":"+str(sport)+"->"+dip+":"+str(dport)
  125. revthreeway = dip+":"+str(dport)+"->"+sip+":"+str(sport)
  126. dbdata = sip+"->"+dip
  127. reverse = dip+"->"+sip
  128. if(halfconnectscan(sip,dip,sport,dport,seqnum,acknum,flags)):
  129. returned = halfconnectscan(sip,dip,sport,dport,seqnum,acknum,flags)
  130. if(isinstance(returned,(str))):
  131. print returned
  132. else:
  133. print bgcolors.BOLD+bgcolors.OKBLUE+revthreeway+bgcolors.ENDC+bgcolors.WARNING+bgcolors.BOLD+" Port Scanning Detected: [Style not Defined]:Attempt to connect closed port!"+bgcolors.ENDC
  134. elif(fullconnectscan(sip,dip,sport,dport,seqnum,acknum,flags)):
  135. returned = fullconnectscan(sip,dip,sport,dport,seqnum,acknum,flags)
  136. if(isinstance(returned,(str))):
  137. print returned
  138. else:
  139. file_name = "blocklist.txt"
  140. new_string = dataforthreewaycheck
  141. opened_file = open(file_name, 'a')
  142. opened_file.write("%r\n" %new_string)
  143. opened_file.close()
  144. print bgcolors.BOLD+bgcolors.OKBLUE+revthreeway+bgcolors.ENDC+bgcolors.WARNING+bgcolors.BOLD+" Port Scanning Detected: [Style not Defined]:Attempt to connect closed port!"+bgcolors.ENDC
  145. elif(xmasscan(sip,dip,sport,dport,seqnum,acknum,flags)):
  146. print bgcolors.BOLD+bgcolors.OKBLUE+dataforthreewaycheck+bgcolors.ENDC +bgcolors.BOLD+bgcolors.FAIL+ " => [Runtime Detection:] XMAS scan detected!"+bgcolors.ENDC
  147. elif(finscan(sip,dip,sport,dport,seqnum,acknum,flags)):
  148. print bgcolors.BOLD+bgcolors.OKBLUE+ dataforthreewaycheck+bgcolors.ENDC+ bgcolors.BOLD+bgcolors.FAIL+" => [Runtime Detection:] FIN scan detected!"+bgcolors.ENDC
  149. elif(nullscan(sip,dip,sport,dport,seqnum,acknum,flags)):
  150. print bgcolors.BOLD+bgcolors.OKBLUE+dataforthreewaycheck +bgcolors.ENDC+bgcolors.BOLD+bgcolors.FAIL+ " => [Runtime Detection:] NULL scan detected!"+bgcolors.ENDC
  151.  
  152.  
  153. def fullconnectscan(sip,dip,sport,dport,seqnum,acknum,flags):
  154. if(scannedports.has_key(dip)):
  155. scannedports[dip].append(str(sport))
  156. else:
  157. scannedports[dip] = []
  158. scannedports[dip].append(str(sport))
  159.  
  160. if(dataforthreewaycheck in threewayhandshake):
  161. if("ACK" in flags and "RST" in flags and len(flags)==2):
  162. if(fullscandb.has_key(dbdata)):
  163. counter = int(fullscandb[dbdata])
  164. if(counter>=3):
  165.  
  166. if(str(dip) not in blacklist):
  167. blacklist.append(str(dip))
  168. return bgcolors.BOLD+bgcolors.OKBLUE+ dip+":"+str(dport)+"->"+sip+":"+str(sport)+bgcolors.ENDC+ bgcolors.BOLD+bgcolors.FAIL+" => [Runtime Detection:] Full connect scan detected!"+bgcolors.ENDC
  169. else:
  170. counter = counter + 1
  171. fullscandb[dbdata] = str(counter)
  172. else:
  173. counter = 0
  174. fullscandb[dbdata] = str(counter)
  175.  
  176. else:
  177. if("SYN" in flags and len(flags)==1):
  178. if(seqnum>0 and acknum==0):
  179. fullscandb[dbdata+"_SYN"] = str(seqnum)+"_"+str(acknum)+"_"+str(sport)+"_"+str(dport)
  180.  
  181. elif("RST" in flags and "ACK" in flags and len(flags)==2):
  182. if(fullscandb.has_key(dip+"->"+sip+"_SYN")):
  183. manage = fullscandb[dip+"->"+sip+"_SYN"]
  184. pieces = manage.split("_")
  185. old_acknum = int(pieces[1])
  186. old_seqnum = int(pieces[0])
  187. if(seqnum==0 and acknum==old_seqnum+1):
  188. if(fullscandb.has_key(dbdata)):
  189. counter = int(fullscandb[dbdata])
  190. if(counter>=3):
  191.  
  192. if(str(dip) not in blacklist):
  193. blacklist.append(str(dip))
  194. return True
  195. else:
  196. counter = counter + 1
  197. fullscandb[dbdata] = str(counter)
  198. else:
  199. counter = 0
  200. fullscandb[dbdata] = str(counter)
  201. return False
  202.  
  203. def halfconnectscan(sip,dip,sport,dport,seqnum,acknum,flags):
  204. if(scannedports.has_key(dip)):
  205. scannedports[dip].append(str(sport))
  206. else:
  207. scannedports[dip] = []
  208. scannedports[dip].append(str(sport))
  209.  
  210. if("SYN" in flags and seqnum>0 and acknum==0 and len(flags)==1):
  211. halfscandb[dbdata+"_"+str(seqnum)] = dbdata+"_SYN_ACK_"+str(seqnum)+"_"+str(acknum)
  212. elif("RST" in flags and "ACK" in flags and len(flags)==2):
  213. if(halfscandb.has_key(reverse+"_"+str(acknum-1))):
  214. del halfscandb[reverse+"_"+str(acknum-1)]
  215. if(str(dip) not in blacklist):
  216. blacklist.append(str(dip))
  217.  
  218. return True
  219. elif("SYN" in flags and "ACK" in flags and len(flags)==2):
  220. if(halfscandb.has_key(reverse+"_"+str(acknum-1))):
  221. del halfscandb[reverse+"_"+str(acknum-1)]
  222. halfscandb[reverse+"_"+str(acknum)] = dbdata+"_RST_"+str(seqnum)+"_"+str(acknum)
  223. elif("RST" in flags and len(flags)==1):
  224. if(halfscandb.has_key(dbdata+"_"+str(seqnum))):
  225. if(str(dip) not in blacklist):
  226. blacklist.append(str(dip))
  227.  
  228. return bgcolors.BOLD+bgcolors.OKBLUE+sip+":"+str(sport)+"->"+dip+":"+str(dport) +bgcolors.ENDC+ bgcolors.BOLD+bgcolors.FAIL+" => [Runtime Detection:] Half connect(SYN scan) scan detected!"+bgcolors.ENDC
  229. return False
  230.  
  231.  
  232.  
  233.  
  234. def xmasscan(sip,dip,sport,dport,seqnum,acknum,flags):
  235. if(scannedports.has_key(dip)):
  236. scannedports[dip].append(str(sport))
  237. else:
  238. scannedports[dip] = []
  239. scannedports[dip].append(str(sport))
  240.  
  241. if("FIN" in flags and "URG" in flags and "PSH" in flags and len(flags)==3):
  242.  
  243. if(str(sip) not in blacklist):
  244. blacklist.append(str(sip))
  245. return True
  246. return False
  247.  
  248.  
  249. def finscan(sip,dip,sport,dport,seqnum,acknum,flags):
  250. if(scannedports.has_key(dip)):
  251. scannedports[dip].append(str(sport))
  252. else:
  253. scannedports[dip] = []
  254. scannedports[dip].append(str(sport))
  255.  
  256. if(dataforthreewaycheck not in threewayhandshake):
  257. if("FIN" in flags and len(flags)==1):
  258. if(str(sip) not in blacklist):
  259. blacklist.append(str(sip))
  260. return True
  261. return False
  262.  
  263.  
  264. def nullscan(sip,dip,sport,dport,seqnum,acknum,flags):
  265. if(scannedports.has_key(dip)):
  266. scannedports[dip].append(str(sport))
  267. else:
  268. scannedports[dip] = []
  269. scannedports[dip].append(str(sport))
  270. if(len(flags)==0):
  271. if(str(sip) not in blacklist):
  272. blacklist.append(str(sip))
  273. return True
  274. return False
  275.  
  276.  
  277.  
  278.  
  279. def ackscan(sip,dip,sport,dport,seqnum,acknum,flags):
  280. if(scannedports.has_key(dip)):
  281. scannedports[dip].append(str(sport))
  282. else:
  283. scannedports[dip] = []
  284. scannedports[dip].append(str(sport))
  285.  
  286. if(dataforthreewaycheck not in threewayhandshake):
  287. if("ACK" in flags and len(flags)==1):
  288.  
  289. if(str(sip) not in blacklist):
  290. blacklist.append(str(sip))
  291. return True
  292. return False
  293.  
  294.  
  295.  
  296. if(os.name=='nt'):
  297. print "[*]Doesn't work on Windows machine."
  298. sys.exit()
  299.  
  300. try:
  301. s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
  302. except socket.error , msg:
  303. print '[*]Socket can\'t be created! Error Code : ' + str(msg[0]) + ' Error Message ' + msg[1]
  304. sys.exit()
  305. except AttributeError:
  306. print "[*]Windows OS doesn't support AF_PACKET."
  307. sys.exit()
  308.  
  309. now = time.time()
  310. protocol_numb = {"1":"ICMP","6":"TCP","17":"UDP"}
  311.  
  312. print header
  313. print bgcolors.BOLD+bgcolors.OKGREEN
  314. print "-"*55
  315. print "Port Scanner Detector v1"
  316. print "-"*55
  317. print "Packet Capturing Started..."
  318. print "-"*55
  319. print ""
  320. print bgcolors.ENDC
  321.  
  322. while True:
  323. if(timeforsniff!=0):
  324. if(time_diff(now,timeforsniff)):
  325. break
  326. try:
  327. packet = s.recvfrom(65565)
  328. packet = packet[0]
  329. eth_length = 14
  330. eth_header = packet[:eth_length]
  331. eth = unpack('!6s6sH' , eth_header)
  332. eth_protocol = socket.ntohs(eth[2])
  333. dest_mac = eth_addr(packet[0:6])
  334. source_mac = eth_addr(packet[6:12])
  335. except:
  336. pass
  337.  
  338. if eth_protocol == 8 :
  339. ip_header = packet[eth_length:20+eth_length]
  340.  
  341. iph = unpack('!BBHHHBBH4s4s' , ip_header)
  342.  
  343. version_ihl = iph[0]
  344. version = version_ihl >> 4
  345. ihl = version_ihl & 0xF
  346.  
  347. iph_length = ihl * 4
  348. protocol = iph[6]
  349. if(str(iph[6]) not in protocol_numb.keys()):
  350. protocol_name = str(iph[6])
  351. else:
  352. protocol_name = protocol_numb[str(iph[6])]
  353. s_addr = socket.inet_ntoa(iph[8]);
  354. d_addr = socket.inet_ntoa(iph[9]);
  355. timestamp = time.time();
  356. elave=None
  357.  
  358.  
  359. #TCP protocol
  360. if protocol == 6 :
  361. t = iph_length + eth_length
  362. tcp_header = packet[t:t+20]
  363. tcph = unpack('!HHLLBBHHH' , tcp_header)
  364.  
  365. source_port = tcph[0]
  366. dest_port = tcph[1];
  367. seq_numb = tcph[2]
  368. dest_numb = tcph[3]
  369. tcp_flags = convert(tcph[5])
  370. testdata = s_addr+":"+str(source_port)+"->"+d_addr+":"+str(dest_port)
  371. if(testdata not in threewayhandshake):
  372. threewaycheck(s_addr,d_addr,source_port,dest_port,seq_numb,dest_numb,tcp_flags)
  373.  
  374. scancheck(s_addr,d_addr,source_port,dest_port,seq_numb,dest_numb,tcp_flags)
  375. try:
  376. signal.signal(signal.SIGINT,show_ports)
  377. except:
  378. pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement