Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utils: Inspect #603

Merged
merged 4 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions bin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ semver = "1.0.20"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
steamlocate = "2.0.0-alpha.0"
term-table = "1.3.2"
time = { version = "0.3.30", features = ["formatting"] }
tracing = { workspace = true }
tracing-subscriber = { version = "0.3.18", features = ["json"] }
Expand Down
2 changes: 2 additions & 0 deletions bin/src/commands/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub fn cli() -> Command {
.about("Use HEMTT standalone utils")
.subcommand_required(false)
.arg_required_else_help(true)
.subcommand(utils::inspect::cli())
.subcommand(utils::verify::cli())
}

Expand All @@ -17,6 +18,7 @@ pub fn cli() -> Command {
/// [`Error`] depending on the modules
pub fn execute(matches: &ArgMatches) -> Result<(), Error> {
match matches.subcommand() {
Some(("inspect", matches)) => utils::inspect::execute(matches),
Some(("verify", matches)) => utils::verify::execute(matches),
_ => unreachable!(),
}
Expand Down
165 changes: 165 additions & 0 deletions bin/src/utils/inspect.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
use std::{
fs::File,
io::{Read, Seek},
path::PathBuf,
};

use clap::{ArgMatches, Command};
use hemtt_pbo::ReadablePbo;
use hemtt_signing::{BIPublicKey, BISign};
use term_table::{
row::Row,
table_cell::{Alignment, TableCell},
Table, TableStyle,
};

use crate::Error;

#[must_use]
pub fn cli() -> Command {
Command::new("inspect")
.about("Inspect an Arma file")
.long_about("Provides information about supported files. Supported: pbo, bikey, bisign")
.arg(
clap::Arg::new("file")
.help("File to inspect")
.required(true),
)
}

/// Execute the inspect command
///
/// # Errors
/// [`Error`] depending on the modules
///
/// # Panics
/// If the args are not present from clap
pub fn execute(matches: &ArgMatches) -> Result<(), Error> {
let path = PathBuf::from(matches.get_one::<String>("file").expect("required"));
match path
.extension()
.unwrap_or_default()
.to_str()
.unwrap_or_default()
{
"pbo" => {
pbo(File::open(&path)?)?;
}
"bikey" => {
bikey(File::open(&path)?, &path)?;
}
"bisign" => {
bisign(File::open(&path)?, &path)?;
}
_ => {
let mut file = File::open(&path)?;
let buf = &mut [0u8; 6];
file.read_exact(buf)?;
file.seek(std::io::SeekFrom::Start(0))?;
// PBO
if buf == b"\x00sreV\x00" {
warn!("The file appears to be a PBO but does not have the .pbo extension.");
pbo(file)?;
return Ok(());
}
// BiSign
if BISign::read(&mut file).is_ok() {
warn!("The file appears to be a BiSign but does not have the .bisign extension.");
file.seek(std::io::SeekFrom::Start(0))?;
bisign(file, &path)?;
return Ok(());
}
file.seek(std::io::SeekFrom::Start(0))?;
// BiPublicKey
if BIPublicKey::read(&mut file).is_ok() {
warn!(
"The file appears to be a BiPublicKey but does not have the .bikey extension."
);
file.seek(std::io::SeekFrom::Start(0))?;
bikey(file, &path)?;
return Ok(());
}
println!("Unsupported file type");
}
}
Ok(())
}

/// Prints information about a [`BIPublicKey`] to stdout
///
/// # Errors
/// [`hemtt_signing::Error`] if the file is not a valid [`BIPublicKey`]
pub fn bikey(mut file: File, path: &PathBuf) -> Result<BIPublicKey, Error> {
let publickey = BIPublicKey::read(&mut file)?;
println!("Public Key: {path:?}");
println!(" - Authority: {}", publickey.authority());
println!(" - Length: {}", publickey.length());
println!(" - Exponent: {}", publickey.exponent());
println!(" - Modulus: {}", publickey.modulus_display(13));
Ok(publickey)
}

/// Prints information about a [`BISign`] to stdout
///
/// # Errors
/// [`hemtt_signing::Error`] if the file is not a valid [`BISign`]
pub fn bisign(mut file: File, path: &PathBuf) -> Result<BISign, Error> {
let signature = BISign::read(&mut file)?;
println!("Signature: {path:?}");
println!(" - Authority: {}", signature.authority());
println!(" - Version: {}", signature.version());
println!(" - Length: {}", signature.length());
println!(" - Exponent: {}", signature.exponent());
println!(" - Modulus: {}", signature.modulus_display(13));
Ok(signature)
}

/// Prints information about a [`ReadablePbo`] to stdout
fn pbo(file: File) -> Result<(), Error> {
let mut pbo = ReadablePbo::from(file)?;
println!("Properties");
for (key, value) in pbo.properties() {
println!(" - {key}: {value}");
}
let stored = *pbo.checksum();
println!(" - Stored Hash: {stored:?}");
let actual = pbo.gen_checksum().unwrap();
println!(" - Actual Hash: {actual:?}");

let files = pbo.files();
println!("Files");
if pbo.is_sorted().is_ok() {
println!(" - Sorted: true");
} else {
println!(" - Sorted: false !!!");
}
println!(" - Count: {}", files.len());
let mut table = Table::new();
table.style = TableStyle::thin();
table.add_row(Row::new(vec![
TableCell::new_with_alignment("Filename", 1, Alignment::Center),
TableCell::new_with_alignment("Method", 1, Alignment::Center),
TableCell::new_with_alignment("Size", 1, Alignment::Center),
TableCell::new_with_alignment("Original", 1, Alignment::Center),
TableCell::new_with_alignment("Timestamp", 1, Alignment::Center),
]));
for file in files {
let mut row = Row::new(vec![
TableCell::new(file.filename()),
TableCell::new_with_alignment(file.mime().to_string(), 1, Alignment::Right),
TableCell::new_with_alignment(file.size().to_string(), 1, Alignment::Right),
TableCell::new_with_alignment(file.original().to_string(), 1, Alignment::Right),
TableCell::new_with_alignment(file.timestamp().to_string(), 1, Alignment::Right),
]);
row.has_separator = table.rows.len() == 1;
table.add_row(row);
}
println!("{}", table.render());
if pbo.is_sorted().is_err() {
warn!("The PBO is not sorted, signatures may be invalid");
}
if stored != actual {
warn!("The PBO has an invalid hash stored");
}
Ok(())
}
2 changes: 1 addition & 1 deletion bin/src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
// mod sign;
pub mod inspect;
pub mod verify;
Empty file removed bin/src/utils/sign.rs
Empty file.
61 changes: 26 additions & 35 deletions bin/src/utils/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ use std::path::PathBuf;

use clap::{ArgMatches, Command};
use hemtt_pbo::ReadablePbo;
use hemtt_signing::{BIPublicKey, BISign};

use crate::Error;
use crate::{
utils::inspect::{bikey, bisign},
Error,
};

#[must_use]
pub fn cli() -> Command {
Expand Down Expand Up @@ -33,81 +35,70 @@ pub fn execute(matches: &ArgMatches) -> Result<(), Error> {
debug!("Reading PBO: {:?}", &pbo_path);
let mut pbo = ReadablePbo::from(std::fs::File::open(&pbo_path)?)?;
debug!("Reading BIKey: {:?}", &bikey_path);
let publickey = BIPublicKey::read(&mut std::fs::File::open(&bikey_path)?)?;
let publickey = bikey(std::fs::File::open(&bikey_path)?, &bikey_path)?;

let signature_path = {
let mut pbo_path = pbo_path.clone();
pbo_path.set_extension(format!("pbo.{}.bisign", publickey.authority()));
pbo_path
};
debug!("Reading Signature: {:?}", &signature_path);
let signature = BISign::read(&mut std::fs::File::open(&signature_path)?)?;

println!("Public Key: {:?}", &bikey_path);
println!("\tAuthority: {}", publickey.authority());
println!("\tLength: {}", publickey.length());
println!("\tExponent: {}", publickey.exponent());
println!("\tModulus: {}", publickey.modulus_display(17));
println!();
let signature = bisign(std::fs::File::open(&signature_path)?, &signature_path)?;

println!();
println!("PBO: {pbo_path:?}");
let stored = *pbo.checksum();
println!("\tStored Hash: {stored:?}");
println!(" - Stored Hash: {stored:?}");
let actual = pbo.gen_checksum().unwrap();
println!("\tActual Hash: {actual:?}");
println!("\tProperties");
println!(" - Actual Hash: {actual:?}");
println!(" - Properties");
for ext in pbo.properties() {
println!("\t\t{}: {}", ext.0, ext.1);
println!(" - {}: {}", ext.0, ext.1);
}
println!(" - Size: {}", pbo_path.metadata()?.len());

if actual != stored {
warn!("Verification Warning: PBO has an invalid hash stored");
}
println!("\tSize: {}", pbo_path.metadata()?.len());

if !pbo.properties().contains_key("prefix") {
println!("Verification Failed: PBO is missing a prefix header");
} else if stored != actual {
println!("Verification Warning: PBO reports an invalid hash");
}

println!();
println!("Signature: {signature_path:?}");
println!("\tAuthority: {}", signature.authority());
println!("\tVersion: {}", signature.version());
println!("\tLength: {}", signature.length());
println!("\tExponent: {}", signature.exponent());
println!("\tModulus: {}", signature.modulus_display(17));

match publickey.verify(&mut pbo, &signature) {
Ok(()) => println!("Verified!"),
Err(hemtt_signing::Error::AuthorityMismatch { .. }) => {
println!("Verification Failed: Authority does not match");
error!("Verification Failed: Authority does not match");
}
Err(hemtt_signing::Error::HashMismatch { .. }) => {
println!("Verification Failed: Signature does not match");
error!("Verification Failed: Signature does not match");
}
Err(hemtt_signing::Error::UknownBISignVersion(v)) => {
println!("Verification Failed: Unknown BI Signature Version: {v}");
error!("Verification Failed: Unknown BI Signature Version: {v}");
}
Err(hemtt_signing::Error::Io(e)) => {
println!("Verification Failed: Encountered IO error: {e}");
error!("Verification Failed: Encountered IO error: {e}");
}
Err(hemtt_signing::Error::Pbo(e)) => {
println!("Verification Failed: Encountered PBO error: {e}");
error!("Verification Failed: Encountered PBO error: {e}");
}
Err(hemtt_signing::Error::Rsa(e)) => {
println!("Verification Failed: Encountered RSA error: {e}");
error!("Verification Failed: Encountered RSA error: {e}");
}
Err(hemtt_signing::Error::InvalidLength) => {
println!("Verification Failed: Invalid length");
error!("Verification Failed: Invalid length");
}
Err(hemtt_signing::Error::AuthorityMissing) => {
println!("Verification Failed: Missing authority");
error!("Verification Failed: Missing authority");
}
Err(hemtt_signing::Error::InvalidFileSorting) => {
if pbo.properties().contains_key("Mikero") {
println!(
"Verification Failed: Invalid file sorting. This is a bug in Mikero tools."
);
error!("Verification Failed: Invalid file sorting. This is a bug in Mikero tools.");
} else {
println!("Verification Failed: Invalid file sorting");
error!("Verification Failed: Invalid file sorting");
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions libs/pbo/src/model/mime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,14 @@ impl Mime {
}
}
}

impl std::fmt::Display for Mime {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Vers => write!(f, "Vers"),
Self::Cprs => write!(f, "Cprs"),
Self::Enco => write!(f, "Enco"),
Self::Blank => write!(f, "Blank"),
}
}
}
Loading