Class: Arachni::HTTP

Inherits:
Object show all
Includes:
Module::Utilities, UI::Output, Singleton
Defined in:
lib/http.rb

Overview

Arachni::Module::HTTP class

Provides a simple, high-performance and thread-safe HTTP interface to modules.

All requests are run Async (compliments of Typhoeus) providing great speed and performance.

Exceptions

Any exceptions or session corruption is handled by the class.<br/> Some are ignored, on others the HTTP session is refreshed.<br/> Point is, you don’t need to worry about it.

@author: Tasos “Zapotek” Laskos

<[email protected]>
<[email protected]>

@version: 0.2.3

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Module::Utilities

#exception_jail, #get_path, #normalize_url, #read_file, #seed

Methods included from UI::Output

#buffer, #debug!, #debug?, #flush_buffer, #mute!, #muted?, #only_positives!, #only_positives?, #print_debug, #print_debug_backtrace, #print_debug_pp, #print_error, #print_error_backtrace, #print_info, #print_line, #print_ok, #print_status, #print_verbose, #reroute_to_file, #reroute_to_file?, #unmute!, #verbose!, #verbose?

Constructor Details

#initializeHTTP

Returns a new instance of HTTP.



72
73
74
# File 'lib/http.rb', line 72

def initialize( )
    reset
end

Instance Attribute Details

The user supplied cookie jar

Returns:

  • (Hash)


62
63
64
# File 'lib/http.rb', line 62

def cookie_jar
  @cookie_jar
end

#curr_res_cntObject (readonly)

Returns the value of attribute curr_res_cnt.



68
69
70
# File 'lib/http.rb', line 68

def curr_res_cnt
  @curr_res_cnt
end

#curr_res_timeObject (readonly)

Returns the value of attribute curr_res_time.



67
68
69
# File 'lib/http.rb', line 67

def curr_res_time
  @curr_res_time
end

#init_headersHash (readonly)

The headers with which the HTTP client is initialized<br/> This is always kept updated.

Returns:

  • (Hash)


55
56
57
# File 'lib/http.rb', line 55

def init_headers
  @init_headers
end

#last_urlURI (readonly)

Returns:

  • (URI)


47
48
49
# File 'lib/http.rb', line 47

def last_url
  @last_url
end

#request_countObject (readonly)

Returns the value of attribute request_count.



64
65
66
# File 'lib/http.rb', line 64

def request_count
  @request_count
end

#response_countObject (readonly)

Returns the value of attribute response_count.



65
66
67
# File 'lib/http.rb', line 65

def response_count
  @response_count
end

#trainerObject (readonly)

Returns the value of attribute trainer.



70
71
72
# File 'lib/http.rb', line 70

def trainer
  @trainer
end

Class Method Details

.content_type(headers_hash) ⇒ Object



732
733
734
735
736
737
738
739
740
741
# File 'lib/http.rb', line 732

def self.content_type( headers_hash )
    return if !headers_hash.is_a?( Hash )

    headers_hash.each_pair {
        |key, val|
        return val if key.to_s.downcase == 'content-type'
    }

    return
end

.parse_cookiejar(cookie_jar) ⇒ Hash

Class method

Parses netscape HTTP cookie files

Parameters:

  • cookie_jar (String)

    the location of the cookie file

Returns:

  • (Hash)

    cookies in name=>value pairs



710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
# File 'lib/http.rb', line 710

def self.parse_cookiejar( cookie_jar )

    cookies = Hash.new

    jar = File.open( cookie_jar, 'r' )
    jar.each_line {
        |line|

        # skip empty lines
        if (line = line.strip).size == 0 then next end

        # skip comment lines
        if line[0] == '#' then next end

        cookie_arr = line.split( "\t" )

        cookies[cookie_arr[-2]] = cookie_arr[-1]
    }

    cookies
end

Instance Method Details

#abortObject



180
181
182
183
184
# File 'lib/http.rb', line 180

def abort
    exception_jail {
        @hydra.abort
    }
end

#after_run(&block) ⇒ Object

Gets called each time a hydra run finishes



279
280
281
# File 'lib/http.rb', line 279

def after_run( &block )
    @after_run << block
end

#after_run_persistent(&block) ⇒ Object



283
284
285
# File 'lib/http.rb', line 283

def after_run_persistent( &block )
    @after_run_persistent << block
end

#average_res_timeObject



