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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//! Intel Management Engine Firmware Parser
//!
//! Intel provides a closed-source tool called FIT(C) to their customers for
//! editing firmware images, as referenced in the following documents:
//! - [FSP guide](https://cdrdv2-public.intel.com/334348/5th-gen-core-i5-5350u-eval-kit-fsp-user-guide.pdf)
//! - [TXE guide](https://www.portwell.eu/index.php?eID=dumpFile&t=f&f=10304&token=9d79dec7d7313cf82d445b05ccd5013a6b97ee81&download=)
use serde::{Deserialize, Serialize};
use crate::EMPTY;
use crate::dir::{
gen2::Directory as Gen2Directory,
gen3::{CPD_MAGIC_BYTES, CodePartitionDirectory},
};
use crate::part::fpt::FTPR;
use crate::part::gen2::DirPartition;
use crate::part::gen3::CPDPartition;
use crate::part::part::Partition;
use crate::part::{
fpt::{FPT, MIN_FPT_SIZE},
gen2::Gen2Partition,
gen3::Gen3Partition,
part::ClearOptions,
partitions::Partitions,
};
use crate::ver::Version;
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub enum Generation {
Gen1,
Gen2,
Gen3,
Unknown,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum Directories {
Gen2(Vec<Gen2Directory>),
Gen3(Vec<CodePartitionDirectory>),
Unknown,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Data {
pub offset: usize,
pub data: Vec<u8>,
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct FPTArea {
pub fpt: FPT,
pub partitions: Partitions,
pub non_covered: Vec<Data>,
pub original_size: usize,
}
impl FPTArea {
/// Clear out fully removable partitions and adjust FPT
pub fn clean(&mut self, options: &ClearOptions) {
let mut fpt = self.fpt.clone();
fpt.clear(options);
self.fpt = fpt;
let mut parts = self.partitions.clone();
parts.clear(options);
self.partitions = parts;
let debug = true;
if debug {
for p in &self.partitions {
println!("Remaining: {}", p.entry());
}
}
}
pub fn check_dir_sigs(&self) -> Vec<(String, Result<(), String>)> {
match &self.partitions {
Partitions::Gen2(parts) => {
let dirs = parts
.iter()
.filter_map(|p| match p {
Gen2Partition::Dir(d) => Some(d.clone()),
_ => None,
})
.collect::<Vec<Box<DirPartition>>>();
dirs.iter()
.map(|d| (d.entry.name(), d.check_signature()))
.collect()
}
Partitions::Gen3(parts) => {
let dirs = parts
.iter()
.filter_map(|p| match p {
Gen3Partition::Dir(d) => Some(d.clone()),
_ => None,
})
.collect::<Vec<CPDPartition>>();
dirs.iter()
.map(|d| (d.entry.name(), d.check_signature()))
.collect()
}
_ => vec![],
}
}
pub fn check_ftpr_presence(&self) -> Result<(), String> {
match &self.partitions {
Partitions::Gen2(parts) => {
if parts.iter().any(|p| p.entry().name() == FTPR) {
Ok(())
} else {
Err("not found".into())
}
}
Partitions::Gen3(parts) => {
if parts.iter().any(|p| p.entry().name() == FTPR) {
Ok(())
} else {
Err("not found".into())
}
}
_ => Err("not recognized as ME generation 2 or 3".into()),
}
}
pub fn relocate_partitions(&mut self) -> Result<(), String> {
let sorted_parts = &self.partitions.get_sorted();
let first = sorted_parts
.into_iter()
.filter(|p| p.entry().size() > 0)
.nth(0);
if let Some(p) = first {
let e = p.entry();
let n = e.name();
let min_offset = MIN_FPT_SIZE;
let new_offset = match &self.partitions {
Partitions::Gen2(parts) => {
// Find a Directory partition to calculate the offset.
let dir_part = parts.iter().find(|p| matches!(p, Gen2Partition::Dir(_)));
match dir_part {
Some(Gen2Partition::Dir(d)) => d.dir.calc_new_offset(min_offset as u32)?,
_ => return Err("no directory partition found".into()),
}
}
Partitions::Gen3(_) => e.offset().min(min_offset) as u32,
_ => todo!(),
};
let old_offset = e.offset();
println!("old offset: {old_offset:08x}");
println!("new offset: {new_offset:08x}");
if let Err(e) = self.partitions.relocate(&n, new_offset) {
return Err(format!("Cannot relocate partitions: {e}"));
}
let offset = new_offset as usize;
// It may happen that some part of the FPT area had not been covered
// by an FPT entry, but it contained data that can now be overwritten
// when relocating partitions.
let mut non_covered = vec![];
let r = offset..offset + e.size();
for nc in &self.non_covered {
let o = nc.offset;
let e = o + nc.data.len();
if r.contains(&o) || r.contains(&e) {
println!("Drop data not covered by FPT and now overlapping: {o:08x}..{e:08x}");
} else {
non_covered.push(nc.clone());
}
}
self.non_covered = non_covered;
// Update partition table entry
for e in &mut self.fpt.entries {
if e.name() == n {
e.set_offset(offset as u32);
}
}
Ok(())
} else {
Err("no FPT partitions found".into())
}
}
/// Clear out fully removable partitions and adjust FPT
pub fn to_vec(&self) -> Result<Vec<u8>, String> {
let debug = true;
if debug {
println!("Recreate ME region from components");
}
let mut res = self.partitions.to_vec()?;
if debug {
println!(" Minimum size: {:08x}", res.len());
}
// Restore the original size, so that the resulting slice fully covers
// the FPT area. The resulting bytes can be used to overwrite the region
// in a given image, e.g., after cleaning or other partition changes.
res.resize(self.original_size, EMPTY);
if debug {
println!(" Restored size: {:08x}", res.len());
}
// Any range within the FPT area may be non-covered.
for u in &self.non_covered {
let o = u.offset;
let s = u.data.len();
let e = o + s;
if debug {
println!("Restore data not covered by FPT @ {o:08x} ({s} bytes)");
}
if e < res.len() {
res[o..e].copy_from_slice(&u.data);
}
}
// NOTE: This *has* to go last; the FPT is not covered by itself.
let raw_fpt = self.fpt.clone().to_vec();
let s = self.fpt.original_size;
if debug {
println!("Write back FPT ({s} bytes)");
}
res[..s].copy_from_slice(&raw_fpt);
Ok(res)
}
}
#[allow(non_camel_case_types)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ME {
pub base: usize,
pub generation: Generation,
pub version: Option<Version>,
pub fpt_area: FPTArea,
// NOTE: There _may_ be directories outside the FPT area.
// It is yet unclear how they are referenced.
pub cpds: Vec<CodePartitionDirectory>,
}
impl ME {
pub fn parse(data: &[u8], base: usize, debug: bool) -> Option<Result<Self, String>> {
if let Some(r) = FPT::parse(data) {
let fpt = match r {
Ok(r) => r,
Err(e) => {
return Some(Err(format!("Cannot parse ME FPT @ {base:08x}: {e:?}")));
}
};
let original_size = data.len();
let partitions = Partitions::parse(&fpt, data, debug);
// TODO: use this when stabilized
/*
let gen2 = core::intrinsics::discriminant_value(Partitions::Gen2);
let gen3 = core::intrinsics::discriminant_value(Partitions::Gen3);
let generation = match partitions {
gen2 => Generation::Gen2,
gen3 => Generation::Gen3,
_ => Generation::Unknown,
};
*/
let generation = if matches!(partitions, Partitions::Gen2(_)) {
Generation::Gen2
} else {
Generation::Gen3
};
let version = partitions.get_me_version();
let non_covered = partitions
.non_covered_ranges()
.iter()
.map(|u| {
let offset = u.start;
let end = u.end;
if offset > data.len() || end > data.len() {
return Data {
data: vec![],
offset,
};
}
let data = data[offset..end].to_vec();
Data { data, offset }
})
.collect();
let fpt_area = FPTArea {
fpt,
partitions,
non_covered,
original_size,
};
// TODO: filter out CPDs that are covered by the FPT
let cpds = Self::cpd_scan(data);
Some(Ok(Self {
base,
fpt_area,
generation,
version,
cpds,
}))
} else {
None
}
}
// Find an FPT in a given slice, and if detected, get the parse result,
// which includes the offset where it was found as its base address.
pub fn scan(data: &[u8], debug: bool) -> Option<Result<Self, String>> {
fn find_me(data: &[u8], debug: bool) -> Option<Result<ME, String>> {
for o in (0..data.len() - MIN_FPT_SIZE - 0x10).step_by(0x40) {
if let Some(r) = ME::parse(&data[o..], o, debug) {
return Some(r);
}
}
None
}
let mut r = find_me(data, debug);
if let Some(Ok(me)) = &mut r {
let all_cpds = Self::cpd_scan(data);
me.cpds = all_cpds;
}
r
}
// Scan for all CPDs (there may be some not listed in FPT)
pub fn cpd_scan(data: &[u8]) -> Vec<CodePartitionDirectory> {
let mut gen3dirs = Vec::<CodePartitionDirectory>::new();
let mut o = 0;
while o < data.len() {
if &data[o..o + 4] == CPD_MAGIC_BYTES {
let Ok(cpd) = CodePartitionDirectory::new(&data[o..], o) else {
continue;
};
gen3dirs.push(cpd);
}
o += 16;
}
if false {
println!("Found {} CPDs doing a full scan", gen3dirs.len());
}
gen3dirs
}
}