VNC Authentication checking with Python

In this post i describe a small python script which can be used to determine the type of authentication used on a VNC Server. It uses the Scapy packet manipulation program to perform all the network data transmissions and retrievals. The program may not be perfect, but with my limited testing it seemed to work ok. To understand how the program works, i need to explain how a VNC client interacts with a VNC server. The RFB Protocol is used to make the connection to the server. By default this runs on TCP port 5900. I import Scapy into the python program, and save the IP address and port number into the variables IpAddress and port.

from scapy.all import *
IpAddress = '192.168.1.13'
port = 5900

It is important to run the following command before executing the script. This allows for the TCP handshake to complete.

iptables -A OUTPUT -p tcp –tcp-flags RST RST -j DROP

The first stage is to perform a TCP handshake to port 5900. I have set the timeout value of the TCP SYN packet to 2 seconds. This prevents the code running in an endless loop if the VNC server dosn’t respond with a SYNACK.

If the server does respond with a SYNACK, the SYNACK packet is stored in the synack variable.

syn = IP(dst=IpAddress)/TCP(dport=port, flags='S') 
synack = sr1(syn, timeout=2) 

I then finish the TCP handshake with an ACK, and send it to the VNC server.

ack = IP(dst=IpAddress)/TCP(dport=port, flags='A', seq=1, ack=synack.seq + 1)
send(ack)

Now the TCP handshake is complete, the VNC server should respond with a protocol version message. This is a message which tell the client the version number supported by the server. This message needs to be captured. To do this i then run a sniffer on the interface, checking for all data incoming from the VNC servers IP address.

filter = 'host ' + IpAddress
vnc = sniff(filter=filter, count=1,timeout=2, prn=vncCheck)

All data that matches the filter is sent to the vncCheck function for further processing. The first stage of this function is to verify that the packet it received is indeed a protocol version message. An example of a protocol message can be seen below:

pv

All protocol version packets are in the format of ‘RFB xxx.yyy\n’. xxx and yyy are the protocol version numbers. Because of this, the best method of determining if the packet is a protocol version message is by simply checking if the packet payload consists of the string ‘RFB’.

if 'RFB' in packet.load:

When the protocol version message is received. The client then sends a client protocol version. This informs the server the protocol version which the client supports and will be used for the communication. In my case i create a the client protocol version packet with the version payload of ‘RFB 003.003\n’.

clientVersion = IP(dst=IpAddress)/TCP(dport=port, flags='AP', seq=1, ack=packet.seq + 1)/'RFB 003.003\n'

The client protocol version is then sent to the VNC server. The response back from the VNC server is saved into the supportedtypesPacket variable. This response contains the type of authenticaion the server uses in the form of a hexadecimal value. For example, from the following screenshot you can see the security type response 00 00 00 02 highlighted at the bottom.

st

The type of authentication the VNC server uses is defined by the last byte. In this case the value 02. The program then extracts this byte and stores it in the variable authenticationType.

authenticationType = str(ord(supportedtypesPacket.load[2])) + str(ord(supportedtypesPacket.load[3]))
authenticationType = int(authenticationType)

Finally, a simple IF statement is used to compares the value to the matching authentication type.

if authenticationType == 00:
	print IpAddress + ' uses an Invalid Authentication type of ' + str(authenticationType)
elif authenticationType == 01:
	print IpAddress + ' uses No Authentication'
elif authenticationType == 02:
	print IpAddress + ' uses VNC Authentication'
elif authenticationType == 05:
	print IpAddress + ' uses RA2 Authentication'
elif authenticationType == 06:
	print IpAddress + ' uses RA2ne Authentication'
elif authenticationType == 16:
	print IpAddress + ' uses Tight Authentication'
elif authenticationType == 17:
	print IpAddress + ' uses Ultra Authentication'
elif authenticationType == 18:
	print IpAddress + ' uses TLS Authentication'
elif authenticationType == 19:
	print IpAddress + ' uses VeNCrypt Authentication'
elif authenticationType == 20:
	print IpAddress + ' uses GTK-VNC SASL Authentication'
elif authenticationType == 21:
	print IpAddress + ' uses MD5 Hash Authentication'
elif authenticationType == 22:
	print IpAddress + ' uses Colin Dean XVP Authentication'
else:
	print IpAddress + ' uses an Unknown Authentication type of: ' + str(authenticationType)

For completeness, you can find below the complete code with indentation and comments included.

from scapy.all import *

#Must run the following command before executing this script. Allows for the TCP handshake to take place.
#iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP

#IP and Port of the VNC server
IpAddress = '192.168.1.13'
port = 5900

