Module: BScan

Includes:
BscanHelper, Mailer
Defined in:
lib/bscan.rb

Constant Summary

Constants included from Mailer

Mailer::ATTACHMENT, Mailer::BODY, Mailer::HEADERS, Mailer::MARKER, Mailer::MESSAGE, Mailer::SIMPLE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Mailer

#pv, #send_email, #sv, #ver, #zip_encode

Methods included from BscanHelper

#do_scan, #esc, #get_url_host_port, #open_in_path, #prop, #search_path, #search_path_file, #send_only, #send_req, #set_len, #verify_response

Instance Attribute Details

#activityObject

Returns the value of attribute activity.



25
26
27
# File 'lib/bscan.rb', line 25

def activity
  @activity
end

#bscan_configObject (readonly)

Returns the value of attribute bscan_config.



27
28
29
# File 'lib/bscan.rb', line 27

def bscan_config
  @bscan_config
end

#modules_onlyObject (readonly)

Returns the value of attribute modules_only.



26
27
28
# File 'lib/bscan.rb', line 26

def modules_only
  @modules_only
end

#statObject

Returns the value of attribute stat.



28
29
30
# File 'lib/bscan.rb', line 28

def stat
  @stat
end

Instance Method Details

#evt_application_closingObject



181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/bscan.rb', line 181

def evt_application_closing
  begin
    Log 2,"BScan.evt_application_closing #{@bscan_config['bscan.smtp.server']} #{@bscan_config['bscan.smtp.to']}"
    @istream.close if @istream
    @stat['end_time'] = Time.now.strftime("%Y-%m-%d %H:%M:%S") 
    send_email if @bscan_config['bscan.smtp.server'] and @bscan_config['bscan.smtp.to']
    @log.close if @log
  rescue Exception => e
    Log 0, "BScan.evt_application_closing Exception: #{e.message}"
    Log 0, e.backtrace.join("\n")
 end
end

#evt_commandline_args(args) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/bscan.rb', line 51

def evt_commandline_args args
  init_stat
  @cmd_params ||= JSON.parse args[0]
  @ll =  @cmd_params['loglevel'].to_i

  lfile = @cmd_params['logfile']
  if lfile != nil
      begin
        @log = java.io.PrintStream.new(lfile)
      rescue Exception => e
        $stderr.puts("BScan.evt_register_callbacks  Error: can't open log file '#{lfile}', exception: #{e.message}")
        $stderr.puts(e.backtrace.join("\n"))
        Process.exit!(2)
      end
  else
    @log = $stdout
  end

  Log 2, "BScan.evt_commandline_args CMD_PARAMS: #{@cmd_params}"
  @cmd_params.each_pair do |k,v|
    Log 2,"BScan.evt_commandline_args #{k}:#{v}"
  end
end

#evt_http_message(tool_name, is_request, message_info) ⇒ Object



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

def evt_http_message(tool_name, is_request, message_info)
  super(tool_name, is_request, message_info)
  if tool_name == 'Scanner'
    if is_request
      Log 2, "#"*70, "# BScan.evt_http_message REQUEST: #{message_info.url.toString}, tool: #{tool_name}", "#"*70
      Log 3, "BScan.evt_http_message #{message_info.req_str}", ""
    else
      Log 2, "# BScan.evt_http_message RESPONSE CODE: #{message_info.statusCode}", ""
      Log 3, "BScan.evt_http_message #{message_info.rsp_str}", ""
    end
  end
  if tool_name == 'Spider'
   if not is_request
      @activity[0] = true
      https = message_info.getProtocol() == "https" ? true : false
      Log 2, "BScan.evt_http_message Passively scanning: #{message_info.url.to_string}"
      do_passive_scan(message_info.getHost(), message_info.getPort(), https, message_info.getRequest(),  message_info.getResponse())
      if (is_in_scope(message_info.url))
        Log 2, "BScan.evt_http_message Actively scanning: #{message_info.url.to_string}"
        isqi = do_active_scan(message_info.getHost(), message_info.getPort(), https, message_info.getRequest(), [])
        @queue.push(isqi)
        run_modules message_info
      end
   end
  end  
