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 Jan 13, 2023
1 parent ec421bc commit 063caeb
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions bmap-rs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ tokio = { version = "1.21.2", features = ["rt", "macros", "fs", "rt-multi-thread
reqwest = { version = "0.11.12", features = ["stream"] }
tokio-util = { version = "0.7.4", features = ["compat"] }
futures = "0.3.25"
sha2 = { version = "0.10.6", features = [ "asm" ] }
hex = "0.4.3"
20 changes: 20 additions & 0 deletions bmap-rs/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use futures::TryStreamExt;
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
use nix::unistd::ftruncate;
use reqwest::{Response, Url};
use sha2::{Digest, Sha256};
use std::ffi::OsStr;
use std::fmt::Write;
use std::fs::File;
Expand Down Expand Up @@ -150,6 +151,24 @@ async fn setup_remote_input(url: Url) -> Result<Response> {
}
}

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 setup_progress_bar(bmap: &Bmap) -> ProgressBar {
let pb = ProgressBar::new(bmap.total_mapped_size());
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
Expand Down Expand Up @@ -184,6 +203,7 @@ fn copy_local_input(source: PathBuf, destination: PathBuf) -> 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 063caeb

Please sign in to comment.