Skip to content

Commit

Permalink
Merge pull request #705 from ReFirmLabs/lint-fixes
Browse files Browse the repository at this point in the history
Lint fixes
  • Loading branch information
devttys0 authored Oct 21, 2024
2 parents adf8df9 + cc14a29 commit 023d124
Show file tree
Hide file tree
Showing 169 changed files with 1,968 additions and 2,175 deletions.
103 changes: 48 additions & 55 deletions src/binwalk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl Binwalk {
/// ```
#[allow(dead_code)]
pub fn new() -> Binwalk {
return Binwalk::configure(None, None, None, None, None).unwrap();
Binwalk::configure(None, None, None, None, None).unwrap()
}

/// Create a new Binwalk instance.
Expand Down Expand Up @@ -171,7 +171,7 @@ impl Binwalk {
// Load magic signatures
for signature in signature_patterns.clone() {
// Check if this signature should be included
if include_signature(&signature, &include, &exclude) == false {
if !include_signature(&signature, &include, &exclude) {
continue;
}

Expand All @@ -185,7 +185,7 @@ impl Binwalk {

// Each signature may have multiple magic bytes associated with it
for pattern in signature.magic.clone() {
if signature.short == true {
if signature.short {
// These are short patterns, and should only be searched for at the very beginning of a file
new_instance.short_signatures.push(signature.clone());
} else {
Expand All @@ -204,7 +204,7 @@ impl Binwalk {
}
}

return Ok(new_instance);
Ok(new_instance)
}

/// Scan a file for magic signatures.
Expand All @@ -228,7 +228,7 @@ impl Binwalk {
///
/// assert!(signature_results.len() > 0);
/// ```
pub fn scan(&self, file_data: &Vec<u8>) -> Vec<signatures::common::SignatureResult> {
pub fn scan(&self, file_data: &[u8]) -> Vec<signatures::common::SignatureResult> {
const FILE_START_OFFSET: usize = 0;

let mut index_adjustment: usize = 0;
Expand All @@ -252,40 +252,35 @@ impl Binwalk {
let magic_start = FILE_START_OFFSET + signature.magic_offset;
let magic_end = magic_start + magic.len();

if file_data.len() > magic_end {
if file_data[magic_start..magic_end] == magic {
debug!(
"Found {} short magic match at offset {:#X}",
signature.description, magic_start
);
if file_data.len() > magic_end && file_data[magic_start..magic_end] == magic {
debug!(
"Found {} short magic match at offset {:#X}",
signature.description, magic_start
);

if let Ok(mut signature_result) =
(signature.parser)(&file_data, magic_start)
{
// Auto populate some signature result fields
signature_result_auto_populate(&mut signature_result, &signature);

// Add this signature to the file map
file_map.push(signature_result.clone());
info!(
"Found valid {} short signature at offset {:#X}",
signature_result.name, FILE_START_OFFSET
);
if let Ok(mut signature_result) = (signature.parser)(file_data, magic_start) {
// Auto populate some signature result fields
signature_result_auto_populate(&mut signature_result, signature);

// Only update the next_valid_offset if confidence is at least medium
if signature_result.confidence >= signatures::common::CONFIDENCE_MEDIUM
{
next_valid_offset = signature_result.offset + signature_result.size;
}
// Add this signature to the file map
file_map.push(signature_result.clone());
info!(
"Found valid {} short signature at offset {:#X}",
signature_result.name, FILE_START_OFFSET
);

// Only one signature can match at fixed offset 0
break;
} else {
debug!(
"{} short signature match at offset {:#X} is invalid",
signature.description, FILE_START_OFFSET
);
// Only update the next_valid_offset if confidence is at least medium
if signature_result.confidence >= signatures::common::CONFIDENCE_MEDIUM {
next_valid_offset = signature_result.offset + signature_result.size;
}

// Only one signature can match at fixed offset 0
break;
} else {
debug!(
"{} short signature match at offset {:#X} is invalid",
signature.description, FILE_START_OFFSET
);
}
}
}
Expand Down Expand Up @@ -343,7 +338,7 @@ impl Binwalk {
* Invoke the signature parser to parse and validate the signature.
* An error indicates a false positive match for the signature type.
*/
if let Ok(mut signature_result) = (signature.parser)(&file_data, magic_offset) {
if let Ok(mut signature_result) = (signature.parser)(file_data, magic_offset) {
// Calculate the end of this signature's data
let signature_end_offset = signature_result.offset + signature_result.size;

Expand Down Expand Up @@ -406,7 +401,7 @@ impl Binwalk {
i -= index_adjustment;

// Make sure the file map index is valid
if file_map.len() == 0 || i >= file_map.len() {
if file_map.is_empty() || i >= file_map.len() {
break;
}

Expand Down Expand Up @@ -498,10 +493,10 @@ impl Binwalk {
// If there are more entries in the file map
if next_index < file_map.len() {
// Look through all remaining file map entries for one with medium to high confidence
for j in next_index..file_map.len() {
if file_map[j].confidence >= signatures::common::CONFIDENCE_MEDIUM {
for file_map_entry in file_map.iter().skip(next_index) {
if file_map_entry.confidence >= signatures::common::CONFIDENCE_MEDIUM {
// If a signature of at least medium confidence is found, assume that *this* signature ends there
next_offset = file_map[j].offset;
next_offset = file_map_entry.offset;
break;
}
}
Expand All @@ -522,7 +517,7 @@ impl Binwalk {

debug!("Found {} valid signatures", file_map.len());

return file_map;
file_map
}

/// Extract all extractable signatures found in a file.
Expand Down Expand Up @@ -550,7 +545,7 @@ impl Binwalk {
/// ```
pub fn extract(
&self,
file_data: &Vec<u8>,
file_data: &[u8],
file_path: &String,
file_map: &Vec<signatures::common::SignatureResult>,
) -> HashMap<String, extractors::common::ExtractionResult> {
Expand All @@ -560,7 +555,7 @@ impl Binwalk {
// Spawn extractors for each extractable signature
for signature in file_map {
// Signatures may opt to not perform extraction; honor this request
if signature.extraction_declined == true {
if signature.extraction_declined {
continue;
}

Expand All @@ -574,7 +569,7 @@ impl Binwalk {
let mut extraction_result =
extractors::common::execute(file_data, file_path, signature, &extractor);

if extraction_result.success == false {
if !extraction_result.success {
debug!(
"Extraction failed for {} (ID: {}) {:#X} - {:#X}",
signature.name, signature.id, signature.offset, signature.size
Expand Down Expand Up @@ -616,7 +611,7 @@ impl Binwalk {
}
}

return extraction_results;
extraction_results
}

/// Analyze a file and optionally extract the file contents.
Expand Down Expand Up @@ -655,19 +650,19 @@ impl Binwalk {
results.file_map = self.scan(&file_data);

// Only extract if told to, and if there were some signatures found in this file
if do_extraction == true && results.file_map.len() > 0 {
if do_extraction && !results.file_map.is_empty() {
// Extract everything we can
debug!(
"Submitting {} signature results to extractor",
results.file_map.len()
);
results.extractions = self.extract(&file_data, &target_file, &results.file_map);
results.extractions = self.extract(&file_data, target_file, &results.file_map);
}
}

debug!("Analysis end: {}", target_file);

return results;
results
}
}

Expand All @@ -677,7 +672,7 @@ fn init_extraction_directory(
extraction_directory: &String,
) -> Result<String, std::io::Error> {
// Create the output directory, equivalent of mkdir -p
match fs::create_dir_all(&extraction_directory) {
match fs::create_dir_all(extraction_directory) {
Ok(_) => {
debug!("Created base output directory: '{}'", extraction_directory);
}
Expand Down Expand Up @@ -713,18 +708,16 @@ fn init_extraction_directory(
// Create a symlink from inside the extraction directory to the specified target file
#[cfg(unix)]
{
match unix::fs::symlink(&target_path, &symlink_path) {
Ok(_) => {
return Ok(symlink_target_path_str);
}
match unix::fs::symlink(target_path, symlink_path) {
Ok(_) => Ok(symlink_target_path_str),
Err(e) => {
error!(
"Failed to create symlink {} -> {}: {}",
symlink_path.display(),
target_path.display(),
e
);
return Err(e);
Err(e)
}
}
}
Expand Down Expand Up @@ -773,7 +766,7 @@ fn include_signature(
return true;
}

return true;
true
}

/// Some SignatureResult fields need to be auto-populated.
Expand Down
2 changes: 1 addition & 1 deletion src/cliparser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,5 @@ pub struct CliArgs {
}

pub fn parse() -> CliArgs {
return CliArgs::parse();
CliArgs::parse()
}
29 changes: 13 additions & 16 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! Common Functions
use chrono::prelude::DateTime;
use crc32_v2;
use log::{debug, error};
use std::fs::File;
use std::io::Read;
Expand All @@ -23,16 +22,16 @@ pub fn read_file(file: impl Into<String>) -> Result<Vec<u8>, std::io::Error> {
match File::open(&file_path) {
Err(e) => {
error!("Failed to open file {}: {}", file_path, e);
return Err(e);
Err(e)
}
Ok(mut fp) => match fp.read_to_end(&mut file_data) {
Err(e) => {
error!("Failed to read file {} into memory: {}", file_path, e);
return Err(e);
Err(e)
}
Ok(file_size) => {
debug!("Loaded {} bytes from {}", file_size, file_path);
return Ok(file_data);
Ok(file_data)
}
},
}
Expand All @@ -56,7 +55,7 @@ pub fn read_file(file: impl Into<String>) -> Result<Vec<u8>, std::io::Error> {
/// assert_eq!(my_data_crc, 0xDB1720A5);
/// ```
pub fn crc32(data: &[u8]) -> u32 {
return crc32_v2::crc32(0, data);
crc32_v2::crc32(0, data)
}

/// Converts an epoch time to a formatted time string.
Expand All @@ -73,8 +72,8 @@ pub fn crc32(data: &[u8]) -> u32 {
pub fn epoch_to_string(epoch_timestamp: u32) -> String {
let date_time = DateTime::from_timestamp(epoch_timestamp.into(), 0);
match date_time {
Some(dt) => return dt.format("%Y-%m-%d %H:%M:%S").to_string(),
None => return "".to_string(),
Some(dt) => dt.format("%Y-%m-%d %H:%M:%S").to_string(),
None => "".to_string(),
}
}

Expand All @@ -91,7 +90,7 @@ fn get_cstring_bytes(raw_data: &[u8]) -> Vec<u8> {
}
}

return cstring;
cstring
}

/// Get a C-style NULL-terminated string from the provided array of u8 bytes.
Expand All @@ -108,16 +107,14 @@ fn get_cstring_bytes(raw_data: &[u8]) -> Vec<u8> {
/// assert_eq!(string, "this_is_a_c_string");
/// ```
pub fn get_cstring(raw_data: &[u8]) -> String {
let string: String;

let raw_string = get_cstring_bytes(raw_data);

match String::from_utf8(raw_string) {
Err(_) => string = "".to_string(),
Ok(s) => string = s.clone(),
}
let string: String = match String::from_utf8(raw_string) {
Err(_) => "".to_string(),
Ok(s) => s.clone(),
};

return string;
string
}

/// Validates data offsets to prevent out-of-bounds access and infinite loops while parsing file formats.
Expand Down Expand Up @@ -158,5 +155,5 @@ pub fn is_offset_safe(
return false;
}

return true;
true
}
Loading

0 comments on commit 023d124

Please sign in to comment.