forked from glaslos/tlsh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tlsh.go
383 lines (324 loc) · 7.76 KB
/
tlsh.go
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/* Copyright 2017 Lukas Rist
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package tlsh
import (
"bufio"
"bytes"
"encoding/hex"
"io"
"math"
"os"
)
const (
log1_5 = 0.4054651
log1_3 = 0.26236426
log1_1 = 0.095310180
codeSize = 32
windowLength = 5
effBuckets = 128
numBuckets = 256
)
// Tlsh holds hash components
type Tlsh struct {
checksum byte
lValue byte
q1Ratio byte
q2Ratio byte
qRatio byte
code [codeSize]byte
}
// New represents type factory for Tlsh
func New(checksum, lValue, q1Ratio, q2Ratio, qRatio byte, code [codeSize]byte) *Tlsh {
return &Tlsh{
checksum: checksum,
lValue: lValue,
q1Ratio: q1Ratio,
q2Ratio: q2Ratio,
qRatio: qRatio,
code: code,
}
}
// Binary returns the binary representation of the hash
func (t *Tlsh) Binary() []byte {
return append([]byte{swapByte(t.checksum), swapByte(t.lValue), t.qRatio}, t.code[:]...)
}
// String returns the string representation of the hash`
func (t *Tlsh) String() string {
return hex.EncodeToString(t.Binary())
}
// Parsing the hash of the string type
func ParseStringToTlsh(hashString string) (*Tlsh, error) {
var code [codeSize]byte
hashByte, err := hex.DecodeString(hashString)
if err != nil {
return &Tlsh{}, err
}
chechsum := swapByte(hashByte[0])
lValue := swapByte(hashByte[1])
qRatio := hashByte[2]
q1Ratio := (qRatio >> 4) & 0xF
q2Ratio := qRatio & 0xF
copy(code[:], hashByte[3:])
return New(chechsum, lValue, q1Ratio, q2Ratio, qRatio, code), nil
}
func quartilePoints(buckets [numBuckets]uint) (q1, q2, q3 uint) {
var spl, spr uint
p1 := uint(effBuckets/4 - 1)
p2 := uint(effBuckets/2 - 1)
p3 := uint(effBuckets - effBuckets/4 - 1)
end := uint(effBuckets - 1)
bucketCopy := make([]uint, effBuckets)
copy(bucketCopy, buckets[:effBuckets])
shortCutLeft := make([]uint, effBuckets)
shortCutRight := make([]uint, effBuckets)
for l, r := uint(0), end; ; {
ret := partition(bucketCopy, l, r)
if ret > p2 {
r = ret - 1
shortCutRight[spr] = ret
spr++
} else if ret < p2 {
l = ret + 1
shortCutLeft[spl] = ret
spl++
} else {
q2 = bucketCopy[p2]
break
}
}
shortCutLeft[spl] = p2 - 1
shortCutRight[spr] = p2 + 1
for i, l := uint(0), uint(0); i <= spl; i++ {
r := shortCutLeft[i]
if r > p1 {
for {
ret := partition(bucketCopy, l, r)
if ret > p1 {
r = ret - 1
} else if ret < p1 {
l = ret + 1
} else {
q1 = bucketCopy[p1]
break
}
}
break
} else if r < p1 {
l = r
} else {
q1 = bucketCopy[p1]
break
}
}
for i, r := uint(0), end; i <= spr; i++ {
l := shortCutRight[i]
if l < p3 {
for {
ret := partition(bucketCopy, l, r)
if ret > p3 {
r = ret - 1
} else if ret < p3 {
l = ret + 1
} else {
q3 = bucketCopy[p3]
break
}
}
break
} else if l > p3 {
r = l
} else {
q3 = bucketCopy[p3]
break
}
}
return q1, q2, q3
}
func partition(buf []uint, left, right uint) uint {
if left == right {
return left
}
if left+1 == right {
if buf[left] > buf[right] {
buf[right], buf[left] = buf[left], buf[right]
}
return left
}
ret := left
pivot := (left + right) >> 1
val := buf[pivot]
buf[pivot] = buf[right]
buf[right] = val
for i := left; i < right; i++ {
if buf[i] < val {
buf[i], buf[ret] = buf[ret], buf[i]
ret++
}
}
buf[right] = buf[ret]
buf[ret] = val
return ret
}
func lValue(length int) byte {
var l byte
if length <= 656 {
l = byte(math.Floor(math.Log(float64(length)) / log1_5))
} else if length <= 3199 {
l = byte(math.Floor(math.Log(float64(length))/log1_3 - 8.72777))
} else {
l = byte(math.Floor(math.Log(float64(length))/log1_1 - 62.5472))
}
return l % 255
}
func swapByte(in byte) byte {
var out byte
out = ((in & 0xF0) >> 4) & 0x0F
out |= ((in & 0x0F) << 4) & 0xF0
return out
}
func bucketsBinaryRepresentation(buckets [numBuckets]uint, q1, q2, q3 uint) [codeSize]byte {
var biHash [codeSize]byte
for i := 0; i < codeSize; i++ {
var h byte
for j := 0; j < 4; j++ {
k := buckets[4*i+j]
if q3 < k {
h += 3 << (byte(j) * 2)
} else if q2 < k {
h += 2 << (byte(j) * 2)
} else if q1 < k {
h += 1 << (byte(j) * 2)
}
}
// Prepend the new h to the hash
biHash[(codeSize-1)-i] = h
}
return biHash
}
func reverse(s [5]byte) [5]byte {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}
func fillBuckets(r FuzzyReader) ([numBuckets]uint, byte, int, error) {
buckets := [numBuckets]uint{}
chunkSlice := make([]byte, windowLength)
chunk := [windowLength]byte{}
salt := [6]byte{2, 3, 5, 7, 11, 13}
fileSize := 0
checksum := byte(0)
n, err := r.Read(chunkSlice)
if err != nil {
return [numBuckets]uint{}, 0, 0, err
}
copy(chunk[:], chunkSlice[0:5])
chunk = reverse(chunk)
fileSize += n
chunk3 := &[3]byte{}
for {
chunk3[0] = chunk[0]
chunk3[1] = chunk[1]
chunk3[2] = checksum
checksum = pearsonHash(0, chunk3)
chunk3[2] = chunk[2]
buckets[pearsonHash(salt[0], chunk3)]++
chunk3[2] = chunk[3]
buckets[pearsonHash(salt[1], chunk3)]++
chunk3[1] = chunk[2]
buckets[pearsonHash(salt[2], chunk3)]++
chunk3[2] = chunk[4]
buckets[pearsonHash(salt[3], chunk3)]++
chunk3[1] = chunk[1]
buckets[pearsonHash(salt[4], chunk3)]++
chunk3[1] = chunk[3]
buckets[pearsonHash(salt[5], chunk3)]++
copy(chunk[1:], chunk[0:4])
chunk[0], err = r.ReadByte()
if err != nil {
if err != io.EOF {
return [numBuckets]uint{}, 0, 0, err
}
break
}
fileSize++
}
return buckets, checksum, fileSize, nil
}
// hashCalculate calculate TLSH
func hashCalculate(r FuzzyReader) (*Tlsh, error) {
buckets, checksum, fileSize, err := fillBuckets(r)
if err != nil {
return &Tlsh{}, err
}
q1, q2, q3 := quartilePoints(buckets)
q1Ratio := byte(float32(q1)*100/float32(q3)) % 16
q2Ratio := byte(float32(q2)*100/float32(q3)) % 16
qRatio := ((q1Ratio & 0xF) << 4) | (q2Ratio & 0xF)
biHash := bucketsBinaryRepresentation(buckets, q1, q2, q3)
return New(checksum, lValue(fileSize), q1Ratio, q2Ratio, qRatio, biHash), nil
}
// FuzzyReader interface
type FuzzyReader interface {
io.Reader
io.ByteReader
}
//HashReader calculates the TLSH for the input reader
func HashReader(r FuzzyReader) (tlsh *Tlsh, err error) {
tlsh, err = hashCalculate(r)
if err != nil {
return &Tlsh{}, err
}
return tlsh, err
}
//HashBytes calculates the TLSH for the input byte slice
func HashBytes(blob []byte) (tlsh *Tlsh, err error) {
r := bytes.NewReader(blob)
return HashReader(r)
}
//HashFilename calculates the TLSH for the input file
func HashFilename(filename string) (tlsh *Tlsh, err error) {
f, err := os.Open(filename)
defer f.Close()
if err != nil {
return &Tlsh{}, err
}
r := bufio.NewReader(f)
return HashReader(r)
}
// Diff current hash with other hash
func (t *Tlsh) Diff(t2 *Tlsh) int {
return diffTotal(t, t2, true)
}
// DiffFilenames calculate distance between two files
func DiffFilenames(filenameA, filenameB string) (int, error) {
f, err := os.Open(filenameA)
defer f.Close()
if err != nil {
return -1, err
}
r := bufio.NewReader(f)
tlshA, err := hashCalculate(r)
if err != nil {
return -1, err
}
f, err = os.Open(filenameB)
defer f.Close()
if err != nil {
return -1, err
}
r = bufio.NewReader(f)
tlshB, err := hashCalculate(r)
if err != nil {
return -1, err
}
return tlshA.Diff(tlshB), nil
}