186
187
188
189
# File 'lib/http.rb', line 186

def average_res_time
    return 0 if @curr_res_cnt == 0
    return @curr_res_time / @curr_res_cnt
end

Gets a url with cookies and url variables

Parameters:

  • url (URI)

    URL to GET

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

    request options

    • :params => cookies || {}

    • :train => force Arachni to analyze the HTML code || false

    • :async => make the request async? || true

    • :headers => HTTP request headers || {}

Returns:



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
# File 'lib/http.rb', line 496

def cookie( url, opts = { } )

    cookies   = opts[:params] || {}
    # params    = opts[:params]
    train     = opts[:train]

    async     = opts[:async]
    async     = true if async == nil

    headers   = opts[:headers] || {}

    headers = @init_headers.dup.
      merge( { 'cookie' => get_cookies_str( cookies ) } ).merge( headers )

    # wrap the code in exception handling
    exception_jail {

        opts = {
            :headers         => headers,
            :follow_location => false,
            # :params          => params
            :timeout       => opts[:timeout]
        }.merge( @opts )

        req = Typhoeus::Request.new( normalize_url( url ), opts )
        req.train! if train

        queue( req, async )
        return req
    }
end

#current_cookiesObject



590
591
592
# File 'lib/http.rb', line 590

def current_cookies
    parse_cookie_str( @init_headers['cookie'] )
end

#custom_404?(res) ⇒ Boolean

Checks whether or not the provided response is a custom 404 page

Parameters:

Returns:

  • (Boolean)


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
# File 'lib/http.rb', line 761

def custom_404?( res )

    @_404 ||= {}
    path  = get_path( res.effective_url )
    @_404[path] ||= {}

    if( !@_404[path]['file'] )

        # force a 404 and grab the html body
        force_404    = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s )
        @_404[path]['file'] = Typhoeus::Request.get( force_404 ).body

        # force another 404 and grab the html body
        force_404   = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s )
        not_found2  = Typhoeus::Request.get( force_404 ).body

        @_404[path]['file_rdiff'] = @_404[path]['file'].rdiff( not_found2 )
    end

    if( !@_404[path]['dir'] )

        force_404    = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) + '/'
        @_404[path]['dir'] = Typhoeus::Request.get( force_404 ).body

        force_404   = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) + '/'
        not_found2  = Typhoeus::Request.get( force_404 ).body

        @_404[path]['dir_rdiff'] = @_404[path]['dir'].rdiff( not_found2 )
    end

    return @_404[path]['dir'].rdiff( res.body ) == @_404[path]['dir_rdiff'] ||
        @_404[path]['file'].rdiff( res.body ) == @_404[path]['file_rdiff']
end

#fire_and_forgetObject



174
175
176
177
178
# File 'lib/http.rb', line 174

def fire_and_forget
    exception_jail {
        @hydra.fire_and_forget
    }
end

#get(url, opts = { }) ⇒ Typhoeus::Request

Gets a URL passing the provided query parameters

Parameters:

  • url (URI)

    URL to GET

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

    request options

    • :params => request parameters || {}

    • :train => force Arachni to analyze the HTML code || false

    • :async => make the request async? || true

    • :headers => HTTP request headers || {}

    • :follow_location => follow redirects || false

Returns:



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
# File 'lib/http.rb', line 342

def get( url, opts = { } )

    params    = opts[:params]    || {}
    remove_id = opts[:remove_id]
    train     = opts[:train]

    follow_location    = opts[:follow_location]    || false

    async     = opts[:async]
    async     = true if async == nil

    headers   = opts[:headers]   || {}
    headers   = @init_headers.dup.merge( headers )


    params = params.merge( { @rand_seed => '' } ) if !remove_id

    #
    # the exception jail function wraps the block passed to it
    # in exception handling and runs it
    #
    # how cool is Ruby? Seriously....
    #
    exception_jail {

        #
        # There are cases where the url already has a query and we also have
        # some params to work with. Some webapp frameworks will break
        # or get confused...plus the url will not be RFC compliant.
        #
        # Thus we need to merge the provided params with the
        # params of the url query and remove the latter from the url.
        #
        cparams = params.dup
        curl    = URI.escape( url.dup )

        cparams = q_to_h( curl ).merge( cparams )

        begin
            curl.gsub!( "?#{URI(curl).query}", '' ) if URI(curl).query
        rescue
            return
        end

        opts = {
            :headers       => headers,
            :params        => cparams.empty? ? nil : cparams,
            :follow_location => follow_location,
            :timeout       => opts[:timeout]
        }.merge( @opts )

        req = Typhoeus::Request.new( curl, opts )
        req.train! if train

        queue( req, async )
        return req
    }

