Heap Overflow Vulnerability in Citrix NetScaler Gateway (CVE-2017-7219)

After presenting my findings on the Swisscom router at the CybSecConference last year, I started looking for a new product to analyze. I quickly found that it’s possible to download virtual “demo” appliances of Citrix products, so I went on to download a Netscaler VPX, which at the time was at version 11.10 (b50.10). The goal as always was to discover a way to compromise the device remotely, which is what led me to discover a heap overflow vulnerability which allows an authenticated user to compromise the device with root privileges. During the research, I (un)fortunately wasn’t able to find a way to exploit the flaw without credentials.

======================
TL;DR;
======================

A heap overflow in the “ping” functionality allows an authenticated VPN user to trigger a use-after-free condition in order to execute arbitrary commands on the appliance. (CVE-2017-7219)

The following Metasploit module can be used to exploit the vulnerability (use at your own risk…), though it will probably only function against the version that was analyzed.

======================
DETAILS
======================

As mentioned above, I began by downloading the virtual appliance and started it up on my machine. Since I’ve never used or configured a Netscaler appliance in the past, it took a while to get things going and configuring it in some kind of standard mode.

Once the appliance is started, it is possible to log into the console with the standard nsroot account. This gives access to a “limited” shell, but Citrix were nice enough to add a shell command which gives root access to the box, so I used this to extract the filesystem and analyze what was going on.

Going through the various files on the system, I found one that seemed promising which was named /netscaler/nsvpnd. As it’s name hints at, it is used to handle requests sent to the VPN web interface. Though only authenticated requests seem to get here, as authentication itself is performed by another binary on the system.

One of the requests that is performed by the nsvpnd binary is the ping request.

This results in the following HTTP request:

POST /cvpn/aHR0cDovLzEyNy4wLjAuMQ/fs/ping HTTP/1.1
Host: 
[...]
Cookie: NSC_AAAC=b2f85f0b72ef21c82eac5ac4d314a4170af182cd945525d5f4f58455e445a4a42; NSC_FSSO=0
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 41


host=127.0.0.1&nsc_nonce=kPIueluG6ubF37J0

Apparently the /cvpn/aHR0cDovLzEyNy4wLjAuMQ part of the URL is not actually required, so it can safely be removed. In any case, this request is eventually handled by one of two vulnerable functions that contain an unbounded strcpy with our host parameter, as shown below.

This is where the overflow happens, though we are not overwriting a stack variable, but one of the members of a struct, which is expected to be at most 256 bytes long. Our parameter on the other hand can go up to 512 bytes, which is what allows us to overflow this buffer.

So it is possible to write up to 256 bytes after the host member of the structure, therefore overwriting any other members of the structure after the host, which is where things get interesting. One of the following members is actually a pointer to another structure (a parameter list) on the heap which was previously allocated and eventually gets free‘d by the application when the request has completely been processed.  This means we can essentially free an arbitrary memory location.

Before going any further, a quick analysis of the system and binary show that FreeBSD uses jemalloc instead of dlmalloc, the heap is not executable, but the stack is, and ASLR is not enabled (this was 2016 after all). Another thing that was helpful in exploiting this particular issue is that all requests to the web interface are handled by one single process, which means we can actually interact many times with the process by sending multiple HTTP requests if required.

At this point, my idea to gain code execution was the following:

  1. Find a function pointer somewhere in the application, as well as the size that was used to allocate that memory
  2. Free the memory address of this function pointer
  3. On the next malloc of the appropriate size, the same address should be returned
  4. Overwrite the function pointer with user-controlled data (a pointer to my shellcode) when it is copied to this memory address
  5. Trigger the function pointer to call my shellcode

The only remaining problem is getting a shellcode to some predictable location. Thankfully, as mentioned earlier, ASLR is disabled, the stack is executable and the value we send in our host parameter is actually stored on the stack! All we need is to get this address and plug it into the function pointer to get the shellcode to execute. Obviously, despite ASLR being disabled, the stack will not always be exactly at the same place, so I used a super-l33t technique consisting of pre-pending my shellcode with lots of NOPs (because 2016).

