Skip to content

Commit 86c2e1b

Browse files
committed
BLD: started implementing add_data (WIP)
1 parent b8fcdf5 commit 86c2e1b

File tree

6 files changed

+116
-30
lines changed

6 files changed

+116
-30
lines changed

enclave/safetrace/app/src/networking/ipc_listener.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,14 @@ pub(self) mod handling {
5757
use serde_json::Value;
5858

5959
extern {
60-
fn ecall_add_personal_data(eid: sgx_enclave_id_t, ret: *mut sgx_status_t,
61-
some_string: *const u8, len: usize) -> sgx_status_t;
60+
fn ecall_add_personal_data(
61+
eid: sgx_enclave_id_t,
62+
ret: *mut sgx_status_t,
63+
encryptedUserId: *const u8,
64+
encryptedUserId_len: usize,
65+
encryptedData: *const u8,
66+
encryptedData_len: usize,
67+
userPubKey: &[u8; 64]) -> sgx_status_t;
6268
}
6369

6470
type ResponseResult = Result<IpcResponse, Error>;
@@ -102,10 +108,20 @@ pub(self) mod handling {
102108
// TODO
103109
//#[logfn(DEBUG)]
104110
pub fn add_personal_data( input: IpcInput, eid: sgx_enclave_id_t) -> ResponseResult {
105-
let mut ret = sgx_status_t::SGX_SUCCESS;
106-
let data = serde_json::to_string(&input).unwrap();
107111

108-
unsafe { ecall_add_personal_data(eid, &mut ret as *mut sgx_status_t, data.as_ptr() as * const u8, data.len()) };
112+
let mut ret = sgx_status_t::SGX_SUCCESS;
113+
let encryptedUserId = input.encryptedUserId.from_hex()?;
114+
let encryptedData = input.encryptedData.from_hex()?;
115+
let mut userPubKey = [0u8; 64];
116+
userPubKey.clone_from_slice(&input.userPubKey.from_hex()?);
117+
118+
unsafe { ecall_add_personal_data(eid,
119+
&mut ret as *mut sgx_status_t,
120+
encryptedUserId.as_ptr() as * const u8,
121+
encryptedUserId.len(),
122+
encryptedData.as_ptr() as * const u8,
123+
encryptedData.len(),
124+
&userPubKey) };
109125

110126
let result = IpcResults::AddPersonalData { status: Status::Passed };
111127
Ok(IpcResponse::AddPersonalData { result })

enclave/safetrace/enclave/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ libsecp256k1 = { version = "0.2" }
2626
lazy_static = {version = "1.3.0", features = ["spin_no_std"] }
2727
tiny-keccak = { version = "1.4" }
2828
sha2 = { version = "0.8.0", default-features = false}
29+
ring = { git = "https://github.com/elichai/ring.git", rev = "sgx-manual", default-features = false }
30+
2931

3032
[patch.'https://github.com/apache/teaclave-sgx-sdk.git']
3133
sgx_alloc = { path = "../../incubator-teaclave-sgx-sdk/sgx_alloc" }

enclave/safetrace/enclave/Enclave.edl

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@ enclave {
2626
trusted {
2727
/* define ECALLs here. */
2828

29-
public sgx_status_t ecall_add_personal_data([in, size=len] const uint8_t* some_string, size_t len);
29+
public sgx_status_t ecall_add_personal_data(
30+
[in, size=encryptedUserId_len] const uint8_t* encryptedUserId,
31+
size_t encryptedUserId_len,
32+
[in, size=encryptedData_len] const uint8_t* encryptedData,
33+
size_t encryptedData_len,
34+
[in] uint8_t user_key[64]
35+
);
3036

3137
public sgx_status_t ecall_get_user_key(
3238
[out] uint8_t sig[65],

enclave/safetrace/enclave/src/data.rs

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1-
use sgx_types::*;
21
use serde::{Serialize, Deserialize};
3-
use std::{slice};
2+
// use std::{slice};
43
use std::string::String;
5-
//use std::vec::Vec;
4+
use errors_t::EnclaveError;
5+
use types::{PubKey, DhKey};
6+
67

78
// Structs
89
#[derive(Serialize, Deserialize, Clone, Debug)]
@@ -20,12 +21,29 @@ pub struct Request {
2021
userPubKey: String
2122
}
2223

23-
pub fn ecall_add_personal_data_internal(data_json: *const u8, some_len: usize) -> sgx_status_t {
24+
pub fn ecall_add_personal_data_internal(
25+
encryptedUserId: &[u8],
26+
encryptedData: &[u8],
27+
userPubKey: &PubKey,
28+
dhKey: &DhKey) -> Result<(), EnclaveError> {
29+
30+
31+
println!("Add personal data inside the enclave");
32+
33+
println!("{:?}", dhKey);
34+
println!("Received UserPub Key Again: {:?}", userPubKey.to_vec());
35+
36+
37+
// // let str_slice = unsafe { slice::from_raw_parts(data_json, some_len) };
38+
39+
// // Input sanitised in EngimaJS to object type
40+
// let mut request: Request = serde_json::from_slice(str_slice).unwrap();
41+
42+
// println!("EncryptedUserId: {:?}", request.encryptedUserId);
43+
44+
// let inputkey = request.userPubKey;
2445

25-
let str_slice = unsafe { slice::from_raw_parts(data_json, some_len) };
2646

27-
// Input sanitised in EngimaJS to object type
28-
let mut request: Request = serde_json::from_slice(str_slice).unwrap();
2947

3048
// Read from the state
3149
// let mut data = Self::get_data();
@@ -35,7 +53,7 @@ pub fn ecall_add_personal_data_internal(data_json: *const u8, some_len: usize)
3553
// write_state!(DATASET => data);
3654

3755
// Ocall to normal world for output
38-
println!("Received Data: {:?}", &request);
56+
//println!("Received Data: {:?}", &request);
3957

40-
sgx_status_t::SGX_SUCCESS
58+
Ok(())
4159
}

enclave/safetrace/enclave/src/keys_t.rs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
use crate::SIGNING_KEY;
2-
use types::{PubKey, DhKey};
2+
use types::{PubKey, DhKey, SymmetricKey};
33
use std::collections::HashMap;
44
use std::{sync::SgxMutex as Mutex, sync::SgxMutexGuard as MutexGuard, vec::Vec};
55
use serde::{Deserialize, Serialize};
66
use secp256k1::{PublicKey, SecretKey, SharedSecret};
77
use errors_t::{CryptoError, EnclaveError, ToolsError::MessagingError};
88
use hash::{Keccak256, prepare_hash_multiple};
99

10+
//use ring::aead::{self, Nonce, Aad};
11+
//use std::{borrow::ToOwned};
12+
1013

1114
#[derive(Debug)]
1215
pub struct KeyPair {
@@ -50,11 +53,11 @@ impl KeyPair {
5053
let pubkey = PublicKey::parse(&pubarr)
5154
.map_err(|e| CryptoError::KeyError { key_type: "Private Key", err: Some(e) })?;
5255

53-
// let shared = SharedSecret::new(&pubkey, &self.privkey)
54-
// .map_err(|_| CryptoError::DerivingKeyError { self_key: self.get_pubkey(), other_key: *_pubarr })?;
56+
let shared = SharedSecret::new(&pubkey, &self.privkey)
57+
.map_err(|_| CryptoError::DerivingKeyError { self_key: self.get_pubkey(), other_key: *_pubarr })?;
5558

5659
let mut result = [0u8; 32];
57-
//result.copy_from_slice(shared.as_ref());
60+
result.copy_from_slice(shared.as_ref());
5861
Ok(result)
5962
}
6063

@@ -161,6 +164,28 @@ impl UserMessage {
161164
// }
162165
}
163166

167+
168+
// const IV_SIZE: usize = 96/8;
169+
// static AES_MODE: &aead::Algorithm = &aead::AES_256_GCM;
170+
// type IV = [u8; IV_SIZE];
171+
172+
// pub fn decrypt(cipheriv: &[u8], key: &SymmetricKey) -> Result<Vec<u8>, CryptoError> {
173+
// if cipheriv.len() < IV_SIZE {
174+
// return Err(CryptoError::ImproperEncryption);
175+
// }
176+
// let aes_decrypt = aead::OpeningKey::new(&AES_MODE, key)
177+
// .map_err(|_| CryptoError::KeyError { key_type: "Decryption", err: None })?;
178+
179+
// let (ciphertext, iv) = cipheriv.split_at(cipheriv.len()-12);
180+
// let nonce = aead::Nonce::try_assume_unique_for_key(&iv).unwrap(); // This Cannot fail because split_at promises that iv.len()==12
181+
// let mut ciphertext = ciphertext.to_owned();
182+
// let decrypted_data = aead::open_in_place(&aes_decrypt, nonce, Aad::empty(), 0, &mut ciphertext);
183+
// let decrypted_data = decrypted_data.map_err(|_| CryptoError::DecryptionError)?;
184+
185+
// Ok(decrypted_data.to_vec())
186+
// }
187+
188+
164189
/// A trait that is basically a shortcut for `mutex.lock().expect(format!("{} mutex is posion", name))`
165190
/// you instead call `mutex.lock_expect(name)` and it will act the same.
166191
pub trait LockExpectMutex<T> {

enclave/safetrace/enclave/src/lib.rs

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,7 @@ extern crate lazy_static;
3636
// extern crate sgx_serialize_derive;
3737

3838
use sgx_types::*;
39-
use std::string::String;
40-
use std::vec::Vec;
41-
use std::io::{self, Write};
4239
use std::{slice};
43-
//use std::{path::PathBuf, str};
44-
4540

4641
extern crate serde;
4742
extern crate serde_json;
@@ -50,6 +45,7 @@ extern crate tiny_keccak;
5045
extern crate sha2;
5146
extern crate rustc_hex;
5247
extern crate arrayvec;
48+
//extern crate ring;
5349

5450
#[macro_use]
5551
mod macros;
@@ -61,11 +57,11 @@ mod types;
6157
mod hash;
6258
mod traits;
6359

64-
use keys_t::{ecall_get_user_key_internal, KeyPair};
60+
use keys_t::{ecall_get_user_key_internal, KeyPair, DH_KEYS, LockExpectMutex};
6561
use data::ecall_add_personal_data_internal;
6662
use storage::*;
67-
use types::EnclaveReturn;
68-
use errors_t::EnclaveError;
63+
use types::{PubKey, DhKey, EnclaveReturn};
64+
use errors_t::{EnclaveError, CryptoError};
6965
use traits::SliceCPtr;
7066

7167
lazy_static! {
@@ -114,8 +110,31 @@ pub unsafe extern "C" fn ecall_get_user_key(sig: &mut [u8; 65], user_pubkey: &[u
114110
EnclaveReturn::Success
115111
}
116112

113+
fn get_io_key(user_key: &PubKey) -> Result<DhKey, EnclaveError> {
114+
let io_key = DH_KEYS
115+
.lock_expect("User DH Key")
116+
.remove(&user_key[..])
117+
.ok_or(CryptoError::MissingKeyError { key_type: "DH Key" })?;
118+
Ok(io_key)
119+
}
120+
117121
#[no_mangle]
118-
pub extern "C" fn ecall_add_personal_data(data_string: *const u8, data_len: usize) -> sgx_status_t {
119-
ecall_add_personal_data_internal(data_string, data_len);
120-
sgx_status_t::SGX_SUCCESS
122+
pub unsafe extern "C" fn ecall_add_personal_data(
123+
encryptedUserId: *const u8,
124+
encryptedUserId_len: usize,
125+
encryptedData: *const u8,
126+
encryptedData_len: usize,
127+
userPubKey: &[u8; 64]) -> EnclaveReturn {
128+
129+
let encryptedUserId = slice::from_raw_parts(encryptedUserId, encryptedUserId_len);
130+
let encryptedData = slice::from_raw_parts(encryptedData, encryptedData_len);
131+
132+
let io_key;
133+
match get_io_key(userPubKey) {
134+
Ok(v) => io_key = v,
135+
Err(e) => return e.into(),
136+
}
137+
138+
let result = ecall_add_personal_data_internal(encryptedUserId, encryptedData, userPubKey, &io_key);
139+
EnclaveReturn::Success
121140
}

0 commit comments

Comments
 (0)