summaryrefslogtreecommitdiffstats
path: root/chrome/browser/policy/url_blacklist_manager.cc
blob: dd070b7cc6b4bb122d214422b01751ff0757a9c2 (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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// Copyright (c) 2012 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/policy/url_blacklist_manager.h"

#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/message_loop.h"
#include "base/prefs/pref_service.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/common/url_constants.h"
#include "google_apis/gaia/gaia_urls.h"
#include "googleurl/src/gurl.h"
#include "net/base/load_flags.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request.h"

#if !defined(OS_CHROMEOS)
#include "chrome/browser/signin/signin_manager.h"
#endif

using content::BrowserThread;
using extensions::URLMatcher;
using extensions::URLMatcherCondition;
using extensions::URLMatcherConditionFactory;
using extensions::URLMatcherConditionSet;
using extensions::URLMatcherPortFilter;
using extensions::URLMatcherSchemeFilter;

namespace policy {

namespace {

// Maximum filters per policy. Filters over this index are ignored.
const size_t kMaxFiltersPerPolicy = 1000;

const char kServiceLoginAuth[] = "/ServiceLoginAuth";

#if !defined(OS_CHROMEOS)

bool IsSigninFlowURL(const GURL& url) {
  // Whitelist all the signin flow URLs flagged by the SigninManager.
  if (SigninManager::IsWebBasedSigninFlowURL(url))
    return true;

  // Additionally whitelist /ServiceLoginAuth.
  if (url.GetOrigin() != GaiaUrls::GetInstance()->gaia_url().GetOrigin())
    return false;
  return url.path() == kServiceLoginAuth;
}

#endif  // !defined(OS_CHROMEOS)

// A task that builds the blacklist on the FILE thread.
scoped_ptr<URLBlacklist> BuildBlacklist(scoped_ptr<base::ListValue> block,
                                        scoped_ptr<base::ListValue> allow) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));

  scoped_ptr<URLBlacklist> blacklist(new URLBlacklist);
  blacklist->Block(block.get());
  blacklist->Allow(allow.get());
  return blacklist.Pass();
}

}  // namespace

struct URLBlacklist::FilterComponents {
  FilterComponents() : port(0), match_subdomains(true), allow(true) {}
  ~FilterComponents() {}

  std::string scheme;
  std::string host;
  uint16 port;
  std::string path;
  bool match_subdomains;
  bool allow;
};

URLBlacklist::URLBlacklist() : id_(0),
                               url_matcher_(new URLMatcher) {
}

URLBlacklist::~URLBlacklist() {
}

void URLBlacklist::AddFilters(bool allow,
                              const base::ListValue* list) {
  URLMatcherConditionSet::Vector all_conditions;
  size_t size = std::min(kMaxFiltersPerPolicy, list->GetSize());
  for (size_t i = 0; i < size; ++i) {
    std::string pattern;
    bool success = list->GetString(i, &pattern);
    DCHECK(success);
    FilterComponents components;
    components.allow = allow;
    if (!FilterToComponents(pattern, &components.scheme, &components.host,
                            &components.match_subdomains, &components.port,
                            &components.path)) {
      LOG(ERROR) << "Invalid pattern " << pattern;
      continue;
    }

    all_conditions.push_back(
        CreateConditionSet(url_matcher_.get(), ++id_, components.scheme,
                           components.host, components.match_subdomains,
                           components.port, components.path));
    filters_[id_] = components;
  }
  url_matcher_->AddConditionSets(all_conditions);
}

void URLBlacklist::Block(const base::ListValue* filters) {
  AddFilters(false, filters);
}

void URLBlacklist::Allow(const base::ListValue* filters) {
  AddFilters(true, filters);
}

bool URLBlacklist::IsURLBlocked(const GURL& url) const {
  std::set<URLMatcherConditionSet::ID> matching_ids =
      url_matcher_->MatchURL(url);

  const FilterComponents* max = NULL;
  for (std::set<URLMatcherConditionSet::ID>::iterator id = matching_ids.begin();
       id != matching_ids.end(); ++id) {
    std::map<int, FilterComponents>::const_iterator it = filters_.find(*id);
    DCHECK(it != filters_.end());
    const FilterComponents& filter = it->second;
    if (!max || FilterTakesPrecedence(filter, *max))
      max = &filter;
  }

  // Default to allow.
  if (!max)
    return false;

  return !max->allow;
}

size_t URLBlacklist::Size() const {
  return filters_.size();
}

// static
bool URLBlacklist::FilterToComponents(const std::string& filter,
                                      std::string* scheme,
                                      std::string* host,
                                      bool* match_subdomains,
                                      uint16* port,
                                      std::string* path) {
  url_parse::Parsed parsed;

  if (URLFixerUpper::SegmentURL(filter, &parsed) == chrome::kFileScheme) {
    base::FilePath file_path;
    if (!net::FileURLToFilePath(GURL(filter), &file_path))
      return false;

    *scheme = chrome::kFileScheme;
    host->clear();
    *match_subdomains = true;
    *port = 0;
    // Special path when the |filter| is 'file://*'.
    *path = (filter == "file://*") ? "" : file_path.AsUTF8Unsafe();
#if defined(FILE_PATH_USES_WIN_SEPARATORS)
    // Separators have to be canonicalized on Windows.
    std::replace(path->begin(), path->end(), '\\', '/');
    *path = "/" + *path;
#endif
    return true;
  }

  if (!parsed.host.is_nonempty())
    return false;

  if (parsed.scheme.is_nonempty())
    scheme->assign(filter, parsed.scheme.begin, parsed.scheme.len);
  else
    scheme->clear();

  host->assign(filter, parsed.host.begin, parsed.host.len);
  // Special '*' host, matches all hosts.
  if (*host == "*") {
    host->clear();
    *match_subdomains = true;
  } else if ((*host)[0] == '.') {
    // A leading dot in the pattern syntax means that we don't want to match
    // subdomains.
    host->erase(0, 1);
    *match_subdomains = false;
  } else {
    url_canon::RawCanonOutputT<char> output;
    url_canon::CanonHostInfo host_info;
    url_canon::CanonicalizeHostVerbose(filter.c_str(), parsed.host,
                                       &output, &host_info);
    if (host_info.family == url_canon::CanonHostInfo::NEUTRAL) {
      // We want to match subdomains. Add a dot in front to make sure we only
      // match at domain component boundaries.
      *host = "." + *host;
      *match_subdomains = true;
    } else {
      *match_subdomains = false;
    }
  }

  if (parsed.port.is_nonempty()) {
    int int_port;
    if (!base::StringToInt(filter.substr(parsed.port.begin, parsed.port.len),
                           &int_port)) {
      return false;
    }
    if (int_port <= 0 || int_port > kuint16max)
      return false;
    *port = int_port;
  } else {
    // Match any port.
    *port = 0;
  }

  if (parsed.path.is_nonempty())
    path->assign(filter, parsed.path.begin, parsed.path.len);
  else
    path->clear();

  return true;
}

// static
scoped_refptr<extensions::URLMatcherConditionSet>
URLBlacklist::CreateConditionSet(
    extensions::URLMatcher* url_matcher,
    int id,
    const std::string& scheme,
    const std::string& host,
    bool match_subdomains,
    uint16 port,
    const std::string& path) {
  URLMatcherConditionFactory* condition_factory =
      url_matcher->condition_factory();
  std::set<URLMatcherCondition> conditions;
  conditions.insert(match_subdomains ?
      condition_factory->CreateHostSuffixPathPrefixCondition(host, path) :
      condition_factory->CreateHostEqualsPathPrefixCondition(host, path));

  scoped_ptr<URLMatcherSchemeFilter> scheme_filter;
  if (!scheme.empty())
    scheme_filter.reset(new URLMatcherSchemeFilter(scheme));

  scoped_ptr<URLMatcherPortFilter> port_filter;
  if (port != 0) {
    std::vector<URLMatcherPortFilter::Range> ranges;
    ranges.push_back(URLMatcherPortFilter::CreateRange(port));
    port_filter.reset(new URLMatcherPortFilter(ranges));
  }

  return new URLMatcherConditionSet(id, conditions,
                                    scheme_filter.Pass(), port_filter.Pass());
}

