Class: PEdump::CLI

Inherits:
Object show all
Defined in:
lib/pedump/cli.rb

Defined Under Namespace

Classes: ProgressProxy

Constant Summary collapse

KNOWN_ACTIONS =
(
  %w'mz dos_stub rich pe ne data_directory sections tls security' +
  %w'strings resources resource_directory imports exports version_info packer web packer_only'
).map(&:to_sym)
DEFAULT_ALL_ACTIONS =
KNOWN_ACTIONS - %w'resource_directory web packer_only'.map(&:to_sym)
URL_BASE =
"http://pedump.me"
COMMENTS =
{
  :Machine => {
    0x014c => 'x86',
    0x0200 => 'Intel Itanium',
    0x8664 => 'x64',
    'default' => '???'
  },
  :Magic => {
    0x010b => '32-bit executable',
    0x020b => '64-bit executable',
    0x0107 => 'ROM image',
    'default' => '???'
  },
  :Subsystem => PEdump::IMAGE_SUBSYSTEMS
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv = ARGV) ⇒ CLI

Returns a new instance of CLI.



52
53
54
# File 'lib/pedump/cli.rb', line 52

def initialize argv = ARGV
  @argv = argv
end

Instance Attribute Details

#argvObject

Returns the value of attribute argv.



41
42
43
# File 'lib/pedump/cli.rb', line 41

def argv
  @argv
end

#dataObject

Returns the value of attribute data.



41
42
43
# File 'lib/pedump/cli.rb', line 41

def data
  @data
end

Class Method Details

.hexdump(data, h = {}) ⇒ Object



779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/pedump/cli.rb', line 779

def self.hexdump data, h = {}
  offset = h[:offset] || 0
  add    = h[:add]    || 0
  size   = h[:size]   || (data.size-offset)
  tail   = h[:tail]   || "\n"
  width  = h[:width]  || 0x10                 # row width, in bytes

  size = data.size-offset if size+offset > data.size

  r = ''; s = ''
  r << "%08x: " % (offset + add)
  ascii = ''
  size.times do |i|
    if i%width==0 && i>0
      r << "%s |%s|\n%08x: " % [s, ascii, offset + add + i]
      ascii = ''; s = ''
    end
    s << " " if i%width%8==0
    c = data[offset+i].ord
    s << "%02x " % c
    ascii << ((32..126).include?(c) ? c.chr : '.')
  end
  r << "%-*s |%-*s|%s" % [width*3+width/8+(width%8==0?0:1), s, width, ascii, tail]
end

Instance Method Details

#_flags2string(flags) ⇒ Object



369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/pedump/cli.rb', line 369

def _flags2string flags
  return '' if !flags || flags.empty?
  a = [flags.shift.dup]
  flags.each do |f|
    if (a.last.size + f.size) < 40
      a.last << ", " << f
    else
      a << f.dup
    end
  end
  a.join("\n"+ ' '*58)
end

#action_title(action) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/pedump/cli.rb', line 270

def action_title action
  if @need_fname_header
    @need_fname_header = false
    puts if @file_idx > 0
    puts "# -----------------------------------------------"
    puts "# #@file_name"
    puts "# -----------------------------------------------"
  end

  s = action.to_s.upcase.tr('_',' ')
  s += " Header" if [:mz, :pe, :rich].include?(action)
  s = "Packer / Compiler" if action == :packer
  "\n=== %s ===\n\n" % s
end

#create_pedump(fname) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/pedump/cli.rb', line 156

def create_pedump fname
  PEdump.new(fname, :force => @options[:force]).tap do |x|
    x.logger.level =
      case @options[:verbose]
      when -100..-3
        Logger::FATAL + 1
      when -2
        Logger::FATAL
      when -1
        Logger::ERROR
      when 0
        Logger::WARN  # default
      when 1
        Logger::INFO
      when 2..100
        Logger::DEBUG
      end
  end
end

#dump(data, opts = {}) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/pedump/cli.rb', line 329

