檔案與目錄操作 API 大同小異,本節示範 既有檔案新增規則 與 建立檔案時預設安全 兩種模式,並解釋為何後者能避免競態條件 (TOCTOU)。
using (FileStream file = new FileStream(
@"E:\AclTest\acltest.txt", FileMode.Open, FileAccess.ReadWrite)) {
FileSecurity security = file.GetAccessControl();
var rule = new FileSystemAccessRule(
new NTAccount(@"XuanHunComputer\xuanhun"),
FileSystemRights.Read,
AccessControlType.Allow);
security.AddAccessRule(rule);
file.SetAccessControl(security); // 持久化
}
FileSecurity security = new FileSecurity();
var rule = new FileSystemAccessRule(
new NTAccount(@"XuanHunComputer\xuanhun"),
FileSystemRights.Read,
AccessControlType.Allow);
security.AddAccessRule(rule);
FileStream file = new FileStream(
@"M:\temp\sample.txt",
FileMode.CreateNew,
FileSystemRights.Read, // 存取權限
FileShare.None, // 共享模式
4096, // 緩衝區大小
FileOptions.None,
security); // 傳入安全描述符
| 時機 | 既有檔案 | 建立新檔案 |
|---|---|---|
| 步驟順序 | 開啟 → 取得安全 → 修改 → 持久化 | 建構安全 → 建立檔案 (傳入安全) |
| 競態視窗 | 有 (建立與套用安全之間) | 無 (原子性建立) |
| 需呼叫 SetAccessControl | 是 | 否 (建構函數內完成) |
FileSecurity 實現 **原子性安全建立**,消除視窗最佳實務:敏感資料檔案**務必在 CreateNew 時指定 FileSecurity**;僅在無法預知權限 (如使用者上傳) 時採用事後修改,並儘量縮短視窗。
本文部分內容改編自《.NET 安全揭秘》
作者:玄魂
出處:https://www.cnblogs.com/xuanhun/