Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] allow compiling and basic crypto without SGX(eg Android) #418

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions sgx_crypto_helper/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,25 @@ crate-type = ["staticlib","rlib"]

[features]
default = ["ucrypto_help"]
rsa2048 = []
crypto = []
ucrypto_help = [
"sgx_ucrypto",
# "sgx_ucrypto",
"libc",
"serde",
"serde_derive",
"serde-big-array"]
mesalock_sgx = [
"sgx_tcrypto",
# "sgx_tcrypto",
"sgx_tstd",
"serde-sgx",
"serde_derive-sgx",
"serde-big-array-sgx"]
# impl encrypt_buffer/etc WIHOUT using sgx_ucrypto nor sgx_tcrypto
crypto_direct = ["rsa", "sha2", "rand", "num-bigint"]

[dependencies]
sgx_ucrypto = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
# sgx_ucrypto = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
libc = { version = "0.2", optional = true }
itertools = { version = "*", default-features = false }
serde = { version = "1.0.104", optional = true }
Expand All @@ -37,9 +41,21 @@ serde-big-array = { version = "0.1", optional = true }
serde-sgx = { git = "https://github.com/mesalock-linux/serde-sgx", package = 'serde', optional = true }
serde_derive-sgx = { git = "https://github.com/mesalock-linux/serde-sgx", package = 'serde_derive', optional = true }
serde-big-array-sgx = { git = "https://github.com/mesalock-linux/serde-big-array-sgx", package = 'serde-big-array', optional = true }
rsa = { optional = true, version = "0.8", default-features = false }
sha2 = { optional = true, version = "0.10", default-features = false }
rand = { optional = true, version = "0.8" }
# SOME deps of our main libs(=imageproc) use "num v0.4.0" so we must default to an old version
# = note: struct `num_bigint::BigUint` and struct `rsa::BigUint` have similar names, but are actually distinct types
# note: struct `num_bigint::BigUint` is defined in crate `num_bigint`
# --> /home/xxx/.cargo/registry/src/github.com-1ecc6299db9ec823/num-bigint-0.4.3/src/biguint.rs:38:1
# 38 | pub struct BigUint {
# | ^^^^^^^^^^^^^^^^^^
# note: struct `rsa::BigUint` is defined in crate `num_bigint_dig`
# --> /home/xxx/.cargo/registry/src/github.com-1ecc6299db9ec823/num-bigint-dig-0.8.2/src/biguint.rs:94:1
num-bigint = { optional = true, version = "0.8", default-features = false, package = "num-bigint-dig" }

[target.'cfg(not(target_env = "sgx"))'.dependencies]
sgx_tcrypto = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
# sgx_tcrypto = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
sgx_tstd = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git", optional = true }
sgx_types = { rev = "v1.1.3", git = "https://github.com/apache/teaclave-sgx-sdk.git" }

Expand Down
142 changes: 142 additions & 0 deletions sgx_crypto_helper/src/crypto_direct.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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..

/// cf /teaclave-sgx-sdk/sgx_tcrypto/src/crypto.rs

///
/// Cryptographic Functions
///
use core::cell::{Cell, RefCell};
use core::mem;
use core::ops::{DerefMut, Drop};
use core::ptr;
use num_bigint::BigUint;
use rsa::{Oaep, PaddingScheme, PublicKey, RsaPrivateKey, RsaPublicKey};
use sgx_types::marker::ContiguousMemory;
use sgx_types::*;

pub struct SgxRsaPubKey {
key: RsaPublicKey,
}

impl SgxRsaPubKey {
/// Normally it calls: "sgx_create_rsa_pub1_key"
/// sgx_create_rsa_pub1_key generates a public key of the desired RSA
/// cryptographic with the input RSA key components.
/// Syntax
/// sgx_status_t sgx_create_rsa_priv2_key(
/// int mod_size,
/// int exp_size,
/// const unsigned char *le_n,
/// const unsigned char *le_e,
/// void **new_pub_key1
/// );
/// Parameters
/// mod_size [in]
/// Size in bytes of the RSA key modulus.
/// exp_size [in]
/// Size in bytes of the RSA public exponent.
/// le_n [in]
/// Pointer to the RSA modulus buffer.
/// le_e [in]
/// Pointer to the RSA public exponent buffer.
/// new_pub_key1 [out]
/// Pointer to the generated RSA public key.
/// Return value
/// SGX_SUCCESS
/// The RSA public key is successfully generated.
/// SGX_ERROR_INVALID_PARAMETER
/// Some of the pointers is NULL, or the input size is less than 0.
/// SGX_ERROR_UNEXPECTED
/// Unexpected error occurs during generating the RSA public key.
pub fn new(mod_size: i32, exp_size: i32, n: &[u8], e: &[u8]) -> SgxRsaPubKey {
assert!(
mod_size as usize == n.len(),
"SgxRsaPubKey::new: wrong modulus length??"
);
assert!(
exp_size as usize == e.len(),
"SgxRsaPubKey::new: wrong exponent length??"
);
SgxRsaPubKey {
// TODO when to choose from_bytes_be? platform? feature? never?
// [interstellar] DO NOT change without testing! This would completely break `integritee-cli`!
key: RsaPublicKey::new(BigUint::from_bytes_le(n), BigUint::from_bytes_le(e))
.map_err(|err| sgx_status_t::SGX_ERROR_INVALID_PARAMETER)
.unwrap(),
}
}

/// Normally it calls: "sgx_rsa_pub_encrypt_sha256"
/// sgx_rsa_pub_encrypt_sha256 performs RSA-OAEP encryption oper-
/// ation, with SHA-256 algorithm
/// sgx_status_t sgx_rsa_pub_encrypt_sha256(
/// void* rsa_key,
/// unsigned char* pout_data,
/// size_t* pout_len,
/// const unsigned char* pin_data,
/// const size_t pin_len
/// );
/// rsa_key [in]
/// Pointer to the RSA public key.
/// pout_data [out]
/// Pointer to the output cipher text buffer.
/// pout_len [out]
/// Length of the output cipher text buffer.
/// pin_data [in]
/// Pointer to the input data buffer.
/// pin_len [in]
/// Length of the input data buffer.
/// Return value
/// SGX_SUCCESS
/// All the outputs are generated successfully.
/// SGX_ERROR_INVALID_PARAMETER
/// Some of the pointers is NULL, or the input data size is 0.
/// SGX_ERROR_UNEXPECTED
/// Unexpected error occurs during performing encryption operation.
pub fn encrypt_sha256(
&self,
out_data: &mut [u8],
out_len: &mut usize,
in_data: &[u8],
) -> SgxError {
let mut rng = rand::thread_rng();
let padding = Oaep::new::<sha2::Sha256>();
let enc_data = self
.key
.encrypt(&mut rng, padding, in_data)
.map_err(|err| sgx_status_t::SGX_ERROR_UNEXPECTED)?;

*out_len = enc_data.len();
out_data.copy_from_slice(&enc_data);

Ok(())
}
}