end

#get_cookies_str(cookies = { }) ⇒ string

Returns a hash of cookies as a string (merged with the cookie-jar)

Parameters:

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

    name=>value pairs

Returns:

  • (string)


670
671
672
673
674
675
676
677
678
679
680
681
682
683
# File 'lib/http.rb', line 670

def get_cookies_str( cookies = { } )

    jar = parse_cookie_str( @init_headers['cookie'] )
    cookies = jar.merge( cookies )

    str = ''
    cookies.each_pair {
        |name, value|
        value = '' if !value
        val = URI.escape( URI.escape( value ), '+;' )
        str += "#{name}=#{val};"
    }
    return str
end

#header(url, opts = { }) ⇒ Typhoeus::Request

Gets a url with optional url variables and modified headers

Parameters:

  • url (URI)

    URL to GET

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

    request options

    • :params => headers || {}

    • :train => force Arachni to analyze the HTML code || false

    • :async => make the request async? || true

Returns:



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
# File 'lib/http.rb', line 539

def header( url, opts = { } )

    headers   = opts[:params] || {}
    # params    = opts[:params]
    train     = opts[:train]

    async     = opts[:async]
    async     = true if async == nil


    # wrap the code in exception handling
    exception_jail {

        orig_headers  = @init_headers.clone
        @init_headers = @init_headers.merge( headers )

        req = Typhoeus::Request.new( normalize_url( url ),
            :headers       => @init_headers.dup,
            :user_agent    => @init_headers['User-Agent'],
            :follow_location => false,
            # :params        => params
            :timeout       => opts[:timeout]
        )
        req.train! if train

        @init_headers = orig_headers.clone

        queue( req, async )
        return req
    }

end

#max_concurrencyObject



195
196
197
# File 'lib/http.rb', line 195

def max_concurrency
    @hydra.max_concurrency
end

#max_concurrency!(max_concurrency) ⇒ Object



191
192
193
# File 'lib/http.rb', line 191

def max_concurrency!( max_concurrency )
    @hydra.max_concurrency = max_concurrency
end

#on_complete(&block) ⇒ Object

Gets called each time a request completes and passes the response to the block



291
292
293
# File 'lib/http.rb', line 291

def on_complete( &block )
    @on_complete << block
end

#on_queue(&block) ⇒ Object

Gets called each time a request is queued and passes the request to the block



299
300
301
# File 'lib/http.rb', line 299

def on_queue( &block )
    @on_queue << block
end

#parse_and_set_cookies(res) ⇒ Object



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
# File 'lib/http.rb', line 613

def parse_and_set_cookies( res )
    cookie_hash = {}

    # extract cookies from the header field
    begin
        [res.headers_hash['Set-Cookie']].flatten.each {
            |set_cookie_str|

            break if !set_cookie_str.is_a?( String )
            cookie_hash.merge!( WEBrick::Cookie.parse_set_cookies(set_cookie_str).inject({}) do |hash, cookie|
                hash[cookie.name] = cookie.value if !!cookie
                hash
            end
            )
        }
    rescue Exception => e
        print_debug( e.to_s )
        print_debug_backtrace( e )
    end

    # extract cookies from the META tags
    begin

        # get get the head in order to check if it has an http-equiv for set-cookie
        head = res.body.match( /<head(.*)<\/head>/imx )

        # if it does feed the head to the parser in order to extract the cookies
        if head && head.to_s.substring?( 'set-cookie' )
            Nokogiri::HTML( head.to_s ).search( "//meta[@http-equiv]" ).each {
                |elem|

                next if elem['http-equiv'].downcase != 'set-cookie'
                k, v = elem['content'].split( ';' )[0].split( '=', 2 )
                cookie_hash[k] = v
            }
        end
    rescue Exception => e
        print_debug( e.to_s )
        print_debug_backtrace( e )
    end

    return if cookie_hash.empty?

    # update framework cookies
    Arachni::Options.instance.cookies = cookie_hash

    current = parse_cookie_str( @init_headers['cookie'] )
    set_cookies( current.merge( cookie_hash ) )
end

