Skip to content

Commit

Permalink
Bmap file integrity check
Browse files Browse the repository at this point in the history
Before using a Bmap file checks if its checksum is correct for the
current bmap file.
Bmap checksum is the application of Sha256 to the file data. When the
bmap file is created, the value of the checksum has to be zero (all ASCII
"0" symbols). Once calculated, zeros are replaced by the checksum, notice
this modifies the file itself.
In order to calculate the checksum before using it and compare it with
the original, we need to set the field as all "0" before applying Sha256.

Closes: #50

Signed-off-by: Rafael Garcia Ruiz <[email protected]>
  • Loading branch information
Razaloc committed Dec 15, 2022
1 parent b3426c2 commit e513da0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
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"
22 changes: 21 additions & 1 deletion bmap-rs/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use anyhow::{anyhow, bail, Context, Result};
use anyhow::{anyhow, bail, ensure, Context, Result};
use bmap::{Bmap, Discarder, SeekForward};
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,24 @@ 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());
ensure!(
checksum == new_checksum,
"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 +121,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 e513da0

Please sign in to comment.