end

#evt_register_callbacks(cb) ⇒ Object



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

def evt_register_callbacks cb
  super(cb)
  begin
    
    Log 2, "="*30, "BScan.evt_register_callbacks registring, log = #{@cmd_params['logfile']}  ", "="*30 
    @bscan_config = @cmd_params['bscan_config']
    @burp_config = @cmd_params['burp_config']
    @issues = @bscan_config['bscan.issues']
    @modules_only = (@bscan_config['bscan.modules_only'] and @bscan_config['bscan.modules_only'] == 'true') 
    
    Log 1, "BScan.evt_register_callbacks No issues dir provided. Issues will not be logged." if not @issues
    if (@issues)
      begin 
        dt = Time.now.strftime("%y%m%d_%H%M%S")
        File.directory? @issues or %x{mkdir -p "#{@issues}"}
        @sstream = "#{@issues}/session.#{dt}.zip"
        ifile = "#{@issues}/issues.#{dt}.txt"
        @istream = java.io.PrintStream.new(ifile)
        @stat['issues'] = ifile
      rescue Exception => e
        Log 0, "BScan.evt_register_callbacks Can't create issues or session files, Exception: #{e.message}"
        Log 0,  e.backtrace.join("\n")
        exit_suite
      end
    end
        
    @queue ||= []
    @activity = [false]
    @inactivity_to = @bscan_config['bscan.inactivity_to']
    @inactivity_to ||= '30'
    @inactivity_to = @inactivity_to.to_i
    # Will exit if @activity = 0  and @queue is empty two times
    if @monitor == nil
      Log 2, "="*30, "BScan.evt_register_callbacks Starting Monitor", "="*30 
      @monitor = Thread.new(@queue, @activity) {|q,a|
        cnt=0;
        while (true) 
          sleep(@inactivity_to/2)        
          q.delete_if {|e| e.getPercentageComplete() == 100}
          if q.length == 0 and not a[0] 
            cnt += 1
          else
            cnt = 0
#            Log 2, "BScan.evt_register_callbacks QUEUE: #{q.length}, Activity: #{a[0]}"
          end
          if cnt > 1
#            Log 2, "BScan.evt_register_callbacks Scanning complete"
            exit_suite
            break
          end
          a[0] = false
        end
      }
    end  
   
    Log 2, '='*30, 'BScan.evt_register_callbacks Params', '='*30
    params = save_config
    params['target.scopeinclude0']='**empty**' # burp can store the previous scope somehow, thus need to clean
    @burp_config.each_pair do |k,v|
      params[k] = v
    end  
    load_config params
    params.each_pair {|k,v| Log 2,"#{k}:#{v}"} # if k =~ /^(scanner|spider)/}
   
   @modules ||= @bscan_config['bscan.modules']
   @modules ||= [] if not @modules
   @modules = [@modules] if not @modules.kind_of?(Array)
   
   mods = []
   @modules.each do |m|
     mods << m.split(',')
   end

   @modules = mods.flatten 
   
  urls = @bscan_config['bscan.url']
  Log 2, "BScan.evt_register_callbacks urls: #{@modules_only} #{urls}"

   run_modules # run_modules without 'msg' will do static reqs only 
   return if @modules_only

    if not urls
     Log 0, "BScan.evt_register_callbacks No URL's provided in config. Use bscan.url param. Multiple entries are OK"
     exit_suite 
    end
    
    urls = [urls] if not urls.kind_of?(Array)
    
    urls.each do |u|
      Log 2, "BScan.evt_register_callbacks checking url: #{u}"
      if not is_in_scope(u)
        Log 2, "BScan.evt_register_callbacks including url: #{u}"
        include_in_scope(u)
      end
      Log 2, "BScan.evt_register_callbacks Sending to spider: #{u}"
      send_to_spider(u)
    end
  end
rescue Exception => e
      Log 0, "BScan.evt_register_callbacks Exception: #{e.message}"
      Log 0,  e.backtrace.join("\n")
      exit_suite