def dump data, opts = {}
  case opts[:format] || @options[:format] || :dump
  when :dump, :hexdump
    puts hexdump(data)
  when :hex
    puts data.each_byte.map{ |x| "%02x" % x }.join(' ')
  when :binary
    print data
  when :c
    name = opts[:name] || "foo"
    puts "// #{data.size} bytes total"
    puts "unsigned char #{name}[] = {"
    data.unpack('C*').each_slice(12) do |row|
      puts "  " + row.map{ |c| "0x%02x," % c}.join(" ")
    end
    puts "};"
  when :inspect
    require 'pp'
    pp data
  when :table
    dump_table data
  end
end

#dump_action(action, f) ⇒ Object



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
# File 'lib/pedump/cli.rb', line 285

def dump_action action, f
  if action.is_a?(Array)
    case action[0]
    when :va2file
      @pedump.sections(f)
      va = action[1] =~ /(^0x)|(h$)/i ? action[1].to_i(16) : action[1].to_i
      file_offset = @pedump.va2file(va)
      printf "va2file(0x%x) = 0x%x  (%d)\n", va, file_offset, file_offset
      return
    else raise "unknown action #{action.inspect}"
    end
  end

  data = @pedump.send(action, f)
  return if !data || (data.respond_to?(:empty?) && data.empty?)

  puts action_title(action)

  return dump(data) if [:inspect, :table].include?(@options[:format])

  dump_opts = {:name => action}
  case action
    when :pe
      data = @pedump.pe.pack
    when :resources
      return dump_resources(data)
    when :strings
      return dump_strings(data)
    when :imports
      return dump_imports(data)
    when :exports
      return dump_exports(data)
    when :version_info
      return dump_version_info(data)
    else
      if data.is_a?(Struct) && data.respond_to?(:pack)
        data = data.pack
      elsif data.is_a?(Array) && data.all?{ |x| x.is_a?(Struct) && x.respond_to?(:pack)}
        data = data.map(&:pack).join
      end
  end
  dump data, dump_opts
end

#dump_data_dir(data) ⇒ Object



753
754
755
756
757
# File 'lib/pedump/cli.rb', line 753

def dump_data_dir data
  data.each do |row|
    printf "  %-12s  rva:0x%8x   size:0x %8x\n", row.type, row.va.to_i, row.size.to_i
  end
end

#dump_exports(data) ⇒ Object



555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'lib/pedump/cli.rb', line 555

def dump_exports data
  printf "# module %s\n", data.name.inspect
  printf "# description %s\n", data.description.inspect if data.description

  if data.Characteristics || data.TimeDateStamp || data.MajorVersion || data.MinorVersion || data.Base
    printf "# flags=0x%x  ts=%s  version=%d.%d  ord_base=%d\n",
      data.Characteristics.to_i,
      Time.at(data.TimeDateStamp.to_i).utc.strftime('"%Y-%m-%d %H:%M:%S"'),
      data.MajorVersion.to_i, data.MinorVersion.to_i,
      data.Base.to_i
  end

  if @options[:verbose] > 0
    [%w'Names', %w'EntryPoints Functions', %w'Ordinals NameOrdinals'].each do |x|
      va  = data["AddressOf"+x.last]
      ofs = @pedump.va2file(va) || '?'
      printf("# %-12s rva=0x%08x  file_offset=%8s\n", x.first, va, ofs) if va
    end
  end

  if data.NumberOfFunctions || data.NumberOfNames
    printf "# nFuncs=%d  nNames=%d\n", data.NumberOfFunctions.to_i, data.NumberOfNames.to_i
  end

  if data.functions && data.functions.any?
    puts
    if @pedump.ne?
      printf "%5s %9s  %s\n", "ORD", "SEG:OFFS", "NAME"
      data.functions.each do |f|
        printf "%5x %4x:%04x  %s\n", f.ord, f.va>>16, f.va&0xffff, f.name
      end
    else
      printf "%5s %8s  %s\n", "ORD", "ENTRY_VA", "NAME"
      data.functions.each do |f|
        printf "%5x %8x  %s\n", f.ord, f.va, f.name
      end
    end
  end
end

#dump_generic_table(data) ⇒ Object



382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/pedump/cli.rb', line 382

