Class: Arachni::Browser

Inherits:
Object show all
Includes:
Support::Mixins::Observable, UI::Output, Utilities
Defined in:
lib/arachni/browser.rb,
lib/arachni/browser/javascript.rb,
lib/arachni/browser/element_locator.rb,
lib/arachni/browser/javascript/dom_monitor.rb,
lib/arachni/browser/javascript/taint_tracer.rb,
lib/arachni/browser/javascript/taint_tracer/frame.rb,
lib/arachni/browser/javascript/taint_tracer/sink/base.rb,
lib/arachni/browser/javascript/taint_tracer/sink/data_flow.rb,
lib/arachni/browser/javascript/taint_tracer/sink/execution_flow.rb,
lib/arachni/browser/javascript/taint_tracer/frame/called_function.rb

Overview

Note:

Depends on PhantomJS 2.1.1.

Real browser driver providing DOM/JS/AJAX support.

Author:

Direct Known Subclasses

Arachni::BrowserCluster::Worker

Defined Under Namespace

Classes: ElementLocator, Error, Javascript

Constant Summary collapse

BROWSER_SPAWN_TIMEOUT =

How much time to wait for the PhantomJS process to spawn before respawning.

60
ELEMENT_APPEARANCE_TIMEOUT =

How much time to wait for a targeted HTML element to appear on the page after the page is loaded.

