Skip to main content
Be Bitwise
x86 AssemblyCapstone: System Calls & I/O

Capstone: Echo Program

This is the capstone for the module. You'll build an echo program from scratch — a stdin-to-stdout version first, then a network-capable server. The exercise pulls together syscalls, file descriptors, buffer management, and the security instincts you've been building.

Part 1: The Stdin Echo Program

An echo program at its most basic just reads from stdin and writes the same bytes to stdout. Trivial in concept. Easy to get wrong if you're sloppy with syscall return values or buffer sizes.

nasm
section .bss
buffer resb 256 ; fixed 256-byte buffer
section .text
global _start
_start:
.echo_loop:
; Read from stdin
mov rax, 0 ; sys_read
mov rdi, 0 ; fd = stdin
lea rsi, [buffer] ; destination buffer
mov rdx, 256 ; maximum bytes to read
syscall
; Check the return value
cmp rax, 0
jle .exit ; 0 = EOF (Ctrl+D), negative = error
; Save the byte count -- this is critical
mov rdx, rax ; rdx = exact number of bytes read
; Write exactly those bytes to stdout
mov rax, 1 ; sys_write
mov rdi, 1 ; fd = stdout
lea rsi, [buffer]
; rdx already set to byte count
syscall
jmp .echo_loop ; repeat
.exit:
mov rax, 60 ; sys_exit
xor rdi, rdi ; exit code 0
syscall

Key design decisions in this simple program:

  1. We read at most 256 bytes because that is our buffer size. Reading more would overflow.
  2. We write exactly as many bytes as we read using the return value from sys_read. We never assume the buffer is full or null-terminated.
  3. We handle EOF (return value 0) by exiting cleanly.
  4. We handle errors (negative return value) by exiting.

Building It Step by Step

Trace what happens when you type "hello" and hit Enter:

nasm
; 1. sys_read returns 6 (5 chars + newline) in rax
; 2. We move 6 into rdx (the write count)
; 3. sys_write sends exactly 6 bytes from buffer to stdout
; 4. The terminal displays "hello\n"
; 5. We loop back to read again

After the read, the buffer holds ['h', 'e', 'l', 'l', 'o', '\n', ?, ?, ...] — the ? slots are whatever stale bytes were sitting in memory beforehand. We write only the first 6 because that's what sys_read reported.

Handling Partial Writes

The simple version assumes sys_write flushes everything in one call. On a real system — sockets in particular — a write often returns short. A serious echo program has to cope:

nasm
; Partial-write loop: keep writing until everything's out
; rsi = buffer start, r14 = total bytes to write
mov r14, rax ; total bytes from read
lea r15, [buffer] ; current write position
.write_loop:
test r14, r14
jz .echo_loop ; all bytes written
mov rax, 1 ; sys_write
mov rdi, 1 ; stdout (or client fd)
mov rsi, r15 ; current position in buffer
mov rdx, r14 ; remaining bytes
syscall
test rax, rax
jle .exit ; error or broken pipe
add r15, rax ; advance past written bytes
sub r14, rax ; decrease remaining count
jmp .write_loop

Looping on sys_write like this is bread-and-butter for network code, where partial writes are routine.

Part 2: Extending to a Network Echo Server

The network version swaps stdin/stdout for socket file descriptors. The echo logic at the core doesn't change — only the setup around it.

