3. 調整限制

沙箱政策可防止沙箱政策呼叫特定系統呼叫,進而減少受攻擊面。不過,攻擊者或許還是可以無限期執行程序,或耗盡 RAM 和其他資源,造成不想要的影響。

為因應這項威脅,沙箱預設會在嚴格執行限制下執行。如果這些預設限制會導致程式的正常執行發生問題,您可以在執行程式物件上呼叫 limits(),使用 sandbox2::Limits 類別進行調整。

以下程式碼片段列舉了一些調整上限的範例。所有可用選項都已記錄在 limits.h 標頭檔案中。

// Restrict the address space size of the sandboxee to 4 GiB.
executor->limits()->set_rlimit_as(4ULL << 30);
// Kill sandboxee with SIGXFSZ if it writes more than 1 GiB to the filesystem.
executor->limits()->set_rlimit_fsize(1ULL << 30);
// Number of file descriptors which can be used by the sandboxee.
executor->limits()->set_rlimit_nofile(1ULL << 10);
// The sandboxee is not allowed to create core files.
executor->limits()->set_rlimit_core(0);
// Maximum 300s of real CPU time.
executor->limits()->set_rlimit_cpu(300);
// Maximum 120s of wall time.
executor->limits()->set_walltime_limit(absl::Seconds(120));

如需 sandbox2::Limits 類別的使用範例,請參閱工具範例。