sev 7.1.0

Library for AMD SEV
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// SPDX-License-Identifier: Apache-2.0

//! Operations to handle ovmf data
use crate::error::*;
use crate::parser::{ByteParser, Decoder, Encoder};
use crate::util::parser_helper::{ReadExt, WriteExt};
use byteorder::{ByteOrder, LittleEndian};
use std::io::Write;
use std::{
    collections::HashMap,
    convert::{TryFrom, TryInto},
    fs::File,
    io::Read,
    path::PathBuf,
};
use uuid::{uuid, Uuid};

#[cfg(feature = "serde")]
use serde::Deserialize;

/// Convert a UUID into a little endian slice
pub fn guid_le_to_slice(guid: &str) -> Result<[u8; 16], MeasurementError> {
    let guid = Uuid::try_from(guid)?;
    let guid = guid.to_bytes_le();
    let guid = guid.as_slice();

    Ok(guid.try_into()?)
}

/// Types of sections declared by OVMF SEV Metadata, as appears in: https://github.com/tianocore/edk2/blob/edk2-stable202405/OvmfPkg/ResetVector/X64/OvmfSevMetadata.asm
#[cfg_attr(feature = "serde", derive(Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SectionType {
    /// SNP Secure Memory
    SnpSecMemory = 1,
    /// SNP secret
    SnpSecrets = 2,
    /// CPUID
    Cpuid = 3,
    /// SVSM_CAA
    SvsmCaa = 4,
    /// SNP kernel hashes
    SnpKernelHashes = 0x10,
}

impl Default for SectionType {
    fn default() -> Self {
        Self::SnpSecMemory
    }
}

impl Encoder<()> for SectionType {
    fn encode(&self, writer: &mut impl Write, _: ()) -> Result<(), std::io::Error> {
        let value: u8 = match self {
            SectionType::SnpSecMemory => 1,
            SectionType::SnpSecrets => 2,
            SectionType::Cpuid => 3,
            SectionType::SvsmCaa => 4,
            SectionType::SnpKernelHashes => 0x10,
        };
        writer.write_bytes(value.to_le_bytes(), ())?;
        Ok(())
    }
}

impl Decoder<()> for SectionType {
    fn decode(reader: &mut impl Read, _: ()) -> Result<Self, std::io::Error> {
        let value = u8::from_le_bytes(reader.read_bytes()?);
        match value {
            1 => Ok(SectionType::SnpSecMemory),
            2 => Ok(SectionType::SnpSecrets),
            3 => Ok(SectionType::Cpuid),
            4 => Ok(SectionType::SvsmCaa),
            0x10 => Ok(SectionType::SnpKernelHashes),
            _ => Err(std::io::ErrorKind::Unsupported.into()),
        }
    }
}

impl ByteParser<()> for SectionType {
    type Bytes = [u8; 1];
    const EXPECTED_LEN: Option<usize> = Some(1);
}

impl TryFrom<u8> for SectionType {
    type Error = OVMFError;

    fn try_from(value: u8) -> Result<Self, OVMFError> {
        match value {
            1 => Ok(SectionType::SnpSecMemory),
            2 => Ok(SectionType::SnpSecrets),
            3 => Ok(SectionType::Cpuid),
            4 => Ok(SectionType::SvsmCaa),
            0x10 => Ok(SectionType::SnpKernelHashes),
            _ => Err(OVMFError::InvalidSectionType),
        }
    }
}

/// OVMF SEV Metadata Section Description
#[repr(C)]
#[cfg_attr(feature = "serde", derive(Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct OvmfSevMetadataSectionDesc {
    /// Guest Physical Adress
    pub gpa: u32,
    /// Size
    pub size: u32,
    /// Section Type
    pub section_type: SectionType,
}

