Skip to content

Commit

Permalink
Bmap file integrity check
Browse files Browse the repository at this point in the history
Checks if the bmap hash is correct for the current bmap file.
Bmap file checksum is calculated having that field as all 0s.
In order to calculate the checksum we need to set the field in the file
as all "0" before applying Sha256.

Closes: #50

Signed-off-by: Rafael Garcia Ruiz <[email protected]>
  • Loading branch information
Razaloc committed Dec 5, 2022
1 parent df43cf8 commit 4004d0f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion bmap-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ anyhow = "1.0.66"
nix = "0.26.1"
flate2 = "1.0.24"
clap = { version = "4.0.18", features = ["derive"] }
indicatif = "0.17.1"
indicatif = "0.17.1"
sha2 = { version = "0.10.6", features = [ "asm" ] }
hex = "0.4.3"
19 changes: 19 additions & 0 deletions bmap-rs/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use clap::Parser;
use flate2::read::GzDecoder;
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use nix::unistd::ftruncate;
use sha2::{Digest, Sha256};
use std::ffi::OsStr;
use std::fmt::Write;
use std::fs::File;
Expand Down Expand Up @@ -89,6 +90,23 @@ fn setup_input(path: &Path) -> Result<Decoder> {
}
}

fn bmap_integrity(checksum: String, xml: String) -> Result<()> {
//Unset the checksum
let mut bmap_hash = Sha256::new();
let default = "0".repeat(64);
let before_checksum = xml.replace(&checksum, &default);

//Compare given and created checksum
bmap_hash.update(before_checksum);
let digest = bmap_hash.finalize_reset();
let new_checksum = hex::encode(digest.as_slice());
if checksum != new_checksum {
bail!("Bmap file doesn't match its checksum. It could be corrupted or compromised.")
}
println!("Bmap integrity checked!");
Ok(())
}

fn copy(c: Copy) -> Result<()> {
if !c.image.exists() {
bail!("Image file doesn't exist")
Expand All @@ -102,6 +120,7 @@ fn copy(c: Copy) -> Result<()> {
b.read_to_string(&mut xml)?;

let bmap = Bmap::from_xml(&xml)?;
bmap_integrity(bmap.bmap_file_checksum(), xml)?;
let output = std::fs::OpenOptions::new()
.write(true)
.create(true)
Expand Down

0 comments on commit 4004d0f

Please sign in to comment.