forked from henrypp/simplewall
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_profile_blocklist.py
197 lines (146 loc) · 5.92 KB
/
build_profile_blocklist.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
import os
import math
import re
import xml.dom.minidom
import ctypes
from ctypes import wintypes
FORMATS = {
"COMPRESSION_FORMAT_LZNT1" : ctypes.c_uint16 (2),
"COMPRESSION_FORMAT_XPRESS" : ctypes.c_uint16 (3),
"COMPRESSION_FORMAT_XPRESS_HUFF" : ctypes.c_uint16 (4)
}
ENGINES = {
"COMPRESSION_ENGINE_STANDARD" : ctypes.c_uint16 (0),
"COMPRESSION_ENGINE_MAXIMUM" : ctypes.c_uint16 (256)
}
def natural_sort (list, key=lambda s:s):
def get_alphanum_key_func (key):
convert = lambda text: int (text) if text.isdigit () else text
return lambda s: [convert (c) for c in re.split ('([0-9]+)', key (s))]
list.sort (key=get_alphanum_key_func (key))
def human_readable_size (size, decimal_places=2):
for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']:
if size < 1024.0 or unit == 'PiB':
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
def pack_file_lznt (buffer_data, buffer_length):
format_and_engine = wintypes.USHORT (FORMATS["COMPRESSION_FORMAT_LZNT1"].value | ENGINES["COMPRESSION_ENGINE_MAXIMUM"].value)
workspace_buffer_size = wintypes.ULONG()
workspace_fragment_size = wintypes.ULONG()
# RtlGetCompressionWorkSpaceSize
ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize.restype = wintypes.LONG
ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize.argtypes = (
wintypes.USHORT,
wintypes.PULONG,
wintypes.PULONG
)
status = ctypes.windll.ntdll.RtlGetCompressionWorkSpaceSize (
format_and_engine,
ctypes.byref(workspace_buffer_size),
ctypes.byref(workspace_fragment_size)
)
if status != 0:
print ('RtlGetCompressionWorkSpaceSize failed: 0x{0:X} {0:d} ({1:s})'.format(status, ctypes.FormatError(status)))
return None, 0
# Allocate memory
compressed_buffer = ctypes.create_string_buffer (buffer_length)
compressed_length = wintypes.ULONG()
workspace = ctypes.create_string_buffer (workspace_fragment_size.value)
# RtlCompressBuffer
ctypes.windll.ntdll.RtlCompressBuffer.restype = wintypes.LONG
ctypes.windll.ntdll.RtlCompressBuffer.argtypes = (
wintypes.USHORT,
wintypes.LPVOID,
wintypes.ULONG,
wintypes.LPVOID,
wintypes.ULONG,
wintypes.ULONG,
wintypes.PULONG,
wintypes.LPVOID
)
status = ctypes.windll.ntdll.RtlCompressBuffer (
format_and_engine,
ctypes.addressof (buffer_data),
ctypes.sizeof (buffer_data),
ctypes.addressof (compressed_buffer),
ctypes.sizeof (compressed_buffer),
wintypes.ULONG (4096),
ctypes.byref (compressed_length),
ctypes.addressof (workspace)
)
if status != 0:
print ('RtlCompressBuffer failed: 0x{0:X} {0:d} ({1:s})'.format (status, ctypes.FormatError(status)))
return None, 0
return compressed_buffer, compressed_length
CURRENT_DIRECTORY = os.path.dirname (os.path.abspath (__file__))
RULES_DIR = os.path.join (CURRENT_DIRECTORY, '..', '!repos', 'WindowsSpyBlocker', 'data', 'firewall')
RULES_FILE = os.path.join (CURRENT_DIRECTORY, 'bin', 'profile_internal.xml')
RULES_FILE_PACKED = os.path.join (CURRENT_DIRECTORY, 'bin', 'profile_internal_packed.bin')
if not os.path.isdir (RULES_DIR):
raise Exception ('Rules directory not found: ' + RULES_DIR)
if not os.path.isfile (RULES_FILE):
raise Exception ('Profile internal not found: ' + RULES_FILE)
# Open profile xml
with open (RULES_FILE, 'r', newline='') as f:
data = f.read ()
if not data:
raise Exception ('File reading failure: ' + RULES_FILE)
# toprettyxml() hack
data = data.replace ('\n', '')
data = data.replace ('\t', '')
xml_doc = xml.dom.minidom.parseString (data)
xml_root = xml_doc.getElementsByTagName ("root")
f.close ()
# Store timestamp
timestamp = int (xml_root[0].getAttribute ('timestamp'))
# Cleanup xml
for node in xml_doc.getElementsByTagName ('rules_blocklist'):
parent = node.parentNode
parent.removeChild (node)
xml_root[0].appendChild (xml_doc.createElement ('rules_blocklist'))
xml_section = xml_doc.getElementsByTagName ('rules_blocklist')
if not xml_section:
raise Exception ('Parse xml failure.')
# Enumerate Windows Spy Blocker spy/extra and update rules
for file_name in os.listdir (RULES_DIR):
module_name = os.path.splitext (file_name)[0]
module_path = os.path.join (RULES_DIR, file_name)
print ('Parsing ' + module_name + '...')
lastmod = int (os.path.getmtime (module_path));
if lastmod > timestamp:
timestamp = lastmod;
with open (module_path, 'r') as f:
rows = f.readlines ()
natural_sort (rows)
f.close ()
for string in rows:
line = string.strip ("\n\r\t ")
if line and not line.startswith ('#') and not line.startswith ('<') and not line.startswith ('>') and not line.startswith ('='):
new_item = xml_doc.createElement ('item')
new_item.setAttribute ('name', module_name + '_' + line)
new_item.setAttribute ('rule', line)
xml_section[0].appendChild (new_item)
# Set new rule timestamp
xml_root[0].setAttribute ('timestamp', str (timestamp))
# Save updated profile xml
data = xml_doc.toprettyxml (indent="\t", newl="\n")
if data:
data = data.replace ('/>', ' />')
with open (RULES_FILE, 'w', newline='') as fn:
fn.write (data)
fn.close ()
with open (RULES_FILE, 'rb') as fn:
data = fn.read ()
if data:
data_length = len (data)
data_buffer = (data_length * ctypes.c_ubyte).from_buffer_copy (data)
compressed_buffer, compressed_size = pack_file_lznt (data_buffer, data_length)
print ('\nPacking rules from %s to %s (%s saved)...' % (human_readable_size (data_length), human_readable_size (compressed_size.value), human_readable_size (data_length - compressed_size.value)))
if compressed_buffer != None and compressed_size.value != 0:
with open (RULES_FILE_PACKED, 'wb') as fn_pack:
write_array_buffer = (compressed_size.value * ctypes.c_ubyte).from_buffer_copy (compressed_buffer)
fn_pack.write (write_array_buffer)
fn_pack.close ()
fn.close ()
print ('\nBlocklist timetamp ' + str (timestamp))