strindex 3.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- strindex/__init__.py +1 -0
- strindex/__main__.py +4 -0
- strindex/strindex.py +965 -0
- strindex-3.2.0.dist-info/LICENSE +21 -0
- strindex-3.2.0.dist-info/METADATA +89 -0
- strindex-3.2.0.dist-info/RECORD +9 -0
- strindex-3.2.0.dist-info/WHEEL +5 -0
- strindex-3.2.0.dist-info/entry_points.txt +3 -0
- strindex-3.2.0.dist-info/top_level.txt +1 -0
strindex/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import strindex
|
strindex/__main__.py
ADDED
strindex/strindex.py
ADDED
|
@@ -0,0 +1,965 @@
|
|
|
1
|
+
import os, sys, argparse, json, pefile, re
|
|
2
|
+
from hashlib import md5
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
SECTION_NAME = b".strdex"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PrintProgress():
|
|
9
|
+
"""
|
|
10
|
+
Extremely fast class to print progress percentage.
|
|
11
|
+
Only takes ~0.1 seconds every 1'000'000 calls,
|
|
12
|
+
or half of that if "iteration >= self.limit" is checked within the loop.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
total: int
|
|
16
|
+
limit: int
|
|
17
|
+
delta: int
|
|
18
|
+
round: int
|
|
19
|
+
percent: float
|
|
20
|
+
print_end: str
|
|
21
|
+
|
|
22
|
+
def __init__(self, total: int, round: int = 0):
|
|
23
|
+
global global_progress
|
|
24
|
+
global_progress = self
|
|
25
|
+
self.total = total
|
|
26
|
+
self.limit = 0
|
|
27
|
+
self.delta = total // (10 ** (round + 2))
|
|
28
|
+
self.round = None if round == 0 else round
|
|
29
|
+
self.percent = 0
|
|
30
|
+
self.print_end = "%" + " " * (round + 3) + "\r"
|
|
31
|
+
self(0)
|
|
32
|
+
|
|
33
|
+
def __call__(self, iteration: int):
|
|
34
|
+
if iteration >= self.limit:
|
|
35
|
+
self.limit += self.delta
|
|
36
|
+
self.percent = round(iteration / self.total * 100, self.round)
|
|
37
|
+
if callable(PrintProgress.callback):
|
|
38
|
+
PrintProgress.callback(self)
|
|
39
|
+
else:
|
|
40
|
+
print(self.percent, end=self.print_end)
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def callback():
|
|
44
|
+
return globals().get("__print_progress_callback__")
|
|
45
|
+
|
|
46
|
+
class Strindex():
|
|
47
|
+
""" A class to parse and create strindex files. """
|
|
48
|
+
|
|
49
|
+
CHARACTER_CLASSES = { # Please add your language's characters here and open a pull request <3
|
|
50
|
+
"default": """\t\n !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~… """,
|
|
51
|
+
"latin": """ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz""",
|
|
52
|
+
"spanish": """¡¿ÁÉÍÓÚÜÑáéíóúüñã""",
|
|
53
|
+
"cyrillic": """ЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяѐёђѓєѕіїјљњћќѝўџѠѡѢѣѤѥѦѧѨѩѪѫѬѭѮѯѰѱѲѳѴѵѶѷѸѹѺѻѼѽѾѿҀҁ҂҃҄҅҆҇҈҉ҊҋҌҍҎҏҐґҒғҔҕҖҗҘҙҚқҜҝҞҟҠҡҢңҤҥҦҧҨҩҪҫҬҭҮүҰұҲҳҴҵҶҷҸҹҺһҼҽҾҿӀӁӂӃӄӅӆӇӈӉӊӋӌӍӎӏӐӑӒӓӔӕӖӗӘәӚӛӜӝӞӟӠӡӢӣӤӥӦӧӨөӪӫӬӭӮӯӰӱӲӳӴӵӶӷӸӹӺӻӼӽӾ""",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
DELIMITERS = (f"{'=' * 80}", f"{'-' * 80}", f'/', f'-')
|
|
57
|
+
HEADER = f"You can freely delete informational lines in the header like this one.\n\n{{}}\n\n"
|
|
58
|
+
INFO = f"#{'=' * 79}/ offset / rva / offset(s)-of-rva-pointer(s) /\n"
|
|
59
|
+
COMPATIBLE_INFO = f"#{'=' * 79}[reallocate pointer(s) if 1]\n# replace this string...\n#{'-' * 79}\n# ...with this string!\n"
|
|
60
|
+
|
|
61
|
+
full_header: str
|
|
62
|
+
settings: dict
|
|
63
|
+
type_order: list[str]
|
|
64
|
+
rva_bytes_length: int
|
|
65
|
+
|
|
66
|
+
overwrite: list[str]
|
|
67
|
+
pointers: list[list[int]]
|
|
68
|
+
rvas: list[int]
|
|
69
|
+
offsets: list[int]
|
|
70
|
+
|
|
71
|
+
original: list[str]
|
|
72
|
+
replace: list[str]
|
|
73
|
+
pointers_switches: list[list[bool]]
|
|
74
|
+
|
|
75
|
+
def __init__(self, filepath: str):
|
|
76
|
+
""" Parses a strindex file and returns a dictionary with the data. """
|
|
77
|
+
|
|
78
|
+
self.full_header = ""
|
|
79
|
+
self.settings = {
|
|
80
|
+
"md5": None,
|
|
81
|
+
"whitelist": None,
|
|
82
|
+
"min_length": 0,
|
|
83
|
+
"prefix_bytes": [''],
|
|
84
|
+
"suffix_bytes": [''],
|
|
85
|
+
"patch_replace": {},
|
|
86
|
+
"clean_pattern": "",
|
|
87
|
+
"source_language": None,
|
|
88
|
+
"target_language": None,
|
|
89
|
+
"among_languages": [],
|
|
90
|
+
}
|
|
91
|
+
self.type_order = []
|
|
92
|
+
|
|
93
|
+
self.overwrite = []
|
|
94
|
+
self.pointers = []
|
|
95
|
+
self.rvas = []
|
|
96
|
+
self.offsets = []
|
|
97
|
+
|
|
98
|
+
self.original = []
|
|
99
|
+
self.replace = []
|
|
100
|
+
self.pointers_switches = []
|
|
101
|
+
|
|
102
|
+
with open(filepath, 'r', encoding='utf-8') as f:
|
|
103
|
+
while line := f.readline():
|
|
104
|
+
if line.startswith("{"):
|
|
105
|
+
strindex_settings_lines = line
|
|
106
|
+
self.full_header += line
|
|
107
|
+
while True:
|
|
108
|
+
try:
|
|
109
|
+
self.settings |= json.loads(strindex_settings_lines)
|
|
110
|
+
except json.JSONDecodeError as e:
|
|
111
|
+
line = f.readline()
|
|
112
|
+
if line.startswith(Strindex.DELIMITERS[0]):
|
|
113
|
+
raise ValueError("Error parsing Strindex settings.")
|
|
114
|
+
strindex_settings_lines += line
|
|
115
|
+
self.full_header += line
|
|
116
|
+
else:
|
|
117
|
+
break
|
|
118
|
+
elif line.startswith(Strindex.DELIMITERS[0]):
|
|
119
|
+
f.seek(f.tell() - len(line))
|
|
120
|
+
break
|
|
121
|
+
else:
|
|
122
|
+
self.full_header += line
|
|
123
|
+
|
|
124
|
+
next_lst = ""
|
|
125
|
+
is_start = True
|
|
126
|
+
while line := f.readline():
|
|
127
|
+
line = line.rstrip('\n')
|
|
128
|
+
if line.startswith(Strindex.DELIMITERS[0]):
|
|
129
|
+
is_start = True
|
|
130
|
+
line = line.lstrip(Strindex.DELIMITERS[0])
|
|
131
|
+
|
|
132
|
+
if next_lst == "original":
|
|
133
|
+
self.replace[-1] = self.original[-1]
|
|
134
|
+
|
|
135
|
+
if Strindex.DELIMITERS[2] in line:
|
|
136
|
+
next_lst = "overwrite"
|
|
137
|
+
self.type_order.append("overwrite")
|
|
138
|
+
self.overwrite.append('')
|
|
139
|
+
|
|
140
|
+
needles = [[int(p, 16) if p else None for p in hex.split(Strindex.DELIMITERS[3])] for hex in line.split(Strindex.DELIMITERS[2])[1:-1]]
|
|
141
|
+
self.pointers.append(needles[-1] if any(needles[-1]) else [])
|
|
142
|
+
self.rvas.append(needles[-2][0] if len(needles) >= 2 else None)
|
|
143
|
+
self.offsets.append(needles[-3][0] if len(needles) >= 3 else None)
|
|
144
|
+
else:
|
|
145
|
+
next_lst = "original"
|
|
146
|
+
self.type_order.append("compatible")
|
|
147
|
+
self.original.append('')
|
|
148
|
+
self.replace.append('')
|
|
149
|
+
|
|
150
|
+
self.pointers_switches.append([bool(int(p)) for p in line])
|
|
151
|
+
elif line == Strindex.DELIMITERS[1] and next_lst == "original":
|
|
152
|
+
is_start = True
|
|
153
|
+
next_lst = "replace"
|
|
154
|
+
else:
|
|
155
|
+
if not is_start:
|
|
156
|
+
line = "\n" + line
|
|
157
|
+
is_start = False
|
|
158
|
+
|
|
159
|
+
getattr(self, next_lst)[-1] += line
|
|
160
|
+
|
|
161
|
+
self.settings["prefix_bytes"] = [bytes.fromhex(prefix) for prefix in self.settings["prefix_bytes"]]
|
|
162
|
+
self.settings["suffix_bytes"] = [bytes.fromhex(suffix) for suffix in self.settings["suffix_bytes"]]
|
|
163
|
+
self.settings["whitelist"] = set(''.join([Strindex.CHARACTER_CLASSES.get(whitelist, whitelist) for whitelist in (self.settings["whitelist"] + ["default"])])) if self.settings["whitelist"] else None
|
|
164
|
+
self.rva_bytes_length = (-((len(hex(max([r for r in self.rvas if r is not None] + [0]))) - 2) // -8)) * 4
|
|
165
|
+
|
|
166
|
+
assert len(self.overwrite) == len(self.pointers), "Overwrite and pointers lists are not the same length."
|
|
167
|
+
assert len(self.original) == len(self.replace) == len(self.pointers_switches), "Original, replace and pointers_switches lists are not the same length."
|
|
168
|
+
assert len(self.type_order) == len(self.overwrite) + len(self.original), "Type order list is not the same length."
|
|
169
|
+
|
|
170
|
+
def get_ordered_lines(self, override = None) -> list[str]:
|
|
171
|
+
ordered_lines = []
|
|
172
|
+
types = {}
|
|
173
|
+
for type in self.type_order:
|
|
174
|
+
if override:
|
|
175
|
+
type = override(type)
|
|
176
|
+
types[type] = (types[type] + 1) if type in types else 0
|
|
177
|
+
ordered_lines.append(getattr(self, type)[types[type]])
|
|
178
|
+
return ordered_lines
|
|
179
|
+
|
|
180
|
+
def create_raw_from_index(self, index: int) -> str:
|
|
181
|
+
type_wanted = self.type_order[index]
|
|
182
|
+
type_index = self.type_order[:index].count(type_wanted)
|
|
183
|
+
|
|
184
|
+
if type_wanted == "overwrite":
|
|
185
|
+
return Strindex.create_raw_from_args(
|
|
186
|
+
self.offsets[type_index],
|
|
187
|
+
self.rvas[type_index],
|
|
188
|
+
self.pointers[type_index],
|
|
189
|
+
self.overwrite[type_index],
|
|
190
|
+
self.rva_bytes_length
|
|
191
|
+
)
|
|
192
|
+
elif type_wanted == "compatible":
|
|
193
|
+
return Strindex.create_compatible_raw_from_args(
|
|
194
|
+
self.pointers_switches[type_index],
|
|
195
|
+
self.original[type_index],
|
|
196
|
+
self.replace[type_index]
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def create_raw_from_args(offset, rva, pointers, overwrite, rva_byte_length) -> str:
|
|
201
|
+
return (
|
|
202
|
+
Strindex.DELIMITERS[0] + Strindex.DELIMITERS[2] +
|
|
203
|
+
hex(offset or 0).lstrip("0x").rjust(8, '0') + Strindex.DELIMITERS[2] +
|
|
204
|
+
hex(rva or 0).lstrip("0x").rjust(rva_byte_length*2, '0') + Strindex.DELIMITERS[2] +
|
|
205
|
+
Strindex.DELIMITERS[3].join([hex(p or 0).lstrip("0x").rjust(8, '0') for p in pointers]) +
|
|
206
|
+
Strindex.DELIMITERS[2] + "\n" +
|
|
207
|
+
overwrite + "\n"
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def create_compatible_raw_from_args(pointers_switches, original, replace) -> str:
|
|
212
|
+
return (
|
|
213
|
+
Strindex.DELIMITERS[0] +
|
|
214
|
+
"".join([str(int(bool(p))) for p in pointers_switches]) + "\n" +
|
|
215
|
+
original + "\n" +
|
|
216
|
+
Strindex.DELIMITERS[1] + "\n" +
|
|
217
|
+
replace + "\n"
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def pe_adjust_optional_header(pe: pefile.PE) -> pefile.PE:
|
|
223
|
+
"""
|
|
224
|
+
Recalculates the SizeOfImage, SizeOfCode, SizeOfInitializedData and
|
|
225
|
+
SizeOfUninitializedData of the optional header.
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
# SizeOfImage = ((VirtualAddress + VirtualSize) of the new last section)
|
|
229
|
+
pe.OPTIONAL_HEADER.SizeOfImage = pe.sections[-1].VirtualAddress + pe.sections[-1].Misc_VirtualSize
|
|
230
|
+
|
|
231
|
+
pe.OPTIONAL_HEADER.SizeOfCode = 0
|
|
232
|
+
pe.OPTIONAL_HEADER.SizeOfInitializedData = 0
|
|
233
|
+
pe.OPTIONAL_HEADER.SizeOfUninitializedData = 0
|
|
234
|
+
|
|
235
|
+
# Recalculating the sizes by iterating over every section and checking if
|
|
236
|
+
# the appropriate characteristics are set.
|
|
237
|
+
for section in pe.sections:
|
|
238
|
+
if section.Characteristics & 0x00000020:
|
|
239
|
+
# Section contains code.
|
|
240
|
+
pe.OPTIONAL_HEADER.SizeOfCode += section.SizeOfRawData
|
|
241
|
+
if section.Characteristics & 0x00000040:
|
|
242
|
+
# Section contains initialized data.
|
|
243
|
+
pe.OPTIONAL_HEADER.SizeOfInitializedData += section.SizeOfRawData
|
|
244
|
+
if section.Characteristics & 0x00000080:
|
|
245
|
+
# Section contains uninitialized data.
|
|
246
|
+
pe.OPTIONAL_HEADER.SizeOfUninitializedData += section.SizeOfRawData
|
|
247
|
+
|
|
248
|
+
return pe
|
|
249
|
+
|
|
250
|
+
def pe_add_header_space(pe: pefile.PE) -> pefile.PE:
|
|
251
|
+
"""
|
|
252
|
+
To make space for a new section header a buffer filled with nulls is added at the
|
|
253
|
+
end of the headers. The buffer has the size of one file alignment.
|
|
254
|
+
The data between the last section header and the end of the headers is copied to
|
|
255
|
+
the new space (everything moved by the size of one file alignment).
|
|
256
|
+
If any data directory entry points to the moved data the pointer is adjusted.
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
FileAlignment = pe.OPTIONAL_HEADER.FileAlignment
|
|
260
|
+
SizeOfHeaders = pe.OPTIONAL_HEADER.SizeOfHeaders
|
|
261
|
+
|
|
262
|
+
data = b'\x00' * FileAlignment
|
|
263
|
+
|
|
264
|
+
# Adding the null buffer.
|
|
265
|
+
pe.__data__ = pe.__data__[:SizeOfHeaders] + data + pe.__data__[SizeOfHeaders:]
|
|
266
|
+
|
|
267
|
+
section_table_offset = (
|
|
268
|
+
pe.DOS_HEADER.e_lfanew + 4 + pe.FILE_HEADER.sizeof() + pe.FILE_HEADER.SizeOfOptionalHeader
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
# Copying the data between the last section header and SizeOfHeaders to the newly allocated
|
|
272
|
+
# space.
|
|
273
|
+
new_section_offset = section_table_offset + pe.FILE_HEADER.NumberOfSections*0x28
|
|
274
|
+
size = SizeOfHeaders - new_section_offset
|
|
275
|
+
data = pe.get_data(new_section_offset, size)
|
|
276
|
+
pe.set_bytes_at_offset(new_section_offset + FileAlignment, data)
|
|
277
|
+
|
|
278
|
+
# Filling the space, from which the data was copied from, with NULLs.
|
|
279
|
+
pe.set_bytes_at_offset(new_section_offset, b'\x00' * FileAlignment)
|
|
280
|
+
|
|
281
|
+
data_directory_offset = section_table_offset - pe.OPTIONAL_HEADER.NumberOfRvaAndSizes * 0x8
|
|
282
|
+
|
|
283
|
+
# Checking data directories if anything points to the space between the last section header
|
|
284
|
+
# and the former SizeOfHeaders. If that's the case the pointer is increased by FileAlignment.
|
|
285
|
+
for data_offset in range(data_directory_offset, section_table_offset, 0x8):
|
|
286
|
+
data_rva = pe.get_dword_from_offset(data_offset)
|
|
287
|
+
|
|
288
|
+
if new_section_offset <= data_rva and data_rva < SizeOfHeaders:
|
|
289
|
+
pe.set_dword_at_offset(data_offset, data_rva + FileAlignment)
|
|
290
|
+
|
|
291
|
+
SizeOfHeaders_offset = pe.DOS_HEADER.e_lfanew + 4 + pe.FILE_HEADER.sizeof() + 0x3C
|
|
292
|
+
|
|
293
|
+
# Adjusting the SizeOfHeaders value.
|
|
294
|
+
pe.set_dword_at_offset(SizeOfHeaders_offset, SizeOfHeaders + FileAlignment)
|
|
295
|
+
|
|
296
|
+
section_raw_address_offset = section_table_offset + 0x14
|
|
297
|
+
|
|
298
|
+
# The raw addresses of the sections are adjusted.
|
|
299
|
+
for section in pe.sections:
|
|
300
|
+
if section.PointerToRawData != 0:
|
|
301
|
+
pe.set_dword_at_offset(section_raw_address_offset, section.PointerToRawData+FileAlignment)
|
|
302
|
+
|
|
303
|
+
section_raw_address_offset += 0x28
|
|
304
|
+
|
|
305
|
+
# All changes in this method were made to the raw data (__data__). To make these changes
|
|
306
|
+
# accessbile in pe __data__ has to be parsed again. Since a new pefile is parsed during
|
|
307
|
+
# the init method, the easiest way is to replace pe with a new pefile based on __data__
|
|
308
|
+
# of the old pe.
|
|
309
|
+
pe = pefile.PE(data=pe.__data__, fast_load=True)
|
|
310
|
+
|
|
311
|
+
return pe
|
|
312
|
+
|
|
313
|
+
def pe_add_section(pe: pefile.PE, Name: str, Data: str, Characteristics=0xE00000E0, VirtualSize=0x00000000, VirtualAddress=0x00000000, RawSize=0x00000000, RawAddress=0x00000000) -> pefile.PE:
|
|
314
|
+
"""
|
|
315
|
+
Tested with pefile 1.2.10-123 on 32bit PE executable files.
|
|
316
|
+
An implementation to push a section header to the section table of a PE file.
|
|
317
|
+
by n0p
|
|
318
|
+
|
|
319
|
+
Adds the section, specified by the functions parameters, at the end of the section table.
|
|
320
|
+
If the space to add an additional section header is insufficient, a buffer is inserted
|
|
321
|
+
after SizeOfHeaders. Data between the last section header and the end of SizeOfHeaders
|
|
322
|
+
is copied to +1 FileAlignment. Data directory entries pointing to this data are fixed.
|
|
323
|
+
|
|
324
|
+
If a RawSize > 0 is set or Data is given the data gets aligned to the FileAlignment and
|
|
325
|
+
is attached at the end of the file.
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
if pe.FILE_HEADER.NumberOfSections == len(pe.sections):
|
|
329
|
+
|
|
330
|
+
FileAlignment = pe.OPTIONAL_HEADER.FileAlignment
|
|
331
|
+
SectionAlignment = pe.OPTIONAL_HEADER.SectionAlignment
|
|
332
|
+
|
|
333
|
+
if len(Name) > 8:
|
|
334
|
+
raise ValueError("The name is too long for a section.")
|
|
335
|
+
|
|
336
|
+
if (
|
|
337
|
+
VirtualAddress < (pe.sections[-1].Misc_VirtualSize + pe.sections[-1].VirtualAddress)
|
|
338
|
+
or VirtualAddress % SectionAlignment != 0
|
|
339
|
+
):
|
|
340
|
+
if (pe.sections[-1].Misc_VirtualSize % SectionAlignment) != 0:
|
|
341
|
+
VirtualAddress = (
|
|
342
|
+
pe.sections[-1].VirtualAddress + pe.sections[-1].Misc_VirtualSize -
|
|
343
|
+
(pe.sections[-1].Misc_VirtualSize % SectionAlignment) + SectionAlignment
|
|
344
|
+
)
|
|
345
|
+
else:
|
|
346
|
+
VirtualAddress = pe.sections[-1].VirtualAddress + pe.sections[-1].Misc_VirtualSize
|
|
347
|
+
|
|
348
|
+
if VirtualSize < len(Data):
|
|
349
|
+
VirtualSize = len(Data)
|
|
350
|
+
|
|
351
|
+
if (len(Data) % FileAlignment) != 0:
|
|
352
|
+
# Padding the data of the section.
|
|
353
|
+
Data += b'\x00' * (FileAlignment - (len(Data) % FileAlignment))
|
|
354
|
+
|
|
355
|
+
if RawSize != len(Data):
|
|
356
|
+
if RawSize > len(Data) and (RawSize % FileAlignment) == 0:
|
|
357
|
+
Data += b'\x00' * (RawSize - (len(Data) % RawSize))
|
|
358
|
+
else:
|
|
359
|
+
RawSize = len(Data)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
section_table_offset = (
|
|
363
|
+
pe.DOS_HEADER.e_lfanew + 4 + pe.FILE_HEADER.sizeof() + pe.FILE_HEADER.SizeOfOptionalHeader
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
# If the new section header exceeds the SizeOfHeaders there won't be enough space
|
|
367
|
+
# for an additional section header. Besides that it's checked if the 0x28 bytes
|
|
368
|
+
# (size of one section header) after the last current section header are filled
|
|
369
|
+
# with nulls/ are free to use.
|
|
370
|
+
if (
|
|
371
|
+
pe.OPTIONAL_HEADER.SizeOfHeaders < section_table_offset + (pe.FILE_HEADER.NumberOfSections+1)*0x28
|
|
372
|
+
or not all(char == b'\x00' for char in pe.get_data(section_table_offset + (pe.FILE_HEADER.NumberOfSections)*0x28, 0x28))
|
|
373
|
+
):
|
|
374
|
+
# Checking if more space can be added.
|
|
375
|
+
if pe.OPTIONAL_HEADER.SizeOfHeaders < pe.sections[0].VirtualAddress:
|
|
376
|
+
pe = pe_add_header_space(pe)
|
|
377
|
+
# print("Additional space to add a new section header was allocated.")
|
|
378
|
+
else:
|
|
379
|
+
raise ValueError("No more space can be added for the section header.")
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
# The validity check of RawAddress is done after space for a new section header may
|
|
383
|
+
# have been added because if space had been added the PointerToRawData of the previous
|
|
384
|
+
# section would have changed.
|
|
385
|
+
if RawAddress != pe.sections[-1].PointerToRawData + pe.sections[-1].SizeOfRawData:
|
|
386
|
+
RawAddress = pe.sections[-1].PointerToRawData + pe.sections[-1].SizeOfRawData
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
# Appending the data of the new section to the file.
|
|
390
|
+
if len(Data) > 0:
|
|
391
|
+
pe.__data__ = pe.__data__[:RawAddress] + Data + pe.__data__[RawAddress:]
|
|
392
|
+
|
|
393
|
+
section_offset = section_table_offset + pe.FILE_HEADER.NumberOfSections*0x28
|
|
394
|
+
|
|
395
|
+
# Manually writing the data of the section header to the file.
|
|
396
|
+
pe.set_bytes_at_offset(section_offset, Name)
|
|
397
|
+
pe.set_dword_at_offset(section_offset+0x08, VirtualSize)
|
|
398
|
+
pe.set_dword_at_offset(section_offset+0x0C, VirtualAddress)
|
|
399
|
+
pe.set_dword_at_offset(section_offset+0x10, RawSize)
|
|
400
|
+
pe.set_dword_at_offset(section_offset+0x14, RawAddress)
|
|
401
|
+
pe.set_dword_at_offset(section_offset+0x18, 0x00000000)
|
|
402
|
+
pe.set_dword_at_offset(section_offset+0x1C, 0x00000000)
|
|
403
|
+
pe.set_word_at_offset(section_offset+0x20, 0x0000)
|
|
404
|
+
pe.set_word_at_offset(section_offset+0x22, 0x0000)
|
|
405
|
+
pe.set_dword_at_offset(section_offset+0x24, Characteristics)
|
|
406
|
+
|
|
407
|
+
pe.FILE_HEADER.NumberOfSections += 1
|
|
408
|
+
|
|
409
|
+
# Parsing the section table of the file again to add the new section to the sections
|
|
410
|
+
# list of pefile.
|
|
411
|
+
pe.parse_sections(section_table_offset)
|
|
412
|
+
|
|
413
|
+
pe = pe_adjust_optional_header(pe)
|
|
414
|
+
else:
|
|
415
|
+
raise ValueError(
|
|
416
|
+
"The NumberOfSections specified in the file header and the size of the sections list of pefile don't match."
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
return pe
|
|
420
|
+
|
|
421
|
+
def pe_get_new_section_base_rva(pe: pefile.PE) -> int:
|
|
422
|
+
""" Returns the base rva for a possibly new PE section. """
|
|
423
|
+
new_section_base_rva = pe.sections[-1].VirtualAddress + pe.sections[-1].Misc_VirtualSize
|
|
424
|
+
if new_section_base_rva % pe.OPTIONAL_HEADER.SectionAlignment:
|
|
425
|
+
new_section_base_rva += pe.OPTIONAL_HEADER.SectionAlignment - (new_section_base_rva % pe.OPTIONAL_HEADER.SectionAlignment)
|
|
426
|
+
new_section_base_rva += pe.OPTIONAL_HEADER.ImageBase
|
|
427
|
+
return new_section_base_rva
|
|
428
|
+
|
|
429
|
+
def pe_section_exists(pe: pefile.PE, section_name: str) -> bool:
|
|
430
|
+
""" Checks if a section with the specified name exists. """
|
|
431
|
+
return any(sect.Name == section_name.ljust(8, b'\x00') for sect in pe.sections)
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def mmap_indices_ordered(mm: bytearray, search_lst: list[bytes], prefix: bytes = b"", suffix: bytes = b"") -> list[int]:
|
|
436
|
+
"""
|
|
437
|
+
Returns the index of the first occurrence of every search list string in a mmap.
|
|
438
|
+
Extremely fast, but can only can work for search lists that are ordered by occurrence order.
|
|
439
|
+
"""
|
|
440
|
+
search_lst = [bytes(search, 'utf-8') if isinstance(search, str) else search for search in search_lst]
|
|
441
|
+
indices = []
|
|
442
|
+
prefix_length = len(prefix)
|
|
443
|
+
start_index = 0
|
|
444
|
+
for search_index in range(len(search_lst)):
|
|
445
|
+
index = mm.find(prefix + search_lst[search_index] + suffix, start_index)
|
|
446
|
+
if index == -1:
|
|
447
|
+
indices.append(None)
|
|
448
|
+
continue
|
|
449
|
+
start_index = index + prefix_length + len(search_lst[search_index])
|
|
450
|
+
indices.append(index + prefix_length)
|
|
451
|
+
return indices
|
|
452
|
+
|
|
453
|
+
def mmap_indices_fixed(mm: bytearray, search_lst: list[bytes], prefixes: list[bytes] = [b""], suffixes: list[bytes] = [b""]) -> list[list[int]]:
|
|
454
|
+
"""
|
|
455
|
+
Returns a list containing the indexes of each occurrence of every search list string in a mmap.
|
|
456
|
+
Extremely fast, but can only can work for unique search strings of fixed length (length is taken from 1st element).
|
|
457
|
+
"""
|
|
458
|
+
if not search_lst:
|
|
459
|
+
return []
|
|
460
|
+
|
|
461
|
+
search_lst_safe = [s for s in search_lst if s is not None]
|
|
462
|
+
|
|
463
|
+
assert len(search_lst_safe) == len(set(search_lst_safe)), "Search list is not unique."
|
|
464
|
+
assert all(len(search) == len(search_lst_safe[0]) for search in search_lst_safe), "Search list is not fixed length."
|
|
465
|
+
assert all(len(prefix) == len(prefixes[0]) for prefix in prefixes), "Prefix list is not fixed length."
|
|
466
|
+
|
|
467
|
+
print_progress = PrintProgress(len(mm))
|
|
468
|
+
fixed_prefix_length = len(prefixes[0])
|
|
469
|
+
fixed_length = fixed_prefix_length + len(search_lst_safe[0]) + len(suffixes[0])
|
|
470
|
+
|
|
471
|
+
indices_dict = {}
|
|
472
|
+
for search_string in search_lst_safe:
|
|
473
|
+
lst = []
|
|
474
|
+
for prefix in prefixes:
|
|
475
|
+
for suffix in suffixes:
|
|
476
|
+
indices_dict[prefix + search_string + suffix] = lst
|
|
477
|
+
|
|
478
|
+
for mm_index in range(len(mm)):
|
|
479
|
+
cur_bytes = mm[mm_index:mm_index + fixed_length]
|
|
480
|
+
if cur_bytes in indices_dict:
|
|
481
|
+
indices_dict[cur_bytes].append(mm_index + fixed_prefix_length)
|
|
482
|
+
if mm_index >= print_progress.limit:
|
|
483
|
+
print_progress(mm_index)
|
|
484
|
+
|
|
485
|
+
indices = list(indices_dict.values())[::len(prefixes) * len(suffixes)]
|
|
486
|
+
for search_index, search_string in enumerate(search_lst):
|
|
487
|
+
if search_string is None:
|
|
488
|
+
indices.insert(search_index, search_string)
|
|
489
|
+
|
|
490
|
+
return indices
|
|
491
|
+
|
|
492
|
+
def replace_with_table(string: str, table: dict[str, str]) -> str:
|
|
493
|
+
""" Replaces all occurrences of keys in a string with their corresponding table values. """
|
|
494
|
+
for key, value in table.items():
|
|
495
|
+
string = string.replace(key, value)
|
|
496
|
+
return string
|
|
497
|
+
|
|
498
|
+
def truncate_prev_char(file):
|
|
499
|
+
""" Truncates the last character of a file. """
|
|
500
|
+
file.seek(file.tell() - 1)
|
|
501
|
+
file.truncate()
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def create(file_filepath: str, strindex_filepath: str, compatible: bool, min_length, prefixes: list[bytes]):
|
|
506
|
+
"""
|
|
507
|
+
Creates a strindex file from a PE file.
|
|
508
|
+
|
|
509
|
+
It works by creating a dictionary with the strings
|
|
510
|
+
and their rva found in the PE file, that meet the filter criteria.
|
|
511
|
+
Then it finds the pointers (the assembly instructions' offsets)
|
|
512
|
+
for the rvas in the dictionary, by only looping the file once.
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
pe = pefile.PE(file_filepath, fast_load=True)
|
|
516
|
+
|
|
517
|
+
if pe_section_exists(pe, SECTION_NAME):
|
|
518
|
+
print(f"This file contains a '{SECTION_NAME.decode('utf-8')}' section. You might not want this.")
|
|
519
|
+
|
|
520
|
+
BYTE_LENGTH = 4 if pe.OPTIONAL_HEADER.Magic == 0x10b else 8
|
|
521
|
+
|
|
522
|
+
temp_strindex = {
|
|
523
|
+
"original": [],
|
|
524
|
+
"offsets": [],
|
|
525
|
+
"rva": [],
|
|
526
|
+
"rva_bytes": [],
|
|
527
|
+
"pointers": []
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
print_progress = PrintProgress(len(pe.__data__))
|
|
531
|
+
byte_string = b''
|
|
532
|
+
for offset, char in enumerate(pe.__data__):
|
|
533
|
+
if char == b'\x00':
|
|
534
|
+
try:
|
|
535
|
+
string = byte_string.decode('utf-8')
|
|
536
|
+
except UnicodeDecodeError:
|
|
537
|
+
continue
|
|
538
|
+
else:
|
|
539
|
+
if len(string) < min_length:
|
|
540
|
+
continue
|
|
541
|
+
offset -= len(byte_string)
|
|
542
|
+
rva = pe.get_rva_from_offset(offset)
|
|
543
|
+
if not rva:
|
|
544
|
+
continue
|
|
545
|
+
rva += pe.OPTIONAL_HEADER.ImageBase
|
|
546
|
+
temp_strindex["original"].append(string)
|
|
547
|
+
temp_strindex["offsets"].append(offset)
|
|
548
|
+
temp_strindex["rva"].append(rva)
|
|
549
|
+
temp_strindex["rva_bytes"].append(rva.to_bytes(BYTE_LENGTH, 'little'))
|
|
550
|
+
finally:
|
|
551
|
+
byte_string = b''
|
|
552
|
+
print_progress(offset)
|
|
553
|
+
else:
|
|
554
|
+
byte_string += char
|
|
555
|
+
|
|
556
|
+
if not temp_strindex["original"]:
|
|
557
|
+
raise ValueError("No strings found in the file.")
|
|
558
|
+
print(f"(1/3) Created search dictionary with {len(temp_strindex['original'])} strings.")
|
|
559
|
+
|
|
560
|
+
temp_strindex["pointers"] = mmap_indices_fixed(pe.__data__, temp_strindex["rva_bytes"], prefixes)
|
|
561
|
+
print(f"(2/3) Found pointers for {len([p for p in temp_strindex['pointers'] if p])} / {len(temp_strindex['original'])} strings.")
|
|
562
|
+
|
|
563
|
+
with open(strindex_filepath, 'w', encoding='utf-8') as f:
|
|
564
|
+
SETTINGS = {
|
|
565
|
+
"md5": md5(pe.__data__).hexdigest()
|
|
566
|
+
}
|
|
567
|
+
if prefixes != [b'']:
|
|
568
|
+
SETTINGS["prefix_bytes"] = [prefix.hex() for prefix in prefixes]
|
|
569
|
+
|
|
570
|
+
f.write(
|
|
571
|
+
Strindex.HEADER.format(json.dumps(SETTINGS, indent=4)) +
|
|
572
|
+
(Strindex.COMPATIBLE_INFO if compatible else Strindex.INFO)
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
for string, offset, rva, _, pointers in zip(*temp_strindex.values()):
|
|
576
|
+
if pointers:
|
|
577
|
+
if compatible:
|
|
578
|
+
f.write(Strindex.create_compatible_raw_from_args(pointers, string, string))
|
|
579
|
+
else:
|
|
580
|
+
f.write(Strindex.create_raw_from_args(offset, rva, pointers, string, BYTE_LENGTH))
|
|
581
|
+
|
|
582
|
+
truncate_prev_char(f)
|
|
583
|
+
print("(3/3) Created strindex file.")
|
|
584
|
+
|
|
585
|
+
def patch(file_filepath: str, strindex_filepath: str, file_patched_filepath: str):
|
|
586
|
+
"""
|
|
587
|
+
Patches a PE file with a strindex file.
|
|
588
|
+
It works by creating a new section with the strings from the strindex file,
|
|
589
|
+
and reallocating the original pointers with the new section's rva.
|
|
590
|
+
For "compatible" strindex files, the re-finding of strings works similarly to the "create" action.
|
|
591
|
+
"""
|
|
592
|
+
|
|
593
|
+
file_filepath_bak = file_filepath + '.bak'
|
|
594
|
+
|
|
595
|
+
pe = pefile.PE(file_filepath_bak if os.path.exists(file_filepath_bak) else file_filepath, fast_load=True)
|
|
596
|
+
|
|
597
|
+
if pe_section_exists(pe, SECTION_NAME):
|
|
598
|
+
raise ValueError(f"This file already contains a '{SECTION_NAME.decode('utf-8')}' section.")
|
|
599
|
+
|
|
600
|
+
if not file_patched_filepath and not os.path.exists(file_filepath_bak):
|
|
601
|
+
pe.write(file_filepath_bak)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
BYTE_LENGTH = 4 if pe.OPTIONAL_HEADER.Magic == 0x10b else 8
|
|
605
|
+
STRDEX_SECTION_BASE_RVA = pe_get_new_section_base_rva(pe)
|
|
606
|
+
STRINDEX = Strindex(strindex_filepath)
|
|
607
|
+
|
|
608
|
+
if STRINDEX.settings["md5"] and STRINDEX.settings["md5"] != md5(pe.__data__).hexdigest():
|
|
609
|
+
print("MD5 hash does not match the one the strindex was created for. You might encounter issues.")
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
new_section_data = bytearray()
|
|
613
|
+
get_original_rva = lambda offset: (pe.get_rva_from_offset(offset) + pe.OPTIONAL_HEADER.ImageBase).to_bytes(BYTE_LENGTH, 'little')
|
|
614
|
+
get_replaced_rva = lambda: (STRDEX_SECTION_BASE_RVA + len(new_section_data)).to_bytes(BYTE_LENGTH, 'little')
|
|
615
|
+
new_section_string = lambda string: bytearray(replace_with_table(string, STRINDEX.settings["patch_replace"]), 'utf-8') + b'\x00'
|
|
616
|
+
|
|
617
|
+
temp_strindex = {
|
|
618
|
+
"original_rva": [],
|
|
619
|
+
"replaced_rva": [],
|
|
620
|
+
"pointers": [],
|
|
621
|
+
"pointers_switches": []
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
# Deal with compatible strings
|
|
625
|
+
for strindex_index, offset in enumerate(mmap_indices_ordered(pe.__data__, STRINDEX.original, b"\x00", b"\x00")):
|
|
626
|
+
if offset is None:
|
|
627
|
+
print(f'String not found: "{STRINDEX.original[strindex_index]}"')
|
|
628
|
+
continue
|
|
629
|
+
|
|
630
|
+
temp_strindex["original_rva"].append(get_original_rva(offset))
|
|
631
|
+
temp_strindex["replaced_rva"].append(get_replaced_rva())
|
|
632
|
+
temp_strindex["pointers_switches"].append(STRINDEX.pointers_switches[strindex_index])
|
|
633
|
+
|
|
634
|
+
new_section_data += new_section_string(STRINDEX.replace[strindex_index])
|
|
635
|
+
|
|
636
|
+
temp_strindex["pointers"] = mmap_indices_fixed(pe.__data__, temp_strindex["original_rva"], STRINDEX.settings["prefix_bytes"], STRINDEX.settings["suffix_bytes"])
|
|
637
|
+
|
|
638
|
+
for original_rva, replaced_rva, pointers, pointers_switches in zip(*temp_strindex.values()):
|
|
639
|
+
if pointers:
|
|
640
|
+
for pointer, switch in zip(pointers, pointers_switches):
|
|
641
|
+
if switch:
|
|
642
|
+
pe.set_bytes_at_offset(pointer, replaced_rva)
|
|
643
|
+
else:
|
|
644
|
+
print("No pointers found for rva: " + original_rva.hex())
|
|
645
|
+
|
|
646
|
+
# Deal with pointers strings
|
|
647
|
+
for strindex_index in range(len(STRINDEX.overwrite)):
|
|
648
|
+
replaced_rva = get_replaced_rva()
|
|
649
|
+
new_section_data += new_section_string(STRINDEX.overwrite[strindex_index])
|
|
650
|
+
|
|
651
|
+
for pointer in STRINDEX.pointers[strindex_index]:
|
|
652
|
+
if pointer:
|
|
653
|
+
pe.set_bytes_at_offset(pointer, replaced_rva)
|
|
654
|
+
else:
|
|
655
|
+
print("No pointers found for string: " + STRINDEX.overwrite[strindex_index])
|
|
656
|
+
print("(1/3) Created section data & relocated pointers.")
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
pe = pe_add_section(pe, Name=SECTION_NAME, Data=new_section_data, Characteristics=0xF0000040)
|
|
660
|
+
print(f"(2/3) Added '{SECTION_NAME.decode('utf-8')}' section.")
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
pe.write(file_patched_filepath or file_filepath)
|
|
664
|
+
print("(3/3) File was patched successfully.")
|
|
665
|
+
|
|
666
|
+
def filter(strindex_filepath: str, strindex_filter_filepath: str):
|
|
667
|
+
"""
|
|
668
|
+
Filters a strindex file with a PE file with respect to length, whitelist and source language.
|
|
669
|
+
"""
|
|
670
|
+
|
|
671
|
+
STRINDEX = Strindex(strindex_filepath)
|
|
672
|
+
STRINDEX_LINES = STRINDEX.get_ordered_lines(lambda t: "original" if t == "compatible" else t)
|
|
673
|
+
|
|
674
|
+
if STRINDEX.settings["source_language"]:
|
|
675
|
+
try:
|
|
676
|
+
from lingua import IsoCode639_1, LanguageDetectorBuilder
|
|
677
|
+
except ImportError:
|
|
678
|
+
raise ImportError(
|
|
679
|
+
"Please install the 'lingua' package (pip install lingua) to filter by language."
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
ALL_LANGUAGES = [code for code in IsoCode639_1.__dict__.values() if isinstance(code, IsoCode639_1)]
|
|
683
|
+
SETTINGS_LANGUAGES = [getattr(IsoCode639_1, code.upper()) for code in STRINDEX.settings["among_languages"]]
|
|
684
|
+
|
|
685
|
+
detector = LanguageDetectorBuilder.from_iso_codes_639_1(*(SETTINGS_LANGUAGES or ALL_LANGUAGES)).build()
|
|
686
|
+
|
|
687
|
+
def is_source_language(string: str) -> bool:
|
|
688
|
+
line_clean = re.sub(STRINDEX.settings["clean_pattern"], "", string)
|
|
689
|
+
confidence = detector.compute_language_confidence_values(line_clean)[0]
|
|
690
|
+
return confidence.language.iso_code_639_1 == getattr(IsoCode639_1, STRINDEX.settings["source_language"].upper()) and confidence.value > 0.5
|
|
691
|
+
|
|
692
|
+
print_progress = PrintProgress(len(STRINDEX_LINES))
|
|
693
|
+
with open(strindex_filter_filepath, 'w', encoding='utf-8') as f:
|
|
694
|
+
f.write(STRINDEX.full_header)
|
|
695
|
+
|
|
696
|
+
for strindex_index, line in enumerate(STRINDEX_LINES):
|
|
697
|
+
if (
|
|
698
|
+
(not STRINDEX.settings["source_language"] or is_source_language(line)) and
|
|
699
|
+
(len(line) >= STRINDEX.settings["min_length"]) and
|
|
700
|
+
(not STRINDEX.settings.get("whitelist") or not any(ch not in STRINDEX.settings["whitelist"] for ch in line))
|
|
701
|
+
):
|
|
702
|
+
f.write(STRINDEX.create_raw_from_index(strindex_index))
|
|
703
|
+
|
|
704
|
+
print_progress(strindex_index)
|
|
705
|
+
|
|
706
|
+
truncate_prev_char(f)
|
|
707
|
+
print("(1/1) Created filtered strindex file.")
|
|
708
|
+
|
|
709
|
+
def update(file_filepath: str, strindex_filepath: str, strindex_update_filepath: str):
|
|
710
|
+
"""
|
|
711
|
+
Updates a compatible strindex file with the new pointers numbers.
|
|
712
|
+
"""
|
|
713
|
+
|
|
714
|
+
pe = pefile.PE(file_filepath, fast_load=True)
|
|
715
|
+
|
|
716
|
+
if pe_section_exists(pe, SECTION_NAME):
|
|
717
|
+
print(f"This file contains a '{SECTION_NAME.decode('utf-8')}' section. You might not want this.")
|
|
718
|
+
|
|
719
|
+
BYTE_LENGTH = 4 if pe.OPTIONAL_HEADER.Magic == 0x10b else 8
|
|
720
|
+
|
|
721
|
+
STRINDEX = Strindex(strindex_filepath)
|
|
722
|
+
STRINDEX_LINES = STRINDEX.get_ordered_lines(lambda t: "original" if t == "compatible" else t)
|
|
723
|
+
|
|
724
|
+
temp_strindex = {
|
|
725
|
+
"rva_bytes": [],
|
|
726
|
+
"pointers": []
|
|
727
|
+
}
|
|
728
|
+
for strindex_index, offset in enumerate(mmap_indices_ordered(pe.__data__, STRINDEX_LINES, b"\x00", b"\x00")):
|
|
729
|
+
if offset is None:
|
|
730
|
+
print(f'String not found: "{STRINDEX_LINES[strindex_index]}"')
|
|
731
|
+
temp_strindex["rva_bytes"].append(None)
|
|
732
|
+
continue
|
|
733
|
+
|
|
734
|
+
temp_strindex["rva_bytes"].append((pe.get_rva_from_offset(offset) + pe.OPTIONAL_HEADER.ImageBase).to_bytes(BYTE_LENGTH, 'little'))
|
|
735
|
+
|
|
736
|
+
temp_strindex["pointers"] = mmap_indices_fixed(pe.__data__, temp_strindex["rva_bytes"], STRINDEX.settings["prefix_bytes"], STRINDEX.settings["suffix_bytes"])
|
|
737
|
+
|
|
738
|
+
with open(strindex_update_filepath, 'w', encoding='utf-8') as f:
|
|
739
|
+
f.write(STRINDEX.full_header)
|
|
740
|
+
|
|
741
|
+
for strindex_index, pointers in enumerate([p for p, t in zip(temp_strindex["pointers"], STRINDEX.type_order) if t == "compatible"]):
|
|
742
|
+
STRINDEX.pointers_switches[strindex_index] = [True] * len(pointers or [])
|
|
743
|
+
|
|
744
|
+
for strindex_index, pointers in enumerate([p for p, t in zip(temp_strindex["pointers"], STRINDEX.type_order) if t == "overwrite"]):
|
|
745
|
+
STRINDEX.pointers[strindex_index] = pointers or []
|
|
746
|
+
|
|
747
|
+
for strindex_index, pointers in enumerate(temp_strindex["pointers"]):
|
|
748
|
+
if pointers:
|
|
749
|
+
f.write(STRINDEX.create_raw_from_index(strindex_index))
|
|
750
|
+
|
|
751
|
+
truncate_prev_char(f)
|
|
752
|
+
print("(1/1) Created updated strindex file.")
|
|
753
|
+
|
|
754
|
+
def delta(strindex_full_filepath: str, strindex_diff_filepath: str, strindex_delta_filepath: str):
|
|
755
|
+
"""
|
|
756
|
+
Filters a full strindex file with a delta strindex file.
|
|
757
|
+
"""
|
|
758
|
+
|
|
759
|
+
STRINDEX_FULL = Strindex(strindex_full_filepath)
|
|
760
|
+
STRINDEX_DIFF = Strindex(strindex_diff_filepath)
|
|
761
|
+
|
|
762
|
+
STRINDEX_FULL_LINES = STRINDEX_FULL.get_ordered_lines(lambda t: "original" if t == "compatible" else t)
|
|
763
|
+
STRINDEX_DIFF_LINES = STRINDEX_DIFF.get_ordered_lines(lambda t: "original" if t == "compatible" else t)
|
|
764
|
+
|
|
765
|
+
with open(strindex_delta_filepath, 'w', encoding='utf-8') as f:
|
|
766
|
+
f.write(STRINDEX_FULL.full_header)
|
|
767
|
+
|
|
768
|
+
diff_index = 0
|
|
769
|
+
for full_index in range(len(STRINDEX_FULL.type_order)):
|
|
770
|
+
try:
|
|
771
|
+
diff_index = STRINDEX_DIFF_LINES.index(STRINDEX_FULL_LINES[full_index], diff_index)
|
|
772
|
+
except ValueError:
|
|
773
|
+
f.write(STRINDEX_FULL.create_raw_from_index(full_index))
|
|
774
|
+
|
|
775
|
+
truncate_prev_char(f)
|
|
776
|
+
|
|
777
|
+
print("(1/1) Created delta strindex file.")
|
|
778
|
+
|
|
779
|
+
def spellcheck(strindex_filepath: str, strindex_spellcheck_filepath: str):
|
|
780
|
+
"""
|
|
781
|
+
Creates a spellcheck file from a strindex file, for the specified language.
|
|
782
|
+
"""
|
|
783
|
+
|
|
784
|
+
try:
|
|
785
|
+
from language_tool_python import LanguageTool
|
|
786
|
+
except ImportError:
|
|
787
|
+
raise ImportError("Please install the 'language-tool-python' package (pip install language-tool-python) to use this feature.")
|
|
788
|
+
|
|
789
|
+
STRINDEX = Strindex(strindex_filepath)
|
|
790
|
+
STRINDEX_LINES = STRINDEX.get_ordered_lines(lambda t: "replace" if t == "original" else t)
|
|
791
|
+
|
|
792
|
+
if not STRINDEX.settings["target_language"]:
|
|
793
|
+
raise ValueError("Please specify the target language to spellcheck in the strindex file ('target_language').")
|
|
794
|
+
|
|
795
|
+
lang = LanguageTool(STRINDEX.settings["target_language"])
|
|
796
|
+
print("(1/2) Created language tool.")
|
|
797
|
+
|
|
798
|
+
with open(strindex_spellcheck_filepath, 'w', encoding='utf-8') as f:
|
|
799
|
+
print_progress = PrintProgress(len(STRINDEX_LINES))
|
|
800
|
+
for strindex_index, line in enumerate(STRINDEX_LINES):
|
|
801
|
+
line_clean = re.sub(STRINDEX.settings["clean_pattern"], "", line)
|
|
802
|
+
for error in lang.check(line_clean):
|
|
803
|
+
f.write('\n'.join(str(error).split('\n')[-3:]) + '\n')
|
|
804
|
+
|
|
805
|
+
print_progress(strindex_index)
|
|
806
|
+
print("(2/2) Spellchecked strindex file.")
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
|
|
810
|
+
def patch_gui():
|
|
811
|
+
try:
|
|
812
|
+
from PySide6 import QtCore, QtWidgets, QtGui
|
|
813
|
+
except ImportError:
|
|
814
|
+
raise ImportError("Please install the 'PySide6' package (pip install pyside6) to use this feature.")
|
|
815
|
+
|
|
816
|
+
class PatchGUI(QtWidgets.QWidget):
|
|
817
|
+
def __init__(self):
|
|
818
|
+
super().__init__()
|
|
819
|
+
|
|
820
|
+
# file selection
|
|
821
|
+
self.pefile_line = QtWidgets.QLineEdit()
|
|
822
|
+
self.pefile_line.setPlaceholderText("Select a PE file")
|
|
823
|
+
self.pefile_line.textChanged.connect(self.update)
|
|
824
|
+
self.pefile_line.textChanged.connect(lambda: self.pefile_line.setStyleSheet(self.pefile_line.styleSheet()))
|
|
825
|
+
self.pefile_line.setFont(QtGui.QFont("monospace"))
|
|
826
|
+
self.pefile_button = QtWidgets.QPushButton("Browse PE Files")
|
|
827
|
+
self.pefile_button.clicked.connect(lambda: self.browse(self.pefile_line, "Open File", "Executable Files (*.exe)"))
|
|
828
|
+
|
|
829
|
+
# strindex selection
|
|
830
|
+
self.strindex_line = QtWidgets.QLineEdit()
|
|
831
|
+
self.strindex_line.setPlaceholderText("Select a Strindex file")
|
|
832
|
+
self.strindex_line.textChanged.connect(self.update)
|
|
833
|
+
self.strindex_line.textChanged.connect(lambda: self.strindex_line.setStyleSheet(self.strindex_line.styleSheet()))
|
|
834
|
+
self.strindex_line.setFont(QtGui.QFont("monospace"))
|
|
835
|
+
self.strindex_button = QtWidgets.QPushButton("Browse Strindex")
|
|
836
|
+
self.strindex_button.clicked.connect(lambda: self.browse(self.strindex_line, "Open Strindex", "Text Files (*.txt)"))
|
|
837
|
+
|
|
838
|
+
# patch button
|
|
839
|
+
self.patch_button = QtWidgets.QPushButton("Patch")
|
|
840
|
+
self.patch_button.clicked.connect(self.patch)
|
|
841
|
+
self.patch_button.setEnabled(False)
|
|
842
|
+
|
|
843
|
+
# progress bar
|
|
844
|
+
self.progress_bar = QtWidgets.QProgressBar()
|
|
845
|
+
self.progress_bar.setRange(0, 100)
|
|
846
|
+
self.progress_bar.setFormat("Patching... %p%")
|
|
847
|
+
self.progress_bar.setAlignment(QtCore.Qt.AlignmentFlag.AlignCenter)
|
|
848
|
+
PrintProgress.callback = lambda progress: self.progress_bar.setValue(progress.percent)
|
|
849
|
+
|
|
850
|
+
# add widgets to layout
|
|
851
|
+
self.grid_layout = QtWidgets.QGridLayout()
|
|
852
|
+
self.grid_layout.addWidget(self.pefile_line, 0, 0)
|
|
853
|
+
self.grid_layout.addWidget(self.pefile_button, 0, 1)
|
|
854
|
+
self.grid_layout.addWidget(self.strindex_line, 1, 0)
|
|
855
|
+
self.grid_layout.addWidget(self.strindex_button, 1, 1)
|
|
856
|
+
self.grid_layout.addWidget(self.patch_button, 2, 0, 1, 2)
|
|
857
|
+
self.grid_layout.setSpacing(10)
|
|
858
|
+
self.grid_layout.setColumnStretch(0, 1)
|
|
859
|
+
self.grid_layout.setColumnMinimumWidth(0, 200)
|
|
860
|
+
self.setLayout(self.grid_layout)
|
|
861
|
+
|
|
862
|
+
# set window properties
|
|
863
|
+
WINDOWS_STYLESHEET = f""""""
|
|
864
|
+
UNIX_STYLESHEET = f"""QLineEdit[text=""]{{color: {self.palette().windowText().color().name()};}}"""
|
|
865
|
+
self.setWindowTitle("Strindex Patch")
|
|
866
|
+
self.setStyleSheet(WINDOWS_STYLESHEET if sys.platform == "win32" else UNIX_STYLESHEET)
|
|
867
|
+
self.setWindowFlag(QtCore.Qt.WindowType.WindowMaximizeButtonHint, False)
|
|
868
|
+
self.setMaximumSize(1600, 0)
|
|
869
|
+
self.resize(800, 0)
|
|
870
|
+
self.center()
|
|
871
|
+
|
|
872
|
+
def browse(self, line: QtWidgets.QLineEdit, caption, filter):
|
|
873
|
+
if filepath := QtWidgets.QFileDialog.getOpenFileName(self, caption, "", filter)[0]:
|
|
874
|
+
line.setText(filepath)
|
|
875
|
+
|
|
876
|
+
def update(self):
|
|
877
|
+
path_exists = os.path.isfile(self.pefile_line.text()) and os.path.isfile(self.strindex_line.text())
|
|
878
|
+
self.patch_button.setEnabled(path_exists)
|
|
879
|
+
|
|
880
|
+
def patch(self):
|
|
881
|
+
self.setEnabled(False)
|
|
882
|
+
self.progress_bar.setValue(0)
|
|
883
|
+
self.grid_layout.replaceWidget(self.patch_button, self.progress_bar)
|
|
884
|
+
self.patch_button.setParent(None)
|
|
885
|
+
QtWidgets.QApplication.processEvents()
|
|
886
|
+
|
|
887
|
+
try:
|
|
888
|
+
patch(self.pefile_line.text(), self.strindex_line.text(), None)
|
|
889
|
+
self.progress_bar.setValue(100)
|
|
890
|
+
except BaseException as e:
|
|
891
|
+
self.message(str(e), QtWidgets.QMessageBox.Critical)
|
|
892
|
+
else:
|
|
893
|
+
self.message("File patched successfully.", QtWidgets.QMessageBox.Information)
|
|
894
|
+
finally:
|
|
895
|
+
self.grid_layout.replaceWidget(self.progress_bar, self.patch_button)
|
|
896
|
+
self.progress_bar.setParent(None)
|
|
897
|
+
self.setEnabled(True)
|
|
898
|
+
QtWidgets.QApplication.processEvents()
|
|
899
|
+
|
|
900
|
+
def center(self):
|
|
901
|
+
res = QtGui.QGuiApplication.primaryScreen().availableGeometry()
|
|
902
|
+
self.move((res.width() - self.width()) // 2, (res.height() - self.height()) // 2)
|
|
903
|
+
|
|
904
|
+
def message(self, text: str, icon):
|
|
905
|
+
msg = QtWidgets.QMessageBox()
|
|
906
|
+
msg.setWindowTitle(self.windowTitle())
|
|
907
|
+
msg.setIcon(icon)
|
|
908
|
+
msg.setText(text)
|
|
909
|
+
msg.setStandardButtons(QtWidgets.QMessageBox.Ok.Ok)
|
|
910
|
+
msg.exec()
|
|
911
|
+
return msg
|
|
912
|
+
|
|
913
|
+
app = QtWidgets.QApplication([])
|
|
914
|
+
gui = PatchGUI()
|
|
915
|
+
gui.show()
|
|
916
|
+
sys.exit(app.exec())
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def main():
|
|
921
|
+
if "__compiled__" in globals():
|
|
922
|
+
patch_gui()
|
|
923
|
+
return
|
|
924
|
+
|
|
925
|
+
try:
|
|
926
|
+
parser = argparse.ArgumentParser(prog="strindex", description="Command line string replacement tool for games.")
|
|
927
|
+
|
|
928
|
+
parser.add_argument("action", type=str, choices=["create", "patch", "patch_gui", "update", "filter", "delta", "spellcheck"], help="Action to perform.")
|
|
929
|
+
parser.add_argument("files", type=str, nargs=argparse.ZERO_OR_MORE, help="One or more files to process.")
|
|
930
|
+
parser.add_argument("-o", "--output", type=str, help="Output file.")
|
|
931
|
+
|
|
932
|
+
# create arguments
|
|
933
|
+
parser.add_argument("-c", "--compatible", action="store_true", help="Whether to create a strindex file compatible with the previous versions of a program.")
|
|
934
|
+
parser.add_argument("-m", "--min-length", type=int, default=3, help="Minimum length of the strings to be included.")
|
|
935
|
+
parser.add_argument("-p", "--prefix-bytes", type=str, action="append", default=[], help="Prefix bytes to add to the rva in the strindex file.")
|
|
936
|
+
|
|
937
|
+
args = parser.parse_args()
|
|
938
|
+
|
|
939
|
+
if not all([os.path.isfile(file) for file in args.files]):
|
|
940
|
+
raise FileNotFoundError("One or more files do not exist.")
|
|
941
|
+
|
|
942
|
+
args.prefix_bytes = [bytes.fromhex(prefix) for prefix in (args.prefix_bytes or [''])]
|
|
943
|
+
|
|
944
|
+
match args.action:
|
|
945
|
+
case "create":
|
|
946
|
+
create(*args.files, (args.output or "strindex.txt"), args.compatible, args.min_length, args.prefix_bytes)
|
|
947
|
+
case "patch":
|
|
948
|
+
patch(*args.files, args.output)
|
|
949
|
+
case "patch_gui":
|
|
950
|
+
patch_gui()
|
|
951
|
+
case "filter":
|
|
952
|
+
filter(*args.files, (args.output or "strindex_filter.txt"))
|
|
953
|
+
case "update":
|
|
954
|
+
update(*args.files, (args.output or "strindex_update.txt"))
|
|
955
|
+
case "delta":
|
|
956
|
+
delta(*args.files, (args.output or "strindex_delta.txt"))
|
|
957
|
+
case "spellcheck":
|
|
958
|
+
spellcheck(*args.files, (args.output or "strindex_spellcheck.txt"))
|
|
959
|
+
except KeyboardInterrupt:
|
|
960
|
+
print("Interrupted by user.")
|
|
961
|
+
except BaseException as e:
|
|
962
|
+
print(e)
|
|
963
|
+
|
|
964
|
+
if __name__ == "__main__":
|
|
965
|
+
main()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Luca Russo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: strindex
|
|
3
|
+
Version: 3.2.0
|
|
4
|
+
Summary: A command line utility to view, edit and patch strings in PE files, with a focus on compatibility and translation.
|
|
5
|
+
Home-page: https://github.com/zWolfrost/strindex
|
|
6
|
+
Author: zWolfrost
|
|
7
|
+
Author-email: zwolfrost@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: PE strings patching translation
|
|
10
|
+
Platform: UNKNOWN
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Topic :: Utilities
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: pefile>=2024.8.26
|
|
17
|
+
Provides-Extra: filter_language
|
|
18
|
+
Requires-Dist: lingua-language-detector; extra == "filter-language"
|
|
19
|
+
Provides-Extra: patch_gui
|
|
20
|
+
Requires-Dist: pyside6; extra == "patch-gui"
|
|
21
|
+
Provides-Extra: spellcheck
|
|
22
|
+
Requires-Dist: language-tool-python; extra == "spellcheck"
|
|
23
|
+
|
|
24
|
+
# strindex
|
|
25
|
+
A command line utility to view, edit and patch strings in PE files, with a focus on compatibility and translation.
|
|
26
|
+
|
|
27
|
+
This script will allow you to replace strings in PE files (".exe", ".dll" etc.) with other strings. It is useful for changing the text of a program without having to recompile it, for example, to translate a program into another language.
|
|
28
|
+
|
|
29
|
+
Apart from using offsets to replace strings, it also has an option to use the original string itself to ensure compatibility with different versions of the same program.
|
|
30
|
+
|
|
31
|
+
It also has a lot of features to help with translation, such as spellchecking & filtering strings by length and character set.
|
|
32
|
+
|
|
33
|
+
The release includes a precompiled version of the program, which ONLY does the patching. If you want to use the other features, you will need to install Python 3.6 or later and the required libraries.
|
|
34
|
+
|
|
35
|
+
## Requirements
|
|
36
|
+
You can install the required libraries with the command `pip install [library name]`.
|
|
37
|
+
|
|
38
|
+
**Required**:
|
|
39
|
+
- Python 3.6 or later.
|
|
40
|
+
- `pefile` library.
|
|
41
|
+
|
|
42
|
+
**Optional**:
|
|
43
|
+
- `lingua` library for filtering by detected language.
|
|
44
|
+
- `language-tool-python` library for spellchecking.
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
There are four available actions:
|
|
48
|
+
- `create`: Create a list of strings from a PE file (a strindex). Use `-c` to create a strindex that uses the original strings as references.
|
|
49
|
+
- `patch`: Patch a PE file with a strindex.
|
|
50
|
+
- `filter`: Filter a strindex by detected language, wordlist or length. You can specify those in the strindex settings.
|
|
51
|
+
- `update`: Update a strindex pointers to match the new ones of a file, useful for when the file is modified (e.g. update)
|
|
52
|
+
- `delta`: Create a delta file between two strindexes, that only contains the lines of the first strindex missing in the second one.
|
|
53
|
+
- `spellcheck`: Spellcheck a strindex. You can specify the target language in the strindex settings as an ISO 639-1 code.
|
|
54
|
+
|
|
55
|
+
You can run the program with the command `python strindex.py -h` to show all available arguments.
|
|
56
|
+
|
|
57
|
+
## Usage Examples
|
|
58
|
+
- Create a strindex from a PE file:
|
|
59
|
+
```sh
|
|
60
|
+
python strindex.py create program.exe -o strindex.txt
|
|
61
|
+
```
|
|
62
|
+
- Patch a PE file with a strindex:
|
|
63
|
+
```sh
|
|
64
|
+
python strindex.py patch program.exe strindex.txt
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Strindex Settings example
|
|
68
|
+
```json
|
|
69
|
+
{
|
|
70
|
+
"md5": "29ed1f9e450d43815c2d1a0cab168da3",
|
|
71
|
+
|
|
72
|
+
"prefix_bytes": ["24c7442404", "ec04c70424"],
|
|
73
|
+
|
|
74
|
+
"patch_replace": {
|
|
75
|
+
"ì": "í",
|
|
76
|
+
"Ì": "Í",
|
|
77
|
+
"ò": "ó",
|
|
78
|
+
"Ò": "Ó"
|
|
79
|
+
},
|
|
80
|
+
|
|
81
|
+
"clean_pattern": "\\[.*?\\]|\\*",
|
|
82
|
+
"whitelist": ["latin", "spanish", "cyrillic"],
|
|
83
|
+
|
|
84
|
+
"source_language": "es",
|
|
85
|
+
"target_language": "it",
|
|
86
|
+
"among_languages": ["en", "ja", "ko", "de", "fr", "es", "pt", "ru", "zh"]
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
strindex/__init__.py,sha256=D-obt7M88ZQ-ZGDTgpu_8El0Sg1As9cduedvKIbGD_U,23
|
|
2
|
+
strindex/__main__.py,sha256=5G2JGqg8sR9hP6qpft54F_QesRYPzYogf3niuancf7Y,64
|
|
3
|
+
strindex/strindex.py,sha256=pq6Cd6l8KKpmev6LWrqncqFKinLulqDZO_UjYwQWcfA,37434
|
|
4
|
+
strindex-3.2.0.dist-info/LICENSE,sha256=ikl0jTWBVoW_gbl0eJ_qOam_pAwp-GorpFmS6df_k6w,1067
|
|
5
|
+
strindex-3.2.0.dist-info/METADATA,sha256=vSWnCdhPsYHReeV4yxTltmhFxdrchg1QMSGbARoyMvk,3513
|
|
6
|
+
strindex-3.2.0.dist-info/WHEEL,sha256=eOLhNAGa2EW3wWl_TU484h7q1UNgy0JXjjoqKoxAAQc,92
|
|
7
|
+
strindex-3.2.0.dist-info/entry_points.txt,sha256=pzPmACvkslmkak6vcLjyXcXQQ8d0s2GQhLS8C-25oGk,53
|
|
8
|
+
strindex-3.2.0.dist-info/top_level.txt,sha256=wY5Lfk2up6ZEmzXatLVrOlhHy-14sEZwb7zzLbP14Cs,9
|
|
9
|
+
strindex-3.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
strindex
|