So we can now break down each step and look at how we can achieve them:

  1. With some reverse engineering and debugging, I found one function pointer that was always allocated at address 0x2840a0c0. This function seems to be used to decode parameters sent in the HTTP requests. The memory address is initially allocated at 0x08097fb9 with a call to malloc(32).
  2. Use the overflow to overwrite the pointer to the parameter list with 0x2840a0c0. The address is then free‘d when the request has finished being processed. Here, we also need to take a note of where our host parameter is located on the stack, as this is where we will store our shellcode.
  3. While searching through the binary’s code, I found one place where a malloc is called with a length which can be specified by the VPN user directly. This is when providing the username and password to log into a SMB server. There may be other parts of the code that could be exploited in a more reliable manner, but this is the first I found and decided to go with it. The only problem is that it means we need to initiate a SMB login to a server that is accessible to the Netscaler appliance.
  4. As long as our password is between 16 and 32 characters, the previously free‘d address is returned and we can therefore overwrite the function pointer with the value of our password. It must therefore be the address of our shellcode, which we discovered was placed on the stack when performing the ping.
  5. The function pointer is actually called at regular intervals by the application while processing data, so we can just wait until it is called to get our code executed.

As you’ve probably deduced by now, in order to exploit the vulnerability, we are going to use two separate HTTP requests. The first one is used to put the shellcode on the stack and trigger the overflow, while the second is used to overwrite the function pointer with the address of our shellcode and actually execute our payload. This is summarised here:

Request 1 (ping host)

→ Start of host value contains shellcode which is conveniently placed on the stack

→ Use overflow to overwrite pointer to parameter list with 0x2840a0c0

→ When the request has been entirely processed, the program frees the address 0x2840a0c0

Request 2 (smb login)

→ Specify a password parameter of length between 16 and 32, this forces malloc to return the address that was previously freed.

→ Password value (shellcode location) overwrites function pointer that was previously located there

→ While processing the request, the overwritten function pointer is called, executing the shellcode

So that’s pretty much it. The following MSF module, should be able to exploit the flaw, but use it at your own risk. I’ve only tested it on a controlled lab environment.

For those of you who participated in our Insomni’hack teaser this year, you’ll notice many similarities with “The Great Escape – part 2” challenge, as it was very much inspired by this flaw.

======================
TIMELINE
======================

  • 08.12.2016: Initial report sent to Citrix
  • 09.12.2016: Case opened by Citrix to investigate the issue
  • 14.12.2016: Vulnerability acknowledged and reproduced by Citrix team
  • February-March 2017: Rollout of fixed Netscaler versions
  • 12.04.2017: Release of security bulletin: https://support.citrix.com/article/CTX222657

 

SCRT is proud to announce the opening of its new office in Bern

To sustain its growth and continue to maintain relations of proximity with its customers and partners, SCRT is glad to announce the opening of its new office in Bern.

SCRT is one of the leaders in Information Security in Switzerland, with headquarters in Préverenges (Vaud) and a branch office in Bordeaux (France). This new SCRT location will facilitate the provision of professional IT Security Services to new and existing clients in the German speaking part of Switzerland.

Ideally located in the Monbijou district, close to the train station, this office offers a dynamic, welcoming and optimal setting for our customers and staff. SCRT will continue to offer the same services at our new address in Bern and ensure our well known proximity and reactivity all over Switzerland.

We look forward to welcoming you!

SecureIT – Valais

Voici les slides de ma présentation de Vendredi dernier pour Secure-IT. J’y ai présenté quelques-unes des techniques les plus communément exploitées en test d’intrusion pour compromettre un domaine Windows ainsi que les différentes remédiations possibles.

Pour ceux qui n’auraient pas le temps de parcourir la totalité des slides, voici un bref résumé des recommendations:

  • Désactiver WPAD et les protocoles de résolutions de noms LLMNR et NetBios
  • Utiliser un système come LAPS pour gérer les mots de passe des administrateurs locaux
  • Limiter l’utilisation des comptes privilégiés (surtout les “admins du domaine”)
  • Utiliser AppLocker pour empêcher l’exécution de programmes non autorisés
  • Améliorer le filtrage réseau entre les VLANs internes et même au sein du même VLAN (Firewall local)
  • Limiter les privilèges utilisés par les applications (notamment Tomcat et serveurs SQL)
  • Utiliser un système de corrélation de logs pour pouvoir détecter les anomalies sur le réseau

L’utilisation de tests d’intrusion de type “Red Team” ou “Purple Team” permet ensuite de valider la pertinence des logs et des alertes remontées, ceci dans le but d’accélérer la réponse à incident pour pouvoir palier à une réelle attaque.

CybSec16

La Cybsec16 est maintenant terminée et toute l’équipe SCRT présente a de nouveau passé un bon moment en compagnie de différents acteurs du monde de la sécurité en suisse romande (et un peu au delà). Une excellente organisation, des conférences intéressantes et diversifiées ainsi que les divers events “networking” ont largement contribué au succès de l’événement.

Comme plusieurs personnes sont venues me demander les slides de ma présentation, les voici:

https://download.scrt.ch/cybsec16/chlam2308161-1_cybsec_swisscom.pdf

En extra, les slides de ma rump session préparée à la dernière seconde:

https://download.scrt.ch/cybsec16/chlam0311161-1_cybsec_rump.pdf

Merci aux organisateurs et à l’année prochaine!

Insomni’hack 2016 teaser results

Last weekend saw the year’s CTF competitions begin with our very own Insomni’hack teaser. Given some of the recent absurdities (http://weputachipinit.tumblr.com/) we decided to go with the Internet of Things as our theme this year.

Before going into some of the details, we’d like to congratulate Dragon Sector for taking the first place once again, finishing in front of Tasteless and KITCTF who complete our podium.

Screenshot from 2016-01-18 10:54:48

The full scoreboard can be found here: https://teaser.insomnihack.ch/scoreboard, and also on CTFtime.

When entering the contest, participants were greeted by a kitchen, where several connected objects (tasks) could be attacked.

Screenshot from 2016-01-18 10:13:00
Nearly 850 teams registered for the teaser, with 245 of them scoring at least once.

Overall, 8 tasks were given in Web, Crypto and Pwning fields, and teams had 36 hours (from 9h UTC, the 16th of January until 21h on the 17th) to complete as many as possible (and as quickly as possible) to get the top spots.

To give an idea of the complexity of each task, the following list shows which team was the first to solve it and at what time:

  • smartcat1: solved by dcua after 16 minutes
  • Bring the noise: solved by 217 after 27 minutes
  • Greenbox: solved by Dragon Sector after 1 hour and 7 minutes
  • smartcat2: solved by dcua after 1 hour and 10 minutes
  • Fridginator 10k: solved by n0n3m4 after 3 hours and 32 minutes
  • toasted: solved by 0x8F after 6 hours and 1 minute
  • rbaced1: solved by Dragon Sector after 6 hours and 25 minutes
  • rbaced2: solved by Dragon Sector after 20 hours and 19 minutes

We quickly notice that smartcat1 and Bring the noise were the easiest tasks, while the two rbaced tasks were the toughest. This also shows with the number of times each task was solved over the course of the weekend:

  • smartcat1 (Web): 209
  • Bring the noise (Crypto): 173
  • smartcat2 (Web): 132
  • Fridginator 10k (Web/Crypto): 52
  • Greenbox (Web): 33
  • toasted (Pwning): 15
  • rbaced1 (Pwning): 12
  • rbaced2 (Pwning): 2

After completing all the tasks, your kitchen looked like this:

Screenshot from 2016-01-18 11:27:45

Writeups for some of the challenges can be found here:

https://github.com/ctfs/write-ups-2016/tree/master/insomnihack-teaser-2016

The event ran rather smoothly, with only a few services needing to be restarted every now and then.

Do note that this is not a qualification round, as anyone can participate in the finals (18th of March, Geneva, Switzerland) and it is entirely free. We’re looking forward to seeing you there!