Skip to content

Commit 063caeb

Browse files
committed
Bmap file integrity check
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]>
1 parent ec421bc commit 063caeb

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

Diff for: bmap-rs/Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,5 @@ tokio = { version = "1.21.2", features = ["rt", "macros", "fs", "rt-multi-thread
2222
reqwest = { version = "0.11.12", features = ["stream"] }
2323
tokio-util = { version = "0.7.4", features = ["compat"] }
2424
futures = "0.3.25"
25+
sha2 = { version = "0.10.6", features = [ "asm" ] }
26+
hex = "0.4.3"

Diff for: bmap-rs/src/main.rs

+20
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use futures::TryStreamExt;
77
use indicatif::{ProgressBar, ProgressState, ProgressStyle};
88
use nix::unistd::ftruncate;
99
use reqwest::{Response, Url};
10+
use sha2::{Digest, Sha256};
1011
use std::ffi::OsStr;
1112
use std::fmt::Write;
1213
use std::fs::File;
@@ -150,6 +151,24 @@ async fn setup_remote_input(url: Url) -> Result<Response> {
150151
}
151152
}
152153

154+
fn bmap_integrity(checksum: String, xml: String) -> Result<()> {
155+
//Unset the checksum
156+
let mut bmap_hash = Sha256::new();
157+
let default = "0".repeat(64);
158+
let before_checksum = xml.replace(&checksum, &default);
159+
160+
//Compare given and created checksum
161+
bmap_hash.update(before_checksum);
162+
let digest = bmap_hash.finalize_reset();
163+
let new_checksum = hex::encode(digest.as_slice());
164+
ensure!(
165+
checksum == new_checksum,
166+
"Bmap file doesn't match its checksum. It could be corrupted or compromised."
167+
);
168+
println!("Bmap integrity checked!");
169+
Ok(())
170+
}
171+
153172
fn setup_progress_bar(bmap: &Bmap) -> ProgressBar {
154173
let pb = ProgressBar::new(bmap.total_mapped_size());
155174
pb.set_style(ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})")
@@ -184,6 +203,7 @@ fn copy_local_input(source: PathBuf, destination: PathBuf) -> Result<()> {
184203
b.read_to_string(&mut xml)?;
185204

186205
let bmap = Bmap::from_xml(&xml)?;
206+
bmap_integrity(bmap.bmap_file_checksum(), xml)?;
187207
let output = std::fs::OpenOptions::new()
188208
.write(true)
189209
.create(true)

0 commit comments

Comments
 (0)