1
0
forked from brl/citadel-tools

refactored scattered functions into a class

This commit is contained in:
Bruce Leidl 2019-04-02 15:16:49 -04:00
parent 81e9e224fc
commit 8a65aa1708

View File

@ -1,117 +1,118 @@
use std::path::{Path,PathBuf}; use std::path::{Path,PathBuf};
use std::collections::HashMap; use std::collections::HashMap;
use std::process::{Command, Stdio};
use std::fs::{self, OpenOptions,File}; use std::fs::{self, OpenOptions,File};
use std::io; use std::io;
use failure::ResultExt; use crate::{Result, MetaInfo, Partition, LoopDevice, Mountpoint};
use crate::{Result,MetaInfo,Partition,util};
const VERITYSETUP: &str = "/sbin/veritysetup";
const LOSETUP: &str = "/sbin/losetup";
/// Generate dm-verity hashtree for a disk image and store in external file. pub struct Verity {
/// Parse output from veritysetup command and return as `VerityOutput`. image: PathBuf,
pub fn generate_initial_hashtree<P: AsRef<Path>, Q:AsRef<Path>>(source: P, hashtree: Q) -> Result<VerityOutput> {
let args = format!("format {} {}", source.as_ref().display(), hashtree.as_ref().display());
// Don't use absolute path to veritysetup so that the build will correctly find the version from cryptsetup-native
let output = util::exec_cmdline_with_output("veritysetup", args)
.context("creating initial hashtree with veritysetup format failed")?;
Ok(VerityOutput::parse(&output))
} }
pub fn generate_image_hashtree<P: AsRef<Path>>(image: P, metainfo: &MetaInfo) -> Result<VerityOutput> { impl Verity {
let verityfile = image.as_ref().with_extension("verity"); const VERITYSETUP: &'static str = "/sbin/veritysetup";
// Make sure file size is correct or else verity tree will be appended in wrong place pub fn new(image: impl AsRef<Path>) -> Self {
let meta = image.as_ref().metadata()?; let image = image.as_ref().to_path_buf();
let len = meta.len() as usize; Verity { image }
let expected = (metainfo.nblocks() + 1) * 4096;
if len != expected {
bail!("Actual file size ({}) does not match expected size ({})", len, expected);
} }
let vout = with_loopdev(image.as_ref(), |loopdev| { pub fn generate_initial_hashtree(&self, output: impl AsRef<Path>) -> Result<VerityOutput> {
let args = format!("--data-blocks={} --salt={} format {} {}", let output = output.as_ref();
metainfo.nblocks(), metainfo.verity_salt(), // Don't use absolute path to veritysetup so that the build will correctly find the version from cryptsetup-native
loopdev, verityfile.display()); let output = cmd_with_output!("veritysetup", "format {} {}", self.path_str(), output.display())?;
let output = util::exec_cmdline_with_output(VERITYSETUP, args)?;
Ok(VerityOutput::parse(&output)) Ok(VerityOutput::parse(&output))
})?; }
let mut input = File::open(&verityfile)?; pub fn generate_image_hashtree(&self, metainfo: &MetaInfo) -> Result<VerityOutput> {
let mut output = OpenOptions::new().append(true).open(image.as_ref())?; let verity_salt = metainfo.verity_salt();
io::copy(&mut input, &mut output)?; self.generate_image_hashtree_with_salt(metainfo, verity_salt)
fs::remove_file(&verityfile)?; }
Ok(vout) pub fn generate_image_hashtree_with_salt(&self, metainfo: &MetaInfo, salt: &str) -> Result<VerityOutput> {
}
pub fn verify_image<P: AsRef<Path>>(image: P, metainfo: &MetaInfo) -> Result<bool> { let verityfile = self.image.with_extension("verity");
with_loopdev(image.as_ref(), |loopdev| { let nblocks = metainfo.nblocks();
let status = Command::new(VERITYSETUP)
.arg(format!("--hash-offset={}", metainfo.nblocks() * 4096))
.arg("verify")
.arg(&loopdev)
.arg(&loopdev)
.arg(metainfo.verity_root())
.stderr(Stdio::inherit())
.status()?;
Ok(status.success())
})
}
// Make sure file size is correct or else verity tree will be appended in wrong place
let meta = self.image.metadata()?;
let len = meta.len() as usize;
let expected = (nblocks + 1) * 4096;
if len != expected {
bail!("Actual file size ({}) does not match expected size ({})", len, expected);
}
let vout = LoopDevice::with_loop(self.path(), Some(4096), true, |loopdev| {
let output = cmd_with_output!(Self::VERITYSETUP, "--data-blocks={} --salt={} format {} {}",
nblocks, salt, loopdev, verityfile.display())?;
Ok(VerityOutput::parse(&output))
})?;
let mut input = File::open(&verityfile)?;
let mut output = OpenOptions::new().append(true).open(self.path())?;
io::copy(&mut input, &mut output)?;
fs::remove_file(&verityfile)?;
Ok(vout)
}
pub fn verify(&self, metainfo: &MetaInfo) -> Result<bool> {
LoopDevice::with_loop(self.path(), Some(4096), true, |loopdev| {
cmd_ok!(Self::VERITYSETUP, "--hash-offset={} verify {} {} {}",
metainfo.nblocks() * 4096,
loopdev, loopdev, metainfo.verity_root())
})
}
pub fn setup_image_device<P: AsRef<Path>>(image: P, metainfo: &MetaInfo) -> Result<PathBuf> { pub fn setup(&self, metainfo: &MetaInfo) -> Result<String> {
let devname = if metainfo.image_type() == "rootfs" { LoopDevice::with_loop(self.path(), Some(4096), true, |loopdev| {
String::from("rootfs") let devname = Self::device_name(metainfo);
} else if metainfo.image_type() == "realmfs" { let srcdev = loopdev.to_string();
let name = metainfo.realmfs_name() Self::setup_device(&srcdev, &devname, metainfo)?;
.ok_or(format_err!("Cannot set up dm-verity on a realmfs '{}' because it has no name field in metainfo", Ok(devname)
image.as_ref().display()))?; })
format!("verity-realmfs-{}", name) }
} else {
format!("verity-{}", metainfo.image_type())
};
with_loopdev(image.as_ref(), |loopdev| { pub fn setup_partition(partition: &Partition) -> Result<()> {
setup_device(&loopdev, &devname, metainfo.nblocks(), metainfo.verity_root()) let metainfo = partition.header().metainfo();
}) let srcdev = partition.path().to_str().unwrap();
} Self::setup_device(srcdev, "rootfs", &metainfo)
}
fn with_loopdev<F,R>(image: &Path, f: F) -> Result<R> pub fn close_device(device_name: &str) -> Result<()> {
where F: FnOnce(&str) -> Result<R> info!("Removing verity device {}", device_name);
{ cmd!(Self::VERITYSETUP, "close {}", device_name)
let loopdev = create_image_loop_device(image.as_ref())?; }
let result = f(&loopdev);
let result_losetup = util::exec_cmdline(LOSETUP, format!("-d {}", loopdev));
let r = result?;
result_losetup.context("Error removing loop device created to generate verity tree")?;
Ok(r)
}
pub fn device_name(metainfo: &MetaInfo) -> String {
if metainfo.image_type() == "rootfs" {
String::from("rootfs")
} else if metainfo.image_type() == "realmfs" {
let name = metainfo.realmfs_name().unwrap_or("unknown");
format!("verity-realmfs-{}-{}", name, metainfo.verity_tag())
} else {
format!("verity-{}", metainfo.image_type())
}
}
pub fn setup_partition_device(partition: &Partition) -> Result<PathBuf> { pub fn device_name_for_mountpoint(mountpoint: &Mountpoint) -> String {
let metainfo = partition.header().metainfo()?; format!("verity-realmfs-{}-{}", mountpoint.realmfs(), mountpoint.tag())
let srcdev = partition.path().to_str().unwrap(); }
setup_device(srcdev, "rootfs", metainfo.nblocks(), metainfo.verity_root())
}
fn setup_device(srcdev: &str, devname: &str, nblocks: usize, roothash: &str) -> Result<PathBuf> { fn setup_device(srcdev: &str, devname: &str, metainfo: &MetaInfo) -> Result<()> {
let args = format!("--hash-offset={} --data-blocks={} create {} {} {} {}", let nblocks = metainfo.nblocks();
nblocks * 4096, nblocks, devname, srcdev, srcdev, roothash); let verity_root = metainfo.verity_root();
util::exec_cmdline(VERITYSETUP, args) cmd!(Self::VERITYSETUP, "--hash-offset={} --data-blocks={} create {} {} {} {}",
.context("Failed to set up verity device")?; nblocks * 4096, nblocks, devname, srcdev, srcdev, verity_root)?;
Ok(PathBuf::from(format!("/dev/mapper/{}", devname))) Ok(())
} }
fn create_image_loop_device(file: &Path) -> Result<String> { fn path(&self) -> &Path {
let args = format!("--offset 4096 --read-only -f --show {}", file.display()); &self.image
let output = util::exec_cmdline_with_output(LOSETUP, args)?; }
Ok(output)
fn path_str(&self) -> &str {
self.image.to_str().unwrap()
}
} }
/// The output from the `veritysetup format` command can be parsed as key/value /// The output from the `veritysetup format` command can be parsed as key/value