Browse Source

All files

SaraBeatriz 5 years ago
commit
f62323a78b

+ 6
- 0
Practica/newFlow.txt
File diff suppressed because it is too large
View File


+ 9
- 0
Practica/otherHash.py View File

@@ -0,0 +1,9 @@
1
+newHash = {}
2
+
3
+dip = "hola"
4
+if dip in newHash:
5
+    newHash[dip] +=1
6
+else:
7
+    newHash[dip] = 1
8
+
9
+print newHash

+ 77
- 0
Practica/realPs.py View File

@@ -0,0 +1,77 @@
1
+import ipaddress
2
+import netflows
3
+
4
+
5
+#Para usar Silk
6
+#SilkFile object (represents a channel for writing to or reading from Silk flow file)
7
+#FGlob object (allows retireval of filenames in a silk data store.)
8
+
9
+
10
+
11
+
12
+
13
+
14
+x = 20
15
+y = 60000
16
+ignoreip = []
17
+myHash={}
18
+myNum = 0
19
+counter = 0
20
+
21
+def ipConversion(number, position):
22
+    mystr = ''
23
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
24
+    for i in range(position+1):
25
+        if i ==position:
26
+            mystr = mystr + ipadd[i]
27
+        else:
28
+            mystr = mystr + ipadd[i] + '.'
29
+    return mystr
30
+def PrimerAnalisis(num):
31
+    newHash={}
32
+    for i in netflows.flowprinter["flows"]: #itera por cada elemento del diccionario de flows
33
+        posA = ipConversion(i["dip"], num)
34
+        if ignoreip != [] and posA[0:4*num] in ignoreip:
35
+            continue
36
+        elif (i['dport'] >= 1 and i['dport'] < x) or i['dport'] > y: #verifica que sean puertos (se me fue la palabra...)
37
+            continue
38
+        else: #agrega a un hash cada puerto con un counter de sus destination ips
39
+            if num ==3:
40
+                if posA in newHash:
41
+                    newHash[posA].append(i['dport'])
42
+                else:
43
+                    newHash[posA] = [i['dport']]
44
+            else:
45
+                if posA in newHash:
46
+                    newHash[posA] += 1
47
+                    #print (posA)
48
+                else:
49
+                    newHash[posA] = 1
50
+                    #print (posA)
51
+
52
+    return newHash
53
+
54
+#MAIN:
55
+while myNum <4:
56
+    myHash= PrimerAnalisis(myNum)
57
+    ignoreip =[]
58
+    for k, v in myHash.items():
59
+        if myNum != 3 and v >= 100:
60
+            continue
61
+        elif myNum == 3 and len(v)>= 100:
62
+            continue
63
+        else:
64
+            ignoreip.append(k)
65
+    myNum += 1
66
+
67
+
68
+for i in ignoreip:
69
+    myHash.pop(i)
70
+for k, v in myHash.items():
71
+    counter +=1
72
+#print (ignoreip)
73
+print (counter)
74
+
75
+
76
+
77
+#Si el valor de la llave es menos que 100, no me interesa.

+ 39
- 0
Practica/trial.py View File

@@ -0,0 +1,39 @@
1
+# ratioHash = {}
2
+# sampleHash = {}
3
+#
4
+# sip = "sara"
5
+# posA = 'alexandra'
6
+#
7
+# connection = [1,1]
8
+#
9
+# print 10/5
10
+#
11
+# for i in range (0, 2):
12
+#     if sip in ratioHash:
13
+#         sampleHash[posA][0]+=connection[0]
14
+#         sampleHash[posA][1]+= connection[1]
15
+#     else:
16
+#         sampleHash[posA] = [connection[0], connection[1]]
17
+#         ratioHash[sip] = sampleHash
18
+#         #print (posA
19
+#
20
+# print ratioHash
21
+#
22
+# import json
23
+# #PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/newFlow.txt'
24
+# PATH = '/mnt/c/Users/Sara/Documents/Univ Classes/Investigacion/Programas/newFlow.txt'
25
+#
26
+# myFile = open(PATH, 'r')
27
+# ip = myFile.read()
28
+# flow = json.loads(ip)
29
+#
30
+# for i in flow['flows']:
31
+#     flags = i["tcpflags"].split(",")
32
+#     print flags[0]
33
+hashi = {}
34
+if 'hola' in hashi:
35
+    hashi['hola'][0]+= 1
36
+else:
37
+    hashi = {'hola': [0, 1]}
38
+
39
+print hashi['hola']

