forked from joxeankoret/deeptoad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkfuzzy.py
360 lines (290 loc) · 10 KB
/
kfuzzy.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env python
"""
Fuzzy hashing algorithms
Copyright (C) 2009, Joxean Koret
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
"""
import os
import sys
import base64
from itertools import imap
try:
from fasttoad_wrap import modsum
except:
def modsum(buf):
return sum(imap(ord, buf)) % 255
try:
import psyco
psyco.full()
except ImportError:
pass
class CFileStr(str):
fd = None
def __init__(self, fd):
self.fd = fd
def __getslice__(self, x, y):
self.fd.seek(x, 0)
buf = self.fd.read(y-x)
self.fd.seek(y)
return buf
def __len__(self):
old = self.fd.tell()
self.fd.seek(0, 2)
pos = self.fd.tell()
self.fd.seek(old)
return pos
class CKoretFuzzyHashing:
""" Generate partial hashes of files or bytes """
bsize = 512
output_size = 32
ignore_range = 2
big_file_size = 1024*1024*10
algorithm = None
reduce_errors = True
remove_spaces = False
def get_bytes(self, f, initial, final):
f.seek(initial)
return f.read(final)
def edit_distance(self, sign1, sign2):
if sign1 == sign2:
return 0
m = max(len(sign1), len(sign2))
distance = 0
for c in xrange(0, m):
if sign1[c:c+1] != sign2[c:c+1]:
distance += 1
return distance
def simplified(self, bytes, aggresive = False):
output_size = self.output_size
ignore_range = self.ignore_range
bsize = self.bsize
total_size = len(bytes)
size = (total_size/bsize) / output_size
buf = []
reduce_errors = self.reduce_errors
# Adjust the output to the desired output size
for c in xrange(0, output_size):
tmp = bytes[c*size:(c*size+1)+bsize]
ret = sum(imap(ord, tmp)) % 255
if reduce_errors:
if ret != 255 and ret != 0:
buf.append(chr(ret))
else:
buf.append(chr(ret))
buf = "".join(buf)
return base64.b64encode(buf).strip("=")[:output_size]
def _hash(self, bytes, aggresive = False):
idx = 0
ret = []
output_size = self.output_size
ignore_range = self.ignore_range
bsize = self.bsize
total_size = len(bytes)
rappend = ret.append
chunk_size = idx*bsize
reduce_errors = self.reduce_errors
# Calculate the sum of every block
while 1:
chunk_size = idx*bsize
#print "pre"
buf = bytes[chunk_size:chunk_size+bsize]
#print "post"
char = modsum(buf)
if reduce_errors:
if char != 255 and char != 0:
rappend(chr(char))
else:
rappend(chr(char))
idx += 1
if chunk_size+bsize > total_size:
break
ret = "".join(ret)
size = len(ret) / output_size
buf = []
# Adjust the output to the desired output size
for c in xrange(0, output_size):
if aggresive:
buf.append(ret[c:c+size+1][ignore_range:ignore_range+1])
else:
buf.append(ret[c:c+size+1][1:2])
i = 0
for x in ret[c:c+size+1]:
i += 1
if i != ignore_range:
continue
i = 0
buf += x
break
ret = "".join(buf)
return base64.b64encode(ret).strip("=")[:output_size]
def _fast_hash(self, bytes, aggresive = False):
i = -1
ret = set()
output_size = self.output_size
size = len(bytes) *1.00 / output_size
bsize = self.bsize
radd = ret.add
while i < output_size:
i += 1
buf = bytes[i*bsize:(i+1)*bsize]
char = sum(imap(ord, buf)) % 255
if self.reduce_errors:
if char != 255 and char != 0:
radd(chr(char))
else:
radd(chr(char))
ret = "".join(ret)
return base64.b64encode(ret).strip("=")[:output_size]
def xor(self, bytes):
ret = 0
for byte in bytes:
ret ^= byte
return ret
def _experimental_hash(self, bytes, aggresive = False):
idx = 0
ret = []
bsize = self.bsize
output_size = self.output_size
size = len(bytes)
ignore_range = self.ignore_range
chunk_size = idx*self.bsize
byte = None
while size > chunk_size + (bsize/output_size):
chunk_size = idx*self.bsize
if byte is None:
val = bsize
elif ord(byte) > 0:
val = ord(byte)
else:
val = output_size
buf = bytes[chunk_size:chunk_size+val]
byte = self.xor(imap(ord, buf)) % 255
byte = chr(byte)
if byte != '\xff' and byte != '\x00':
ret.append(byte)
idx += 1
ret = "".join(ret)
buf = ""
size = len(ret)/output_size
for n in xrange(0, output_size):
buf += ret[n*size:(n*size)+1]
return base64.b64encode(buf).strip("=")[:output_size]
def mix_blocks(self, bytes):
idx = 0
buf = bytes
ret = ""
size1 = 0
size2 = 0
total_size = len(bytes)
while 1:
size1 = idx*self.bsize
size2 = (idx+1)*self.bsize
tmp = buf[size1:size2]
tm2 = tmp
ret += tmp
ret += tm2
idx += 1
if len(tmp) < self.bsize:
break
return ret
def cleanSpaces(self, bytes):
bytes = bytes.replace(" ", "").replace("\r", "").replace("\n", "")
bytes = bytes.replace("\t", "")
return bytes
def hash_bytes(self, bytes, aggresive = False):
if self.remove_spaces:
bytes = self.cleanSpaces(bytes)
mix = self.mix_blocks(bytes)
if self.algorithm is None:
func = self._hash
else:
func = self.algorithm
hash1 = func(mix, aggresive)
hash2 = func(bytes, aggresive)
hash3 = func(bytes[::-1], aggresive)
return hash1 + ";" + hash2 + ";" + hash3
def hash_file(self, filename, aggresive = False):
f = file(filename, "rb")
f.seek(0, 2)
size = f.tell()
if size > self.big_file_size:
print
print "Warning! Support for big files (%d MB > %d MB) is broken!" % (size/1024/1024, self.big_file_size / 1024 / 1024)
fbytes = CFileStr(f)
else:
f.seek(0)
fbytes = f.read()
f.close()
return self.hash_bytes(fbytes, aggresive)
class kdha:
""" Interface to make partially compatible the KFuzzy hashing algorithms with
the standard python hashlib format. This is the Koret Default Hashing Algorithm """
digest_size = 32
block_size = 512
_bytes = ""
_kfd = None
def __init__(self, bytes):
""" Initialize the object """
self._bytes = bytes
self._kfd = CKoretFuzzyHashing()
def update(self, bytes):
""" Not very usefull, just for compatibility... """
self._bytes += bytes
def hexdigest(self):
""" Returns and hexadecimal digest """
self._kfd.bsize = self.block_size
self._kfd.output_size = self.digest_size
hash = self._kfd.hash_bytes(self._bytes)
return hash
def digest(self):
""" Same as hexdigest """
return self.hexdigest()
class kfha(kdha):
""" Interface to make partially compatible the KFuzzy hashing algorithms with
the standard python hashlib format. This is the Koret Fast Hashing Algorithm """
def __init__(self, bytes):
self._bytes = bytes
self._kfd = CKoretFuzzyHashing()
self._kfd.algorithm = self._kfd._fast_hash
class ksha(kdha):
""" Interface to make partially compatible the KFuzzy hashing algorithms with
the standard python hashlib format. This is the Koret Simplified Hashing Algorithm """
def __init__(self, bytes):
self._bytes = bytes
self._kfd = CKoretFuzzyHashing()
self._kfd.algorithm = self._kfd.simplified
def usage():
print "Usage:", sys.argv[0], "<filename>"
def main(path):
hash = CKoretFuzzyHashing()
#hash.algorithm = hash._fast_hash
if os.path.isdir(path):
print "Signature;Simple Signature;Reverse Signature;Filename"
for root, dirs, files in os.walk(path):
for name in files:
tmp = os.path.join(root, name)
try:
ret = hash.hash_file(tmp, True)
print "%s;%s" % (ret, tmp)
except:
print "***ERROR with file %s" % tmp
print sys.exc_info()[1]
else:
hash = CKoretFuzzyHashing()
ret = hash.hash_file(path, True)
print "%s;%s" % (path, ret)
if __name__ == "__main__":
if len(sys.argv) == 1:
usage()
else:
main(sys.argv[1])