Source Code for network and port scanner, TRW algorithm, and reduction method implementations.

bruteforce_filteredbyfiles.py 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #Version 2 #Itera por sip /16 y cuenta numero de puertos por cada dip
  2. #hello
  3. from silk import *
  4. global_num = 2 #posicion del subnetwork. 1 implica A.x.x.x, 2 implica A.B.x.x, etc.
  5. #funcion que recibe un string del ip address y devuelve otro string hasta el subnetwork
  6. #que indica el numero de posicion
  7. def ipConversion(number, position):
  8. mystr = '.'
  9. ipadd = number.split(".")
  10. return mystr.join(ipadd[:position])
  11. #Esta funcion recorre la lista de flows, las manda por la funcion de Filter para verificar
  12. #que sean puertos no comunes, luego guarda una lista de esos flows especificos en un file
  13. #y devuelve un hash de los flows filtrados.
  14. def FilterBySIP(flows, flowHash, num):
  15. fc = 0
  16. dportHash = {}
  17. fdout = open("tmpfile%s" % num, "w")
  18. for filename in flows:
  19. for rec in silkfile_open(filename, READ):#reading the flow file
  20. fc += 1
  21. if (':' in str(rec.sip)) or (num > global_num and ipConversion(str(rec.sip), num) not in flowHash): #Si en el paso anterior se vio que no
  22. continue
  23. dip = str(rec.dip)
  24. sip = str(rec.sip)
  25. dport= rec.dport
  26. sport= rec.sport
  27. Filter(fdout, ipConversion(sip, num+1), dip, sport, dport, dportHash)
  28. fdout.write("%s:%s:%s:%s\n" % (sip, dip, sport, dport))
  29. # print fc
  30. fdout.close()
  31. return dportHash
  32. #Esta funcion recorre la lista de flows guardados en el file creado en el step anterior,
  33. #verifica que esten en el hash creado en el step anterior, las manda por la funcion de Filter para verificar
  34. #que sean puertos no comunes, luego guarda una lista de esos flows especificos en un file
  35. #y devuelve un hash de los flows filtrados.
  36. def FilterBySIPTMP(flowHash, num):
  37. dportHash = {}
  38. fdout = open("tmpfile%s" % num, "w")
  39. with open("tmpfile%s" % (num - 1), "r") as f:
  40. for flow in f:
  41. sip, dip, sport, dport = flow.split(":")
  42. #print ipConversion(sip, num)
  43. sport = int(sport)
  44. dport = int(dport)
  45. if ipConversion(sip, num) not in flowHash:
  46. continue
  47. Filter(fdout, ipConversion(sip, num+1), dip, sport, dport, dportHash)
  48. fdout.write("%s:%s:%s:%s\n" % (sip, dip, sport, dport))
  49. fdout.close()
  50. return dportHash
  51. #argumentos consisten del file con los flows, source y destination ip y puertos y
  52. #un hash vacio para guardar los source ips con la lista de puertos a donde se conecta
  53. #la funcion verifica que los puertos no sean puertos comunes, para asi agregar el flow al hash
  54. def Filter(fd, sip, dip, sport, dport, dportHash):
  55. if dport > 1024 and (sport <= 1024 or (sport >= 8000 and sport < 9000)):
  56. return
  57. if sip in dportHash:
  58. # if dip in dportHash[sip]["dips"]:
  59. # dportHash[sip]["dips"][dip] += 1
  60. # else:
  61. # dportHash[sip]["dips"][dip] = 1
  62. if dport in dportHash[sip]["dports"]:
  63. dportHash[sip]["dports"][dport] += 1
  64. #return
  65. else:
  66. dportHash[sip]["dports"][dport] = 1
  67. else:
  68. dportHash[sip] = {"dports": {}}
  69. dportHash[sip]["dips"] = {}
  70. #fd.write("%s:%s:%s:%s\n" % (sip, dip, sport, dport))
  71. def FilterBySIPFull(flowHash, num):
  72. flow_Counter=0
  73. dportHash = {}
  74. for filename in FGlob(type="all", start_date=startDate, end_date=endDate, site_config_file="/etc/silk/conf-v9/silk.conf", data_rootdir="/home/scratch/flow/rwflowpack/"):
  75. for rec in silkfile_open(filename, READ):#reading the flow file
  76. if (':' in str(rec.sip)) or (num > global_num and ipConversion(str(rec.sip), num) not in flowHash): #Si en el paso anterior se vio que no
  77. continue
  78. dip = str(rec.dip)
  79. sip = ipConversion(str(rec.sip), num+1)
  80. dport= rec.dport
  81. if sip in dportHash:
  82. if dip in dportHash[sip]:
  83. if dport in dportHash[sip][dip]:
  84. dportHash[sip][dip][dport] += 1
  85. else:
  86. dportHash[sip][dip][dport] = 1
  87. else:
  88. dportHash[sip][dip] = {dport : 1}
  89. else:
  90. dportHash[sip] = { dip: {dport: 1} }
  91. return dportHash
  92. #Hace lo mismo que la funcion FilterBySIPTMP, lo unico que esta vez no hace falta verificar los puertos
  93. #y ademas crea otro hash de los source ips con sus destination ips con sus puertos
  94. def last_step(flowHash, num):
  95. dportHash = {}
  96. with open("tmpfile%s" % (num), "r") as f:
  97. for flow in f:
  98. sip, dip, sport, dport = flow.split(":")
  99. sport = int(sport)
  100. dport = int(dport)
  101. if (':' in sip) or (num > global_num and sip not in flowHash):
  102. print sip
  103. print "Do we ever enter here?"
  104. continue
  105. if sip in dportHash:
  106. if dip in dportHash[sip]:
  107. if dport in dportHash[sip][dip]:
  108. dportHash[sip][dip][dport] += 1
  109. else:
  110. dportHash[sip][dip][dport] = 1
  111. else:
  112. dportHash[sip][dip] = {dport : 1}
  113. else:
  114. dportHash[sip] = { dip: {dport: 1} }
  115. return dportHash
  116. #Funcion que verifica que el total de puertos por cada source ip con su destination ip
  117. #sea mayor que 100. Devuelve un hash con los flows filtrados.
  118. def filter_laststep(flowhash):
  119. otherhash ={}
  120. for sips in flowhash: #se itera por todos los dip y sus counters o puertos
  121. for dips, dports in flowhash[sips].items():
  122. #print "Filter", len(dports)
  123. if len(dports) >= 100: #si la cantidad de puertos es mayor o igual a 100, nos interesan
  124. #y por lo tanto se guardan en un hash
  125. if sips in otherhash:
  126. otherhash[sips][dips] = dports
  127. else:
  128. otherhash[sips] = {dips: dports}
  129. return otherhash
  130. def main():
  131. #variable del intervalo de los flows a verificar
  132. startDate = "2018/08/01"
  133. endDate = "2018/08/31"
  134. myNum = global_num #variable que dicta la posicion del subnetwork
  135. #lista de flows total
  136. flows = FGlob(type="all", start_date=startDate, end_date=endDate, site_config_file="/etc/silk/conf-v9/silk.conf", data_rootdir="/home/scratch/flow/rwflowpack/")
  137. otherHash = {}
  138. flowHash = FilterBySIP(flows, otherHash, myNum) #hash de todos los sourceip en el subnetwork de posicion myNum con sus puertos
  139. print "Before thresh 1", len(flowHash)
  140. #Verifica source ips sospechosos por cantidad de puertos conectados
  141. #devuelve hash con los source ips filtrados
  142. for sip in flowHash:
  143. if len(flowHash[sip]["dports"]) >= 100:
  144. otherHash[sip] = flowHash[sip]
  145. print "After thresh 1", len(otherHash)
  146. while myNum <3:
  147. flowHash= FilterBySIPTMP(otherHash, myNum + 1)
  148. #print "Before thresh 2", len(flowHash)
  149. otherHash = {}
  150. for sip in flowHash: #se itera por todos los dip y sus counters o puertos
  151. if len(flowHash[sip]["dports"]) >= 100:
  152. otherHash[sip] = flowHash[sip]
  153. #print "After thresh 2", len(otherHash)
  154. myNum += 1
  155. final_hash = last_step(otherHash, myNum)
  156. #print final_hash
  157. # for sips in final_hash: #se itera por todos los dip y sus counters o puertos
  158. # for dips, dports in final_hash[sips].items():
  159. # print "final", len(dports)"
  160. filtered_final_hash = filter_laststep(final_hash)
  161. fc = 0
  162. fo=0
  163. for sip in filtered_final_hash:
  164. fc +=1
  165. for dip in filtered_final_hash[sip]:
  166. fo +=1
  167. #print sip, dip, filtered_final_hash[sip][dip]
  168. #print (flowHash)
  169. print fc
  170. print fo
  171. if __name__== "__main__":
  172. main()