Module: Dorothy

Defined in:
lib/dorothy2/BFM.rb,
lib/dorothy2.rb,
lib/dorothy2/NAM.rb,
lib/dorothy2/VSM.rb,
lib/dorothy2/vtotal.rb,
lib/dorothy2/do-init.rb,
lib/dorothy2/version.rb,
lib/dorothy2/Settings.rb,
lib/dorothy2/do-utils.rb,
lib/dorothy2/do-logger.rb

Overview

Copyright © 2010-2013 marco riccardi. This file is part of Dorothy - www.honeynet.it/dorothy See the file ‘LICENSE’ for copying permission.

Defined Under Namespace

Modules: DoroConfig, DoroSettings, Ssh, Util Classes: DoroLogger, Doro_NAM, Doro_VSM, DorothyFetcher, Insertdb, Loadmalw, Vtotal

Constant Summary collapse

VERSION =
"1.0.9"

Instance Method Summary collapse

Instance Method Details

#analyze(bin, guestvm) ⇒ Object

ANALYZE THE SOURCE



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

def analyze(bin, guestvm)

  #RESERVING AN ANALYSIS ID
  db = Insertdb.new
  anal_id = db.get_anal_id

  #set home vars
  sample_home = DoroSettings.env[:analysis_dir] + "/#{anal_id}"
  bin.dir_bin = "#{sample_home}/bin/"
  bin.dir_pcap = "#{sample_home}/pcap/"
  bin.dir_screens = "#{sample_home}/screens/"
  bin.dir_downloads = "#{sample_home}/downloads/"

  vm_log_header = "VM#{guestvm[0]} ".yellow + "[" + "#{anal_id}".red + "] "

  LOGGER.info "VSM", vm_log_header + "Analyzing binary #{bin.filename}"

  begin
    #crate dir structure in analisys home
    unless File.directory?(sample_home)
      LOGGER.info "VSM",vm_log_header + "Creating DIRS"
      Dir.mkdir sample_home
      Dir.mkdir bin.dir_bin
      Dir.mkdir bin.dir_pcap
      Dir.mkdir bin.dir_screens
      Dir.mkdir bin.dir_downloads

      if VERBOSE
        LOGGER.debug "VSM", sample_home
        LOGGER.debug "VSM",bin.dir_bin
        LOGGER.debug "VSM",bin.dir_pcap
        LOGGER.debug "VSM",bin.dir_screens
      end

    else
      LOGGER.warn "VSM",vm_log_header + "Malware #{bin.md5} sample_home already present, WTF!? Skipping.."
      #print "\n"
      return false
    end



    FileUtils.cp(bin.binpath,bin.dir_bin)  # mv?


    #Creating a new VSM object for managing the SandBox VM
    LOGGER.info "VSM",vm_log_header + "Connecting to ESX Server #{DoroSettings.esx[:host]}"

    vsm = Doro_VSM::ESX.new(DoroSettings.esx[:host],DoroSettings.esx[:user],DoroSettings.esx[:pass],guestvm[1], guestvm[3], guestvm[4])
    reverted = false


    #Copy File to VM
    r = 0

    begin
      vsm.check_internet
    rescue
      if r <= 2
        r = r+1
        LOGGER.warn "VSM",vm_log_header + " GUESTOS Connection problem to Internet, retry n. #{r}/3"
        sleep 20
        retry
      end
      LOGGER.error "VSM", vm_log_header + " Guest system is not able to connect to internet"
      r = 0
      retry
    end



    LOGGER.info "VSM",vm_log_header + "Copying #{bin.md5} to VM"

    filecontent = File.open(bin.binpath, "rb") { |byte| byte.read } #load filebinary
    vsm.copy_file(bin.filename,filecontent)

    #Start Sniffer
    dumpname = anal_id.to_s + "-" + bin.md5
    pid = @nam.start_sniffer(guestvm[2],DoroSettings.nam[:interface], dumpname, DoroSettings.nam[:pcaphome])
    LOGGER.info "NAM",vm_log_header + "Start sniffing module"
    LOGGER.debug "NAM",vm_log_header + "Tcpdump instance #{pid} started" if VERBOSE

    #sleep 5

    @screenshots = Array.new

    #Execute File into VM
    LOGGER.info "VSM",vm_log_header + "Executing #{bin.md5} with #{EXTENSIONS["prog_args"]}"

    if MANUAL
      LOGGER.debug "VSM",vm_log_header + " MANUAL mode detected. You can now logon to rdp:// "

      LOGGER.info "MANUAL-MODE",vm_log_header + "

        Choose your next action:
        1) Take Screenshot
        2) Take ProcessList
        3) Execute #{bin.filename}
        0) Continue and revert the machine.

        Select a nuber:"
      answer = gets.chop

      until answer == "0"
        case answer
          when "1" then
            @screenshots.push vsm.screenshot
            LOGGER.info "MANUAL-MODE",vm_log_header +  "Screenshot taken"
          when "2"
            @current_procs = vsm.get_running_procs
            LOGGER.info "MANUAL-MODE",vm_log_header +  "Current ProcessList taken"
          when "3"
            guestpid = vsm.exec_file("C:\\#{bin.filename}",EXTENSIONS[bin.extension])
            LOGGER.debug "MANUAL-MODE",vm_log_header + "Program executed with PID #{guestpid}"
          #when "x" then -- More interactive actions to add
          else
            LOGGER.info "MANUAL-MODE",vm_log_header +  "Please select a number"
        end
        answer = gets.chop
      end

      LOGGER.info "MANUAL-MODE",vm_log_header + "Moving forward.."


    else
      guestpid = vsm.exec_file("C:\\#{bin.filename}",EXTENSIONS[bin.extension])
      LOGGER.debug "VSM",vm_log_header + "Program executed with PID #{guestpid}" if VERBOSE
      sleep 1
      returncode = vsm.get_status(guestpid)
      raise "The program was not correctly executed into the Sandbox. Status code: #{returncode}" unless returncode == 0 || returncode.nil?

      LOGGER.info "VSM",vm_log_header + " Sleeping #{DoroSettings.sandbox[:sleeptime]} seconds".yellow
      sleep DoroSettings.sandbox[:screen1time] % DoroSettings.sandbox[:sleeptime]

      DoroSettings.sandbox[:num_screenshots].times do
        @screenshots.push vsm.screenshot
        sleep DoroSettings.sandbox[:screen2time] % DoroSettings.sandbox[:sleeptime]
      end

      sleep DoroSettings.sandbox[:sleeptime]

      #Get Procs
      @current_procs = vsm.get_running_procs

    end


    #Stop Sniffer, revert the VM
    stop_nam_revertvm(@nam, pid, vsm, guestvm[0], reverted, vm_log_header)

    vsm.revert_vm
    reverted = true

    #Analyze new procs
    LOGGER.info "VSM", vm_log_header + "Checking for spowned processes"

    unless @current_procs.nil?
      @procs = vsm.get_new_procs(@current_procs)
      if @procs.size > 0
        LOGGER.info "VSM", vm_log_header + "#{@procs.size} new process(es) found"
        @procs.each_key do |pid|
          LOGGER.info "VSM", vm_log_header + "[" + "+".red + "]" + " PID: #{pid}, NAME: #{@procs[pid]["pname"]}, COMMAND: #{@procs[pid]["cmdLine"]}"
        end
      end
    end

    #Downloading PCAP
    LOGGER.info "NAM", vm_log_header + "Downloading #{dumpname}.pcap to #{bin.dir_pcap}"
    Ssh.download(DoroSettings.nam[:host], DoroSettings.nam[:user],DoroSettings.nam[:pass], DoroSettings.nam[:pcaphome] + "/#{dumpname}.pcap", bin.dir_pcap)

    #Downloading Screenshots from esx
    LOGGER.info "NAM", vm_log_header + "Downloading Screenshots"

    @screenshots.each do |screen|
      Ssh.download(DoroSettings.esx[:host],DoroSettings.esx[:user], DoroSettings.esx[:pass], screen, bin.dir_screens)
      #Put them to 644
      File.chmod(0644, bin.dir_screens + File.basename(screen), bin.dir_screens + File.basename(screen) )
    end

    #UPDATE DOROTHIBE DB###################################

    dump = Loadmalw.new(bin.dir_pcap + dumpname + ".pcap")

    #TODO: dump.filname depends on the PCAPR pcaps path.
    #9/pcap/9-7bbf2e721d9b03988dc448344fd45a0c.pcap
    #pcapr_filename = anal_id + "/pcap/" + dump.filename


    if DoroSettings.pcapr[:local]
      pcapr_filename = "#{anal_id}/pcap/#{dump.filename}"
      pcaprid = Loadmalw.calc_pcaprid(pcapr_filename, dump.size).rstrip
    else
      pcaprid = Loadmalw.calc_pcaprid(dump.filename, dump.size).rstrip
    end

    LOGGER.debug "NAM", vm_log_header + "Pcaprid: " + pcaprid if VERBOSE

    empty_pcap = false

    if dump.size <= 30
      LOGGER.warn "NAM", vm_log_header + "WARNING - EMPTY PCAP FILE!!!! ::.."
      #FileUtils.rm_r(sample_home)
      empty_pcap = true
    end

    dumpvalues = [dump.sha, dump.size, pcaprid, dump.binpath, 'false']
    dump.sha = "EMPTYPCAP" if empty_pcap
    analysis_values = [anal_id, bin.sha, guestvm[0], dump.sha, get_time]

    if pcaprid.nil? || bin.dir_pcap.nil? || bin.sha.nil? || bin.md5.nil?
      LOGGER.error "VSM", "VM#{guestvm[0]} Can't retrieve the required information"
      raise "Some info missing.."
    end


    LOGGER.debug "DB", "VM#{guestvm[0]} Database insert phase" if VERBOSE

    db.begin_t  #needed for rollbacks
    in_transaction = true

    unless empty_pcap
      unless db.insert("traffic_dumps", dumpvalues)
        LOGGER.fatal "DB", "VM#{guestvm[0]} Error while inserting data into table traffic_dumps. Skipping binary #{bin.md5}"
        raise "DB-ERROR"
      end
    end



    unless db.insert("analyses", analysis_values)
      LOGGER.fatal "DB", vm_log_header + "Error while inserting data into table analyses. Skipping binary #{bin.md5}"
      raise "DB-ERROR"
    end

    @procs.each_key do |pid|
      @procs[pid]["endTime"] ? end_time = get_time(@procs[pid]["endTime"]) : end_time = "null"
      @procs[pid]["exitCode"] ? exit_code = @procs[pid]["exitCode"] : exit_code = "null"
      sys_procs_values = [anal_id, pid, @procs[pid]["pname"], @procs[pid]["owner"], @procs[pid]["cmdLine"], get_time(@procs[pid]["startTime"]), end_time, exit_code ]
      unless db.insert("sys_procs", sys_procs_values)
        LOGGER.fatal "DB", vm_log_header + "Error while inserting data into table sys_procs. Skipping binary #{bin.md5}"
        raise "DB-ERROR"
      end
    end


    #TODO ADD RT CODE

    db.commit
    in_transaction = false
    db.close

    LOGGER.info "VSM", vm_log_header + "Removing file from /bins directory"
    FileUtils.rm(bin.binpath)
    LOGGER.info "VSM", vm_log_header + "Process compleated successfully"

  rescue SignalException
    LOGGER.warn "DOROTHY", "SIGINT".red + " Catched, exiting gracefully."
    stop_nam_revertvm(@nam, pid, vsm, guestvm[0], reverted, vm_log_header)
    LOGGER.debug "VSM", vm_log_header + "Removing working dir"
    FileUtils.rm_r(sample_home)
    if in_transaction
      db.rollback  #rollback in case there is a transaction on going
      db.close
    end

  rescue Exception => e
    LOGGER.error "VSM", vm_log_header + "An error occurred while analyzing #{bin.filename}, skipping\n"
    LOGGER.debug "Dorothy" , "#{$!}\n #{e.inspect} \n #{e.backtrace}" if VERBOSE

    LOGGER.warn "Dorothy", vm_log_header + "Stopping NAM instances if presents, reverting the Sandbox, and removing working directory"

    stop_nam_revertvm(@nam, pid, vsm, guestvm[0], reverted, vm_log_header)
    LOGGER.debug "VSM", vm_log_header + "Removing working dir"

    FileUtils.rm_r(sample_home)

    if in_transaction
      db.rollback  #rollback in case there is a transaction on going
      db.close
    end

    LOGGER.warn "VSM", vm_log_header + "Recover finished."


  end