+ 63
- 0
Programas/NS_orig.py View File

@@ -0,0 +1,63 @@
1
+#Network Scan without reduction
2
+
3
+import ipaddress
4
+import json
5
+
6
+
7
+x = 20
8
+y = 60000
9
+deletevar = []
10
+newHash={}
11
+
12
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/netflows.txt'
13
+
14
+myFile = open(PATH, 'r')
15
+ip = myFile.read()
16
+flow = json.loads(ip)
17
+
18
+def ipConversion(number, position):
19
+    mystr = ''
20
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
21
+    for i in range(position+1):
22
+        if i ==position:
23
+            mystr = mystr + ipadd[i]
24
+        else:
25
+            mystr = mystr + ipadd[i] + '.'
26
+    return mystr #devuelve los numeros en notacion string
27
+
28
+
29
+for i in flow["flows"]: #itera por cada elemento del diccionario de flows
30
+    #Cambiar esto al unirlo con el trw
31
+    if i['sip'] == 2291263257: #Este numero se lo dara el trw que verifica que sip son scanners
32
+        dip = ipConversion(i['dip'], 0)
33
+        host = ipConversion(i['dip'], 3)
34
+        if dip in newHash and host not in newHash[dip]:
35
+            newHash[dip].append(host)
36
+        else:
37
+            newHash[dip] = [host]
38
+
39
+#LO SIGUIENTE ESTA COMENTADO Y LO EXPLICO EN EL WORD
40
+
41
+
42
+# for k, v in newHash.items(): #itera por cada ip address y sus puertos
43
+#     if len(v) >= 100:
44
+#         #print ("something suspicious...")
45
+#         continue
46
+#     else: #Si no tiene una cantidad considerable de puertos, agrega el ip a una lista
47
+#         if k in deletevar:
48
+#             continue
49
+#         else:
50
+#             deletevar.append(k)
51
+
52
+#
53
+# for i in deletevar: #borra todos los elementos que estan en la lista deletevar
54
+#                     #del hash con todos los ip y sus puertos
55
+#     newHash.pop(i)
56
+
57
+counter = 0 #Para contar total de elementos en el hash
58
+for k, v in newHash.items(): #imprime los destination ip address con sus puertos
59
+    counter = counter+1
60
+    #k = str(ipaddress.IPv4Address(k))
61
+    print ("{}:{}".format(k,v))
62
+print (counter)
63
+print( "Done checking:")

+ 81
- 0
Programas/PS_delete.py View File

