Need working Rust code for creating/editing files on ESP (EFI System Partition) in Windows

⚓ Rust    📅 2025-08-08    👤 surdeus    👁️ 4      

surdeus

Hello everyone!

I am writing a utility in Rust for creating/editing files on the EFI System Partition (ESP) under Windows (creating/editing a file on the FAT32 ESP partition). Reading and backing up work fine, but when I try to write, I run into Windows system protection: I get ERROR_ACCESS_DENIED (code 5) when writing via .\PhysicalDriveN, even with administrator rights.

What has already been done:
• ESP search via GPT has been implemented in Rust:
• I open .\PhysicalDriveN, read GPT (EFI PART), and search for a partition of type C12A7328-F81F-11D2-BA4B-00A0C93EC93B.
• I calculate start_lba and length_lba, read ESP into memory (works stably).
• Implemented volume enumeration (FindFirstVolumeW/FindNextVolumeW) and mapping via IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS:
• Find the volume whose start_lba/length_lba match the ESP on the desired disk.

Tried:
• Locking and unmounting the volume (FSCTL_LOCK_VOLUME/FSCTL_DISMOUNT_VOLUME) — on the volume descriptor; Windows returns ERROR_ACCESS_DENIED.
• Write directly to .\PhysicalDriveN with FILE_FLAG_NO_BUFFERING|WRITE_THROUGH, aligned to sector size — ERROR_ACCESS_DENIED on WriteFile.
• Opening the physical disk with GENERIC_ALL does not help, it falls back to GENERIC_READ|GENERIC_WRITE, writing is still prohibited.
• Dry-run mode (all FAT32 logic in memory) is fully functional: I create/edit a file, correctly update FAT/directories, etc.

Log/symptoms (abbreviated):
• ESP: PhysicalDrive0, start_lba=2048, length_lba=204800, 512 B/sector.
• ESP volume is located correctly: ?\Volume{...}, start_lba=2048, length_lba=204800.
• FSCTL_LOCK_VOLUME on the volume returns 5 (Access denied).
• Writing to .\PhysicalDrive0 at offset start_lba*sector_size — WriteFile -> 5 (Access denied).

Environment:
• Windows 11 x64, running with administrator privileges.
• Rust: 1.78+ (stable), windows library for WinAPI.

Why working “through the file system” is not suitable:
• mountvol X: /s is not always available/reliable in my environment. I need a method that is guaranteed to work in headless/script mode. But if there is a reliable program through the file system without raw I/O, I will also consider it.

I would be very grateful for:
• Rust code snippets/mini-project that you actually write in ESP on Windows 10/11.
• A confirmed working sequence of API calls (FSCTL/IOCTL/privileges/mount).

1 post - 1 participant

Read full topic

🏷️ Rust_feed