base::Time multiplicative operator overloading
[chromium-blink-merge.git] / chrome / browser / safe_browsing / database_manager.h
blobd23962098db0394da3ae06cf5dd4147d9da94569
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.
4 //
5 // The Safe Browsing service is responsible for downloading anti-phishing and
6 // anti-malware tables and checking urls against them.
8 #ifndef CHROME_BROWSER_SAFE_BROWSING_DATABASE_MANAGER_H_
9 #define CHROME_BROWSER_SAFE_BROWSING_DATABASE_MANAGER_H_
11 #include <deque>
12 #include <map>
13 #include <set>
14 #include <string>
15 #include <vector>
17 #include "base/callback.h"
18 #include "base/containers/hash_tables.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/synchronization/lock.h"
22 #include "base/time/time.h"
23 #include "chrome/browser/safe_browsing/protocol_manager.h"
24 #include "chrome/browser/safe_browsing/safe_browsing_util.h"
25 #include "url/gurl.h"
27 class SafeBrowsingService;
28 class SafeBrowsingDatabase;
30 namespace base {
31 class Thread;
34 namespace net {
35 class URLRequestContext;
36 class URLRequestContextGetter;
39 namespace safe_browsing {
40 class ClientSideDetectionService;
41 class DownloadProtectionService;
44 // Construction needs to happen on the main thread.
45 class SafeBrowsingDatabaseManager
46 : public base::RefCountedThreadSafe<SafeBrowsingDatabaseManager>,
47 public SafeBrowsingProtocolManagerDelegate {
48 public:
49 class Client;
51 // Bundle of SafeBrowsing state while performing a URL or hash prefix check.
52 struct SafeBrowsingCheck {
53 // |check_type| should correspond to the type of item that is being
54 // checked, either a URL or a binary hash/URL. We store this for two
55 // purposes: to know which of Client's methods to call when a result is
56 // known, and for logging purposes. It *isn't* used to predict the response
57 // list type, that is information that the server gives us.
58 SafeBrowsingCheck(const std::vector<GURL>& urls,
59 const std::vector<SBFullHash>& full_hashes,
60 Client* client,
61 safe_browsing_util::ListType check_type,
62 const std::vector<SBThreatType>& expected_threats);
63 ~SafeBrowsingCheck();
65 // Either |urls| or |full_hashes| is used to lookup database. |*_results|
66 // are parallel vectors containing the results. They are initialized to
67 // contain SB_THREAT_TYPE_SAFE.
68 std::vector<GURL> urls;
69 std::vector<SBThreatType> url_results;
70 std::vector<std::string> url_metadata;
71 std::vector<SBFullHash> full_hashes;
72 std::vector<SBThreatType> full_hash_results;
74 Client* client;
75 bool need_get_hash;
76 base::TimeTicks start; // When check was sent to SB service.
77 safe_browsing_util::ListType check_type; // See comment in constructor.
78 std::vector<SBThreatType> expected_threats;
79 std::vector<SBPrefix> prefix_hits;
80 std::vector<SBFullHashResult> cache_hits;
82 // Vends weak pointers for TimeoutCallback(). If the response is
83 // received before the timeout fires, factory is destructed and
84 // the timeout won't be fired.
85 // TODO(lzheng): We should consider to use this time out check
86 // for browsing too (instead of implementin in
87 // safe_browsing_resource_handler.cc).
88 scoped_ptr<base::WeakPtrFactory<
89 SafeBrowsingDatabaseManager> > timeout_factory_;
91 private:
92 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingCheck);
95 class Client {
96 public:
97 void OnSafeBrowsingResult(const SafeBrowsingCheck& check);
99 protected:
100 virtual ~Client() {}
102 // Called when the result of checking a browse URL is known.
103 virtual void OnCheckBrowseUrlResult(const GURL& url,
104 SBThreatType threat_type,
105 const std::string& metadata) {}
107 // Called when the result of checking a download URL is known.
108 virtual void OnCheckDownloadUrlResult(const std::vector<GURL>& url_chain,
109 SBThreatType threat_type) {}
111 // Called when the result of checking a set of extensions is known.
112 virtual void OnCheckExtensionsResult(
113 const std::set<std::string>& threats) {}
116 // Creates the safe browsing service. Need to initialize before using.
117 explicit SafeBrowsingDatabaseManager(
118 const scoped_refptr<SafeBrowsingService>& service);
120 // Returns true if the url's scheme can be checked.
121 bool CanCheckUrl(const GURL& url) const;
123 // Returns whether download protection is enabled.
124 bool download_protection_enabled() const {
125 return enable_download_protection_;
128 // Called on the IO thread to check if the given url is safe or not. If we
129 // can synchronously determine that the url is safe, CheckUrl returns true.
130 // Otherwise it returns false, and "client" is called asynchronously with the
131 // result when it is ready.
132 virtual bool CheckBrowseUrl(const GURL& url, Client* client);
134 // Check if the prefix for |url| is in safebrowsing download add lists.
135 // Result will be passed to callback in |client|.
136 virtual bool CheckDownloadUrl(const std::vector<GURL>& url_chain,
137 Client* client);
139 // Check which prefixes in |extension_ids| are in the safebrowsing blacklist.
140 // Returns true if not, false if further checks need to be made in which case
141 // the result will be passed to |client|.
142 virtual bool CheckExtensionIDs(const std::set<std::string>& extension_ids,
143 Client* client);
145 // Check if the given url is on the side-effect free whitelist.
146 // Can be called on any thread. Returns false if the check cannot be performed
147 // (e.g. because we are disabled or because of an invalid scheme in the URL).
148 // Otherwise, returns true if the URL is on the whitelist based on matching
149 // the hash prefix only (so there may be false positives).
150 virtual bool CheckSideEffectFreeWhitelistUrl(const GURL& url);
152 // Check if the |url| matches any of the full-length hashes from the client-
153 // side phishing detection whitelist. Returns true if there was a match and
154 // false otherwise. To make sure we are conservative we will return true if
155 // an error occurs. This method must be called on the IO thread.
156 virtual bool MatchCsdWhitelistUrl(const GURL& url);
158 // Check if the given IP address (either IPv4 or IPv6) matches the malware
159 // IP blacklist.
160 virtual bool MatchMalwareIP(const std::string& ip_address);
162 // Check if the |url| matches any of the full-length hashes from the download
163 // whitelist. Returns true if there was a match and false otherwise. To make
164 // sure we are conservative we will return true if an error occurs. This
165 // method must be called on the IO thread.
166 virtual bool MatchDownloadWhitelistUrl(const GURL& url);
168 // Check if |str| matches any of the full-length hashes from the download
169 // whitelist. Returns true if there was a match and false otherwise. To make
170 // sure we are conservative we will return true if an error occurs. This
171 // method must be called on the IO thread.
172 virtual bool MatchDownloadWhitelistString(const std::string& str);
174 // Check if the |url| matches any of the full-length hashes from the off-
175 // domain inclusion whitelist. Returns true if there was a match and false
176 // otherwise. To make sure we are conservative, we will return true if an
177 // error occurs. This method must be called on the IO thread.
178 virtual bool MatchInclusionWhitelistUrl(const GURL& url);
180 // Check if the CSD malware IP matching kill switch is turned on.
181 virtual bool IsMalwareKillSwitchOn();
183 // Check if the CSD whitelist kill switch is turned on.
184 virtual bool IsCsdWhitelistKillSwitchOn();
186 // Called on the IO thread to cancel a pending check if the result is no
187 // longer needed.
188 void CancelCheck(Client* client);
190 // Called on the IO thread when the SafeBrowsingProtocolManager has received
191 // the full hash results for prefix hits detected in the database.
192 void HandleGetHashResults(SafeBrowsingCheck* check,
193 const std::vector<SBFullHashResult>& full_hashes,
194 const base::TimeDelta& cache_lifetime);
196 // Called to initialize objects that are used on the io_thread. This may be
197 // called multiple times during the life of the DatabaseManager. Must be
198 // called on IO thread.
199 void StartOnIOThread();
201 // Called to stop or shutdown operations on the io_thread. This may be called
202 // multiple times during the life of the DatabaseManager. Must be called
203 // on IO thread. If shutdown is true, the manager is disabled permanently.
204 void StopOnIOThread(bool shutdown);
206 protected:
207 ~SafeBrowsingDatabaseManager() override;
209 // protected for tests.
210 void NotifyDatabaseUpdateFinished(bool update_succeeded);
212 private:
213 friend class base::RefCountedThreadSafe<SafeBrowsingDatabaseManager>;
214 friend class SafeBrowsingServerTest;
215 friend class SafeBrowsingServiceTest;
216 friend class SafeBrowsingServiceTestHelper;
217 friend class SafeBrowsingDatabaseManagerTest;
218 FRIEND_TEST_ALL_PREFIXES(SafeBrowsingDatabaseManagerTest,
219 GetUrlSeverestThreatType);
221 typedef std::set<SafeBrowsingCheck*> CurrentChecks;
222 typedef std::vector<SafeBrowsingCheck*> GetHashRequestors;
223 typedef base::hash_map<SBPrefix, GetHashRequestors> GetHashRequests;
225 // Clients that we've queued up for checking later once the database is ready.
226 struct QueuedCheck {
227 QueuedCheck(const safe_browsing_util::ListType check_type,
228 Client* client,
229 const GURL& url,
230 const std::vector<SBThreatType>& expected_threats,
231 const base::TimeTicks& start);
232 ~QueuedCheck();
233 safe_browsing_util::ListType check_type;
234 Client* client;
235 GURL url;
236 std::vector<SBThreatType> expected_threats;
237 base::TimeTicks start; // When check was queued.
240 // Return the threat type of the severest entry in |full_hashes| which matches
241 // |hash|, or SAFE if none match.
242 static SBThreatType GetHashSeverestThreatType(
243 const SBFullHash& hash,
244 const std::vector<SBFullHashResult>& full_hashes);
246 // Given a URL, compare all the possible host + path full hashes to the set of
247 // provided full hashes. Returns the threat type of the severest matching
248 // result from |full_hashes|, or SAFE if none match.
249 static SBThreatType GetUrlSeverestThreatType(
250 const GURL& url,
251 const std::vector<SBFullHashResult>& full_hashes,
252 size_t* index);
254 // Called to stop operations on the io_thread. This may be called multiple
255 // times during the life of the DatabaseManager. Should be called on IO
256 // thread.
257 void DoStopOnIOThread();
259 // Returns whether |database_| exists and is accessible.
260 bool DatabaseAvailable() const;
262 // Called on the IO thread. If the database does not exist, queues up a call
263 // on the db thread to create it. Returns whether the database is available.
265 // Note that this is only needed outside the db thread, since functions on the
266 // db thread can call GetDatabase() directly.
267 bool MakeDatabaseAvailable();
269 // Should only be called on db thread as SafeBrowsingDatabase is not
270 // threadsafe.
271 SafeBrowsingDatabase* GetDatabase();
273 // Called on the IO thread with the check result.
274 void OnCheckDone(SafeBrowsingCheck* info);
276 // Called on the database thread to retrieve chunks.
277 void GetAllChunksFromDatabase(GetChunksCallback callback);
279 // Called on the IO thread with the results of all chunks.
280 void OnGetAllChunksFromDatabase(const std::vector<SBListChunkRanges>& lists,
281 bool database_error,
282 GetChunksCallback callback);
284 // Called on the IO thread after the database reports that it added a chunk.
285 void OnAddChunksComplete(AddChunksCallback callback);
287 // Notification that the database is done loading its bloom filter. We may
288 // have had to queue checks until the database is ready, and if so, this
289 // checks them.
290 void DatabaseLoadComplete();
292 // Called on the database thread to add/remove chunks and host keys.
293 void AddDatabaseChunks(const std::string& list,
294 scoped_ptr<ScopedVector<SBChunkData> > chunks,
295 AddChunksCallback callback);
297 void DeleteDatabaseChunks(
298 scoped_ptr<std::vector<SBChunkDelete> > chunk_deletes);
300 void NotifyClientBlockingComplete(Client* client, bool proceed);
302 void DatabaseUpdateFinished(bool update_succeeded);
304 // Called on the db thread to close the database. See CloseDatabase().
305 void OnCloseDatabase();
307 // Runs on the db thread to reset the database. We assume that resetting the
308 // database is a synchronous operation.
309 void OnResetDatabase();
311 // Internal worker function for processing full hashes.
312 void OnHandleGetHashResults(SafeBrowsingCheck* check,
313 const std::vector<SBFullHashResult>& full_hashes);
315 // Run one check against |full_hashes|. Returns |true| if the check
316 // finds a match in |full_hashes|.
317 bool HandleOneCheck(SafeBrowsingCheck* check,
318 const std::vector<SBFullHashResult>& full_hashes);
320 // Invoked by CheckDownloadUrl. It checks the download URL on
321 // safe_browsing_thread_.
322 void CheckDownloadUrlOnSBThread(SafeBrowsingCheck* check);
324 // The callback function when a safebrowsing check is timed out. Client will
325 // be notified that the safebrowsing check is SAFE when this happens.
326 void TimeoutCallback(SafeBrowsingCheck* check);
328 // Calls the Client's callback on IO thread after CheckDownloadUrl finishes.
329 void CheckDownloadUrlDone(SafeBrowsingCheck* check);
331 // Checks all extension ID hashes on safe_browsing_thread_.
332 void CheckExtensionIDsOnSBThread(SafeBrowsingCheck* check);
334 // Helper function that calls safe browsing client and cleans up |checks_|.
335 void SafeBrowsingCheckDone(SafeBrowsingCheck* check);
337 // Helper function to set |check| with default values and start a safe
338 // browsing check with timeout of |timeout|. |task| will be called on
339 // success, otherwise TimeoutCallback will be called.
340 void StartSafeBrowsingCheck(SafeBrowsingCheck* check,
341 const base::Closure& task);
343 // SafeBrowsingProtocolManageDelegate override
344 void ResetDatabase() override;
345 void UpdateStarted() override;
346 void UpdateFinished(bool success) override;
347 void GetChunks(GetChunksCallback callback) override;
348 void AddChunks(const std::string& list,
349 scoped_ptr<ScopedVector<SBChunkData>> chunks,
350 AddChunksCallback callback) override;
351 void DeleteChunks(
352 scoped_ptr<std::vector<SBChunkDelete>> chunk_deletes) override;
354 scoped_refptr<SafeBrowsingService> sb_service_;
356 CurrentChecks checks_;
358 // Used for issuing only one GetHash request for a given prefix.
359 GetHashRequests gethash_requests_;
361 // The persistent database. We don't use a scoped_ptr because it
362 // needs to be destroyed on a different thread than this object.
363 SafeBrowsingDatabase* database_;
365 // Lock used to prevent possible data races due to compiler optimizations.
366 mutable base::Lock database_lock_;
368 // Whether the service is running. 'enabled_' is used by the
369 // SafeBrowsingDatabaseManager on the IO thread during normal operations.
370 bool enabled_;
372 // Indicate if download_protection is enabled by command switch
373 // so we allow this feature to be exersized.
374 bool enable_download_protection_;
376 // Indicate if client-side phishing detection whitelist should be enabled
377 // or not.
378 bool enable_csd_whitelist_;
380 // Indicate if the download whitelist should be enabled or not.
381 bool enable_download_whitelist_;
383 // Indicate if the extension blacklist should be enabled.
384 bool enable_extension_blacklist_;
386 // Indicate if the side effect free whitelist should be enabled.
387 bool enable_side_effect_free_whitelist_;
389 // Indicate if the csd malware IP blacklist should be enabled.
390 bool enable_ip_blacklist_;
392 // Indicate if the unwanted software blacklist should be enabled.
393 bool enable_unwanted_software_blacklist_;
395 // The SafeBrowsing thread that runs database operations.
397 // Note: Functions that run on this thread should run synchronously and return
398 // to the IO thread, not post additional tasks back to this thread, lest we
399 // cause a race condition at shutdown time that leads to a database leak.
400 scoped_ptr<base::Thread> safe_browsing_thread_;
402 // Indicates if we're currently in an update cycle.
403 bool update_in_progress_;
405 // When true, newly fetched chunks may not in the database yet since the
406 // database is still updating.
407 bool database_update_in_progress_;
409 // Indicates if we're in the midst of trying to close the database. If this
410 // is true, nothing on the IO thread should access the database.
411 bool closing_database_;
413 std::deque<QueuedCheck> queued_checks_;
415 // Timeout to use for safe browsing checks.
416 base::TimeDelta check_timeout_;
418 DISALLOW_COPY_AND_ASSIGN(SafeBrowsingDatabaseManager);
421 #endif // CHROME_BROWSER_SAFE_BROWSING_DATABASE_MANAGER_H_