end

#check_support(bin) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/dorothy2.rb', line 71

def check_support(bin)
  if EXTENSIONS.key?(bin.extension)
    true
  else
    LOGGER.warn("VSM", "File extension #{bin.extension} currently not configured in etc/extensions.yml, skipping")
    LOGGER.debug("VSM", "Filtype: #{bin.type}") if VERBOSE
    dir_not_supported = File.dirname(bin.binpath) + "/not_supported"
    Dir.mkdir(dir_not_supported) unless File.exists?(dir_not_supported)
    FileUtils.cp(bin.binpath,dir_not_supported) #mv?
    FileUtils.rm(bin.binpath) ## mv?
    return false
  end
end

#get_time(local = Time.new) ⇒ Object



40
41
42
43
# File 'lib/dorothy2.rb', line 40

def get_time(local=Time.new)
  time = local
  time.utc.strftime("%Y-%m-%d %H:%M:%S")
end

#run_baselineObject

Create Baseline



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/dorothy2.rb', line 390

def run_baseline
  db = Insertdb.new
  guestvm = db.find_vm
  LOGGER.info "VSM","VM#{guestvm[0]}".red + " Executng the baseline run"
  vsm = Doro_VSM::ESX.new(DoroSettings.esx[:host],DoroSettings.esx[:user],DoroSettings.esx[:pass],guestvm[1], guestvm[3], guestvm[4])
  vsm.check_internet
  LOGGER.info "VSM","VM#{guestvm[0]}".red + " Sleeping #{DoroSettings.sandbox[:sleeptime]} seconds".yellow
  sleep DoroSettings.sandbox[:sleeptime]
  vsm.get_running_procs(nil, true)  #save on file
  LOGGER.info "VSM", "VM#{guestvm[0]} ".red + "Reverting VM".yellow
  vsm.revert_vm
  db.free_vm(guestvm[0])
  db.close