@@ -0,0 +1,81 @@
1
+import ipaddress
2
+import json
3
+
4
+#Port Scanner, using a reduction method,re-reading the list the 4
5
+#times.
6
+
7
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/netflows.txt'
8
+
9
+myFile = open(PATH, 'r')
10
+ip = myFile.read()
11
+flow = json.loads(ip)
12
+
13
+#Son los limites de los Puertos que queremos verificar
14
+x = 20
15
+y = 60000
16
+
17
+#Variables inicializadas
18
+hashbrown = {}
19
+myNum = 0
20
+
21
+#Esta funcion convierte la direccion de ip de un entero a un string usando la libreria de ipaddress.
22
+#Recibe dos parametros, la direccion de ip en entero y un numero k. Esta funcion devuelve un arreglo compuesto de cada
23
+#numero decimal entre los puntos del string. Dependiendo del numero k sera hasta que posision del arreglo se devolvera.
24
+def ipConversion(number, k):
25
+
26
+    mystr = ''
27
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
28
+    for i in range(k+1):
29
+        mystr = mystr + ipadd[i] + '.'
30
+    return mystr
31
+
32
+
33
+#This function returns a hash with the ip address as the key and a list of the ports asociated with
34
+#that ipaddress
35
+def PrimerAnalisis(number):
36
+    ps = {}
37
+    for i in flow["flows"]: #for each element of the value of 'flows'
38
+        posA = ipConversion(i["dip"], number) #change the ip address to string
39
+
40
+        if (i['dport'] >= 1 and i['dport'] < x) or i['dport'] > y: #verifica que sean puertos (se me fue la palabra...)
41
+            continue
42
+        else: #agrega a un hash cada puerto con su destination ip
43
+            if posA in ps:
44
+                ps[posA].append(i['dport'])
45
+
46
+            else:
47
+                ps[posA] = [i['dport']]
48
+
49
+    return ps
50
+
51
+deletevar = []
52
+while myNum < 4: #recorrera 4 veces la lista de flows empezando con el primer numero decimal de los ip hasta el 4to
53
+    hashBrown= PrimerAnalisis(myNum) #crea un hash
54
+
55
+    for k, v in hashBrown.items(): #itera por cada ip address y sus puertos
56
+        if len(v) >= 100:
57
+            #print ("something suspicious...")
58
+            continue
59
+        else: #Si no tiene una cantidad considerable de puertos, sigue verificando
60
+            #print  ("nothing Suspicious but: (%s:%s)" %(k, v) )
61
+            if myNum == 3 : #Si se llega a la ultima verificacion se agregan a una lista para luego borrarlas del hash
62
+                if k in deletevar:
63
+                    continue
64
+                else:
65
+                    deletevar.append(k)
66
+            else:
67
+                continue
68
+
69
+    myNum = myNum + 1
70
+
71
+
72
+for i in deletevar: #borra todos los elementos que estan en la lista deletevar
73
+                    #del hash con todos los ip y sus puertos
74
+    hashBrown.pop(i)
75
+
76
+counter = 0#Para contar total de elementos en el hash
77
+for k, v in hashBrown.items(): #imprime los destination ip address con los puertos
78
+    counter = counter+1
79
+    #print ("{}:{}".format(k,v))
80
+print (counter)
81
+#print( "Done checking:")

+ 55
- 0
Programas/PS_orig.py View File

@@ -0,0 +1,55 @@
1
+#Port Scan without reduction
2
+
3
+import ipaddress
4
+import json
5
+
6
+
7
+#Version 1
8
+#Read all the flows and append to a hash their destination ip and destination port
9
+#Check which flows share the same destination ip though differente dports.
10
+
11
+x = 20
12
+y = 60000
13
+deletevar = []
14
+newHash={}
15
+
16
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/netflows.txt'
17
+
18
+myFile = open(PATH, 'r')
19
+ip = myFile.read()
20
+flow = json.loads(ip)
21
+
22
+for i in flow["flows"]: #itera por cada elemento del diccionario de flows
23
+    #if (i['dport'] >= 1 and i['dport'] < x) or i['dport'] > y: #verifica que sean puertos (se me fue la palabra...)
24
+        #continue
25
+    #else: #agrega a un hash cada puerto con su destination ip
26
+    if i['sip'] == 2291263257:
27
+        if i['dip'] in newHash:
28
+            newHash[i['dip']].append(i['dport'])
29
+        else:
30
+            newHash[i['dip']] = [i['dport']]
31
+
32
+#LO SIGUIENTE ESTA COMENTADO Y LO EXPLICO EN EL WORD
33
+
34
+# for k, v in newHash.items(): #itera por cada ip address y sus puertos
35
+#     if len(v) >= 100:
36
+#         #print ("something suspicious...")
37
+#         continue
38
+#     else: #Si no tiene una cantidad considerable de puertos, agrega el ip a una lista
39
+#         if k in deletevar:
40
+#             continue
41
+#         else:
42
+#             deletevar.append(k)
43
+
44
+
45
+#for i in deletevar: #borra todos los elementos que estan en la lista deletevar
46
+                    #del hash con todos los ip y sus puertos
47
+#    newHash.pop(i)
48
+
49
+counter = 0 #Para contar total de elementos en el hash
50
+for k, v in newHash.items(): #imprime los destination ip address con sus puertos
51
+    counter = counter+1
52
+    k = str(ipaddress.IPv4Address(k))
53
+    print ("{}:{}".format(k,v))
54
+print (counter)
55
+print( "Done checking:")

+ 102
- 0
Programas/PS_reduc.py View File

@@ -0,0 +1,102 @@
1
+#Reduction Port Scanner
2
+
3
+import ipaddress
4
+import json
5
+
6
+
7
+#Para usar Silk
8
+#SilkFile object (represents a channel for writing to or reading from Silk flow file)
9
+#FGlob object (allows retireval of filenames in a silk data store.)
10
+
11
+
12
+minPort = 20
13
+maxPort= 60000
14
+flowHash={}
15
+otherHash= {}
16
+myNum = 0
17
+counter = 0
18
+
19
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/netflows.txt'
20
+
21
+myFile = open(PATH, 'r')
22
+ip = myFile.read()
23
+flow = json.loads(ip)
24
+
25
+#Funcion que convierte el int ipaddress en notacion string y devuelve los numeros
26
+#hasta la posicion del punto dada en los parametros
27
+def ipConversion(number, position):
28
+    mystr = ''
29
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
30
+    for i in range(position+1):
31
+        if i ==position:
32
+            mystr = mystr + ipadd[i]
33
+        else:
34
+            mystr = mystr + ipadd[i] + '.'
35
+    return mystr #devuelve los numeros en notacion string
36
+
37
+#Funcion que verifica los flows y guarda su dip y, primero un counter de sus puertos,
38
+#y luego los puertos, en un hash. Recibe dos parametros, un hash para verificar
39
+#si ignorar o no el flow (dado en el main), y un numero para la idea de reduccion
40
+def PrimerAnalisis(flowHash, num):
41
+    sampleHash={}
42
+    for i in flow["flows"]: #itera por cada elemento del diccionario de flows
43
+        posA = ipConversion(i["dip"], num) #devuelve la primera clase del ip en notacion string
44
+        if num != 0 and ipConversion(i["dip"], num-1) not in flowHash: #Si en el paso anterior se vio que no
45
+                                                                     #tiene el length de puertos requerido, se ignora
46
+            continue
47
+        elif (i['dport'] >= 1 and i['dport'] < minPort) or i['dport'] > maxPort: #verifica que sean puertos validos (creo que se dice asi)
48
+            continue
49
+        else: #agrega a un hash cada puerto con un counter de sus destination ips
50
+            if posA in sampleHash:
51
+                sampleHash[posA] += 1
52
+                #print (posA)
53
+            else:
54
+                sampleHash[posA] = 1
55
+                #print (posA)
56
+
57
+    return sampleHash
58
+
59
+def UltimoAnalisis(flowHash, num):
60
+    sampleHash = {}
61
+    for i in flow["flows"]: #itera por cada elemento del diccionario de flows
62
+        posA = ipConversion(i["dip"], num) #devuelve la primera clase del ip en notacion string
63
+        if ipConversion(i["dip"], num-1) not in flowHash: #Si en el paso anterior se vio que no
64
+                                                                     #tiene el length de puertos requerido, se ignora
65
+            continue
66
+        elif (i['dport'] >= 1 and i['dport'] < minPort) or i['dport'] > maxPort: #verifica que sean puertos validos (creo que se dice asi)
67
+            continue
68
+        else: # Como es el caso de la ultima busqueda, se agrega una lista de los puertos
69
+            if posA in sampleHash:
70
+                sampleHash[posA].append(i['dport'])
71
+            else:
72
+                sampleHash[posA] = [i['dport']]
73
+    return sampleHash
74
+
75
+#MAIN:
76
+while myNum <3: #Se itera las cuatro veces de acuerdo con la notacion de ipv4
77
+    flowHash= PrimerAnalisis(otherHash, myNum)
78
+    otherHash = {} #Se borra el hash para agregar elementos nuevos con la nueva etapa de la busqueda
79
+    for dips, dports in flowHash.items(): #se itera por todos los dip y sus counters o puertos
80
+        if dports >= 100: #si la cantidad de puertos es mayor o igual a 100, nos interesan
81
+                                    #y por lo tanto se guardan en un hash
82
+            otherHash[dips] = dports
83
+
84
+    myNum += 1
85
+    #print (flowHash)
86
+
87
+
88
+#Ultimo chequeo, utilizando el ip completo
89
+flowHash = UltimoAnalisis(otherHash, myNum)
90
+otherHash = {} #Se borra el hash para agregar elementos nuevos con la nueva etapa de la busqueda
91
+for dips, dports in flowHash.items():
92
+    if len(dports)>= 100: #si la cantidad de puertos es mayor o igual a 100, nos interesan
93
+                                #y por lo tanto se guardan en un hash
94
+        otherHash[dips] = dports
95
+        print (flowHash)
96
+
97
+
98
+
99
+for dips, dports in otherHash.items():
100
+    counter +=1 #para contar los elementos del hash
101
+
102
+print (counter)

