Class: PEdump::CLI
Defined Under Namespace
Classes: ProgressProxy
Constant Summary collapse
- SHORTCUT_ACTIONS =
{ clr: i'clr_header clr_readytorun clr_metadata clr_streams clr_strings clr_tables', }
- ACTION_COMMENTS =
{}
- ACTION_ARGS =
{ clr_tables: "[TABLES]", }
- KNOWN_ACTIONS =
( i'mz dos_stub rich pe ne te data_directory clr_header clr_metadata clr_readytorun clr_streams clr_strings clr_tables sections tls security' + i'strings resources resource_directory imports exports version_info imphash packer web console packer_only' + i'extract tail' ) + SHORTCUT_ACTIONS.keys
- DEFAULT_ALL_ACTIONS =
KNOWN_ACTIONS - i'resource_directory web packer_only console extract disasm clr clr_tables' - SHORTCUT_ACTIONS.keys
- URL_BASE =
"https://pedump.me"- COMMENTS =
{ PEdump::IMAGE_FILE_HEADER => { Characteristics: Proc.new{ |v| _flags2string(v.flags) }, Machine: { 0x014c => 'x86', 0x0200 => 'Intel Itanium', 0x8664 => 'x64', default: '???' } }, PEdump::IMAGE_COR20_HEADER => { Flags: Proc.new{ |v| _flags2string(v.flags) }, }, PEdump::CLR::MetadataTableStreamHeader => { HeapSizes: Proc.new{ |v| _flags2string(v.heap_sizes) }, Valid: Proc.new{ |v| _flags2string(v.valid_flags) }, Sorted: Proc.new{ |v| _flags2string(v.sorted_flags) }, }, PEdump::CLR::READYTORUN_CORE_HEADER => { Flags: Proc.new{ |v| _flags2string(v.flags) }, }, }
Instance Attribute Summary collapse
-
#argv ⇒ Object
Returns the value of attribute argv.
-
#data ⇒ Object
Returns the value of attribute data.
-
#success ⇒ Object
Returns the value of attribute success.
Class Method Summary collapse
Instance Method Summary collapse
- #action_title(action) ⇒ Object
- #console(f) ⇒ Object
- #create_pedump(io) ⇒ Object
- #disasm(x) ⇒ Object
- #dump(data, opts = {}) ⇒ Object
- #dump_action(action, f) ⇒ Object
- #dump_clr_streams(data) ⇒ Object
- #dump_clr_tables(data) ⇒ Object
- #dump_data_dir(data) ⇒ Object
- #dump_efi_data_dir(data) ⇒ Object
- #dump_exports(data) ⇒ Object
- #dump_generic_table(data) ⇒ Object
- #dump_imports(data) ⇒ Object
- #dump_ne_segments(data) ⇒ Object
- #dump_packer_only(fnames) ⇒ Object
- #dump_packers(data) ⇒ Object
- #dump_res_dir(entry, level = 0) ⇒ Object
-
#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 %5dn”, 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 “ #0,2=#v” end puts #p child end end end.
- #dump_rich_hdr(data) ⇒ Object
- #dump_sections(data) ⇒ Object
- #dump_security(data) ⇒ Object
- #dump_strings(data) ⇒ Object
- #dump_table(data, opts = {}) ⇒ Object
- #dump_tls(data) ⇒ Object
- #dump_version_info(data) ⇒ Object
- #extract(x) ⇒ Object
- #extract_datadir(id) ⇒ Object
- #extract_resource(id) ⇒ Object
- #extract_section(id) ⇒ Object
- #extract_tail(offset) ⇒ Object
-
#initialize(argv = ARGV) ⇒ CLI
constructor
A new instance of CLI.
- #run ⇒ Object
- #set_dll_char(x) ⇒ Object
- #set_os_version(ver) ⇒ Object
- #upload(f) ⇒ Object
Constructor Details
#initialize(argv = ARGV) ⇒ CLI
Returns a new instance of CLI.
59 60 61 |
# File 'lib/pedump/cli.rb', line 59 def initialize argv = ARGV @argv = argv end |
Instance Attribute Details
#argv ⇒ Object
Returns the value of attribute argv.
34 35 36 |
# File 'lib/pedump/cli.rb', line 34 def argv @argv end |
#data ⇒ Object
Returns the value of attribute data.
34 35 36 |
# File 'lib/pedump/cli.rb', line 34 def data @data end |
#success ⇒ Object
Returns the value of attribute success.
34 35 36 |
# File 'lib/pedump/cli.rb', line 34 def success @success end |
Class Method Details
._flags2string(flags, max_width: 80) ⇒ Object
505 506 507 508 509 510 511 512 513 514 515 516 517 518 |
# File 'lib/pedump/cli.rb', line 505 def self._flags2string flags, max_width: 80 return '' if !flags || flags.empty? flags.map!{ |f| f.is_a?(String) ? f.dup : f.to_s } a = [flags.shift] flags.each do |f| if (a.last.size + f.size) < max_width a.last << ", " << f else a << f.dup end end a.join("\n"+ ' '*58) end |
Instance Method Details
#action_title(action) ⇒ Object
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/pedump/cli.rb', line 362 def action_title action if @need_fname_header @need_fname_header = false puts if @file_idx > 0 puts "# -----------------------------------------------" puts "# #@file_name" puts "# -----------------------------------------------" end action = action.first if action.is_a?(Array) s = action.to_s.upcase.tr('_',' ') s += " Header" if [:mz, :pe, :rich].include?(action) s = "Packer / Compiler" if action == :packer s = "imphash" if action == :imphash "\n=== %s ===\n\n" % s end |
#console(f) ⇒ Object
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/pedump/cli.rb', line 339 def console f require 'pedump/loader' require 'pp' ARGV.clear # clear ARGV so IRB is not confused require 'irb' f.rewind ldr = @ldr = PEdump::Loader.new(f) # override IRB.setup, called from IRB.start m0 = IRB.method(:setup) IRB.define_singleton_method :setup do |*args| m0.call *args conf[:IRB_RC] = Proc.new do |context| context.main.instance_variable_set '@ldr', ldr context.main.define_singleton_method(:ldr){ @ldr } end end puts "[.] ldr = PEdump::Loader.new(open(#{f.path.inspect}))".gray IRB.start end |
#create_pedump(io) ⇒ Object
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
# File 'lib/pedump/cli.rb', line 217 def create_pedump io PEdump.new(io, :force => [:force]).tap do |x| x.logger.level = case [: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 |
#disasm(x) ⇒ Object
1108 1109 1110 |
# File 'lib/pedump/cli.rb', line 1108 def disasm x puts "TODO" end |
#dump(data, opts = {}) ⇒ Object
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
# File 'lib/pedump/cli.rb', line 440 def dump data, opts = {} case opts[:format] || [:format] || :dump when :dump, :hexdump data.hexdump 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, opts when :yaml require 'yaml' puts data.to_yaml when :json require 'json' puts data.to_json end end |
#dump_action(action, f) ⇒ Object
380 381 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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 |
# File 'lib/pedump/cli.rb', line 380 def dump_action action, f data = nil got_data = false if action.is_a?(Array) case action[0] when :disasm return when :va2file, :file2va cmd = action[0] @pedump.sections(f) va = action[1] =~ /(^0x)|(h$)/i ? action[1].to_i(16) : action[1].to_i file_offset = @pedump.send(cmd, va) if file_offset printf("%s(0x%x) = 0x%x (%d)\n", cmd, va, file_offset, file_offset) else @success = false end return else if respond_to?(action[0]) return send(*action) else data = @pedump.send(*action) got_data = true end end end data = @pedump.send(action, f) unless got_data return if !data || (data.respond_to?(:empty?) && data.empty?) puts action_title(action) unless [:format] == :binary || @actions == [:imphash] return dump(data, action: action) if [:inspect, :table, :json, :yaml].include?([: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_clr_streams(data) ⇒ Object
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 |
# File 'lib/pedump/cli.rb', line 653 def dump_clr_streams data clr_header = @pedump.clr_header clr_data_file_ofs = clr_header.MetaData.va.to_i > 0 && @pedump.va2file(clr_header.MetaData.va) fmt = "%8x %8x %-32s\n" printf fmt.tr('x','s'), *%w'offset size name' data.each do |s| printf fmt, s.offset, s.size, s.name.inspect if clr_data_file_ofs && s.offset < clr_header.MetaData.size if s.name == "#-" || s.name == "#~" pos = clr_data_file_ofs + s.offset @pedump.io.seek(pos) hdr = PEdump::CLR::MetadataTableStreamHeader.read(@pedump.io) dump hdr end end end end |
#dump_clr_tables(data) ⇒ Object
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 |
# File 'lib/pedump/cli.rb', line 672 def dump_clr_tables data strings = @pedump.clr_strings rescue {} strings ||= {} blob_stream = @pedump.clr_streams.find{ |s| s.name == "#Blob" } clr_header = @pedump.clr_header clr_data_file_ofs = clr_header.MetaData.va.to_i > 0 && @pedump.va2file(clr_header.MetaData.va) blob_file_ofs = blob_stream.offset + clr_data_file_ofs if blob_stream blob_size = blob_stream&.size prev_signature = nil data.each do |key, table| table_idx = PEdump::CLR::MetadataTableStreamHeader::FLAGS.keys.index(key) printf "# %02x %s: [%d]\n", table_idx, key, table.size table.each_with_index do |row, idx| next if idx == 0 && row.nil? if [:tokens] token = (table_idx << 24) | idx printf "%08x: ", token else printf "%6x: ", idx end print row.to_table comments = [] if row.respond_to?(:decode_Class) table_key, idx = row.decode_Class if table_key && idx referred_row = data[table_key]&.at(idx) comments << referred_row&.get_name(strings) end end signature = nil if row.respond_to?(:Signature) && blob_file_ofs && blob_size && row.Signature < blob_size @pedump.io.seek(blob_file_ofs + row.Signature + 1) signature = PEdump::CLR::Signature.read(@pedump.io, key) end comments << row.get_name(strings) || row.to_s if comments.any? name_with_ns = comments.join(key == :MemberRef ? '.' : ' ') if signature prefix = if signature.respond_to?(:ret_type) "#{signature.ret_type} " elsif signature.respond_to?(:type) "#{signature.type} " else '' end suffix = '' if signature.respond_to?(:params) && signature.params suffix = '(' + signature.params.join(', ') + ')' end name_with_ns = prefix + name_with_ns + suffix name_with_ns.gsub!(/(?:CLASS|VALUE) (\h{7,8})/) do |orig| id = $1.to_i(16) table_id = id >> 24 table_key = PEdump::CLR::MetadataTableStreamHeader::FLAGS.keys[table_id] idx = id & 0xffffff referred_row = data[table_key]&.at(idx) referred_name = referred_row&.get_name(strings) || referred_row&.to_s referred_name || orig end name_with_ns.gsub!(/System\.Nullable\`1 <([^<>]+)>/, '\1?') end printf " %s", name_with_ns end puts if [:verbose] > 0 was = false h = row.to_h h.keys.each do |field_key| if row.respond_to?("decode_#{field_key}") was = true a = row.send("decode_#{field_key}") printf "%20s: %-20s", field_key, a.inspect table_key, idx = a if table_key && idx referred_row = data[table_key]&.at(idx) if referred_row printf "%s", referred_row.get_name(strings) || referred_row.to_s end end puts end if field_key == :Signature && signature && prev_signature != row.Signature printf "%20s: ", "Signature" @pedump.io.seek(blob_file_ofs + row.Signature + 1) sig_data = @pedump.io.read(32) # not real length puts sig_data.bytes.map{ |b| "%02x" % b }.join(' ') printf "%20s ", "" p signature was = true prev_signature = row.Signature end end puts if was end end puts end end |
#dump_data_dir(data) ⇒ Object
1078 1079 1080 1081 1082 |
# File 'lib/pedump/cli.rb', line 1078 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_efi_data_dir(data) ⇒ Object
1084 1085 1086 1087 1088 |
# File 'lib/pedump/cli.rb', line 1084 def dump_efi_data_dir data data.each_with_index do |row, idx| printf " %-12s rva:0x%8x size:0x %8x\n", PEdump::EFI_IMAGE_DATA_DIRECTORY::TYPES[idx], row.va.to_i, row.size.to_i end end |
#dump_exports(data) ⇒ Object
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 |
# File 'lib/pedump/cli.rb', line 880 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 [: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
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 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 |
# File 'lib/pedump/cli.rb', line 520 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[data.class] && cmt=COMMENTS[data.class][k] case cmt when Hash cmt[v] || cmt[:default] when Array cmt[v] when Proc cmt.call(data) else raise "invalid comment type: #{cmt.inspect}" end end comment ||= '' comment.strip! comment = " #{comment}" unless comment.empty? if v.to_s.size > 10 || v < 10 # don't show decimal printf "%30s: %6s %16s%s\n", k, "", v.to_s(16), comment else printf "%30s: %10d %12s%s\n", k, v, v.to_s(16), comment end end when PEdump::IMAGE_DATA_DIRECTORY # in CLR headers if v.va.to_i != 0 && v.size.to_i != 0 printf "%30s: {va: %x, size: %x}\n", k, v.va, v.size else printf "%30s:\n", k 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 if v.is_a?(Array) && v.all?{ |x| x.is_a?(Struct) } a = v printf "%30s: %24s\n", k, a[0] a[1..-1].each do |v| printf "%30s %24s\n", "", v end else printf "%30s: %24s\n", k, v.to_s.inspect end end end end |
#dump_imports(data) ⇒ Object
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 |
# File 'lib/pedump/cli.rb', line 920 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| (x.original_first_thunk || x.first_thunk).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
1069 1070 1071 1072 1073 1074 1075 1076 |
# File 'lib/pedump/cli.rb', line 1069 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
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/pedump/cli.rb', line 237 def dump_packer_only fnames max_fname_len = fnames.map(&:size).max fnames.each do |fname| if File.directory?(fname) if [: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 [:verbose] > 0 printf("%-*s %s\n", max_fname_len+1, "#{fname}:", pname) if pname end end end end |
#dump_packers(data) ⇒ Object
869 870 871 872 873 874 875 876 877 878 |
# File 'lib/pedump/cli.rb', line 869 def dump_packers data if [: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
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
# File 'lib/pedump/cli.rb', line 958 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
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 |
# File 'lib/pedump/cli.rb', line 1029 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
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 |
# File 'lib/pedump/cli.rb', line 1090 def dump_rich_hdr data if decoded = data.decode puts " ID VER COUNT DESCRIPTION" decoded.each do |row| # printf " %5d %4x %7d %4x %12d %8x\n", # row.id, row.id, row.version, row.version, row.times, row.times printf " %4x %4x %12d %s\n", row.id, row.version, row.times, ::PEdump::RICH_IDS[(row.id<<16) + row.version] end else puts "# raw:" data.hexdump puts puts "# dexored:" data.dexor.hexdump end end |
#dump_sections(data) ⇒ Object
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 |
# File 'lib/pedump/cli.rb', line 1054 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
783 784 785 786 787 788 789 790 791 792 793 794 795 |
# File 'lib/pedump/cli.rb', line 783 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
948 949 950 951 952 953 954 955 956 |
# File 'lib/pedump/cli.rb', line 948 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, opts = {}) ⇒ Object
584 585 586 587 588 589 590 591 592 593 594 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 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 |
# File 'lib/pedump/cli.rb', line 584 def dump_table data, opts = {} case data when File # tail printf "0x%x (%d) bytes starting at 0x%x:\n\n", data.size-data.tell, data.size-data.tell, data.tell a = data.read(4096).to_hexdump.split("\n", 11) if a.size > 10 a[10] = "..." end puts a.join("\n") return when PEdump::CLR::TablesHash return dump_clr_tables data when PEdump::CLR::StringsHash data.each do |offset, str| printf "%8x: %s\n", offset, str.inspect end return end 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::EFI_IMAGE_DATA_DIRECTORY dump_efi_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 when PEdump::CLR::MetadataStreamHeader dump_clr_streams data else puts "[?] dump_table: don't know how to dump: #{data.inspect[0,50]}" unless (data.respond_to?(:empty?) && data.empty?) end elsif data.is_a?(PEdump::DOSStub) data.hexdump elsif data.is_a?(PEdump::RichHdr) dump_rich_hdr data else case opts[:action] when :imphash puts "#{data} #{@file_name}" else puts "[?] Don't know how to display #{data.inspect[0,50]}... as a table" end end end |
#dump_tls(data) ⇒ Object
797 798 799 800 801 802 803 804 805 806 807 808 809 |
# File 'lib/pedump/cli.rb', line 797 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
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 |
# File 'lib/pedump/cli.rb', line 811 def dump_version_info data if [: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 [: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 |
#extract(x) ⇒ Object
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 |
# File 'lib/pedump/cli.rb', line 1112 def extract x a = x.split(':',2) case a[0] when 'datadir' extract_datadir a[1] when 'resource' extract_resource a[1] when 'section' extract_section a[1] when 'tail' extract_tail a[1] else raise "invalid #{x.inspect}" end end |
#extract_datadir(id) ⇒ Object
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 |
# File 'lib/pedump/cli.rb', line 1128 def extract_datadir id entry = @pedump.data_directory.find{ |x| x.type == id } unless entry @pedump.logger.fatal "[!] entry #{id.inspect} not found" exit(1) end if entry.size != 0 _copy_stream @pedump.io, $stdout, entry.size, @pedump.va2file(entry.va) end end |
#extract_resource(id) ⇒ Object
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 |
# File 'lib/pedump/cli.rb', line 1139 def extract_resource id res = nil if id =~ /\A0x\h+\Z/ needle = id.to_i(16) res = @pedump.resources.find{ |r| r.file_offset == needle } elsif id =~ /\A\d+\Z/ needle = id.to_i(10) res = @pedump.resources.find{ |r| r.file_offset == needle } elsif id['/'] type, name = id.split('/', 2) res = @pedump.resources.find{ |r| r.type == type && r.name == name } else @pedump.logger.fatal "[!] invalid resource id #{id.inspect}" exit(1) end unless res @pedump.logger.fatal "[!] resource #{id.inspect} not found" exit(1) end _copy_stream @pedump.io, $stdout, res.size, res.file_offset end |
#extract_section(id) ⇒ Object
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 |
# File 'lib/pedump/cli.rb', line 1161 def extract_section id section = nil if id['/'] a = id.split('/',2) if a[0] == 'rva' value = a[1].to_i(0) # auto hex/dec, but also can parse oct and bin section = @pedump.sections.find{ |s| s.VirtualAddress == value } elsif a[0] == 'raw' value = a[1].to_i(0) # auto hex/dec, but also can parse oct and bin section = @pedump.sections.find{ |s| s.PointerToRawData == value } else @pedump.logger.fatal "[!] invalid section id #{id.inspect}" exit(1) end else section = @pedump.sections.find{ |s| s.Name == id } end unless section @pedump.logger.fatal "[!] section #{id.inspect} not found" exit(1) end _copy_stream @pedump.io, $stdout, section.SizeOfRawData, section.PointerToRawData end |
#extract_tail(offset) ⇒ Object
1185 1186 1187 1188 1189 |
# File 'lib/pedump/cli.rb', line 1185 def extract_tail offset io = @pedump.tail io.seek(offset.to_i(16), IO::SEEK_CUR) if offset _copy_stream io, $stdout end |
#run ⇒ Object
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 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 |
# File 'lib/pedump/cli.rb', line 63 def run @success = true @actions = [] = { :format => :table, :verbose => 0 } optparser = OptionParser.new do |opts| opts. = "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| [:verbose] += 1 end opts.on "-q", "--quiet", "Silent any warnings","(can be used multiple times)" do |v| [:verbose] -= 1 end opts.on "-F", "--force", "Try to dump by all means","(can cause exceptions & heavy wounds)" do |v| [:force] ||= 0 [:force] += 1 end opts.on "-f", "--format FORMAT", [:binary, :c, :dump, :hex, :inspect, :json, :table, :yaml], "Output format: bin,c,dump,hex,inspect,json,table,yaml","(default: table)" do |v| [:format] = v end opts.separator '' KNOWN_ACTIONS.sort.each do |t| a = [ "--#{t.to_s.tr('_','-')}" + (ACTION_ARGS[t] ? " #{ACTION_ARGS[t]}" : ""), ACTION_COMMENTS[t] || t.to_s, lambda{ |arg| @actions << (arg && ACTION_ARGS[t] ? [t, arg] : t) }, ] 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.separator '' opts.on "--tokens", "Show CLR tokens" do [:tokens] = true end opts.on "--deep", "packer deep scan, significantly slower" do [:deep] ||= 0 [:deep] += 1 PEdump::Packer.default_deep = [: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 [:recursive] = true end opts.on "--all", "Dump all but resource-directory (default)" do @actions = DEFAULT_ALL_ACTIONS end opts.separator '' # opts.on "--disasm [X]", "Disassemble a symbol/VA" do |v| # @actions << [:disasm, v] # end opts.on("--extract ID", "Extract a resource/section/data_dir", "ID: datadir:EXPORT - datadir by type", "ID: resource:0x98478 - resource by offset", "ID: resource:ICON/#1 - resource by type & name", "ID: section:.text - section by name", "ID: section:rva/0x1000 - section by RVA", "ID: section:raw/0x400 - section by RAW_PTR", "ID: tail - file tail", "ID: tail:c00 - file tail + 0xc00 offset", ) do |v| @actions << [:extract, v] end opts.separator '' opts.on "--va2file VA", "Convert VA to file offset" do |va| @actions << [:va2file, va] end opts.on "--file2va OFFSET", "Convert file offset to VA" do |offset| @actions << [:file2va, offset] end opts.separator '' opts.on "--set-os-version VER", "Patch OS version in PE header" do |ver| @actions << [:set_os_version, ver] end opts.on "--set-dll-char X", "Patch IMAGE_OPTIONAL_HEADER32.DllCharacteristics" do |x| @actions << [:set_dll_char, x] end opts.separator '' opts.on "-W", "--web", "Uploads files to a #{URL_BASE}","for a nice HTML tables with image previews,","candies & stuff" do @actions << :web end opts.on "-C", "--console", "opens IRB console with specified file loaded" do @actions << :console 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 SHORTCUT_ACTIONS.each do |k,v| if idx = @actions.index(k) @actions[idx,1] = *v end 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 f next if ![:force] && !@pedump.supported_file?(f) @actions.each do |action| case action when :web; upload f when :console; console f else dump_action action,f end end end end @success rescue Errno::EPIPE # output interrupt, f.ex. when piping output to a 'head' command # prevents a 'Broken pipe - <STDOUT> (Errno::EPIPE)' message @success end |
#set_dll_char(x) ⇒ Object
1191 1192 1193 1194 1195 1196 1197 |
# File 'lib/pedump/cli.rb', line 1191 def set_dll_char x @pedump.pe.image_optional_header.DllCharacteristics = x.to_i(0) io = @pedump.io.reopen(@file_name,'rb+') io.seek @pedump.pe.ioh_offset io.write @pedump.pe.image_optional_header.pack io.close end |
#set_os_version(ver) ⇒ Object
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 |
# File 'lib/pedump/cli.rb', line 1199 def set_os_version ver raise "[!] invalid version #{ver.inspect}" unless ver =~ /\A(\d+)\.(\d+)\Z/ raise "[!] no IMAGE_OPTIONAL_HEADER" if @pedump.pe.ifh.SizeOfOptionalHeader.to_i == 0 major = $1.to_i minor = $2.to_i ver = "#{major}.#{minor}" ioh = @pedump.pe.image_optional_header prev_os_ver = "#{ioh.MajorOperatingSystemVersion}.#{ioh.MinorOperatingSystemVersion}" prev_ss_ver = "#{ioh.MajorSubsystemVersion}.#{ioh.MinorSubsystemVersion}" if prev_os_ver == ver && prev_ss_ver == ver @pedump.logger.warn "[?] already has #{ver}" return end if prev_os_ver != ver ioh. = major ioh. = minor @pedump.logger.warn "[.] MajorOperatingSystemVersion: #{prev_os_ver} -> #{ver}" end if prev_ss_ver != ver ioh.MajorSubsystemVersion = major ioh.MinorSubsystemVersion = minor @pedump.logger.warn "[.] MajorSubsystemVersion: #{prev_ss_ver} -> #{ver}" end io = @pedump.io.reopen(@file_name,'rb+') io.seek @pedump.pe.ioh_offset io.write ioh.pack io.close end |
#upload(f) ⇒ Object
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 |
# File 'lib/pedump/cli.rb', line 281 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' require 'net/http/post/multipart' 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.warn "[.] checking if file already uploaded.." uri = URI.parse URL_BASE Net::HTTP.start(uri.host, uri.port, use_ssl: (uri.scheme == 'https')) do |http| http.open_timeout = 10 http.read_timeout = 10 # doing HTTP HEAD is a lot faster than open-uri h = http.head("/#{md5}/") if h.code.to_i == 200 && h.content_type.to_s.strip.downcase == "text/html" @pedump.logger.warn "[.] file already uploaded: #{file_url}" return elsif h.code.to_i != 404 # 404 means that there's no such file and we're OK to upload @pedump.logger.fatal "[!] invalid server response: \"#{h.code} #{h.msg}\" (#{h.content_type})" exit(1) end end f.rewind # upload with progress post_url = URI.parse(URL_BASE+'/upload') # UploadIO is from multipart-post 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, use_ssl: (post_url.scheme == 'https')) do |http| http.request(req) end ppx.finish! unless [200, 302, 303].include?(res.code.to_i) @pedump.logger.fatal "[!] invalid server response: #{res.code} #{res.msg}" @pedump.logger.fatal res.body unless res.body.empty? exit(1) end puts "[.] uploaded: #{file_url}" ensure $stdout.sync = stdout_sync end |