1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/safe_browsing/safe_browsing_database.h"
10 #include "base/bind.h"
11 #include "base/file_util.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/stats_counters.h"
15 #include "base/process/process.h"
16 #include "base/process/process_metrics.h"
17 #include "base/sha1.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/time/time.h"
21 #include "chrome/browser/safe_browsing/prefix_set.h"
22 #include "chrome/browser/safe_browsing/safe_browsing_store_file.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "crypto/sha2.h"
25 #include "net/base/net_util.h"
28 #if defined(OS_MACOSX)
29 #include "base/mac/mac_util.h"
32 using content::BrowserThread
;
36 // Filename suffix for the bloom filter.
37 const base::FilePath::CharType kBloomFilterFile
[] =
38 FILE_PATH_LITERAL(" Filter 2");
39 // Filename suffix for the prefix set.
40 const base::FilePath::CharType kPrefixSetFile
[] =
41 FILE_PATH_LITERAL(" Prefix Set");
42 // Filename suffix for download store.
43 const base::FilePath::CharType kDownloadDBFile
[] =
44 FILE_PATH_LITERAL(" Download");
45 // Filename suffix for client-side phishing detection whitelist store.
46 const base::FilePath::CharType kCsdWhitelistDBFile
[] =
47 FILE_PATH_LITERAL(" Csd Whitelist");
48 // Filename suffix for the download whitelist store.
49 const base::FilePath::CharType kDownloadWhitelistDBFile
[] =
50 FILE_PATH_LITERAL(" Download Whitelist");
51 // Filename suffix for the extension blacklist store.
52 const base::FilePath::CharType kExtensionBlacklistDBFile
[] =
53 FILE_PATH_LITERAL(" Extension Blacklist");
54 // Filename suffix for the side-effect free whitelist store.
55 const base::FilePath::CharType kSideEffectFreeWhitelistDBFile
[] =
56 FILE_PATH_LITERAL(" Side-Effect Free Whitelist");
57 // Filename suffix for the csd malware IP blacklist store.
58 const base::FilePath::CharType kIPBlacklistDBFile
[] =
59 FILE_PATH_LITERAL(" IP Blacklist");
61 // Filename suffix for browse store.
62 // TODO(shess): "Safe Browsing Bloom Prefix Set" is full of win.
63 // Unfortunately, to change the name implies lots of transition code
64 // for little benefit. If/when file formats change (say to put all
65 // the data in one file), that would be a convenient point to rectify
67 const base::FilePath::CharType kBrowseDBFile
[] = FILE_PATH_LITERAL(" Bloom");
69 // The maximum staleness for a cached entry.
70 const int kMaxStalenessMinutes
= 45;
72 // Maximum number of entries we allow in any of the whitelists.
73 // If a whitelist on disk contains more entries then all lookups to
74 // the whitelist will be considered a match.
75 const size_t kMaxWhitelistSize
= 5000;
77 // If the hash of this exact expression is on a whitelist then all
78 // lookups to this whitelist will be considered a match.
79 const char kWhitelistKillSwitchUrl
[] =
80 "sb-ssl.google.com/safebrowsing/csd/killswitch"; // Don't change this!
82 // If the hash of this exact expression is on a whitelist then the
83 // malware IP blacklisting feature will be disabled in csd.
85 const char kMalwareIPKillSwitchUrl
[] =
86 "sb-ssl.google.com/safebrowsing/csd/killswitch_malware";
88 const size_t kMaxIpPrefixSize
= 128;
89 const size_t kMinIpPrefixSize
= 1;
91 // To save space, the incoming |chunk_id| and |list_id| are combined
92 // into an |encoded_chunk_id| for storage by shifting the |list_id|
93 // into the low-order bits. These functions decode that information.
94 // TODO(lzheng): It was reasonable when database is saved in sqlite, but
95 // there should be better ways to save chunk_id and list_id after we use
96 // SafeBrowsingStoreFile.
97 int GetListIdBit(const int encoded_chunk_id
) {
98 return encoded_chunk_id
& 1;
100 int DecodeChunkId(int encoded_chunk_id
) {
101 return encoded_chunk_id
>> 1;
103 int EncodeChunkId(const int chunk
, const int list_id
) {
104 DCHECK_NE(list_id
, safe_browsing_util::INVALID
);
105 return chunk
<< 1 | list_id
% 2;
108 // Generate the set of full hashes to check for |url|. If
109 // |include_whitelist_hashes| is true we will generate additional path-prefixes
110 // to match against the csd whitelist. E.g., if the path-prefix /foo is on the
111 // whitelist it should also match /foo/bar which is not the case for all the
112 // other lists. We'll also always add a pattern for the empty path.
113 // TODO(shess): This function is almost the same as
114 // |CompareFullHashes()| in safe_browsing_util.cc, except that code
115 // does an early exit on match. Since match should be the infrequent
116 // case (phishing or malware found), consider combining this function
118 void BrowseFullHashesToCheck(const GURL
& url
,
119 bool include_whitelist_hashes
,
120 std::vector
<SBFullHash
>* full_hashes
) {
121 std::vector
<std::string
> hosts
;
122 if (url
.HostIsIPAddress()) {
123 hosts
.push_back(url
.host());
125 safe_browsing_util::GenerateHostsToCheck(url
, &hosts
);
128 std::vector
<std::string
> paths
;
129 safe_browsing_util::GeneratePathsToCheck(url
, &paths
);
131 for (size_t i
= 0; i
< hosts
.size(); ++i
) {
132 for (size_t j
= 0; j
< paths
.size(); ++j
) {
133 const std::string
& path
= paths
[j
];
134 SBFullHash full_hash
;
135 crypto::SHA256HashString(hosts
[i
] + path
, &full_hash
,
137 full_hashes
->push_back(full_hash
);
139 // We may have /foo as path-prefix in the whitelist which should
140 // also match with /foo/bar and /foo?bar. Hence, for every path
141 // that ends in '/' we also add the path without the slash.
142 if (include_whitelist_hashes
&&
144 path
[path
.size() - 1] == '/') {
145 crypto::SHA256HashString(hosts
[i
] + path
.substr(0, path
.size() - 1),
146 &full_hash
, sizeof(full_hash
));
147 full_hashes
->push_back(full_hash
);
153 // Get the prefixes matching the download |urls|.
154 void GetDownloadUrlPrefixes(const std::vector
<GURL
>& urls
,
155 std::vector
<SBPrefix
>* prefixes
) {
156 std::vector
<SBFullHash
> full_hashes
;
157 for (size_t i
= 0; i
< urls
.size(); ++i
)
158 BrowseFullHashesToCheck(urls
[i
], false, &full_hashes
);
160 for (size_t i
= 0; i
< full_hashes
.size(); ++i
)
161 prefixes
->push_back(full_hashes
[i
].prefix
);
164 // Helper function to compare addprefixes in |store| with |prefixes|.
165 // The |list_bit| indicates which list (url or hash) to compare.
167 // Returns true if there is a match, |*prefix_hits| (if non-NULL) will contain
168 // the actual matching prefixes.
169 bool MatchAddPrefixes(SafeBrowsingStore
* store
,
171 const std::vector
<SBPrefix
>& prefixes
,
172 std::vector
<SBPrefix
>* prefix_hits
) {
173 prefix_hits
->clear();
174 bool found_match
= false;
176 SBAddPrefixes add_prefixes
;
177 store
->GetAddPrefixes(&add_prefixes
);
178 for (SBAddPrefixes::const_iterator iter
= add_prefixes
.begin();
179 iter
!= add_prefixes
.end(); ++iter
) {
180 for (size_t j
= 0; j
< prefixes
.size(); ++j
) {
181 const SBPrefix
& prefix
= prefixes
[j
];
182 if (prefix
== iter
->prefix
&&
183 GetListIdBit(iter
->chunk_id
) == list_bit
) {
184 prefix_hits
->push_back(prefix
);
192 // Find the entries in |full_hashes| with prefix in |prefix_hits|, and
193 // add them to |full_hits| if not expired. "Not expired" is when
194 // either |last_update| was recent enough, or the item has been
195 // received recently enough. Expired items are not deleted because a
196 // future update may make them acceptable again.
198 // For efficiency reasons the code walks |prefix_hits| and
199 // |full_hashes| in parallel, so they must be sorted by prefix.
200 void GetCachedFullHashesForBrowse(const std::vector
<SBPrefix
>& prefix_hits
,
201 const std::vector
<SBAddFullHash
>& full_hashes
,
202 std::vector
<SBFullHashResult
>* full_hits
,
203 base::Time last_update
) {
204 const base::Time expire_time
=
205 base::Time::Now() - base::TimeDelta::FromMinutes(kMaxStalenessMinutes
);
207 std::vector
<SBPrefix
>::const_iterator piter
= prefix_hits
.begin();
208 std::vector
<SBAddFullHash
>::const_iterator hiter
= full_hashes
.begin();
210 while (piter
!= prefix_hits
.end() && hiter
!= full_hashes
.end()) {
211 if (*piter
< hiter
->full_hash
.prefix
) {
213 } else if (hiter
->full_hash
.prefix
< *piter
) {
216 if (expire_time
< last_update
||
217 expire_time
.ToTimeT() < hiter
->received
) {
218 SBFullHashResult result
;
219 const int list_bit
= GetListIdBit(hiter
->chunk_id
);
220 DCHECK(list_bit
== safe_browsing_util::MALWARE
||
221 list_bit
== safe_browsing_util::PHISH
);
222 const safe_browsing_util::ListType list_id
=
223 static_cast<safe_browsing_util::ListType
>(list_bit
);
224 if (!safe_browsing_util::GetListName(list_id
, &result
.list_name
))
226 result
.add_chunk_id
= DecodeChunkId(hiter
->chunk_id
);
227 result
.hash
= hiter
->full_hash
;
228 full_hits
->push_back(result
);
231 // Only increment |hiter|, |piter| might have multiple hits.
237 // This function generates a chunk range string for |chunks|. It
238 // outputs one chunk range string per list and writes it to the
239 // |list_ranges| vector. We expect |list_ranges| to already be of the
240 // right size. E.g., if |chunks| contains chunks with two different
241 // list ids then |list_ranges| must contain two elements.
242 void GetChunkRanges(const std::vector
<int>& chunks
,
243 std::vector
<std::string
>* list_ranges
) {
244 // Since there are 2 possible list ids, there must be exactly two
245 // list ranges. Even if the chunk data should only contain one
246 // line, this code has to somehow handle corruption.
247 DCHECK_EQ(2U, list_ranges
->size());
249 std::vector
<std::vector
<int> > decoded_chunks(list_ranges
->size());
250 for (std::vector
<int>::const_iterator iter
= chunks
.begin();
251 iter
!= chunks
.end(); ++iter
) {
252 int mod_list_id
= GetListIdBit(*iter
);
253 DCHECK_GE(mod_list_id
, 0);
254 DCHECK_LT(static_cast<size_t>(mod_list_id
), decoded_chunks
.size());
255 decoded_chunks
[mod_list_id
].push_back(DecodeChunkId(*iter
));
257 for (size_t i
= 0; i
< decoded_chunks
.size(); ++i
) {
258 ChunksToRangeString(decoded_chunks
[i
], &((*list_ranges
)[i
]));
262 // Helper function to create chunk range lists for Browse related
264 void UpdateChunkRanges(SafeBrowsingStore
* store
,
265 const std::vector
<std::string
>& listnames
,
266 std::vector
<SBListChunkRanges
>* lists
) {
270 DCHECK_GT(listnames
.size(), 0U);
271 DCHECK_LE(listnames
.size(), 2U);
272 std::vector
<int> add_chunks
;
273 std::vector
<int> sub_chunks
;
274 store
->GetAddChunks(&add_chunks
);
275 store
->GetSubChunks(&sub_chunks
);
277 // Always decode 2 ranges, even if only the first one is expected.
278 // The loop below will only load as many into |lists| as |listnames|
280 std::vector
<std::string
> adds(2);
281 std::vector
<std::string
> subs(2);
282 GetChunkRanges(add_chunks
, &adds
);
283 GetChunkRanges(sub_chunks
, &subs
);
285 for (size_t i
= 0; i
< listnames
.size(); ++i
) {
286 const std::string
& listname
= listnames
[i
];
287 DCHECK_EQ(safe_browsing_util::GetListId(listname
) % 2,
288 static_cast<int>(i
% 2));
289 DCHECK_NE(safe_browsing_util::GetListId(listname
),
290 safe_browsing_util::INVALID
);
291 lists
->push_back(SBListChunkRanges(listname
));
292 lists
->back().adds
.swap(adds
[i
]);
293 lists
->back().subs
.swap(subs
[i
]);
297 void UpdateChunkRangesForLists(SafeBrowsingStore
* store
,
298 const std::string
& listname0
,
299 const std::string
& listname1
,
300 std::vector
<SBListChunkRanges
>* lists
) {
301 std::vector
<std::string
> listnames
;
302 listnames
.push_back(listname0
);
303 listnames
.push_back(listname1
);
304 UpdateChunkRanges(store
, listnames
, lists
);
307 void UpdateChunkRangesForList(SafeBrowsingStore
* store
,
308 const std::string
& listname
,
309 std::vector
<SBListChunkRanges
>* lists
) {
310 UpdateChunkRanges(store
, std::vector
<std::string
>(1, listname
), lists
);
313 // Order |SBAddFullHash| on the prefix part. |SBAddPrefixLess()| from
314 // safe_browsing_store.h orders on both chunk-id and prefix.
315 bool SBAddFullHashPrefixLess(const SBAddFullHash
& a
, const SBAddFullHash
& b
) {
316 return a
.full_hash
.prefix
< b
.full_hash
.prefix
;
319 // This code always checks for non-zero file size. This helper makes
320 // that less verbose.
321 int64
GetFileSizeOrZero(const base::FilePath
& file_path
) {
323 if (!base::GetFileSize(file_path
, &size_64
))
330 // The default SafeBrowsingDatabaseFactory.
331 class SafeBrowsingDatabaseFactoryImpl
: public SafeBrowsingDatabaseFactory
{
333 virtual SafeBrowsingDatabase
* CreateSafeBrowsingDatabase(
334 bool enable_download_protection
,
335 bool enable_client_side_whitelist
,
336 bool enable_download_whitelist
,
337 bool enable_extension_blacklist
,
338 bool enable_side_effect_free_whitelist
,
339 bool enable_ip_blacklist
) OVERRIDE
{
340 return new SafeBrowsingDatabaseNew(
341 new SafeBrowsingStoreFile
,
342 enable_download_protection
? new SafeBrowsingStoreFile
: NULL
,
343 enable_client_side_whitelist
? new SafeBrowsingStoreFile
: NULL
,
344 enable_download_whitelist
? new SafeBrowsingStoreFile
: NULL
,
345 enable_extension_blacklist
? new SafeBrowsingStoreFile
: NULL
,
346 enable_side_effect_free_whitelist
? new SafeBrowsingStoreFile
: NULL
,
347 enable_ip_blacklist
? new SafeBrowsingStoreFile
: NULL
);
350 SafeBrowsingDatabaseFactoryImpl() { }
353 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingDatabaseFactoryImpl
);
357 SafeBrowsingDatabaseFactory
* SafeBrowsingDatabase::factory_
= NULL
;
359 // Factory method, non-thread safe. Caller has to make sure this s called
360 // on SafeBrowsing Thread.
361 // TODO(shess): There's no need for a factory any longer. Convert
362 // SafeBrowsingDatabaseNew to SafeBrowsingDatabase, and have Create()
363 // callers just construct things directly.
364 SafeBrowsingDatabase
* SafeBrowsingDatabase::Create(
365 bool enable_download_protection
,
366 bool enable_client_side_whitelist
,
367 bool enable_download_whitelist
,
368 bool enable_extension_blacklist
,
369 bool enable_side_effect_free_whitelist
,
370 bool enable_ip_blacklist
) {
372 factory_
= new SafeBrowsingDatabaseFactoryImpl();
373 return factory_
->CreateSafeBrowsingDatabase(
374 enable_download_protection
,
375 enable_client_side_whitelist
,
376 enable_download_whitelist
,
377 enable_extension_blacklist
,
378 enable_side_effect_free_whitelist
,
379 enable_ip_blacklist
);
382 SafeBrowsingDatabase::~SafeBrowsingDatabase() {
386 base::FilePath
SafeBrowsingDatabase::BrowseDBFilename(
387 const base::FilePath
& db_base_filename
) {
388 return base::FilePath(db_base_filename
.value() + kBrowseDBFile
);
392 base::FilePath
SafeBrowsingDatabase::DownloadDBFilename(
393 const base::FilePath
& db_base_filename
) {
394 return base::FilePath(db_base_filename
.value() + kDownloadDBFile
);
398 base::FilePath
SafeBrowsingDatabase::BloomFilterForFilename(
399 const base::FilePath
& db_filename
) {
400 return base::FilePath(db_filename
.value() + kBloomFilterFile
);
404 base::FilePath
SafeBrowsingDatabase::PrefixSetForFilename(
405 const base::FilePath
& db_filename
) {
406 return base::FilePath(db_filename
.value() + kPrefixSetFile
);
410 base::FilePath
SafeBrowsingDatabase::CsdWhitelistDBFilename(
411 const base::FilePath
& db_filename
) {
412 return base::FilePath(db_filename
.value() + kCsdWhitelistDBFile
);
416 base::FilePath
SafeBrowsingDatabase::DownloadWhitelistDBFilename(
417 const base::FilePath
& db_filename
) {
418 return base::FilePath(db_filename
.value() + kDownloadWhitelistDBFile
);
422 base::FilePath
SafeBrowsingDatabase::ExtensionBlacklistDBFilename(
423 const base::FilePath
& db_filename
) {
424 return base::FilePath(db_filename
.value() + kExtensionBlacklistDBFile
);
428 base::FilePath
SafeBrowsingDatabase::SideEffectFreeWhitelistDBFilename(
429 const base::FilePath
& db_filename
) {
430 return base::FilePath(db_filename
.value() + kSideEffectFreeWhitelistDBFile
);
434 base::FilePath
SafeBrowsingDatabase::IpBlacklistDBFilename(
435 const base::FilePath
& db_filename
) {
436 return base::FilePath(db_filename
.value() + kIPBlacklistDBFile
);
439 SafeBrowsingStore
* SafeBrowsingDatabaseNew::GetStore(const int list_id
) {
440 if (list_id
== safe_browsing_util::PHISH
||
441 list_id
== safe_browsing_util::MALWARE
) {
442 return browse_store_
.get();
443 } else if (list_id
== safe_browsing_util::BINURL
) {
444 return download_store_
.get();
445 } else if (list_id
== safe_browsing_util::CSDWHITELIST
) {
446 return csd_whitelist_store_
.get();
447 } else if (list_id
== safe_browsing_util::DOWNLOADWHITELIST
) {
448 return download_whitelist_store_
.get();
449 } else if (list_id
== safe_browsing_util::EXTENSIONBLACKLIST
) {
450 return extension_blacklist_store_
.get();
451 } else if (list_id
== safe_browsing_util::SIDEEFFECTFREEWHITELIST
) {
452 return side_effect_free_whitelist_store_
.get();
453 } else if (list_id
== safe_browsing_util::IPBLACKLIST
) {
454 return ip_blacklist_store_
.get();
460 void SafeBrowsingDatabase::RecordFailure(FailureType failure_type
) {
461 UMA_HISTOGRAM_ENUMERATION("SB2.DatabaseFailure", failure_type
,
462 FAILURE_DATABASE_MAX
);
465 SafeBrowsingDatabaseNew::SafeBrowsingDatabaseNew()
466 : creation_loop_(base::MessageLoop::current()),
467 browse_store_(new SafeBrowsingStoreFile
),
468 reset_factory_(this),
469 corruption_detected_(false),
470 change_detected_(false) {
471 DCHECK(browse_store_
.get());
472 DCHECK(!download_store_
.get());
473 DCHECK(!csd_whitelist_store_
.get());
474 DCHECK(!download_whitelist_store_
.get());
475 DCHECK(!extension_blacklist_store_
.get());
476 DCHECK(!side_effect_free_whitelist_store_
.get());
477 DCHECK(!ip_blacklist_store_
.get());
480 SafeBrowsingDatabaseNew::SafeBrowsingDatabaseNew(
481 SafeBrowsingStore
* browse_store
,
482 SafeBrowsingStore
* download_store
,
483 SafeBrowsingStore
* csd_whitelist_store
,
484 SafeBrowsingStore
* download_whitelist_store
,
485 SafeBrowsingStore
* extension_blacklist_store
,
486 SafeBrowsingStore
* side_effect_free_whitelist_store
,
487 SafeBrowsingStore
* ip_blacklist_store
)
488 : creation_loop_(base::MessageLoop::current()),
489 browse_store_(browse_store
),
490 download_store_(download_store
),
491 csd_whitelist_store_(csd_whitelist_store
),
492 download_whitelist_store_(download_whitelist_store
),
493 extension_blacklist_store_(extension_blacklist_store
),
494 side_effect_free_whitelist_store_(side_effect_free_whitelist_store
),
495 ip_blacklist_store_(ip_blacklist_store
),
496 reset_factory_(this),
497 corruption_detected_(false) {
498 DCHECK(browse_store_
.get());
501 SafeBrowsingDatabaseNew::~SafeBrowsingDatabaseNew() {
502 // The DCHECK is disabled due to crbug.com/338486 .
503 // DCHECK_EQ(creation_loop_, base::MessageLoop::current());
506 void SafeBrowsingDatabaseNew::Init(const base::FilePath
& filename_base
) {
507 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
508 // Ensure we haven't been run before.
509 DCHECK(browse_filename_
.empty());
510 DCHECK(download_filename_
.empty());
511 DCHECK(csd_whitelist_filename_
.empty());
512 DCHECK(download_whitelist_filename_
.empty());
513 DCHECK(extension_blacklist_filename_
.empty());
514 DCHECK(side_effect_free_whitelist_filename_
.empty());
515 DCHECK(ip_blacklist_filename_
.empty());
517 browse_filename_
= BrowseDBFilename(filename_base
);
518 browse_prefix_set_filename_
= PrefixSetForFilename(browse_filename_
);
522 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
523 base::Unretained(this)));
524 DVLOG(1) << "Init browse store: " << browse_filename_
.value();
527 // NOTE: There is no need to grab the lock in this function, since
528 // until it returns, there are no pointers to this class on other
529 // threads. Then again, that means there is no possibility of
530 // contention on the lock...
531 base::AutoLock
locked(lookup_lock_
);
532 full_browse_hashes_
.clear();
533 pending_browse_hashes_
.clear();
537 if (download_store_
.get()) {
538 download_filename_
= DownloadDBFilename(filename_base
);
539 download_store_
->Init(
541 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
542 base::Unretained(this)));
543 DVLOG(1) << "Init download store: " << download_filename_
.value();
546 if (csd_whitelist_store_
.get()) {
547 csd_whitelist_filename_
= CsdWhitelistDBFilename(filename_base
);
548 csd_whitelist_store_
->Init(
549 csd_whitelist_filename_
,
550 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
551 base::Unretained(this)));
552 DVLOG(1) << "Init csd whitelist store: " << csd_whitelist_filename_
.value();
553 std::vector
<SBAddFullHash
> full_hashes
;
554 if (csd_whitelist_store_
->GetAddFullHashes(&full_hashes
)) {
555 LoadWhitelist(full_hashes
, &csd_whitelist_
);
557 WhitelistEverything(&csd_whitelist_
);
560 WhitelistEverything(&csd_whitelist_
); // Just to be safe.
563 if (download_whitelist_store_
.get()) {
564 download_whitelist_filename_
= DownloadWhitelistDBFilename(filename_base
);
565 download_whitelist_store_
->Init(
566 download_whitelist_filename_
,
567 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
568 base::Unretained(this)));
569 DVLOG(1) << "Init download whitelist store: "
570 << download_whitelist_filename_
.value();
571 std::vector
<SBAddFullHash
> full_hashes
;
572 if (download_whitelist_store_
->GetAddFullHashes(&full_hashes
)) {
573 LoadWhitelist(full_hashes
, &download_whitelist_
);
575 WhitelistEverything(&download_whitelist_
);
578 WhitelistEverything(&download_whitelist_
); // Just to be safe.
581 if (extension_blacklist_store_
.get()) {
582 extension_blacklist_filename_
= ExtensionBlacklistDBFilename(filename_base
);
583 extension_blacklist_store_
->Init(
584 extension_blacklist_filename_
,
585 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
586 base::Unretained(this)));
587 DVLOG(1) << "Init extension blacklist store: "
588 << extension_blacklist_filename_
.value();
591 if (side_effect_free_whitelist_store_
.get()) {
592 side_effect_free_whitelist_filename_
=
593 SideEffectFreeWhitelistDBFilename(filename_base
);
594 side_effect_free_whitelist_prefix_set_filename_
=
595 PrefixSetForFilename(side_effect_free_whitelist_filename_
);
596 side_effect_free_whitelist_store_
->Init(
597 side_effect_free_whitelist_filename_
,
598 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
599 base::Unretained(this)));
600 DVLOG(1) << "Init side-effect free whitelist store: "
601 << side_effect_free_whitelist_filename_
.value();
603 // If there is no database, the filter cannot be used.
604 base::File::Info db_info
;
605 if (base::GetFileInfo(side_effect_free_whitelist_filename_
, &db_info
)
606 && db_info
.size
!= 0) {
607 const base::TimeTicks before
= base::TimeTicks::Now();
608 side_effect_free_whitelist_prefix_set_
.reset(
609 safe_browsing::PrefixSet::LoadFile(
610 side_effect_free_whitelist_prefix_set_filename_
));
611 DVLOG(1) << "SafeBrowsingDatabaseNew read side-effect free whitelist "
613 << (base::TimeTicks::Now() - before
).InMilliseconds() << " ms";
614 UMA_HISTOGRAM_TIMES("SB2.SideEffectFreeWhitelistPrefixSetLoad",
615 base::TimeTicks::Now() - before
);
616 if (!side_effect_free_whitelist_prefix_set_
.get())
617 RecordFailure(FAILURE_SIDE_EFFECT_FREE_WHITELIST_PREFIX_SET_READ
);
620 // Delete any files of the side-effect free sidelist that may be around
621 // from when it was previously enabled.
622 SafeBrowsingStoreFile::DeleteStore(
623 SideEffectFreeWhitelistDBFilename(filename_base
));
626 if (ip_blacklist_store_
.get()) {
627 ip_blacklist_filename_
= IpBlacklistDBFilename(filename_base
);
628 ip_blacklist_store_
->Init(
629 ip_blacklist_filename_
,
630 base::Bind(&SafeBrowsingDatabaseNew::HandleCorruptDatabase
,
631 base::Unretained(this)));
632 DVLOG(1) << "SafeBrowsingDatabaseNew read ip blacklist: "
633 << ip_blacklist_filename_
.value();
634 std::vector
<SBAddFullHash
> full_hashes
;
635 if (ip_blacklist_store_
->GetAddFullHashes(&full_hashes
)) {
636 LoadIpBlacklist(full_hashes
);
638 DVLOG(1) << "Unable to load full hashes from the IP blacklist.";
639 LoadIpBlacklist(std::vector
<SBAddFullHash
>()); // Clear the list.
644 bool SafeBrowsingDatabaseNew::ResetDatabase() {
645 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
647 // Delete files on disk.
648 // TODO(shess): Hard to see where one might want to delete without a
649 // reset. Perhaps inline |Delete()|?
653 // Reset objects in memory.
655 base::AutoLock
locked(lookup_lock_
);
656 full_browse_hashes_
.clear();
657 pending_browse_hashes_
.clear();
658 prefix_miss_cache_
.clear();
659 browse_prefix_set_
.reset();
660 side_effect_free_whitelist_prefix_set_
.reset();
661 ip_blacklist_
.clear();
663 // Wants to acquire the lock itself.
664 WhitelistEverything(&csd_whitelist_
);
665 WhitelistEverything(&download_whitelist_
);
669 // TODO(lzheng): Remove matching_list, it is not used anywhere.
670 bool SafeBrowsingDatabaseNew::ContainsBrowseUrl(
672 std::string
* matching_list
,
673 std::vector
<SBPrefix
>* prefix_hits
,
674 std::vector
<SBFullHashResult
>* full_hits
,
675 base::Time last_update
) {
676 // Clear the results first.
677 matching_list
->clear();
678 prefix_hits
->clear();
681 std::vector
<SBFullHash
> full_hashes
;
682 BrowseFullHashesToCheck(url
, false, &full_hashes
);
683 if (full_hashes
.empty())
686 // This function is called on the I/O thread, prevent changes to
687 // filter and caches.
688 base::AutoLock
locked(lookup_lock_
);
690 // |browse_prefix_set_| is empty until it is either read from disk, or the
691 // first update populates it. Bail out without a hit if not yet
693 if (!browse_prefix_set_
.get())
696 size_t miss_count
= 0;
697 for (size_t i
= 0; i
< full_hashes
.size(); ++i
) {
698 const SBPrefix prefix
= full_hashes
[i
].prefix
;
699 if (browse_prefix_set_
->Exists(prefix
)) {
700 prefix_hits
->push_back(prefix
);
701 if (prefix_miss_cache_
.count(prefix
) > 0)
706 // If all the prefixes are cached as 'misses', don't issue a GetHash.
707 if (miss_count
== prefix_hits
->size())
710 // Find the matching full-hash results. |full_browse_hashes_| are from the
711 // database, |pending_browse_hashes_| are from GetHash requests between
713 std::sort(prefix_hits
->begin(), prefix_hits
->end());
715 GetCachedFullHashesForBrowse(*prefix_hits
, full_browse_hashes_
,
716 full_hits
, last_update
);
717 GetCachedFullHashesForBrowse(*prefix_hits
, pending_browse_hashes_
,
718 full_hits
, last_update
);
722 bool SafeBrowsingDatabaseNew::ContainsDownloadUrl(
723 const std::vector
<GURL
>& urls
,
724 std::vector
<SBPrefix
>* prefix_hits
) {
725 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
727 // Ignore this check when download checking is not enabled.
728 if (!download_store_
.get())
731 std::vector
<SBPrefix
> prefixes
;
732 GetDownloadUrlPrefixes(urls
, &prefixes
);
733 return MatchAddPrefixes(download_store_
.get(),
734 safe_browsing_util::BINURL
% 2,
739 bool SafeBrowsingDatabaseNew::ContainsCsdWhitelistedUrl(const GURL
& url
) {
740 // This method is theoretically thread-safe but we expect all calls to
741 // originate from the IO thread.
742 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
743 std::vector
<SBFullHash
> full_hashes
;
744 BrowseFullHashesToCheck(url
, true, &full_hashes
);
745 return ContainsWhitelistedHashes(csd_whitelist_
, full_hashes
);
748 bool SafeBrowsingDatabaseNew::ContainsDownloadWhitelistedUrl(const GURL
& url
) {
749 std::vector
<SBFullHash
> full_hashes
;
750 BrowseFullHashesToCheck(url
, true, &full_hashes
);
751 return ContainsWhitelistedHashes(download_whitelist_
, full_hashes
);
754 bool SafeBrowsingDatabaseNew::ContainsExtensionPrefixes(
755 const std::vector
<SBPrefix
>& prefixes
,
756 std::vector
<SBPrefix
>* prefix_hits
) {
757 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
758 if (!extension_blacklist_store_
)
761 return MatchAddPrefixes(extension_blacklist_store_
.get(),
762 safe_browsing_util::EXTENSIONBLACKLIST
% 2,
767 bool SafeBrowsingDatabaseNew::ContainsSideEffectFreeWhitelistUrl(
769 SBFullHash full_hash
;
773 safe_browsing_util::CanonicalizeUrl(url
, &host
, &path
, &query
);
774 std::string url_to_check
= host
+ path
;
776 url_to_check
+= "?" + query
;
777 crypto::SHA256HashString(url_to_check
, &full_hash
, sizeof(full_hash
));
779 // This function can be called on any thread, so lock against any changes
780 base::AutoLock
locked(lookup_lock_
);
782 // |side_effect_free_whitelist_prefix_set_| is empty until it is either read
783 // from disk, or the first update populates it. Bail out without a hit if
784 // not yet available.
785 if (!side_effect_free_whitelist_prefix_set_
.get())
788 return side_effect_free_whitelist_prefix_set_
->Exists(full_hash
.prefix
);
791 bool SafeBrowsingDatabaseNew::ContainsMalwareIP(const std::string
& ip_address
) {
792 net::IPAddressNumber ip_number
;
793 if (!net::ParseIPLiteralToNumber(ip_address
, &ip_number
)) {
794 DVLOG(2) << "Unable to parse IP address: '" << ip_address
<< "'";
797 if (ip_number
.size() == net::kIPv4AddressSize
) {
798 ip_number
= net::ConvertIPv4NumberToIPv6Number(ip_number
);
800 if (ip_number
.size() != net::kIPv6AddressSize
) {
801 DVLOG(2) << "Unable to convert IPv4 address to IPv6: '"
802 << ip_address
<< "'";
803 return false; // better safe than sorry.
805 // This function can be called from any thread.
806 base::AutoLock
locked(lookup_lock_
);
807 for (IPBlacklist::const_iterator it
= ip_blacklist_
.begin();
808 it
!= ip_blacklist_
.end();
810 const std::string
& mask
= it
->first
;
811 DCHECK_EQ(mask
.size(), ip_number
.size());
812 std::string
subnet(net::kIPv6AddressSize
, '\0');
813 for (size_t i
= 0; i
< net::kIPv6AddressSize
; ++i
) {
814 subnet
[i
] = ip_number
[i
] & mask
[i
];
816 const std::string hash
= base::SHA1HashString(subnet
);
817 DVLOG(2) << "Lookup Malware IP: "
818 << " ip:" << ip_address
819 << " mask:" << base::HexEncode(mask
.data(), mask
.size())
820 << " subnet:" << base::HexEncode(subnet
.data(), subnet
.size())
821 << " hash:" << base::HexEncode(hash
.data(), hash
.size());
822 if (it
->second
.count(hash
) > 0) {
829 bool SafeBrowsingDatabaseNew::ContainsDownloadWhitelistedString(
830 const std::string
& str
) {
832 crypto::SHA256HashString(str
, &hash
, sizeof(hash
));
833 std::vector
<SBFullHash
> hashes
;
834 hashes
.push_back(hash
);
835 return ContainsWhitelistedHashes(download_whitelist_
, hashes
);
838 bool SafeBrowsingDatabaseNew::ContainsWhitelistedHashes(
839 const SBWhitelist
& whitelist
,
840 const std::vector
<SBFullHash
>& hashes
) {
841 base::AutoLock
l(lookup_lock_
);
842 if (whitelist
.second
)
844 for (std::vector
<SBFullHash
>::const_iterator it
= hashes
.begin();
845 it
!= hashes
.end(); ++it
) {
846 if (std::binary_search(whitelist
.first
.begin(), whitelist
.first
.end(), *it
))
852 // Helper to insert entries for all of the prefixes or full hashes in
853 // |entry| into the store.
854 void SafeBrowsingDatabaseNew::InsertAdd(int chunk_id
, SBPrefix host
,
855 const SBEntry
* entry
, int list_id
) {
856 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
858 SafeBrowsingStore
* store
= GetStore(list_id
);
861 STATS_COUNTER("SB.HostInsert", 1);
862 const int encoded_chunk_id
= EncodeChunkId(chunk_id
, list_id
);
863 const int count
= entry
->prefix_count();
865 DCHECK(!entry
->IsSub());
867 // No prefixes, use host instead.
868 STATS_COUNTER("SB.PrefixAdd", 1);
869 store
->WriteAddPrefix(encoded_chunk_id
, host
);
870 } else if (entry
->IsPrefix()) {
872 for (int i
= 0; i
< count
; i
++) {
873 const SBPrefix prefix
= entry
->PrefixAt(i
);
874 STATS_COUNTER("SB.PrefixAdd", 1);
875 store
->WriteAddPrefix(encoded_chunk_id
, prefix
);
878 // Prefixes and hashes.
879 const base::Time receive_time
= base::Time::Now();
880 for (int i
= 0; i
< count
; ++i
) {
881 const SBFullHash full_hash
= entry
->FullHashAt(i
);
882 const SBPrefix prefix
= full_hash
.prefix
;
884 STATS_COUNTER("SB.PrefixAdd", 1);
885 store
->WriteAddPrefix(encoded_chunk_id
, prefix
);
887 STATS_COUNTER("SB.PrefixAddFull", 1);
888 store
->WriteAddHash(encoded_chunk_id
, receive_time
, full_hash
);
893 // Helper to iterate over all the entries in the hosts in |chunks| and
894 // add them to the store.
895 void SafeBrowsingDatabaseNew::InsertAddChunks(
896 const safe_browsing_util::ListType list_id
,
897 const SBChunkList
& chunks
) {
898 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
900 SafeBrowsingStore
* store
= GetStore(list_id
);
903 for (SBChunkList::const_iterator citer
= chunks
.begin();
904 citer
!= chunks
.end(); ++citer
) {
905 const int chunk_id
= citer
->chunk_number
;
907 // The server can give us a chunk that we already have because
908 // it's part of a range. Don't add it again.
909 const int encoded_chunk_id
= EncodeChunkId(chunk_id
, list_id
);
910 if (store
->CheckAddChunk(encoded_chunk_id
))
913 store
->SetAddChunk(encoded_chunk_id
);
914 for (std::deque
<SBChunkHost
>::const_iterator hiter
= citer
->hosts
.begin();
915 hiter
!= citer
->hosts
.end(); ++hiter
) {
916 // NOTE: Could pass |encoded_chunk_id|, but then inserting add
917 // chunks would look different from inserting sub chunks.
918 InsertAdd(chunk_id
, hiter
->host
, hiter
->entry
, list_id
);
923 // Helper to insert entries for all of the prefixes or full hashes in
924 // |entry| into the store.
925 void SafeBrowsingDatabaseNew::InsertSub(int chunk_id
, SBPrefix host
,
926 const SBEntry
* entry
, int list_id
) {
927 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
929 SafeBrowsingStore
* store
= GetStore(list_id
);
932 STATS_COUNTER("SB.HostDelete", 1);
933 const int encoded_chunk_id
= EncodeChunkId(chunk_id
, list_id
);
934 const int count
= entry
->prefix_count();
936 DCHECK(entry
->IsSub());
938 // No prefixes, use host instead.
939 STATS_COUNTER("SB.PrefixSub", 1);
940 const int add_chunk_id
= EncodeChunkId(entry
->chunk_id(), list_id
);
941 store
->WriteSubPrefix(encoded_chunk_id
, add_chunk_id
, host
);
942 } else if (entry
->IsPrefix()) {
944 for (int i
= 0; i
< count
; i
++) {
945 const SBPrefix prefix
= entry
->PrefixAt(i
);
946 const int add_chunk_id
=
947 EncodeChunkId(entry
->ChunkIdAtPrefix(i
), list_id
);
949 STATS_COUNTER("SB.PrefixSub", 1);
950 store
->WriteSubPrefix(encoded_chunk_id
, add_chunk_id
, prefix
);
953 // Prefixes and hashes.
954 for (int i
= 0; i
< count
; ++i
) {
955 const SBFullHash full_hash
= entry
->FullHashAt(i
);
956 const int add_chunk_id
=
957 EncodeChunkId(entry
->ChunkIdAtPrefix(i
), list_id
);
959 STATS_COUNTER("SB.PrefixSub", 1);
960 store
->WriteSubPrefix(encoded_chunk_id
, add_chunk_id
, full_hash
.prefix
);
962 STATS_COUNTER("SB.PrefixSubFull", 1);
963 store
->WriteSubHash(encoded_chunk_id
, add_chunk_id
, full_hash
);
968 // Helper to iterate over all the entries in the hosts in |chunks| and
969 // add them to the store.
970 void SafeBrowsingDatabaseNew::InsertSubChunks(
971 safe_browsing_util::ListType list_id
,
972 const SBChunkList
& chunks
) {
973 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
975 SafeBrowsingStore
* store
= GetStore(list_id
);
978 for (SBChunkList::const_iterator citer
= chunks
.begin();
979 citer
!= chunks
.end(); ++citer
) {
980 const int chunk_id
= citer
->chunk_number
;
982 // The server can give us a chunk that we already have because
983 // it's part of a range. Don't add it again.
984 const int encoded_chunk_id
= EncodeChunkId(chunk_id
, list_id
);
985 if (store
->CheckSubChunk(encoded_chunk_id
))
988 store
->SetSubChunk(encoded_chunk_id
);
989 for (std::deque
<SBChunkHost
>::const_iterator hiter
= citer
->hosts
.begin();
990 hiter
!= citer
->hosts
.end(); ++hiter
) {
991 InsertSub(chunk_id
, hiter
->host
, hiter
->entry
, list_id
);
996 void SafeBrowsingDatabaseNew::InsertChunks(const std::string
& list_name
,
997 const SBChunkList
& chunks
) {
998 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1000 if (corruption_detected_
|| chunks
.empty())
1003 const base::TimeTicks before
= base::TimeTicks::Now();
1005 const safe_browsing_util::ListType list_id
=
1006 safe_browsing_util::GetListId(list_name
);
1007 DVLOG(2) << list_name
<< ": " << list_id
;
1009 SafeBrowsingStore
* store
= GetStore(list_id
);
1012 change_detected_
= true;
1014 store
->BeginChunk();
1015 if (chunks
.front().is_add
) {
1016 InsertAddChunks(list_id
, chunks
);
1018 InsertSubChunks(list_id
, chunks
);
1020 store
->FinishChunk();
1022 UMA_HISTOGRAM_TIMES("SB2.ChunkInsert", base::TimeTicks::Now() - before
);
1025 void SafeBrowsingDatabaseNew::DeleteChunks(
1026 const std::vector
<SBChunkDelete
>& chunk_deletes
) {
1027 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1029 if (corruption_detected_
|| chunk_deletes
.empty())
1032 const std::string
& list_name
= chunk_deletes
.front().list_name
;
1033 const safe_browsing_util::ListType list_id
=
1034 safe_browsing_util::GetListId(list_name
);
1036 SafeBrowsingStore
* store
= GetStore(list_id
);
1039 change_detected_
= true;
1041 for (size_t i
= 0; i
< chunk_deletes
.size(); ++i
) {
1042 std::vector
<int> chunk_numbers
;
1043 RangesToChunks(chunk_deletes
[i
].chunk_del
, &chunk_numbers
);
1044 for (size_t j
= 0; j
< chunk_numbers
.size(); ++j
) {
1045 const int encoded_chunk_id
= EncodeChunkId(chunk_numbers
[j
], list_id
);
1046 if (chunk_deletes
[i
].is_sub_del
)
1047 store
->DeleteSubChunk(encoded_chunk_id
);
1049 store
->DeleteAddChunk(encoded_chunk_id
);
1054 void SafeBrowsingDatabaseNew::CacheHashResults(
1055 const std::vector
<SBPrefix
>& prefixes
,
1056 const std::vector
<SBFullHashResult
>& full_hits
) {
1057 // This is called on the I/O thread, lock against updates.
1058 base::AutoLock
locked(lookup_lock_
);
1060 if (full_hits
.empty()) {
1061 prefix_miss_cache_
.insert(prefixes
.begin(), prefixes
.end());
1065 // TODO(shess): SBFullHashResult and SBAddFullHash are very similar.
1066 // Refactor to make them identical.
1067 const base::Time now
= base::Time::Now();
1068 const size_t orig_size
= pending_browse_hashes_
.size();
1069 for (std::vector
<SBFullHashResult
>::const_iterator iter
= full_hits
.begin();
1070 iter
!= full_hits
.end(); ++iter
) {
1071 const int list_id
= safe_browsing_util::GetListId(iter
->list_name
);
1072 if (list_id
== safe_browsing_util::MALWARE
||
1073 list_id
== safe_browsing_util::PHISH
) {
1074 int encoded_chunk_id
= EncodeChunkId(iter
->add_chunk_id
, list_id
);
1075 SBAddFullHash
add_full_hash(encoded_chunk_id
, now
, iter
->hash
);
1076 pending_browse_hashes_
.push_back(add_full_hash
);
1080 // Sort new entries then merge with the previously-sorted entries.
1081 std::vector
<SBAddFullHash
>::iterator
1082 orig_end
= pending_browse_hashes_
.begin() + orig_size
;
1083 std::sort(orig_end
, pending_browse_hashes_
.end(), SBAddFullHashPrefixLess
);
1084 std::inplace_merge(pending_browse_hashes_
.begin(),
1085 orig_end
, pending_browse_hashes_
.end(),
1086 SBAddFullHashPrefixLess
);
1089 bool SafeBrowsingDatabaseNew::UpdateStarted(
1090 std::vector
<SBListChunkRanges
>* lists
) {
1091 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1094 // If |BeginUpdate()| fails, reset the database.
1095 if (!browse_store_
->BeginUpdate()) {
1096 RecordFailure(FAILURE_BROWSE_DATABASE_UPDATE_BEGIN
);
1097 HandleCorruptDatabase();
1101 if (download_store_
.get() && !download_store_
->BeginUpdate()) {
1102 RecordFailure(FAILURE_DOWNLOAD_DATABASE_UPDATE_BEGIN
);
1103 HandleCorruptDatabase();
1107 if (csd_whitelist_store_
.get() && !csd_whitelist_store_
->BeginUpdate()) {
1108 RecordFailure(FAILURE_WHITELIST_DATABASE_UPDATE_BEGIN
);
1109 HandleCorruptDatabase();
1113 if (download_whitelist_store_
.get() &&
1114 !download_whitelist_store_
->BeginUpdate()) {
1115 RecordFailure(FAILURE_WHITELIST_DATABASE_UPDATE_BEGIN
);
1116 HandleCorruptDatabase();
1120 if (extension_blacklist_store_
&&
1121 !extension_blacklist_store_
->BeginUpdate()) {
1122 RecordFailure(FAILURE_EXTENSION_BLACKLIST_UPDATE_BEGIN
);
1123 HandleCorruptDatabase();
1127 if (side_effect_free_whitelist_store_
&&
1128 !side_effect_free_whitelist_store_
->BeginUpdate()) {
1129 RecordFailure(FAILURE_SIDE_EFFECT_FREE_WHITELIST_UPDATE_BEGIN
);
1130 HandleCorruptDatabase();
1134 if (ip_blacklist_store_
&& !ip_blacklist_store_
->BeginUpdate()) {
1135 RecordFailure(FAILURE_IP_BLACKLIST_UPDATE_BEGIN
);
1136 HandleCorruptDatabase();
1140 UpdateChunkRangesForLists(browse_store_
.get(),
1141 safe_browsing_util::kMalwareList
,
1142 safe_browsing_util::kPhishingList
,
1145 // NOTE(shess): |download_store_| used to contain kBinHashList, which has been
1146 // deprecated. Code to delete the list from the store shows ~15k hits/day as
1147 // of Feb 2014, so it has been removed. Everything _should_ be resilient to
1148 // extra data of that sort.
1149 UpdateChunkRangesForList(download_store_
.get(),
1150 safe_browsing_util::kBinUrlList
, lists
);
1152 UpdateChunkRangesForList(csd_whitelist_store_
.get(),
1153 safe_browsing_util::kCsdWhiteList
, lists
);
1155 UpdateChunkRangesForList(download_whitelist_store_
.get(),
1156 safe_browsing_util::kDownloadWhiteList
, lists
);
1158 UpdateChunkRangesForList(extension_blacklist_store_
.get(),
1159 safe_browsing_util::kExtensionBlacklist
, lists
);
1161 UpdateChunkRangesForList(side_effect_free_whitelist_store_
.get(),
1162 safe_browsing_util::kSideEffectFreeWhitelist
, lists
);
1164 UpdateChunkRangesForList(ip_blacklist_store_
.get(),
1165 safe_browsing_util::kIPBlacklist
, lists
);
1167 corruption_detected_
= false;
1168 change_detected_
= false;
1172 void SafeBrowsingDatabaseNew::UpdateFinished(bool update_succeeded
) {
1173 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1175 // The update may have failed due to corrupt storage (for instance,
1176 // an excessive number of invalid add_chunks and sub_chunks).
1177 // Double-check that the databases are valid.
1178 // TODO(shess): Providing a checksum for the add_chunk and sub_chunk
1179 // sections would allow throwing a corruption error in
1181 if (!update_succeeded
) {
1182 if (!browse_store_
->CheckValidity())
1183 DLOG(ERROR
) << "Safe-browsing browse database corrupt.";
1185 if (download_store_
.get() && !download_store_
->CheckValidity())
1186 DLOG(ERROR
) << "Safe-browsing download database corrupt.";
1188 if (csd_whitelist_store_
.get() && !csd_whitelist_store_
->CheckValidity())
1189 DLOG(ERROR
) << "Safe-browsing csd whitelist database corrupt.";
1191 if (download_whitelist_store_
.get() &&
1192 !download_whitelist_store_
->CheckValidity()) {
1193 DLOG(ERROR
) << "Safe-browsing download whitelist database corrupt.";
1196 if (extension_blacklist_store_
&&
1197 !extension_blacklist_store_
->CheckValidity()) {
1198 DLOG(ERROR
) << "Safe-browsing extension blacklist database corrupt.";
1201 if (side_effect_free_whitelist_store_
&&
1202 !side_effect_free_whitelist_store_
->CheckValidity()) {
1203 DLOG(ERROR
) << "Safe-browsing side-effect free whitelist database "
1207 if (ip_blacklist_store_
&& !ip_blacklist_store_
->CheckValidity()) {
1208 DLOG(ERROR
) << "Safe-browsing IP blacklist database corrupt.";
1212 if (corruption_detected_
)
1215 // Unroll the transaction if there was a protocol error or if the
1216 // transaction was empty. This will leave the prefix set, the
1217 // pending hashes, and the prefix miss cache in place.
1218 if (!update_succeeded
|| !change_detected_
) {
1219 // Track empty updates to answer questions at http://crbug.com/72216 .
1220 if (update_succeeded
&& !change_detected_
)
1221 UMA_HISTOGRAM_COUNTS("SB2.DatabaseUpdateKilobytes", 0);
1222 browse_store_
->CancelUpdate();
1223 if (download_store_
.get())
1224 download_store_
->CancelUpdate();
1225 if (csd_whitelist_store_
.get())
1226 csd_whitelist_store_
->CancelUpdate();
1227 if (download_whitelist_store_
.get())
1228 download_whitelist_store_
->CancelUpdate();
1229 if (extension_blacklist_store_
)
1230 extension_blacklist_store_
->CancelUpdate();
1231 if (side_effect_free_whitelist_store_
)
1232 side_effect_free_whitelist_store_
->CancelUpdate();
1233 if (ip_blacklist_store_
)
1234 ip_blacklist_store_
->CancelUpdate();
1238 if (download_store_
) {
1239 int64 size_bytes
= UpdateHashPrefixStore(
1241 download_store_
.get(),
1242 FAILURE_DOWNLOAD_DATABASE_UPDATE_FINISH
);
1243 UMA_HISTOGRAM_COUNTS("SB2.DownloadDatabaseKilobytes",
1244 static_cast<int>(size_bytes
/ 1024));
1247 UpdateBrowseStore();
1248 UpdateWhitelistStore(csd_whitelist_filename_
,
1249 csd_whitelist_store_
.get(),
1251 UpdateWhitelistStore(download_whitelist_filename_
,
1252 download_whitelist_store_
.get(),
1253 &download_whitelist_
);
1255 if (extension_blacklist_store_
) {
1256 int64 size_bytes
= UpdateHashPrefixStore(
1257 extension_blacklist_filename_
,
1258 extension_blacklist_store_
.get(),
1259 FAILURE_EXTENSION_BLACKLIST_UPDATE_FINISH
);
1260 UMA_HISTOGRAM_COUNTS("SB2.ExtensionBlacklistKilobytes",
1261 static_cast<int>(size_bytes
/ 1024));
1264 if (side_effect_free_whitelist_store_
)
1265 UpdateSideEffectFreeWhitelistStore();
1267 if (ip_blacklist_store_
)
1268 UpdateIpBlacklistStore();
1271 void SafeBrowsingDatabaseNew::UpdateWhitelistStore(
1272 const base::FilePath
& store_filename
,
1273 SafeBrowsingStore
* store
,
1274 SBWhitelist
* whitelist
) {
1278 // For the whitelists, we don't cache and save full hashes since all
1279 // hashes are already full.
1280 std::vector
<SBAddFullHash
> empty_add_hashes
;
1282 // Note: prefixes will not be empty. The current data store implementation
1283 // stores all full-length hashes as both full and prefix hashes.
1284 SBAddPrefixes prefixes
;
1285 std::vector
<SBAddFullHash
> full_hashes
;
1286 if (!store
->FinishUpdate(empty_add_hashes
, &prefixes
, &full_hashes
)) {
1287 RecordFailure(FAILURE_WHITELIST_DATABASE_UPDATE_FINISH
);
1288 WhitelistEverything(whitelist
);
1292 #if defined(OS_MACOSX)
1293 base::mac::SetFileBackupExclusion(store_filename
);
1296 LoadWhitelist(full_hashes
, whitelist
);
1299 int64
SafeBrowsingDatabaseNew::UpdateHashPrefixStore(
1300 const base::FilePath
& store_filename
,
1301 SafeBrowsingStore
* store
,
1302 FailureType failure_type
) {
1303 // We don't cache and save full hashes.
1304 std::vector
<SBAddFullHash
> empty_add_hashes
;
1306 // These results are not used after this call. Simply ignore the
1307 // returned value after FinishUpdate(...).
1308 SBAddPrefixes add_prefixes_result
;
1309 std::vector
<SBAddFullHash
> add_full_hashes_result
;
1311 if (!store
->FinishUpdate(empty_add_hashes
,
1312 &add_prefixes_result
,
1313 &add_full_hashes_result
)) {
1314 RecordFailure(failure_type
);
1317 #if defined(OS_MACOSX)
1318 base::mac::SetFileBackupExclusion(store_filename
);
1321 return GetFileSizeOrZero(store_filename
);
1324 void SafeBrowsingDatabaseNew::UpdateBrowseStore() {
1325 // Copy out the pending add hashes. Copy rather than swapping in
1326 // case |ContainsBrowseURL()| is called before the new filter is complete.
1327 std::vector
<SBAddFullHash
> pending_add_hashes
;
1329 base::AutoLock
locked(lookup_lock_
);
1330 pending_add_hashes
.insert(pending_add_hashes
.end(),
1331 pending_browse_hashes_
.begin(),
1332 pending_browse_hashes_
.end());
1335 // Measure the amount of IO during the filter build.
1336 base::IoCounters io_before
, io_after
;
1337 base::ProcessHandle handle
= base::Process::Current().handle();
1338 scoped_ptr
<base::ProcessMetrics
> metric(
1339 #if !defined(OS_MACOSX)
1340 base::ProcessMetrics::CreateProcessMetrics(handle
)
1342 // Getting stats only for the current process is enough, so NULL is fine.
1343 base::ProcessMetrics::CreateProcessMetrics(handle
, NULL
)
1347 // IoCounters are currently not supported on Mac, and may not be
1348 // available for Linux, so we check the result and only show IO
1349 // stats if they are available.
1350 const bool got_counters
= metric
->GetIOCounters(&io_before
);
1352 const base::TimeTicks before
= base::TimeTicks::Now();
1354 SBAddPrefixes add_prefixes
;
1355 std::vector
<SBAddFullHash
> add_full_hashes
;
1356 if (!browse_store_
->FinishUpdate(pending_add_hashes
,
1357 &add_prefixes
, &add_full_hashes
)) {
1358 RecordFailure(FAILURE_BROWSE_DATABASE_UPDATE_FINISH
);
1362 // TODO(shess): If |add_prefixes| were sorted by the prefix, it
1363 // could be passed directly to |PrefixSet()|, removing the need for
1364 // |prefixes|. For now, |prefixes| is useful while debugging
1366 std::vector
<SBPrefix
> prefixes
;
1367 prefixes
.reserve(add_prefixes
.size());
1368 for (SBAddPrefixes::const_iterator iter
= add_prefixes
.begin();
1369 iter
!= add_prefixes
.end(); ++iter
) {
1370 prefixes
.push_back(iter
->prefix
);
1373 std::sort(prefixes
.begin(), prefixes
.end());
1374 scoped_ptr
<safe_browsing::PrefixSet
>
1375 prefix_set(new safe_browsing::PrefixSet(prefixes
));
1377 // This needs to be in sorted order by prefix for efficient access.
1378 std::sort(add_full_hashes
.begin(), add_full_hashes
.end(),
1379 SBAddFullHashPrefixLess
);
1381 // Swap in the newly built filter and cache.
1383 base::AutoLock
locked(lookup_lock_
);
1384 full_browse_hashes_
.swap(add_full_hashes
);
1386 // TODO(shess): If |CacheHashResults()| is posted between the
1387 // earlier lock and this clear, those pending hashes will be lost.
1388 // It could be fixed by only removing hashes which were collected
1389 // at the earlier point. I believe that is fail-safe as-is (the
1390 // hash will be fetched again).
1391 pending_browse_hashes_
.clear();
1392 prefix_miss_cache_
.clear();
1393 browse_prefix_set_
.swap(prefix_set
);
1396 DVLOG(1) << "SafeBrowsingDatabaseImpl built prefix set in "
1397 << (base::TimeTicks::Now() - before
).InMilliseconds()
1398 << " ms total. prefix count: " << add_prefixes
.size();
1399 UMA_HISTOGRAM_LONG_TIMES("SB2.BuildFilter", base::TimeTicks::Now() - before
);
1401 // Persist the prefix set to disk. Since only this thread changes
1402 // |browse_prefix_set_|, there is no need to lock.
1405 // Gather statistics.
1406 if (got_counters
&& metric
->GetIOCounters(&io_after
)) {
1407 UMA_HISTOGRAM_COUNTS("SB2.BuildReadKilobytes",
1408 static_cast<int>(io_after
.ReadTransferCount
-
1409 io_before
.ReadTransferCount
) / 1024);
1410 UMA_HISTOGRAM_COUNTS("SB2.BuildWriteKilobytes",
1411 static_cast<int>(io_after
.WriteTransferCount
-
1412 io_before
.WriteTransferCount
) / 1024);
1413 UMA_HISTOGRAM_COUNTS("SB2.BuildReadOperations",
1414 static_cast<int>(io_after
.ReadOperationCount
-
1415 io_before
.ReadOperationCount
));
1416 UMA_HISTOGRAM_COUNTS("SB2.BuildWriteOperations",
1417 static_cast<int>(io_after
.WriteOperationCount
-
1418 io_before
.WriteOperationCount
));
1421 int64 file_size
= GetFileSizeOrZero(browse_prefix_set_filename_
);
1422 UMA_HISTOGRAM_COUNTS("SB2.PrefixSetKilobytes",
1423 static_cast<int>(file_size
/ 1024));
1424 file_size
= GetFileSizeOrZero(browse_filename_
);
1425 UMA_HISTOGRAM_COUNTS("SB2.BrowseDatabaseKilobytes",
1426 static_cast<int>(file_size
/ 1024));
1428 #if defined(OS_MACOSX)
1429 base::mac::SetFileBackupExclusion(browse_filename_
);
1433 void SafeBrowsingDatabaseNew::UpdateSideEffectFreeWhitelistStore() {
1434 std::vector
<SBAddFullHash
> empty_add_hashes
;
1435 SBAddPrefixes add_prefixes
;
1436 std::vector
<SBAddFullHash
> add_full_hashes_result
;
1438 if (!side_effect_free_whitelist_store_
->FinishUpdate(
1441 &add_full_hashes_result
)) {
1442 RecordFailure(FAILURE_SIDE_EFFECT_FREE_WHITELIST_UPDATE_FINISH
);
1446 // TODO(shess): If |add_prefixes| were sorted by the prefix, it
1447 // could be passed directly to |PrefixSet()|, removing the need for
1448 // |prefixes|. For now, |prefixes| is useful while debugging
1450 std::vector
<SBPrefix
> prefixes
;
1451 prefixes
.reserve(add_prefixes
.size());
1452 for (SBAddPrefixes::const_iterator iter
= add_prefixes
.begin();
1453 iter
!= add_prefixes
.end(); ++iter
) {
1454 prefixes
.push_back(iter
->prefix
);
1457 std::sort(prefixes
.begin(), prefixes
.end());
1458 scoped_ptr
<safe_browsing::PrefixSet
>
1459 prefix_set(new safe_browsing::PrefixSet(prefixes
));
1461 // Swap in the newly built prefix set.
1463 base::AutoLock
locked(lookup_lock_
);
1464 side_effect_free_whitelist_prefix_set_
.swap(prefix_set
);
1467 const base::TimeTicks before
= base::TimeTicks::Now();
1468 const bool write_ok
= side_effect_free_whitelist_prefix_set_
->WriteFile(
1469 side_effect_free_whitelist_prefix_set_filename_
);
1470 DVLOG(1) << "SafeBrowsingDatabaseNew wrote side-effect free whitelist prefix "
1471 << "set in " << (base::TimeTicks::Now() - before
).InMilliseconds()
1473 UMA_HISTOGRAM_TIMES("SB2.SideEffectFreePrefixSetWrite",
1474 base::TimeTicks::Now() - before
);
1477 RecordFailure(FAILURE_SIDE_EFFECT_FREE_WHITELIST_PREFIX_SET_WRITE
);
1479 // Gather statistics.
1480 int64 file_size
= GetFileSizeOrZero(
1481 side_effect_free_whitelist_prefix_set_filename_
);
1482 UMA_HISTOGRAM_COUNTS("SB2.SideEffectFreeWhitelistPrefixSetKilobytes",
1483 static_cast<int>(file_size
/ 1024));
1484 file_size
= GetFileSizeOrZero(side_effect_free_whitelist_filename_
);
1485 UMA_HISTOGRAM_COUNTS("SB2.SideEffectFreeWhitelistDatabaseKilobytes",
1486 static_cast<int>(file_size
/ 1024));
1488 #if defined(OS_MACOSX)
1489 base::mac::SetFileBackupExclusion(side_effect_free_whitelist_filename_
);
1490 base::mac::SetFileBackupExclusion(
1491 side_effect_free_whitelist_prefix_set_filename_
);
1495 void SafeBrowsingDatabaseNew::UpdateIpBlacklistStore() {
1496 // For the IP blacklist, we don't cache and save full hashes since all
1497 // hashes are already full.
1498 std::vector
<SBAddFullHash
> empty_add_hashes
;
1500 // Note: prefixes will not be empty. The current data store implementation
1501 // stores all full-length hashes as both full and prefix hashes.
1502 SBAddPrefixes prefixes
;
1503 std::vector
<SBAddFullHash
> full_hashes
;
1504 if (!ip_blacklist_store_
->FinishUpdate(empty_add_hashes
,
1505 &prefixes
, &full_hashes
)) {
1506 RecordFailure(FAILURE_IP_BLACKLIST_UPDATE_FINISH
);
1507 LoadIpBlacklist(std::vector
<SBAddFullHash
>()); // Clear the list.
1511 #if defined(OS_MACOSX)
1512 base::mac::SetFileBackupExclusion(ip_blacklist_filename_
);
1515 LoadIpBlacklist(full_hashes
);
1518 void SafeBrowsingDatabaseNew::HandleCorruptDatabase() {
1519 // Reset the database after the current task has unwound (but only
1520 // reset once within the scope of a given task).
1521 if (!reset_factory_
.HasWeakPtrs()) {
1522 RecordFailure(FAILURE_DATABASE_CORRUPT
);
1523 base::MessageLoop::current()->PostTask(FROM_HERE
,
1524 base::Bind(&SafeBrowsingDatabaseNew::OnHandleCorruptDatabase
,
1525 reset_factory_
.GetWeakPtr()));
1529 void SafeBrowsingDatabaseNew::OnHandleCorruptDatabase() {
1530 RecordFailure(FAILURE_DATABASE_CORRUPT_HANDLER
);
1531 corruption_detected_
= true; // Stop updating the database.
1533 DLOG(FATAL
) << "SafeBrowsing database was corrupt and reset";
1536 // TODO(shess): I'm not clear why this code doesn't have any
1537 // real error-handling.
1538 void SafeBrowsingDatabaseNew::LoadPrefixSet() {
1539 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1540 DCHECK(!browse_prefix_set_filename_
.empty());
1542 // If there is no database, the filter cannot be used.
1543 base::File::Info db_info
;
1544 if (!base::GetFileInfo(browse_filename_
, &db_info
) || db_info
.size
== 0)
1547 // Cleanup any stale bloom filter (no longer used).
1548 // TODO(shess): Track failure to delete?
1549 base::FilePath bloom_filter_filename
=
1550 BloomFilterForFilename(browse_filename_
);
1551 base::DeleteFile(bloom_filter_filename
, false);
1553 const base::TimeTicks before
= base::TimeTicks::Now();
1554 browse_prefix_set_
.reset(safe_browsing::PrefixSet::LoadFile(
1555 browse_prefix_set_filename_
));
1556 DVLOG(1) << "SafeBrowsingDatabaseNew read prefix set in "
1557 << (base::TimeTicks::Now() - before
).InMilliseconds() << " ms";
1558 UMA_HISTOGRAM_TIMES("SB2.PrefixSetLoad", base::TimeTicks::Now() - before
);
1560 if (!browse_prefix_set_
.get())
1561 RecordFailure(FAILURE_BROWSE_PREFIX_SET_READ
);
1564 bool SafeBrowsingDatabaseNew::Delete() {
1565 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1567 const bool r1
= browse_store_
->Delete();
1569 RecordFailure(FAILURE_DATABASE_STORE_DELETE
);
1571 const bool r2
= download_store_
.get() ? download_store_
->Delete() : true;
1573 RecordFailure(FAILURE_DATABASE_STORE_DELETE
);
1575 const bool r3
= csd_whitelist_store_
.get() ?
1576 csd_whitelist_store_
->Delete() : true;
1578 RecordFailure(FAILURE_DATABASE_STORE_DELETE
);
1580 const bool r4
= download_whitelist_store_
.get() ?
1581 download_whitelist_store_
->Delete() : true;
1583 RecordFailure(FAILURE_DATABASE_STORE_DELETE
);
1585 base::FilePath bloom_filter_filename
=
1586 BloomFilterForFilename(browse_filename_
);
1587 const bool r5
= base::DeleteFile(bloom_filter_filename
, false);
1589 RecordFailure(FAILURE_DATABASE_FILTER_DELETE
);
1591 const bool r6
= base::DeleteFile(browse_prefix_set_filename_
, false);
1593 RecordFailure(FAILURE_BROWSE_PREFIX_SET_DELETE
);
1595 const bool r7
= base::DeleteFile(extension_blacklist_filename_
, false);
1597 RecordFailure(FAILURE_EXTENSION_BLACKLIST_DELETE
);
1599 const bool r8
= base::DeleteFile(side_effect_free_whitelist_filename_
,
1602 RecordFailure(FAILURE_SIDE_EFFECT_FREE_WHITELIST_DELETE
);
1604 const bool r9
= base::DeleteFile(
1605 side_effect_free_whitelist_prefix_set_filename_
,
1608 RecordFailure(FAILURE_SIDE_EFFECT_FREE_WHITELIST_PREFIX_SET_DELETE
);
1610 const bool r10
= base::DeleteFile(ip_blacklist_filename_
, false);
1612 RecordFailure(FAILURE_IP_BLACKLIST_DELETE
);
1614 return r1
&& r2
&& r3
&& r4
&& r5
&& r6
&& r7
&& r8
&& r9
&& r10
;
1617 void SafeBrowsingDatabaseNew::WritePrefixSet() {
1618 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1620 if (!browse_prefix_set_
.get())
1623 const base::TimeTicks before
= base::TimeTicks::Now();
1624 const bool write_ok
= browse_prefix_set_
->WriteFile(
1625 browse_prefix_set_filename_
);
1626 DVLOG(1) << "SafeBrowsingDatabaseNew wrote prefix set in "
1627 << (base::TimeTicks::Now() - before
).InMilliseconds() << " ms";
1628 UMA_HISTOGRAM_TIMES("SB2.PrefixSetWrite", base::TimeTicks::Now() - before
);
1631 RecordFailure(FAILURE_BROWSE_PREFIX_SET_WRITE
);
1633 #if defined(OS_MACOSX)
1634 base::mac::SetFileBackupExclusion(browse_prefix_set_filename_
);
1638 void SafeBrowsingDatabaseNew::WhitelistEverything(SBWhitelist
* whitelist
) {
1639 base::AutoLock
locked(lookup_lock_
);
1640 whitelist
->second
= true;
1641 whitelist
->first
.clear();
1644 void SafeBrowsingDatabaseNew::LoadWhitelist(
1645 const std::vector
<SBAddFullHash
>& full_hashes
,
1646 SBWhitelist
* whitelist
) {
1647 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1648 if (full_hashes
.size() > kMaxWhitelistSize
) {
1649 WhitelistEverything(whitelist
);
1653 std::vector
<SBFullHash
> new_whitelist
;
1654 new_whitelist
.reserve(full_hashes
.size());
1655 for (std::vector
<SBAddFullHash
>::const_iterator it
= full_hashes
.begin();
1656 it
!= full_hashes
.end(); ++it
) {
1657 new_whitelist
.push_back(it
->full_hash
);
1659 std::sort(new_whitelist
.begin(), new_whitelist
.end());
1661 SBFullHash kill_switch
;
1662 crypto::SHA256HashString(kWhitelistKillSwitchUrl
, &kill_switch
,
1663 sizeof(kill_switch
));
1664 if (std::binary_search(new_whitelist
.begin(), new_whitelist
.end(),
1666 // The kill switch is whitelisted hence we whitelist all URLs.
1667 WhitelistEverything(whitelist
);
1669 base::AutoLock
locked(lookup_lock_
);
1670 whitelist
->second
= false;
1671 whitelist
->first
.swap(new_whitelist
);
1675 void SafeBrowsingDatabaseNew::LoadIpBlacklist(
1676 const std::vector
<SBAddFullHash
>& full_hashes
) {
1677 DCHECK_EQ(creation_loop_
, base::MessageLoop::current());
1678 IPBlacklist new_blacklist
;
1679 DVLOG(2) << "Writing IP blacklist of size: " << full_hashes
.size();
1680 for (std::vector
<SBAddFullHash
>::const_iterator it
= full_hashes
.begin();
1681 it
!= full_hashes
.end();
1683 const char* full_hash
= it
->full_hash
.full_hash
;
1684 DCHECK_EQ(crypto::kSHA256Length
, arraysize(it
->full_hash
.full_hash
));
1685 // The format of the IP blacklist is:
1686 // SHA-1(IPv6 prefix) + uint8(prefix size) + 11 unused bytes.
1687 std::string
hashed_ip_prefix(full_hash
, base::kSHA1Length
);
1688 size_t prefix_size
= static_cast<uint8
>(full_hash
[base::kSHA1Length
]);
1689 if (prefix_size
> kMaxIpPrefixSize
|| prefix_size
< kMinIpPrefixSize
) {
1690 DVLOG(2) << "Invalid IP prefix size in IP blacklist: " << prefix_size
;
1691 RecordFailure(FAILURE_IP_BLACKLIST_UPDATE_INVALID
);
1692 new_blacklist
.clear(); // Load empty blacklist.
1696 // We precompute the mask for the given subnet size to speed up lookups.
1697 // Basically we need to create a 16B long string which has the highest
1698 // |size| bits sets to one.
1699 std::string
mask(net::kIPv6AddressSize
, '\0');
1700 mask
.replace(0, prefix_size
/ 8, prefix_size
/ 8, '\xFF');
1701 if ((prefix_size
% 8) != 0) {
1702 mask
[prefix_size
/ 8] = 0xFF << (8 - (prefix_size
% 8));
1704 DVLOG(2) << "Inserting malicious IP: "
1705 << " raw:" << base::HexEncode(full_hash
, crypto::kSHA256Length
)
1706 << " mask:" << base::HexEncode(mask
.data(), mask
.size())
1707 << " prefix_size:" << prefix_size
1708 << " hashed_ip:" << base::HexEncode(hashed_ip_prefix
.data(),
1709 hashed_ip_prefix
.size());
1710 new_blacklist
[mask
].insert(hashed_ip_prefix
);
1713 base::AutoLock
locked(lookup_lock_
);
1714 ip_blacklist_
.swap(new_blacklist
);
1717 bool SafeBrowsingDatabaseNew::IsMalwareIPMatchKillSwitchOn() {
1718 SBFullHash malware_kill_switch
;
1719 crypto::SHA256HashString(kMalwareIPKillSwitchUrl
, &malware_kill_switch
,
1720 sizeof(malware_kill_switch
));
1721 std::vector
<SBFullHash
> full_hashes
;
1722 full_hashes
.push_back(malware_kill_switch
);
1723 return ContainsWhitelistedHashes(csd_whitelist_
, full_hashes
);