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
// SPDX-License-Identifier: Apache-2.0
use super::attestation::{get_attestation_key_id, get_key_size, get_quote, get_target_info};
#[cfg(feature = "gdb")]
use crate::backend::execute_gdb;
use crate::backend::Command;
use std::arch::asm;
use std::arch::x86_64::CpuidResult;
use std::io;
use std::iter;
use std::mem::{size_of, MaybeUninit};
#[cfg(feature = "gdb")]
use std::net::TcpStream;
use std::sync::Arc;
use crate::backend::sgx::attestation::get_quote_size;
use anyhow::{Context, Result};
use sallyport::host::{deref_aligned, deref_slice};
use sallyport::item;
use sallyport::item::enarxcall::sgx::{Report, TargetInfo};
use sallyport::item::enarxcall::Payload;
use sallyport::item::{Block, Item};
use sgx::enclu::{EENTER, EEXIT, ERESUME};
use sgx::ssa::Vector;
use vdso::Symbol;
pub struct Thread {
enclave: Arc<super::Keep>,
vdso: &'static Symbol,
tcs: *const super::Tcs,
block: Vec<usize>,
cssa: usize,
how: usize,
#[cfg(feature = "gdb")]
gdb_fd: Option<TcpStream>,
}
impl Drop for Thread {
fn drop(&mut self) {
self.enclave.tcs.write().unwrap().push(self.tcs)
}
}
impl super::super::Keep for super::Keep {
fn spawn(self: Arc<Self>) -> Result<Option<Box<dyn super::super::Thread>>> {
let vdso = vdso::Vdso::locate()
.expect("vDSO not found")
.lookup("__vdso_sgx_enter_enclave")
.expect("__vdso_sgx_enter_enclave not found");
let tcs = match self.tcs.write().unwrap().pop() {
Some(tcs) => tcs,
None => return Ok(None),
};
let block = vec![0; self.sallyport_block_size as usize / size_of::<usize>()];
Ok(Some(Box::new(Thread {
enclave: self,
vdso,
tcs,
block,
cssa: usize::default(),
how: EENTER,
#[cfg(feature = "gdb")]
gdb_fd: None,
})))
}
}
fn sgx_enarxcall<'a>(enarxcall: &'a mut Payload, data: &'a mut [u8]) -> Result<Option<Item<'a>>> {
match enarxcall {
item::Enarxcall {
num: item::enarxcall::Number::Cpuid,
argv: [leaf, subleaf, cpuid_offset, ..],
ret,
} => {
let cpuid_buf = unsafe {
// Safety: `deref_aligned` gives us a pointer to an aligned `CpuidResult` struct.
// We also know, that the resulting pointer is inside the allocated sallyport block, where `data`
// is a subslice of.
&mut *deref_aligned::<MaybeUninit<CpuidResult>>(data, *cpuid_offset, 1)
.map_err(io::Error::from_raw_os_error)
.context("sgx_enarxcall deref")?
};
// Safety: we know we are on an SGX machine, which can do cpuid
let cpuid_ret = unsafe { core::arch::x86_64::__cpuid_count(*leaf as _, *subleaf as _) };
cpuid_buf.write(cpuid_ret);
*ret = 0;
Ok(None)
}
item::Enarxcall {
num: item::enarxcall::Number::GetSgxTargetInfo,
argv: [target_info_offset, ..],
ret,
} => {
let out_buf = unsafe {
// Safety: `deref_slice` gives us a pointer to a byte slice, which does not have to be aligned.
// We also know, that the resulting pointer is inside the allocated sallyport block, where `data`
// is a subslice of.
&mut *deref_slice::<u8>(data, *target_info_offset, size_of::<TargetInfo>())
.map_err(io::Error::from_raw_os_error)
.context("sgx_enarxcall deref")?
};
let akid = get_attestation_key_id().context("error obtaining attestation key id")?;
let pkeysize = get_key_size(akid.clone()).context("error obtaining key size")?;
*ret = get_target_info(akid, pkeysize, out_buf).context("error getting target info")?;
Ok(None)
}
item::Enarxcall {
num: item::enarxcall::Number::GetSgxQuote,
argv: [report_offset, quote_offset, quote_len, ..],
ret,
} => {
let report_buf = unsafe {
// Safety: `deref_slice` gives us a pointer to a byte slice, which does not have to be aligned.
// We also know, that the resulting pointer is inside the allocated sallyport block, where `data`
// is a subslice of.
&mut *deref_slice::<u8>(data, *report_offset, size_of::<Report>())
.map_err(io::Error::from_raw_os_error)
.context("sgx_enarxcall deref")?
};
let quote_buf = unsafe {
// Safety: `deref_slice` gives us a pointer to a byte slice, which does not have to be aligned.
// We also know, that the resulting pointer is inside the allocated sallyport block, where `data`
// is a subslice of.
&mut *deref_slice::<u8>(data, *quote_offset, *quote_len)
.map_err(io::Error::from_raw_os_error)
.context("sgx_enarxcall deref")?
};
let akid = get_attestation_key_id().context("error obtaining attestation key id")?;
*ret = get_quote(report_buf, akid, quote_buf).context("error getting quote")?;
Ok(None)
}
item::Enarxcall {
num: item::enarxcall::Number::GetSgxQuoteSize,
ret,
..
} => {
let akid = get_attestation_key_id().context("error obtaining attestation key id")?;
*ret = get_quote_size(akid).context("error getting quote size")?;
Ok(None)
}
_ => return Ok(Some(Item::Enarxcall(enarxcall, data))),
}
}
impl super::super::Thread for Thread {
fn enter(&mut self, _gdblisten: &Option<String>) -> Result<Command> {
let mut run: Run = unsafe { MaybeUninit::zeroed().assume_init() };
run.tcs = self.tcs as u64;
let how = self.how;
// The `enclu` instruction consumes `rax`, `rbx` and `rcx`. However,
// the vDSO function preserves `rbx` AND sets `rax` as the return
// value. All other registers are passed to and from the enclave
// unmodified.
unsafe {
asm!(
"push rbx", // save rbx
"push rbp", // save rbp
"mov rbp, rsp", // save rsp
"and rsp, ~0xf", // align to 16+0
"push 0", // align to 16+8
"push r10", // push run address
"call r11", // call vDSO function
"mov rsp, rbp", // restore rsp
"pop rbp", // restore rbp
"pop rbx", // restore rbx
inout("rdi") self.block.as_mut_ptr() => _,
lateout("rsi") _,
lateout("rdx") _,
inout("rcx") how => _,
lateout("r8") _,
lateout("r9") _,
inout("r10") &mut run => _,
inout("r11") self.vdso => _,
lateout("r12") _,
lateout("r13") _,
lateout("r14") _,
lateout("r15") _,
lateout("rax") _,
);
}
self.how = match run.function as usize {
EENTER | ERESUME if run.vector == Vector::InvalidOpcode => EENTER,
#[cfg(feature = "gdb")]
EENTER | ERESUME if run.vector == Vector::Page => EENTER,
EEXIT => ERESUME,
_ => panic!("Unexpected AEX: {:?}", run.vector),
};
// Keep track of the CSSA
match self.how {
EENTER => self.cssa += 1,
ERESUME => match self.cssa {
0 => unreachable!(),
_ => self.cssa -= 1,
},
_ => unreachable!(),
}
// If we have handled an InvalidOpcode error, evaluate the sallyport.
//
// Currently, we have no way to know if the sallyport contains a valid
// request by evaluating the sallyport directly. So we must presume
// that the sallyport is only valid when moving from CSSA 2 to CSSA 1.
//
// After the sallyport rework, we can test the sallyport itself and
// remove this logic.
if self.cssa > 0 {
if let (EENTER, ERESUME) = (how, self.how) {
let block: Block = self.block.as_mut_slice().into();
for item in block {
match item {
Item::Gdbcall(_gdbcall, _data) => {
#[cfg(feature = "gdb")]
unsafe {
execute_gdb(
_gdbcall,
_data,
&mut self.gdb_fd,
_gdblisten.as_ref().unwrap(),
)
.map_err(io::Error::from_raw_os_error)
.context("execute_gdb")?;
}
}
Item::Enarxcall(enarxcall, data) => {
sallyport::host::execute(sgx_enarxcall(enarxcall, data)?.into_iter())
.map_err(io::Error::from_raw_os_error)
.context("sallyport::host::execute")?;
}
// Catch exit and exit_group for a clean shutdown
Item::Syscall(syscall, ..)
if (syscall.num == libc::SYS_exit as usize
|| syscall.num == libc::SYS_exit_group as usize) =>
{
if cfg!(feature = "dbg") {
dbg!(&syscall);
}
return Ok(Command::Exit(syscall.argv[0] as _));
}
Item::Syscall(ref _syscall, ..) => {
#[cfg(feature = "dbg")]
match (
_syscall.num as libc::c_long,
_syscall.argv[1] as libc::c_int,
) {
(
libc::SYS_write | libc::SYS_read,
libc::STDIN_FILENO | libc::STDOUT_FILENO | libc::STDERR_FILENO,
) => {}
_ => {
dbg!(&_syscall);
}
}
sallyport::host::execute(iter::once(item))
.map_err(io::Error::from_raw_os_error)
.context("sallyport::host::execute")?;
}
}
}
}
}
Ok(Command::Continue)
}
}
// This structure is defined by the Linux kernel.
//
// See: https://github.com/torvalds/linux/blob/84292fffc2468125632a21c09533a89426ea212e/arch/x86/include/uapi/asm/sgx.h#L112
#[repr(C)]
#[derive(Debug)]
struct Run {
tcs: u64,
function: u32,
vector: Vector,
padding: u8,
exception_error_code: u16,
exception_addr: u64,
user_handler: u64,
user_data: u64,
reserved: [u64; 27],
}