Skip to main content

sgxs_loaders/sgx_enclave_common/
mod.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7pub extern crate libloading as dl;
8
9use std::convert::TryFrom;
10use std::io::{Result as IoResult, Error as IoError};
11use std::os::raw::c_void;
12use std::sync::Arc;
13use std::{fmt, mem, ptr};
14
15use sgx_isa::{Attributes, Einittoken, Miscselect, PageType, SecinfoFlags, Secs, Sigstruct};
16use sgxs::einittoken::EinittokenProvider;
17use sgxs::loader;
18use sgxs::sgxs::{MeasEAdd, MeasECreate, PageChunks, SgxsRead};
19use thiserror::Error as ThisError;
20
21use crate::{MappingInfo, Tcs};
22use crate::generic::{self, EinittokenError, EnclaveLoad, Mapping};
23
24mod defs;
25
26use self::defs::*;
27
28#[derive(ThisError, Debug)]
29#[non_exhaustive]
30pub enum LibraryError {
31    #[error(
32        "Enclave type not supported, Intel SGX not supported, or Intel SGX device not present"
33    )]
34    NotSupported,
35    #[error("SGX - SIGSTRUCT contains an invalid value")]
36    InvalidSigstruct,
37    #[error("SGX - invalid signature or the SIGSTRUCT value")]
38    InvalidSignature,
39    #[error("SGX - invalid SECS attribute")]
40    InvalidAttribute,
41    #[error("SGX - invalid measurement")]
42    InvalidMeasurement,
43    #[error(
44        "Enclave not authorized to run. For example, the enclave does not have a signing privilege required for a requested attribute."
45    )]
46    NotAuthorized,
47    #[error("Address is not a valid enclave")]
48    InvalidEnclave,
49    #[error("SGX - enclave is lost (likely due to a power event)")]
50    EnclaveLost,
51    #[error(
52        "Invalid Parameter (unspecified) - may occur due to a wrong length or format type"
53    )]
54    InvalidParameter,
55    #[error(
56        "Out of memory. May be a result of allocation failure in the API or internal function calls"
57    )]
58    OutOfMemory,
59    #[error("Out of EPC memory")]
60    DeviceNoResources,
61    #[error("Enclave has already been initialized")]
62    AlreadyInitialized,
63    #[error("Address is not within a valid enclave / Address has already been committed")]
64    InvalidAddress,
65    #[error("Please retry the operation - an unmasked event occurred in EINIT")]
66    Retry,
67    #[error("Invalid size")]
68    InvalidSize,
69    #[error("Enclave is not initialized - the operation requires an initialized enclave")]
70    NotInitialized,
71    #[error("Unexpected error in the API")]
72    Unexpected,
73    #[error("Unknown error ({}) in SGX device interface", _0)]
74    Other(u32),
75    #[error("Failed to adjust the page table permissions: {}", _0)]
76    PageTableFailure(IoError),
77}
78
79impl From<u32> for LibraryError {
80    fn from(error: u32) -> Self {
81        use self::LibraryError::*;
82        match error {
83            ENCLAVE_NOT_SUPPORTED => NotSupported,
84            ENCLAVE_INVALID_SIG_STRUCT => InvalidSigstruct,
85            ENCLAVE_INVALID_SIGNATURE => InvalidSignature,
86            ENCLAVE_INVALID_ATTRIBUTE => InvalidAttribute,
87            ENCLAVE_INVALID_MEASUREMENT => InvalidMeasurement,
88            ENCLAVE_NOT_AUTHORIZED => NotAuthorized,
89            ENCLAVE_INVALID_ENCLAVE => InvalidEnclave,
90            ENCLAVE_LOST => EnclaveLost,
91            ENCLAVE_INVALID_PARAMETER => InvalidParameter,
92            ENCLAVE_OUT_OF_MEMORY => OutOfMemory,
93            ENCLAVE_DEVICE_NO_RESOURCES => DeviceNoResources,
94            ENCLAVE_ALREADY_INITIALIZED => AlreadyInitialized,
95            ENCLAVE_INVALID_ADDRESS => InvalidAddress,
96            ENCLAVE_RETRY => Retry,
97            ENCLAVE_INVALID_SIZE => InvalidSize,
98            ENCLAVE_NOT_INITIALIZED => NotInitialized,
99            ENCLAVE_UNEXPECTED => Unexpected,
100            _ => Other(error),
101        }
102    }
103}
104
105#[derive(ThisError, Debug)]
106pub enum Error {
107    #[error("Failed to call ECREATE.")]
108    Create(#[source] LibraryError),
109    #[error("Failed to call EADD.")]
110    Add(#[source] LibraryError),
111    #[error("Failed to call EINIT.")]
112    Init(#[source] LibraryError),
113}
114
115impl EinittokenError for Error {
116    fn is_einittoken_error(&self) -> bool {
117        match self {
118            &Error::Init(LibraryError::InvalidAttribute) |
119            &Error::Init(LibraryError::InvalidMeasurement) |
120            // InvalidEinitToken and InvalidCpusvn get coded this way
121            &Error::Init(LibraryError::Other(ENCLAVE_UNEXPECTED)) => true,
122            _ => false,
123        }
124    }
125}
126
127impl EnclaveLoad for InnerLibrary {
128    type Error = Error;
129    type MapData = ();
130
131    fn new(
132        device: Arc<InnerLibrary>,
133        ecreate: MeasECreate,
134        attributes: Attributes,
135        miscselect: Miscselect,
136    ) -> Result<Mapping<Self>, Self::Error> {
137        let secs = Secs {
138            size: ecreate.size,
139            ssaframesize: ecreate.ssaframesize,
140            miscselect,
141            attributes,
142            ..Default::default()
143        };
144
145        let mut error = 0;
146
147        let base = unsafe {
148            (device.enclave_create)(
149                ptr::null_mut(),
150                ecreate.size as _,
151                0,
152                EnclaveType::Sgx1,
153                &secs,
154                mem::size_of::<Secs>(),
155                Some(&mut error),
156            )
157        };
158
159        if base.is_null() {
160            Err(Error::Create(error.into()))
161        } else {
162            Ok(Mapping {
163                device,
164                mapdata: (),
165                tcss: vec![],
166                base: base as _,
167                size: ecreate.size,
168            })
169        }
170    }
171
172    fn add(
173        mapping: &mut Mapping<Self>,
174        page: (MeasEAdd, PageChunks, [u8; 4096]),
175    ) -> Result<(), Self::Error> {
176        let (eadd, chunks, data) = page;
177        let data = Align4096(data);
178
179        let mut flags = PageProperties::empty();
180        if eadd
181            .secinfo
182            .flags
183            .intersects(SecinfoFlags::PENDING | SecinfoFlags::MODIFIED | SecinfoFlags::PR)
184        {
185            return Err(Error::Add(LibraryError::InvalidParameter));
186        }
187        if eadd.secinfo.flags.intersects(SecinfoFlags::R) {
188            flags.insert(PageProperties::R)
189        }
190        if eadd.secinfo.flags.intersects(SecinfoFlags::W) {
191            flags.insert(PageProperties::W)
192        }
193        if eadd.secinfo.flags.intersects(SecinfoFlags::X) {
194            flags.insert(PageProperties::X)
195        }
196        match PageType::try_from(eadd.secinfo.flags.page_type()) {
197            Ok(PageType::Reg) => {}
198            Ok(PageType::Tcs) => flags.insert(PageProperties::TCS),
199            _ => return Err(Error::Add(LibraryError::InvalidParameter)),
200        }
201        match chunks.0 {
202            0 => flags.insert(PageProperties::UNVALIDATED),
203            0xffff => {}
204            _ => return Err(Error::Add(LibraryError::InvalidParameter)),
205        }
206
207        unsafe {
208            let mut error = 0;
209            if (mapping.device.enclave_load_data)(
210                (mapping.base + eadd.offset) as _,
211                0x1000,
212                &data,
213                flags,
214                Some(&mut error),
215            ) != 0x1000
216            {
217                return Err(Error::Add(error.into()));
218            }
219        }
220
221        Ok(())
222    }
223
224    fn init(
225        mapping: &mut Mapping<Self>,
226        sigstruct: &Sigstruct,
227        einittoken: Option<&Einittoken>,
228    ) -> Result<(), Self::Error> {
229        unsafe {
230            let mut error = 0;
231
232            if let Some(einittoken) = einittoken {
233                if !(mapping.device.enclave_set_information)(
234                    mapping.base as _,
235                    InfoType::EnclaveLaunchToken,
236                    einittoken as *const _ as _,
237                    mem::size_of::<Einittoken>(),
238                    Some(&mut error),
239                ) {
240                    match Error::Init(error.into()) {
241                        // ignore error if setting einittoken is not supported
242                        Error::Init(LibraryError::NotSupported) => {}
243                        err => return Err(err),
244                    }
245                }
246            }
247
248            if !(mapping.device.enclave_initialize)(
249                mapping.base as _,
250                sigstruct,
251                Sigstruct::UNPADDED_SIZE,
252                Some(&mut error),
253            ) {
254                return Err(Error::Init(error.into()));
255            }
256
257            Ok(())
258        }
259    }
260
261    fn destroy(mapping: &mut Mapping<Self>) {
262        unsafe {
263            (mapping.device.enclave_delete)(mapping.base as _, None);
264        }
265    }
266}
267
268struct InnerLibrary {
269    library: dl::Library,
270    enclave_create: EnclaveCreateFn,
271    enclave_load_data: EnclaveLoadDataFn,
272    enclave_initialize: EnclaveInitializeFn,
273    enclave_delete: EnclaveDeleteFn,
274    enclave_set_information: EnclaveSetInformationFn,
275}
276
277impl fmt::Debug for InnerLibrary {
278    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
279        f.debug_struct("InnerLibrary")
280            .field("library", &self.library)
281            .field("enclave_create", &(self.enclave_create as *const c_void))
282            .field(
283                "enclave_load_data",
284                &(self.enclave_load_data as *const c_void),
285            )
286            .field(
287                "enclave_initialize",
288                &(self.enclave_initialize as *const c_void),
289            )
290            .field("enclave_delete", &(self.enclave_delete as *const c_void))
291            .field(
292                "enclave_set_information",
293                &(self.enclave_set_information as *const c_void),
294            )
295            .finish()
296    }
297}
298
299#[derive(Debug)]
300pub struct Library {
301    inner: generic::Device<InnerLibrary>,
302}
303
304pub struct LibraryBuilder {
305    inner: generic::DeviceBuilder<InnerLibrary>,
306}
307
308impl Library {
309    pub fn load(library: Option<dl::Library>) -> IoResult<LibraryBuilder> {
310        unsafe {
311            let library = library.map_or_else(|| dl::Library::new(LIBRARY), Ok)?;
312            let enclave_create = *library.get::<EnclaveCreateFn>(SYM_ENCLAVE_CREATE)?;
313            let enclave_load_data = *library.get::<EnclaveLoadDataFn>(SYM_ENCLAVE_LOAD_DATA)?;
314            let enclave_initialize = *library.get::<EnclaveInitializeFn>(SYM_ENCLAVE_INITIALIZE)?;
315            let enclave_delete = *library.get::<EnclaveDeleteFn>(SYM_ENCLAVE_DELETE)?;
316            let enclave_set_information =
317                *library.get::<EnclaveSetInformationFn>(SYM_ENCLAVE_SET_INFORMATION)?;
318            Ok(LibraryBuilder {
319                inner: generic::DeviceBuilder {
320                    device: generic::Device {
321                        inner: Arc::new(InnerLibrary {
322                            library,
323                            enclave_create,
324                            enclave_load_data,
325                            enclave_initialize,
326                            enclave_delete,
327                            enclave_set_information,
328                        }),
329                        einittoken_provider: None,
330                    },
331                },
332            })
333        }
334    }
335}
336
337impl loader::Load for Library {
338    type MappingInfo = MappingInfo;
339    type Tcs = Tcs;
340
341    fn load<R: SgxsRead>(
342        &mut self,
343        reader: &mut R,
344        sigstruct: &Sigstruct,
345        attributes: Attributes,
346        miscselect: Miscselect,
347    ) -> ::std::result::Result<loader::Mapping<Self>, ::anyhow::Error> {
348        self.inner
349            .load(reader, sigstruct, attributes, miscselect)
350            .map(Into::into)
351    }
352}
353
354impl LibraryBuilder {
355    pub fn einittoken_provider<P: Into<Box<dyn EinittokenProvider>>>(
356        mut self,
357        einittoken_provider: P,
358    ) -> Self {
359        self.inner.einittoken_provider(einittoken_provider.into());
360        self
361    }
362
363    pub fn build(self) -> Library {
364        Library {
365            inner: self.inner.build(),
366        }
367    }
368}