summaryrefslogtreecommitdiffstats
path: root/chrome/browser/safe_browsing/download_protection_service.cc
blob: f87fb0b0bce64811d476428abcd8e330908ca7da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/safe_browsing/download_protection_service.h"

#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/signature_util.h"
#include "chrome/common/net/http_return.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "content/browser/download/download_item.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_fetcher.h"
#include "content/public/common/url_fetcher_delegate.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"

namespace safe_browsing {

const char DownloadProtectionService::kDownloadRequestUrl[] =
    "https://sb-ssl.google.com/safebrowsing/clientreport/download";

namespace {
bool IsBinaryFile(const FilePath& file) {
  return (file.MatchesExtension(FILE_PATH_LITERAL(".exe")) ||
          file.MatchesExtension(FILE_PATH_LITERAL(".cab")) ||
          file.MatchesExtension(FILE_PATH_LITERAL(".msi")));
}
}  // namespace

DownloadProtectionService::DownloadInfo::DownloadInfo()
    : total_bytes(0), user_initiated(false) {}

DownloadProtectionService::DownloadInfo::~DownloadInfo() {}

// static
DownloadProtectionService::DownloadInfo
DownloadProtectionService::DownloadInfo::FromDownloadItem(
    const DownloadItem& item) {
  DownloadInfo download_info;
  download_info.local_file = item.full_path();
  download_info.download_url_chain = item.url_chain();
  download_info.referrer_url = item.referrer_url();
  // TODO(bryner): Fill in the hash (we shouldn't compute it again)
  download_info.total_bytes = item.total_bytes();
  // TODO(bryner): Populate user_initiated
  return download_info;
}

class DownloadProtectionService::CheckClientDownloadRequest
    : public base::RefCountedThreadSafe<
          DownloadProtectionService::CheckClientDownloadRequest,
          BrowserThread::DeleteOnUIThread>,
      public content::URLFetcherDelegate {
 public:
  CheckClientDownloadRequest(const DownloadInfo& info,
                             const CheckDownloadCallback& callback,
                             DownloadProtectionService* service,
                             SafeBrowsingService* sb_service)
      : info_(info),
        callback_(callback),
        service_(service),
        sb_service_(sb_service),
        pingback_enabled_(service_->enabled()),
        is_signed_(false) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  }

  void Start() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    // TODO(noelutz): implement some cache to make sure we don't issue the same
    // request over and over again if a user downloads the same binary multiple
    // times.
    if (info_.download_url_chain.empty()) {
      RecordStats(REASON_INVALID_URL);
      PostFinishTask(SAFE);
      return;
    }
    const GURL& final_url = info_.download_url_chain.back();
    if (!final_url.is_valid() || final_url.is_empty() ||
        !final_url.SchemeIs("http")) {
      RecordStats(REASON_INVALID_URL);
      PostFinishTask(SAFE);
      return;  // For now we only support HTTP download URLs.
    }

    if (!IsBinaryFile(info_.local_file)) {
      RecordStats(REASON_NOT_BINARY_FILE);
      PostFinishTask(SAFE);
      return;
    }

    // Compute features from the file contents. Note that we record histograms
    // based on the result, so this runs regardless of whether the pingbacks
    // are enabled.  Since we do blocking I/O, this happens on the file thread.
    BrowserThread::PostTask(
        BrowserThread::FILE,
        FROM_HERE,
        base::Bind(&CheckClientDownloadRequest::ExtractFileFeatures, this));
  }

  // Canceling a request will cause us to always report the result as SAFE.
  // In addition, the DownloadProtectionService will not be notified when the
  // request finishes, so it must drop its reference after calling Cancel.
  void Cancel() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    service_ = NULL;
    if (fetcher_.get()) {
      // The DownloadProtectionService is going to release its reference, so we
      // might be destroyed before the URLFetcher completes.  Cancel the
      // fetcher so it does not try to invoke OnURLFetchComplete.
      FinishRequest(SAFE);
      fetcher_.reset();
    }
    // Note: If there is no fetcher, then some callback is still holding a
    // reference to this object.  We'll eventually wind up in some method on
    // the UI thread that will call FinishRequest() and run the callback.
  }

  // From the content::URLFetcherDelegate interface.
  virtual void OnURLFetchComplete(const content::URLFetcher* source) OVERRIDE {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    DCHECK_EQ(source, fetcher_.get());
    VLOG(2) << "Received a response for URL: "
            << info_.download_url_chain.back() << ": success="
            << source->GetStatus().is_success() << " response_code="
            << source->GetResponseCode();
    DownloadCheckResultReason reason = REASON_MAX;
    reason = REASON_SERVER_PING_FAILED;
    if (source->GetStatus().is_success() &&
        RC_REQUEST_OK == source->GetResponseCode()) {
      std::string data;
      source->GetResponseAsString(&data);
      if (data.size() > 0) {
        // For now no matter what we'll always say the download is safe.
        // TODO(noelutz): Parse the response body to see exactly what's going
        // on.
        reason = REASON_INVALID_RESPONSE_PROTO;
      }
    }

    if (reason != REASON_MAX) {
      RecordStats(reason);
    }
    // We don't need the fetcher anymore.
    fetcher_.reset();
    FinishRequest(SAFE);
  }

 private:
  friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
  friend class DeleteTask<CheckClientDownloadRequest>;

  virtual ~CheckClientDownloadRequest() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  }

  void ExtractFileFeatures() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
    if (safe_browsing::signature_util::IsSigned(info_.local_file)) {
      VLOG(2) << "Downloaded a signed binary: " << info_.local_file.value();
      is_signed_ = true;
    } else {
      VLOG(2) << "Downloaded an unsigned binary: " << info_.local_file.value();
      is_signed_ = false;
    }
    UMA_HISTOGRAM_BOOLEAN("SBClientDownload.SignedBinaryDownload", is_signed_);

    // TODO(noelutz): DownloadInfo should also contain the IP address of every
    // URL in the redirect chain.  We also should check whether the download
    // URL is hosted on the internal network.
    BrowserThread::PostTask(
        BrowserThread::IO,
        FROM_HERE,
        base::Bind(&CheckClientDownloadRequest::CheckWhitelists, this));
  }

  void CheckWhitelists() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
    DownloadCheckResultReason reason = REASON_MAX;
    if (!sb_service_.get()) {
      reason = REASON_SB_DISABLED;
    } else {
      for (size_t i = 0; i < info_.download_url_chain.size(); ++i) {
        const GURL& url = info_.download_url_chain[i];
        if (url.is_valid() && sb_service_->MatchDownloadWhitelistUrl(url)) {
          reason = REASON_WHITELISTED_URL;
          break;
        }
      }
      if (info_.referrer_url.is_valid() && reason == REASON_MAX &&
          sb_service_->MatchDownloadWhitelistUrl(info_.referrer_url)) {
        reason = REASON_WHITELISTED_REFERRER;
      }
      if (reason != REASON_MAX || is_signed_) {
        UMA_HISTOGRAM_COUNTS("SBClientDownload.SignedOrWhitelistedDownload", 1);
      }
    }
    if (reason != REASON_MAX) {
      RecordStats(reason);
      PostFinishTask(SAFE);
    } else if (!pingback_enabled_) {
      RecordStats(REASON_SB_DISABLED);
      PostFinishTask(SAFE);
    } else {
      // TODO(noelutz): check signature and CA against whitelist.

      // The URLFetcher is owned by the UI thread, so post a message to
      // start the pingback.
      BrowserThread::PostTask(
          BrowserThread::UI,
          FROM_HERE,
          base::Bind(&CheckClientDownloadRequest::SendRequest, this));
    }
  }

  void SendRequest() {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

    // This is our last chance to check whether the request has been canceled
    // before sending it.
    if (!service_) {
      RecordStats(REASON_REQUEST_CANCELED);
      FinishRequest(SAFE);
      return;
    }

    ClientDownloadRequest request;
    request.set_url(info_.download_url_chain.back().spec());
    request.mutable_digests()->set_sha256(info_.sha256_hash);
    request.set_length(info_.total_bytes);
    for (size_t i = 0; i < info_.download_url_chain.size(); ++i) {
      ClientDownloadRequest::Resource* resource = request.add_resources();
      resource->set_url(info_.download_url_chain[i].spec());
      if (i == info_.download_url_chain.size() - 1) {
        // The last URL in the chain is the download URL.
        resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);
        resource->set_referrer(info_.referrer_url.spec());
      } else {
        resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);
      }
      // TODO(noelutz): fill out the remote IP addresses.
    }
    request.set_user_initiated(info_.user_initiated);
    std::string request_data;
    if (!request.SerializeToString(&request_data)) {
      RecordStats(REASON_INVALID_REQUEST_PROTO);
      FinishRequest(SAFE);
      return;
    }

    VLOG(2) << "Sending a request for URL: "
            << info_.download_url_chain.back();
    fetcher_.reset(content::URLFetcher::Create(0 /* ID used for testing */,
                                               GURL(kDownloadRequestUrl),
                                               content::URLFetcher::POST,
                                               this));
    fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
    fetcher_->SetRequestContext(service_->request_context_getter_.get());
    fetcher_->SetUploadData("application/octet-stream", request_data);
    fetcher_->Start();
  }

  void PostFinishTask(DownloadCheckResult result) {
    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        base::Bind(&CheckClientDownloadRequest::FinishRequest, this, result));
  }

  void FinishRequest(DownloadCheckResult result) {
    DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
    if (service_) {
      callback_.Run(result);
      service_->RequestFinished(this);
    } else {
      callback_.Run(SAFE);
    }
  }

  void RecordStats(DownloadCheckResultReason reason) {
    UMA_HISTOGRAM_ENUMERATION("SBClientDownload.CheckDownloadStats",
                              reason,
                              REASON_MAX);
  }

  DownloadInfo info_;
  CheckDownloadCallback callback_;
  // Will be NULL if the request has been canceled.
  DownloadProtectionService* service_;
  scoped_refptr<SafeBrowsingService> sb_service_;
  const bool pingback_enabled_;
  bool is_signed_;
  scoped_ptr<content::URLFetcher> fetcher_;

  DISALLOW_COPY_AND_ASSIGN(CheckClientDownloadRequest);
};

DownloadProtectionService::DownloadProtectionService(
    SafeBrowsingService* sb_service,
    net::URLRequestContextGetter* request_context_getter)
    : sb_service_(sb_service),
      request_context_getter_(request_context_getter),
      enabled_(false) {}

DownloadProtectionService::~DownloadProtectionService() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  CancelPendingRequests();
}

void DownloadProtectionService::SetEnabled(bool enabled) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (enabled == enabled_) {
    return;
  }
  enabled_ = enabled;
  if (!enabled_) {
    CancelPendingRequests();
  }
}

void DownloadProtectionService::CheckClientDownload(
    const DownloadProtectionService::DownloadInfo& info,
    const CheckDownloadCallback& callback) {
  scoped_refptr<CheckClientDownloadRequest> request(
      new CheckClientDownloadRequest(info, callback, this, sb_service_));
  download_requests_.insert(request);
  request->Start();
}

void DownloadProtectionService::CancelPendingRequests() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  for (std::set<scoped_refptr<CheckClientDownloadRequest> >::iterator it =
           download_requests_.begin();
       it != download_requests_.end(); ++it) {
    (*it)->Cancel();
  }
  download_requests_.clear();
}

void DownloadProtectionService::RequestFinished(
    CheckClientDownloadRequest* request) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  std::set<scoped_refptr<CheckClientDownloadRequest> >::iterator it =
      download_requests_.find(request);
  DCHECK(it != download_requests_.end());
  download_requests_.erase(*it);
}

}  // namespace safe_browsing