Class: Arachni::Parser

Inherits:
Object show all
Includes:
Module::Utilities, UI::Output
Defined in:
lib/arachni/parser/parser.rb,
lib/arachni/parser/page.rb,
lib/arachni/parser/elements.rb

Overview

Analyzer class

Analyzes HTML code extracting forms, links and cookies depending on user opts.<br/>

It grabs all element attributes not just URLs and variables.<br/> All URLs are converted to absolute and URLs outside the domain are ignored.<br/>

Forms

Form analysis uses both regular expressions and the Nokogiri parser<br/> in order to be able to handle badly written HTML code, such as not closed<br/> tags and tag overlaps.

In order to ease audits, in addition to parsing forms into data structures<br/> like “select” and “option”, all auditable inputs are put under the<br/> “auditable” key.

Links are extracted using the Nokogiri parser.

Cookies

Cookies are extracted from the HTTP headers and parsed by WEBrick::Cookie

@author: Tasos “Zapotek” Laskos

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

@version: 0.2.2

Defined Under Namespace

Modules: Element, Extractors Classes: Page

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Module::Utilities

#exception_jail, #get_path, #hash_keys_to_str, #normalize_url, #read_file, #seed, #uri_decode, #uri_encode, #uri_parse, #uri_parser, #url_sanitize

Methods included from UI::Output

#buffer, #debug!, #debug?, #flush_buffer, #mute!, #muted?, #only_positives!, #only_positives?, #print_bad, #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?, #uncap_buffer!, #unmute!, #verbose!, #verbose?

Constructor Details

#initialize(opts, res) ⇒ Parser

Constructor <br/> Instantiates Analyzer class with user options.

Parameters:



99
100
101
102
103
104
105
106
107
108
109
# File 'lib/arachni/parser/parser.rb', line 99

def initialize( opts, res )
    @opts = opts

    @code = res.code
    @url  = url_sanitize( res.effective_url )
    @html = res.body
    @response_headers = res.headers_hash

    @doc   = nil
    @paths = nil
end

Instance Attribute Details

#optsOptions (readonly)

Options instance

Returns:



91
92
93
# File 'lib/arachni/parser/parser.rb', line 91

def opts
  @opts
end

#urlString

Returns the url of the page.

Returns:

  • (String)

    the url of the page



84
85
86
# File 'lib/arachni/parser/parser.rb', line 84

def url
  @url
end

Instance Method Details

#baseObject



547
548
549
550
551
552
553
554
# File 'lib/arachni/parser/parser.rb', line 547

def base
    begin
        tmp = doc.search( '//base[@href]' )
        return tmp[0]['href'].dup
    rescue
        return
    end
end

#cookiesArray<Element::Cookie>

Extracts cookies from an HTTP headers

Parameters:

  • headers (String)

    HTTP headers

  • html (String)

    the HTML code of the page

Returns:



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

