daily-tech:2026-11-16
現象:一個指標,為什麼不能直接讀? / Symptom: Why can’t one pointer simply be read?
寫 eBPF 時,最容易踩到的坑不是語法,而是「我明明先算出位址,為什麼載入核心就被拒絕?」原因是 eBPF 程式會在核心內執行;Linux 不能等錯誤發生後才補救,因此載入前先由 verifier 檢查指標型別、數值範圍、對齊與控制流程。
When writing eBPF, the frustrating failure is often not syntax: “I calculated the address, so why did the kernel reject the program?” eBPF runs inside the kernel. Linux therefore checks pointer types, value ranges, alignment, and control flow before loading instead of repairing a fault afterward.
機制:verifier 追蹤的是狀態,不是猜測 / Mechanism: the verifier tracks states, not guesses
官方文件把暫存器分成 scalar 與多種 pointer。scalar 會保存最小、最大值與未知位元;指標則帶著來源與可存取範圍。以封包為例,先取出 data 與 data_end,再確認 data 加上標頭長度沒有越過 data_end,之後那個分支內的讀取才被視為安全。若中間把指標做成無法證明範圍的運算,狀態會退化成 scalar,後面的記憶體讀取就會失效。
The kernel documentation describes registers as scalars or several pointer types. A scalar carries bounds and unknown bits; a pointer carries its origin and an accessible range. For packet data, the program loads data and data_end, proves that the header fits before data_end, and only then reads it. If an operation destroys the verifier’s range knowledge, the pointer becomes a scalar and a later memory read is rejected.
影響:可觀測性換來額外約束 / Impact: observability comes with constraints
這種設計讓 eBPF 能接近核心熱路徑,卻也讓「看起來合理」不等於「可證明安全」。NULL 檢查會改變後續分支的型別;map value、socket reference 與封包指標也各有生命週期規則。工程上不要只盯著 verifier log 的最後一行,應回頭找哪個分支讓範圍或 reference 狀態遺失。
This design lets eBPF observe hot kernel paths, but “looks reasonable” is not the same as “provably safe.” A NULL check changes the type known in the following branch, while map values, socket references, and packet pointers have different lifetime rules. When a load fails, do not read only the last verifier line; find the branch where range or reference knowledge was lost.
可操作步驟:先縮小,再驗證 / Practical steps: narrow first, then verify
先把程式縮成一個最小讀取:明確檢查 data_end,再讀固定長度;接著一次只加入一個 helper、map lookup 或分支。用 bpftool 或 loader 保留完整 verifier log,並在與目標核心相同版本的測試環境跑過。這不是保證程式永遠安全,而是讓每個安全假設都能被核心的規則檢查。
Reduce the program to one minimal read: check data_end explicitly, then read a fixed length. Add one helper, map lookup, or branch at a time. Keep the complete verifier log with bpftool or your loader, and test on a kernel version matching the target. This does not promise universal safety; it makes each safety assumption visible to the kernel’s rules.
void *data = (void *)(long)skb->data;
void *end = (void *)(long)skb->data_end;
if (data + sizeof(struct ethhdr) > end) return 0;
/* only after the proof: read the header */來源 / Sources:Linux Kernel eBPF verifier;Linux BPF documentation。查核日:2026-11-16(Asia/Taipei)。
留言
張貼留言