// static
bool URLBlacklist::FilterTakesPrecedence(const FilterComponents& lhs,
                                         const FilterComponents& rhs) {
  if (lhs.match_subdomains && !rhs.match_subdomains)
    return false;
  if (!lhs.match_subdomains && rhs.match_subdomains)
    return true;

  size_t host_length = lhs.host.length();
  size_t other_host_length = rhs.host.length();
  if (host_length != other_host_length)
    return host_length > other_host_length;

  size_t path_length = lhs.path.length();
  size_t other_path_length = rhs.path.length();
  if (path_length != other_path_length)
    return path_length > other_path_length;

  if (lhs.allow && !rhs.allow)
    return true;

  return false;
}

URLBlacklistManager::URLBlacklistManager(PrefService* pref_service)
    : ui_weak_ptr_factory_(this),
      pref_service_(pref_service),
      io_weak_ptr_factory_(this),
      blacklist_(new URLBlacklist) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  pref_change_registrar_.Init(pref_service_);
  base::Closure callback = base::Bind(&URLBlacklistManager::ScheduleUpdate,
                                      base::Unretained(this));
  pref_change_registrar_.Add(prefs::kUrlBlacklist, callback);
  pref_change_registrar_.Add(prefs::kUrlWhitelist, callback);

  // Start enforcing the policies without a delay when they are present at
  // startup.
  if (pref_service_->HasPrefPath(prefs::kUrlBlacklist))
    Update();
}

void URLBlacklistManager::ShutdownOnUIThread() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // Cancel any pending updates, and stop listening for pref change updates.
  ui_weak_ptr_factory_.InvalidateWeakPtrs();
  pref_change_registrar_.RemoveAll();
}

URLBlacklistManager::~URLBlacklistManager() {
}

void URLBlacklistManager::ScheduleUpdate() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // Cancel pending updates, if any. This can happen if two preferences that
  // change the blacklist are updated in one message loop cycle. In those cases,
  // only rebuild the blacklist after all the preference updates are processed.
  ui_weak_ptr_factory_.InvalidateWeakPtrs();
  base::MessageLoop::current()->PostTask(
      FROM_HERE,
      base::Bind(&URLBlacklistManager::Update,
                 ui_weak_ptr_factory_.GetWeakPtr()));
}

void URLBlacklistManager::Update() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // The preferences can only be read on the UI thread.
  scoped_ptr<base::ListValue> block(
      pref_service_->GetList(prefs::kUrlBlacklist)->DeepCopy());
  scoped_ptr<base::ListValue> allow(
      pref_service_->GetList(prefs::kUrlWhitelist)->DeepCopy());

  // Go through the IO thread to grab a WeakPtr to |this|. This is safe from
  // here, since this task will always execute before a potential deletion of
  // ProfileIOData on IO.
  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&URLBlacklistManager::UpdateOnIO,
                                     base::Unretained(this),
                                     base::Passed(&block),
                                     base::Passed(&allow)));
}

void URLBlacklistManager::UpdateOnIO(scoped_ptr<base::ListValue> block,
                                     scoped_ptr<base::ListValue> allow) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  // The URLBlacklist is built on the FILE thread. Once it's ready, it is passed
  // to the URLBlacklistManager on IO.
  BrowserThread::PostTaskAndReplyWithResult(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&BuildBlacklist,
                 base::Passed(&block),
                 base::Passed(&allow)),
      base::Bind(&URLBlacklistManager::SetBlacklist,
                 io_weak_ptr_factory_.GetWeakPtr()));
}

void URLBlacklistManager::SetBlacklist(scoped_ptr<URLBlacklist> blacklist) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  blacklist_ = blacklist.Pass();
}

bool URLBlacklistManager::IsURLBlocked(const GURL& url) const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  return blacklist_->IsURLBlocked(url);
}

bool URLBlacklistManager::IsRequestBlocked(
    const net::URLRequest& request) const {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  int filter_flags = net::LOAD_MAIN_FRAME | net::LOAD_SUB_FRAME;
  if ((request.load_flags() & filter_flags) == 0)
    return false;

#if !defined(OS_CHROMEOS)
  if (IsSigninFlowURL(request.url()))
    return false;
#endif

  return IsURLBlocked(request.url());
}

// static
void URLBlacklistManager::RegisterUserPrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterListPref(prefs::kUrlBlacklist,
                             user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
  registry->RegisterListPref(prefs::kUrlWhitelist,
                             user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}

}  // namespace policy