1use std::io::{Read, Result as IoResult, Write};
8
9use time::OffsetDateTime;
10use time::macros::format_description;
11
12use abi::{SIGSTRUCT_HEADER1, SIGSTRUCT_HEADER2};
13pub use abi::{Attributes, AttributesFlags, Miscselect, Sigstruct};
14use crypto::{Hash, SgxHashOps, SgxRsaOps, SgxRsaPubOps};
15use sgxs::{copy_measured, SgxsRead};
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub struct EnclaveHash {
19 hash: Hash,
20}
21
22impl EnclaveHash {
23 pub fn new(hash: Hash) -> Self {
24 EnclaveHash { hash }
25 }
26
27 pub fn hash(&self) -> Hash {
28 self.hash
29 }
30
31 pub fn from_stream<R: SgxsRead, H: SgxHashOps>(stream: &mut R) -> Result<Self, anyhow::Error> {
32 struct WriteToHasher<H> {
33 hasher: H,
34 }
35
36 impl<H: SgxHashOps> Write for WriteToHasher<H> {
37 fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
38 self.hasher.update(buf);
39 Ok(buf.len())
40 }
41
42 fn flush(&mut self) -> IoResult<()> {
43 Ok(())
44 }
45 }
46
47 let mut out = WriteToHasher { hasher: H::new() };
48 copy_measured(stream, &mut out)?;
49 Ok(Self::new(out.hasher.finish()))
50 }
51}
52
53pub fn verify<K: SgxRsaOps, H: SgxHashOps>(sig: &Sigstruct, key: &K) -> Result<(), K::Error> {
57 Signer::check_key(key);
58 key.verify_sha256_pkcs1v1_5(&sig.signature[..], Signer::sighash::<H>(sig))
59}
60
61#[derive(Clone, Debug)]
62pub struct Signer {
63 date: u32,
64 swdefined: u32,
65 miscselect: Miscselect,
66 miscmask: u32,
67 attributes: Attributes,
68 attributemask: [u64; 2],
69 isvextprodid: [u8; 16],
70 isvprodid: u16,
71 isvsvn: u16,
72 enclavehash: EnclaveHash,
73}
74
75impl Signer {
76 pub fn new(enclavehash: EnclaveHash) -> Signer {
79 let format = format_description!("[Year][month][day]");
80 let now = OffsetDateTime::now_utc()
82 .format(&format)
83 .unwrap()
84 .to_string();
85
86 Signer {
87 date: u32::from_str_radix(&now, 16).unwrap(),
88 swdefined: 0,
89 miscselect: Miscselect::default(),
90 miscmask: !0,
91 attributes: Attributes {
92 flags: abi::AttributesFlags::MODE64BIT,
93 xfrm: 0x3,
94 },
95 attributemask: [!abi::AttributesFlags::DEBUG.bits(), !0x3],
96 isvextprodid: [0; 16],
97 isvprodid: 0,
98 isvsvn: 0,
99 enclavehash,
100 }
101 }
102
103 fn check_key<K: SgxRsaOps>(key: &K) {
104 if key.len() != 3072 {
105 panic!("Key size is not 3072 bits");
106 }
107 if key.e() != [3] {
108 panic!("Key public exponent is not 3");
109 }
110 }
111
112 fn sighash<H: SgxHashOps>(sig: &Sigstruct) -> Hash {
113 let mut hasher = H::new();
114 let data = sig.signature_data();
115 hasher.update(data.0);
116 hasher.update(data.1);
117 hasher.finish()
118 }
119
120 pub fn unsigned_hash<H: SgxHashOps>(&self) -> Hash {
121 let sig = Self::unsigned_sig(self);
122
123 Self::sighash::<H>(&sig)
124 }
125
126 pub fn unsigned_sig(&self) -> Sigstruct {
127 let sig = Sigstruct {
128 header: SIGSTRUCT_HEADER1,
129 vendor: 0,
130 date: self.date,
131 header2: SIGSTRUCT_HEADER2,
132 swdefined: self.swdefined,
133 _reserved1: [0; 84],
134 modulus: [0; 384],
135 exponent: 3,
136 signature: [0; 384],
137 miscselect: self.miscselect,
138 miscmask: self.miscmask,
139 cet_attributes: 0,
140 cet_attributes_mask: 0,
141 _reserved2: 0,
142 isvfamilyid: [0; 16],
143 attributes: self.attributes,
144 attributemask: self.attributemask,
145 enclavehash: self.enclavehash.hash,
146 _reserved3: [0; 16],
147 isvextprodid: self.isvextprodid,
148 isvprodid: self.isvprodid,
149 isvsvn: self.isvsvn,
150 _reserved4: [0; 12],
151 q1: [0; 384],
152 q2: [0; 384],
153 };
154
155 sig
156 }
157
158 pub fn sign<K: SgxRsaOps, H: SgxHashOps>(self, key: &K) -> Result<Sigstruct, K::Error> {
162 Self::check_key(key);
163
164 let mut sig = Self::unsigned_sig(&self);
165
166 let (s, q1, q2) = key.sign_sha256_pkcs1v1_5_with_q1_q2(Self::sighash::<H>(&sig))?;
167 let n = key.n();
168
169 (&mut sig.modulus[..]).write_all(&n).unwrap();
171 (&mut sig.signature[..]).write_all(&s).unwrap();
172 (&mut sig.q1[..]).write_all(&q1).unwrap();
173 (&mut sig.q2[..]).write_all(&q2).unwrap();
174
175 Ok(sig)
176 }
177
178 pub fn cat_sign<K: SgxRsaPubOps + SgxRsaOps>(
181 &self,
182 key: &K,
183 mut s_vec: Vec<u8>,
184 ) -> Result<Sigstruct, <K as SgxRsaPubOps>::Error> {
185 Self::check_key(key);
186
187 let mut sig = Self::unsigned_sig(&self);
188 let (q1, q2) = key.calculate_q1_q2(&s_vec)?;
189
190 s_vec.reverse();
193
194 let n = key.n();
195
196 (&mut sig.modulus[..]).write_all(&n).unwrap();
197 (&mut sig.signature[..]).write_all(&s_vec).unwrap();
198 (&mut sig.q1[..]).write_all(&q1).unwrap();
199 (&mut sig.q2[..]).write_all(&q2).unwrap();
200
201 Ok(sig)
202 }
203
204 pub fn date(&mut self, year: u16, month: u8, day: u8) -> &mut Self {
205 self.date = u32::from_str_radix(&format!("{:04}{:02}{:02}", year, month, day), 16).unwrap();
207 self
208 }
209
210 pub fn swdefined(&mut self, swdefined: u32) -> &mut Self {
211 self.swdefined = swdefined;
212 self
213 }
214
215 pub fn isvextprodid(&mut self, isvextprodid: [u8; 16]) -> &mut Self {
216 self.isvextprodid = isvextprodid;
217 self
218 }
219
220 pub fn isvprodid(&mut self, isvprodid: u16) -> &mut Self {
221 self.isvprodid = isvprodid;
222 self
223 }
224
225 pub fn isvsvn(&mut self, isvsvn: u16) -> &mut Self {
226 self.isvsvn = isvsvn;
227 self
228 }
229
230 pub fn miscselect(&mut self, miscselect: Miscselect, mask: u32) -> &mut Self {
231 self.miscselect = miscselect;
232 self.miscmask = mask;
233 self
234 }
235
236 pub fn attributes_flags(&mut self, flags: AttributesFlags, mask: u64) -> &mut Self {
237 self.attributes.flags = flags;
238 self.attributemask[0] = mask;
239 self
240 }
241
242 pub fn attributes_xfrm(&mut self, xfrm: u64, mask: u64) -> &mut Self {
243 self.attributes.xfrm = xfrm;
244 self.attributemask[1] = mask;
245 self
246 }
247
248 pub fn enclavehash(&mut self, hash: EnclaveHash) -> &mut Self {
249 self.enclavehash = hash;
250 self
251 }
252}
253
254pub fn read<R: Read>(reader: &mut R) -> IoResult<Sigstruct> {
255 let mut buf = [0u8; 1808];
256 reader.read_exact(&mut buf)?;
257 Sigstruct::try_copy_from(&buf).ok_or_else(|| unreachable!())
258}
259
260#[cfg(test)]
261mod tests {
262 use super::{EnclaveHash, Signer};
263
264 #[test]
265 fn signer() {
266 let signer = Signer::new(EnclaveHash::new([0; 32]));
267 assert!(signer.date & 0xff <= 0x31); assert!(signer.date & 0xff00 <= 0x1200); assert!(signer.date & 0xffff0000 >= 0x20240000); assert!(signer.date & 0xffff0000 <= 0x20500000);
271 }
272}