impl Encoder<()> for OvmfSevMetadataSectionDesc {
    fn encode(&self, writer: &mut impl Write, _: ()) -> Result<(), std::io::Error> {
        writer.write_bytes(self.gpa, ())?;
        writer.write_bytes(self.size, ())?;
        writer.write_bytes(self.section_type, ())?;
        Ok(())
    }
}

impl Decoder<()> for OvmfSevMetadataSectionDesc {
    fn decode(reader: &mut impl Read, _: ()) -> Result<Self, std::io::Error> {
        let gpa = reader.read_bytes()?;
        let size = reader.read_bytes()?;
        let section_type = reader.read_bytes()?;
        Ok(Self {
            gpa,
            size,
            section_type,
        })
    }
}

impl ByteParser<()> for OvmfSevMetadataSectionDesc {
    // packed representation: 4 (gpa) + 4 (size) + 1 (section_type) = 9 bytes
    type Bytes = [u8; 9];
    const EXPECTED_LEN: Option<usize> = Some(9);
}

impl OvmfSevMetadataSectionDesc {
    fn bytes_from_offset(value: &[u8], offset: usize) -> Result<Self, std::io::Error> {
        let mut bytes = &value[offset..offset + std::mem::size_of::<OvmfSevMetadataSectionDesc>()];
        let decoded = Self::decode(&mut bytes, ())?;

        Ok(decoded)
    }
}

/// OVMF Metadata Header
#[repr(C)]
#[cfg_attr(feature = "serde", derive(Deserialize))]
#[derive(Debug, Clone, Copy)]
struct OvmfSevMetadataHeader {
    /// Header Signature
    signature: [u8; 4],
    /// Size
    size: u32,
    /// Version
    version: u32,
    /// Number of items
    num_items: u32,
}

impl Encoder<()> for OvmfSevMetadataHeader {
    fn encode(&self, writer: &mut impl Write, _: ()) -> Result<(), std::io::Error> {
        writer.write_bytes(self.signature, ())?;
        writer.write_bytes(self.size, ())?;
        writer.write_bytes(self.version, ())?;
        writer.write_bytes(self.num_items, ())?;
        Ok(())
    }
}

impl Decoder<()> for OvmfSevMetadataHeader {
    fn decode(reader: &mut impl Read, _: ()) -> Result<Self, std::io::Error> {
        let signature = reader.read_bytes()?;
        let size = reader.read_bytes()?;
        let version = reader.read_bytes()?;
        let num_items = reader.read_bytes()?;
        Ok(Self {
            signature,
            size,
            version,
            num_items,
        })
    }
}

impl ByteParser<()> for OvmfSevMetadataHeader {
    // packed representation: 4 (signature) + 4 (size) + 4 (version) + 4 (num_items) = 16 bytes
    type Bytes = [u8; 16];
    const EXPECTED_LEN: Option<usize> = Some(16);
}

impl OvmfSevMetadataHeader {
    fn bytes_from_offset(value: &[u8], offset: usize) -> Result<Self, std::io::Error> {
        let mut bytes = &value[offset..offset + std::mem::size_of::<OvmfSevMetadataHeader>()];
        let decoded = Self::decode(&mut bytes, ())?;

        Ok(decoded)
    }

    /// Verify Header Signature
    fn verify(&self) -> Result<(), OVMFError> {
        let expected_signature: &[u8] = b"ASEV";
        if !self.signature.eq(expected_signature) {
            return Err(OVMFError::SEVMetadataVerification("signature".to_string()));
        }

        if self.version != 1 {
            return Err(OVMFError::SEVMetadataVerification("version".to_string()));
        }

        Ok(())
    }
}

/// OVMF Footer
#[repr(C, packed)]
#[derive(Debug, Clone, Copy)]
struct OvmfFooterTableEntry {
    /// Size
    size: u16,
    /// GUID
    guid: [u8; 16],
}

impl TryFrom<&[u8]> for OvmfFooterTableEntry {
    type Error = MeasurementError;

