-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpkt
More file actions
executable file
·289 lines (243 loc) · 11.1 KB
/
pkt
File metadata and controls
executable file
·289 lines (243 loc) · 11.1 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#! /usr/bin/env python3
from netfilterqueue import NetfilterQueue
import argparse
import shutil
import os
import yara
import sys
import yaml
from src.terminal import *
from src.packet import *
class Pkt:
def __init__(self, verbose, rules_path, out):
try:
self.log = log
except NameError:
# if in module, we do not care
self.log = lambda _: None
try:
self.rules = yara.compile(f'{rules_path}default.yar')
self.rules_RAW = yara.compile(f'{rules_path}default_RAW.yar')
except Exception as e:
self.log.warn(f"Failed to open default yara file! {e}")
sys.exit(1)
self.out = out
self.counter = 0
self.verbose = verbose
self.nfq = NetfilterQueue()
def run(self):
try:
shutil.rmtree(self.out)
except OSError:
log.warn(f"Failed to remove {self.out} directory")
os.mkdir(self.out)
self.log.succ("Starting")
self.nfq.bind(1, self.pkt)
try:
self.nfq.run()
except KeyboardInterrupt:
log.warn("Bye!")
self.nfq.unbind()
def pkt(self, packet):
self.counter += 1
pinfo = {
"a1_port_trojan": "", # trojan port?
"a1_port_trojan_exp_proto": "", # expected protocol
"a1_port_trojan_act_l4_proto": "", # actual layer 4 protocol
"a1_port_trojan_act_l7_proto": "", # actual protocol observed
"l3_ipv4_src": "", # source ipv4 address
"l3_ipv4_dst": "", # destination ipv4 address
"l3_ipv4_proto": "", # layer 4 protocol
"l3_ipv4_ttl": "", # ipv4 time to live
"l4_tcp_port_src": "", # tcp source port
"l4_tcp_port_dst": "", # tcp destination port
"l4_tcp_seq": "", # tcp sequence number
"l4_tcp_ack": "", # tcp acknowledgement number
"l4_tcp_res": "",
"l4_tcp_flags_urg": "", # URG flag?
"l4_tcp_flags_ack": "", # ACK flag?
"l4_tcp_flags_psh": "", # PSH flag?
"l4_tcp_flags_rst": "", # RST flag?
"l4_tcp_flags_syn": "", # SYN flag?
"l4_tcp_flags_fin": "", # FIN flag?
"l4_udp_port_src": "", # udp source port
"l4_udp_port_dst": "", # udp destination port
"l4_udp_size": "", # udp payload size
"l7_dns_is_query": "", # dns query or answer?
"l7_dns_txid": "", # dns transaction id
"l7_dns_n_queries": "", # number of dns queries
"l7_dns_n_answers": "", # number of dns answers
"l7_dns_n_authority": "",
"l7_dns_n_additional": "", # number of additional dns queries/answers
"l6_tls_handshake": "", # type of tls handshake
"l6_tls_version": "", # tls version
"l6_tls_n_ciphersuites": "", # number cipher suites supported
"l6_tls_suites": "", # the tls cipher suites space delimited
"l6_tls_ja3": "", # ja3 fingerprint hash (TODO: this)
}
pld = packet.get_payload()
ip = IP(pld)
pinfo["l3_ipv4_src"] = ip.src
pinfo["l3_ipv4_dst"] = ip.dst
pinfo["l3_ipv4_proto"] = ip.proto
pinfo["l3_ipv4_ttl"] = ip.ttl
if self.verbose > 0:
self.log.info(f"{ip.src} -> {ip.dst} {self.counter}")
match ip.proto:
case "TCP":
tcp = TCP(ip.data)
pinfo["l4_tcp_port_src"] = tcp.src_port
pinfo["l4_tcp_port_dst"] = tcp.dst_port
pinfo["l4_tcp_seq"] = tcp.seq
pinfo["l4_tcp_ack"] = tcp.ack
pinfo["l4_tcp_res"] = tcp.res
pinfo["l4_tcp_flags_urg"] = tcp.flags["urg"]
pinfo["l4_tcp_flags_ack"] = tcp.flags["ack"]
pinfo["l4_tcp_flags_psh"] = tcp.flags["psh"]
pinfo["l4_tcp_flags_rst"] = tcp.flags["rst"]
pinfo["l4_tcp_flags_syn"] = tcp.flags["syn"]
pinfo["l4_tcp_flags_fin"] = tcp.flags["fin"]
if self.verbose > 1:
self.log.info(f"\tTCP {tcp.src_port} -> {tcp.dst_port}")
if self.verbose > 2:
self.log.info(
f"\tSize {len(tcp.data)} Sequence number {tcp.seq}")
self.log.info(
f"\tFlags {tcp.flags['syn']} {tcp.flags['ack']} {tcp.flags['psh']} {tcp.flags['urg']} {tcp.flags['fin']} {tcp.flags['rst']}")
try: # try decoding tls
if tcp.data != b'':
tls = TLS(tcp.data)
pinfo["l6_tls_content_type"] = tls.content_type
pinfo["l6_tls_handshake"] = tls.handshake
pinfo["l6_tls_version"] = tls.version
pinfo["l6_tls_n_ciphersuites"] = int(
tls.cipher_suites_len/2)
pinfo["l6_tls_suites"] = " ".join(tls.suites)
pinfo["l6_tls_ja3"] = ""
if self.verbose > 1:
self.log.info(
f"\t\tTLS version {tls.version} content type {tls.content_type}")
if self.verbose > 2:
if tls.content_type == "handshake":
self.log.info(
f"\t\thandshake type {tls.handshake} cipher suites {' '.join(tls.suites)}")
except Exception as e:
pass
# self.log.warn(e)
# input()
case "UDP":
udp = UDP(ip.data)
pinfo["l4_udp_port_src"] = udp.src_port
pinfo["l4_udp_port_dst"] = udp.dst_port
pinfo["l4_udp_port_size"] = udp.size
if self.verbose > 1:
self.log.info(f"\tUDP {udp.src_port} -> {udp.dst_port}")
if self.verbose > 2:
self.log.info(f"\tPayload size {udp.size}")
try: # try decoding dns
dns = DNS(udp.data)
pinfo["l7_dns_is_query"] = dns.is_query
pinfo["l7_dns_txid"] = dns.txid
pinfo["l7_dns_n_queries"] = dns.nqueries
pinfo["l7_dns_n_answers"] = dns.nanswers
pinfo["l7_dns_n_authority"] = dns.nauthority
pinfo["l7_dns_n_additional"] = dns.nadditional
if self.verbose > 1:
self.log.info(
f"\t\tDNS query? {dns.is_query == 0x8000} txid {dns.txid}")
if self.verbose > 2:
self.log.info(
f"\t\t{dns.queries} queries {dns.nqueries} answers {dns.nanswers}")
if udp.src_port == 53 or udp.dst_port == 53:
pass
else:
pinfo["a1_port_trojan"] = "True"
pinfo["a1_port_trojan_exp_proto"] = Protocols(
udp, "UDP").protos
pinfo["a1_port_trojan_act_l4_proto"] = "UDP"
pinfo["a1_port_trojan_act_l7_proto"] = "dns"
except Exception as e:
pass
# self.log.warn(e)
if pinfo["a1_port_trojan"] == "True":
match pinfo["a1_port_trojan_act_l4_proto"]:
case "UDP":
trojan_packet = udp
case "TCP":
trojan_packet = tcp
if self.verbose > 1:
self.log.warn(
f"\tTrojan protocol detected! from {ip.src}:{trojan_packet.src_port} to {ip.dst}:{trojan_packet.dst_port}")
self.log.warn(
f"\texpected {pinfo['a1_port_trojan_exp_proto']} got {pinfo['a1_port_trojan_act_l7_proto']}")
os.mkdir(f"{self.out}{self.counter}")
with open(f"{self.out}{self.counter}/info.yml", "w") as fp:
fp.write(yaml.dump(pinfo))
with open(f"{self.out}{self.counter}/raw.bin", "wb") as fp:
fp.write(ip.data)
matches = self.rules.match(f"{self.out}{self.counter}/info.yml")
for i in self.rules_RAW.match(f"{self.out}{self.counter}/raw.bin"):
matches.append(i)
if matches != []:
self.log.alert("\tPacket matched!")
if self.verbose > 1 and self.verbose <= 2:
self.log.alert(
"\t" + " ".join([rule.rule for rule in matches]))
end_verdict = "accept"
for match_ in matches:
if self.verbose > 2:
self.log.alert(
f"\t{match_.rule} - {match_.meta['behaviour']}")
for behaviour in match_.meta['behaviour'].split():
match behaviour:
case "drop":
end_verdict = "drop"
case "accept":
if end_verdict != "drop":
end_verdict = "accept"
case "log":
print("TODO: this")
if end_verdict == "accept":
packet.accept()
else:
packet.drop()
else:
packet.accept()
if __name__ == "__main__":
log = Log()
log.succ("pkt v1.0.0")
if os.geteuid() != 0:
log.warn('This script needs to be run as root')
sys.exit(1)
parser = argparse.ArgumentParser(
description='A stateless firewall with yara like rules in python.', allow_abbrev=True)
parser.add_argument('--verbose', '-v', action='count',
default=0, help='Increases verbosity')
parser.add_argument(
'--rules', '-r', help='The directory in which the rules are stored', type=str, default='rules/')
parser.add_argument(
'--out', '-o', help='The directory in which the packet output is stored', type=str, default='packets/')
parser.add_argument('--service', '-s',
help='Systemd service configuration', choices=['start', 'stop', 'restart', 'install', 'uninstall'], type=str, default=None)
parser.add_argument(
'--daemon', '-d', help='If you are running pkt as a daemon', type=bool)
args = parser.parse_args()
if args.service != None:
match args.service:
case 'start':
os.system('systemctl start pkt.service')
case 'stop':
os.system('systemctl stop pkt.service')
case 'restart':
os.system('systemctl restart pkt.service')
case 'install':
shutil.copyfile('lib/pkt.service',
'/etc/systemd/system/pkt.service')
os.system('systemctl enable pkt.service')
case 'uninstall':
os.system('systemctl disable pkt.service')
os.remove('/etc/systemd/system/pkt.service')
else:
verbosity = 1 if args.daemon else args.verbose
_pkt = Pkt(verbosity, args.rules, args.out)
_pkt.run()