forked from letsencrypt/boulder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkurl.go
353 lines (315 loc) · 11 KB
/
checkurl.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
/*
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 (
"bytes"
"crypto/sha256"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
// "runtime/debug"
"strconv"
"strings"
"time"
)
//import "encoding/hex"
type FullHashCache struct {
CreationDate time.Time
CacheLifeTime int
}
func newFullHashCache(creationDate time.Time, cacheLifeTime int) (fch *FullHashCache) {
fch = &FullHashCache{
CreationDate: creationDate,
CacheLifeTime: cacheLifeTime,
}
return fch
}
// Check to see if a URL is marked as unsafe by Google.
// Returns what list the URL is on, or an empty string if the URL is unlisted.
// Note that this query may perform a blocking HTTP request; if speed is important
// it may be preferable to use MightBeListed which will return quickly. If showing
// a warning to the user however, this call must be used.
func (sb *SafeBrowsing) IsListed(url string) (list string, err error) {
list, _, err = sb.queryUrl(url, true)
return list, err
}
// Check to see if a URL is likely marked as unsafe by Google.
// Returns what list the URL may be listed on, or an empty string if the URL is not listed.
// Note that this query does not perform a "request for full hashes" and MUST NOT be
// used to show a warning to the user.
func (sb *SafeBrowsing) MightBeListed(url string) (list string, fullHashMatch bool, err error) {
return sb.queryUrl(url, false)
}
var ErrOutOfDateHashes = errors.New("Unable to check listing, list hasn't been updated for 45 mins")
// Here is where we actually look up the hashes against our map.
func (sb *SafeBrowsing) queryUrl(url string, matchFullHash bool) (list string, fullHashMatch bool, err error) {
// defer debug.FreeOSMemory()
if matchFullHash && !sb.IsUpToDate() {
// we haven't had a sucessful update in the last 45 mins! abort!
return "", false, ErrOutOfDateHashes
}
// first Canonicalize
url = Canonicalize(url)
urls := GenerateTestCandidates(url)
// sb.Logger.Debug("Checking %d iterations of url", len(urls))
for list, sbl := range sb.Lists {
for _, url := range urls {
hostKey := ExtractHostKey(url)
hostKeyHash := HostHash(getHash(hostKey)[:4])
// sb.Logger.Debug("Host hash: %s", hex.EncodeToString([]byte(hostKeyHash)))
sbl.updateLock.RLock()
// hash it up
// sb.Logger.Debug("Hashing %s", url)
urlHash := getHash(url)
prefix := urlHash[:PREFIX_4B_SZ]
lookupHash := string(prefix)
fullLookupHash := string(urlHash)
// sb.Logger.Debug("testing hash: %s, full = %s",
// hex.EncodeToString([]byte(lookupHash)),
// hex.EncodeToString([]byte(fullLookupHash)))
fhc, ok := sb.Cache[hostKeyHash]
if ok && !fhc.checkValidity() {
delete(sb.Cache, hostKeyHash)
// sbl.Logger.Debug("Delete full length hash: %s",
// hex.EncodeToString([]byte(fullLookupHash)))
sbl.FullHashRequested.Delete(lookupHash)
sbl.FullHashes.Delete(fullLookupHash)
}
// look up full hash matches
if sbl.FullHashes.Get(fullLookupHash) {
sbl.updateLock.RUnlock()
return list, true, nil
}
// now see if there is a match in our prefix trie
keysToLookupMap := make(map[LookupHash]bool)
if sbl.Lookup.Get(lookupHash) {
if !matchFullHash || OfflineMode {
// sb.Logger.Debug("Partial hash hit")
sbl.updateLock.RUnlock()
return list, false, nil
}
// have we have already asked for full hashes for this prefix?
if sbl.FullHashRequested.Get(string(lookupHash)) {
// sb.Logger.Debug("Full length hash miss")
sbl.updateLock.RUnlock()
continue
}
// we matched a prefix and need to request a full hash
// sb.Logger.Debug("Need to request full length hashes for %s",
// hex.EncodeToString([]byte(prefix)))
keysToLookupMap[prefix] = true
}
sbl.updateLock.RUnlock()
if len(keysToLookupMap) > 0 {
err := sb.requestFullHashes(list, hostKeyHash, keysToLookupMap)
if err != nil {
return "", false, err
}
sbl.updateLock.RLock()
// re-check for full hash hit.
if sbl.FullHashes.Get(string(fullLookupHash)) {
sbl.updateLock.RUnlock()
return list, true, nil
}
sbl.updateLock.RUnlock()
}
}
// debug.FreeOSMemory()
}
return "", false, nil
}
// Checks to ensure we have had a successful update in the last 45 mins
func (sb *SafeBrowsing) IsUpToDate() bool {
return !OfflineMode && time.Since(sb.LastUpdated) < (time.Duration(45)*time.Minute)
}
func getHash(input string) (hash LookupHash) {
hasher := sha256.New()
hasher.Write([]byte(input))
return LookupHash(hasher.Sum(nil))
}
// Full hashes request have a temporary response validity
func (fhc *FullHashCache) checkValidity() bool {
return (time.Since(fhc.CreationDate) < (time.Duration(fhc.CacheLifeTime) * time.Second))
}
// request full hases for a set of lookup prefixes.
func (sb *SafeBrowsing) requestFullHashes(list string, host HostHash, prefixes map[LookupHash]bool) error {
if len(prefixes) == 0 {
return nil
}
query := "%d:%d\n%s"
buf := bytes.Buffer{}
firstPrefixLen := 0
for prefix, _ := range prefixes {
_, err := buf.Write([]byte(prefix))
if err != nil {
return err
}
if firstPrefixLen == 0 {
firstPrefixLen = len(prefix)
}
if firstPrefixLen != len(prefix) {
return fmt.Errorf("Attempted to used variable length hashes in lookup!")
}
}
body := fmt.Sprintf(query,
firstPrefixLen,
len(buf.String()),
buf.String())
url := fmt.Sprintf(
"https://safebrowsing.google.com/safebrowsing/gethash?"+
"client=%s&key=%s&appver=%s&pver=%s",
sb.Client, sb.Key, sb.AppVersion, sb.ProtocolVersion)
response, err := sb.request(url, body, true)
if err != nil {
return err // non-server error with HTTP
}
defer response.Body.Close()
// mark these prefxes as having been requested
sb.Lists[list].updateLock.Lock()
for prefix, _ := range prefixes {
sb.Lists[list].FullHashRequested.Set(string(prefix))
}
sb.Lists[list].updateLock.Unlock()
if response.StatusCode != 200 {
if response.StatusCode == 503 {
// Retry in background with a new thread
go sb.doFullHashBackOffRequest(host, url, body)
return fmt.Errorf("Service temporarily Unavailable")
}
return fmt.Errorf("Unable to lookup full hash, server returned %d",
response.StatusCode)
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return sb.processFullHashes(string(data), host)
}
// Process the retrieved full hashes, saving them to disk
func (sb *SafeBrowsing) processFullHashes(data string, host HostHash) (err error) {
// defer debug.FreeOSMemory()
split := strings.Split(data, "\n")
split_sz := len(split)
if split_sz == 0 {
return nil
}
cacheLifeTime, err := strconv.Atoi(split[0])
if err != nil {
return err
}
sb.Cache[host] = newFullHashCache(time.Now(), cacheLifeTime)
if split_sz <= 2 {
return nil
}
for i, len_splitsplit, chunk_sz := 1, 0, 0; (i+1) < split_sz && err == nil; i += chunk_sz {
splitsplit := strings.Split(split[i], ":")
len_splitsplit = len(splitsplit)
if len_splitsplit < 3 {
return fmt.Errorf("Malformated response: %s", split[i])
} else if len_splitsplit == 4 {
num_resp, err := strconv.Atoi(splitsplit[2])
if err != nil {
return err
} else if (num_resp + 2 + i) > split_sz {
return fmt.Errorf("Malformated response: %s", split[i])
}
chunk_sz = 2 + num_resp
} else {
chunk_sz = 2
}
err = sb.readFullHashChunk(split[i+1], splitsplit[0], host)
}
return err
}
func (sb *SafeBrowsing) readFullHashChunk(hashes string, list string, host HostHash) (err error) {
if hashes == "" || list == "" || host == "" {
return fmt.Errorf("Imcomplete data to readFullHashChunck()")
}
hashlen := 32
hasheslen := len(hashes)
for i := 0; (i + hashlen) <= hasheslen; i += hashlen {
hash := hashes[i:(i + hashlen)]
//sb.Lists[list].Logger.Debug("Adding full length hash: %s",
//hex.EncodeToString([]byte(hash)))
if sb.Lists == nil {
return fmt.Errorf("Google safe browsing lists have not been initialized")
} else if sb.Lists[list] == nil {
return fmt.Errorf("Google safe browsing list (%s) have not been initialized", list)
}
sb.Lists[list].updateLock.Lock()
sb.Lists[list].FullHashes.Set(hash)
sb.Lists[list].updateLock.Unlock()
}
return nil
}
// Continue the attempt to request for full hashes in the background, observing the required backoff behaviour.
func (sb *SafeBrowsing) doFullHashBackOffRequest(host HostHash, url string, body string) {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
randomFloat := r.Float64()
var response *http.Response
response.StatusCode = 503
var err error
for x := 0; response.StatusCode == 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 {
sb.Logger.Warn(
"Back-off for full hash %s exceeded 8 hours, it ain't going to happen, giving up: %s",
body,
response,
)
return
}
sb.Logger.Warn(
"Update failed, in full hash back-off mode (waiting %d mins)",
mins,
)
time.Sleep(time.Duration(mins) * time.Minute)
response, err = sb.request(url, body, true)
if err != nil {
sb.Logger.Error(
"Unable to request full hashes from response in back-off mode: %s",
err,
)
continue
}
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
sb.Logger.Error(
"Unable to request full hashes from response in back-off mode: %s",
err,
)
}
err = sb.processFullHashes(string(data), host)
if err != nil {
sb.Logger.Error(
"Unable process full hashes from response in back-off mode: %s; trying again.",
err,
)
sb.doFullHashBackOffRequest(host, url, body)
}
}