def dump_generic_table data
  data.each_pair do |k,v|
    next if [:DataDirectory, :section_table].include?(k)
    case v
    when Numeric
      case k
      when /\AMajor.*Version\Z/
        printf "%30s: %24s\n", k.to_s.sub('Major',''), "#{v}.#{data[k.to_s.sub('Major','Minor')]}"
      when /\AMinor.*Version\Z/
      when /TimeDateStamp/
        printf "%30s: %24s\n", k, Time.at(v).utc.strftime('"%Y-%m-%d %H:%M:%S"')
      else
        comment = ''
        if COMMENTS[k]
          comment = COMMENTS[k][v] || (COMMENTS[k].is_a?(Hash) ? COMMENTS[k]['default'] : '') || ''
        elsif data.is_a?(PEdump::IMAGE_FILE_HEADER) && k == :Characteristics
          comment = _flags2string(data.flags)
        elsif k == :DllCharacteristics
          comment = _flags2string(data.flags)
        end
        comment.strip!
        comment = "  #{comment}" unless comment.empty?
        printf "%30s: %10d  %12s%s\n", k, v, v<10 ? v : ("0x"+v.to_s(16)), comment
      end
    when Struct
      # IMAGE_FILE_HEADER:
      # IMAGE_OPTIONAL_HEADER:
      printf "\n# %s:\n", v.class.to_s.split('::').last
      dump_table v
    when Time
      printf "%30s: %24s\n", k, v.strftime('"%Y-%m-%d %H:%M:%S"')
    else
      printf "%30s: %24s\n", k, v.to_s.inspect
    end
  end
end

#dump_imports(data) ⇒ Object



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# File 'lib/pedump/cli.rb', line 595

def dump_imports data
  fmt = "%-15s %5s %5s  %s\n"
  printf fmt, "MODULE_NAME", "HINT", "ORD", "FUNCTION_NAME"
  data.each do |x|
    case x
    when PEdump::IMAGE_IMPORT_DESCRIPTOR
      (Array(x.original_first_thunk) + Array(x.first_thunk)).uniq.each do |f|
        next unless f
        # imported function
        printf fmt,
          x.module_name,
          f.hint ? f.hint.to_s(16) : '',
          f.ordinal ? f.ordinal.to_s(16) : '',
          f.name
      end
    when PEdump::ImportedFunction
      printf fmt,
        x.module_name,
        x.hint ? x.hint.to_s(16) : '',
        x.ordinal ? x.ordinal.to_s(16) : '',
        x.name
    else
      raise "invalid #{x.inspect}"
    end
  end
end

#dump_ne_segments(data) ⇒ Object



743
744
745
746
747
748
749
750
# File 'lib/pedump/cli.rb', line 743

def dump_ne_segments data
  fmt = "%2x %6x %6x %9x %9x %6x  %s\n"
  printf fmt.tr('x','s'), *%w'# OFFSET SIZE MIN_ALLOC FILE_OFFS FLAGS', ''
  data.each_with_index do |seg,idx|
    printf fmt, idx+1, seg.offset, seg.size, seg.min_alloc_size, seg.file_offset, seg.flags,
      seg.flags_desc
  end
end

#dump_packer_only(fnames) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/pedump/cli.rb', line 176

def dump_packer_only fnames
  max_fname_len = fnames.map(&:size).max
  fnames.each do |fname|
    if File.directory?(fname)
      if @options[:recursive]
        dump_packer_only(Dir[File.join(fname.shellescape,"*")])
      else
        STDERR.puts "[?] #{fname} is a directory, and recursive flag is not set"
      end
    else
      File.open(fname,'rb') do |f|
        @pedump = create_pedump fname
        packers = @pedump.packers(f)
        pname = Array(packers).first.try(:packer).try(:name)
        pname ||= "unknown" if @options[:verbose] > 0
        printf("%-*s %s\n", max_fname_len+1, "#{fname}:", pname) if pname
      end
    end
  end
end

#dump_packers(data) ⇒ Object



544
545
546
547
548
549
550
551
552
553
# File 'lib/pedump/cli.rb', line 544

def dump_packers data
  if @options[:verbose] > 0
    data.each do |p|
      printf "%8x %4d %s\n", p.offset, p.packer.size, p.packer.name
    end
  else
    # show only largest detected unless verbose output requested
    puts "  #{data.first.packer.name}"
  end
end