    /// Generate footer from data
    fn try_from(value: &[u8]) -> Result<OvmfFooterTableEntry, MeasurementError> {
        // Bytes 2-17 are the GUID
        let guid: [u8; 16] = value[2..18].try_into()?;
        // first 2 bytes are the size
        let size_nums: [u8; 2] = value[0..2].try_into()?;
        let size = u16::from_le_bytes(size_nums);
        Ok(OvmfFooterTableEntry { size, guid })
    }
}

const FOUR_GB: u64 = 0x100000000;
const OVMF_TABLE_FOOTER_GUID: Uuid = uuid!("96b582de-1fb2-45f7-baea-a366c55a082d");
const SEV_HASH_TABLE_RV_GUID: Uuid = uuid!("7255371f-3a3b-4b04-927b-1da6efa8d454");
const SEV_ES_RESET_BLOCK_GUID: Uuid = uuid!("00f771de-1a7e-4fcb-890e-68c77e2fb44e");
const OVMF_SEV_META_DATA_GUID: Uuid = uuid!("dc886566-984a-4798-a75e-5585a7bf67cc");

/// OVMF Structure
pub struct OVMF {
    /// OVMF data
    data: Vec<u8>,
    /// Table matching GUID to its data
    table: HashMap<Uuid, Vec<u8>>,
    /// Metadata item description
    metadata_items: Vec<OvmfSevMetadataSectionDesc>,
}

impl OVMF {
    /// Generate new OVMF structure by parsing the footer table and SEV metadata
    pub fn new(ovmf_file: PathBuf) -> Result<Self, MeasurementError> {
        let mut data = Vec::new();
        let mut file = match File::open(ovmf_file) {
            Ok(file) => file,
            Err(e) => return Err(MeasurementError::FileError(e)),
        };

        file.read_to_end(&mut data)?;

        let mut ovmf = OVMF {
            data,
            table: HashMap::new(),
            metadata_items: Vec::new(),
        };

        ovmf.parse_footer_table()?;
        ovmf.parse_sev_metadata()?;

        Ok(ovmf)
    }

    /// Grab OVMF data
    pub fn data(&self) -> &Vec<u8> {
        &self.data
    }

    /// Calculate OVMF GPA
    pub fn gpa(&self) -> u64 {
        FOUR_GB - self.data.len() as u64
    }

    /// Get an item from the OVMF table
    fn table_item(&self, guid: &Uuid) -> Option<&Vec<u8>> {
        self.table.get(guid)
    }

    /// Get the OVMF metadata items
    pub fn metadata_items(&self) -> &Vec<OvmfSevMetadataSectionDesc> {
        &self.metadata_items
    }

    /// Check if the metadata items have the desired section
    pub fn has_metadata_section(&self, section_type: SectionType) -> bool {
        self.metadata_items()
            .iter()
            .any(|s| s.section_type == section_type)
    }

    /// Check that the table supports SEV hashes
    pub fn is_sev_hashes_table_supported(&self) -> bool {
        self.table.contains_key(&SEV_HASH_TABLE_RV_GUID)
            && self.sev_hashes_table_gpa().unwrap_or(0) != 0
    }

    /// Get the SEV HASHES GPA
    pub fn sev_hashes_table_gpa(&self) -> Result<u64, OVMFError> {
        if !self.table.contains_key(&SEV_HASH_TABLE_RV_GUID) {
            return Err(OVMFError::EntryMissingInTable(
                "SEV_HASH_TABLE_RV_GUID".to_string(),
            ));
        }

        if let Some(gpa) = self
            .table_item(&SEV_HASH_TABLE_RV_GUID)
            .and_then(|entry| entry.get(..4))
            .map(|bytes| LittleEndian::read_u32(bytes) as u64)
        {
            Ok(gpa)
        } else {
            Err(OVMFError::GetTableItemError)
        }
    }

