Class: Arachni::Plugins::Proxy

Inherits:
Arachni::Plugin::Base show all
Defined in:
components/plugins/proxy/template_scope.rb,
components/plugins/proxy.rb

Overview

Passive proxy.

Will gather data based on user actions and exchanged HTTP traffic and push that data to Framework#push_to_page_queue to be audited.

Author:

Defined Under Namespace

Classes: TemplateScope

Constant Summary collapse

BASEDIR =
"#{File.dirname( __FILE__ )}/proxy/"
BASE_URL =
'http://arachni.proxy/'
MSG_SHUTDOWN =
'Shutting down the Arachni proxy plug-in...'
MSG_DISALLOWED =
'You can\'t access this resource via the Arachni ' +
'proxy plug-in for the following reasons:'
MSG_NOT_IN_DOMAIN =
'This resource is on a domain or subdomain' +
' outside the scope of the audit.'
MSG_EXCLUDED =
'This resource is matched by an exclude rule.'
MSG_NOT_INCLUDED =
'This resource is disallowed based on an include rule.'
'arachni.proxy.session_token'

Constants included from Arachni

BANNER, Cookie, Form, Header, JSON, Link, LinkTemplate, NestedCookie, Severity, UIForm, UIInput, VERSION, WEBSITE, WIKI, XML

Instance Attribute Summary

Attributes inherited from Arachni::Plugin::Base

#framework, #options

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Arachni::Plugin::Base

#browser_cluster, distributable, distributable?, #framework_abort, #framework_pause, #framework_resume, gems, #http, #info, #initialize, is_distributable, merge, #register_results, #restore, #session, #suspend, #wait_while_framework_running, #with_browser

Methods inherited from Component::Base

author, description, fullname, #shortname, shortname, shortname=, version

Methods included from Component::Output

#depersonalize_output, #depersonalize_output?, #intercept_print_message

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

Methods included from Component::Utilities

#read_file

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_path?, #skip_resource?, #skip_response?, #to_absolute, #uri_decode, #uri_encode, #uri_parse, #uri_parse_query, #uri_parser, #uri_rewrite

Methods included from Arachni

URI, collect_young_objects, #get_long_win32_filename, jruby?, null_device, profile?, windows?

Constructor Details

This class inherits a constructor from Arachni::Plugin::Base

Class Method Details

.infoObject


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
# File 'components/plugins/proxy.rb', line 493