#dump_res_dir(entry, level = 0) ⇒ Object



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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/pedump/cli.rb', line 632

def dump_res_dir entry, level = 0
  if entry.is_a?(PEdump::IMAGE_RESOURCE_DIRECTORY)
    # root entry
    printf "dir? %8s %8s %5s %5s",    "FLAGS", "TIMESTMP", "VERS", 'nEnt'
    printf " | %-15s %8s | ",         "NAME", "OFFSET"
    printf "data? %8s %8s %5s %8s\n", 'DATA_OFS', 'DATA_SZ', 'CP', 'RESERVED'
  end

  dir =
    case entry
    when PEdump::IMAGE_RESOURCE_DIRECTORY
      entry
    when PEdump::IMAGE_RESOURCE_DIRECTORY_ENTRY
      entry.data
    end

  fmt1  = "DIR: %8x %8x %5s %5d"
  fmt1s = fmt1.tr("xd\nDIR:","ss ") % ['','','','']

  if dir.is_a?(PEdump::IMAGE_RESOURCE_DIRECTORY)
    printf fmt1,
      dir.Characteristics, dir.TimeDateStamp,
      [dir.MajorVersion,dir.MinorVersion].join('.'),
      dir.NumberOfNamedEntries + dir.NumberOfIdEntries
  else
    print fmt1s
  end

  name =
    case level
    when 0 then "ROOT"
    when 1 then PEdump::ROOT_RES_NAMES[entry.Name] || entry.name
    else entry.name
    end

  printf " | %-15s", name
  printf("\n%s   %15s",fmt1s,'') if name.size > 15
  printf " %8x | ", entry.respond_to?(:OffsetToData) ? entry.OffsetToData : 0

  if dir.is_a?(PEdump::IMAGE_RESOURCE_DIRECTORY)
    puts
    dir.entries.each do |child|
      dump_res_dir child, level+1
    end
  elsif dir
    printf "DATA: %8x %8x %5s %8x\n", dir.OffsetToData, dir.Size, dir.CodePage, dir.Reserved
  else
    puts # null dir
  end
end

#dump_resources(data) ⇒ Object

def dump_res_dir0 dir, level=0, dir_entry = nil

  dir_entry ||= PEdump::IMAGE_RESOURCE_DIRECTORY_ENTRY.new
  printf "%-10s %8x %8x %8x %5s %5d\n", dir_entry.name || "ROOT", dir_entry.OffsetToData.to_i,
    dir.Characteristics, dir.TimeDateStamp,
    [dir.MajorVersion,dir.MinorVersion].join('.'),
    dir.NumberOfNamedEntries + dir.NumberOfIdEntries
  dir.entries.each do |child|
    if child.data.is_a?(PEdump::IMAGE_RESOURCE_DIRECTORY)
      dump_res_dir child.data, level+1, child
    else
      print "  "*(level+1) + "CHILD"
      child.data.each_pair do |k,v|
        print " #{k[0,2]}=#{v}"
      end
      puts
      #p child
    end
  end
end


703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
# File 'lib/pedump/cli.rb', line 703

def dump_resources data
  keys = []; fmt = []
  fmt << "%11x " ; keys << :file_offset
  fmt << "%5d "  ; keys << :cp
  fmt << "%5x "  ; keys << :lang
  fmt << "%8d  " ; keys << :size
  fmt << "%-13s "; keys << :type
  fmt << "%s\n"  ; keys << :name
  printf fmt.join.tr('dx','s'), *keys.map(&:to_s).map(&:upcase)
  data.each do |res|
    fmt.each_with_index do |f,i|
      if v = res.send(keys[i])
        if f['x']
          printf f.tr('x','s'), v.to_i < 10 ? v.to_s : "0x#{v.to_s(16)}"
        else
          printf f, v
        end
      else
        # NULL value
        printf f.tr('xd','s'), ''
      end
    end
  end
end

#dump_rich_hdr(data) ⇒ Object



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'lib/pedump/cli.rb', line 759