+ 1
- 0
Programas/netflows.txt
File diff suppressed because it is too large
View File


+ 14
- 0
Programas/practiceHash.py View File

@@ -0,0 +1,14 @@
1
+import socket
2
+import json
3
+import random
4
+
5
+
6
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
7
+for i in range (5):
8
+    val = random.randint(1, 5)
9
+    dataScript = {'sara':val, 'ale':4}
10
+    message = json.dumps(dataScript)
11
+    s.sendto(message, ('localhost', 2702))
12
+    print "Sending %s message" % i
13
+
14
+print "Sent messages"

+ 88
- 0
Programas/practiceSet.py View File

@@ -0,0 +1,88 @@
1
+import ipaddress
2
+import netflows
3
+
4
+
5
+#Port Scanner, using a reduction method, and deleting the addresses as
6
+#the program sees they are of no use.
7
+
8
+flow = netflows.flowprinters() #Agrega el diccionario de flows a una variable
9
+
10
+
11
+
12
+
13
+#Son los limites de los Puertos que queremos verificar
14
+x = 20
15
+y = 60000
16
+
17
+#Variables inicializadas
18
+hashbrown = {}
19
+myNum = 0
20
+
21
+#Esta funcion convierte la direccion de ip de un entero a un string usando la libreria de ipaddress.
22
+#Recibe dos parametros, la direccion de ip en entero y un numero k. Esta funcion devuelve un arreglo compuesto de cada
23
+#numero decimal entre los puntos del string. Dependiendo del numero k sera hasta que posision del arreglo se devolvera.
24
+def ipConversion(number, k):
25
+
26
+    mystr = ''
27
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
28
+    for i in range(k+1):
29
+        mystr = mystr + ipadd[i] + '.'
30
+    return mystr
31
+
32
+
33
+#This function returns a hash with the ip address as the key and a list of the ports asociated with
34
+#that ipaddress
35
+def PrimerAnalisis(number):
36
+    ps = {}
37
+    for i in flow["flows"]: #for each element of the value of 'flows'
38
+        posA = ipConversion(i["dip"], number) #change the ip address to string
39
+
40
+        if (i['dport'] >= 1 and i['dport'] < x) or i['dport'] > y: #verifica que sean puertos (se me fue la palabra...)
41
+            continue
42
+        else: #agrega a un hash cada puerto con su destination ip
43
+            if posA in ps:
44
+                ps[posA].append(i['dport'])
45
+
46
+            else:
47
+                ps[posA] = [i['dport']]
48
+
49
+    return ps
50
+
51
+deletevar = []
52
+while myNum < 4: #recorrera 4 veces la lista de flows empezando con el primer numero decimal de los ip hasta el 4to
53
+    hashBrown= PrimerAnalisis(myNum) #crea un hash
54
+
55
+    for k, v in hashBrown.items(): #itera por cada ip address y sus puertos
56
+        if len(v) >= 100:
57
+            #print ("something suspicious...")
58
+            continue
59
+        else: #Si no tiene una cantidad considerable de puertos, la borra de la lista sigue verificando
60
+            #print  ("nothing Suspicious but: (%s:%s)" %(k, v) )
61
+
62
+            for il in flow['flows']: #vuelve a iterar por la lista de flows para borrar de la lista la que
63
+                                    # no tiene suficiente puertos
64
+                newi = ipConversion(il["dip"], myNum)
65
+                if k == newi:
66
+                    #index = flow['flows'].index(newi)
67
+                    flow['flows'].remove(il)
68
+                    if myNum == 3 : #Si se llega a la ultima verificacion se agregan a una lista para luego borrarlas del hash
69
+                        if k in deletevar:
70
+                            continue
71
+                        else:
72
+                            deletevar.append(k)
73
+                else:
74
+                    continue
75
+
76
+    myNum = myNum + 1
77
+
78
+
79
+or i in deletevar: #borra todos los elementos que estan en la lista deletevar
80
+                    #del hash con todos los ip y sus puertos
81
+    hashBrown.pop(i)
82
+
83
+counter = 0 #Para contar total de elementos en el hash
84
+for k, v in hashBrown.items(): #imprime los destination ip address con los puertos
85
+    counter = counter+1
86
+    print ("{}:{}".format(k,v))
87
+print (counter)
88
+print( "Done checking:")

+ 14
- 0
Programas/pythonpractice.py View File

@@ -0,0 +1,14 @@
1
+import ipaddress
2
+import json
3
+
4
+
5
+#hashbleh = [{'name':'sara', 'number':46}, {'name':'ale', 'number':6}, {'name':'ian', 'number':10},
6
+#{'name':'ale', 'number':32}, {'name':'sara', 'number':22}, {'name': 'marisa', 'number':90},
7
+#{'name':'ian', 'number':30}, {'name':'Kevin', 'number':34}]
8
+#lista de hashes
9
+
10
+path = '/Users/Sara/Documents/Univ Classes/Investigacion/newFlow.txt'
11
+myFile = open(path, 'r')
12
+flow = myFile.read()
13
+ip = json.loads(flow)
14
+print(type(ip))

+ 45
- 0
Programas/simulate.py View File

@@ -0,0 +1,45 @@
1
+#Plan:
2
+
3
+#Create a program where it will receive a string of data
4
+#That string will be added to a dictionary, with the ip attributes as its keys
5
+#simulate a filter. Like give it a shell script input with one of the attributes
6
+#And have it present the thingies...
7
+#check in Julios visualization what is presented when filtered
8
+
9
+import socket
10
+
11
+import argparse
12
+import sys
13
+import select
14
+import json
15
+
16
+parser = argparse.ArgumentParser()
17
+parser.add_argument('filter', type = str)
18
+args = parser.parse_args()
19
+
20
+soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
21
+#soc.setblocking(0)
22
+soc.bind(('localhost', 2702))
23
+temp = 1
24
+num = 0
25
+filterArray = []
26
+soc.settimeout(5)
27
+while temp:
28
+    print ("waiting to receive message")
29
+    num = num + 1
30
+    #ready = select.select([soc], [], [], timeout_in_seconds)
31
+    try:
32
+        data, address = soc.recvfrom(2702)
33
+        print "\nreceived %s message" %num
34
+        newData = json.loads(data)
35
+    except socket.error:
36
+        print "\nNo message to receive, leave loop"
37
+        temp = 0
38
+
39
+
40
+    for k, v in newData.items():
41
+        if k == args.filter:
42
+            print k
43
+            filterArray.append(v)
44
+
45
+print filterArray

+ 46
- 0
Programas/trw.py View File