5
ASSET_EXTENSIONS =
Set.new(%w( css js jpg jpeg png gif json ))
INPUT_EVENTS =
Set.new([
    :change, :blur, :focus, :select, :keyup, :keypress, :keydown, :input
])
INPUT_EVENTS_TO_FORCE =
Set.new([
    :focus, :change, :blur, :select
])
ASSET_EXTRACTORS =
[
    /<\s*link.*?href=\s*['"]?(.*?)?['"]?[\s>]/im,
    /src\s*=\s*['"]?(.*?)?['"]?[\s>]/i,
]
USER_AGENT =

Unfortunately, we can't expose the HTTP user-agent for client-side stuff, because Selenium needs to know that we're using a Webkit-based browser in order to use the right JS code to trigger events etc.

'Mozilla/5.0 AppleWebKit/538.1 (KHTML, like Gecko) ' <<
"Arachni/#{Arachni::VERSION} Safari/538.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utilities

#available_port, available_port_mutex, #bytes_to_kilobytes, #bytes_to_megabytes, #caller_name, #caller_path, #cookie_decode, #cookie_encode, #cookies_from_file, #cookies_from_parser, #cookies_from_response, #exception_jail, #exclude_path?, #follow_protocol?, #form_decode, #form_encode, #forms_from_parser, #forms_from_response, #full_and_absolute_url?, #generate_token, #get_path, #hms_to_seconds, #html_decode, #html_encode, #include_path?, #links_from_parser, #links_from_response, #normalize_url, #page_from_response, #page_from_url, #parse_set_cookie, #path_in_domain?, #path_too_deep?, #port_available?, #rand_port, #random_seed, #redundant_path?, #regexp_array_match, #remove_constants, #request_parse_body, #seconds_to_hms, #skip_page?, #skip_resource?, #skip_response?, #to_absolute, #uri_decode, #uri_encode, #uri_parse, #uri_parse_query, #uri_parser, #uri_rewrite

Methods included from UI::Output

#caller_location, #debug?, #debug_level, #debug_level_1?, #debug_level_2?, #debug_level_3?, #debug_level_4?, #debug_off, #debug_on, #disable_only_positives, #error_buffer, #error_log_fd, #error_logfile, #has_error_log?, #included, #log_error, #mute, #muted?, #only_positives, #only_positives?, #print_bad, #print_debug, #print_debug_backtrace, #print_debug_exception, #print_debug_level_1, #print_debug_level_2, #print_debug_level_3, #print_debug_level_4, #print_error, #print_error_backtrace, #print_exception, #print_info, #print_line, #print_ok, #print_status, #print_verbose, #reroute_to_file, #reroute_to_file?, reset_output_options, #set_error_logfile, #unmute, #verbose?, #verbose_off, #verbose_on

Constructor Details

#initialize(options = {}) ⇒ Browser

Returns a new instance of Browser.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :concurrency (Integer)

    Maximum number of concurrent connections.

  • :store_pages (Bool) — default: true

    Whether to store pages in addition to just passing them to #on_new_page.

  • :width (Integer) — default: 1600

    Window width.

  • :height (Integer) — default: 1200

    Window height.


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
# File 'lib/arachni/browser.rb', line 176

def initialize( options = {} )
    super()
    @options = options.dup

    @ignore_scope = options[:ignore_scope]

    @width  = options[:width]  || 1600
    @height = options[:height] || 1200

    @options[:store_pages] = true if !@options.include?( :store_pages )

    start_webdriver

    # User-controlled preloaded responses, by URL.
    @preloads = {}

    # Captured pages -- populated by #capture.
    @captured_pages = []

    # Snapshots of the working page resulting from firing of events and
    # clicking of JS links.
    @page_snapshots = {}

    # Same as @page_snapshots but it doesn't deduplicate and only contains
    # pages with sink (Page::DOM#sink) data as populated by Javascript#flush_sink.
    @page_snapshots_with_sinks = []

    # Captures HTTP::Response objects per URL for open windows.
    @window_responses = {}


    # Keeps track of resources which should be skipped -- like already fired
    # events and clicked links etc.
    @skip_states = Support::LookUp::HashSet.new( hasher: :persistent_hash )

    @transitions = []
    @request_transitions = []
    @add_request_transitions = true

    # Last loaded URL.
    @last_url = nil

    @javascript = Javascript.new( self )
end

Instance Attribute Details

#browser_pidInteger (readonly)

Returns PID of the browser process.

Returns:

  • (Integer)

    PID of the browser process.


133
134
135
# File 'lib/arachni/browser.rb', line 133

def browser_pid
  @browser_pid
end

#javascriptJavascript (readonly)

Returns:


118
119
120
# File 'lib/arachni/browser.rb', line 118

def javascript
  @javascript
end

#last_urlObject (readonly)

Returns the value of attribute last_url


135
136
137
# File 'lib/arachni/browser.rb', line 135

def last_url
  @last_url
end

#lifeline_pidInteger (readonly)

Returns PID of the lifeline process managing the browser process.

Returns:

  • (Integer)

    PID of the lifeline process managing the browser process.


129
130
131
# File 'lib/arachni/browser.rb', line 129

def lifeline_pid
  @lifeline_pid
end

#page_snapshots_with_sinksArray<Page> (readonly)

Returns Same as #page_snapshots but it doesn't deduplicate and only contains pages with sink (Page::DOM#data_flow_sinks or Page::DOM#execution_flow_sinks) data as populated by Arachni::Browser::Javascript#data_flow_sinks and Arachni::Browser::Javascript#execution_flow_sinks.


115
116
117
# File 'lib/arachni/browser.rb', line 115

def page_snapshots_with_sinks
  @page_snapshots_with_sinks
end

#preloadsHash (readonly)

Returns Preloaded resources, by URL.

Returns:

  • (Hash)

    Preloaded resources, by URL.


94
95
96
# File 'lib/arachni/browser.rb', line 94

def preloads
  @preloads
end

#proxyObject (readonly)

Returns the value of attribute proxy


96
97
98
# File 'lib/arachni/browser.rb', line 96

def proxy
  @proxy
end

#seleniumSelenium::WebDriver::Driver (readonly)

Returns Selenium driver interface.

Returns:

  • (Selenium::WebDriver::Driver)

    Selenium driver interface.


104
105
106
# File 'lib/arachni/browser.rb', line 104

def selenium
  @selenium
end

#skip_statesSupport::LookUp::HashSet (readonly)

Returns States that have been visited and should be skipped.

Returns:

See Also:

  • #skip_state
  • #skip_state?

125
126
127
# File 'lib/arachni/browser.rb', line 125

def skip_states
  @skip_states
end

#transitionsArray<Page::DOM::Transition> (readonly)


90
91
92
# File 'lib/arachni/browser.rb', line 90

def transitions
  @transitions
end

#watirWatir::Browser (readonly)

Returns Watir driver interface.

Returns:

  • (Watir::Browser)

    Watir driver interface.


100
101
102
# File 'lib/arachni/browser.rb', line 100

def watir
  @watir
end

Class Method Details

.add_asset_domain(url) ⇒ Object


155
156
157
158
159
160
161
162
# File 'lib/arachni/browser.rb', line 155

def add_asset_domain( url )
    return if url.to_s.empty?
    return if !(curl = Arachni::URI( url ))
    return if !(domain = curl.domain)

    asset_domains << domain
    domain
end

.asset_domainsObject


151
152
153
# File 'lib/arachni/browser.rb', line 151

def asset_domains
    @asset_domains ||= Set.new
end

.executableString

Returns Path to the PhantomJS executable.

Returns:

  • (String)

    Path to the PhantomJS executable.


147
148
149
# File 'lib/arachni/browser.rb', line 147

def executable
    Selenium::WebDriver::PhantomJS.path
end

.has_executable?Bool

Returns true if a supported browser is in the OS PATH, false otherwise.

Returns:

  • (Bool)

    true if a supported browser is in the OS PATH, false otherwise.


141
142
143
# File 'lib/arachni/browser.rb', line 141

def has_executable?
    !!executable
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)

1120
1121
1122
# File 'lib/arachni/browser.rb', line 1120

def alive?
    @lifeline_pid && Processes::Manager.alive?( @lifeline_pid )
end

#capture?Bool

Returns true if request capturing is enabled, false otherwise.

Returns:

  • (Bool)

    true if request capturing is enabled, false otherwise.

See Also:


777
778
779
# File 'lib/arachni/browser.rb', line 777

def capture?
    !!@capture
end

#capture_snapshot(transition = nil) ⇒ Object


902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
# File 'lib/arachni/browser.rb', line 902

def capture_snapshot( transition = nil )
    pages = []

    request_transitions = flush_request_transitions
    transitions = ([transition] + request_transitions).flatten.compact

    window_handles = @selenium.window_handles

    begin
        window_handles.each do |handle|
            if window_handles.size > 1
                @selenium.switch_to.window( handle )
            end

            # We don't even have an HTTP response for the page, don't
            # bother trying anything else.
            next if !response

            unique_id = javascript.dom_event_digest
            already_seen = skip_state?( unique_id )
            skip_state unique_id

            with_sinks = javascript.has_sinks?

            # Avoid a #to_page call if at all possible because it'll generate
            # loads of data.
            next if (already_seen && !with_sinks) ||
                (page = to_page).code == 0

            if pages.empty?
                transitions.each do |t|
                    @transitions << t
                    page.dom.push_transition t
                end
            end

            capture_snapshot_with_sink( page )

            next if already_seen

            # Safegued against pages which generate an inf number of DOM
            # states regardless of UI interactions.
            transition_id ="#{page.dom.url}:#{page.dom.playable_transitions.map(&:hash)}"
            transition_id_seen = skip_state?( transition_id )
            skip_state transition_id
            next if transition_id_seen

            notify_on_new_page( page )

            if store_pages?
                @page_snapshots[unique_id] = page
                pages << page
            end
        end
    rescue => e
        print_debug "Could not capture snapshot for: #{@last_url}"

        if transition
            print_debug "-- #{transition}"
        end

        print_debug
        print_debug_exception e
    ensure
        @selenium.switch_to.default_content
    end

    pages
end

#captured_pagesArray<Page>

Returns Captured HTTP requests performed by the web page (AJAX etc.) converted into forms of pages to assist with analysis and audit.

Returns:

  • (Array<Page>)

    Captured HTTP requests performed by the web page (AJAX etc.) converted into forms of pages to assist with analysis and audit.


791
792
793
# File 'lib/arachni/browser.rb', line 791

def captured_pages
    @captured_pages
end

#clear_buffersObject


221
222
223
224
225
226
227
228
229
# File 'lib/arachni/browser.rb', line 221

def clear_buffers
    synchronize do
        @preloads.clear
        @captured_pages.clear
        @page_snapshots.clear
        @page_snapshots_with_sinks.clear
        @window_responses.clear
    end
end

#cookiesArray<Cookie>

Returns Cookies visible to JS.

Returns:


998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File 'lib/arachni/browser.rb', line 998

def cookies
    js_cookies = begin
         # Watir doesn't tell us if cookies are HttpOnly, so we need to figure
         # this out ourselves, by checking for JS visibility.
        javascript.run( 'return document.cookie' )
    # We may not have a page.
    rescue Selenium::WebDriver::Error::WebDriverError
        ''
    end

    # The domain attribute cannot be trusted, PhantomJS thinks all cookies
    # are for subdomains too.
    # Do not try to hack around this because it'll be a waste of time,
    # leading to confusion and duplicate cookies.
    #
    # Still, we ask Selenium for cookies instead of parsing the JS ones
    # and merging with the HTTP cookiejar because this allows us to get
    # a path attribute for JS cookies.
    @selenium.manage.all_cookies.map do |c|

        c[:httponly] = !js_cookies.include?( c[:name].to_s )
        c[:path]     = c[:path].gsub( /\/+/, '/' )
        c[:expires]  = Time.parse( c[:expires].to_s ) if c[:expires]

        c[:raw_name]  = c[:name].to_s
        c[:raw_value] = c[:value].to_s

        c[:name]  = Cookie.decode( c[:name].to_s )
        c[:value] = Cookie.value_to_v0( c[:value].to_s )

        Cookie.new c.merge( url: @last_url || self.url )
    end
end

#distribute_event(resource, locator, event) ⇒ Object

Note:

Only used when running as part of Arachni::BrowserCluster to distribute page analysis across a pool of browsers.

Distributes the triggering of event on the element at element_index on page.

Parameters:


535
536
537
# File 'lib/arachni/browser.rb', line 535

def distribute_event( resource, locator, event )
    trigger_event( resource, locator, event )
end

#dom_urlString

Returns Current URL, as provided by the browser.

Returns:

  • (String)

    Current URL, as provided by the browser.


412
413
414
# File 'lib/arachni/browser.rb', line 412

def dom_url
    @selenium.current_url
end

#each_element_with_events(whitelist = []) {|ElementLocator, Array<Symbol>| ... } ⇒ Object

Note:

Will skip non-visible elements as they can't be manipulated.

Iterates over all elements which have events and passes their info to the given block.

Yields:

  • (ElementLocator, Array<Symbol>)

    Element locator along with the element's applicable events along with their handlers and attributes.


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
# File 'lib/arachni/browser.rb', line 448

def each_element_with_events( whitelist = [])
    current_url = self.url

    javascript.each_dom_element_with_events whitelist do |element|
        tag_name   = element['tag_name']
        attributes = element['attributes']
        events     = element['events']

        case tag_name
            when 'a'
                href = attributes['href'].to_s

                if !href.empty?
                    if href.downcase.start_with?( 'javascript:' )
                        (events[:click] ||= []) << href
                    else
                        next if skip_path?( to_absolute( href, current_url ) )
                    end
                end

            when 'input'
                if attributes['type'].to_s.downcase == 'image'
                    (events[:click] ||= []) << 'image'
                end

            when 'form'
                action = attributes['action'].to_s

                if !action.empty?
                    if action.downcase.start_with?( 'javascript:' )
                        (events[:submit] ||= []) << action
                    else
                        next if skip_path?( to_absolute( action, current_url ) )
                    end
                end
        end

        next if events.empty?

        yield ElementLocator.new( tag_name: tag_name, attributes: attributes ),
                events
    end

    self
end

#explore_and_flush(depth = nil) ⇒ Array<Page>

Explores the browser's DOM tree and captures page snapshots for each state change until there are no more available.

Parameters:

  • depth (Integer) (defaults to: nil)

    How deep to go into the DOM tree.

Returns:

  • (Array<Page>)

    Page snapshots for each state.


424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/arachni/browser.rb', line 424

def explore_and_flush( depth = nil )
    pages         = [ to_page ]
    current_depth = 0

    loop do
        bcnt   = pages.size
        pages |= pages.map { |p| load( p ).trigger_events.flush_pages }.flatten

        break if pages.size == bcnt || (depth && depth >= current_depth)

        current_depth += 1
    end

    pages.compact
end

#fire_event(element, event, options = {}) ⇒ Page::DOM::Transition, false

Triggers event on element.

Parameters:

Options Hash (options):

Returns:


578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/arachni/browser.rb', line 578

def fire_event( element, event, options = {} )
    event   = event.to_s.downcase.sub( /^on/, '' ).to_sym
    locator = nil

    options[:inputs] = options[:inputs].my_stringify if options[:inputs]

    if element.is_a? ElementLocator
        locator = element

        begin
            Selenium::WebDriver::Wait.new( timeout: ELEMENT_APPEARANCE_TIMEOUT ).
                until { element = element.locate( self ) }

        rescue Selenium::WebDriver::Error::WebDriverError => e
            print_debug "Element '#{element.inspect}' could not be " <<
                            "located for triggering '#{event}'."
            print_debug
            print_debug_exception e
            return
        end
    end

    if locator
        opening_tag = locator.to_s
        tag_name    = locator.tag_name
    else
        opening_tag = element.opening_tag
        tag_name    = element.tag_name
        locator     = ElementLocator.from_html( opening_tag )
    end

    print_debug_level_2 "[start]: #{event} (#{options}) #{locator}"

    tag_name = tag_name.to_sym

    notify_on_fire_event( element, event )

    pre_timeouts = javascript.timeouts

    begin
        transition = Page::DOM::Transition.new( locator, event, options ) do
            force = true

            # It's better to use the helpers whenever possible instead of
            # firing events manually.
            if tag_name == :form
                fill_in_form_inputs( element, options[:inputs] )

                if event == :fill
                    force = false
                end

                if event == :submit
                    force = false

                    begin
                        element.find_elements( :css,
                            "input[type='submit'], button[type='submit']"
                        ).first.click
                    rescue => e
                        print_debug "No submit button, will trigger 'submit' event."
                        print_debug_exception e

                        element.submit
                    end
                end

            elsif event == :click
                force = false

                element.click

            elsif INPUT_EVENTS.include? event
                force = INPUT_EVENTS_TO_FORCE.include?( event )

                # Send keys will append to the existing value, so we need to
                # clear it first. The receiving input may not support values
                # though, so watch out.
                element.clear if [:input, :textarea].include?( tag_name )

                # Simulates real text input and will trigger associated events.
                # Except for INPUT_EVENTS_TO_FORCE of course.
                element.send_keys( (options[:value] || value_for( element )).to_s )
            end

            if force
                print_debug_level_2 "[forcing event]: #{event} (#{options}) #{locator}"
                fire_event_js locator, event
            end

            print_debug_level_2 "[waiting for requests]: #{event} (#{options}) #{locator}"
            wait_for_pending_requests
            print_debug_level_2 "[done waiting for requests]: #{event} (#{options}) #{locator}"

            # Maybe we switched to a different page, wait until the custom
            # JS env has been put in place.
            javascript.wait_till_ready
            javascript.set_element_ids

            update_cookies
        end

        print_debug_level_2 "[done in #{transition.time}s]: #{event} (#{options}) #{locator}"

        delay = (javascript.timeouts - pre_timeouts).compact.map { |t| t[1].to_i }.max
        if delay
            print_debug_level_2 "Found new timers with max #{delay}ms."
            delay = [Options.http.request_timeout, delay].min / 1000.0

            print_debug_level_2 "Will wait for #{delay}s."
            sleep delay
        end

        transition
    rescue Selenium::WebDriver::Error::WebDriverError => e

        print_debug "Error when triggering event for: #{dom_url}"
        print_debug "-- '#{event}' on: #{opening_tag} -- #{locator.css}"
        print_debug
        print_debug_exception e
        nil
    end
end

#fire_event_js(locator, event, wait: 0.1) ⇒ Object

This is essentially the same thing as Watir::Element#fire_event but 10 times faster.

Does not perform any sort of sanitization nor sanity checking, it will just try to trigger the event.

Parameters:

  • locator (Browser::ElementLocator)
  • event (Symbol, String)
  • wait (Numeric) (defaults to: 0.1)

    Amount of time to wait (in seconds) after triggering the event.


712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'lib/arachni/browser.rb', line 712

def fire_event_js( locator, event, wait: 0.1 )
    r = javascript.run <<-EOJS
        var element = document.querySelector( #{locator.css.inspect} );

        // Could not be found.
        if( !element ) return false;

        // Invisible.
        if( element.offsetWidth <= 0 && element.offsetHeight <= 0 ) return false;

        var event = document.createEvent( "Events" );

        event.initEvent( "#{event}", true, true );

        event.view     = window;
        event.altKey   = false;
        event.ctrlKey  = false;
        event.shiftKey = false;
        event.metaKey  = false;
        event.keyCode  = 0;
        event.charCode = 'a';

        element.dispatchEvent( event );

        return true;
    EOJS

    sleep( wait ) if r

    r
end

#flush_page_snapshots_with_sinksArray<Page>

Returns #page_snapshots_with_sinks and flushes it.

Returns:


974
975
976
977
978
# File 'lib/arachni/browser.rb', line 974

def flush_page_snapshots_with_sinks
    @page_snapshots_with_sinks.dup
ensure
    @page_snapshots_with_sinks.clear
end

#flush_pagesArray<Page>

Returns Flushes and returns the captured and snapshot pages.

Returns:

See Also:


989
990
991
992
993
994
# File 'lib/arachni/browser.rb', line 989

def flush_pages
    captured_pages + page_snapshots
ensure
    @captured_pages.clear
    @page_snapshots.clear
end

#goto(url, options = {}) ⇒ Page::DOM::Transition

Returns Transition used to replay the resource visit.

Parameters:

  • url (String)

    Loads the given URL in the browser.

  • options (Hash) (defaults to: {})
  • [Bool] (Hash)

    a customizable set of options

  • [Array<Cookie>] (Hash)

    a customizable set of options

Returns:


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
# File 'lib/arachni/browser.rb', line 310

def goto( url, options = {} )
    take_snapshot      = options.include?(:take_snapshot) ?
        options[:take_snapshot] : true
    extra_cookies      = options[:cookies] || {}
    update_transitions = options.include?(:update_transitions) ?
        options[:update_transitions] : true

    pre_add_request_transitions = @add_request_transitions
    if !update_transitions
        @add_request_transitions = false
    end

    @last_url = Arachni::URI( url ).to_s
    self.class.add_asset_domain @last_url

    ensure_open_window

    load_cookies url, extra_cookies

    transition = Page::DOM::Transition.new( :page, :load,
        url:     url,
        cookies: extra_cookies
    ) do
        print_debug_level_2 "Loading #{url} ..."
        @selenium.navigate.to url
        print_debug_level_2 '...done.'

        wait_till_ready

        Options.browser_cluster.css_to_wait_for( url ).each do |css|
            print_info "Waiting for #{css.inspect} to appear for: #{url}"

            begin
                Selenium::WebDriver::Wait.new(
                    timeout: Options.browser_cluster.job_timeout
                ).until { @selenium.find_element( :css, css ) }

                print_info "#{css.inspect} appeared for: #{url}"
            rescue Selenium::WebDriver::Error::TimeOutError
                print_bad "#{css.inspect} did not appear for: #{url}"
            end

        end

        javascript.set_element_ids
    end

    if @add_request_transitions
        @transitions << transition
    end

    @add_request_transitions = pre_add_request_transitions

    update_cookies

    # Capture the page at its initial state.
    capture_snapshot if take_snapshot

    transition
end

#inspectObject


1124
1125
1126
1127
1128
1129
1130
1131
# File 'lib/arachni/browser.rb', line 1124

def inspect
    s = "#<#{self.class} "
    s << "pid=#{@lifeline_pid} "
    s << "browser_pid=#{@browser_pid} "
    s << "last-url=#{@last_url.inspect} "
    s << "transitions=#{@transitions.size}"
    s << '>'
end

#load(resource, options = {}) ⇒ Browser

Returns self.

Parameters:

  • resource (String, HTTP::Response, Page, Page:::DOM)

    Loads the given resource in the browser. If it is a string it will be treated like a URL.

Returns:


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
# File 'lib/arachni/browser.rb', line 245

def load( resource, options = {} )

    case resource
        when String
            @transitions = []
            goto resource, options

        when HTTP::Response
            @transitions = []
            goto preload( resource ), options

        when Page
            HTTP::Client.update_cookies resource.cookie_jar

            load resource.dom

        when Page::DOM
            @transitions = resource.transitions.dup
            update_skip_states resource.skip_states

            @add_request_transitions = false if @transitions.any?
            resource.restore self
            @add_request_transitions = true

        else
            fail Error::Load,
                 "Can't load resource of type #{resource.class}."
    end

    self
end

#load_delayObject


1042
1043
1044
1045
# File 'lib/arachni/browser.rb', line 1042

def load_delay
    #(intervals + timeouts).map { |t| t[1] }.max
    @javascript.timeouts.compact.map { |t| t[1].to_i }.max
end

#on_fire_event(&block) ⇒ Object


29
# File 'lib/arachni/browser.rb', line 29

advertise :on_fire_event

#on_new_page(&block) ⇒ Object


32
# File 'lib/arachni/browser.rb', line 32

advertise :on_new_page

#on_new_page_with_sink(&block) ⇒ Object


35
# File 'lib/arachni/browser.rb', line 35

advertise :on_new_page_with_sink

#on_response(&block) ⇒ Object


38
# File 'lib/arachni/browser.rb', line 38

advertise :on_response

#page_snapshotsArray<Page>

Returns Page snapshots (stored after events have been fired and JS links clicked) with hashes as keys and pages as values.

Returns:

  • (Array<Page>)

    Page snapshots (stored after events have been fired and JS links clicked) with hashes as keys and pages as values.


784
785
786
# File 'lib/arachni/browser.rb', line 784

def page_snapshots
    @page_snapshots.values
end

#preload(resource) ⇒ Object

Note:

The preloaded resource will be removed once used.

Parameters:


281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/arachni/browser.rb', line 281

def preload( resource )
    response =  case resource
                    when HTTP::Response
                        resource

                    when Page
                        resource.response

                    else
                        fail Error::Load,
                             "Can't preload resource of type #{resource.class}."
                end

    save_response( response ) if !response.url.include?( request_token )

    @preloads[response.url] = response
    response.url
end

#responseObject


1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
# File 'lib/arachni/browser.rb', line 1063

def response
    u = dom_url

    if u == 'about:blank'
        print_debug 'Blank page.'
        return
    end

    if skip_path?( u )
        print_debug "Response is out of scope: #{u}"
        return
    end

    r = get_response( u )

    return r if r && r.code != 504

    if r
        print_debug "Origin server timed-out when requesting: #{u}"
    else
        print_debug "Response never arrived for: #{u}"

        print_debug 'Available responses are:'
        @window_responses.each do |k, _|
            print_debug "-- #{k}"
        end

        print_debug 'Tried:'
        print_debug "-- #{u}"
        print_debug "-- #{normalize_url( u )}"
        print_debug "-- #{normalize_watir_url( u )}"
    end

    nil
end

#shutdownObject


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
# File 'lib/arachni/browser.rb', line 377

def shutdown
    print_debug 'Shutting down...'

    print_debug_level_2 'Killing process.'
    if @kill_process
        begin
            @kill_process.close
        rescue => e
            print_debug_exception e
        end
    end

    print_debug_level_2 'Shutting down proxy...'
    @proxy.shutdown rescue Reactor::Error::NotRunning
    print_debug_level_2 '...done.'

    @proxy        = nil
    @kill_process = nil
    @watir        = nil
    @selenium     = nil
    @lifeline_pid = nil
    @browser_pid  = nil
    @browser_url  = nil

    print_debug '...shutdown complete.'
end

#skip_path?(path) ⇒ Boolean

Returns:

  • (Boolean)

1059
1060
1061
# File 'lib/arachni/browser.rb', line 1059

def skip_path?( path )
    enforce_scope? && super( path )
end

#sourceString

Returns HTML code of the evaluated (DOM/JS/AJAX) page.

Returns:

  • (String)

    HTML code of the evaluated (DOM/JS/AJAX) page.


1038
1039
1040
# File 'lib/arachni/browser.rb', line 1038

def source
    @selenium.page_source
end

#source_with_line_numbersString

Returns Prefixes each source line with a number.

Returns:

  • (String)

    Prefixes each source line with a number.


233
234
235
236
237
# File 'lib/arachni/browser.rb', line 233

def source_with_line_numbers
    source.lines.map.with_index do |line, i|
        "#{i+1} - #{line}"
    end.join
end

#start_captureBrowser

Starts capturing requests and parses them into elements of pages, accessible via #captured_pages.


754
755
756
757
# File 'lib/arachni/browser.rb', line 754

def start_capture
    @capture = true
    self
end

#statePage::DOM

Returns:


796
797
798
799
800
801
802
803
804
805
806
807
# File 'lib/arachni/browser.rb', line 796

def state
    d_url = dom_url

    return if !response

    Page::DOM.new(
        url:         d_url,
        transitions: @transitions.dup,
        digest:      @javascript.dom_digest,
        skip_states: skip_states.dup
    )
end

#stop_captureBrowser

Stops the HTTP::Request capture.

Returns:

See Also:


767
768
769
770
# File 'lib/arachni/browser.rb', line 767

def stop_capture
    @capture = false
    self
end

#to_pagePage

Returns Converts the current browser window to a page.

Returns:

  • (Page)

    Converts the current browser window to a page.


811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
# File 'lib/arachni/browser.rb', line 811

def to_page
    d_url = dom_url

    if !(r = response)
        return Page.from_data(
            dom: {
                url: d_url
            },
            response: {
                code: 0,
                url:  url
            }
        )
    end

    # We need sink data for both the current taint and to determine cookie
    # usage, so grab all of the data-flow sinks once.
    data_flow_sinks = {}
    if @javascript.supported?
        data_flow_sinks = @javascript.taint_tracer.data_flow_sinks
    end

    page                          = r.to_page
    page.body                     = source
    page.dom.url                  = d_url
    page.dom.cookies              = self.cookies
    page.dom.digest               = @javascript.dom_digest
    page.dom.execution_flow_sinks = @javascript.execution_flow_sinks
    page.dom.data_flow_sinks      = data_flow_sinks[@javascript.taint] || []
    page.dom.transitions          = @transitions.dup
    page.dom.skip_states          = skip_states.dup

    if Options.audit.ui_inputs?
        page.ui_inputs = Element::UIInput.from_browser( self, page )
    end

    if Options.audit.ui_forms?
        page.ui_forms = Element::UIForm.from_browser( self, page )
    end

    # Go through auditable DOM forms and cookies and remove the DOM from
    # them if no events are associated with it.
    #
    # This can save **A LOT** of time during the audit.
    if @javascript.supported?
        if Options.audit.form_doms?
            page.forms.each do |form|
                next if !form.node || !form.dom

                action = form.node['action'].to_s
                form.dom.browser = self

                next if action.downcase.start_with?( 'javascript:' ) ||
                    form.dom.locate.events.any?

                form.skip_dom = true
            end

            page.
            page.clear_cache
        end

        if Options.audit.cookie_doms?
            page.cookies.each do |cookie|
                if (sinks = data_flow_sinks[cookie.name] ||
                    data_flow_sinks[cookie.value])

                    # Don't be satisfied with just a taint match, make sure
                    # the full value is identical.
                    #
                    # For example, if a cookie has '1' as a name or value
                    # that's too generic and can match irrelevant data.
                    #
                    # The current approach isn't perfect of course, but it's
                    # the best we can do.
                    next if sinks.find do |sink|
                        sink.tainted_value == cookie.name ||
                            sink.tainted_value == cookie.value
                    end
                end

                cookie.skip_dom = true
            end

            page.
        end
    end

    page
end

#trigger_event(resource, element, event, restore = true) ⇒ Object

Note:

Captures page #page_snapshots.

Triggers event on the element described by tag on page.

Parameters:


548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# File 'lib/arachni/browser.rb', line 548

def trigger_event( resource, element, event, restore = true )
    transition = fire_event( element, event )

    if !transition
        print_info "Could not trigger '#{event}' on: #{element}"

        if restore
            print_info 'Restoring page.'
            restore( resource )
        end

        return
    end

    capture_snapshot( transition )
    restore( resource ) if restore
end

#trigger_eventsBrowser

Triggers all events on all elements (once) and captures page snapshots.

Returns:


499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/arachni/browser.rb', line 499

def trigger_events
    dom = self.state
    return self if !dom

    url = normalize_url( dom.url )

    count = 1
    each_element_with_events do |locator, events|
        state = "#{url}:#{locator.tag_name}:#{locator.attributes}:#{events.keys.sort}"
        next if skip_state?( state )
        skip_state state

        events.each do |name, _|
            if Options.scope.dom_event_limit_reached?( count )
                print_debug "DOM event limit reached for: #{dom.url}"
                next
            end

            distribute_event( dom, locator, name.to_sym )

            count += 1
        end
    end

    self
end

#update_cookiesObject


1032
1033
1034
# File 'lib/arachni/browser.rb', line 1032

def update_cookies
    HTTP::Client.update_cookies self.cookies
end

#urlString

Returns Current URL, noralized via #URI.

Returns:

  • (String)

    Current URL, noralized via #URI


406
407
408
# File 'lib/arachni/browser.rb', line 406

def url
    normalize_url dom_url
end

#wait_for_timersObject


1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
# File 'lib/arachni/browser.rb', line 1047

def wait_for_timers
    delay = load_delay
    return if !delay

    effective_delay = [Options.http.request_timeout, delay].min / 1000.0
    print_debug_level_2 "Waiting for max timer #{effective_delay}s (original was #{delay}ms)..."

    sleep effective_delay

    print_debug_level_2 '...done.'
end

#wait_till_readyObject


371
372
373
374
375
# File 'lib/arachni/browser.rb', line 371

def wait_till_ready
    @javascript.wait_till_ready
    wait_for_timers
    wait_for_pending_requests
end