#Function which is executed on each packet.
def vncCheck(packet):
    #Checks that the packet is a server protocol version response. (Should contain 'RFB' if it is.
    if packet.haslayer('Raw'):
        if 'RFB' in packet.load:
            #Creates and sends a clientVersion response. The security type response from the VNC server is saved in the
            #Variable supportedtypesPacket
            clientVersion = IP(dst=IpAddress)/TCP(dport=port, flags='AP', seq=1, ack=packet.seq + 1)/'RFB 003.003\n'
            supportedtypesPacket = sr1(clientVersion)
            #Extract the HEX value from the security type response.
            authenticationType = str(ord(supportedtypesPacket.load[2])) + str(ord(supportedtypesPacket.load[3]))
            authenticationType = int(authenticationType)
            #Match the value with the correct authentication type.
            print IpAddress + ' Uses an Authentication type of : ' + str(authenticationType)
            if authenticationType == 00:
                print IpAddress + ' uses an Invalid Authentication type of ' + str(authenticationType)
            elif authenticationType == 01:
                print IpAddress + ' uses No Authentication'
            elif authenticationType == 02:
                print IpAddress + ' uses VNC Authentication'
            elif authenticationType == 05:
                print IpAddress + ' uses RA2 Authentication'
            elif authenticationType == 06:
                print IpAddress + ' uses RA2ne Authentication'
            elif authenticationType == 16:
                print IpAddress + ' uses Tight Authentication'
            elif authenticationType == 17:
                print IpAddress + ' uses Ultra Authentication'
            elif authenticationType == 18:
                print IpAddress + ' uses TLS Authentication'
            elif authenticationType == 19:
                print IpAddress + ' uses VeNCrypt Authentication'
            elif authenticationType == 20:
                print IpAddress + ' uses GTK-VNC SASL Authentication'
            elif authenticationType == 21:
                print IpAddress + ' uses MD5 Hash Authentication'
            elif authenticationType == 22:
                print IpAddress + ' uses Colin Dean XVP Authentication'
            else:
                print IpAddress + ' uses an Unknown Authentication type of: ' + str(authenticationType)

#Creates and sends a TCP SYN packet to the VNC server. (Step 1 of the TCP handshake)
syn = IP(dst=IpAddress)/TCP(dport=port, flags='S')
synack = sr1(syn, timeout=2)

#Creates and sends an ACK packet is response to the servers SYNACK. (Step 3 of the TCP handshake)
ack = IP(dst=IpAddress)/TCP(dport=port, flags='A', seq=1, ack=synack.seq + 1)
send(ack)

#Sniffs incoming network data after the initial TCP handshake. Sends the packets to the vncCheck function.
filter = 'host ' + IpAddress
vnc = sniff(filter=filter, count=1,timeout=2, prn=vncCheck)

Hacking the TalkTalk HUAWEI HG523a Router Part 2

For part 1 please Click Here.

OK. So i have access to the routers busybox console. I found by typing the busybox command it displays all the commands available on the device.

# busybox
BusyBox vv1.9.1 (2012-03-05 00:16:52 CST) multi-call binary
Copyright (C) 1998-2007 Erik Andersen, Rob Landley, Denys Vlasenko
and others. Licensed under GPLv2.
See source distribution for full notice.

Usage: busybox [function] [arguments]...
or: function [arguments]...

BusyBox is a multi-call binary that combines many common Unix
utilities into a single executable.  Most people will create a
link to busybox for each function they wish to use and BusyBox
will act like whatever it was invoked as!

Currently defined functions:
[, [[, arp, ash, cat, chmod, chown, cp, date, echo, ftpget,
ftpput, halt, ifconfig, init, kill, killall, linuxrc,
ln, ls, mcast, mkdir, mknod, mount, netstat, nslookup,
ping, poweroff, ps, reboot, rm, route, sh, sleep, test,
top, traceroute, umount, vconfig, wget

#

As you can see the amount of commands available is quite small. Looking at some other busybox console outputs posted online there are usually many more programs available to run. There is a great page found here which details many of the programs or ‘applets’ that busybox can have installed and describes what they are for. Many of the commands available on the HG523a aren’t of much use.

My next aim is to try and extract the filesystem from the device. Allowing me to analyse it more easily on another computer with more tools available.

I tried to mount a directory over nfs but i found out that nfs isnt supported on the device. If you run the command cat /proc/filesystems you can check what file systems are supported. If NFS is listed in this output it may have been an option.

# cat /proc/filesystems
nodev   rootfs
nodev   bdev
nodev   proc
nodev   sockfs
nodev   pipefs
nodev   tmpfs
squashfs
nodev   ramfs
#

My next attempt involved copying the device file which contains the file system. I first checked the file system type. This information is important later on.

# cat /proc/mounts
rootfs / rootfs rw 0 0
/dev/root / squashfs ro 0 0
none /dev tmpfs rw 0 0
/proc /proc proc rw 0 0
none /var tmpfs rw 0 0
none /tmp tmpfs rw 0 0
none /mnt tmpfs rw 0 0

From this output you can see the root filesystem is running on squashfs.

I next went on to find where the file system is stored. /dev/root dosnt exist which was slightly confusing.

# cat /proc/mtd
dev:    size   erasesize  name
mtd0: 00010000 00001000 "boot"
mtd1: 00001000 00001000 "flag"
mtd2: 003c0000 00001000 "main"
mtd3: 0002d000 00001000 "config"
#

This mtd file showed that the router software is split into 4 parts.

Boot, which i assume is the boot loader.
Flag, which I’m note sure.
Main, which i assume is the file system. especially considering it is the largest in size.
Config. Which again, I’m not entirely sure what is it. But the one of interest is the one called main on mtd2.

Now. looking in the dev directory you can see there are all the mtd devices.

# cd /dev
# ls
initctl    mtdblock6  mtd4       tty1       kmem       I2S        ram2
mem        mtdblock5  mtd3       tty2       port       boardled   ram3
ttyp2      mtdblock4  mtd2       tty3       null       wlchr      adsl0
ttyp1      mtdblock3  mtd1       tty4       ac0        ttyUSB0
ttyp0      mtdblock2  mtd0       ppp        acl0       ttyUSB1
ptyp2      mtdblock1  ptmx       printer0   urandom    ttyUSB2
ptyp1      mtdblock0  ttyS0      console    gpio       ttyUSB3
ptyp0      mtd6       tty        bhal       hwnat0     ram0
zero       mtd5       tty0       commondrv  i2cM0      ram1
#

If you remember when i typed in the busybox command at the beginning, there was a command called ftpput. This ftpput command is the way I’m going to extract the firmware from the device.

# ftpput
BusyBox vv1.9.1 (2012-03-05 00:16:52 CST) multi-call binary

Usage: ftpput [options] remote-host

Download or upload via FTP.

Options:
-g    Download
-s    Upload
-v    Verbose
-u    Username to be used
-p    Password to be used
-l    Local file path
-r    Remote file path
-P    Port to be used, optional
-B    Bind local ip, optional
-A    Remote resolved ip, optional
-b    Transfer start position
-e    Transfer length
-m    Max transfer size
-c    Compress downloaded file

#

So i opened up my Kali linux virtual machine and installed an FTP server. I then attempted to upload using ftpput on the router. One of the difficulties i had with this program is that it was very unforgiving with the syntax. It wouldn’t respond stating the mistake you made with the input. But in the end after some searching i found the correct command.

ftpput -s -v -u ftpuser -p toor -l /dev/mtdblock2 -r /ftpdir/mtdblock2 192.168.1.3

ftpuser is the username that has write access on my ftp server on the Kali virtual machine.
toor is the password
/dev/mtdblock2 is the file I’m copying.
/ftpdir/mtdblock2 is the location on the ftp server the file is saved.
192.168.1.3 is the FTP server IP address

So now i have mtdblock2 on my virtual machine.

The next stage is to extract the firmware from mtdblock2. I did attempt initially to try and mount the device directly hoping it would work. But sadly it didn’t.

root@kali:~/Desktop/talktalk# mount -t squashfs mtdblock2 /mnt
mount: wrong fs type, bad option, bad superblock on /dev/loop0,
missing codepage or helper program, or other error
In some cases useful info is found in syslog - try
dmesg | tail  or so

I then went on to run binwalk on it.

root@kali:~/Desktop/talktalk# binwalk mtdblock2

DECIMAL       HEX           DESCRIPTION
-------------------------------------------------------------------------------------------------------------------
0             0x0           Squashfs filesystem, big endian, lzma signature, version 3.0, size: 2072620 bytes,  182 inodes, blocksize: 65536 bytes, created: Sun Mar  4 16:18:17 2012
2076736       0x1FB040      LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 3827500 bytes

As you can see, it is showing that there is a Squashfs filesystem right at the start of the file. Which confirms the findings when i ran cat /proc/mount on the device.

I then went on to download firmware-mod-kit in an attempt to unsquash the filesystem. It is an insanely awesome set of scripts which goes through all the unsquashfs versions and attempts to extract the firmware. Once downloaded and installed i ran the unsquashfs_all.sh script against mtdblock2 and waited.

Eventually, version squashfs-3.2-r2-hg612-lzma/unsquashfs successfully extracted the firmware. I can browse the directories and view the files like i could on the device. But now have much more freedom in what i want to do next.

root@kali:~/Desktop/talktalk/squashfs-root/bin# ls
adslcmd   busybox  cms      ddnsc     echo       ipcheck    klog  mini_upnpd  netlogger  ripd     sntp      tr111   wlancmd
adslctrl  cat      console  dhcpc     equipcmd   iptables   ln    mkdir       netstat    rm       startbsp  umount  wscd
ash       chmod    cp       dhcps     ethcmd     iwcontrol  log   mknod       ping       sh       swapdev   upg     zebra
atmcmd    chown    cwmp     dns       igmpproxy  iwpriv     ls    mount       pppc       siproxd  tc        upnp
brctl     cli      date     ebtables  ip         kill       mic   mpoad       ps         sleep    telnetd   web

I have made uploaded a copy of the file system here if anyone wants to download it and take a look. Please let me know if you find anything interesting.

Make sure to check back next time as i go even deeper into the TalkTalk HUAWEI HG523a Router.

Hacking the TalkTalk HUAWEI HG523a Router

I got my hands on a TalkTalk HUAWEI HG523a. This is one of the routers distributed to TalkTalk subscribers. This is my first attempt of doing any kind of embedded device analysis so i decided it would be beneficial to document the steps i take. As i progress i will write new posts detailing what i have done.

Before i start, one of the best resources i have found in working through this project is devttys0.com. A lot of the things i do in this post i found in that blog.

OK, so the first thing i decided to do was to open the router and try to find some kind of serial interface that would allow me to get a shell on the device. The picture below shows what the top of the PCB looks like.

Untitled

 

 

 

 

 

 

 

 

 

 

 

Looking at the board you can see a a grouping of five pins that look quite like a serial port. You would expect to find a transmit, receive, power and ground pins to connect to. The next step to to identify which pin is which. I did this using a multimeter.

close

 

 

 

 

 

 

 

 
The first pin to identify is ground. To do this i switched the multimeter to continuity mode. This checks if there is an electrical connection between the two probes. I attached one of the multimeter probes to the power socket casing (which is a known ground point) and the other on each of the pins in turn. You would expect the multimeter to show there’s continuity if it is connected to two ground pins. In this case it showed continuity on pin 4. So this is the ground pin.

The next step is to identify the transmit pin. You would expect when the router is powered it it will display boot messages and other information on the serial interface. This kind of behavior can be seen on the multimeter as an erratic voltage. So to find the transmit pin simply connect one probe to ground as always, and the other to each pin in turn. The pin that exhibits an unstable voltage that constantly changes is likely the transmit pin. In this case the transmit pin is pin 5.

With this router i couldn’t clearly identify the power and receive pins. Both pin 1 and pin 3  has a 3.3 volt power and pin 2 was completely dead. So all i did was take a guess. I found that pin 1 is the receive pin and pin 3 is the power pin.

the next step is to connect to this serial interface. I used a USB-UART adapter i bought off ebay for a whopping £1.19. So i connect the USB-UART adapter to the pins on the router and power it up. I connect to the COM port using putty and was greeted with the following:

incbaud

 

 

 

 

 

 

 

 

 

From my limited understanding i believed this to be because the BAUD rate was incorrect. So i found a very cool python script called baudrate which allows you to easily find the correct baud rate for the interface your trying to connect to.  You just enter the command and use the arrow keys to cycle through the baud rates until you find the correct one. (The correct one will display the boot-up text correctly.)

root@kali:~/Documents/baudrate-1.0/src# python baudrate.py /dev/ttyUSB0

Starting baudrate detection on /dev/ttyUSB0, turn on your serial device now.
Press Ctl+C to quit.
@@@@@@@@@@@@@@@@@@@@@ Baudrate: 115200 @@@@@@@@@@@@@@@@@@@@@

*******____________skb_________size 224
/proc/FastPath created
Realtek MCast FastPath
/proc/mc_FastPath created
NET: Registered protocol family 1
NET: Registered protocol family 17
Bridge LAN vlan registered
Ebtables v2.0 registered
802.1Q VLAN Support v1.8 Ben Greear <greearb@candelatech.com>
All bugs added by David S. Miller <davem@redhat.com>
VFS: Mounted root (squashfs filesystem) readonly.
Freeing unused kernel memory: 108k freed
init started: BusyBox vv1.9.1 (2012-03-05 00:16:52 CST)
starting pid 69, tty '': '/etc/init.d/rcS'
rcs
RCS DONE
starting pid 72, tty '': '/bin/sh'

BusyBox vv1.9.1 (2012-03-05 00:16:52 CST) built-in shell (ash)

From this output you can see that at a baud rate of 115200 the text displays normally. So the serial interface uses a 115200 baud rate. As it turns out this is quite common.

Once the boot up has finished i hit enter on the keyboard and it displayed a login prompt. I entered the default user name and password of admin and admin which was printed on a sticker on the router. This then logged me into the routes serial interface.

prompt

 

 

 

 

 

 

 

 

 

 

 

 

As you can see from the screenshot you are entered into a ATP command line interface. Looking through the options of this interface it seems quite limited as to what you can do. Some things of interest include:

By typing ‘debug display cwmp’ it allows you to view details for the TR-069 application layer protocol used for the remote updating of router firmware.

ATP>debug display cwmp
ACS URL: http://acs.talktalk.co.uk:7547/ACS-server/ACS
User Name:
Password:
Connection Request User Name: userid
Connection Request Password: cRP#21530316207S2C088299
Connection Request URL:
Inform Enable: 1
Inform Period: 86400

You also have the option for setting the authentication type used for cwmp.

ATP>debug set cwmp authtype ?
0: none; 1: basic; 2: digest; 3: adapt

And to set the password for TR-064 with:

ATP>debug set tr064 pwd mypassword123
ATP>

Going through all the other options i couldn’t find many other useful commands. I decided to do a bit of googling to see if there was any hidden commands that could be used. I found a blog post where someone said to enter the shell command to bring up a Busybox shell. I gave this a try and it worked.

BusyBox vv1.9.1 (2012-03-05 00:16:52 CST) built-in shell (ash)
Enter 'help' for a list of built-in commands.
# ls
var   usr   tmp   sbin  proc  mnt   lib   init  etc   dev   bin
#

As it turns out. Looking at the same blog post its possible to get the same level of access by just telnetting into the router and entering the admin admin login details i used. But i suppose what i have done is good practice, and a lot of fun :)

Make sure you check back for what i attempt next with this TalkTalk router.

Malware Analysis Part 2: First Attempt

Please read part 1 first if you would like to know how the analysis lab is setup.

There are various sites you can use to download sample malicious software. The one i used is called openmalware.org. I wasn’t completely sure which sample to choose. I wanted one which was recent so i decided to get a a sample called “BC.Heuristic.Trojan.SusPacked.BF-6.A” I’m not going to link to it for obvious reasons but the MD5 hash of the sample is 0148d6e7f75480b3353f1416328b5135. This can be used as a search term on the open malware site to find sample i used in this analysis attempt.

Once i downloaded the file i took a snapshot of the registry and files on the machine using Regshot. I then ran the file, took another snapshot and compared the two. The restults shows that multiple files and folders were created when it executed.

Files added: 3
----------------------------------
C:\Program Files\Windos\logg.dat
C:\Program Files\Windos\Windos.exe
C:\WINDOWS\Prefetch\MALWARE.EXE-155B9235.pf
----------------------------------
Files [attributes?] modified: 3
----------------------------------
C:\Documents and Settings\james\NTUSER.DAT.LOG
C:\WINDOWS\system32\config\software.LOG
C:\WINDOWS\system32\config\system.LOG
----------------------------------
Folders added: 1
----------------------------------
C:\Program Files\Windos
----------------------------------

I also noticed that the Debian server has received a flood of DNS requests from the malware infected machine.

Untitled-1

So the malware is attempting to fetch its IP for its server and i assume either download additional stuff or send some data to the server.

Because of this DNS request the next step i figured was to put my DNS server to good use and respond to the request with one of my own IP’s to see what it did next. So i opened the /etc/hosts file and added a new entry pointing se7aaaaa.no-##.### (redacted) to my debian server 192.168.56.101. I then started Wireshark on the malware infested machine and reset the DNS daemon.

Untitled-2

This part i’m not 100% sure on. But what i can gather from this is that it is trying to start a TCP connection with my Debian server on the port 81 which is the TOR port. although it doesn’t necessarily mean its trying to connect in any way to the TOR network. Obviously whatever its trying to do the server isn’t responding appropriately (or not at all) and therefore the connection isn’t fully made. The next step i made was to set a netcat listener on the port and see what is being sent. To do this i entered the following command:

nc -l -p 81

-l specifies a listener and -p the port i want to listen on.

Untitled-1As you can see what i received is unintelligible.

In my next posting i will continue the analysis of this file. Once i figured out where to go from here :)