rescue => e
  LOGGER.error "VSM", "VM#{guestvm[0]} An error occurred while performing the BASELINE run, please retry"
  LOGGER.debug "Dorothy" , "#{$!}\n #{e.inspect} \n #{e.backtrace}" if VERBOSE
  LOGGER.warn "VSM", "VM#{guestvm[0]} ".red + "[RECOVER] Reverting VM".yellow
  vsm.revert_vm
  db.free_vm(guestvm[0])
  db.close
end

#start_analysis(bins) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/dorothy2.rb', line 46

def start_analysis(bins)
  @binum = bins.size
  bins.each do |bin|
    next unless check_support(bin)
    scan(bin) unless DoroSettings.env[:testmode]   #avoid to stress VT if we are just testing
    if MANUAL #no multithread
      db = Insertdb.new
      guestvm = db.find_vm
      analyze(bin, guestvm)
      db.free_vm(guestvm[0])
      db.close
    else      #Use multithreading
      @analysis_threads << Thread.new(bin.filename){
        db = Insertdb.new
        sleep rand(@binum * 2)  #OPTIMIZE #REVIEW
        sleep rand(30) while !(guestvm = db.find_vm)  #guestvm struct: array ["sandbox id", "sandbox name", "ipaddress", "user", "password"]
        analyze(bin, guestvm)
        db.free_vm(guestvm[0])
        db.close
      }
    end
  end
end

#stop_nam_revertvm(nam, pid, vsm, guestvm, reverted, vm_log_header) ⇒ Object

Stop NAM instance and Revert VM



375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/dorothy2.rb', line 375

def stop_nam_revertvm(nam, pid, vsm, guestvm, reverted, vm_log_header)

  if pid
    LOGGER.info "VSM", vm_log_header + " Stopping sniffing module " + pid.to_s
    nam.stop_sniffer(pid)
  end

  unless reverted || vsm.nil?
    LOGGER.info "VSM", vm_log_header + " Reverting VM"
    vsm.revert_vm
    sleep 3   #wait some seconds for letting the vm revert..
  end
end