def cookies

    cookies_arr = []
    cookies     = []

    begin
        doc.search( "//meta[@http-equiv]" ).each {
            |elem|

            next if elem['http-equiv'].downcase != 'set-cookie'
            k, v = elem['content'].split( ';' )[0].split( '=', 2 )
            cookies_arr << Element::Cookie.new( @url, { 'name' => k, 'value' => v } )
        }
    rescue Exception => e
        # ap e
        # ap e.backtrace
    end


    # don't ask me why....
    if @response_headers.to_s.downcase.substring?( 'set-cookie' )
        begin
            cookies << ::WEBrick::Cookie.parse_set_cookies( @response_headers['Set-Cookie'].to_s )
            cookies << ::WEBrick::Cookie.parse_set_cookies( @response_headers['set-cookie'].to_s )
        rescue Exception => e
            # ap e
            # ap e.backtrace
            return cookies_arr
        end
    end

    cookies.flatten.uniq.each_with_index {
        |cookie, i|
        cookies_arr[i] = Hash.new

        cookie.instance_variables.each {
            |var|
            value = cookie.instance_variable_get( var ).to_s
            value.strip!

            key = normalize_name( var )
            val = value.gsub( /[\"\\\[\]]/, '' )

            next if val == seed
            cookies_arr[i][key] = val
        }

        # cookies.reject!{ |cookie| cookie['name'] == cookies_arr[i]['name'] }

        cookies_arr[i] = Element::Cookie.new( @url, cookies_arr[i] )
    }
    cookies_arr.flatten!
    return cookies_arr
end

#dir(url) ⇒ Object



456
457
458
# File 'lib/arachni/parser/parser.rb', line 456

def dir( url )
    URI( File.dirname( URI( url.to_s ).path ) + '/' )
end

#docObject



179
180
181
182
# File 'lib/arachni/parser/parser.rb', line 179

def doc
  return @doc if @doc
  @doc = Nokogiri::HTML( @html ) if @html rescue nil
end

#exclude?(url) ⇒ Boolean

Returns:

  • (Boolean)


598
599
600
601
602
603
604
605
# File 'lib/arachni/parser/parser.rb', line 598

def exclude?( url )
    @opts.exclude.each {
        |pattern|
        return true if url.to_s =~ pattern
    }

    return false
end

#extract_domain(url) ⇒ String

Extracts the domain from a URI object

Parameters:

  • url (URI)

Returns:



587
588
589
590
591
592
593
594
595
596
# File 'lib/arachni/parser/parser.rb', line 587

def extract_domain( url )

    if !url.host then return false end

    splits = url.host.split( /\./ )

    if splits.length == 1 then return true end

    splits[-2] + "." + splits[-1]
end

#forms(html = nil) ⇒ Array<Element::Form>

TODO: Add support for radio buttons.

Extracts forms from HTML document

Parameters:

  • html (String) (defaults to: nil)

Returns:

See Also:

  • #form_attrs
  • #form_textareas
  • #form_selects
  • #form_inputs
  • #merge_select_with_input


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

def forms( html = nil )

    elements = []

    begin
        html = html || @html.clone
        #
        # This imitates Firefox's behavior when it comes to
        # broken/unclosed form tags
        #

        # get properly closed forms
        forms = html.scan( /<form(.*?)<\/form>/ixm ).flatten

        # now remove them from html...
        forms.each { |form| html.gsub!( form, '' ) }

        # and get unclosed forms.
        forms |= html.scan( /<form (.*)(?!<\/form>)/ixm ).flatten

    rescue Exception => e
        return elements
    end

    i = 0
    forms.each {
        |form|

        elements[i] = Hash.new
        elements[i]['attrs']    = form_attrs( form )

        if( !elements[i]['attrs'] || !elements[i]['attrs']['action'] )
            action = @url.to_s
        else
            action = url_sanitize( elements[i]['attrs']['action'] )
        end
        action = uri_encode( action ).to_s

        elements[i]['attrs']['action'] = to_absolute( action.clone ).to_s

        if( !elements[i]['attrs']['method'] )
            elements[i]['attrs']['method'] = 'post'
        else
            elements[i]['attrs']['method'] =
                elements[i]['attrs']['method'].downcase
        end

        next if skip?( elements[i]['attrs']['action'] )

        elements[i]['textarea'] = form_textareas( form )
        elements[i]['select']   = form_selects( form )
        elements[i]['input']    = form_inputs( form )

        # merge the form elements to make auditing easier
        elements[i]['auditable'] =
            elements[i]['input'] | elements[i]['textarea']

        elements[i]['auditable'] =
            merge_select_with_input( elements[i]['auditable'],
                elements[i]['select'] )

        elements[i] = Element::Form.new( @url, elements[i] )


        i += 1
    }

    elements.reject {
        |form|
        !form.is_a?( Element::Form ) || form.auditable.empty?
    }
end

#headersHash

Returns a list of valid auditable HTTP header fields.

It’s more of a placeholder method, it doesn’t actually analyze anything.<br/> It’s a long shot that any of these will be vulnerable but better be safe than sorry.

Returns:

  • (Hash)

    HTTP header fields



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/arachni/parser/parser.rb', line 247

def headers
    headers_arr  = []
    {
        'accept'          => 'text/html,application/xhtml+xml,application' +
            '/xml;q=0.9,*/*;q=0.8',
        'accept-charset'  => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
        'accept-language' => 'en-gb,en;q=0.5',
        'accept-encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
        'from'       => @opts.authed_by || '',
        'user-agent' => @opts.user_agent || '',
        'referer'    => @url,
        'pragma'     => 'no-cache'
    }.each {
        |k,v|
        headers_arr << Element::Header.new( @url, { k => v } )
    }

    return headers_arr
end

#in_domain?(uri) ⇒ Boolean

Returns true if uri is in the same domain as the page, returns false otherwise

Returns:

  • (Boolean)


569
570
571
572
573
574
575
576
577
578
# File 'lib/arachni/parser/parser.rb', line 569

def in_domain?( uri )

    curi = URI.parse( normalize_url( uri.to_s ) )

    if( @opts.follow_subdomains )
        return extract_domain( curi ) ==  extract_domain( URI( @url.to_s ) )
    end

    return curi.host == URI.parse( normalize_url( @url.to_s ) ).host
end

#include?(url) ⇒ Boolean

Returns:

  • (Boolean)


607
608
609
610
611
612
613
614
615
616
# File 'lib/arachni/parser/parser.rb', line 607

def include?( url )
    return true if @opts.include.empty?

    @opts.include.each {
        |pattern|
        pattern = Regexp.new( pattern ) if pattern.is_a?( String )
        return true if url.to_s =~ pattern
    }
    return false
end

Extracts variables and their values from a link

Parameters:

Returns:

  • (Hash)

    name=>value pairs

See Also:



483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
# File 'lib/arachni/parser/parser.rb', line 483

def link_vars( link )
    if !link then return {} end

    var_string = link.split( /\?/ )[1]
    if !var_string then return {} end

    var_hash = Hash.new
    var_string.split( /&/ ).each {
        |pair|
        name, value = pair.split( /=/ )

        next if value == seed
        var_hash[name] = value
    }

    var_hash

end

Extracts links from HTML document

Parameters:

Returns:

See Also:



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

def links

    link_arr = []
    elements_by_name( 'a' ).each_with_index {
        |link|

        link['href'] = to_absolute( link['href'] )

        if !link['href'] then next end
        next if skip?( link['href'] )

        link['vars'] = {}
        link_vars( link['href'] ).each_pair {
            |key, val|
            begin
                link['vars'][key] = url_sanitize( val )
            rescue
                link['vars'][key] = val
            end
        }

        link['href'] = url_sanitize( link['href'] )

        link_arr << Element::Link.new( @url, link )

    }

    return link_arr
end

#merge_with_cookiejar(cookies) ⇒ Array<Element::Cookie>

Merges ‘cookies’ with the cookiejar and returns it as an array

Parameters:

Returns:



222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/arachni/parser/parser.rb', line 222

def merge_with_cookiejar( cookies )
    return cookies if !@opts.cookies

    @opts.cookies.each_pair {
        |name, value|
        cookies << Element::Cookie.new( @url,
            {
                'name'    => name,
                'value'   => value
            } )
    }

    return cookies
end

#merge_with_cookiestore(cookies) ⇒ Object



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

def merge_with_cookiestore( cookies )

    @cookiestore ||= []

    if @cookiestore.empty?
        @cookiestore = cookies
    else
        tmp = {}
        @cookiestore.each {
            |cookie|
            tmp.merge!( cookie.simple )
        }

        cookies.each {
            |cookie|
            tmp.merge!( cookie.simple )
        }

        @cookiestore = tmp.map {
            |name, value|
            Element::Cookie.new( @url, {
                'name'    => name,
                'value'   => value
            } )
        }
    end

    return @cookiestore

end

#pathsArray<URI>

Array of distinct links to follow

Returns:



465
466
467
468
469
470
471
472
# File 'lib/arachni/parser/parser.rb', line 465

def paths
  return @paths unless @paths.nil?
  @paths = []
  return @paths if !doc

  @paths = run_extractors
  return @paths
end

#runPage

Runs the Analyzer and extracts forms, links and cookies

Returns:



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

def run

    # non text files won't contain any auditable elements
    if !text?
        return Page.new( {
            :code        => @code,
            :url         => @url,
            :query_vars  => link_vars( @url ),
            :html        => @html,
            :headers     => [],
            :response_headers     => @response_headers,
            :paths       => [],
            :forms       => [],
            :links       => [],
            :cookies     => [],
            :cookiejar   => []
        } )
    end


    cookies_arr = cookies
    cookies_arr = merge_with_cookiejar( cookies_arr.flatten.uniq )

    jar = {}
    jar = @opts.cookies = Arachni::HTTP.parse_cookiejar( @opts.cookie_jar ) if @opts.cookie_jar

    preped = {}
    cookies_arr.each{ |cookie| preped.merge!( cookie.simple ) }

    jar = preped.merge( jar )

    c_links = links

    if !( vars = link_vars( @url ) ).empty?
        url = to_absolute( @url )
        c_links << Arachni::Parser::Element::Link.new( url, {
            'href' => url,
            'vars' => vars
        } )
    end

    return Page.new( {
        :code        => @code,
        :url         => @url,
        :query_vars  => link_vars( @url ),
        :html        => @html,
        :headers     => headers(),
        :response_headers     => @response_headers,
        :paths       => paths(),
        :forms       => @opts.audit_forms ? forms() : [],
        :links       => @opts.audit_links ? c_links : [],
        :cookies     => merge_with_cookiestore( merge_with_cookiejar( cookies_arr ) ),
        :cookiejar   => jar
    } )

end

#skip?(path) ⇒ Boolean

Returns:

  • (Boolean)


618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/arachni/parser/parser.rb', line 618

def skip?( path )
    return true if !path

    begin
        return true if !include?( path )
        return true if exclude?( path )
        return true if too_deep?( path )
        return true if !in_domain?( path )
    rescue
        true
    end
end

#text?Boolean

Returns:

  • (Boolean)


173
174
175
176
177
# File 'lib/arachni/parser/parser.rb', line 173

def text?
    type = Arachni::HTTP.content_type( @response_headers )
    return false if !type
    return type.to_s.substring?( 'text' )
end

#to_absolute(link) ⇒ String

Converts relative URL link into an absolute URL based on the location of the page

Parameters:

Returns:



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

def to_absolute( link )

    begin
        link = normalize_url( link )
        if uri_parser.parse( link ).host
            return link
        end
    rescue Exception => e
        # ap e
        # ap e.backtrace
        return nil
    end

    begin
        # remove anchor
        link = uri_encode( link.to_s.gsub( /#[a-zA-Z0-9_-]*$/,'' ) )

        if url = base
            base_url = uri_parser.parse( url )
        else
            base_url = uri_parser.parse( @url )
        end

        relative = uri_parser.parse( link )
        absolute = base_url.merge( relative )

        absolute.path = '/' if absolute.path && absolute.path.empty?

        return absolute.to_s
    rescue Exception => e
        # ap e
        # ap e.backtrace
        return nil
    end
end

#too_deep?(url) ⇒ Boolean

Returns:

  • (Boolean)


557
558
559
560
561
562
563
# File 'lib/arachni/parser/parser.rb', line 557

def too_deep?( url )
    if @opts.depth_limit > 0 && (@opts.depth_limit + 1) <= URI(url.to_s).path.count( '/' )
        return true
    else
        return false
    end
end