@@ -0,0 +1,46 @@
1
+import ipaddress
2
+import json
3
+
4
+
5
+#Para usar Silk
6
+#SilkFile object (represents a channel for writing to or reading from Silk flow file)
7
+#FGlob object (allows retireval of filenames in a silk data store.)
8
+
9
+
10
+minPort = 20
11
+maxPort= 60000
12
+flowHash={}
13
+otherHash= {}
14
+myNum = 0
15
+counter = 0
16
+
17
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/netflows.txt'
18
+
19
+myFile = open(PATH, 'r')
20
+ip = myFile.read()
21
+flow = json.loads(ip)
22
+
23
+#Funcion que convierte y devuelve el int ipaddress en notacion punto-decimal
24
+def ipConversion(number):
25
+    ipadd = str(ipaddress.IPv4Address(number))
26
+    return ipadd
27
+
28
+
29
+def Analisis(flowHash):
30
+    sampleHash={} #hash para contener los dip con el numero de conecciones y failed coneccciones
31
+    connection = [0] * 2 #Lista para contener los valores de conecciones failed y conecciones buenas
32
+    for i in flow["flows"]: #itera por cada elemento del diccionario de flows
33
+        posA = ipConversion(i["sip"]) #Devuelve el ip en notacion punto-decimal
34
+        if i["connection"] == "synack": #No se cual es el formato de esto
35
+            connection[1]=1 #good conections
36
+        else:
37
+            connection [0] =1 #failed conections
38
+        if posA in sampleHash:
39
+            sampleHash[posA][0]+=connection[0]
40
+            sampleHash[posA][1]+= connection[1]
41
+            #print (posA)
42
+        else:
43
+            sampleHash[posA] = [connection[0], connection[1]]
44
+            #print (posA)
45
+
46
+    return sampleHash

+ 72
- 0
Programas/trw_real.py View File

@@ -0,0 +1,72 @@
1
+import ipaddress
2
+import json
3
+
4
+
5
+#Para usar Silk
6
+#SilkFile object (represents a channel for writing to or reading from Silk flow file)
7
+#FGlob object (allows retireval of filenames in a silk data store.)
8
+
9
+
10
+#threshold of the ratio
11
+p = 5
12
+flowHash={}
13
+otherHash= {}
14
+myNum = 0
15
+counter = 0
16
+
17
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/netflows.txt'
18
+
19
+myFile = open(PATH, 'r')
20
+ip = myFile.read()
21
+flow = json.loads(ip)
22
+
23
+#Funcion que convierte y devuelve el int ipaddress en notacion punto-decimal
24
+def ipConversion(number, position):
25
+    mystr = ''
26
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
27
+    for i in range(position+1):
28
+        if i ==position:
29
+            mystr = mystr + ipadd[i]
30
+        else:
31
+            mystr = mystr + ipadd[i] + '.'
32
+    return mystr #devuelve los numeros en notacion string
33
+
34
+
35
+def AnalisisReduciendo(flowHash, num):
36
+    connection = [0] * 2 #Lista para contener los valores de conecciones fallidas y conecciones buenas
37
+    for i in flow["flows"]: #itera por cada elemento del diccionario de flows
38
+        dip = ipConversion(i["sip"], num) #Devuelve el ip en notacion punto-decimal
39
+        flags = i["tcpflags"].split(",")  #array of all tcp flags that are set
40
+        if num != 0 and ipConversion(i["sip"], num-1) not in flowHash: #Si en el paso anterior se vio que no
41
+                                                                     #tiene el length de puertos requerido, se ignora
42
+            continue
43
+        else:
44
+            if 'A' in flags: #if the acknowledge flag is set
45
+            connection[1]=1 #good conections
46
+            else:
47
+                connection [0] =1 #failed conections
48
+            if sip in ratioHash: #si sip esta en ratioHash => que posA esta en sampleHash
49
+                                #por lo tanto ya se puede sumar las conecciones al ratio del dip
50
+                ratioHash[sip][0]+=connection[0]
51
+                ratioHash[sip][1] += connection[1]]
52
+            else: #si sip no esta en ratioHash tampoco
53
+                ratioHash= {sip: [connection[0], connection[1]]}
54
+
55
+
56
+    return ratioHash
57
+
58
+while myNum <4: #Se itera las cuatro veces de acuerdo con la notacion de ipv4
59
+    flowHash= AnalisisReduciendo(otherHash, myNum)
60
+    otherHash = {} #Se borra el hash para agregar elementos nuevos con la nueva etapa de la busqueda
61
+    for sip, dipHash in flowHash.items(): #se itera por todos los dip y sus counters o puertos
62
+        if (dipHash['dip'][0] / dipHash['dip'][1])  < 0: #si la cantidad de succesful
63
+                                                        #connections es mas que failed connections
64
+            #not scanner, ignore
65
+        else if (dipHash['dip'][0] / dipHash['dip'][1])  < p:
66
+            #not scanner, ignore
67
+        else:
68
+            #scanner, oh oh
69
+
70
+
71
+    myNum += 1
72
+    #print (flowHash)