def dump_rich_hdr data
  if decoded = data.decode
    puts "    LIB_ID        VERSION        TIMES_USED   "
    decoded.each do |row|
      printf " %5d  %2x    %7d  %4x   %7d %3x\n",
        row.id, row.id, row.version, row.version, row.times, row.times
    end
  else
    puts "# raw:"
    puts hexdump(data)
    puts
    puts "# dexored:"
    puts hexdump(data.dexor)
  end
end

#dump_sections(data) ⇒ Object



728
729
730
731
732
733
734
735
736
737
738
739
740
741
# File 'lib/pedump/cli.rb', line 728

def dump_sections data
  printf "  %-8s %8s %8s %8s %8s %5s %8s %5s %8s  %8s\n",
    'NAME', 'RVA', 'VSZ','RAW_SZ','RAW_PTR','nREL','REL_PTR','nLINE','LINE_PTR','FLAGS'
  data.each do |s|
    name = s.Name[/[^a-z0-9_.]/i] ? s.Name.inspect : s.Name
    name = "#{name}\n          " if name.size > 8
    printf "  %-8s %8x %8x %8x %8x %5x %8x %5x %8x  %8x  %s\n", name.to_s,
      s.VirtualAddress.to_i,      s.VirtualSize.to_i,
      s.SizeOfRawData.to_i,       s.PointerToRawData.to_i,
      s.NumberOfRelocations.to_i, s.PointerToRelocations.to_i,
      s.NumberOfLinenumbers.to_i, s.PointerToLinenumbers.to_i,
      s.flags.to_i,               s.flags_desc
  end
end

#dump_security(data) ⇒ Object



458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/pedump/cli.rb', line 458

def dump_security data
  return unless data
  data.each do |win_cert|
    if win_cert.data.respond_to?(:certificates)
      win_cert.data.certificates.each do |cert|
        puts cert.to_text
        puts
      end
    else
      @pedump.logger.error "[?] no certificates in #{win_cert.class}"
    end
  end
end

#dump_strings(data) ⇒ Object



622
623
624
625
626
627
628
629
630
# File 'lib/pedump/cli.rb', line 622

def dump_strings data
  printf "%5s %5s  %4s  %s\n", "ID", "ID", "LANG", "STRING"
  prev_lang = nil
  data.sort_by{|s| [s.lang, s.id] }.each do |s|
    #puts if prev_lang && prev_lang != s.lang
    printf "%5d %5x  %4s  %s\n", s.id, s.id, s.lang && s.lang.to_s(16), s.value.inspect
    prev_lang = s.lang
  end
end

#dump_table(data) ⇒ Object



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
455
456
# File 'lib/pedump/cli.rb', line 419

def dump_table data
  if data.is_a?(Struct)
    return dump_res_dir(data) if data.is_a?(PEdump::IMAGE_RESOURCE_DIRECTORY)
    return dump_exports(data) if data.is_a?(PEdump::IMAGE_EXPORT_DIRECTORY)
    dump_generic_table data
  elsif data.is_a?(Enumerable) && data.map(&:class).uniq.size == 1
    case data.first
    when PEdump::IMAGE_DATA_DIRECTORY
      dump_data_dir data
    when PEdump::IMAGE_SECTION_HEADER
      dump_sections data
    when PEdump::Resource
      dump_resources data
    when PEdump::STRING
      dump_strings data
    when PEdump::IMAGE_IMPORT_DESCRIPTOR, PEdump::ImportedFunction
      dump_imports data
    when PEdump::Packer::Match
      dump_packers data
    when PEdump::VS_VERSIONINFO, PEdump::NE::VS_VERSIONINFO
      dump_version_info data
    when PEdump::IMAGE_TLS_DIRECTORY32, PEdump::IMAGE_TLS_DIRECTORY64
      dump_tls data
    when PEdump::WIN_CERTIFICATE
      dump_security data
    when PEdump::NE::Segment
      dump_ne_segments data
    else
      puts "[?] don't know how to dump: #{data.inspect[0,50]}" unless data.empty?
    end
  elsif data.is_a?(PEdump::DOSStub)
    puts hexdump(data)
  elsif data.is_a?(PEdump::RichHdr)
    dump_rich_hdr data
  else
    puts "[?] Don't know how to display #{data.inspect[0,50]}... as a table"
  end
end

#dump_tls(data) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/pedump/cli.rb', line 472

