-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpci.py
executable file
·203 lines (172 loc) · 7.05 KB
/
pci.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
import pyshark
import socket
from py2neo import Graph, Node, Relationship, NodeMatcher
import geoip2.database
import re
from datetime import datetime, timezone
import sys
import signal
import argparse
import logging.config
import yaml
# logging settings
with open('logging.yml', 'rt') as f:
config = yaml.safe_load(f.read())
f.close()
logging.config.dictConfig(config)
logger = logging.getLogger(__name__)
# check databases
try:
_graph_db = Graph('http://localhost:7474', user="neo4j", password="password1")
_matcher = NodeMatcher(_graph_db)
_reader = geoip2.database.Reader('./db/geoip/GeoLite2-City.mmdb',
mode=geoip2.database.MODE_MMAP)
except:
logger.info("neo4j of geoip not available")
sys.exit(1)
def packet_analysis_live(cap):
cap.set_debug()
logger.debug(cap.get_parameters())
cap.sniff(timeout=50)
signal.signal(signal.SIGINT, signal_handler)
for pkt in cap.sniff_continuously():
do_the_job(pkt)
stop()
def packet_analysis(cap):
cap.set_debug()
logger.debug(cap.get_parameters())
signal.signal(signal.SIGINT, signal_handler)
for pkt in cap:
do_the_job(pkt)
stop()
def stop():
cap.close()
_reader.close()
logger.info("Analysis ending ...")
sys.exit(0)
def signal_handler(sig, frame):
logger.info('You pressed Ctrl+C!')
stop()
def get_host_name(ip):
host_name = "Unknown"
try:
host_name = socket.gethostbyaddr(ip)[0]
except Exception:
logger.error("Can't resolve host name: " + ip)
return host_name
def create_node(arg, existing_node):
logger.debug("New node: " + arg)
try:
_graph_db.create(existing_node)
except Exception:
logger.error("Neo4j not available")
def get_node(arg):
pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
ipv4 = pat.match(arg)
if ipv4:
if arg.startswith('192.168') or arg.startswith('172.16') or arg.startswith('10.0'):
existing_node = _matcher.match("local_machine", name=arg).first()
if existing_node:
existing_node['count'] += 1
existing_node['last_update'] = datetime.now(timezone.utc).isoformat()
_graph_db.push(existing_node)
else:
existing_node = Node("local_machine", name=arg, local=True, count=1,
creation_date=datetime.now(timezone.utc).isoformat(),
last_update=datetime.now(timezone.utc).isoformat())
create_node(arg, existing_node)
else:
existing_node = _matcher.match("machine", name=arg).first()
if existing_node:
existing_node['count'] += 1
existing_node['last_update'] = datetime.now(timezone.utc).isoformat()
_graph_db.push(existing_node)
else:
domain_name = "Unknown"
country_name = "Unknown"
sub_name = "Unknown"
city_name = "Unknown"
domain_name = get_host_name(arg)
try:
response = _reader.city(arg)
if response:
country_name = response.country.iso_code
sub_name = response.subdivisions.most_specific.iso_code
city_name = response.city.name
except Exception:
pass
existing_node = Node("machine", name=arg, domain=domain_name, country=country_name,
sub=sub_name, city=city_name, count=1,
creation_date=datetime.now(timezone.utc).isoformat(),
last_update=datetime.now(timezone.utc).isoformat())
create_node(arg, existing_node)
else:
pat_mac = re.compile('((?:[\da-fA-F]{2}[:\-]){5}[\da-fA-F]{2})')
mac_address = pat_mac.match(arg)
if mac_address:
existing_node = _matcher.match("network", name=arg).first()
if existing_node:
existing_node['count'] += 1
existing_node['last_update'] = datetime.now(timezone.utc).isoformat()
_graph_db.push(existing_node)
else:
existing_node = Node("network", name=arg, count=1,
creation_date=datetime.now(timezone.utc).isoformat(),
last_update=datetime.now(timezone.utc).isoformat())
create_node(arg, existing_node)
else:
existing_node = _matcher.match("machine_ipv6", name=arg).first()
if existing_node:
existing_node['count'] += 1
existing_node['last_update'] = datetime.now(timezone.utc).isoformat()
_graph_db.push(existing_node)
else:
existing_node = Node("machine_ipv6", name=arg, count=1,
creation_date=datetime.now(timezone.utc).isoformat(),
last_update=datetime.now(timezone.utc).isoformat())
create_node(arg, existing_node)
return existing_node
def do_the_job(pkt):
src = pkt.source
dst = pkt.destination
typ = pkt.protocol
info = pkt.info
length = pkt.length
# print(pkt)
# print('%s %s --> %s (%s) - %s' % (typ, src, dst, length, info))
logger.debug("Protocol: " + typ + ", Source: " + src + ", Destination: " + dst)
a = get_node(arg=src)
b = get_node(arg=dst)
# PACKET_TO = Relationship.type(typ)
# _graph_db.merge(PACKET_TO(a, b))
_graph_db.merge(Relationship(a, typ, b))
if __name__ == "__main__":
# args parser
parser = argparse.ArgumentParser(description='Packet communications investigator')
parser.add_argument("-f", '--file',
help='directory to clean if not declared use of current dir',
action='store', dest='filepath')
parser.add_argument("-i", "--interface", help="chose interface", action="store", dest='interface')
parser.add_argument("-r", "--ring", help="activate ring buffer", action="store_true",
default=False)
args = parser.parse_args()
# live ring capture
if args.ring:
logger.info("Starting Live Ring Capture on " + args.interface)
cap = pyshark.LiveRingCapture(interface=args.interface, only_summaries=True, ring_file_size=4096,
num_ring_files=50, ring_file_name='./db/pcap/pci.pcapng')
packet_analysis_live(cap)
# live capture
elif args.interface:
logger.info("Starting Live Capture on " + args.interface)
cap = pyshark.LiveCapture(interface=args.interface, only_summaries=True)
packet_analysis_live(cap)
# pcap
elif args.filepath:
logger.info("Starting pcap analysis on " + args.filepath)
cap = pyshark.FileCapture(input_file=args.filepath, only_summaries=True)
packet_analysis(cap)
else:
parser.print_help()
sys.exit()