summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/safe_browsing/phishing_classifier_delegate.cc
blob: 5ed08d0374443f4fefff8c5f10b86957737fd5e3 (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
// 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/renderer/safe_browsing/phishing_classifier_delegate.h"

#include <set>

#include "base/callback.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_callback_factory.h"
#include "chrome/common/safebrowsing_messages.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/safe_browsing/feature_extractor_clock.h"
#include "chrome/renderer/safe_browsing/phishing_classifier.h"
#include "chrome/renderer/safe_browsing/scorer.h"
#include "content/renderer/navigation_state.h"
#include "content/renderer/render_view.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"

namespace safe_browsing {


static GURL StripRef(const GURL& url) {
  GURL::Replacements replacements;
  replacements.ClearRef();
  return url.ReplaceComponents(replacements);
}

typedef std::set<PhishingClassifierDelegate*> PhishingClassifierDelegates;
static base::LazyInstance<PhishingClassifierDelegates>
    g_delegates(base::LINKER_INITIALIZED);

static base::LazyInstance<scoped_ptr<const safe_browsing::Scorer> >
    g_phishing_scorer(base::LINKER_INITIALIZED);

class ScorerCallback {
 public:
  static Scorer::CreationCallback* CreateCallback() {
    ScorerCallback* scorer_callback = new ScorerCallback();
    return scorer_callback->callback_factory_->NewCallback(
        &ScorerCallback::PhishingScorerCreated);
  }

 private:
  ScorerCallback() {
    callback_factory_.reset(
        new base::ScopedCallbackFactory<ScorerCallback>(this));
  }

  // Callback to be run once the phishing Scorer has been created.
  void PhishingScorerCreated(safe_browsing::Scorer* scorer) {
    if (!scorer) {
      DLOG(ERROR) << "Unable to create a PhishingScorer - corrupt model?";
      return;
    }

    g_phishing_scorer.Get().reset(scorer);

    PhishingClassifierDelegates::iterator i;
    for (i = g_delegates.Get().begin(); i != g_delegates.Get().end(); ++i)
      (*i)->SetPhishingScorer(scorer);

    delete this;
  }

  scoped_ptr<base::ScopedCallbackFactory<ScorerCallback> > callback_factory_;
};

void PhishingClassifierDelegate::SetPhishingModel(
    IPC::PlatformFileForTransit model_file) {
  safe_browsing::Scorer::CreateFromFile(
      IPC::PlatformFileForTransitToPlatformFile(model_file),
      RenderThread::current()->GetFileThreadMessageLoopProxy(),
      ScorerCallback::CreateCallback());
}

PhishingClassifierDelegate::PhishingClassifierDelegate(
    RenderView* render_view,
    PhishingClassifier* classifier)
    : RenderViewObserver(render_view),
      last_finished_load_id_(-1),
      last_page_id_sent_to_classifier_(-1) {
  g_delegates.Get().insert(this);
  if (!classifier) {
    classifier = new PhishingClassifier(render_view,
                                        new FeatureExtractorClock());
  }

  classifier_.reset(classifier);

  if (g_phishing_scorer.Get().get())
    SetPhishingScorer(g_phishing_scorer.Get().get());
}

PhishingClassifierDelegate::~PhishingClassifierDelegate() {
  CancelPendingClassification();
  g_delegates.Get().erase(this);
}

void PhishingClassifierDelegate::SetPhishingScorer(
    const safe_browsing::Scorer* scorer) {
  if (!render_view()->webview())
    return;  // RenderView is tearing down.

  classifier_->set_phishing_scorer(scorer);
  // Start classifying the current page if all conditions are met.
  // See MaybeStartClassification() for details.
  MaybeStartClassification();
}


void PhishingClassifierDelegate::OnStartPhishingDetection(const GURL& url) {
  last_url_received_from_browser_ = StripRef(url);
  // Start classifying the current page if all conditions are met.
  // See MaybeStartClassification() for details.
  MaybeStartClassification();
}

void PhishingClassifierDelegate::DidCommitProvisionalLoad(
    WebKit::WebFrame* frame, bool is_new_navigation) {
  // A new page is starting to load.  Unless the load is a navigation within
  // the same page, we need to cancel classification since we may get an
  // inconsistent result.
  NavigationState* state = NavigationState::FromDataSource(
      frame->dataSource());
  if (!state->was_within_same_page()) {
    CancelPendingClassification();
  }
}

void PhishingClassifierDelegate::PageCaptured(const string16& page_text) {
  last_finished_load_id_ = render_view()->page_id();
  last_finished_load_url_ = StripToplevelUrl();
  classifier_page_text_ = page_text;
  MaybeStartClassification();
}

void PhishingClassifierDelegate::CancelPendingClassification() {
  if (classifier_->is_ready()) {
    classifier_->CancelPendingClassification();
  }
  classifier_page_text_.clear();
}

bool PhishingClassifierDelegate::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(PhishingClassifierDelegate, message)
    IPC_MESSAGE_HANDLER(SafeBrowsingMsg_StartPhishingDetection,
                        OnStartPhishingDetection)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void PhishingClassifierDelegate::ClassificationDone(bool is_phishy,
                                                    double phishy_score) {
  // We no longer need the page text.
  classifier_page_text_.clear();
  VLOG(2) << "Phishy verdict = " << is_phishy << " score = " << phishy_score;
  if (!is_phishy) {
    return;
  }

  Send(new SafeBrowsingHostMsg_DetectedPhishingSite(
      routing_id(),
      last_url_sent_to_classifier_,
      phishy_score));
}

GURL PhishingClassifierDelegate::StripToplevelUrl() {
  return StripRef(render_view()->webview()->mainFrame()->url());
}

void PhishingClassifierDelegate::MaybeStartClassification() {
  // We can begin phishing classification when the following conditions are
  // met:
  //  1. A Scorer has been created
  //  2. The browser has sent a StartPhishingDetection message for the current
  //     toplevel URL.
  //  3. The page has finished loading and the page text has been extracted.
  //  4. The load is a new navigation (not a session history navigation).
  //  5. The toplevel URL has not already been classified.
  //
  // Note that if we determine that this particular navigation should not be
  // classified at all (as opposed to deferring it until we get an IPC or the
  // load completes), we discard the page text since it won't be needed.
  if (!classifier_->is_ready()) {
    VLOG(2) << "Not starting classification, no Scorer created.";
    // Keep classifier_page_text_, in case a Scorer is set later.
    return;
  }

  if (last_finished_load_id_ <= last_page_id_sent_to_classifier_) {
    // Skip loads from session history navigation.
    VLOG(2) << "Not starting classification, last finished load id is "
            << last_finished_load_id_ << " but we have classified up to "
            << "load id " << last_page_id_sent_to_classifier_;
    classifier_page_text_.clear();  // we won't need this.
    return;
  }

  if (last_finished_load_id_ != render_view()->page_id()) {
    VLOG(2) << "Render view page has changed, not starting classification";
    classifier_page_text_.clear();  // we won't need this.
    return;
  }
  // If the page id is unchanged, the toplevel URL should also be unchanged.
  DCHECK_EQ(StripToplevelUrl(), last_finished_load_url_);

  if (last_finished_load_url_ == last_url_sent_to_classifier_) {
    // We've already classified this toplevel URL, so this was likely an
    // in-page navigation or a subframe navigation.  The browser should not
    // send a StartPhishingDetection IPC in this case.
    VLOG(2) << "Toplevel URL is unchanged, not starting classification.";
    classifier_page_text_.clear();  // we won't need this.
    return;
  }

  if (last_url_received_from_browser_ != last_finished_load_url_) {
    // The browser has not yet confirmed that this URL should be classified,
    // so defer classification for now.
    VLOG(2) << "Not starting classification, last url from browser is "
            << last_url_received_from_browser_ << ", last finished load is "
            << last_finished_load_url_;
    // Keep classifier_page_text_, in case the browser notifies us later that
    // we should classify the URL.
    return;
  }

  VLOG(2) << "Starting classification for " << last_finished_load_url_;
  last_url_sent_to_classifier_ = last_finished_load_url_;
  last_page_id_sent_to_classifier_ = last_finished_load_id_;
  classifier_->BeginClassification(
      &classifier_page_text_,
      NewCallback(this, &PhishingClassifierDelegate::ClassificationDone));
}

}  // namespace safe_browsing