def dump_tls data
  fmt = "%10x %10x %8x  %8x  %8x  %8x\n"
  printf fmt.tr('x','s'), *%w'RAW_START RAW_END INDEX CALLBKS ZEROFILL FLAGS'
  data.each do |tls|
    printf fmt,
      tls.StartAddressOfRawData.to_i,
      tls.EndAddressOfRawData.to_i,
      tls.AddressOfIndex.to_i,
      tls.AddressOfCallBacks.to_i,
      tls.SizeOfZeroFill.to_i,
      tls.Characteristics.to_i
  end
end

#dump_version_info(data) ⇒ Object



486
487
488
489
490
491
492
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
# File 'lib/pedump/cli.rb', line 486

def dump_version_info data
  if @options[:format] != :table
    File.open(@file_name,'rb') do |f|
      @pedump.resources.find_all{ |r| r.type == 'VERSION'}.each do |res|
        f.seek res.file_offset
        data = f.read(res.size)
        dump data
      end
    end
    return
  end

  fmt = "  %-20s:  %s\n"
  data.each do |vi|
    puts "# VS_FIXEDFILEINFO:"

    if @options[:verbose] > 0 || vi.Value.dwSignature != 0xfeef04bd
      printf(fmt, "Signature", "0x#{vi.Value.dwSignature.to_i.to_s(16)}")
    end

    printf fmt, 'FileVersion', [
      vi.Value.dwFileVersionMS.to_i >> 16,
      vi.Value.dwFileVersionMS.to_i &  0xffff,
      vi.Value.dwFileVersionLS.to_i >> 16,
      vi.Value.dwFileVersionLS.to_i &  0xffff
    ].join('.')

    printf fmt, 'ProductVersion', [
      vi.Value.dwProductVersionMS.to_i >> 16,
      vi.Value.dwProductVersionMS.to_i &  0xffff,
      vi.Value.dwProductVersionLS.to_i >> 16,
      vi.Value.dwProductVersionLS.to_i &  0xffff
    ].join('.')

    vi.Value.each_pair do |k,v|
      next if k[/[ML]S$/] || k == :valid || k == :dwSignature
      printf fmt, k.to_s.sub(/^dw/,''), v.to_i > 9 ? "0x#{v.to_s(16)}" : v
    end

    vi.Children.each do |file_info|
      case file_info
      when PEdump::StringFileInfo, PEdump::NE::StringFileInfo
        file_info.Children.each do |string_table|
          puts "\n# StringTable #{string_table.szKey}:"
          string_table.Children.each do |string|
            printf fmt, string.szKey, string.Value.inspect
          end
        end
      when PEdump::VarFileInfo, PEdump::NE::VarFileInfo
        puts
        printf fmt, "VarFileInfo", '[ 0x' + file_info.Children.Value.map{|v| v.to_s(16)}.join(", 0x") + ' ]'
      else
        puts "[?] unknown child type: #{file_info.inspect}, use -fi to inspect"
      end
    end
  end
end

#hexdump(*args) ⇒ Object



775
776
777
# File 'lib/pedump/cli.rb', line 775

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

#runObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
146
147
148
149
150
151
152
153
154
# File 'lib/pedump/cli.rb', line 56

