Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(191)

Side by Side Diff: chrome/browser/safe_browsing/protocol_manager.cc

Issue 10069031: Replace SafeBrowsing MAC with downloads over SSL. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 8 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/safe_browsing/protocol_manager.h" 5 #include "chrome/browser/safe_browsing/protocol_manager.h"
6 6
7 #ifndef NDEBUG 7 #ifndef NDEBUG
8 #include "base/base64.h" 8 #include "base/base64.h"
9 #endif 9 #endif
10 #include "base/bind.h"
11 #include "base/environment.h" 10 #include "base/environment.h"
12 #include "base/logging.h" 11 #include "base/logging.h"
13 #include "base/metrics/histogram.h" 12 #include "base/metrics/histogram.h"
14 #include "base/rand_util.h" 13 #include "base/rand_util.h"
15 #include "base/stl_util.h" 14 #include "base/stl_util.h"
16 #include "base/string_util.h" 15 #include "base/string_util.h"
17 #include "base/stringprintf.h" 16 #include "base/stringprintf.h"
18 #include "base/timer.h" 17 #include "base/timer.h"
19 #include "chrome/browser/safe_browsing/protocol_parser.h" 18 #include "chrome/browser/safe_browsing/protocol_parser.h"
20 #include "chrome/browser/safe_browsing/safe_browsing_service.h" 19 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
(...skipping 20 matching lines...) Expand all
41 static const int kSbMaxBackOff = 8; 40 static const int kSbMaxBackOff = 8;
42 41
43 // The default SBProtocolManagerFactory. 42 // The default SBProtocolManagerFactory.
44 class SBProtocolManagerFactoryImpl : public SBProtocolManagerFactory { 43 class SBProtocolManagerFactoryImpl : public SBProtocolManagerFactory {
45 public: 44 public:
46 SBProtocolManagerFactoryImpl() { } 45 SBProtocolManagerFactoryImpl() { }
47 virtual ~SBProtocolManagerFactoryImpl() { } 46 virtual ~SBProtocolManagerFactoryImpl() { }
48 virtual SafeBrowsingProtocolManager* CreateProtocolManager( 47 virtual SafeBrowsingProtocolManager* CreateProtocolManager(
49 SafeBrowsingService* sb_service, 48 SafeBrowsingService* sb_service,
50 const std::string& client_name, 49 const std::string& client_name,
51 const std::string& client_key,
52 const std::string& wrapped_key,
53 net::URLRequestContextGetter* request_context_getter, 50 net::URLRequestContextGetter* request_context_getter,
54 const std::string& info_url_prefix, 51 const std::string& url_prefix,
55 const std::string& mackey_url_prefix,
56 bool disable_auto_update) { 52 bool disable_auto_update) {
57 return new SafeBrowsingProtocolManager( 53 return new SafeBrowsingProtocolManager(
58 sb_service, client_name, client_key, wrapped_key, 54 sb_service, client_name, request_context_getter,
59 request_context_getter, info_url_prefix, mackey_url_prefix, 55 url_prefix, disable_auto_update);
60 disable_auto_update);
61 } 56 }
62 private: 57 private:
63 DISALLOW_COPY_AND_ASSIGN(SBProtocolManagerFactoryImpl); 58 DISALLOW_COPY_AND_ASSIGN(SBProtocolManagerFactoryImpl);
64 }; 59 };
65 60
66 // SafeBrowsingProtocolManager implementation ---------------------------------- 61 // SafeBrowsingProtocolManager implementation ----------------------------------
67 62
68 // static 63 // static
69 SBProtocolManagerFactory* SafeBrowsingProtocolManager::factory_ = NULL; 64 SBProtocolManagerFactory* SafeBrowsingProtocolManager::factory_ = NULL;
70 65
71 // static 66 // static
72 SafeBrowsingProtocolManager* SafeBrowsingProtocolManager::Create( 67 SafeBrowsingProtocolManager* SafeBrowsingProtocolManager::Create(
73 SafeBrowsingService* sb_service, 68 SafeBrowsingService* sb_service,
74 const std::string& client_name, 69 const std::string& client_name,
75 const std::string& client_key,
76 const std::string& wrapped_key,
77 net::URLRequestContextGetter* request_context_getter, 70 net::URLRequestContextGetter* request_context_getter,
78 const std::string& info_url_prefix, 71 const std::string& url_prefix,
79 const std::string& mackey_url_prefix,
80 bool disable_auto_update) { 72 bool disable_auto_update) {
81 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); 73 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
82 if (!factory_) 74 if (!factory_)
83 factory_ = new SBProtocolManagerFactoryImpl(); 75 factory_ = new SBProtocolManagerFactoryImpl();
84 return factory_->CreateProtocolManager(sb_service, client_name, client_key, 76 return factory_->CreateProtocolManager(sb_service, client_name,
85 wrapped_key, request_context_getter, 77 request_context_getter,
86 info_url_prefix, mackey_url_prefix, 78 url_prefix, disable_auto_update);
87 disable_auto_update);
88 } 79 }
89 80
90 SafeBrowsingProtocolManager::SafeBrowsingProtocolManager( 81 SafeBrowsingProtocolManager::SafeBrowsingProtocolManager(
91 SafeBrowsingService* sb_service, 82 SafeBrowsingService* sb_service,
92 const std::string& client_name, 83 const std::string& client_name,
93 const std::string& client_key,
94 const std::string& wrapped_key,
95 net::URLRequestContextGetter* request_context_getter, 84 net::URLRequestContextGetter* request_context_getter,
96 const std::string& http_url_prefix, 85 const std::string& url_prefix,
97 const std::string& https_url_prefix,
98 bool disable_auto_update) 86 bool disable_auto_update)
99 : sb_service_(sb_service), 87 : sb_service_(sb_service),
100 request_type_(NO_REQUEST), 88 request_type_(NO_REQUEST),
101 update_error_count_(0), 89 update_error_count_(0),
102 gethash_error_count_(0), 90 gethash_error_count_(0),
103 update_back_off_mult_(1), 91 update_back_off_mult_(1),
104 gethash_back_off_mult_(1), 92 gethash_back_off_mult_(1),
105 next_update_sec_(-1), 93 next_update_sec_(-1),
106 update_state_(FIRST_REQUEST), 94 update_state_(FIRST_REQUEST),
107 initial_request_(true),
108 chunk_pending_to_write_(false), 95 chunk_pending_to_write_(false),
109 client_key_(client_key),
110 wrapped_key_(wrapped_key),
111 update_size_(0), 96 update_size_(0),
112 client_name_(client_name), 97 client_name_(client_name),
113 request_context_getter_(request_context_getter), 98 request_context_getter_(request_context_getter),
114 http_url_prefix_(http_url_prefix), 99 url_prefix_(url_prefix),
115 https_url_prefix_(https_url_prefix),
116 disable_auto_update_(disable_auto_update) { 100 disable_auto_update_(disable_auto_update) {
117 DCHECK(!http_url_prefix_.empty() && !https_url_prefix_.empty()); 101 DCHECK(!url_prefix_.empty());
118 102
119 // Set the backoff multiplier fuzz to a random value between 0 and 1. 103 // Set the backoff multiplier fuzz to a random value between 0 and 1.
120 back_off_fuzz_ = static_cast<float>(base::RandDouble()); 104 back_off_fuzz_ = static_cast<float>(base::RandDouble());
121 // The first update must happen between 1-5 minutes of start up. 105 // The first update must happen between 1-5 minutes of start up.
122 next_update_sec_ = base::RandInt(60, kSbTimerStartIntervalSec); 106 next_update_sec_ = base::RandInt(60, kSbTimerStartIntervalSec);
123 107
124 chrome::VersionInfo version_info; 108 chrome::VersionInfo version_info;
125 if (!version_info.is_valid() || version_info.Version().empty()) 109 if (!version_info.is_valid() || version_info.Version().empty())
126 version_ = "0.1"; 110 version_ = "0.1";
127 else 111 else
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
161 SafeBrowsingService::SafeBrowsingCheck* check, 145 SafeBrowsingService::SafeBrowsingCheck* check,
162 const std::vector<SBPrefix>& prefixes) { 146 const std::vector<SBPrefix>& prefixes) {
163 // If we are in GetHash backoff, we need to check if we're past the next 147 // If we are in GetHash backoff, we need to check if we're past the next
164 // allowed time. If we are, we can proceed with the request. If not, we are 148 // allowed time. If we are, we can proceed with the request. If not, we are
165 // required to return empty results (i.e. treat the page as safe). 149 // required to return empty results (i.e. treat the page as safe).
166 if (gethash_error_count_ && Time::Now() <= next_gethash_time_) { 150 if (gethash_error_count_ && Time::Now() <= next_gethash_time_) {
167 std::vector<SBFullHashResult> full_hashes; 151 std::vector<SBFullHashResult> full_hashes;
168 sb_service_->HandleGetHashResults(check, full_hashes, false); 152 sb_service_->HandleGetHashResults(check, full_hashes, false);
169 return; 153 return;
170 } 154 }
171 bool use_mac = !client_key_.empty(); 155 GURL gethash_url = GetHashUrl();
172 GURL gethash_url = GetHashUrl(use_mac);
173 content::URLFetcher* fetcher = content::URLFetcher::Create( 156 content::URLFetcher* fetcher = content::URLFetcher::Create(
174 gethash_url, content::URLFetcher::POST, this); 157 gethash_url, content::URLFetcher::POST, this);
175 hash_requests_[fetcher] = check; 158 hash_requests_[fetcher] = check;
176 159
177 std::string get_hash; 160 std::string get_hash;
178 SafeBrowsingProtocolParser parser; 161 SafeBrowsingProtocolParser parser;
179 parser.FormatGetHash(prefixes, &get_hash); 162 parser.FormatGetHash(prefixes, &get_hash);
180 163
181 fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE); 164 fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE);
182 fetcher->SetRequestContext(request_context_getter_); 165 fetcher->SetRequestContext(request_context_getter_);
183 fetcher->SetUploadData("text/plain", get_hash); 166 fetcher->SetUploadData("text/plain", get_hash);
184 fetcher->Start(); 167 fetcher->Start();
185 } 168 }
186 169
187 void SafeBrowsingProtocolManager::GetNextUpdate() { 170 void SafeBrowsingProtocolManager::GetNextUpdate() {
188 if (initial_request_) {
189 if (client_key_.empty() || wrapped_key_.empty()) {
190 IssueKeyRequest();
191 return;
192 } else {
193 initial_request_ = false;
194 }
195 }
196
197 if (!request_.get()) 171 if (!request_.get())
198 IssueUpdateRequest(); 172 IssueUpdateRequest();
199 } 173 }
200 174
201 // content::URLFetcherDelegate implementation ---------------------------------- 175 // content::URLFetcherDelegate implementation ----------------------------------
202 176
203 // All SafeBrowsing request responses are handled here. 177 // All SafeBrowsing request responses are handled here.
204 // TODO(paulg): Clarify with the SafeBrowsing team whether a failed parse of a 178 // TODO(paulg): Clarify with the SafeBrowsing team whether a failed parse of a
205 // chunk should retry the download and parse of that chunk (and 179 // chunk should retry the download and parse of that chunk (and
206 // what back off / how many times to try), and if that effects the 180 // what back off / how many times to try), and if that effects the
(...skipping 28 matching lines...) Expand all
235 if (source->GetResponseCode() == 200 || source->GetResponseCode() == 204) { 209 if (source->GetResponseCode() == 200 || source->GetResponseCode() == 204) {
236 // For tracking our GetHash false positive (204) rate, compared to real 210 // For tracking our GetHash false positive (204) rate, compared to real
237 // (200) responses. 211 // (200) responses.
238 if (source->GetResponseCode() == 200) 212 if (source->GetResponseCode() == 200)
239 RecordGetHashResult(check->is_download, GET_HASH_STATUS_200); 213 RecordGetHashResult(check->is_download, GET_HASH_STATUS_200);
240 else 214 else
241 RecordGetHashResult(check->is_download, GET_HASH_STATUS_204); 215 RecordGetHashResult(check->is_download, GET_HASH_STATUS_204);
242 can_cache = true; 216 can_cache = true;
243 gethash_error_count_ = 0; 217 gethash_error_count_ = 0;
244 gethash_back_off_mult_ = 1; 218 gethash_back_off_mult_ = 1;
245 bool re_key = false;
246 SafeBrowsingProtocolParser parser; 219 SafeBrowsingProtocolParser parser;
247 std::string data; 220 std::string data;
248 source->GetResponseAsString(&data); 221 source->GetResponseAsString(&data);
249 parsed_ok = parser.ParseGetHash( 222 parsed_ok = parser.ParseGetHash(
250 data.data(), 223 data.data(),
251 static_cast<int>(data.length()), 224 static_cast<int>(data.length()),
252 client_key_,
253 &re_key,
254 &full_hashes); 225 &full_hashes);
255 if (!parsed_ok) { 226 if (!parsed_ok) {
256 // If we fail to parse it, we must still inform the SafeBrowsingService 227 // If we fail to parse it, we must still inform the SafeBrowsingService
257 // so that it doesn't hold up the user's request indefinitely. Not sure 228 // so that it doesn't hold up the user's request indefinitely. Not sure
258 // what to do at that point though! 229 // what to do at that point though!
259 full_hashes.clear(); 230 full_hashes.clear();
260 } else {
261 if (re_key)
262 HandleReKey();
263 } 231 }
264 } else { 232 } else {
265 HandleGetHashError(Time::Now()); 233 HandleGetHashError(Time::Now());
266 if (source->GetStatus().status() == net::URLRequestStatus::FAILED) { 234 if (source->GetStatus().status() == net::URLRequestStatus::FAILED) {
267 VLOG(1) << "SafeBrowsing GetHash request for: " << source->GetURL() 235 VLOG(1) << "SafeBrowsing GetHash request for: " << source->GetURL()
268 << " failed with error: " << source->GetStatus().error(); 236 << " failed with error: " << source->GetStatus().error();
269 } else { 237 } else {
270 VLOG(1) << "SafeBrowsing GetHash request for: " << source->GetURL() 238 VLOG(1) << "SafeBrowsing GetHash request for: " << source->GetURL()
271 << " failed with error: " << source->GetResponseCode(); 239 << " failed with error: " << source->GetResponseCode();
272 } 240 }
273 } 241 }
274 242
275 // Call back the SafeBrowsingService with full_hashes, even if there was a 243 // Call back the SafeBrowsingService with full_hashes, even if there was a
276 // parse error or an error response code (in which case full_hashes will be 244 // parse error or an error response code (in which case full_hashes will be
277 // empty). We can't block the user regardless of the error status. 245 // empty). We can't block the user regardless of the error status.
278 sb_service_->HandleGetHashResults(check, full_hashes, can_cache); 246 sb_service_->HandleGetHashResults(check, full_hashes, can_cache);
279 247
280 hash_requests_.erase(it); 248 hash_requests_.erase(it);
281 } else { 249 } else {
282 // Update, chunk or key response. 250 // Update or chunk response.
283 fetcher.reset(request_.release()); 251 fetcher.reset(request_.release());
284 252
285 if (request_type_ == UPDATE_REQUEST) { 253 if (request_type_ == UPDATE_REQUEST) {
286 if (!fetcher.get()) { 254 if (!fetcher.get()) {
287 // We've timed out waiting for an update response, so we've cancelled 255 // We've timed out waiting for an update response, so we've cancelled
288 // the update request and scheduled a new one. Ignore this response. 256 // the update request and scheduled a new one. Ignore this response.
289 return; 257 return;
290 } 258 }
291 259
292 // Cancel the update response timeout now that we have the response. 260 // Cancel the update response timeout now that we have the response.
(...skipping 12 matching lines...) Expand all
305 must_back_off = true; 273 must_back_off = true;
306 chunk_request_urls_.clear(); 274 chunk_request_urls_.clear();
307 UpdateFinished(false); 275 UpdateFinished(false);
308 } 276 }
309 277
310 switch (request_type_) { 278 switch (request_type_) {
311 case CHUNK_REQUEST: 279 case CHUNK_REQUEST:
312 if (parsed_ok) 280 if (parsed_ok)
313 chunk_request_urls_.pop_front(); 281 chunk_request_urls_.pop_front();
314 break; 282 break;
315 case GETKEY_REQUEST:
316 if (initial_request_) {
317 // This is the first request we've made this session. Now that we
318 // have the keys, do the regular update request.
319 initial_request_ = false;
320 GetNextUpdate();
321 return;
322 }
323 break;
324 case UPDATE_REQUEST: 283 case UPDATE_REQUEST:
325 if (chunk_request_urls_.empty() && parsed_ok) { 284 if (chunk_request_urls_.empty() && parsed_ok) {
326 // We are up to date since the servers gave us nothing new, so we 285 // We are up to date since the servers gave us nothing new, so we
327 // are done with this update cycle. 286 // are done with this update cycle.
328 UpdateFinished(true); 287 UpdateFinished(true);
329 } 288 }
330 break; 289 break;
331 default: 290 default:
332 NOTREACHED(); 291 NOTREACHED();
333 break; 292 break;
(...skipping 26 matching lines...) Expand all
360 } 319 }
361 320
362 bool SafeBrowsingProtocolManager::HandleServiceResponse(const GURL& url, 321 bool SafeBrowsingProtocolManager::HandleServiceResponse(const GURL& url,
363 const char* data, 322 const char* data,
364 int length) { 323 int length) {
365 SafeBrowsingProtocolParser parser; 324 SafeBrowsingProtocolParser parser;
366 325
367 switch (request_type_) { 326 switch (request_type_) {
368 case UPDATE_REQUEST: { 327 case UPDATE_REQUEST: {
369 int next_update_sec = -1; 328 int next_update_sec = -1;
370 bool re_key = false;
371 bool reset = false; 329 bool reset = false;
372 scoped_ptr<std::vector<SBChunkDelete> > chunk_deletes( 330 scoped_ptr<std::vector<SBChunkDelete> > chunk_deletes(
373 new std::vector<SBChunkDelete>); 331 new std::vector<SBChunkDelete>);
374 std::vector<ChunkUrl> chunk_urls; 332 std::vector<ChunkUrl> chunk_urls;
375 if (!parser.ParseUpdate(data, length, client_key_, 333 if (!parser.ParseUpdate(data, length, &next_update_sec,
376 &next_update_sec, &re_key,
377 &reset, chunk_deletes.get(), &chunk_urls)) { 334 &reset, chunk_deletes.get(), &chunk_urls)) {
378 return false; 335 return false;
379 } 336 }
380 337
381 last_update_ = Time::Now(); 338 last_update_ = Time::Now();
382 339
383 if (update_state_ == FIRST_REQUEST) 340 if (update_state_ == FIRST_REQUEST)
384 update_state_ = SECOND_REQUEST; 341 update_state_ = SECOND_REQUEST;
385 else if (update_state_ == SECOND_REQUEST) 342 else if (update_state_ == SECOND_REQUEST)
386 update_state_ = NORMAL_REQUEST; 343 update_state_ = NORMAL_REQUEST;
387 344
388 // New time for the next update. 345 // New time for the next update.
389 if (next_update_sec > 0) { 346 if (next_update_sec > 0) {
390 next_update_sec_ = next_update_sec; 347 next_update_sec_ = next_update_sec;
391 } else if (update_state_ == SECOND_REQUEST) { 348 } else if (update_state_ == SECOND_REQUEST) {
392 next_update_sec_ = base::RandInt(15 * 60, 45 * 60); 349 next_update_sec_ = base::RandInt(15 * 60, 45 * 60);
393 } 350 }
394 351
395 // We need to request a new set of keys for MAC.
396 if (re_key)
397 HandleReKey();
398
399 // New chunks to download. 352 // New chunks to download.
400 if (!chunk_urls.empty()) { 353 if (!chunk_urls.empty()) {
401 UMA_HISTOGRAM_COUNTS("SB2.UpdateUrls", chunk_urls.size()); 354 UMA_HISTOGRAM_COUNTS("SB2.UpdateUrls", chunk_urls.size());
402 for (size_t i = 0; i < chunk_urls.size(); ++i) 355 for (size_t i = 0; i < chunk_urls.size(); ++i)
403 chunk_request_urls_.push_back(chunk_urls[i]); 356 chunk_request_urls_.push_back(chunk_urls[i]);
404 } 357 }
405 358
406 // Handle the case were the SafeBrowsing service tells us to dump our 359 // Handle the case were the SafeBrowsing service tells us to dump our
407 // database. 360 // database.
408 if (reset) { 361 if (reset) {
409 sb_service_->ResetDatabase(); 362 sb_service_->ResetDatabase();
410 return true; 363 return true;
411 } 364 }
412 365
413 // Chunks to delete from our storage. Pass ownership of 366 // Chunks to delete from our storage. Pass ownership of
414 // |chunk_deletes|. 367 // |chunk_deletes|.
415 if (!chunk_deletes->empty()) 368 if (!chunk_deletes->empty())
416 sb_service_->HandleChunkDelete(chunk_deletes.release()); 369 sb_service_->HandleChunkDelete(chunk_deletes.release());
417 370
418 break; 371 break;
419 } 372 }
420 case CHUNK_REQUEST: { 373 case CHUNK_REQUEST: {
421 UMA_HISTOGRAM_TIMES("SB2.ChunkRequest", 374 UMA_HISTOGRAM_TIMES("SB2.ChunkRequest",
422 base::Time::Now() - chunk_request_start_); 375 base::Time::Now() - chunk_request_start_);
423 376
424 const ChunkUrl chunk_url = chunk_request_urls_.front(); 377 const ChunkUrl chunk_url = chunk_request_urls_.front();
425 bool re_key = false;
426 scoped_ptr<SBChunkList> chunks(new SBChunkList); 378 scoped_ptr<SBChunkList> chunks(new SBChunkList);
427 UMA_HISTOGRAM_COUNTS("SB2.ChunkSize", length); 379 UMA_HISTOGRAM_COUNTS("SB2.ChunkSize", length);
428 update_size_ += length; 380 update_size_ += length;
429 if (!parser.ParseChunk(chunk_url.list_name, data, length, 381 if (!parser.ParseChunk(chunk_url.list_name, data, length,
430 client_key_, chunk_url.mac, 382 chunks.get())) {
431 &re_key, chunks.get())) {
432 #ifndef NDEBUG 383 #ifndef NDEBUG
433 std::string data_str; 384 std::string data_str;
434 data_str.assign(data, length); 385 data_str.assign(data, length);
435 std::string encoded_chunk; 386 std::string encoded_chunk;
436 base::Base64Encode(data_str, &encoded_chunk); 387 base::Base64Encode(data_str, &encoded_chunk);
437 VLOG(1) << "ParseChunk error for chunk: " << chunk_url.url 388 VLOG(1) << "ParseChunk error for chunk: " << chunk_url.url
438 << ", client_key: " << client_key_
439 << ", wrapped_key: " << wrapped_key_
440 << ", mac: " << chunk_url.mac
441 << ", Base64Encode(data): " << encoded_chunk 389 << ", Base64Encode(data): " << encoded_chunk
442 << ", length: " << length; 390 << ", length: " << length;
443 #endif 391 #endif
444 return false; 392 return false;
445 } 393 }
446 394
447 if (re_key)
448 HandleReKey();
449
450 // Chunks to add to storage. Pass ownership of |chunks|. 395 // Chunks to add to storage. Pass ownership of |chunks|.
451 if (!chunks->empty()) { 396 if (!chunks->empty()) {
452 chunk_pending_to_write_ = true; 397 chunk_pending_to_write_ = true;
453 sb_service_->HandleChunk(chunk_url.list_name, chunks.release()); 398 sb_service_->HandleChunk(chunk_url.list_name, chunks.release());
454 } 399 }
455 400
456 break; 401 break;
457 } 402 }
458 case GETKEY_REQUEST: {
459 std::string client_key, wrapped_key;
460 if (!parser.ParseNewKey(data, length, &client_key, &wrapped_key))
461 return false;
462
463 client_key_ = client_key;
464 wrapped_key_ = wrapped_key;
465 BrowserThread::PostTask(
466 BrowserThread::UI, FROM_HERE,
467 base::Bind(&SafeBrowsingService::OnNewMacKeys,
468 sb_service_, client_key_, wrapped_key_));
469 break;
470 }
471 403
472 default: 404 default:
473 return false; 405 return false;
474 } 406 }
475 407
476 return true; 408 return true;
477 } 409 }
478 410
479 void SafeBrowsingProtocolManager::Initialize() { 411 void SafeBrowsingProtocolManager::Initialize() {
480 // Don't want to hit the safe browsing servers on build/chrome bots. 412 // Don't want to hit the safe browsing servers on build/chrome bots.
(...skipping 83 matching lines...) Expand 10 before | Expand all | Expand 10 after
564 GURL chunk_url = NextChunkUrl(next_chunk.url); 496 GURL chunk_url = NextChunkUrl(next_chunk.url);
565 request_type_ = CHUNK_REQUEST; 497 request_type_ = CHUNK_REQUEST;
566 request_.reset(content::URLFetcher::Create( 498 request_.reset(content::URLFetcher::Create(
567 chunk_url, content::URLFetcher::GET, this)); 499 chunk_url, content::URLFetcher::GET, this));
568 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE); 500 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
569 request_->SetRequestContext(request_context_getter_); 501 request_->SetRequestContext(request_context_getter_);
570 chunk_request_start_ = base::Time::Now(); 502 chunk_request_start_ = base::Time::Now();
571 request_->Start(); 503 request_->Start();
572 } 504 }
573 505
574 void SafeBrowsingProtocolManager::IssueKeyRequest() {
575 GURL key_url = MacKeyUrl();
576 request_type_ = GETKEY_REQUEST;
577 request_.reset(content::URLFetcher::Create(
578 key_url, content::URLFetcher::GET, this));
579 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
580 request_->SetRequestContext(request_context_getter_);
581 request_->Start();
582 }
583
584 void SafeBrowsingProtocolManager::OnGetChunksComplete( 506 void SafeBrowsingProtocolManager::OnGetChunksComplete(
585 const std::vector<SBListChunkRanges>& lists, bool database_error) { 507 const std::vector<SBListChunkRanges>& lists, bool database_error) {
586 DCHECK_EQ(request_type_, UPDATE_REQUEST); 508 DCHECK_EQ(request_type_, UPDATE_REQUEST);
587 if (database_error) { 509 if (database_error) {
588 UpdateFinished(false); 510 UpdateFinished(false);
589 ScheduleNextUpdate(false); 511 ScheduleNextUpdate(false);
590 return; 512 return;
591 } 513 }
592 514
593 const bool use_mac = !client_key_.empty();
594
595 // Format our stored chunks: 515 // Format our stored chunks:
596 std::string list_data; 516 std::string list_data;
597 bool found_malware = false; 517 bool found_malware = false;
598 bool found_phishing = false; 518 bool found_phishing = false;
599 for (size_t i = 0; i < lists.size(); ++i) { 519 for (size_t i = 0; i < lists.size(); ++i) {
600 list_data.append(FormatList(lists[i], use_mac)); 520 list_data.append(FormatList(lists[i]));
601 if (lists[i].name == safe_browsing_util::kPhishingList) 521 if (lists[i].name == safe_browsing_util::kPhishingList)
602 found_phishing = true; 522 found_phishing = true;
603 523
604 if (lists[i].name == safe_browsing_util::kMalwareList) 524 if (lists[i].name == safe_browsing_util::kMalwareList)
605 found_malware = true; 525 found_malware = true;
606 } 526 }
607 527
608 // If we have an empty database, let the server know we want data for these 528 // If we have an empty database, let the server know we want data for these
609 // lists. 529 // lists.
610 if (!found_phishing) 530 if (!found_phishing)
611 list_data.append(FormatList( 531 list_data.append(FormatList(
612 SBListChunkRanges(safe_browsing_util::kPhishingList), use_mac)); 532 SBListChunkRanges(safe_browsing_util::kPhishingList)));
613 533
614 if (!found_malware) 534 if (!found_malware)
615 list_data.append(FormatList( 535 list_data.append(FormatList(
616 SBListChunkRanges(safe_browsing_util::kMalwareList), use_mac)); 536 SBListChunkRanges(safe_browsing_util::kMalwareList)));
617 537
618 GURL update_url = UpdateUrl(use_mac); 538 GURL update_url = UpdateUrl();
619 request_.reset(content::URLFetcher::Create( 539 request_.reset(content::URLFetcher::Create(
620 update_url, content::URLFetcher::POST, this)); 540 update_url, content::URLFetcher::POST, this));
621 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE); 541 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
622 request_->SetRequestContext(request_context_getter_); 542 request_->SetRequestContext(request_context_getter_);
623 request_->SetUploadData("text/plain", list_data); 543 request_->SetUploadData("text/plain", list_data);
624 request_->Start(); 544 request_->Start();
625 545
626 // Begin the update request timeout. 546 // Begin the update request timeout.
627 update_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(kSbMaxUpdateWaitSec), 547 update_timer_.Start(FROM_HERE, TimeDelta::FromSeconds(kSbMaxUpdateWaitSec),
628 this, 548 this,
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
683 fetcher->SetUploadData("application/octet-stream", report); 603 fetcher->SetUploadData("application/octet-stream", report);
684 // Don't try too hard to send reports on failures. 604 // Don't try too hard to send reports on failures.
685 fetcher->SetAutomaticallyRetryOn5xx(false); 605 fetcher->SetAutomaticallyRetryOn5xx(false);
686 fetcher->Start(); 606 fetcher->Start();
687 safebrowsing_reports_.insert(fetcher); 607 safebrowsing_reports_.insert(fetcher);
688 } 608 }
689 609
690 610
691 // static 611 // static
692 std::string SafeBrowsingProtocolManager::FormatList( 612 std::string SafeBrowsingProtocolManager::FormatList(
693 const SBListChunkRanges& list, bool use_mac) { 613 const SBListChunkRanges& list) {
694 std::string formatted_results; 614 std::string formatted_results;
695 formatted_results.append(list.name); 615 formatted_results.append(list.name);
696 formatted_results.append(";"); 616 formatted_results.append(";");
697 if (!list.adds.empty()) { 617 if (!list.adds.empty()) {
698 formatted_results.append("a:" + list.adds); 618 formatted_results.append("a:" + list.adds);
699 if (!list.subs.empty() || use_mac) 619 if (!list.subs.empty())
700 formatted_results.append(":"); 620 formatted_results.append(":");
701 } 621 }
702 if (!list.subs.empty()) { 622 if (!list.subs.empty()) {
703 formatted_results.append("s:" + list.subs); 623 formatted_results.append("s:" + list.subs);
704 if (use_mac)
705 formatted_results.append(":");
706 } 624 }
707 if (use_mac)
708 formatted_results.append("mac");
709 formatted_results.append("\n"); 625 formatted_results.append("\n");
710 626
711 return formatted_results; 627 return formatted_results;
712 } 628 }
713 629
714 void SafeBrowsingProtocolManager::HandleReKey() {
715 client_key_.clear();
716 wrapped_key_.clear();
717 IssueKeyRequest();
718 }
719
720 void SafeBrowsingProtocolManager::HandleGetHashError(const Time& now) { 630 void SafeBrowsingProtocolManager::HandleGetHashError(const Time& now) {
721 int next = GetNextBackOffTime(&gethash_error_count_, &gethash_back_off_mult_); 631 int next = GetNextBackOffTime(&gethash_error_count_, &gethash_back_off_mult_);
722 next_gethash_time_ = now + TimeDelta::FromSeconds(next); 632 next_gethash_time_ = now + TimeDelta::FromSeconds(next);
723 } 633 }
724 634
725 void SafeBrowsingProtocolManager::UpdateFinished(bool success) { 635 void SafeBrowsingProtocolManager::UpdateFinished(bool success) {
726 UMA_HISTOGRAM_COUNTS("SB2.UpdateSize", update_size_); 636 UMA_HISTOGRAM_COUNTS("SB2.UpdateSize", update_size_);
727 update_size_ = 0; 637 update_size_ = 0;
728 sb_service_->UpdateFinished(success); 638 sb_service_->UpdateFinished(success);
729 } 639 }
730 640
731 std::string SafeBrowsingProtocolManager::ComposeUrl( 641 std::string SafeBrowsingProtocolManager::ComposeUrl(
732 const std::string& prefix, const std::string& method, 642 const std::string& prefix, const std::string& method,
733 const std::string& client_name, const std::string& version, 643 const std::string& client_name, const std::string& version,
734 const std::string& additional_query) { 644 const std::string& additional_query) {
735 DCHECK(!prefix.empty() && !method.empty() && 645 DCHECK(!prefix.empty() && !method.empty() &&
736 !client_name.empty() && !version.empty()); 646 !client_name.empty() && !version.empty());
737 std::string url = base::StringPrintf("%s/%s?client=%s&appver=%s&pver=2.2", 647 std::string url = base::StringPrintf("%s/%s?client=%s&appver=%s&pver=2.2",
738 prefix.c_str(), method.c_str(), 648 prefix.c_str(), method.c_str(),
739 client_name.c_str(), version.c_str()); 649 client_name.c_str(), version.c_str());
740 if (!additional_query.empty()) { 650 if (!additional_query.empty()) {
741 DCHECK(url.find("?") != std::string::npos); 651 DCHECK(url.find("?") != std::string::npos);
742 url.append("&"); 652 url.append("&");
743 url.append(additional_query); 653 url.append(additional_query);
744 } 654 }
745 return url; 655 return url;
746 } 656 }
747 657
748 GURL SafeBrowsingProtocolManager::UpdateUrl(bool use_mac) const { 658 GURL SafeBrowsingProtocolManager::UpdateUrl() const {
749 std::string url = ComposeUrl(http_url_prefix_, "downloads", client_name_, 659 return GURL(ComposeUrl(url_prefix_, "downloads", client_name_, version_,
750 version_, additional_query_);
751 if (use_mac) {
752 url.append("&wrkey=");
753 url.append(wrapped_key_);
754 }
755 return GURL(url);
756 }
757
758 GURL SafeBrowsingProtocolManager::GetHashUrl(bool use_mac) const {
759 std::string url= ComposeUrl(http_url_prefix_, "gethash", client_name_,
760 version_, additional_query_);
761 if (use_mac) {
762 url.append("&wrkey=");
763 url.append(wrapped_key_);
764 }
765 return GURL(url);
766 }
767
768 GURL SafeBrowsingProtocolManager::MacKeyUrl() const {
769 return GURL(ComposeUrl(https_url_prefix_, "newkey", client_name_, version_,
770 additional_query_)); 660 additional_query_));
771 } 661 }
772 662
663 GURL SafeBrowsingProtocolManager::GetHashUrl() const {
664 return GURL(ComposeUrl(url_prefix_, "gethash", client_name_, version_,
665 additional_query_));
666 }
667
773 GURL SafeBrowsingProtocolManager::SafeBrowsingHitUrl( 668 GURL SafeBrowsingProtocolManager::SafeBrowsingHitUrl(
774 const GURL& malicious_url, const GURL& page_url, 669 const GURL& malicious_url, const GURL& page_url,
775 const GURL& referrer_url, bool is_subresource, 670 const GURL& referrer_url, bool is_subresource,
776 SafeBrowsingService::UrlCheckResult threat_type) const { 671 SafeBrowsingService::UrlCheckResult threat_type) const {
777 DCHECK(threat_type == SafeBrowsingService::URL_MALWARE || 672 DCHECK(threat_type == SafeBrowsingService::URL_MALWARE ||
778 threat_type == SafeBrowsingService::URL_PHISHING || 673 threat_type == SafeBrowsingService::URL_PHISHING ||
779 threat_type == SafeBrowsingService::BINARY_MALWARE_URL || 674 threat_type == SafeBrowsingService::BINARY_MALWARE_URL ||
780 threat_type == SafeBrowsingService::BINARY_MALWARE_HASH || 675 threat_type == SafeBrowsingService::BINARY_MALWARE_HASH ||
781 threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL); 676 threat_type == SafeBrowsingService::CLIENT_SIDE_PHISHING_URL);
782 // The malware and phishing hits go over HTTP. 677 std::string url = ComposeUrl(url_prefix_, "report", client_name_,
783 std::string url = ComposeUrl(http_url_prefix_, "report", client_name_,
784 version_, additional_query_); 678 version_, additional_query_);
785 std::string threat_list = "none"; 679 std::string threat_list = "none";
786 switch (threat_type) { 680 switch (threat_type) {
787 case SafeBrowsingService::URL_MALWARE: 681 case SafeBrowsingService::URL_MALWARE:
788 threat_list = "malblhit"; 682 threat_list = "malblhit";
789 break; 683 break;
790 case SafeBrowsingService::URL_PHISHING: 684 case SafeBrowsingService::URL_PHISHING:
791 threat_list = "phishblhit"; 685 threat_list = "phishblhit";
792 break; 686 break;
793 case SafeBrowsingService::BINARY_MALWARE_URL: 687 case SafeBrowsingService::BINARY_MALWARE_URL:
(...skipping 10 matching lines...) Expand all
804 } 698 }
805 return GURL(base::StringPrintf("%s&evts=%s&evtd=%s&evtr=%s&evhr=%s&evtb=%d", 699 return GURL(base::StringPrintf("%s&evts=%s&evtd=%s&evtr=%s&evhr=%s&evtb=%d",
806 url.c_str(), threat_list.c_str(), 700 url.c_str(), threat_list.c_str(),
807 net::EscapeQueryParamValue(malicious_url.spec(), true).c_str(), 701 net::EscapeQueryParamValue(malicious_url.spec(), true).c_str(),
808 net::EscapeQueryParamValue(page_url.spec(), true).c_str(), 702 net::EscapeQueryParamValue(page_url.spec(), true).c_str(),
809 net::EscapeQueryParamValue(referrer_url.spec(), true).c_str(), 703 net::EscapeQueryParamValue(referrer_url.spec(), true).c_str(),
810 is_subresource)); 704 is_subresource));
811 } 705 }
812 706
813 GURL SafeBrowsingProtocolManager::MalwareDetailsUrl() const { 707 GURL SafeBrowsingProtocolManager::MalwareDetailsUrl() const {
814 // The malware details go over HTTPS.
815 std::string url = base::StringPrintf( 708 std::string url = base::StringPrintf(
816 "%s/clientreport/malware?client=%s&appver=%s&pver=1.0", 709 "%s/clientreport/malware?client=%s&appver=%s&pver=1.0",
817 https_url_prefix_.c_str(), 710 url_prefix_.c_str(),
818 client_name_.c_str(), 711 client_name_.c_str(),
819 version_.c_str()); 712 version_.c_str());
820 return GURL(url); 713 return GURL(url);
821 } 714 }
822 715
823 GURL SafeBrowsingProtocolManager::NextChunkUrl(const std::string& url) const { 716 GURL SafeBrowsingProtocolManager::NextChunkUrl(const std::string& url) const {
824 std::string next_url; 717 std::string next_url;
825 if (!StartsWithASCII(url, "http://", false) && 718 if (!StartsWithASCII(url, "http://", false) &&
826 !StartsWithASCII(url, "https://", false)) { 719 !StartsWithASCII(url, "https://", false)) {
827 next_url.append("http://"); 720 // Use https if we updated via https, otherwise http (useful for testing).
721 if (StartsWithASCII(url_prefix_, "https://", false))
722 next_url.append("https://");
723 else
724 next_url.append("http://");
828 next_url.append(url); 725 next_url.append(url);
829 } else { 726 } else {
830 next_url = url; 727 next_url = url;
831 } 728 }
832 if (!additional_query_.empty()) { 729 if (!additional_query_.empty()) {
833 if (next_url.find("?") != std::string::npos) { 730 if (next_url.find("?") != std::string::npos) {
834 next_url.append("&"); 731 next_url.append("&");
835 } else { 732 } else {
836 next_url.append("?"); 733 next_url.append("?");
837 } 734 }
838 next_url.append(additional_query_); 735 next_url.append(additional_query_);
839 } 736 }
840 return GURL(next_url); 737 return GURL(next_url);
841 } 738 }
OLDNEW
« no previous file with comments | « chrome/browser/safe_browsing/protocol_manager.h ('k') | chrome/browser/safe_browsing/protocol_manager_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698