+ 78
- 0
Programas/trw_reducps.py View File

@@ -0,0 +1,78 @@
1
+import ipaddress
2
+import json
3
+
4
+
5
+#Para usar Silk
6
+#SilkFile object (represents a channel for writing to or reading from Silk flow file)
7
+#FGlob object (allows retireval of filenames in a silk data store.)
8
+
9
+
10
+#threshold of the ratio
11
+p = 5
12
+flowHash={}
13
+otherHash= {}
14
+myNum = 0
15
+counter = 0
16
+
17
+PATH = '/Users/Sara/Documents/Univ Classes/Investigacion/Programas/netflows.txt'
18
+
19
+myFile = open(PATH, 'r')
20
+ip = myFile.read()
21
+flow = json.loads(ip)
22
+
23
+#Funcion que convierte y devuelve el int ipaddress en notacion punto-decimal
24
+def ipConversion(number, position):
25
+    mystr = ''
26
+    ipadd = (str(ipaddress.IPv4Address(number))).split(".") #Devuelve un arreglo
27
+    for i in range(position+1):
28
+        if i ==position:
29
+            mystr = mystr + ipadd[i]
30
+        else:
31
+            mystr = mystr + ipadd[i] + '.'
32
+    return mystr #devuelve los numeros en notacion string
33
+
34
+
35
+def AnalisisReduciendo(flowHash, num):
36
+    connection = [0] * 2 #Lista para contener los valores de conecciones fallidas y conecciones buenas
37
+    ratioHash = {}
38
+    for i in flow["flows"]: #itera por cada elemento del diccionario de flows
39
+        sip = ipConversion(i["sip"], 3)
40
+        dip = ipConversion(i["dip"], num) #Devuelve el ip en notacion punto-decimal
41
+        flags = i["tcpflags"].split(",")  #array of all tcp flags that are set
42
+        if num != 0 and ipConversion(i["dip"], num-1) not in flowHash: #Si en el paso anterior se vio que no
43
+                                                                     #tiene el length de puertos requerido, se ignora
44
+            continue
45
+        else:
46
+            if 'A' in flags: #if the acknowledge flag is set
47
+            connection[1]=1 #good conections
48
+            else:
49
+                connection [0] =1 #failed conections
50
+            if sip in ratioHash: #si sip esta en ratioHash => que posA esta en sampleHash
51
+                                #por lo tanto ya se puede sumar las conecciones al ratio del dip
52
+                if dip in ratioHash[sip]:
53
+                    ratioHash[sip][dip][0]+=connection[0]
54
+                    ratioHash[sip][dip][1] += connection[1]]
55
+                else:
56
+                    ratioHash[sip][dip] = [connection[0], connection[1]]
57
+            else: #si sip no esta en ratioHash tampoco posA en sampleHash por lo
58
+                    #tanto se inicializa posA en sampleHash y luego sip en ratioHash con su valor de sampleHash
59
+                ratioHash[sip] = {dip: [connection[0], connection[1]]}
60
+
61
+
62
+    return ratioHash
63
+
64
+while myNum <4: #Se itera las cuatro veces de acuerdo con la notacion de ipv4
65
+    flowHash= AnalisisReduciendo(otherHash, myNum)
66
+    otherHash = {} #Se borra el hash para agregar elementos nuevos con la nueva etapa de la busqueda
67
+    for sip, dipHash in flowHash.items(): #se itera por todos los dip y sus counters o puertos
68
+        if (dipHash['dip'][0] / dipHash['dip'][1])  < 0: #si la cantidad de succesful
69
+                                                        #connections es mas que failed connections
70
+            #not scanner, ignore
71
+        else if (dipHash['dip'][0] / dipHash['dip'][1])  < p:
72
+            #not scanner, ignore
73
+        else:
74
+            #scanner, oh oh
75
+
76
+
77
+    myNum += 1
78
+    #print (flowHash)