Converts HTTP cookies from string to Hash

Parameters:

Returns:

  • (Hash)


692
693
694
695
696
697
698
699
# File 'lib/http.rb', line 692

def parse_cookie_str( str )
    cookie_jar = Hash.new
    str.split( ';' ).each {
        |kvp|
        cookie_jar[kvp.split( "=" )[0]] = kvp.split( "=" )[1]
    }
    return cookie_jar
end

#parse_url(url) ⇒ URI

Encodes and parses a URL String

Parameters:

Returns:

  • (URI)

    URI object



750
751
752
# File 'lib/http.rb', line 750

def parse_url( url )
    URI.parse( URI.encode( url ) )
end

#post(url, opts = { }) ⇒ Typhoeus::Request

Posts a form to a URL with the provided query parameters

Parameters:

  • url (URI)

    URL to POST

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

    request options

    • :params => request parameters || {}

    • :train => force Arachni to analyze the HTML code || false

    • :async => make the request async? || true

    • :headers => HTTP request headers || {}

Returns:



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
# File 'lib/http.rb', line 414

def post( url, opts = { } )

    params    = opts[:params]
    train     = opts[:train]

    async     = opts[:async]
    async     = true if async == nil

    headers   = opts[:headers] || {}
    headers   = @init_headers.dup.merge( headers )

    exception_jail {

        opts = {
            :method        => :post,
            :headers       => headers,
            :params        => params,
            :follow_location => false,
            :timeout       => opts[:timeout]
        }.merge( @opts )

        req = Typhoeus::Request.new( normalize_url( url ), opts )
        req.train! if train

        queue( req, async )
        return req
    }
end

#q_to_h(url) ⇒ Object



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/http.rb', line 572

def q_to_h( url )
    params = {}

    begin
        query = URI( url.to_s ).query
        return params if !query

        query.split( '&' ).each {
            |param|
            k,v = param.split( '=', 2 )
            params[k] = v
        }
    rescue
    end

    return params
end

#queue(req, async = true) ⇒ Object

Queues a Tyhpoeus::Request and applies an ‘on_complete’ callback on behal of the trainer.

Parameters:

  • req (Tyhpoeus::Request)

    the request to queue

  • async (Bool) (defaults to: true)

    run request async?



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
# File 'lib/http.rb', line 206

def queue( req, async = true )

    req.id = @request_count

    @on_queue.each {
        |block|
        exception_jail{ block.call( req, async ) }
    }

    if( !async )
        @hydra_sync.queue( req )
    else
        @hydra.queue( req )
    end

    @request_count += 1

    print_debug( '------------' )
    print_debug( 'Queued request.' )
    print_debug( 'ID#: ' + req.id.to_s )
    print_debug( 'URL: ' + req.url )
    print_debug( 'Method: ' + req.method.to_s  )
    print_debug( 'Params: ' + req.params.to_s  )
    print_debug( 'Headers: ' + req.headers.to_s  )
    print_debug( 'Train?: ' + req.train?.to_s  )
    print_debug(  '------------' )

    req.on_complete( true ) {
        |res|

        @response_count += 1
        @curr_res_cnt   += 1
        @curr_res_time  += res.start_transfer_time

        @on_complete.each {
            |block|
            exception_jail{ block.call( res ) }
        }

        parse_and_set_cookies( res )

        print_debug( '------------' )
        print_debug( 'Got response.' )
        print_debug( 'Request ID#: ' + res.request.id.to_s )
        print_debug( 'URL: ' + res.effective_url )
        print_debug( 'Method: ' + res.request.method.to_s  )
        print_debug( 'Params: ' + res.request.params.to_s  )
        print_debug( 'Headers: ' + res.request.headers.to_s  )
        print_debug( 'Train?: ' + res.request.train?.to_s  )
        print_debug( '------------' )

        if( req.train? )
            # handle redirections
            if( ( redir = redirect?( res.dup ) ).is_a?( String ) )
                req2 = get( redir, :remove_id => true )
                req2.on_complete {
                    |res2|
                    @trainer.add_response( res2, true )
                } if req2
            else
                @trainer.add_response( res )
            end
        end
    }

    exception_jail {
        @hydra_sync.run if !async
    }
end

#request(url, opts) ⇒ Typhoeus::Request

Makes a generic request

Parameters:

  • url (URI)
  • opts (Hash)

Returns:



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/http.rb', line 311

