Skip to content

Commit f7de05d

Browse files
committed
partitioning/writer: Clear up to first 2MiB per partition
Without doing this, stale data leaks through from underlying medium Signed-off-by: Ikey Doherty <[email protected]>
1 parent 8a40893 commit f7de05d

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

crates/partitioning/src/writer.rs

+28-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
use std::{
77
fs,
8-
io::{Seek, Write},
8+
io::{self, Seek, Write},
99
};
1010

1111
use disks::BlockDevice;
@@ -50,6 +50,21 @@ pub struct DiskWriter<'a> {
5050
pub planner: &'a Planner,
5151
}
5252

53+
/// Zero out up to 2MiB of a region by writing 32 * 64KiB blocks
54+
fn zero_prefix_n<W: Write + Seek>(writer: &mut W, offset: u64, size: u64) -> io::Result<()> {
55+
let zeros = [0u8; 65_536];
56+
writer.seek(std::io::SeekFrom::Start(offset))?;
57+
// Write up to 32 blocks or until we hit the partition size
58+
for _ in 0..32 {
59+
if offset + (65_536 * (32 + 1)) as u64 > size {
60+
break;
61+
}
62+
writer.write_all(&zeros)?;
63+
}
64+
writer.flush()?;
65+
Ok(())
66+
}
67+
5368
impl<'a> DiskWriter<'a> {
5469
/// Create a new DiskWriter.
5570
pub fn new(device: &'a BlockDevice, planner: &'a Planner) -> Self {
@@ -111,16 +126,12 @@ impl<'a> DiskWriter<'a> {
111126
blkpg::remove_kernel_partitions(self.device.device())?;
112127
}
113128

129+
let mut zero_regions = vec![];
130+
114131
let mut gpt_table = if self.planner.wipe_disk() {
115132
if writable {
116133
// Zero out the first MiB to clear any old partition tables and boot sectors
117-
// Write 16*64 KiB = 1 MiB of zeros to the start of the disk
118-
let zeros = [0u8; 65_536];
119-
device.seek(std::io::SeekFrom::Start(0))?;
120-
for _ in 0..16 {
121-
device.write_all(&zeros)?;
122-
}
123-
device.flush()?;
134+
zero_prefix_n(device, 0, 1_048_576)?;
124135

125136
let mbr = mbr::ProtectiveMBR::with_lb_size(
126137
u32::try_from((self.device.size() / 512) - 1).unwrap_or(0xFF_FF_FF_FF),
@@ -178,6 +189,10 @@ impl<'a> DiskWriter<'a> {
178189
let id =
179190
gpt_table.add_partition_at(&part_name, *partition_id, start_lba, size_lba, part_type, 0)?;
180191
println!("Added partition {}: {:?}", partition_id, id);
192+
// Store start and size for zeroing
193+
if writable {
194+
zero_regions.push((*start, *end));
195+
}
181196
}
182197
}
183198
}
@@ -195,6 +210,11 @@ impl<'a> DiskWriter<'a> {
195210
if writable {
196211
let original = gpt_table.write()?;
197212
original.sync_all()?;
213+
214+
for (start, end) in zero_regions {
215+
zero_prefix_n(original, start, end - start)?;
216+
}
217+
198218
blkpg::create_kernel_partitions(self.device.device())?;
199219
}
200220

0 commit comments

Comments
 (0)