1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::{fmt};
use error::{Error, Result};
use super::image::*;
use super::{Align, Pe};
pub struct Security<'a, P> {
pe: P,
security: &'a [u8],
}
impl<'a, P: Pe<'a> + Copy> Security<'a, P> {
pub(crate) fn try_from(pe: P) -> Result<Security<'a, P>> {
if pe.align() != Align::File {
return Err(Error::Unmapped);
}
let datadir = pe.data_directory().get(IMAGE_DIRECTORY_ENTRY_SECURITY).ok_or(Error::Bounds)?;
if datadir.VirtualAddress == 0 {
return Err(Error::Null);
}
if datadir.VirtualAddress % 8 != 0 || datadir.Size % 8 != 0 {
return Err(Error::Misaligned);
}
if datadir.Size == 0 {
return Err(Error::Bounds);
}
let start = datadir.VirtualAddress as usize;
let end = (datadir.VirtualAddress + datadir.Size) as usize;
let security = pe.image().get(start..end).ok_or(Error::Bounds)?;
Ok(Security { pe, security })
}
pub fn pe(&self) -> P {
self.pe
}
pub fn image(&self) -> &'a WIN_CERTIFICATE {
unsafe {
&*(self.security.as_ptr() as *const _)
}
}
pub fn certificate_type(&self) -> u16 {
self.image().wCertificateType
}
pub fn certificate_data(&self) -> &'a [u8] {
unsafe {
self.security.get_unchecked(8..)
}
}
}
impl<'a, P: Pe<'a> + Copy> fmt::Debug for Security<'a, P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Security")
.field("certificate_type", &self.certificate_type())
.field("certificate_data.len", &self.certificate_data().len())
.finish()
}
}
#[cfg(feature = "serde")]
mod serde {
use util::serde_helper::*;
use super::{Pe, Security};
impl<'a, P: Pe<'a> + Copy> Serialize for Security<'a, P> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let is_human_readable = serializer.is_human_readable();
let mut state = serializer.serialize_struct("Security", 2)?;
state.serialize_field("certificate_type", &self.certificate_type())?;
if cfg!(feature = "data-encoding") && is_human_readable {
#[cfg(feature = "data-encoding")]
state.serialize_field("certificate_data",
&::data_encoding::BASE64.encode(self.certificate_data()))?;
}
else {
state.serialize_field("certificate_data", &self.certificate_data())?;
}
state.end()
}
}
}
#[cfg(test)]
pub(crate) fn test<'a, P: Pe<'a> + Copy>(pe: P) -> Result<()> {
let security = pe.security()?;
let _ = format!("{:?}", security);
let _certificate_type = security.certificate_type();
let _certificate_data = security.certificate_data();
Ok(())
}