def request( url, opts )
    headers   = opts[:headers]   || {}
    opts[:headers] = @init_headers.dup.merge( headers )

    train     = opts[:train]
    async     = opts[:async]
    async     = true if async == nil

    exception_jail {

        req = Typhoeus::Request.new( normalize_url( url ), opts.merge( @opts ) )
        req.train! if train

        queue( req, async )
        return req
    }
end

#resetObject



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
# File 'lib/http.rb', line 76

def reset

    opts = Options.instance

    # someone wants to reset us although nothing has been *set* in the first place
    # otherwise we'd have a url in opts
    return if !opts.url


    req_limit = opts.http_req_limit

    hydra_opts = {
        :max_concurrency               => req_limit,
        :disable_ssl_peer_verification => true,
        :username                      => opts.url.user,
        :password                      => opts.url.password,
        :method                        => :auto,
    }

    @hydra      = Typhoeus::Hydra.new( hydra_opts )
    @hydra_sync = Typhoeus::Hydra.new( hydra_opts.merge( :max_concurrency => 1 ) )

    @hydra.disable_memoization
    @hydra_sync.disable_memoization

    @trainer = Arachni::Module::Trainer.new
    @trainer.http = self

    @init_headers = {
        'cookie' => '',
        'From'   => opts.authed_by || '',
        'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'User-Agent'    => opts.user_agent
    }

    cookies = {}
    cookies.merge!( self.class.parse_cookiejar( opts.cookie_jar ) ) if opts.cookie_jar
    cookies.merge!( opts.cookies ) if opts.cookies

    set_cookies( cookies ) if !cookies.empty?

    proxy_opts = {}
    proxy_opts = {
        :proxy           => "#{opts.proxy_addr}:#{opts.proxy_port}",
        :proxy_username  => opts.proxy_user,
        :proxy_password  => opts.proxy_pass,
        :proxy_type      => opts.proxy_type
    } if opts.proxy_addr

    @opts = {
        :user_agent      => opts.user_agent,
        :follow_location => false,
        # :timeout         => 8000
    }.merge( proxy_opts )

    @request_count  = 0
    @response_count = 0

    # we'll use it to identify our requests
    @rand_seed = seed( )

    @curr_res_time = 0
    @curr_res_cnt  = 0

    @on_complete = []
    @on_queue    = []

    @after_run = []
    @after_run_persistent = []
end

#runObject

Runs Hydra (all the asynchronous queued HTTP requests)

Should only be called by the framework after all module threads have beed joined!



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/http.rb', line 153

def run
    exception_jail {
        @hydra.run

        @after_run.each {
            |block|
            block.call
        }

        @after_run.clear

        @after_run_persistent.each {
            |block|
            block.call
        }

        @curr_res_time = 0
        @curr_res_cnt  = 0
    }
end

#set_cookies(cookies) ⇒ void

This method returns an undefined value.

Sets cookies for the HTTP session

Parameters:

  • cookies (Hash)

    name=>value pairs



605
606
607
608
609
610
611
# File 'lib/http.rb', line 605

def set_cookies( cookies )
    @init_headers['cookie'] = ''
    @cookie_jar = cookies.each_pair {
        |name, value|
        @init_headers['cookie'] += "#{name}=#{value};"
    }
end

#trace(url, opts = { }) ⇒ Typhoeus::Request

Sends an HTTP TRACE request to “url”.

Parameters:

  • url (URI)

    URL to POST

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

    request options

    • :params => request parameters || {}

    • :train => force Arachni to analyze the HTML code || false

    • :async => make the request async? || true

    • :headers => HTTP request headers || {}

Returns:



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
# File 'lib/http.rb', line 455

def trace( url, opts = { } )

    params    = opts[:params]
    train     = opts[:train]

    async     = opts[:async]
    async     = true if async == nil

    headers   = opts[:headers] || {}
    headers   = @init_headers.dup.merge( headers )

    exception_jail {

        opts = {
            :method        => :trace,
            :headers       => headers,
            :params        => params,
            :follow_location => false
        }.merge( @opts )

        req = Typhoeus::Request.new( normalize_url( url ), opts )
        req.train! if train

        queue( req, async )
        return req
    }
end

#update_cookies(cookies) ⇒ Object



594
595
596
# File 'lib/http.rb', line 594

def update_cookies( cookies )
    set_cookies( current_cookies.merge( cookies ) )
end