-
Notifications
You must be signed in to change notification settings - Fork 756
/
browser.rb
1868 lines (1492 loc) · 56.5 KB
/
browser.rb
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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
701
702
703
704
705
706
707
708
709
710
711
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
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
901
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=begin
Copyright 2010-2016 Tasos Laskos <tasos.laskos@arachni-scanner.com>
This file is part of the Arachni Framework project and is subject to
redistribution and commercial restrictions. Please see the Arachni Framework
web site for more information on licensing and terms of use.
=end
require 'childprocess'
require 'watir-webdriver'
require_relative 'selenium/webdriver/element'
require_relative 'processes/manager'
require_relative 'browser/element_locator'
require_relative 'browser/javascript'
module Arachni
# @note Depends on PhantomJS 1.9.2.
#
# Real browser driver providing DOM/JS/AJAX support.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@arachni-scanner.com>
class Browser
include UI::Output
include Utilities
include Support::Mixins::Observable
# @!method on_fire_event( &block )
advertise :on_fire_event
# @!method on_new_page( &block )
advertise :on_new_page
# @!method on_new_page_with_sink( &block )
advertise :on_new_page_with_sink
# @!method on_response( &block )
advertise :on_response
personalize_output
# {Browser} error namespace.
#
# All {Browser} errors inherit from and live under it.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@arachni-scanner.com>
class Error < Arachni::Error
# Raised when the browser could not be spawned.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@arachni-scanner.com>
class Spawn < Error
end
# Raised when a given resource can't be loaded.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@arachni-scanner.com>
class Load < Error
end
end
# How much time to wait for the PhantomJS process to spawn before respawning.
PHANTOMJS_SPAWN_TIMEOUT = 4
# How much time to wait for a targeted HTML element to appear on the page
# after the page is loaded.
ELEMENT_APPEARANCE_TIMEOUT = 5
# Let the browser take as long as it needs to complete an operation.
WATIR_COM_TIMEOUT = 3600 # 1 hour.
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=['"](.*?)['"].*?>/im,
/<\s*script.*?src=['"](.*?)['"].*?>/im,
/<\s*img.*?src=['"](.*?)['"].*?>/im,
/<\s*input.*?src=['"](.*?)['"].*?>/im,
]
# @return [Array<Page::DOM::Transition>]
attr_reader :transitions
# @return [Hash]
# Preloaded resources, by URL.
attr_reader :preloads
# @return [Watir::Browser]
# Watir driver interface.
attr_reader :watir
# @return [Selenium::WebDriver]
# Selenium driver interface.
attr_reader :selenium
# @return [Array<Page>]
# 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 {Javascript#data_flow_sinks} and {Javascript#execution_flow_sinks}.
#
# @see Javascript#data_flow_sinks
# @see Javascript#execution_flow_sinks
# @see Page::DOM#data_flow_sinks
# @see Page::DOM#execution_flow_sinks
attr_reader :page_snapshots_with_sinks
# @return [Javascript]
attr_reader :javascript
# @return [Support::LookUp::HashSet]
# States that have been visited and should be skipped.
#
# @see #skip_state
# @see #skip_state?
attr_reader :skip_states
# @return [Integer]
# PID of the lifeline process managing the browser process.
attr_reader :lifeline_pid
# @return [Integer]
# PID of the browser process.
attr_reader :browser_pid
attr_reader :last_url
class <<self
# @return [Bool]
# `true` if a supported browser is in the OS PATH, `false` otherwise.
def has_executable?
!!executable
end
# @return [String]
# Path to the PhantomJS executable.
def executable
Selenium::WebDriver::PhantomJS.path
end
def asset_domains
@asset_domains ||= Set.new
end
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
end
asset_domains
# @param [Hash] options
# @option options [Integer] :concurrency
# Maximum number of concurrent connections.
# @option options [Bool] :store_pages (true)
# Whether to store pages in addition to just passing them to {#on_new_page}.
# @option options [Integer] :width (1600)
# Window width.
# @option options [Integer] :height (1200)
# Window height.
def initialize( options = {} )
super()
@options = options.dup
@ignore_scope = options[:ignore_scope]
@width = options[:width] || 1600
@height = options[:height] || 1200
@proxy = HTTP::ProxyServer.new(
concurrency: @options[:concurrency],
address: '127.0.0.1',
request_handler: proc do |request, response|
exception_jail { request_handler( request, response ) }
end,
response_handler: proc do |request, response|
exception_jail { response_handler( request, response ) }
end
)
@options[:store_pages] = true if !@options.include?( :store_pages )
@proxy.start_async
@watir = ::Watir::Browser.new( selenium )
# User-controlled response cache, by URL.
@cache = Support::Cache::LeastRecentlyUsed.new( 200 )
# 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 = {}
@elements_with_events = {}
# 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
def clear_buffers
synchronize do
@elements_with_events.clear
@preloads.clear
@cache.clear
@captured_pages.clear
@page_snapshots.clear
@page_snapshots_with_sinks.clear
@window_responses.clear
end
end
# @return [String]
# Prefixes each source line with a number.
def source_with_line_numbers
source.lines.map.with_index do |line, i|
"#{i+1} - #{line}"
end.join
end
# @param [String, HTTP::Response, Page, Page:::DOM] resource
# Loads the given resource in the browser. If it is a string it will be
# treated like a URL.
#
# @return [Browser]
# `self`
def load( resource, options = {} )
case resource
when String
goto resource, options
when HTTP::Response
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
# @note The preloaded resource will be removed once used, for a persistent
# cache use {#cache}.
#
# @param [HTTP::Response, Page] resource
# Preloads a resource to be instantly available by URL via {#load}.
def preload( resource )
response = case resource
when HTTP::Response
resource
when Page
resource.response
else
fail Error::Load,
"Can't load resource of type #{resource.class}."
end
save_response( response ) if !response.url.include?( request_token )
@preloads[response.url] = response
response.url
end
# @param [HTTP::Response, Page] resource
# Cache a resource in order to be instantly available by URL via {#load}.
def cache( resource = nil )
return @cache if !resource
response = case resource
when HTTP::Response
resource
when Page
resource.response
else
fail Error::Load,
"Can't load resource of type #{resource.class}."
end
save_response response
@cache[response.url] = response
response.url
end
# @param [String] url
# Loads the given URL in the browser.
# @param [Hash] options
# @option [Bool] :take_snapshot (true)
# Take a snapshot right after loading the page.
# @option [Array<Cookie>] :cookies ([])
# Extra cookies to pass to the webapp.
#
# @return [Page::DOM::Transition]
# Transition used to replay the resource visit.
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 appeared 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
def wait_till_ready
print_debug_level_2 'Waiting for custom JS...'
@javascript.wait_till_ready
print_debug_level_2 '...done.'
wait_for_timers
wait_for_pending_requests
end
def shutdown
begin
watir.close if alive?
# Bucnh of dirrent errors can be raised here, Selenium, HTTP client,
# don't try to catch them by type because we'll probably miss some.
rescue
end
kill_process
@proxy.shutdown rescue Reactor::Error::NotRunning
end
# @return [String]
# Current URL, noralized via #{Arachni::URI.}
def url
normalize_url dom_url
end
# @return [String]
# Current URL, as provided by the browser.
def dom_url
javascript.run( 'return document.URL;' )
end
# Explores the browser's DOM tree and captures page snapshots for each
# state change until there are no more available.
#
# @param [Integer] depth
# How deep to go into the DOM tree.
#
# @return [Array<Page>]
# Page snapshots for each state.
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
# @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.
#
# @yield [ElementLocator,Array<Symbol>]
# Element locator along with the element's applicable events along with
# their handlers and attributes.
def each_element_with_events
current_url = self.url
javascript.dom_elements_with_events.each 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
# @note The results will be cached, if direct access in necessary
# use {#each_element_with_events}.
#
# @return [Hash<ElementLocator,Array<Symbol>>]
# Element locator along with the element's applicable events along with
# their handlers and attributes.
def elements_with_events( clear_cache = false )
current_url = self.url
@elements_with_events.clear if clear_cache
if @elements_with_events.include?( current_url )
return @elements_with_events[current_url]
end
@elements_with_events.clear
@elements_with_events[current_url] ||= {}
each_element_with_events do |locator, events|
@elements_with_events[current_url][locator] = events
end
@elements_with_events[current_url]
end
# @return [String]
# Snapshot ID used to determine whether or not a page snapshot has already
# been seen.
#
# Uses both elements and their DOM events and possible audit workload to
# determine the ID, as page snapshots should be retained both when further
# browser analysis can be performed and when new element audit workload
# (but possibly without any DOM relevance) is available.
def snapshot_id
current_url = self.url
id = Set.new
javascript.dom_elements_with_events.each do |element|
tag_name = element['tag_name']
attributes = element['attributes']
events = element['events']
element_id = attributes['id'].to_s
case tag_name
when 'a'
href = attributes['href'].to_s
element_id << href
if !href.empty?
if href.downcase.start_with?( 'javascript:' )
(events[:click] ||= []) << href
else
absolute = to_absolute( href, current_url )
next if skip_path?( absolute )
(events[:click] ||= []) << href
end
else
(events[:click] ||= []) << current_url
end
when 'input', 'textarea', 'select'
(events[:input] ||= []) << tag_name.to_sym
element_id << attributes['name'].to_s
when 'form'
action = attributes['action'].to_s
element_id << "#{action}#{attributes['name']}"
if !action.empty?
if action.downcase.start_with?( 'javascript:' )
(events[:submit] ||= []) << action
else
absolute = to_absolute( action, current_url )
if !skip_path?( absolute )
(events[:submit] ||= []) << absolute
end
end
else
(events[:submit] ||= []) << current_url
end
end
next if events.empty?
id << "#{tag_name}:#{element_id}:#{events.keys.sort}".persistent_hash
end
id << [:cookies, cookies.map(&:name).sort].to_s.persistent_hash
id.to_a.sort.map(&:to_s).join(':')
end
# Triggers all events on all elements (**once**) and captures
# {#page_snapshots page snapshots}.
#
# @return [Browser]
# `self`
def trigger_events
dom = self.state
elements_with_events( true ).each do |locator, events|
state = "#{locator.tag_name}:#{locator.attributes}:#{events.keys.sort}"
next if skip_state?( state )
skip_state state
events.each do |name, _|
distribute_event( dom, locator, name.to_sym )
end
end
self
end
# @note Only used when running as part of {BrowserCluster} to distribute
# page analysis across a pool of browsers.
#
# Distributes the triggering of `event` on the element at `element_index`
# on `page`.
#
# @param [String, Page, Page::DOM, HTTP::Response] resource
# @param [ElementLocator] locator
# @param [Symbol] event
def distribute_event( resource, locator, event )
trigger_event( resource, locator, event )
end
# @note Captures page {#page_snapshots}.
#
# Triggers `event` on the element described by `tag` on `page`.
#
# @param [String, Page, Page::DOM, HTTP::Response] resource
# Page containing the element's `tag`.
# @param [ElementLocator] element
# @param [Symbol] event
# Event to trigger.
def trigger_event( resource, element, event, restore = true )
event = event.to_sym
transition = fire_event( element, event )
if !transition
print_info "Could not trigger '#{event}' on '#{element}' because" <<
' the page has changed, capturing a new snapshot.'
capture_snapshot
if restore
print_info 'Restoring page.'
restore( resource )
end
return
end
capture_snapshot( transition )
restore( resource ) if restore
end
# Triggers `event` on `element`.
#
# @param [Selenium::WebDriver::Element, ElementLocator] element
# @param [Symbol] event
# @param [Hash] options
# @option options [Hash<Symbol,String=>String>] :inputs
# Values to use to fill-in inputs. Keys should be input names or ids.
#
# Defaults to using {OptionGroups::Input} if not specified.
#
# @return [Page::DOM::Transition, false]
# Transition if the operation was successful, `nil` otherwise.
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 Watir helpers whenever possible instead
# of firing events manually.
if tag_name == :form
fill_in_form_inputs( element, options[:inputs] )
if event == :submit
force = false
element.submit
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}"
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: #{url}"
print_debug "-- '#{event}' on: #{opening_tag} -- #{locator.css}"
print_debug
print_debug_exception e
nil
end
end
# 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.
#
# @param [Browser::ElementLocator] locator
# @param [Symbol,String] event
# @param [Bool] ret
# Return JS result?
# @param [Numeric] wait
# Amount of time to wait (in seconds) after triggering the event.
def fire_event_js( locator, event, ret: false, wait: 0.1 )
r = javascript.run <<-EOJS
var element = document.querySelector( #{locator.css.inspect} );
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';
#{'return' if ret} element.dispatchEvent( event );
EOJS
sleep wait
r
end
# Starts capturing requests and parses them into elements of pages,
# accessible via {#captured_pages}.
#
# @return [Browser]
# `self`
#
# @see #stop_capture
# @see #capture?
# @see #captured_pages
# @see #flush_pages
def start_capture
@capture = true
self
end
# Stops the {HTTP::Request} capture.
#
# @return [Browser]
# `self`
#
# @see #start_capture
# @see #capture?
# @see #flush_pages
def stop_capture
@capture = false
self
end
# @return [Bool]
# `true` if request capturing is enabled, `false` otherwise.
#
# @see #start_capture
# @see #stop_capture
def capture?
!!@capture
end
# @return [Array<Page>]
# Page snapshots (stored after events have been fired and JS links clicked)
# with hashes as keys and pages as values.
def page_snapshots
@page_snapshots.values
end
# @return [Array<Page>]
# Captured HTTP requests performed by the web page (AJAX etc.) converted
# into forms of pages to assist with analysis and audit.
def captured_pages
@captured_pages
end
# @return [Page::DOM]
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
# @return [Page]
# Converts the current browser window to a {Page page}.
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.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.update_metadata
page.clear_cache
end
if Options.audit.cookie_doms?
page.cookies.each do |cookie|
next if data_flow_sinks.include?( cookie.name ) ||
data_flow_sinks.include?( cookie.value )
cookie.skip_dom = true
end
page.update_metadata
end
end
page
end
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 = self.snapshot_id
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