def self.info
    {
        name:        'Proxy',
        description: %q{
* Gathers data based on user actions and exchanged HTTP
traffic and pushes that data to the framework's page-queue to be audited.
* Updates the framework cookies with the cookies of the HTTP requests and
responses, thus it can also be used to login to a web application.
* Supports SSL interception.
* Authorization via a configurable session token.

**MANAGEMENT**

* [Control panel](http://arachni.proxy/panel)
* [Shutdown URL](http://arachni.proxy/shutdown)

_The above URLs will only work from a browser configured to use the proxy._

**SSL**

When browsing HTTPS sites, please accept the Arachni SSL certificate or install
the CA certificate manually from:

%s

**INFO**

To skip crawling and only audit elements discovered by using the proxy
set the scope page-limit option to '0'.

**NOTICE**

The `session_token` will be looked for in a cookie named
`arachni.proxy.session_token`, so if you choose to use a token to restrict
access to the proxy and need to pass traffic through the proxy programmatically
please configure your HTTP client with a cookie named `arachni.proxy.session_token`
with the value of the 'session_token' option.

**WARNING**

The `session_token` option is not a way to secure usage of this proxy but rather
a way to restrict usage enough to avoid users unwittingly interfering with each
others' sessions.
} % Arachni::HTTP::ProxyServer::SSLInterceptor::CA_CERTIFICATE,
        author:      'Tasos "Zapotek" Laskos <[email protected]>',
        version:     '0.4',
        options:     [
            Options::Port.new( :port,
                description: 'Port to bind to.',
                default:     8282
            ),
            Options::Address.new( :bind_address,
                description: 'IP address to bind to.',
                # Don't use 0.0.0.0, it breaks SSL interception on MS Windows.
                default:     '127.0.0.1'
            ),
            Options::Bool.new( :ignore_responses,
                description: 'Forces the proxy to only extract vector '+
                    'information from observed HTTP requests and not analyze responses.',
                default: false
            ),
            Options::String.new( :session_token,
                description: 'A session token to demand from users before allowing them to use the proxy.'
            ),
            Options::Int.new( :timeout,
                description: 'How long to wait for a request to complete, in milliseconds.',
                default:     20000
            )
        ]
    }
end

.url_for(type) ⇒ Object


481
482
483
484
485
486
487
488
# File 'components/plugins/proxy.rb', line 481

def self.url_for( type )
    {
        shutdown: "#{BASE_URL}shutdown",
        panel:    "#{BASE_URL}panel",
        inspect:  "#{BASE_URL}panel/inspect",
        sign_in:  "#{BASE_URL}sign_in",
    }[type]
end

Instance Method Details

#asset?(url) ⇒ Boolean

Returns:

  • (Boolean)

475
476
477
478
479
# File 'components/plugins/proxy.rb', line 475

def asset?( url )
    url.start_with?( "#{url_for( :panel )}/css/" ) ||
        url.start_with?( "#{url_for( :panel )}/js/" ) ||
        url.start_with?( "#{url_for( :panel )}/img/" )
end

#clean_upObject


81
82
83
84
85
86
87
88
89
90
91
92
# File 'components/plugins/proxy.rb', line 81

def clean_up
    return if @cleaned_up
    @cleaned_up = true

    @server.shutdown

    @pages_mutex.synchronize do
        @pages.each { |p| framework.push_to_page_queue( p, true ) }
    end

    framework_resume
end

#erb(*args) ⇒ Object


449
450
451
452
453
454
# File 'components/plugins/proxy.rb', line 449

def erb( *args )
    TemplateScope.get.erb( *args )
rescue => e
    ap e
    ap e.backtrace
end

#find_login_formArray<Arachni::Element::Form>

Tries to determine which form is the login one from the logged requests in the recorded login sequence.


314
315
316
317
318
319
320
# File 'components/plugins/proxy.rb', line 314

def 
    @login_sequence.each do |r|
        form = ( r )
        return form if form
    end
    nil
end

#find_login_form_from_request(request) ⇒ Array<Arachni::Element::Form>

Goes through all forms which contain password fields and tries to match them to the given request.

Parameters:

Returns:

See Also:


330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'components/plugins/proxy.rb', line 330

def ( request )
    return if (params = request_parse_body( request.body )).empty?

    f = @pages_mutex.synchronize do
        session.(
            pages:  @pages.to_a,
            action: normalize_url( request.url ),
            inputs: params.keys
        )
    end

    return if !f
    f.update( params )
end

#forms_with_passwordArray<Arachni::Element::Form>

Goes through the logged pages and returns all forms which contain password fields


349
350
351
352
353
# File 'components/plugins/proxy.rb', line 349

def forms_with_password
    @pages_mutex.synchronize do
        @pages.map { |p| p.forms.select { |f| f.requires_password? } }.flatten
    end
end

#ignore_responses?Boolean

Returns:

  • (Boolean)

456
457
458
# File 'components/plugins/proxy.rb', line 456

def ignore_responses?
    @options[:ignore_responses]
end

#panel_iframeObject


429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'components/plugins/proxy.rb', line 429

def panel_iframe
    <<-HTML
        <style type='text/css'>
            .panel {
                left:   0px;
                top:    0px;
                margin: 0px;
                width:  100%;
                height: 50px;
                border: 0px;
                position:fixed;
            }
            body {
                padding-top: 40px;
            }
        </style>
        <iframe class='panel' src='#{TemplateScope::PANEL_URL}'></iframe>
    HTML
end

#prepareObject


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'components/plugins/proxy.rb', line 37

def prepare
    require_relative 'proxy/template_scope'

    @server = Arachni::HTTP::ProxyServer.new(
         address:          options[:bind_address],
         port:             options[:port],
         response_handler: method( :response_handler ),
         request_handler:  method( :request_handler ),
         timeout:          options[:timeout]
    )

    @pages       = Set.new
    @pages_mutex = Mutex.new
    @login_sequence = []

    framework_pause
end

#prepare_pages_for_inspectionObject


355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'components/plugins/proxy.rb', line 355

def prepare_pages_for_inspection
    @pages_mutex.synchronize do
        (@pages.map do |p|
            next if !p.text?
            p = p.dup

            %w(links forms cookies jsons xmls).each do |type|
                p.send(
                    "#{type}=",
                    p.send(type).reject { |e| e.inputs.empty? }
                )
            end

            if !(p.forms.any? || p.links.any? || p.cookies.any? || p.jsons.any? ||
                p.xmls.any?)
                next
            end

            p
        end).compact
    end
end

#record_startObject


302
303
304
305
# File 'components/plugins/proxy.rb', line 302

def record_start
    @login_sequence = []
    @record = true
end

#record_stopObject


306
307
308
# File 'components/plugins/proxy.rb', line 306

def record_stop
    @record = false
end

#recording?Boolean

Returns:

  • (Boolean)

298
299
300
# File 'components/plugins/proxy.rb', line 298

def recording?
    @record ||= false
end

#request_handler(req, res) ⇒ Object


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
# File 'components/plugins/proxy.rb', line 117

def request_handler( req, res )
    url = req.url

    if !system_url?( url ) && req.scope.out?
        print_info "Ignoring, out of scope: #{url}"
        return true
    end

    # Clear the template scope to prepare it for this request.
    TemplateScope.get.clear

    TemplateScope.get.set :page_count, prepare_pages_for_inspection.size
    TemplateScope.get.set :recording, recording?

    #
    # Bare with me 'cause this is gonna get weird.
    #
    # We need the session cookie to be set for both the domain of the scan
    # target (so that we'll be able to authorize every request) *and*
    # for the domain used for controlling the proxy via the panel
    # (so that we can check those requests too prevent another user
    # from shutting down the proxy).
    #
    p = URI( framework.options.url )

    # This is the URL we'll use to sign in and set the cookie for the
    # domain of the scan target.
     = "#{p.scheme}://#{p.host}/arachni.proxy.sign_in"

    TemplateScope.get.set :sign_in_url, 

    params = request_parse_body( req.body.to_s ).
        merge( uri_parse_query( url ) ) || {}

    print_status "Requesting #{url}"

    # This is a sign-in request.
    if params['session_token'] == options[:session_token].to_s
        # Set us up for the redirection that's coming.
        res.code = 302

        # Set the session cookie.
        res.headers['Set-Cookie'] = "#{SESSION_TOKEN_COOKIE}=#{options[:session_token]}; path=/"

        # This is the cookie-set request for the domain of the scan target domain...
        if url ==  && req.method == :post

            # ...now we need to set the cookie for the proxy control domain
            # so redirect us to its handler.
            res.headers['Location'] = "#{url_for( :sign_in )}?session_token=#{options[:session_token]}"

        # This is the cookie-set request for the domain of the proxy control domain...
        elsif url.start_with?( url_for( :sign_in ) )

            # ...time to send the user to the webapp.
            res.headers['Location'] = framework.options.url
        end

        return
    elsif requires_token?( url ) && !valid_session_token?( req )
        print_info MSG_DISALLOWED
        print_info '  * Request does not have a valid session token'

        # Unauthorized.
        res.code = 401
        set_response_body( res, erb( 'sign_in'.to_sym ) )

        return
    end

    if shutdown?( url )
        print_status 'Shutting down...'
        set_response_body( res, erb( :shutdown_message ) )
        clean_up
        return
    end

    @login_sequence << req if recording?

    # Avoid propagating the proxy's session cookie to the webapp.
    req.cookies.delete SESSION_TOKEN_COOKIE

    res.code = 200

    if url.start_with? url_for( :panel )
        TemplateScope.get.set :pages, prepare_pages_for_inspection

        body =  case '/' + res.parsed_url.path.split( '/' )[2..-1].join( '/' )
                    when '/'
                        erb :panel

                    when '/vectors.yml'
                        res.headers['Content-Type'] = 'application/x-yaml'

                        erb :vectors,
                            layout:  false,
                            format:  :yml,
                            vectors: vectors_yaml

                    when '/help'
                        erb :help

                    when '/record/start'
                        record_start
                        erb :panel

                    when '/record/stop'
                        record_stop
                        erb :verify_login_check, verify_fail: false, params: {
                            'url'     => framework.options.session.check_url,
                            'pattern' => framework.options.session.check_pattern
                        }

                    when '/verify/login_check'

                        if req.method != :post
                            erb :verify_login_check, verify_fail: false
                        else
                            framework.options.session.check_url     = params['url']
                            framework.options.session.check_pattern = params['pattern']

                            if !session.logged_in?
                                erb :verify_login_check,
                                    params:      params,
                                    verify_fail: true
                            else
                                erb :verify_login_sequence,
                                    params: params,
                                    form:   
                            end

                        end

                    when '/verify/login_sequence'
                         = 
                        session.configure(
                            url:    .url,
                            inputs: .inputs
                        )

                        logged_in = false
                        framework.http.sandbox do |http|
                            http.cookie_jar.clear
                            session.
                            logged_in = session.logged_in?
                        end

                        erb :verify_login_final, ok: logged_in

                    else
                        res.headers['Cache-Control'] = 'max-age=2592000'
                        begin
                            IO.read TemplateScope::PANEL_BASEDIR + '/../' + res.parsed_url.path
                        rescue Errno::ENOENT
                            # forbidden
                            res.code = 404
                            erb '404_not_found'.to_sym
                        end
                    end.to_s
        set_response_body( res, body )
        return
    end

    true

rescue => e
    ap e
    ap e.backtrace
end

#requires_token?(url) ⇒ Boolean

Returns:

  • (Boolean)

287
288
289
# File 'components/plugins/proxy.rb', line 287

def requires_token?( url )
    !(asset?( url ) || url.start_with?( url_for( :sign_in ) ))
end

#response_handler(request, response) ⇒ Object

Called by the proxy for each response.


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
# File 'components/plugins/proxy.rb', line 379

def response_handler( request, response )
    return response if response.scope.out? || !response.text? ||
        response.code == 304

    if ignore_responses?
        page = Page.from_data(
            url:      response.url,
            response: response.to_h
        )
    else
        page = response.to_page
    end

    page = update_forms( page, request, response )

    print_info " *  #{page.forms.size} forms"
    print_info " *  #{page.links.size} links"
    print_info " *  #{page.cookies.size} cookies"
    print_info " *  #{page.jsons.size} JSON"
    print_info " *  #{page.xmls.size} XML"

    @pages_mutex.synchronize do
        @pages << page.dup
    end
end

#runObject


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
# File 'components/plugins/proxy.rb', line 55

def run
    print_status "Listening on: #{@server.url}"

    print_info "Control panel URL: #{url_for( :panel )}"
    print_info "Shutdown URL:      #{url_for( :shutdown )}"
    print_info 'The scan will resume once you visit the shutdown URL.'
    print_info
    print_info 'When browsing HTTPS sites, please accept the Arachni SSL certificate' +
        ' or install the CA certificate manually from:'
    print_info "    #{Arachni::HTTP::ProxyServer::SSLInterceptor::CA_CERTIFICATE}"
    print_info
    print_bad '**DO NOT** forget to revoke it after using the proxy, as it' +
        ' can be used by anyone to impersonate 3rd party servers.'
    print_info
    print_info '*' * 82
    print_info '* You need to clear your browser\'s cookies for this site before using the proxy! *'
    print_info '*' * 82
    print_info

    TemplateScope.get.set :params, {}

    @server.start_async

    wait_while_framework_running
end

#set_response_body(res, body) ⇒ Object


468
469
470
471
472
473
# File 'components/plugins/proxy.rb', line 468

def set_response_body( res, body )
    res.body = body
    res.headers['content-length'] = res.body.size.to_s
    res.headers['content-type'] = 'text/html' if body =~ /<(\s)*html(\s*)(.*?)>/i
    res
end

#shutdown?(url) ⇒ Boolean

Returns:

  • (Boolean)

464
465
466
# File 'components/plugins/proxy.rb', line 464

def shutdown?( url )
    url.to_s.start_with? url_for( :shutdown )
end

#system_url?(url) ⇒ Boolean

Returns:

  • (Boolean)

460
461
462
# File 'components/plugins/proxy.rb', line 460

def system_url?( url )
    url.start_with? BASE_URL
end

#update_forms(page, request, response) ⇒ Object


405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# File 'components/plugins/proxy.rb', line 405

def update_forms( page, request, response )
    if (json = Arachni::Element::JSON.from_request( response.url, request ))
        page.jsons |= [json]
        return page
    end

    if (xml = Arachni::Element::XML.from_request( response.url, request ))
        page.xmls |= [xml]
        return page
    end

    page.forms |= [Form.new(
        url:    response.url,
        action: response.url,
        method: request.method,
        inputs: request_parse_body( request.body.to_s )
    )]
    page

rescue => e
    ap e
    ap e.backtrace
end

#url_for(*args) ⇒ Object


489
490
491
# File 'components/plugins/proxy.rb', line 489

def url_for( *args )
    self.class.url_for( *args )
end

#valid_session_token?(request) ⇒ Boolean

Returns:

  • (Boolean)

291
292
293
294
295
296
# File 'components/plugins/proxy.rb', line 291

def valid_session_token?( request )
    session_token = options[:session_token]
    return true if session_token.to_s.empty?

    request.effective_cookies[SESSION_TOKEN_COOKIE] == session_token
end

#vectors_yamlObject


94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'components/plugins/proxy.rb', line 94

def vectors_yaml
    vectors = []
    prepare_pages_for_inspection.each do |page|
        page.elements.each do |element|
            next if element.inputs.empty?

            data = {
                type:   element.type,
                method: element.method,
                action: element.action,
                inputs: element.inputs
            }

            if element.respond_to? :source
                data[:source] = element.source
            end

            vectors << data
        end
    end
    vectors.to_yaml
end