def run
  @actions = []
  @options = { :format => :table, :verbose => 0 }
  optparser = OptionParser.new do |opts|
    opts.banner = "Usage: pedump [options]"

    opts.on "--version", "Print version information and exit" do
      puts PEdump::VERSION
      exit
    end
    opts.on "-v", "--verbose", "Run verbosely","(can be used multiple times)" do |v|
      @options[:verbose] += 1
    end
    opts.on "-q", "--quiet", "Silent any warnings","(can be used multiple times)" do |v|
      @options[:verbose] -= 1
    end
    opts.on "-F", "--force", "Try to dump by all means","(can cause exceptions & heavy wounds)" do |v|
      @options[:force] ||= 0
      @options[:force] += 1
    end
    opts.on "-f", "--format FORMAT", [:binary, :c, :dump, :hex, :inspect, :table],
      "Output format: bin,c,dump,hex,inspect,table","(default: table)" do |v|
      @options[:format] = v
    end
    KNOWN_ACTIONS.each do |t|
      a = [
        "--#{t.to_s.tr('_','-')}",
        eval("lambda{ |_| @actions << :#{t.to_s.tr('-','_')} }")
      ]
      a.unshift(a[0][1,2].upcase) if a[0] =~ /--(((ex|im)port|section|resource)s|version-info)/
      a.unshift(a[0][1,2]) if a[0] =~ /--strings/
      opts.on *a
    end

    opts.on "--deep", "packer deep scan, significantly slower" do
      @options[:deep] ||= 0
      @options[:deep] += 1
      PEdump::Packer.default_deep = @options[:deep]
    end

    opts.on '-P', "--packer-only", "packer/compiler detect only,","mimics 'file' command output" do
      @actions << :packer_only
    end

    opts.on '-r', "--recursive", "recurse dirs in packer detect" do
      @options[:recursive] = true
    end

    opts.on "--all", "Dump all but resource-directory (default)" do
      @actions = DEFAULT_ALL_ACTIONS
    end
    opts.on "--va2file VA", "Convert RVA to file offset" do |va|
      @actions << [:va2file,va]
    end
    opts.on "-W", "--web", "Uploads files to a #{URL_BASE}","for a nice HTML tables with image previews,","candies & stuff" do
      @actions << :web
    end
  end

  if (@argv = optparser.parse(@argv)).empty?
    puts optparser.help
    return
  end

  if (@actions-KNOWN_ACTIONS).any?{ |x| !x.is_a?(Array) }
    puts "[?] unknown actions: #{@actions-KNOWN_ACTIONS}"
    @actions.delete_if{ |x| !KNOWN_ACTIONS.include?(x) }
  end
  @actions = DEFAULT_ALL_ACTIONS if @actions.empty?

  if @actions.include?(:packer_only)
    raise "[!] can't mix --packer-only with other actions" if @actions.size > 1
    dump_packer_only(argv)
    return
  end

  argv.each_with_index do |fname,idx|
    @need_fname_header = (argv.size > 1)
    @file_idx  = idx
    @file_name = fname

    File.open(fname,'rb') do |f|
      @pedump = create_pedump fname

      next if !@options[:force] && !@pedump.mz(f)

      @actions.each do |action|
        if action == :web
          upload f
        else
          dump_action action,f
        end
      end
    end
  end
rescue Errno::EPIPE
  # output interrupt, f.ex. when piping output to a 'head' command
  # prevents a 'Broken pipe - <STDOUT> (Errno::EPIPE)' message
end

#upload(f) ⇒ Object



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
# File 'lib/pedump/cli.rb', line 218

def upload f
  if @pedump.mz(f).signature != 'MZ'
    @pedump.logger.error "[!] refusing to upload a non-MZ file"
    return
  end

  require 'digest/md5'
  require 'open-uri'
  require 'net/http/post/multipart'
  require 'progressbar'

  stdout_sync = STDOUT.sync
  STDOUT.sync = true

  md5 = Digest::MD5.file(f.path).hexdigest
  @pedump.logger.info "[.] md5: #{md5}"
  file_url = "#{URL_BASE}/#{md5}/"

  @pedump.logger.info "[.] checking if file already uploaded.."
  begin
    if (r=open(file_url).read) == "OK"
      @pedump.logger.warn "[.] file already uploaded: #{file_url}"
      return
    else
      raise "invalid server response: #{r}"
    end
  rescue OpenURI::HTTPError
    raise unless $!.to_s == "404 Not Found"
  end

  f.rewind

  # upload with progressbar
  post_url = URI.parse(URL_BASE+'/')
  uio = UploadIO.new(f, "application/octet-stream", File.basename(f.path))
  ppx = ProgressProxy.new(uio)
  req = Net::HTTP::Post::Multipart.new post_url.path, "file" => ppx
  res = Net::HTTP.start(post_url.host, post_url.port){ |http| http.request(req) }
  ppx.pbar.finish

  puts
  puts "[.] analyzing..."

  if (r=open(File.join(URL_BASE,md5,'analyze')).read) != "OK"
    raise "invalid server response: #{r}"
  end

  puts "[.] uploaded: #{file_url}"
ensure
  STDOUT.sync = stdout_sync
end