    /// Get the SEV-ES EIP
    pub fn sev_es_reset_eip(&self) -> Result<u32, OVMFError> {
        if !self.table.contains_key(&SEV_ES_RESET_BLOCK_GUID) {
            return Err(OVMFError::EntryMissingInTable(
                "SEV_ES_RESET_BLOCK_GUID".to_string(),
            ));
        }

        if let Some(eip) = self
            .table_item(&SEV_ES_RESET_BLOCK_GUID)
            .and_then(|entry| entry.get(..4))
            .map(LittleEndian::read_u32)
        {
            Ok(eip)
        } else {
            Err(OVMFError::GetTableItemError)
        }
    }

    /// Parse footer table data
    fn parse_footer_table(&mut self) -> Result<(), MeasurementError> {
        self.table.clear();
        let size = self.data.len();
        const ENTRY_HEADER_SIZE: usize = std::mem::size_of::<OvmfFooterTableEntry>();
        //The OVMF table ends 32 bytes before the end of the firmware binary
        let start_of_footer_table = size - 32 - ENTRY_HEADER_SIZE;
        let footer =
            OvmfFooterTableEntry::try_from(&self.data.as_slice()[start_of_footer_table..])?;

        let expected_footer_guid = guid_le_to_slice(OVMF_TABLE_FOOTER_GUID.to_string().as_str())?;

        if !footer.guid.eq(&expected_footer_guid) {
            return Err(OVMFError::MismatchingGUID)?;
        }

        if (footer.size as usize) < ENTRY_HEADER_SIZE {
            return Err(OVMFError::InvalidSize(
                "OVMF Table Footer".to_string(),
                footer.size as usize,
                ENTRY_HEADER_SIZE,
            ))?;
        }

        let table_size = footer.size as usize - ENTRY_HEADER_SIZE;

        let table_start = start_of_footer_table - table_size;
        let table_bytes = &self.data[table_start..start_of_footer_table];
        let mut offset = table_size;
        while offset >= ENTRY_HEADER_SIZE {
            let entry =
                OvmfFooterTableEntry::try_from(&table_bytes[offset - ENTRY_HEADER_SIZE..offset])?;
            if entry.size < ENTRY_HEADER_SIZE as u16 {
                return Err(OVMFError::InvalidSize(
                    "OVMF Table Entry".to_string(),
                    entry.size as usize,
                    ENTRY_HEADER_SIZE,
                ))?;
            }
            let entry_guid = Uuid::from_slice_le(&entry.guid)?;

            if offset < entry.size as usize {
                break;
            }
            let entry_data = &table_bytes[offset - entry.size as usize..offset - ENTRY_HEADER_SIZE];
            self.table.insert(entry_guid, entry_data.to_vec());

            offset -= entry.size as usize;
        }

        Ok(())
    }

    /// parse SEV metadata
    fn parse_sev_metadata(&mut self) -> Result<(), MeasurementError> {
        match self.table.get(&OVMF_SEV_META_DATA_GUID) {
            Some(entry) => {
                let offset_from_end = i32::from_le_bytes(entry[..4].try_into()?);
                let header_start = self.data.len() - (offset_from_end as usize);
                let header =
                    OvmfSevMetadataHeader::bytes_from_offset(self.data.as_slice(), header_start)?;
                header.verify()?;
                let items = &self.data[header_start + std::mem::size_of::<OvmfSevMetadataHeader>()
                    ..header_start + header.size as usize];
                for i in 0..header.num_items {
                    let offset = (i as usize) * std::mem::size_of::<OvmfSevMetadataSectionDesc>();
                    let item = OvmfSevMetadataSectionDesc::bytes_from_offset(items, offset)?;
                    self.metadata_items.push(item.to_owned());
                }
            }

            None => {
                return Err(OVMFError::EntryMissingInTable(
                    "OVMF_SEV_METADATA_GUID".to_string(),
                ))?;
            }
        }

        Ok(())
    }
}