簡體   English   中英

如何避免不適合緩沖區的 stdin 輸入被發送到 Linux 64 位 Intel (x86-64) 程序集中的 shell

[英]How to avoid stdin input that does not fit in buffer be sent to the shell in Linux 64-bit Intel (x86-64) assembly

編輯:標題已更改,正如@Gunner 指出的那樣,這不是緩沖區溢出。

在 Linux 64 位 Intel 程序NR_read使用NR_readstdin讀取用戶輸入時,我想知道如何避免將不適合輸入緩沖區的輸入發送到 Linux shell,例如。 砸? 例如,在這個示例程序中,我定義了一個 255 字節的輸入緩沖區(緩沖區的大小可以是任何 >= 1)。 超過 255 個字節的輸入的其余部分被發送到 bash(如果從 bash 運行),這顯然是一個嚴重的漏洞。 如何在 Linux 64 位程序集中讀取輸入以避免此漏洞?

這是我的代碼:

[bits 64]

section .text
global _start

; can be compiled eg. with nasm or yasm.
; nasm:
; nasm -f elf64 read_stdin_64.asm; ld read_stdin_64.o -o read_stdin_64
; yasm:
; yasm -f elf64 -m amd64 read_stdin_64.asm -o read_stdin_64.o; ld read_stdin_64.o -o read_stdin_64

NR_read     equ 0
NR_exit     equ 60

STDIN       equ 1

; input:
; rax   number of syscall
; rdi   parameter 1
; rsi   parameter 2
; rdx   parameter 3
; r10   parameter 4
; r8    parameter 5
; r9    parameter 6
;
; output:
; rax   syscall's output
@do_syscall:
    push    rcx
    push    r11
    syscall      ; 64-bit syscall, overwrites rcx and r11
    pop     r11  ; syscall's return value in rax
    pop     rcx
    ret

@read_stdin:
    push    rdi
    push    rsi
    push    rdx
    mov     rdi,STDIN                ; file handle to read. STDIN = 1.
    lea     rsi,[input_buffer]
    mov     rdx,input_buffer_length  ; length of string
    mov     rax,NR_read              ; number of syscall (0)
    call    @do_syscall
    sub     rax,1                    ; get the number of writable characters.
    pop     rdx
    pop     rsi
    pop     rdi
    ret

_start:     ; linker entry point
    call    @read_stdin

@end_program:
    xor     rdi,rdi
    mov     rax,NR_exit  ; number of syscall (60)
    syscall

section .data

input_buffer         times 255 db 0
input_buffer_length  equ $-input_buffer

讀取 syscall 已經內置了該保護。不過還有一件事:您不應該明確使用syscall 如果您的代碼被帶到 x86-64 機器(使用sysenter )怎么辦? 您應該使用 Linux 的 VDSO(虛擬動態共享對象),其中包含在所有架構上執行系統調用的代碼,無論它們是支持syscallsysenter還是僅支持int

這不是其他人所說的緩沖區溢出。 我寫了一個關於在 Linux 中從終端讀取的教程,它也展示了如何處理這個問題。 它使用 32 位 Int 0x80,但您可以輕松更改它以滿足您的需要。

http://www.dreamincode.net/forums/topic/286248-nasm-linux-terminal-inputoutput-wint-80h/

您可以讀取輸入,直到找到換行符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM