forked from virtee/sev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sev.rs
431 lines (347 loc) · 12.6 KB
/
sev.rs
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
// SPDX-License-Identifier: Apache-2.0
//! An implementation of the SEV (non-ES, non-SNP) launch process as a type-state machine.
//! This ensures (at compile time) that the right steps are called in the
//! right order.
use crate::error::{Error::InvalidLen, Indeterminate};
#[cfg(target_os = "linux")]
use crate::launch::linux::ioctl::*;
#[cfg(target_os = "linux")]
use crate::launch::linux::sev::*;
use crate::*;
use std::convert::TryFrom;
use std::io::Result;
use std::mem::MaybeUninit;
use std::os::unix::io::AsRawFd;
use bitflags::bitflags;
use serde::{Deserialize, Serialize};
/// Launcher type-state that indicates a brand new launch.
pub struct New;
/// Launcher type-state that indicates an in-progress launch.
pub struct Started(Handle);
/// Launcher type-state that indicates the availability of a measurement.
pub struct Measured(Handle, Measurement);
/// Launcher type-state that indicates the launcher is finished launching, and it's attestation
/// report can be fetched.
pub struct Finished;
/// Facilitates the correct execution of the SEV launch process.
pub struct Launcher<T, U: AsRawFd, V: AsRawFd> {
state: T,
vm_fd: U,
sev: V,
}
impl<T, U: AsRawFd, V: AsRawFd> Launcher<T, U, V> {
/// Give access to the vm fd to create vCPUs or such.
pub fn as_mut_vmfd(&mut self) -> &mut U {
&mut self.vm_fd
}
}
impl<U: AsRawFd, V: AsRawFd> Launcher<New, U, V> {
/// Begin the SEV launch process.
pub fn new(kvm: U, sev: V) -> Result<Self> {
let mut launcher = Launcher {
vm_fd: kvm,
sev,
state: New,
};
let mut cmd = Command::from(&launcher.sev, &Init);
INIT.ioctl(&mut launcher.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(launcher)
}
/// Begin the SEV-ES launch process.
pub fn new_es(kvm: U, sev: V) -> Result<Self> {
let mut launcher = Launcher {
vm_fd: kvm,
sev,
state: New,
};
let mut cmd = Command::from(&launcher.sev, &EsInit);
ES_INIT
.ioctl(&mut launcher.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(launcher)
}
/// Create an encrypted guest context.
pub fn start(mut self, start: Start) -> Result<Launcher<Started, U, V>> {
let mut launch_start = LaunchStart::new(&start.policy, &start.cert, &start.session);
let mut cmd = Command::from_mut(&self.sev, &mut launch_start);
LAUNCH_START
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
let next = Launcher {
state: Started(launch_start.into()),
vm_fd: self.vm_fd,
sev: self.sev,
};
Ok(next)
}
}
impl<U: AsRawFd, V: AsRawFd> Launcher<Started, U, V> {
/// Encrypt guest data with its VEK.
pub fn update_data(&mut self, data: &[u8]) -> Result<()> {
let launch_update_data = LaunchUpdateData::new(data);
let mut cmd = Command::from(&self.sev, &launch_update_data);
KvmEncRegion::new(data).register(&mut self.vm_fd)?;
LAUNCH_UPDATE_DATA
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(())
}
/// Register the encrypted memory region to a virtual machine.
/// Corresponds to the `KVM_MEMORY_ENCRYPT_REG_REGION` ioctl.
pub fn register_kvm_enc_region(&mut self, data: &[u8]) -> Result<()> {
KvmEncRegion::new(data).register(&mut self.vm_fd)?;
Ok(())
}
/// Encrypt guest data with its VEK, while the KVM encrypted memory region is not registered.
pub fn update_data_without_registration(&mut self, data: &[u8]) -> Result<()> {
let launch_update_data = LaunchUpdateData::new(data);
let mut cmd = Command::from(&self.sev, &launch_update_data);
LAUNCH_UPDATE_DATA
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(())
}
/// Encrypt the VMSA on SEV-ES.
pub fn update_vmsa(&mut self) -> Result<()> {
let launch_update_vmsa = LaunchUpdateVmsa::new();
let mut cmd = Command::from(&self.sev, &launch_update_vmsa);
LAUNCH_UPDATE_VMSA
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(())
}
/// Request a measurement from the SEV firmware.
pub fn measure(mut self) -> Result<Launcher<Measured, U, V>> {
let mut measurement = MaybeUninit::uninit();
let mut launch_measure = LaunchMeasure::new(&mut measurement);
let mut cmd = Command::from_mut(&self.sev, &mut launch_measure);
LAUNCH_MEASUREMENT
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
let next = Launcher {
state: Measured(self.state.0, unsafe { measurement.assume_init() }),
vm_fd: self.vm_fd,
sev: self.sev,
};
Ok(next)
}
}
impl<U: AsRawFd, V: AsRawFd> Launcher<Measured, U, V> {
/// Get the measurement that the SEV platform recorded.
pub fn measurement(&self) -> Measurement {
self.state.1
}
/// Inject a secret into the guest.
///
/// ## Remarks
///
/// This should only be called after a successful attestation flow.
pub fn inject(&mut self, secret: &Secret, guest: usize) -> Result<()> {
let launch_secret = LaunchSecret::new(&secret.header, guest, &secret.ciphertext[..]);
let mut cmd = Command::from(&self.sev, &launch_secret);
LAUNCH_SECRET
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(())
}
/// Complete the SEV launch process.
pub fn finish(mut self) -> Result<Handle> {
let mut cmd = Command::from(&self.sev, &LaunchFinish);
LAUNCH_FINISH
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(self.state.0)
}
/// Complete the SEV launch process, and produce another Launcher capable of fetching an
/// attestation report.
pub fn finish_attestable(mut self) -> Result<Launcher<Finished, U, V>> {
let mut cmd = Command::from(&self.sev, &LaunchFinish);
LAUNCH_FINISH
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
let next = Launcher {
state: Finished,
vm_fd: self.vm_fd,
sev: self.sev,
};
Ok(next)
}
}
impl<U: AsRawFd, V: AsRawFd> Launcher<Finished, U, V> {
/// Get the attestation report of the VM.
pub fn report(&mut self, mnonce: [u8; 16]) -> Result<Vec<u8>> {
let mut first = LaunchAttestation::default();
let mut cmd = Command::from_mut(&self.sev, &mut first);
let mut len = 0;
let e = LAUNCH_ATTESTATION
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e));
if let Err(err) = e {
if let Indeterminate::Known(InvalidLen) = err {
len = first.len;
} else {
return Err(err.into());
}
}
let mut bytes = vec![0u8; usize::try_from(len).unwrap()];
let mut second = LaunchAttestation::new(mnonce, &mut bytes);
cmd = Command::from_mut(&self.sev, &mut second);
LAUNCH_ATTESTATION
.ioctl(&mut self.vm_fd, &mut cmd)
.map_err(|e| cmd.encapsulate(e))?;
Ok(bytes)
}
}
bitflags! {
/// Configurable SEV Policy options.
#[derive(Default, Deserialize, Serialize)]
pub struct PolicyFlags: u16 {
/// When set, debugging the guest is forbidden.
const NO_DEBUG = 0b00000001u16.to_le();
/// When set, sharing keys with other guests is prohibited.
const NO_KEY_SHARING = 0b00000010u16.to_le();
/// When set, SEV-ES protections are required.
const ENCRYPTED_STATE = 0b00000100u16.to_le();
/// When set, the guest may not be sent to another platform.
const NO_SEND = 0b00001000u16.to_le();
/// When set, the guest may not be transmitted to a platform
/// that is outside of the domain.
const DOMAIN = 0b00010000u16.to_le();
/// When set, the guest may not be transmitted to another
/// platform that is not SEV-capable.
const SEV = 0b00100000u16.to_le();
}
}
/// Describes a policy that the AMD Secure Processor will
/// enforce.
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Policy {
/// The various policy optons are encoded as bit flags.
pub flags: PolicyFlags,
/// The desired minimum platform firmware version.
pub minfw: Version,
}
/// Convert a policy represented as a u32 to a Policy struct.
impl From<u32> for Policy {
fn from(p: u32) -> Self {
let flags = p as u16;
let flags = PolicyFlags::from_bits_truncate(flags);
let p = p >> 16;
let p = p as u16;
let minfw = Version::from(p);
Self { flags, minfw }
}
}
/// A secure channel between the tenant and the AMD Secure
/// Processor.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Session {
/// Used for deriving a shared secret between the tenant
/// and the AMD SP.
pub nonce: [u8; 16],
/// The TEK and TIK concatenated together and wrapped by
/// the Key Encryption Key and the Key Integrity Key.
/// (KIK (KEK (TEK|TIK))).
pub wrap_tk: [u8; 32],
/// The initialization vector.
pub wrap_iv: [u8; 16],
/// Integrity protection for the wrapped keys (see the
/// `wrap_tk` field of this struct).
pub wrap_mac: [u8; 32],
/// The integrity-protected SEV policy.
pub policy_mac: [u8; 32],
}
/// Used to establish a secure session with the AMD SP.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Start {
/// The tenant's policy for this SEV guest.
pub policy: Policy,
/// The tenant's Diffie-Hellman certificate.
pub cert: certs::sev::sev::Certificate,
/// A secure channel with the AMD SP.
pub session: Session,
}
impl codicon::Decoder<()> for Start {
type Error = std::io::Error;
fn decode(mut reader: impl Read, _: ()) -> std::io::Result<Self> {
reader.load()
}
}
impl codicon::Encoder<()> for Start {
type Error = std::io::Error;
fn encode(&self, mut writer: impl Write, _: ()) -> std::io::Result<()> {
writer.save(self)
}
}
bitflags! {
/// Additional descriptions of the secret header packet.
#[derive(Default, Deserialize, Serialize)]
pub struct HeaderFlags: u32 {
/// If set, the contents of the packet are compressed and
/// the AMD SP must decompress them.
const COMPRESSED = 0b00000001u32.to_le();
}
}
/// The header for a data packet that contains secret information
/// to be injected into the guest.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Header {
/// Describes the secret packet (for example: if it is
/// compressed).
pub flags: HeaderFlags,
/// The initialization vector.
pub iv: [u8; 16],
/// Integrity protection MAC.
pub mac: [u8; 32],
}
/// A packet containing secret information to be injected
/// into the guest.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Secret {
/// The header for this packet.
pub header: Header,
/// The encrypted secret to inject.
pub ciphertext: Vec<u8>,
}
impl codicon::Decoder<()> for Secret {
type Error = std::io::Error;
fn decode(mut reader: impl Read, _: ()) -> std::io::Result<Self> {
let header = reader.load()?;
let mut ciphertext = vec![];
let _ = reader.read_to_end(&mut ciphertext)?;
Ok(Self { header, ciphertext })
}
}
impl codicon::Encoder<()> for Secret {
type Error = std::io::Error;
fn encode(&self, mut writer: impl Write, _: ()) -> std::io::Result<()> {
writer.save(&self.header)?;
writer.write_all(&self.ciphertext)
}
}
/// A measurement of the SEV guest.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Measurement {
/// The measurement.
pub measure: [u8; 32],
/// A random nonce.
pub mnonce: [u8; 16],
}
impl codicon::Decoder<()> for Measurement {
type Error = std::io::Error;
fn decode(mut reader: impl Read, _: ()) -> std::io::Result<Self> {
reader.load()
}
}
impl codicon::Encoder<()> for Measurement {
type Error = std::io::Error;
fn encode(&self, mut writer: impl Write, _: ()) -> std::io::Result<()> {
writer.save(self)
}
}