// impl Default for SgxRsaPubKey {
// fn default() -> Self {
// Self::new()
// }
// }

pub struct SgxRsaPrivKey {
key: RefCell<sgx_rsa_key_t>,
mod_size: Cell<i32>,
exp_size: Cell<i32>,
createflag: Cell<bool>,
}
36 changes: 25 additions & 11 deletions sgx_crypto_helper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(clippy::too_many_arguments)]

#![cfg_attr(all(feature = "mesalock_sgx", not(target_env = "sgx")), no_std)]
#![cfg_attr(target_env = "sgx", feature(rustc_private))]
#![cfg_attr(test, feature(test))]
Expand All @@ -39,43 +38,57 @@
#[macro_use]
extern crate sgx_tstd as std;

extern crate sgx_types;
#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
extern crate sgx_tcrypto as crypto;
#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
extern crate sgx_types;
#[cfg(all(
feature = "crypto",
not(any(feature = "mesalock_sgx", target_env = "sgx"))
))]
extern crate sgx_ucrypto as crypto;

use std::prelude::v1::*;
use sgx_types::SgxResult;
#[cfg(feature = "crypto_direct")]
mod crypto_direct;

#[cfg(any(feature = "crypto"))]
use crypto::SgxRsaPrivKey;
#[cfg(any(feature = "crypto"))]
use crypto::SgxRsaPubKey;
use sgx_types::SgxResult;
use std::prelude::v1::*;

/// A trait to express the ability to create a RSA keypair with default e
/// (65537) or customized e, and to_privkey/to_pubkey, encryption/decryption API.
pub trait RsaKeyPair {
/// Create a new RSA keypair with default e = 65537.
fn new() -> SgxResult<Self> where Self: std::marker::Sized;
fn new() -> SgxResult<Self>
where
Self: std::marker::Sized;
/// Create a new RSA keypair with customized e
fn new_with_e(e: u32) -> SgxResult<Self> where Self: std::marker::Sized;
fn new_with_e(e: u32) -> SgxResult<Self>
where
Self: std::marker::Sized;
/// Get a private key instance typed `SgxRsaPrivKey` which is defined in sgx_tcrypto/sgx_ucrypto.
#[cfg(any(feature = "crypto"))]
fn to_privkey(self) -> SgxResult<SgxRsaPrivKey>;
/// get a public key instance typed `SgxPubPrivKey` which is defined in sgx_tcrypto/sgx_ucrypto.
#[cfg(any(feature = "crypto"))]
fn to_pubkey(self) -> SgxResult<SgxRsaPubKey>;
/// Encrypt a u8 slice to a Vec<u8>. Returns the length of ciphertext if OK.
fn encrypt_buffer(self, plaintext: &[u8], ciphertext: &mut Vec<u8>) -> SgxResult<usize>;
/// Decrypt a u8 slice to a Vec<u8>. Returns the length of plaintext if OK.
fn decrypt_buffer(self, ciphertext: &[u8], plaintext: &mut Vec<u8>) -> SgxResult<usize>;
}

#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
extern crate serde_sgx;
#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
extern crate serde;

#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
extern crate serde_derive_sgx as serde_derive;
extern crate serde_sgx;

#[cfg(not(any(feature = "mesalock_sgx", target_env = "sgx")))]
extern crate serde_derive;
#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
extern crate serde_derive_sgx as serde_derive;

#[cfg(any(feature = "mesalock_sgx", target_env = "sgx"))]
#[macro_use]
Expand All @@ -84,5 +97,6 @@ extern crate serde_big_array_sgx as serde_big_array;
#[macro_use]
extern crate serde_big_array;

#[cfg(feature = "rsa2048")]
pub mod rsa2048;
pub mod rsa3072;
Loading