-
Notifications
You must be signed in to change notification settings - Fork 47
/
enclave_wrappers.rs
261 lines (219 loc) · 7.11 KB
/
enclave_wrappers.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
/*
Copyright 2019 Supercomputing Systems AG
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use std::str;
use std::fs;
use log::*;
use sgx_types::*;
use sgx_crypto_helper::rsa3072::{Rsa3072PubKey};
use constants::*;
use enclave_api::*;
use init_enclave::init_enclave;
use primitives::{ed25519};
use substrate_api_client::{Api, hexstr_to_u256};
use my_node_runtime::{UncheckedExtrinsic, Call, SubstraTEEProxyCall};
use parity_codec::{Decode, Encode};
use primitive_types::U256;
use wasm::SgxWasmAction;
use crypto::*;
// function to get the account nonce of a user
pub fn get_account_nonce(api: &substrate_api_client::Api, user: [u8; 32]) -> U256 {
info!("[>] Get account nonce");
let accountid = ed25519::Public::from_raw(user);
let result_str = api.get_storage("System", "AccountNonce", Some(accountid.encode())).unwrap();
let nonce = hexstr_to_u256(result_str);
info!("[<] Account nonce of {:?} is {}\n", accountid, nonce);
nonce
}
// decrypt and process the payload (in the enclave)
// then compose the extrinsic (in the enclave)
// and send an extrinsic back to the substraTEE-node
pub fn process_forwarded_payload(
eid: sgx_enclave_id_t,
ciphertext: Vec<u8>,
retval: &mut sgx_status_t,
port: &str) {
let mut api = Api::new(format!("ws://127.0.0.1:{}", port));
api.init();
let mut unchecked_extrinsic = UncheckedExtrinsic::new_unsigned(Call::SubstraTEEProxy(SubstraTEEProxyCall::confirm_call(vec![0; 32])));
// decrypt and process the payload. we will get an extrinsic back
let result = decryt_and_process_payload(eid, ciphertext, &mut unchecked_extrinsic, retval, port);
match result {
sgx_status_t::SGX_SUCCESS => {
let mut _xthex = hex::encode(unchecked_extrinsic.encode());
_xthex.insert_str(0, "0x");
// sending the extrinsic
println!();
println!("[+] Send the extrinsic");
let tx_hash = api.send_extrinsic(_xthex).unwrap();
println!("[+] Transaction got finalized. Hash: {:?}\n", tx_hash);
},
_ => {
println!();
error!("Payload not processed due to errors.");
}
}
}
pub fn decryt_and_process_payload(
eid: sgx_enclave_id_t,
mut ciphertext: Vec<u8>,
ue: &mut UncheckedExtrinsic,
retval: &mut sgx_status_t,
port: &str, ) -> sgx_status_t {
println!("[>] Decrypt and process the payload");
// initiate the api and get the genesis hash
let mut api = Api::new(format!("ws://127.0.0.1:{}", port));
api.init();
let genesis_hash = api.genesis_hash.unwrap().as_bytes().to_vec();
// get the public signing key of the TEE
let mut key = [0; 32];
let ecc_key = fs::read(ECC_PUB_KEY).expect("Unable to open ECC public key file");
key.copy_from_slice(&ecc_key[..]);
info!("[+] Got ECC public key of TEE = {:?}", key);
// get enclaves's account nonce
let nonce = get_account_nonce(&api, key);
let nonce_bytes = U256::encode(&nonce);
// read wasm file to string
let module = include_bytes!("../../bin/worker_enclave.compact.wasm").to_vec();
// calculate the SHA256 of the WASM
let wasm_hash = rsgx_sha256_slice(&module).unwrap();
let wasm_hash_str = serde_json::to_string(&wasm_hash).unwrap();
// prepare the request
let req = SgxWasmAction::Call {
module : Some(module),
function : "update_counter".to_string(),
};
debug!("Request for WASM = {:?}", req);
let req_str = serde_json::to_string(&req).unwrap();
// update the counter and compose the extrinsic
let unchecked_extrinsic_size = 137;
let mut unchecked_extrinsic : Vec<u8> = vec![0u8; unchecked_extrinsic_size as usize];
let result = unsafe {
call_counter_wasm(eid,
retval,
req_str.as_ptr() as * const u8,
req_str.len(),
ciphertext.as_mut_ptr(),
ciphertext.len() as u32,
genesis_hash.as_ptr(),
genesis_hash.len() as u32,
nonce_bytes.as_ptr(),
nonce_bytes.len() as u32,
wasm_hash_str.as_ptr(),
wasm_hash_str.len() as u32,
unchecked_extrinsic.as_mut_ptr(),
unchecked_extrinsic_size as u32
)
};
match result {
sgx_status_t::SGX_SUCCESS => debug!("[+] ECALL Enclave successful"),
_ => {
error!("[-] ECALL Enclave Failed {}!", result.as_str());
}
}
match retval {
sgx_status_t::SGX_SUCCESS => {
println!("[<] Message decoded and processed in the enclave");
*ue = UncheckedExtrinsic::decode(&mut unchecked_extrinsic.as_slice()).unwrap();
sgx_status_t::SGX_SUCCESS
},
_ => {
error!("[<] Error processing message in the enclave");
sgx_status_t::SGX_ERROR_UNEXPECTED
}
}
}
pub fn get_signing_key_tee() {
println!();
println!("*** Start the enclave");
let enclave = match init_enclave() {
Ok(r) => {
println!("[+] Init Enclave Successful. EID = {}!", r.geteid());
r
},
Err(x) => {
error!("[-] Init Enclave Failed {}!", x);
return;
},
};
// request the key
println!();
println!("*** Ask the signing key from the TEE");
let pubkey_size = 32;
let mut pubkey = [0u8; 32];
let mut retval = sgx_status_t::SGX_SUCCESS;
let result = unsafe {
get_ecc_signing_pubkey(enclave.geteid(),
&mut retval,
pubkey.as_mut_ptr(),
pubkey_size
)
};
match result {
sgx_status_t::SGX_SUCCESS => {},
_ => {
error!("[-] ECALL Enclave Failed {}!", result.as_str());
return;
}
}
println!("[+] Signing key: {:?}", pubkey);
println!();
println!("*** Write the ECC signing key to a file");
match fs::write(ECC_PUB_KEY, pubkey) {
Err(x) => { error!("[-] Failed to write '{}'. {}", ECC_PUB_KEY, x); },
_ => { println!("[+] File '{}' written successfully", ECC_PUB_KEY); }
}
}
pub fn get_public_key_tee()
{
println!();
println!("*** Start the enclave");
let enclave = match init_enclave() {
Ok(r) => {
println!("[+] Init Enclave Successful. EID = {}!", r.geteid());
r
},
Err(x) => {
error!("[-] Init Enclave Failed {}!", x);
return;
},
};
// request the key
println!();
println!("*** Ask the public key from the TEE");
let pubkey_size = 8192;
let mut pubkey = vec![0u8; pubkey_size as usize];
let mut retval = sgx_status_t::SGX_SUCCESS;
let result = unsafe {
get_rsa_encryption_pubkey(enclave.geteid(),
&mut retval,
pubkey.as_mut_ptr(),
pubkey_size
)
};
match result {
sgx_status_t::SGX_SUCCESS => {},
_ => {
error!("[-] ECALL Enclave Failed {}!", result.as_str());
return;
}
}
let rsa_pubkey: Rsa3072PubKey = serde_json::from_str(str::from_utf8(&pubkey[..]).unwrap()).unwrap();
println!("[+] {:?}", rsa_pubkey);
println!();
println!("*** Write the RSA3072 public key to a file");
let rsa_pubkey_json = serde_json::to_string(&rsa_pubkey).unwrap();
match fs::write(RSA_PUB_KEY, rsa_pubkey_json) {
Err(x) => { error!("[-] Failed to write '{}'. {}", RSA_PUB_KEY, x); },
_ => { println!("[+] File '{}' written successfully", RSA_PUB_KEY); }
}
}