forked from hanc00l/nemo_go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iconhash.go
375 lines (342 loc) · 9.7 KB
/
iconhash.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
package fingerprint
import (
"bytes"
"crypto/sha1"
"encoding/base64"
"fmt"
"github.com/hanc00l/nemo_go/pkg/conf"
"github.com/hanc00l/nemo_go/pkg/logging"
"github.com/hanc00l/nemo_go/pkg/task/custom"
"github.com/hanc00l/nemo_go/pkg/task/domainscan"
"github.com/hanc00l/nemo_go/pkg/task/portscan"
"github.com/hanc00l/nemo_go/pkg/utils"
"github.com/mat/besticon/besticon"
"github.com/remeh/sizedwaitgroup"
"github.com/twmb/murmur3"
"hash"
"image"
"os"
"path/filepath"
"strings"
"sync"
)
// besticon方式已废弃
// 目前采用httpx方式获取icon路径,通过golang以HTTP方式获取icon,然后计算icon的hash值
type IconHash struct {
ResultPortScan *portscan.Result
ResultDomainScan *domainscan.Result
IconHashInfoResult *IconHashInfoResult
DomainTargetPort map[string]map[int]struct{}
OptimizationMode bool
}
type IconHashResult struct {
Url string
Hash string
ImageData []byte
}
type IconHashInfo struct {
Url string
Hash string
ImageData []byte
}
type IconHashInfoResult struct {
sync.RWMutex
Result []IconHashInfo
}
var (
// used by besticon
keepImageBytes = true
// used by github.com/Becivells/iconhash
isUint32 = false
debug = false
)
func NewIconHash() *IconHash {
return &IconHash{}
}
func (i *IconHash) Do() {
swg := sizedwaitgroup.New(fpIconHashThreadNumber[conf.WorkerPerformanceMode])
i.IconHashInfoResult = &IconHashInfoResult{Result: make([]IconHashInfo, 0)}
btc := custom.NewBlackTargetCheck(custom.CheckAll)
if i.ResultPortScan != nil && i.ResultPortScan.IPResult != nil {
for ipName, ipResult := range i.ResultPortScan.IPResult {
if btc.CheckBlack(ipName) {
logging.RuntimeLog.Warningf("%s is in blacklist,skip...", ipName)
continue
}
for portNumber := range ipResult.Ports {
if _, ok := blankPort[portNumber]; ok {
continue
}
if i.OptimizationMode {
if !CheckForHttpxFingerResult(ipName, "", portNumber, i.ResultPortScan, i.ResultDomainScan) {
continue
}
}
url := utils.FormatHostUrl("", ipName, portNumber) //fmt.Sprintf("%v:%v", ipName, portNumber)
swg.Add()
go func(ip string, port int, u string) {
defer swg.Done()
iconHashes := i.RunFetchIconHashes(u)
if len(iconHashes) > 0 {
for _, r := range iconHashes {
par := portscan.PortAttrResult{
Source: "iconhash",
Tag: "favicon",
Content: fmt.Sprintf("%s | %s", r.Hash, r.Url),
}
i.ResultPortScan.SetPortAttr(ip, port, par)
if len(r.ImageData) > 0 {
i.IconHashInfoResult.Lock()
i.IconHashInfoResult.Result = append(i.IconHashInfoResult.Result, IconHashInfo{
Url: r.Url,
Hash: r.Hash,
ImageData: r.ImageData,
})
i.IconHashInfoResult.Unlock()
}
}
}
}(ipName, portNumber, url)
}
}
}
if i.ResultDomainScan != nil && i.ResultDomainScan.DomainResult != nil {
if i.DomainTargetPort == nil {
i.DomainTargetPort = make(map[string]map[int]struct{})
}
for domain := range i.ResultDomainScan.DomainResult {
if btc.CheckBlack(domain) {
logging.RuntimeLog.Warningf("%s is in blacklist,skip...", domain)
continue
}
//如果无域名对应的端口,默认80和443
if _, ok := i.DomainTargetPort[domain]; !ok || len(i.DomainTargetPort[domain]) == 0 {
i.DomainTargetPort[domain] = make(map[int]struct{})
i.DomainTargetPort[domain][80] = struct{}{}
i.DomainTargetPort[domain][443] = struct{}{}
}
for port := range i.DomainTargetPort[domain] {
if _, ok := blankPort[port]; ok {
continue
}
if i.OptimizationMode {
if !CheckForHttpxFingerResult("", domain, port, i.ResultPortScan, i.ResultDomainScan) {
continue
}
}
url := utils.FormatHostUrl("", domain, port)
swg.Add()
go func(d string, u string) {
defer swg.Done()
iconHashes := i.RunFetchIconHashes(u)
if len(iconHashes) > 0 {
for _, r := range iconHashes {
dar := domainscan.DomainAttrResult{
Source: "iconhash",
Tag: "favicon",
Content: fmt.Sprintf("%s | %s", r.Hash, r.Url),
}
i.ResultDomainScan.SetDomainAttr(d, dar)
if len(r.ImageData) > 0 {
i.IconHashInfoResult.Lock()
i.IconHashInfoResult.Result = append(i.IconHashInfoResult.Result, IconHashInfo{
Url: r.Url,
Hash: r.Hash,
ImageData: r.ImageData,
})
i.IconHashInfoResult.Unlock()
}
}
}
}(domain, url)
}
}
}
swg.Wait()
}
func (i *IconHash) RunFetchIconHashes(url string) (hashResult []IconHashResult) {
var icons []besticon.Icon
protocoll := utils.GetProtocol(url, 5)
// 获取缺省的icon:
u1 := fmt.Sprintf("%s://%s/favicon.ico", protocoll, url)
icon1 := fetchIconDetails(u1)
if icon1.Error == nil {
icons = append(icons, icon1)
}
// 缺省的icon不存在再尝试读取其它icon
if len(icons) == 0 {
// 获取网页中定义的全部icon
u2 := fmt.Sprintf("%s://%s", protocoll, url)
//finder := besticon.IconFinder{}
finder := besticon.New().NewIconFinder()
icons2, err := finder.FetchIcons(u2)
if err == nil {
icons = append(icons, icons2...)
}
}
//计算哈希值
for _, icon := range icons {
hash := mmh3Hash32(standBase64(icon.ImageData))
if isContainString(hashResult, hash) == false {
hashResult = append(hashResult, IconHashResult{Url: icon.URL, Hash: hash, ImageData: icon.ImageData})
}
}
return
}
// SaveFile 保存icon Image文件
func (i *IconHash) SaveFile(localSavePath string, result []IconHashInfo) string {
count := 0
for _, ihf := range result {
if ihf.Url == "" || ihf.Hash == "" || len(ihf.ImageData) <= 0 {
continue
}
fileSuffix := utils.GetFaviconSuffixUrl(ihf.Url)
if fileSuffix == "" {
continue
}
//文件名为md5(iconHash).后缀
filePathName := filepath.Join(localSavePath, fmt.Sprintf("%s.%s", utils.MD5(ihf.Hash), fileSuffix))
err := os.WriteFile(filePathName, ihf.ImageData, 0666)
if err != nil {
msg := fmt.Sprintf("write icon file %s fail:%v", filePathName, err)
logging.RuntimeLog.Error(msg)
logging.CLILog.Error(msg)
continue
}
count++
}
return fmt.Sprintf("iconimage:%d", count)
}
// fetchIconDetails 根据URL获取并校验icon文件
// forked from github.com/mat/besticon/besticon/besticon.go
func fetchIconDetails(url string) besticon.Icon {
i := besticon.Icon{URL: url}
bi := besticon.New()
response, e := bi.Get(url)
//response, e := besticon.Get(url)
if e != nil {
i.Error = e
return i
}
b, e := bi.GetBodyBytes(response)
//b, e := besticon.GetBodyBytes(response)
if e != nil {
i.Error = e
return i
}
if isSVG(b) {
// Special handling for svg, which golang can't decode with
// image.DecodeConfig. Fill in an absurdly large width/height so SVG always
// wins size contests.
i.Format = "svg"
i.Width = 9999
i.Height = 9999
} else {
cfg, format, e := image.DecodeConfig(bytes.NewReader(b))
if e != nil {
i.Error = fmt.Errorf("besticon: unknown image format: %s", e)
return i
}
// jpeg => jpg
if format == "jpeg" {
format = "jpg"
}
i.Width = cfg.Width
i.Height = cfg.Height
i.Format = format
}
i.Bytes = len(b)
i.Sha1sum = sha1Sum(b)
if keepImageBytes {
i.ImageData = b
}
return i
}
// SVG detector. We can't use image.RegisterFormat, since RegisterFormat is
// limited to a simple magic number check. It's easy to confuse the first few
// bytes of HTML with SVG.
func isSVG(body []byte) bool {
// is it long enough?
if len(body) < 10 {
return false
}
// does it start with something reasonable?
switch {
case bytes.Equal(body[0:2], []byte("<!")):
case bytes.Equal(body[0:2], []byte("<?")):
case bytes.Equal(body[0:4], []byte("<svg")):
default:
return false
}
// is there an <svg in the first 300 bytes?
if off := bytes.Index(body, []byte("<svg")); off == -1 || off > 300 {
return false
}
return true
}
func sha1Sum(b []byte) string {
hash := sha1.New()
hash.Write(b)
bs := hash.Sum(nil)
return fmt.Sprintf("%x", bs)
}
// mmh3Hash32 计算icon的hash
// forked from https://github.com/Becivells/iconhash
func mmh3Hash32(raw []byte) string {
var h32 hash.Hash32 = murmur3.New32()
h32.Write(raw)
if isUint32 {
return fmt.Sprintf("%d", h32.Sum32())
}
return fmt.Sprintf("%d", int32(h32.Sum32()))
}
// standBase64 计算 base64 的值
func standBase64(braw []byte) []byte {
bckd := base64.StdEncoding.EncodeToString(braw)
var buffer bytes.Buffer
for i := 0; i < len(bckd); i++ {
ch := bckd[i]
buffer.WriteByte(ch)
if (i+1)%76 == 0 {
buffer.WriteByte('\n')
}
}
buffer.WriteByte('\n')
if debug {
fmt.Print("---------------------------start base64 content--------------------------------\n")
fmt.Printf("====> base64:\n%s\n", buffer.String())
defer fmt.Print("---------------------------end base64 content--------------------------------\n")
}
return buffer.Bytes()
}
// SplitChar76 按照 76 字符切分
func SplitChar76(braw []byte) []byte {
// 去掉 data:image/vnd.microsoft.icon;base64
if strings.HasPrefix(string(braw), "data:image/vnd.microsoft.icon;base64,") {
braw = braw[37:]
}
var buffer bytes.Buffer
for i := 0; i < len(braw); i++ {
ch := braw[i]
buffer.WriteByte(ch)
if (i+1)%76 == 0 {
buffer.WriteByte('\n')
}
}
buffer.WriteByte('\n')
if debug {
fmt.Print("---------------------------start base64 content--------------------------------\n")
fmt.Printf("====> base64 split 76:\n %s\n", buffer.String())
defer fmt.Print("---------------------------end base64 content--------------------------------\n")
}
return buffer.Bytes()
}
// isContainString 判断一个哈希值是否在数组中
func isContainString(arrays []IconHashResult, hash string) bool {
for _, a := range arrays {
if hash == a.Hash {
return true
}
}
return false
}