blob: 6706a08fd46f6e35cfba04e5d5b500b367057ff5 [file] [log] [blame]
Victor Hsiehac4f3f42021-02-26 12:35:58 -08001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! A module for writing to a file from a trusted world to an untrusted storage.
18//!
19//! Architectural Model:
20//! * Trusted world: the writer, a signing secret, has some memory, but NO persistent storage.
21//! * Untrusted world: persistent storage, assuming untrusted.
22//! * IPC mechanism between trusted and untrusted world
23//!
24//! Use cases:
25//! * In the trusted world, we want to generate a large file, sign it, and share the signature for
26//! a third party to verify the file.
27//! * In the trusted world, we want to read a previously signed file back with signature check
28//! without having to touch the whole file.
29//!
30//! Requirements:
31//! * Communication between trusted and untrusted world is not cheap, and files can be large.
32//! * A file write pattern may not be sequential, neither does read.
33//!
34//! Considering the above, a technique similar to fs-verity is used. fs-verity uses an alternative
35//! hash function, a Merkle tree, to calculate the hash of file content. A file update at any
36//! location will propagate the hash update from the leaf to the root node. Unlike fs-verity, which
37//! assumes static files, to support write operation, we need to allow the file (thus tree) to
38//! update.
39//!
40//! For the trusted world to generate a large file with random write and hash it, the writer needs
41//! to hold some private information and update the Merkle tree during a file write (or even when
42//! the Merkle tree needs to be stashed to the untrusted storage).
43//!
44//! A write to a file must update the root hash. In order for the root hash to update, a tree
45//! walk to update from the write location to the root node is necessary. Importantly, in case when
46//! (part of) the Merkle tree needs to be read from the untrusted storage (e.g. not yet verified in
47//! cache), the original path must be verified by the trusted signature before the update to happen.
48//!
49//! Denial-of-service is a known weakness if the untrusted storage decides to simply remove the
50//! file. But there is nothing we can do in this architecture.
51//!
52//! Rollback attack is another possible attack, but can be addressed with a rollback counter when
53//! possible.
54
55use std::io;
56use std::sync::{Arc, RwLock};
57
58use crate::common::{ChunkedSizeIter, CHUNK_SIZE};
59use crate::crypto::{CryptoError, Sha256Hash, Sha256Hasher};
60use crate::fsverity::MerkleLeaves;
61use crate::reader::ReadOnlyDataByChunk;
62
63// Implement the conversion from `CryptoError` to `io::Error` just to avoid manual error type
64// mapping below.
65impl From<CryptoError> for io::Error {
66 fn from(error: CryptoError) -> Self {
67 io::Error::new(io::ErrorKind::Other, error)
68 }
69}
70
71/// A trait to write a buffer to the destination at a given offset. The implementation does not
72/// necessarily own or maintain the destination state.
73pub trait RandomWrite {
74 /// Writes `buf` to the destination at `offset`. Returns the written size, which may not be the
75 /// full buffer.
76 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>;
77
78 /// Writes the full `buf` to the destination at `offset`.
79 fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
80 let mut input_offset = 0;
81 let mut output_offset = offset;
82 while input_offset < buf.len() {
83 let size = self.write_at(&buf[input_offset..], output_offset)?;
84 input_offset += size;
85 output_offset += size as u64;
86 }
87 Ok(())
88 }
89}
90
91/// VerifiedFileEditor provides an integrity layer to an underlying read-writable file, which may
92/// not be stored in a trusted environment. Only new, empty files are currently supported.
93pub struct VerifiedFileEditor<F: ReadOnlyDataByChunk + RandomWrite> {
94 file: F,
95 merkle_tree: Arc<RwLock<MerkleLeaves>>,
96}
97
98#[allow(dead_code)]
99impl<F: ReadOnlyDataByChunk + RandomWrite> VerifiedFileEditor<F> {
100 /// Wraps a supposedly new file for integrity protection.
101 pub fn new(file: F) -> Self {
102 Self { file, merkle_tree: Arc::new(RwLock::new(MerkleLeaves::new())) }
103 }
104
105 /// Calculates the fs-verity digest of the current file.
106 pub fn calculate_fsverity_digest(&self) -> io::Result<Sha256Hash> {
107 let merkle_tree = self.merkle_tree.read().unwrap();
108 merkle_tree.calculate_fsverity_digest().map_err(|e| io::Error::new(io::ErrorKind::Other, e))
109 }
110
111 fn new_hash_for_incomplete_write(
112 &self,
113 source: &[u8],
114 offset_from_alignment: usize,
115 output_chunk_index: usize,
116 merkle_tree: &mut MerkleLeaves,
117 ) -> io::Result<Sha256Hash> {
118 // The buffer is initialized to 0 purposely. To calculate the block hash, the data is
119 // 0-padded to the block size. When a chunk read is less than a chunk, the initial value
120 // conveniently serves the padding purpose.
121 let mut orig_data = [0u8; CHUNK_SIZE as usize];
122
123 // If previous data exists, read back and verify against the known hash (since the
124 // storage / remote server is not trusted).
125 if merkle_tree.is_index_valid(output_chunk_index) {
126 self.read_chunk(output_chunk_index as u64, &mut orig_data)?;
127
128 // Verify original content
129 let hash = Sha256Hasher::new()?.update(&orig_data)?.finalize()?;
130 if !merkle_tree.is_consistent(output_chunk_index, &hash) {
131 return Err(io::Error::new(io::ErrorKind::InvalidData, "Inconsistent hash"));
132 }
133 }
134
135 Ok(Sha256Hasher::new()?
136 .update(&orig_data[..offset_from_alignment])?
137 .update(source)?
138 .update(&orig_data[offset_from_alignment + source.len()..])?
139 .finalize()?)
140 }
141
142 fn new_chunk_hash(
143 &self,
144 source: &[u8],
145 offset_from_alignment: usize,
146 current_size: usize,
147 output_chunk_index: usize,
148 merkle_tree: &mut MerkleLeaves,
149 ) -> io::Result<Sha256Hash> {
150 if current_size as u64 == CHUNK_SIZE {
151 // Case 1: If the chunk is a complete one, just calculate the hash, regardless of
152 // write location.
153 Ok(Sha256Hasher::new()?.update(source)?.finalize()?)
154 } else {
155 // Case 2: For an incomplete write, calculate the hash based on previous data (if
156 // any).
157 self.new_hash_for_incomplete_write(
158 source,
159 offset_from_alignment,
160 output_chunk_index,
161 merkle_tree,
162 )
163 }
164 }
165}
166
167impl<F: ReadOnlyDataByChunk + RandomWrite> RandomWrite for VerifiedFileEditor<F> {
168 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
169 // Since we don't need to support 32-bit CPU, make an assert to make conversion between
170 // u64 and usize easy below. Otherwise, we need to check `divide_roundup(offset + buf.len()
171 // <= usize::MAX` or handle `TryInto` errors.
172 debug_assert!(usize::MAX as u64 == u64::MAX, "Only 64-bit arch is supported");
173
174 // The write range may not be well-aligned with the chunk boundary. There are various cases
175 // to deal with:
176 // 1. A write of a full 4K chunk.
177 // 2. A write of an incomplete chunk, possibly beyond the original EOF.
178 //
179 // Note that a write beyond EOF can create a hole. But we don't need to handle it here
180 // because holes are zeros, and leaves in MerkleLeaves are hashes of 4096-zeros by
181 // default.
182
183 // Now iterate on the input data, considering the alignment at the destination.
184 for (output_offset, current_size) in
185 ChunkedSizeIter::new(buf.len(), offset, CHUNK_SIZE as usize)
186 {
187 // Lock the tree for the whole write for now. There may be room to improve to increase
188 // throughput.
189 let mut merkle_tree = self.merkle_tree.write().unwrap();
190
191 let offset_in_buf = (output_offset - offset) as usize;
192 let source = &buf[offset_in_buf as usize..offset_in_buf as usize + current_size];
193 let output_chunk_index = (output_offset / CHUNK_SIZE) as usize;
194 let offset_from_alignment = (output_offset % CHUNK_SIZE) as usize;
195
196 let new_hash = match self.new_chunk_hash(
197 source,
198 offset_from_alignment,
199 current_size,
200 output_chunk_index,
201 &mut merkle_tree,
202 ) {
203 Ok(hash) => hash,
204 Err(e) => {
205 // Return early when any error happens before the right. Even if the hash is not
206 // consistent for the current chunk, we can still consider the earlier writes
207 // successful. Note that nothing persistent has been done in this iteration.
208 let written = output_offset - offset;
209 if written > 0 {
210 return Ok(written as usize);
211 }
212 return Err(e);
213 }
214 };
215
216 // A failed, partial write here will make the backing file inconsistent to the (old)
217 // hash. Nothing can be done within this writer, but at least it still maintains the
218 // (original) integrity for the file. To matches what write(2) describes for an error
219 // case (though it's about direct I/O), "Partial data may be written ... should be
220 // considered inconsistent", an error below is propagated.
221 self.file.write_all_at(&source, output_offset)?;
222
223 // Update the hash only after the write succeeds. Note that this only attempts to keep
224 // the tree consistent to what has been written regardless the actual state beyond the
225 // writer.
226 let size_at_least = offset.saturating_add(buf.len() as u64);
227 merkle_tree.update_hash(output_chunk_index, &new_hash, size_at_least);
228 }
229 Ok(buf.len())
230 }
231}
232
233impl<F: ReadOnlyDataByChunk + RandomWrite> ReadOnlyDataByChunk for VerifiedFileEditor<F> {
234 fn read_chunk(&self, chunk_index: u64, buf: &mut [u8]) -> io::Result<usize> {
235 self.file.read_chunk(chunk_index, buf)
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 // Test data below can be generated by:
242 // $ perl -e 'print "\x{00}" x 6000' > foo
243 // $ perl -e 'print "\x{01}" x 5000' >> foo
244 // $ fsverity digest foo
245 use super::*;
246 use anyhow::Result;
247 use std::cell::RefCell;
248 use std::convert::TryInto;
249
250 struct InMemoryWriter {
251 data: RefCell<Vec<u8>>,
252 fail_read: bool,
253 }
254
255 impl InMemoryWriter {
256 pub fn new() -> InMemoryWriter {
257 InMemoryWriter { data: RefCell::new(Vec::new()), fail_read: false }
258 }
259 }
260
261 impl RandomWrite for InMemoryWriter {
262 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
263 let begin: usize =
264 offset.try_into().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
265 let end = begin + buf.len();
266 if end > self.data.borrow().len() {
267 self.data.borrow_mut().resize(end, 0);
268 }
269 self.data.borrow_mut().as_mut_slice()[begin..end].copy_from_slice(&buf);
270 Ok(buf.len())
271 }
272 }
273
274 impl ReadOnlyDataByChunk for InMemoryWriter {
275 fn read_chunk(&self, chunk_index: u64, buf: &mut [u8]) -> io::Result<usize> {
276 debug_assert!(buf.len() as u64 >= CHUNK_SIZE);
277
278 if self.fail_read {
279 return Err(io::Error::new(io::ErrorKind::Other, "test!"));
280 }
281
282 let borrowed = self.data.borrow();
283 let chunk = &borrowed
284 .chunks(CHUNK_SIZE as usize)
285 .nth(chunk_index as usize)
286 .ok_or_else(|| {
287 io::Error::new(
288 io::ErrorKind::InvalidInput,
289 format!("read_chunk out of bound: index {}", chunk_index),
290 )
291 })?;
292 buf[..chunk.len()].copy_from_slice(&chunk);
293 Ok(chunk.len())
294 }
295 }
296
297 #[test]
298 fn test_writer() -> Result<()> {
299 let writer = InMemoryWriter::new();
300 let buf = [1; 4096];
301 assert_eq!(writer.data.borrow().len(), 0);
302
303 assert_eq!(writer.write_at(&buf, 16384)?, 4096);
304 assert_eq!(writer.data.borrow()[16384..16384 + 4096], buf);
305
306 assert_eq!(writer.write_at(&buf, 2048)?, 4096);
307 assert_eq!(writer.data.borrow()[2048..2048 + 4096], buf);
308
309 assert_eq!(writer.data.borrow().len(), 16384 + 4096);
310 Ok(())
311 }
312
313 #[test]
314 fn test_verified_writer_no_write() -> Result<()> {
315 // Verify fs-verity hash without any write.
316 let file = VerifiedFileEditor::new(InMemoryWriter::new());
317 assert_eq!(
318 file.calculate_fsverity_digest()?,
319 to_u8_vec("3d248ca542a24fc62d1c43b916eae5016878e2533c88238480b26128a1f1af95")
320 .as_slice()
321 );
322 Ok(())
323 }
324
325 #[test]
326 fn test_verified_writer_from_zero() -> Result<()> {
327 // Verify a write of a full chunk.
328 let file = VerifiedFileEditor::new(InMemoryWriter::new());
329 assert_eq!(file.write_at(&[1; 4096], 0)?, 4096);
330 assert_eq!(
331 file.calculate_fsverity_digest()?,
332 to_u8_vec("cd0875ca59c7d37e962c5e8f5acd3770750ac80225e2df652ce5672fd34500af")
333 .as_slice()
334 );
335
336 // Verify a write of across multiple chunks.
337 let file = VerifiedFileEditor::new(InMemoryWriter::new());
338 assert_eq!(file.write_at(&[1; 4097], 0)?, 4097);
339 assert_eq!(
340 file.calculate_fsverity_digest()?,
341 to_u8_vec("2901b849fda2d91e3929524561c4a47e77bb64734319759507b2029f18b9cc52")
342 .as_slice()
343 );
344
345 // Verify another write of across multiple chunks.
346 let file = VerifiedFileEditor::new(InMemoryWriter::new());
347 assert_eq!(file.write_at(&[1; 10000], 0)?, 10000);
348 assert_eq!(
349 file.calculate_fsverity_digest()?,
350 to_u8_vec("7545409b556071554d18973a29b96409588c7cda4edd00d5586b27a11e1a523b")
351 .as_slice()
352 );
353 Ok(())
354 }
355
356 #[test]
357 fn test_verified_writer_unaligned() -> Result<()> {
358 // Verify small, unaligned write beyond EOF.
359 let file = VerifiedFileEditor::new(InMemoryWriter::new());
360 assert_eq!(file.write_at(&[1; 5], 3)?, 5);
361 assert_eq!(
362 file.calculate_fsverity_digest()?,
363 to_u8_vec("a23fc5130d3d7b3323fc4b4a5e79d5d3e9ddf3a3f5872639e867713512c6702f")
364 .as_slice()
365 );
366
367 // Verify bigger, unaligned write beyond EOF.
368 let file = VerifiedFileEditor::new(InMemoryWriter::new());
369 assert_eq!(file.write_at(&[1; 6000], 4000)?, 6000);
370 assert_eq!(
371 file.calculate_fsverity_digest()?,
372 to_u8_vec("d16d4c1c186d757e646f76208b21254f50d7f07ea07b1505ff48b2a6f603f989")
373 .as_slice()
374 );
375 Ok(())
376 }
377
378 #[test]
379 fn test_verified_writer_with_hole() -> Result<()> {
380 // Verify an aligned write beyond EOF with holes.
381 let file = VerifiedFileEditor::new(InMemoryWriter::new());
382 assert_eq!(file.write_at(&[1; 4096], 4096)?, 4096);
383 assert_eq!(
384 file.calculate_fsverity_digest()?,
385 to_u8_vec("4df2aefd8c2a9101d1d8770dca3ede418232eabce766bb8e020395eae2e97103")
386 .as_slice()
387 );
388
389 // Verify an unaligned write beyond EOF with holes.
390 let file = VerifiedFileEditor::new(InMemoryWriter::new());
391 assert_eq!(file.write_at(&[1; 5000], 6000)?, 5000);
392 assert_eq!(
393 file.calculate_fsverity_digest()?,
394 to_u8_vec("47d5da26f6934484e260630a69eb2eebb21b48f69bc8fbf8486d1694b7dba94f")
395 .as_slice()
396 );
397
398 // Just another example with a small write.
399 let file = VerifiedFileEditor::new(InMemoryWriter::new());
400 assert_eq!(file.write_at(&[1; 5], 16381)?, 5);
401 assert_eq!(
402 file.calculate_fsverity_digest()?,
403 to_u8_vec("8bd118821fb4aff26bb4b51d485cc481a093c68131b7f4f112e9546198449752")
404 .as_slice()
405 );
406 Ok(())
407 }
408
409 #[test]
410 fn test_verified_writer_various_writes() -> Result<()> {
411 let file = VerifiedFileEditor::new(InMemoryWriter::new());
412 assert_eq!(file.write_at(&[1; 2048], 0)?, 2048);
413 assert_eq!(file.write_at(&[1; 2048], 4096 + 2048)?, 2048);
414 assert_eq!(
415 file.calculate_fsverity_digest()?,
416 to_u8_vec("4c433d8640c888b629dc673d318cbb8d93b1eebcc784d9353e07f09f0dcfe707")
417 .as_slice()
418 );
419 assert_eq!(file.write_at(&[1; 2048], 2048)?, 2048);
420 assert_eq!(file.write_at(&[1; 2048], 4096)?, 2048);
421 assert_eq!(
422 file.calculate_fsverity_digest()?,
423 to_u8_vec("2a476d58eb80394052a3a783111e1458ac3ecf68a7878183fed86ca0ff47ec0d")
424 .as_slice()
425 );
426 assert_eq!(file.write_at(&[0; 2048], 2048)?, 2048);
427 assert_eq!(file.write_at(&[0; 2048], 4096)?, 2048);
428 assert_eq!(
429 file.calculate_fsverity_digest()?,
430 to_u8_vec("4c433d8640c888b629dc673d318cbb8d93b1eebcc784d9353e07f09f0dcfe707")
431 .as_slice()
432 );
433 assert_eq!(file.write_at(&[1; 4096], 2048)?, 4096);
434 assert_eq!(
435 file.calculate_fsverity_digest()?,
436 to_u8_vec("2a476d58eb80394052a3a783111e1458ac3ecf68a7878183fed86ca0ff47ec0d")
437 .as_slice()
438 );
439 assert_eq!(file.write_at(&[1; 2048], 8192)?, 2048);
440 assert_eq!(file.write_at(&[1; 2048], 8192 + 2048)?, 2048);
441 assert_eq!(
442 file.calculate_fsverity_digest()?,
443 to_u8_vec("23cbac08371e6ee838ebcc7ae6512b939d2226e802337be7b383c3e046047d24")
444 .as_slice()
445 );
446 Ok(())
447 }
448
449 #[test]
450 fn test_verified_writer_inconsistent_read() -> Result<()> {
451 let file = VerifiedFileEditor::new(InMemoryWriter::new());
452 assert_eq!(file.write_at(&[1; 8192], 0)?, 8192);
453
454 // Replace the expected hash of the first/0-th chunk. An incomplete write will fail when it
455 // detects the inconsistent read.
456 {
457 let mut merkle_tree = file.merkle_tree.write().unwrap();
458 let overriding_hash = [42; Sha256Hasher::HASH_SIZE];
459 merkle_tree.update_hash(0, &overriding_hash, 8192);
460 }
461 assert!(file.write_at(&[1; 1], 2048).is_err());
462
463 // A write of full chunk can still succeed. Also fixed the inconsistency.
464 assert_eq!(file.write_at(&[1; 4096], 4096)?, 4096);
465
466 // Replace the expected hash of the second/1-th chunk. A write range from previous chunk can
467 // still succeed, but returns early due to an inconsistent read but still successfully. A
468 // resumed write will fail since no bytes can be written due to the same inconsistency.
469 {
470 let mut merkle_tree = file.merkle_tree.write().unwrap();
471 let overriding_hash = [42; Sha256Hasher::HASH_SIZE];
472 merkle_tree.update_hash(1, &overriding_hash, 8192);
473 }
474 assert_eq!(file.write_at(&[10; 8000], 0)?, 4096);
475 assert!(file.write_at(&[10; 8000 - 4096], 4096).is_err());
476 Ok(())
477 }
478
479 #[test]
480 fn test_verified_writer_failed_read_back() -> Result<()> {
481 let mut writer = InMemoryWriter::new();
482 writer.fail_read = true;
483 let file = VerifiedFileEditor::new(writer);
484 assert_eq!(file.write_at(&[1; 8192], 0)?, 8192);
485
486 // When a read back is needed, a read failure will fail to write.
487 assert!(file.write_at(&[1; 1], 2048).is_err());
488 Ok(())
489 }
490
491 fn to_u8_vec(hex_str: &str) -> Vec<u8> {
492 assert!(hex_str.len() % 2 == 0);
493 (0..hex_str.len())
494 .step_by(2)
495 .map(|i| u8::from_str_radix(&hex_str[i..i + 2], 16).unwrap())
496 .collect()
497 }
498}