linux2021
目的: 檢驗學員對 Linux 記憶體管理、memfd 和 mmap 系統呼叫的認知
1
在 你所不知道的 C 語言:連結器和執行檔資訊 提過 ELF 執行檔格式,更多資訊可見 Executable and Linkable Format,以 64 位元 ELF 來說,開頭的幾個位元組的意義:
offset | size | Purpose |
---|---|---|
0x00 | 4 | 0x7F followed by ELF(45 4c 46 ) in ASCII; these four bytes constitute the magic number. |
0x04 | 1 | This byte is set to either 1 or 2 to signify 32- or 64-bit format, respectively. |
0x05 | 1 | This byte is set to either 1 or 2 to signify little or big endianness, respectively. This affects interpretation of multi-byte fields starting with offset 0x10 . |
x06 | 1 | Set to 1 for the original and current version of ELF. |
… | … | …待續… |
以下程式碼嘗試在既有的 ELF 檔案內嵌另一個 ELF 檔案 (可預先加密),目的是隱匿特定的程式,避免被掃毒程式或防火牆偵測出來,或將高價值的程式嵌入到文件、圖片,甚至是影音檔案中,透過特定的載入器自檔案提取出執行檔並執行,這手法在 Digital rights management (DRM) 和 Digital watermarking 領域不算少見。
假設即將被嵌入的程式碼名為 payload.c
:
編譯並移去除錯用的符號:
接著我們要開發得以載入 ELF 的程式,在這之前,先探討以下函式及系統呼叫:
假定程式載入器檔名為 loader.c
,內容如下:
編譯、嵌入上述 payload
執行檔,然後再執行: (你沒看錯,真的用 cat
命令)
在 x86_64 GNU/Linux (核心版本: 4.15+) 預期輸出為:
注意:只有一行 "Hello world!" 字串
請補完程式碼,只要考慮 x86_64 硬體架構即可。
作答區 (注意: 複選題,儘量選取有效的答案)
AAA = ?
(a)
newelf - entirefile
(b)
size - newelf
(c)
entirefile - newelf
(d)
size - newelf - entirefile
(e)
size - newelf + entirefile
(f)
newelf - entirefile + size
(g)
entirefile - newelf - size
size - (newelf - entirefile)
BBB = ?
(a)
getpid()
(b)
getpid() != pid
(c)
getpid() == pid
(d)
0
(e)
1
延伸問題:
2
考慮以下透過 mmap 實作快速檔案複製的程式碼: mmap-filecopy.c
編譯方式:
假設原本已有檔名為 in
的檔案,且 out
不存在目前的路徑,可執行以下命令:
這樣即可達成快速的檔案複製。
請補完程式碼,使得符合預期。
作答區
PROP = ?
(a)
PROT_READ | PROT_WRITE
(b)
PROT_READ
延伸問題: