-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathattestation.rs
executable file
·641 lines (536 loc) · 20.7 KB
/
attestation.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Baidu, Inc., nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use sgx_types::*;
use sgx_tse::*;
use sgx_tcrypto::*;
use sgx_rand::*;
use std::prelude::v1::*;
use std::sync::Arc;
use std::net::TcpStream;
use std::string::String;
use std::slice;
use std::ptr;
use std::str;
use std::io::{Write, Read};
use std::untrusted::fs;
use std::vec::Vec;
use itertools::Itertools;
use core::default::Default;
use runtime_primitives::generic::Era;
use primitive_types::U256;
use parity_codec::{Decode, Encode, Compact};
use utils::{hash_from_slice};
use utils::get_ecc_seed;
use my_node_runtime::{
UncheckedExtrinsic,
Call,
SubstraTEERegistryCall
};
use primitives::{ed25519};
use crypto::ed25519::{keypair, signature};
use utils::blake2_256;
use constants::{RA_SPID, RA_API_KEY};
//pub const PROD_HOSTNAME:&str = "as.sgx.trustedservices.intel.com";
pub const DEV_HOSTNAME : &str = "api.trustedservices.intel.com";
pub const SIGRL_SUFFIX : &str = "/sgx/dev/attestation/v3/sigrl/";
pub const REPORT_SUFFIX : &str = "/sgx/dev/attestation/v3/report";
extern "C" {
pub fn ocall_sgx_init_quote (
ret_val : *mut sgx_status_t,
ret_ti : *mut sgx_target_info_t,
ret_gid : *mut sgx_epid_group_id_t) -> sgx_status_t;
pub fn ocall_get_ias_socket (
ret_val : *mut sgx_status_t,
ret_fd : *mut i32) -> sgx_status_t;
pub fn ocall_get_quote (
ret_val : *mut sgx_status_t,
p_sigrl : *const u8,
sigrl_len : u32,
p_report : *const sgx_report_t,
quote_type : sgx_quote_sign_type_t,
p_spid : *const sgx_spid_t,
p_nonce : *const sgx_quote_nonce_t,
p_qe_report : *mut sgx_report_t,
p_quote : *mut u8,
maxlen : u32,
p_quote_len : *mut u32) -> sgx_status_t;
}
fn parse_response_attn_report(resp : &[u8]) -> (String, String, String){
debug!(" [Enclave] Entering parse_response_attn_report");
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut respp = httparse::Response::new(&mut headers);
let result = respp.parse(resp);
debug!(" [Enclave] respp.parse result {:?}", result);
let msg : &'static str;
match respp.code {
Some(200) => msg = "OK Operation Successful",
Some(401) => msg = "Unauthorized Failed to authenticate or authorize request.",
Some(404) => msg = "Not Found GID does not refer to a valid EPID group ID.",
Some(500) => msg = "Internal error occurred",
Some(503) => msg = "Service is currently not able to process the request (due to
a temporary overloading or maintenance). This is a
temporary state – the same request can be repeated after
some time. ",
_ => {error!("DBG:{}", respp.code.unwrap()); msg = "Unknown error occured"},
}
debug!(" [Enclave] msg = {}", msg);
let mut len_num : u32 = 0;
let mut sig = String::new();
let mut cert = String::new();
let mut attn_report = String::new();
for i in 0..respp.headers.len() {
let h = respp.headers[i];
//println!("{} : {}", h.name, str::from_utf8(h.value).unwrap());
match h.name{
"Content-Length" => {
let len_str = String::from_utf8(h.value.to_vec()).unwrap();
len_num = len_str.parse::<u32>().unwrap();
debug!(" [Enclave] Content length = {}", len_num);
}
"X-IASReport-Signature" => sig = str::from_utf8(h.value).unwrap().to_string(),
"X-IASReport-Signing-Certificate" => cert = str::from_utf8(h.value).unwrap().to_string(),
_ => (),
}
}
// Remove %0A from cert, and only obtain the signing cert
cert = cert.replace("%0A", "");
cert = ::cert::percent_decode(cert);
let v: Vec<&str> = cert.split("-----").collect();
let sig_cert = v[2].to_string();
if len_num != 0 {
let header_len = result.unwrap().unwrap();
let resp_body = &resp[header_len..];
attn_report = str::from_utf8(resp_body).unwrap().to_string();
debug!(" [Enclave] Attestation report = {}", attn_report);
}
// len_num == 0
(attn_report, sig, sig_cert)
}
fn parse_response_sigrl(resp : &[u8]) -> Vec<u8> {
debug!(" [Enclave] Entering parse_response_sigrl");
let mut headers = [httparse::EMPTY_HEADER; 16];
let mut respp = httparse::Response::new(&mut headers);
let result = respp.parse(resp);
debug!(" [Enclave] Parse result {:?}", result);
debug!(" [Enclave] Parse response {:?}", respp);
let msg : &'static str;
match respp.code {
Some(200) => msg = "OK Operation Successful",
Some(401) => msg = "Unauthorized Failed to authenticate or authorize request.",
Some(404) => msg = "Not Found GID does not refer to a valid EPID group ID.",
Some(500) => msg = "Internal error occurred",
Some(503) => msg = "Service is currently not able to process the request (due to
a temporary overloading or maintenance). This is a
temporary state – the same request can be repeated after
some time. ",
_ => msg = "Unknown error occured",
}
debug!(" [Enclave] msg = {}", msg);
let mut len_num : u32 = 0;
for i in 0..respp.headers.len() {
let h = respp.headers[i];
if h.name == "content-length" {
let len_str = String::from_utf8(h.value.to_vec()).unwrap();
len_num = len_str.parse::<u32>().unwrap();
debug!(" [Enclave] Content length = {}", len_num);
}
}
if len_num != 0 {
let header_len = result.unwrap().unwrap();
let resp_body = &resp[header_len..];
debug!(" [Enclave] Base64-encoded SigRL: {:?}", resp_body);
return base64::decode(str::from_utf8(resp_body).unwrap()).unwrap();
}
// len_num == 0
Vec::new()
}
pub fn make_ias_client_config() -> rustls::ClientConfig {
let mut config = rustls::ClientConfig::new();
config.root_store.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
config
}
pub fn get_sigrl_from_intel(fd : c_int, gid : u32) -> Vec<u8> {
debug!(" [Enclave] Entering get_sigrl_from_intel. fd = {:?}", fd);
let config = make_ias_client_config();
//let sigrl_arg = SigRLArg { group_id : gid };
//let sigrl_req = sigrl_arg.to_httpreq();
let ias_key = get_ias_api_key();
let req = format!("GET {}{:08x} HTTP/1.1\r\nHOST: {}\r\nOcp-Apim-Subscription-Key: {}\r\nConnection: Close\r\n\r\n",
SIGRL_SUFFIX,
gid,
DEV_HOSTNAME,
ias_key);
debug!(" [Enclave] request = {}", req);
let dns_name = webpki::DNSNameRef::try_from_ascii_str(DEV_HOSTNAME).unwrap();
let mut sess = rustls::ClientSession::new(&Arc::new(config), dns_name);
let mut sock = TcpStream::new(fd).unwrap();
let mut tls = rustls::Stream::new(&mut sess, &mut sock);
let _result = tls.write(req.as_bytes());
let mut plaintext = Vec::new();
debug!(" [Enclave] tls.write complete");
match tls.read_to_end(&mut plaintext) {
Ok(_) => (),
Err(e) => {
error!(" [Enclave] tls.read_to_end: {:?}", e);
}
}
debug!(" [Enclave] tls.read_to_end complete");
let resp_string = String::from_utf8(plaintext.clone()).unwrap();
debug!(" [Enclave] resp_string = {}", resp_string);
parse_response_sigrl(&plaintext)
}
// TODO: support pse
pub fn get_report_from_intel(fd : c_int, quote : Vec<u8>) -> (String, String, String) {
debug!(" [Enclave] Entering get_report_from_intel. fd = {:?}", fd);
let config = make_ias_client_config();
let encoded_quote = base64::encode("e[..]);
let encoded_json = format!("{{\"isvEnclaveQuote\":\"{}\"}}\r\n", encoded_quote);
let ias_key = get_ias_api_key();
let req = format!("POST {} HTTP/1.1\r\nHOST: {}\r\nOcp-Apim-Subscription-Key:{}\r\nContent-Length:{}\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{}",
REPORT_SUFFIX,
DEV_HOSTNAME,
ias_key,
encoded_json.len(),
encoded_json);
debug!(" [Enclave] Req = {}", req);
let dns_name = webpki::DNSNameRef::try_from_ascii_str(DEV_HOSTNAME).unwrap();
let mut sess = rustls::ClientSession::new(&Arc::new(config), dns_name);
let mut sock = TcpStream::new(fd).unwrap();
let mut tls = rustls::Stream::new(&mut sess, &mut sock);
let _result = tls.write(req.as_bytes());
let mut plaintext = Vec::new();
debug!(" [Enclave] tls.write complete");
tls.read_to_end(&mut plaintext).unwrap();
debug!(" [Enclave] tls.read_to_end complete");
let resp_string = String::from_utf8(plaintext.clone()).unwrap();
debug!(" [Enclave] resp_string = {}", resp_string);
let (attn_report, sig, cert) = parse_response_attn_report(&plaintext);
(attn_report, sig, cert)
}
fn as_u32_le(array: [u8; 4]) -> u32 {
u32::from(array[0]) +
(u32::from(array[1]) << 8) +
(u32::from(array[2]) << 16) +
(u32::from(array[3]) << 24)
}
#[allow(const_err)]
pub fn create_attestation_report(pub_k: &sgx_ec256_public_t, sign_type: sgx_quote_sign_type_t) -> Result<(String, String, String), sgx_status_t> {
// Workflow:
// (1) ocall to get the target_info structure (ti) and epid group id (eg)
// (1.5) get sigrl
// (2) call sgx_create_report with ti+data, produce an sgx_report_t
// (3) ocall to sgx_get_quote to generate (*mut sgx-quote_t, uint32_t)
// (1) get ti + eg
let mut ti : sgx_target_info_t = sgx_target_info_t::default();
let mut eg : sgx_epid_group_id_t = sgx_epid_group_id_t::default();
let mut rt : sgx_status_t = sgx_status_t::SGX_ERROR_UNEXPECTED;
let res = unsafe {
ocall_sgx_init_quote(&mut rt as *mut sgx_status_t,
&mut ti as *mut sgx_target_info_t,
&mut eg as *mut sgx_epid_group_id_t)
};
debug!(" [Enclave] EPID group id = {:?}", eg);
if res != sgx_status_t::SGX_SUCCESS {
return Err(res);
}
if rt != sgx_status_t::SGX_SUCCESS {
return Err(rt);
}
let eg_num = as_u32_le(eg);
// (1.5) get sigrl
let mut ias_sock : i32 = 0;
let res = unsafe {
ocall_get_ias_socket(&mut rt as *mut sgx_status_t,
&mut ias_sock as *mut i32)
};
if res != sgx_status_t::SGX_SUCCESS {
return Err(res);
}
if rt != sgx_status_t::SGX_SUCCESS {
return Err(rt);
}
info!(" [Enclave] ias_sock = {}", ias_sock);
// Now sigrl_vec is the revocation list, a vec<u8>
let sigrl_vec : Vec<u8> = get_sigrl_from_intel(ias_sock, eg_num);
// (2) Generate the report
// Fill ecc256 public key into report_data
/* Code von Baidu */
let mut report_data: sgx_report_data_t = sgx_report_data_t::default();
let mut pub_k_gx = pub_k.gx;
pub_k_gx.reverse();
let mut pub_k_gy = pub_k.gy;
pub_k_gy.reverse();
report_data.d[..32].clone_from_slice(&pub_k_gx);
report_data.d[32..].clone_from_slice(&pub_k_gy);
let rep = match rsgx_create_report(&ti, &report_data) {
Ok(r) =>{
debug!(" [Enclave] Report creation successful. mr_signer.m = {:?}", r.body.mr_signer.m);
Some(r)
},
Err(e) =>{
error!(" [Enclave] Report creation failed. {:?}", e);
None
},
};
/* Code von Alain
let mut report_data: sgx_report_data_t = sgx_report_data_t::default();
let mut pub_k_gx = pub_k.gx.clone();
pub_k_gx.reverse();
let mut pub_k_gy = pub_k.gy.clone();
pub_k_gy.reverse();
// report_data.d[..32].clone_from_slice(&pub_k_gx);
// report_data.d[32..].clone_from_slice(&pub_k_gy);
// TODO: block hash would guarantee that the quote is recent. add it as well
// report_data = hash{pub_k_gx||pub_k_gy||block_hash}
let mut context = [0;96];
let block_hash_slice = [0;32];
context[..32].clone_from_slice(&pub_k_gx);
context[32..64].clone_from_slice(&pub_k_gy);
context[64..].clone_from_slice(&block_hash_slice);
report_data.d.clone_from_slice(&rsgx_sha256_slice(&context[..]).unwrap());
let rep = match rsgx_create_report(&ti, &report_data) {
Ok(r) =>{
println!("Report creation => success {:?}", r.body.mr_signer.m);
Some(r)
},
Err(e) =>{
println!("Report creation => failed {:?}", e);
None
},
};
*/
let mut quote_nonce = sgx_quote_nonce_t { rand : [0;16] };
let mut os_rng = os::SgxRng::new().unwrap();
os_rng.fill_bytes(&mut quote_nonce.rand);
let mut qe_report = sgx_report_t::default();
const RET_QUOTE_BUF_LEN : u32 = 2048;
let mut return_quote_buf : [u8; RET_QUOTE_BUF_LEN as usize] = [0;RET_QUOTE_BUF_LEN as usize];
let mut quote_len : u32 = 0;
// (3) Generate the quote
// Args:
// 1. sigrl: ptr + len
// 2. report: ptr 432bytes
// 3. linkable: u32, unlinkable=0, linkable=1
// 4. spid: sgx_spid_t ptr 16bytes
// 5. sgx_quote_nonce_t ptr 16bytes
// 6. p_sig_rl + sigrl size ( same to sigrl)
// 7. [out]p_qe_report need further check
// 8. [out]p_quote
// 9. quote_size
let (p_sigrl, sigrl_len) =
if sigrl_vec.is_empty() {
(ptr::null(), 0)
} else {
(sigrl_vec.as_ptr(), sigrl_vec.len() as u32)
};
let p_report = (&rep.unwrap()) as * const sgx_report_t;
let quote_type = sign_type;
let spid : sgx_spid_t = load_spid(RA_SPID);
let p_spid = &spid as *const sgx_spid_t;
let p_nonce = "e_nonce as * const sgx_quote_nonce_t;
let p_qe_report = &mut qe_report as *mut sgx_report_t;
let p_quote = return_quote_buf.as_mut_ptr();
let maxlen = RET_QUOTE_BUF_LEN;
let p_quote_len = &mut quote_len as *mut u32;
let result = unsafe {
ocall_get_quote(&mut rt as *mut sgx_status_t,
p_sigrl,
sigrl_len,
p_report,
quote_type,
p_spid,
p_nonce,
p_qe_report,
p_quote,
maxlen,
p_quote_len)
};
if result != sgx_status_t::SGX_SUCCESS {
return Err(result);
}
if rt != sgx_status_t::SGX_SUCCESS {
error!(" [Enclave] ocall_get_quote failed. {}", rt);
return Err(rt);
}
// Added 09-28-2018
// Perform a check on qe_report to verify if the qe_report is valid
match rsgx_verify_report(&qe_report) {
Ok(()) => debug!(" [Enclave] rsgx_verify_report success!"),
Err(x) => {
error!(" [Enclave] rsgx_verify_report failed. {:?}", x);
return Err(x);
},
}
// Check if the qe_report is produced on the same platform
if ti.mr_enclave.m != qe_report.body.mr_enclave.m ||
ti.attributes.flags != qe_report.body.attributes.flags ||
ti.attributes.xfrm != qe_report.body.attributes.xfrm {
error!(" [Enclave] qe_report does not match current target_info!");
return Err(sgx_status_t::SGX_ERROR_UNEXPECTED);
}
debug!(" [Enclave] qe_report check success");
// Check qe_report to defend against replay attack
// The purpose of p_qe_report is for the ISV enclave to confirm the QUOTE
// it received is not modified by the untrusted SW stack, and not a replay.
// The implementation in QE is to generate a REPORT targeting the ISV
// enclave (target info from p_report) , with the lower 32Bytes in
// report.data = SHA256(p_nonce||p_quote). The ISV enclave can verify the
// p_qe_report and report.data to confirm the QUOTE has not be modified and
// is not a replay. It is optional.
let mut rhs_vec : Vec<u8> = quote_nonce.rand.to_vec();
rhs_vec.extend(&return_quote_buf[..quote_len as usize]);
let rhs_hash = rsgx_sha256_slice(&rhs_vec[..]).unwrap();
let lhs_hash = &qe_report.body.report_data.d[..32];
debug!(" [Enclave] rhs hash = {:02X}", rhs_hash.iter().format(""));
debug!(" [Enclave] lhs hash = {:02X}", lhs_hash.iter().format(""));
if rhs_hash != lhs_hash {
error!(" [Enclave] Quote is tampered!");
return Err(sgx_status_t::SGX_ERROR_UNEXPECTED);
}
let quote_vec : Vec<u8> = return_quote_buf[..quote_len as usize].to_vec();
let res = unsafe {
ocall_get_ias_socket(&mut rt as *mut sgx_status_t,
&mut ias_sock as *mut i32)
};
if res != sgx_status_t::SGX_SUCCESS {
return Err(res);
}
if rt != sgx_status_t::SGX_SUCCESS {
return Err(rt);
}
let (attn_report, sig, cert) = get_report_from_intel(ias_sock, quote_vec);
Ok((attn_report, sig, cert))
//TODO: return context as well
}
fn load_spid(filename: &str) -> sgx_spid_t {
let mut spidfile = fs::File::open(filename).expect("cannot open spid file");
let mut contents = String::new();
spidfile.read_to_string(&mut contents).expect("cannot read the spid file");
::hex::decode_spid(&contents)
}
fn get_ias_api_key() -> String {
let mut keyfile = fs::File::open(RA_API_KEY).expect("cannot open ias key file");
let mut key = String::new();
keyfile.read_to_string(&mut key).expect("cannot read the ias key file");
key.trim_end().to_owned()
}
pub fn create_ra_report_and_signature(sign_type: sgx_quote_sign_type_t) -> Result<(Vec<u8>, Vec<u8>), sgx_status_t> {
info!(" [Enclave] Generate keypair");
let ecc_handle = SgxEccHandle::new();
let _result = ecc_handle.open();
let (prv_k, pub_k) = ecc_handle.create_key_pair().unwrap();
info!(" [Enclave] Generate keypair successful");
info!(" [Enclave] Create attestation report");
let (attn_report, sig, cert) = match create_attestation_report(&pub_k, sign_type) {
Ok(r) => r,
Err(e) => {
error!(" [Enclave] Error in create_attestation_report: {:?}", e);
return Err(e);
}
};
println!(" [Enclave] Create attestation report successful");
debug!(" attn_report = {:?}", attn_report);
debug!(" sig = {:?}", sig);
debug!(" cert = {:?}", cert);
// concat the information
let payload = attn_report + "|" + &sig + "|" + &cert;
// generate an ECC certificate
info!(" [Enclave] Generate ECC Certificate");
let (key_der, cert_der) = match ::cert::gen_ecc_cert(payload, &prv_k, &pub_k, &ecc_handle) {
Ok(r) => r,
Err(e) => {
error!(" [Enclave] gen_ecc_cert failed: {:?}", e);
return Err(e);
}
};
let _result = ecc_handle.close();
info!(" [Enclave] Generate ECC Certificate successful");
Ok((key_der, cert_der))
}
#[no_mangle]
pub unsafe extern "C" fn perform_ra(
genesis_hash: * const u8,
genesis_hash_size: u32,
nonce: * const u8,
nonce_size: u32,
url: * const u8,
url_size: u32,
unchecked_extrinsic: * mut u8,
unchecked_extrinsic_size: u32
) -> sgx_status_t {
// initialize the logging environment in the enclave
env_logger::init();
// our certificate is unlinkable
let sign_type = sgx_quote_sign_type_t::SGX_UNLINKABLE_SIGNATURE;
let (_key_der, cert_der) = match create_ra_report_and_signature(sign_type) {
Ok(r) => r,
Err(e) => return e,
};
info!(" [Enclave] Compose extrinsic");
let genesis_hash_slice = slice::from_raw_parts(genesis_hash, genesis_hash_size as usize);
let mut nonce_slice = slice::from_raw_parts(nonce, nonce_size as usize);
let url_slice = slice::from_raw_parts(url, url_size as usize);
let extrinsic_slice = slice::from_raw_parts_mut(unchecked_extrinsic, unchecked_extrinsic_size as usize);
let seed = match get_ecc_seed() {
Ok(seed) => seed,
Err(status) => return status,
};
let nonce = U256::decode(&mut nonce_slice).unwrap();
let genesis_hash = hash_from_slice(genesis_hash_slice);
let era = Era::immortal();
let function = Call::SubstraTEERegistry(SubstraTEERegistryCall::register_enclave(cert_der.to_vec(), url_slice.to_vec()));
let index = nonce.low_u64();
let raw_payload = (Compact(index), function, era, genesis_hash);
let (privkey, pubkey) = keypair(&seed);
let sign = raw_payload.using_encoded(|payload| if payload.len() > 256 {
// include the blake2 hash of the payload
signature(&blake2_256(payload)[..], &privkey)
} else {
//println!("signing {}", HexDisplay::from(&payload));
signature(payload, &privkey)
});
// convert to valid signatures
let signerpub = ed25519::Public::from_raw(pubkey);
let signature = ed25519::Signature::from_raw(sign);
// build the extrinsic
let ex = UncheckedExtrinsic::new_signed(
index,
raw_payload.1,
signerpub.into(),
signature,
era,
);
let encoded = ex.encode();
debug!(" [Enclave] Encoded extrinsic = {:?}", encoded);
// split the extrinsic_slice at the length of the encoded extrinsic
// and fill the right side with whitespace
let (left, right) = extrinsic_slice.split_at_mut(encoded.len());
left.clone_from_slice(&encoded);
right.iter_mut().for_each(|x| *x = 0x20);
sgx_status_t::SGX_SUCCESS
}