end

#evt_scan_issue(issue) ⇒ Object



142
143
144
145
146
# File 'lib/bscan.rb', line 142

def evt_scan_issue issue
  super(issue)
#    Buby::HttpRequestResponseHelper.implant(issue.http_messages)
  write_issue_state issue
end

#is_module_static(n, p) ⇒ Object



104
105
106
107
108
# File 'lib/bscan.rb', line 104

def is_module_static n,p
  pref = 'bscan.' + n + '.'
  pref += p + '.' if p and p.length > 0
  @bscan_config[pref + 'static_request'] == 'true'  
end

#Log(mtype, *msgs) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/bscan.rb', line 30

def Log (mtype, *msgs)
  pr = "Unknown:"
  case mtype
  when 0
    pr = "ERROR:"
  when 1
    pr = "WARN:"
  when 2
    pr = "INFO:"
  when 3
    pr = "DEBUG:"
  end  
  msgs.each do |msg|
    if (@ll >= mtype)
      dt = Time.now.strftime("%y%m%d %H%M%S")
      @log.println "#{dt} #{pr} #{msg}"
    end
  end
  @log.flush
end

#run_modules(msg = nil) ⇒ Object



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

def run_modules msg=nil
  if @modules 
    @modules.each do |m|
      begin
        mod,prop=m.split(':',2)
        prop ||=''
        mn = File.basename(mod,".rb")
        is_static = is_module_static(mn,prop)
        Log 2, "BScan.run_modules executing module #{mod}:#{prop} #{is_static}"
        mn.camelize!
        if (is_static && !msg) || (!is_static && msg)
          eval("
#           puts '=====================MODULE PATH: ' + $:.join(':') 
          require '#{mod}'
          require 'bscan/utils/bscan_helper.rb'
          
          class #{mn}#{prop}Class
            include #{mn}
            include BscanHelper
          end
          #{mn}#{prop}Class.new.run(self, msg, prop)
          ")
        end
      rescue Exception => e
        Log 1, "BScan.run_modules Can't exceute module #{mod}, Exception: #{e.message}"
        Log 1, e.backtrace.join("\n")
      end
    end
  end
end

#sync_save_state(issue) ⇒ Object



148
149
150
151
152
153
# File 'lib/bscan.rb', line 148

def sync_save_state issue
  @sync_state_mutex ||= Mutex.new
  @sync_state_mutex.synchronize {
    save_state(@sstream) if @sstream and issue.severity =~ /(High)/
  }
end

#write_issue_state(issue) ⇒ Object



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

def write_issue_state issue
#   Log 2,"INSPECT: #{issue.http_messages[0].methods}  #{issue.http_messages[0].inspect}  #{issue.http_messages[0].to_s} "
  
  @stat['high'] += 1 if issue.severity =~ /High/i
  @stat['med'] += 1 if issue.severity =~ /Med/i
  @stat['low'] += 1 if issue.severity =~ /Low/i
  @stat['urls'] += "  #{issue.url}\n"
  
  Log 2,"BScan.write_issue_state #{not @istream} #{issue.http_messages[0].methods}  #{issue.http_messages[0].to_s} "
  @istream or return
  begin 
    @istream.println '#'*70
    @istream.println "#{issue.issue_name} : #{issue.url}"
    @istream.println "Severity: #{issue.severity}(#{issue.confidence})"
    @istream.println "Background: #{issue.issue_background}"
    @istream.println "Details: #{issue.issue_detail}" 
    @istream.println "Remediation: #{issue.remediation_background}"
    @istream.println "Request: #{issue.http_messages[0].req_str}" 
    @istream.println "Response: #{issue.http_messages[0].rsp_str}"
    # sync_save_state issue throws exceptions
    @istream.flush 
  rescue Exception => e
    Log 0, "BScan.write_issue_state Can't write issue #{issue.issue_name}, Exception: #{e.message}"
    Log 0,  e.backtrace.join("\n")
  end
end