nasm
section .bss
sock_addr resb 16
cli_addr resb 16
cli_len resd 1
net_buf resb 1024
section .data
ready_msg db "Echo server listening on port 8080", 10
ready_len equ $ - ready_msg
section .text
global _start
_start:
; ---- Socket Setup ----
; Create socket
mov rax, 41 ; sys_socket
mov rdi, 2 ; AF_INET
mov rsi, 1 ; SOCK_STREAM
xor rdx, rdx
syscall
mov r12, rax ; r12 = server socket fd
; Build sockaddr_in for 127.0.0.1:8080 (loopback only)
lea rdi, [sock_addr]
mov word [rdi], 2 ; AF_INET
mov word [rdi + 2], 0x901F ; port 8080 (big-endian)
mov dword [rdi + 4], 0x0100007F ; 127.0.0.1
; Bind
mov rax, 49
mov rdi, r12
lea rsi, [sock_addr]
mov rdx, 16
syscall
test rax, rax
js .fatal
; Listen
mov rax, 50
mov rdi, r12
mov rsi, 5
syscall
test rax, rax
js .fatal
; Print ready message
mov rax, 1
mov rdi, 1
lea rsi, [ready_msg]
mov rdx, ready_len
syscall
; ---- Accept Loop ----
.accept_loop:
mov dword [cli_len], 16
mov rax, 43 ; sys_accept
mov rdi, r12
lea rsi, [cli_addr]
lea rdx, [cli_len]
syscall
test rax, rax
jns .got_client
cmp rax, -4 ; -EINTR: interrupted by a signal
je .accept_loop
cmp rax, -103 ; -ECONNABORTED: client gave up first
je .accept_loop
jmp .fatal ; anything else (e.g. -EMFILE) won't fix itself
.got_client:
mov r13, rax ; r13 = client socket fd
; ---- Echo Loop for This Client ----
.client_loop:
mov rax, 0 ; sys_read
mov rdi, r13 ; client fd
lea rsi, [net_buf]
mov rdx, 1024 ; buffer size = max read
syscall
cmp rax, 0
jle .close_client ; EOF or error -> close
; Write back what we received, looping on partial writes
mov r14, rax ; bytes still to send
lea r15, [net_buf] ; current position
.send_loop:
test r14, r14
jz .client_loop ; all sent: read the next chunk
mov rax, 44 ; sys_sendto
mov rdi, r13 ; client fd
mov rsi, r15
mov rdx, r14
mov r10, 0x4000 ; MSG_NOSIGNAL: no SIGPIPE if the client left
xor r8, r8 ; no destination address
xor r9, r9
syscall
test rax, rax
jle .close_client ; error (e.g. -EPIPE): drop this client
add r15, rax
sub r14, rax
jmp .send_loop
.close_client:
mov rax, 3 ; sys_close
mov rdi, r13
syscall
jmp .accept_loop ; wait for next client
.fatal:
mov rax, 60
mov rdi, 1
syscall

Testing the Server

You can test the echo server using nc (netcat):

bash
# Terminal 1: Run the server
nasm -f elf64 echo_server.asm -o echo_server.o
ld echo_server.o -o echo_server
./echo_server
# Terminal 2: Connect and test
echo "Hello, Assembly!" | nc localhost 8080
# Should print back: Hello, Assembly!
Security: Input Length Validation Is Non-Negotiable

Even this little echo program needs length validation. Our sys_read caps input at 1024 bytes because that's the buffer size. Pass a larger number in rdx and the kernel will happily walk past the end of your buffer, corrupting whatever's next door. Every buffer has a size. Every read has to respect it. No exceptions.

Security Analysis of Our Echo Server

Our toy server has plenty of holes that a production version would have to close:

  1. Single-threaded: one client at a time. Everyone else waits, which makes denial of service trivial.
  2. No input sanitisation: it echoes whatever bytes show up. Real services usually need to filter or validate.
  3. No timeout: a client that connects and goes silent holds the server forever.
  4. No logging: no record of who connected, when, or what they sent.
  5. No syscall restriction: the process can invoke anything. A seccomp policy would clip the damage if someone found a way in.

Even fifty lines of code has a real attack surface. Security isn't bolted on at the end — it's a design constraint from line one.

Try It Yourself

The sandbox checks Part 1 only, so build the stdin echo program below. Run the network server from Part 2 on your own machine and test it with nc. Read from stdin, write to stdout, get the byte count right, and bail cleanly on EOF.

Practise on your own machine

You need Linux on x86-64: a virtual machine, WSL 2 on Windows, or a container. Then install the tools with sudo apt install nasm gcc gdb binutils.

What is Next

Syscalls, file I/O, and network programming are now under your belt. The next module digs into how assembly meshes with the C ecosystem — object files, linking, calling into libc, and writing position-independent code for shared libraries.

Challenges

Write a program that reads up to 256 bytes from stdin using the read syscall, then writes those bytes back to stdout using the write syscall. The program should handle the byte count correctly.

Assembly (NASM 2.14.02)