-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathsafebrowsing.go
385 lines (339 loc) · 10.7 KB
/
safebrowsing.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
384
385
/*
Copyright (c) 2013, Richard Johnson
Copyright (c) 2014, Kilian Gilonne
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package safebrowsing
import (
"bufio"
"bytes"
"fmt"
"io"
"math/rand"
"net/http"
"os"
// "runtime/debug"
"strconv"
"strings"
"time"
)
type FullHash string
type LookupHash string
type SafeBrowsing struct {
DataDir string
Key string
Client string
AppVersion string
ProtocolVersion string
UpdateDelay int
LastUpdated time.Time
Lists map[string]*SafeBrowsingList
request func(string, string, bool) (*http.Response, error)
Logger logger
}
var SupportedLists map[string]bool = map[string]bool{
"goog-malware-shavar": true,
"googpub-phish-shavar": true,
}
var Logger logger = new(DefaultLogger)
var Client string = "api"
var AppVersion string = "1.5.2"
var ProtocolVersion string = "3.0"
var OfflineMode bool = false
var Transport *http.Transport = &http.Transport{}
func NewSafeBrowsing(apiKey string, dataDirectory string) (sb *SafeBrowsing, err error) {
sb = &SafeBrowsing{
Key: apiKey,
Client: Client,
AppVersion: AppVersion,
ProtocolVersion: ProtocolVersion,
DataDir: dataDirectory,
Lists: make(map[string]*SafeBrowsingList),
request: request,
Logger: Logger,
}
// if the dataDirectory does not currently exist, have a go at creating it:
err = os.MkdirAll(dataDirectory, os.ModeDir|0700)
if err != nil {
sb.Logger.Error(
"Directory \"%s\" does not exist, and I was unable to create it!",
dataDirectory)
}
// if we are in offline mode we want to just load up the lists we
// currently have and work with that
if OfflineMode {
for listName, _ := range SupportedLists {
fileName := sb.DataDir + "/" + listName + ".dat"
tmpList := newSafeBrowsingList(listName, fileName)
tmpList.Logger = sb.Logger
err := tmpList.load(nil)
if err != nil {
sb.Logger.Warn("Error loading list %s: %s", listName, err)
continue
}
sb.Lists[listName] = tmpList
}
// debug.FreeOSMemory()
return sb, nil
}
// normal mode, contact the server for updates, etc.
err = sb.UpdateProcess()
return sb, err
}
func (sb *SafeBrowsing) UpdateProcess() (err error) {
sb.Logger.Info("Requesting list of lists from server...")
err = sb.requestSafeBrowsingLists()
if err != nil {
return err
}
err = sb.loadExistingData()
if err != nil {
return err
}
err, status := sb.update()
if (err != nil) && (status != 503) {
return err
} else if status == 503 {
sb.Logger.Warn("GSB service temporarily unavailable")
}
go sb.reloadLoop()
return nil
}
func (sb *SafeBrowsing) requestSafeBrowsingLists() (err error) {
// defer debug.FreeOSMemory()
url := fmt.Sprintf(
"https://safebrowsing.google.com/safebrowsing/list?"+
"client=%s&%s=%s&appver=%s&pver=%s",
sb.Client, sb.keyParam(), sb.Key, sb.AppVersion, sb.ProtocolVersion)
listresp, err := sb.request(url, "", true)
if err != nil {
return err
}
if listresp.StatusCode == 503 {
sb.requestSafeBrowsingLists()
} else if listresp.StatusCode != 200 {
return fmt.Errorf("Unexpected server response code: %d", listresp.StatusCode)
}
return sb.processSafeBrowsingLists(listresp.Body)
}
func (sb *SafeBrowsing) processSafeBrowsingLists(body io.Reader) (err error) {
buf := bytes.Buffer{}
if _, err = buf.ReadFrom(body); err != nil {
return fmt.Errorf("Unable to read list data: %s", err)
}
for _, listName := range strings.Split(strings.TrimSpace(buf.String()), "\n") {
if _, exists := SupportedLists[listName]; !exists {
continue
}
fileName := sb.DataDir + "/" + listName + ".dat"
tmpList := newSafeBrowsingList(listName, fileName)
tmpList.Logger = sb.Logger
sb.Lists[listName] = tmpList
}
return nil
}
func (sb *SafeBrowsing) loadExistingData() error {
sb.Logger.Info("Loading existing data....")
for _, sbl := range sb.Lists {
err := sbl.load(nil)
if err != nil {
return fmt.Errorf("Error loading list from %s: %s", sb.DataDir, err)
}
// debug.FreeOSMemory()
}
return nil
}
func (sb *SafeBrowsing) update() (err error, status int) {
sb.Logger.Info("Requesting updates...")
if err, status = sb.requestRedirectList(); err != nil {
return fmt.Errorf("Unable to retrieve updates: %s", err.Error()), status
}
for listName, list := range sb.Lists {
if err = list.loadDataFromRedirectLists(); err != nil {
return fmt.Errorf("Unable to process updates for %s: %s", listName, err.Error()), status
}
}
// update the last updated time
sb.LastUpdated = time.Now()
return nil, status
}
func (sb *SafeBrowsing) requestRedirectList() (err error, status int) {
// defer debug.FreeOSMemory()
url := fmt.Sprintf(
"https://safebrowsing.google.com/safebrowsing/downloads?"+
"client=%s&%s=%s&appver=%s&pver=%s",
sb.Client, sb.keyParam(), sb.Key, sb.AppVersion, sb.ProtocolVersion)
listsStr := ""
for list, sbl := range sb.Lists {
listsStr += string(list) + ";"
addChunkRange := sbl.ChunkRanges[CHUNK_TYPE_ADD]
if addChunkRange != "" {
listsStr += "a:" + addChunkRange + ":"
}
subChunkRange := sbl.ChunkRanges[CHUNK_TYPE_SUB]
if subChunkRange != "" {
listsStr += "s:" + subChunkRange
}
listsStr += "\n"
}
redirects, err := sb.request(url, listsStr, true)
if err != nil {
return err, 0
}
defer redirects.Body.Close()
if redirects.StatusCode != 200 {
tmp := &bytes.Buffer{}
tmp.ReadFrom(redirects.Body)
return fmt.Errorf("Unexpected server response code: %d\n%s", redirects.StatusCode, tmp), redirects.StatusCode
}
if err = sb.processRedirectList(redirects.Body); err != nil {
return err, redirects.StatusCode
}
return nil, redirects.StatusCode
}
func (sb *SafeBrowsing) processRedirectList(buf io.Reader) error {
// defer debug.FreeOSMemory()
scanner := bufio.NewScanner(buf)
//initialize temporary var
var currentListName string
var RedirectList []string = nil
currentDeletes := make(map[ChunkData_ChunkType]map[ChunkNum]bool)
currentDeletes[CHUNK_TYPE_ADD] = make(map[ChunkNum]bool)
currentDeletes[CHUNK_TYPE_SUB] = make(map[ChunkNum]bool)
for scanner.Scan() {
line := scanner.Text()
bits := strings.SplitN(line, ":", 2)
switch bits[0] {
case "n":
updateDelayStr := bits[1]
updateDelay, err := strconv.Atoi(updateDelayStr)
if err != nil {
return fmt.Errorf("Unable to parse timeout: %s", err)
}
sb.UpdateDelay = updateDelay
case "r":
// we need to reset full!
sb.reset()
// the docs say to request again, so we do that...
err, _ := sb.requestRedirectList()
return err
case "i":
if RedirectList != nil {
// save to DataRedirects
sb.Lists[currentListName].DataRedirects = RedirectList
sb.Lists[currentListName].DeleteChunks = currentDeletes
}
// reinitialize temporary var
RedirectList = make([]string, 0)
currentDeletes = make(map[ChunkData_ChunkType]map[ChunkNum]bool)
currentDeletes[CHUNK_TYPE_ADD] = make(map[ChunkNum]bool, 0)
currentDeletes[CHUNK_TYPE_SUB] = make(map[ChunkNum]bool, 0)
currentListName = bits[1]
case "u":
RedirectList = append(RedirectList, "https://"+bits[1])
case "ad":
addDeletes, err := parseChunkRange(bits[1])
if err != nil {
return fmt.Errorf("Error parsing delete add chunks range: %s", err)
}
currentDeletes[CHUNK_TYPE_ADD] = addDeletes
case "sd":
subDeletes, err := parseChunkRange(bits[1])
if err != nil {
return fmt.Errorf("Error parsing delete sub chunks range: %s", err)
}
currentDeletes[CHUNK_TYPE_SUB] = subDeletes
default:
continue
}
// debug.FreeOSMemory()
}
// add the final list
sb.Lists[currentListName].DataRedirects = RedirectList
sb.Lists[currentListName].DeleteChunks = currentDeletes
if err := scanner.Err(); err != nil && err != io.EOF {
return fmt.Errorf("Unable to parse list response: %s", err)
}
return nil
}
func (sb *SafeBrowsing) reset() {
// reinitalize all lists
for _, sbl := range sb.Lists {
// clear cache
sbl.Cache = make(map[FullHash]*FullHashCache)
sbl.Lookup = NewTrie()
sbl.FullHashes = NewTrie()
sbl.FullHashRequested = NewTrie()
sbl.DataRedirects = make([]string, 0)
sbl.DeleteChunks = make(map[ChunkData_ChunkType]map[ChunkNum]bool)
sbl.DeleteChunks[CHUNK_TYPE_ADD] = make(map[ChunkNum]bool, 0)
sbl.DeleteChunks[CHUNK_TYPE_SUB] = make(map[ChunkNum]bool, 0)
// kill off the chunks
sbl.ChunkRanges = map[ChunkData_ChunkType]string{
CHUNK_TYPE_ADD: "",
CHUNK_TYPE_SUB: "",
}
// delete any files we have loaded for this map
if sbl.FileName != "" {
os.Remove(sbl.FileName)
}
// debug.FreeOSMemory()
}
}
func (sb *SafeBrowsing) reloadLoop() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
randomFloat := r.Float64()
for {
// wait the update delay
duration := time.Duration(sb.UpdateDelay) * time.Second
sb.Logger.Info("Next update in %d seconds", sb.UpdateDelay)
time.Sleep(duration)
err, status := sb.update()
for x := 0; status == 503; x++ {
// first we wait 1 min, than some time between 30-60 mins
// doubling until we stop at 480 mins or succeed
mins := (30 * (randomFloat + 1) * float64(x)) + 1
if mins > 480 {
mins = 480
}
sb.Logger.Warn(
"Update failed, in back-off mode (waiting %d mins): %s",
mins,
err,
)
time.Sleep(time.Duration(mins) * time.Minute)
err, status = sb.update()
}
// debug.FreeOSMemory()
}
// Recover from all panicks in reloadLoop, just to log the erros.
defer func() {
if r := recover(); r != nil {
sb.Logger.Error("reloadLoop panicked: %v", r)
}
}()
}
const v3KeyPrefix = "AIza"
func (sb *SafeBrowsing) keyParam() string {
if strings.HasPrefix(sb.Key, v3KeyPrefix) {
return "key"
}
return "apikey"
}