Skip to content

Commit

Permalink
pe: add authenticode support
Browse files Browse the repository at this point in the history
Authenticode is the hashing format used to sign PE binaries. This
provides the hash to be signed.
  • Loading branch information
baloo committed Mar 10, 2023
1 parent 170395f commit 39eadb5
Show file tree
Hide file tree
Showing 3 changed files with 201 additions and 3 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ description = "An impish, cross-platform, ELF, Mach-o, and PE binary parsing and

[dependencies]
plain = "0.2.3"
digest = { version = "0.10.6", optional = true }

[dependencies.log]
version = "0.4"
Expand All @@ -50,6 +51,8 @@ mach64 = ["alloc", "endian_fd", "archive"]
pe32 = ["alloc", "endian_fd"]
pe64 = ["alloc", "endian_fd"]
archive = ["alloc"]
pe_source = []
pe_authenticode = ["pe_source", "digest"]

[badges.travis-ci]
branch = "master"
Expand Down
144 changes: 144 additions & 0 deletions src/pe/authenticode.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Reference:
// https://learn.microsoft.com/en-us/windows-hardware/drivers/install/authenticode
// https://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/Authenticode_PE.docx

// Authenticode works by omiting sections of the PE binary from the digest
// those sections are:
// - checksum
// - data directory entry for certtable
// - certtable

use alloc::vec::Vec;
use core::ops::Range;
use digest::{Digest, Output};

use super::PE;

pub trait Authenticode<'s> {
type Iter: Iterator<Item = &'s [u8]>;

/// [`authenticode_ranges`] returns the various ranges of the binary that are relevant for
/// signature.
fn authenticode_ranges(&'s self) -> Self::Iter;

/// [`authenticode_digest`] returns the result of the provided hash algorithm.
fn authenticode_digest<D: Digest>(&'s self) -> Output<D> {
let mut digest = D::new();

for chunk in self.authenticode_ranges() {
digest.update(chunk);
}

digest.finalize()
}

/// [`authenticode_slice`] is intended for convience when signing a binary with a PKCS#11
/// interface (HSM backed).
/// Some algorithm (RSA-PKCS) for signature require the non-prehashed slice to be provided.
fn authenticode_slice(&'s self) -> Box<[u8]> {
let mut length = 0;
for chunk in self.authenticode_ranges() {
length += chunk.len();
}

let mut out = Vec::with_capacity(length);
for chunk in self.authenticode_ranges() {
out.extend_from_slice(chunk);
}

out.into()
}
}

impl<'pe> Authenticode<'pe> for PE<'pe> {
type Iter = AuthenticodeSectionsIter<'pe>;

fn authenticode_ranges(&'pe self) -> AuthenticodeSectionsIter<'pe> {
self.authenticode_sections.iter(self.bytes)
}
}

#[derive(Debug, Clone, Default)]
pub(super) struct AuthenticodeSections {
pub checksum: Option<Range<usize>>,
pub datadir_entry_certtable: Option<Range<usize>>,
pub certtable: Option<Range<usize>>,
}

impl AuthenticodeSections {
fn iter<'s>(&'s self, bytes: &'s [u8]) -> AuthenticodeSectionsIter<'s> {
AuthenticodeSectionsIter {
bytes,
state: IterState::default(),
sections: self,
}
}
}

pub struct AuthenticodeSectionsIter<'s> {
bytes: &'s [u8],
state: IterState,
sections: &'s AuthenticodeSections,
}

#[derive(Default)]
enum IterState {
#[default]
Initial,
DatadirEntry {
start: usize,
},
CertTable {
start: usize,
},
Final {
start: usize,
},
Done,
}

impl<'s> Iterator for AuthenticodeSectionsIter<'s> {
type Item = &'s [u8];

fn next(&mut self) -> Option<Self::Item> {
loop {
match self.state {
IterState::Initial => {
if let Some(checksum) = self.sections.checksum.as_ref() {
self.state = IterState::DatadirEntry {
start: checksum.end,
};
return Some(&self.bytes[..checksum.start]);
} else {
self.state = IterState::DatadirEntry { start: 0 };
}
}
IterState::DatadirEntry { start } => {
if let Some(datadir_entry) = self.sections.datadir_entry_certtable.as_ref() {
self.state = IterState::CertTable {
start: datadir_entry.end,
};
return Some(&self.bytes[start..datadir_entry.start]);
} else {
self.state = IterState::CertTable { start }
}
}
IterState::CertTable { start } => {
if let Some(certtable) = self.sections.certtable.as_ref() {
self.state = IterState::Final {
start: certtable.end,
};
return Some(&self.bytes[start..certtable.start]);
} else {
self.state = IterState::Final { start }
}
}
IterState::Final { start } => {
self.state = IterState::Done;
return Some(&self.bytes[start..]);
}
IterState::Done => return None,
}
}
}
}
57 changes: 54 additions & 3 deletions src/pe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

use alloc::vec::Vec;

#[cfg(feature = "pe_authenticode")]
pub mod authenticode;
pub mod certificate_table;
pub mod characteristic;
pub mod data_directories;
Expand All @@ -29,6 +31,11 @@ use log::debug;
#[derive(Debug)]
/// An analyzed PE32/PE32+ binary
pub struct PE<'a> {
#[cfg(feature = "pe_source")]
/// Underlying bytes
bytes: &'a [u8],
#[cfg(feature = "pe_authenticode")]
authenticode_sections: authenticode::AuthenticodeSections,
/// The PE header
pub header: header::Header,
/// A list of the sections in this PE binary
Expand Down Expand Up @@ -72,11 +79,25 @@ impl<'a> PE<'a> {
/// Reads a PE binary from the underlying `bytes`
pub fn parse_with_opts(bytes: &'a [u8], opts: &options::ParseOptions) -> error::Result<Self> {
let header = header::Header::parse(bytes)?;
#[cfg(feature = "pe_authenticode")]
let mut authenticode_sections = authenticode::AuthenticodeSections::default();

debug!("{:#?}", header);
let offset = &mut (header.dos_header.pe_pointer as usize
let optional_header_offset = header.dos_header.pe_pointer as usize
+ header::SIZEOF_PE_MAGIC
+ header::SIZEOF_COFF_HEADER
+ header.coff_header.size_of_optional_header as usize);
+ header::SIZEOF_COFF_HEADER;

#[cfg(feature = "pe_authenticode")]
{
authenticode_sections.checksum = if header.coff_header.size_of_optional_header >= 68 {
Some(optional_header_offset + 64..optional_header_offset + 68)
} else {
None
};
}
let offset =
&mut (optional_header_offset + header.coff_header.size_of_optional_header as usize);

let sections = header.coff_header.sections(bytes, offset)?;
let is_lib = characteristic::is_dll(header.coff_header.characteristics);
let mut entry = 0;
Expand All @@ -92,6 +113,25 @@ impl<'a> PE<'a> {
let mut certificates = Default::default();
let mut is_64 = false;
if let Some(optional_header) = header.optional_header {
#[cfg(feature = "pe_authenticode")]
{
match optional_header {
oh if oh.standard_fields.magic == optional_header::MAGIC_32
&& header.coff_header.size_of_optional_header >= 136 =>
{
authenticode_sections.datadir_entry_certtable =
Some(optional_header_offset + 128..optional_header_offset + 136);
}
oh if oh.standard_fields.magic == optional_header::MAGIC_64
&& header.coff_header.size_of_optional_header >= 152 =>
{
authenticode_sections.datadir_entry_certtable =
Some(optional_header_offset + 144..optional_header_offset + 152);
}
_ => {}
}
}

entry = optional_header.standard_fields.address_of_entry_point as usize;
image_base = optional_header.windows_fields.image_base as usize;
is_64 = optional_header.container()? == container::Container::Big;
Expand Down Expand Up @@ -190,9 +230,20 @@ impl<'a> PE<'a> {
certificate_table.virtual_address,
certificate_table.size,
)?;

#[cfg(feature = "pe_authenticode")]
{
let start = certificate_table.virtual_address as usize;
let end = start + certificate_table.size as usize;
authenticode_sections.certtable = Some(start..end);
}
}
}
Ok(PE {
#[cfg(feature = "pe_source")]
bytes,
#[cfg(feature = "pe_authenticode")]
authenticode_sections,
header,
sections,
size: 0,
Expand Down

0 comments on commit 39eadb5

Please sign in to comment.