Unverified Commit 0f995bb1 authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #183 from skalenetwork/develop

Create stable branch
parents bc336404 a10c7a05
...@@ -22,47 +22,47 @@ ...@@ -22,47 +22,47 @@
*/ */
#include <memory> #include <memory>
#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" #include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp"
#include "leveldb/db.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
#include "third_party/intel/create_enclave.h"
#include "bls.h" #include "bls.h"
#include <bls/BLSutils.h> #include <bls/BLSutils.h>
#include "leveldb/db.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
#include "BLSPrivateKeyShareSGX.h" #include "BLSPrivateKeyShareSGX.h"
#include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h"
#include "secure_enclave_u.h"
#include "third_party/intel/sgx_detect.h"
#include <gmp.h>
#include <sgx_urts.h>
#include "sgxwallet_common.h"
#include "sgxwallet.h" #include "sgxwallet.h"
#include "SGXException.h"
#include "third_party/spdlog/spdlog.h"
#include "common.h"
#include "SGXWalletServer.h" #include "SGXWalletServer.h"
#include "BLSCrypto.h" #include "SEKManager.h"
#include "LevelDB.h"
#include "ServerInit.h" #include "ServerInit.h"
#include "BLSCrypto.h"
#include "SGXException.h"
#include "third_party/spdlog/spdlog.h" string *FqToString(libff::alt_bn128_Fq *_fq) {
#include "common.h"
CHECK_STATE(_fq);
std::string *FqToString(libff::alt_bn128_Fq *_fq) {
mpz_t t; mpz_t t;
mpz_init(t); mpz_init(t);
_fq->as_bigint().to_mpz(t); _fq->as_bigint().to_mpz(t);
char arr[mpz_sizeinbase(t, 10) + 2]; SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2);
mpz_get_str(arr, 10, t); mpz_get_str(arr, 10, t);
mpz_clear(t); mpz_clear(t);
return new std::string(arr); return new string(arr);
} }
int char2int(char _input) { int char2int(char _input) {
...@@ -75,11 +75,18 @@ int char2int(char _input) { ...@@ -75,11 +75,18 @@ int char2int(char _input) {
return -1; return -1;
} }
void carray2Hex(const unsigned char *d, int _len, char *_hexArray) { void carray2Hex(const unsigned char *d, uint64_t _len, char *_hexArray,
uint64_t _hexArrayLen) {
CHECK_STATE(d);
CHECK_STATE(_hexArray);
char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (int j = 0; j < _len; j++) { CHECK_STATE(_hexArrayLen > 2 * _len);
for (uint64_t j = 0; j < _len; j++) {
_hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)]; _hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)];
_hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F]; _hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F];
} }
...@@ -87,38 +94,29 @@ void carray2Hex(const unsigned char *d, int _len, char *_hexArray) { ...@@ -87,38 +94,29 @@ void carray2Hex(const unsigned char *d, int _len, char *_hexArray) {
_hexArray[_len * 2] = 0; _hexArray[_len * 2] = 0;
} }
bool hex2carray(const char *_hex, uint64_t *_bin_len, uint8_t *_bin) {
int len = strnlen(_hex, 2 * BUF_LEN);
if (len == 0 && len % 2 == 1) bool hex2carray(const char *_hex, uint64_t *_bin_len,
return false; uint8_t *_bin, uint64_t _max_length) {
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) { CHECK_STATE(_hex);
int high = char2int((char) _hex[i * 2]); CHECK_STATE(_bin);
int low = char2int((char) _hex[i * 2 + 1]); CHECK_STATE(_bin_len)
if (high < 0 || low < 0) {
return false;
}
_bin[i] = (unsigned char) (high * 16 + low); uint64_t len = strnlen(_hex, 2 * _max_length + 1);
}
return true; CHECK_STATE(len != 2 * _max_length + 1);
}
CHECK_STATE(len <= 2 * _max_length);
bool hex2carray2(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin, const int _max_length) {
int len = strnlen(_hex, _max_length);
if (len == 0 && len % 2 == 1) if (len == 0 && len % 2 == 1)
return false; return false;
*_bin_len = len / 2; *_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) { for (uint64_t i = 0; i < len / 2; i++) {
int high = char2int((char) _hex[i * 2]); int high = char2int((char) _hex[i * 2]);
int low = char2int((char) _hex[i * 2 + 1]); int low = char2int((char) _hex[i * 2 + 1]);
...@@ -134,13 +132,20 @@ bool hex2carray2(const char *_hex, uint64_t *_bin_len, ...@@ -134,13 +132,20 @@ bool hex2carray2(const char *_hex, uint64_t *_bin_len,
bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex, bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) { char *_sig) {
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto keyStr = make_shared<string>(_encryptedKeyHex); auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared<array<uint8_t, 32>>(); auto hash = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())) { if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
...@@ -156,43 +161,39 @@ bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t ...@@ -156,43 +161,39 @@ bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t
} }
bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) { bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) {
auto hash = make_shared<array<uint8_t, 32>>();
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto hash = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())) { if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
shared_ptr<signatures::Bls> obj; shared_ptr <signatures::Bls> obj;
obj = make_shared<signatures::Bls>(signatures::Bls(_t, _n)); obj = make_shared<signatures::Bls>(signatures::Bls(_t, _n));
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint = obj->HashtoG1withHint(hash); pair <libff::alt_bn128_G1, string> hash_with_hint = obj->HashtoG1withHint(hash);
string *xStr = FqToString(&(hash_with_hint.first.X)); string *xStr = FqToString(&(hash_with_hint.first.X));
if (xStr == nullptr) { CHECK_STATE(xStr);
std::cerr << "Null xStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
string *yStr = FqToString(&(hash_with_hint.first.Y)); string *yStr = FqToString(&(hash_with_hint.first.Y));
if (yStr == nullptr) { if (yStr == nullptr) {
std::cerr << "Null yStr" << std::endl;
delete xStr; delete xStr;
BOOST_THROW_EXCEPTION(runtime_error("Null yStr")); BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
} }
char errMsg[BUF_LEN]; vector<char> errMsg(BUF_LEN, 0);
memset(errMsg, 0, BUF_LEN);
char xStrArg[BUF_LEN]; SAFE_CHAR_BUF(xStrArg, BUF_LEN);SAFE_CHAR_BUF(yStrArg, BUF_LEN);SAFE_CHAR_BUF(signature, BUF_LEN);
char yStrArg[BUF_LEN];
char signature[BUF_LEN];
memset(xStrArg, 0, BUF_LEN);
memset(yStrArg, 0, BUF_LEN);
strncpy(xStrArg, xStr->c_str(), BUF_LEN); strncpy(xStrArg, xStr->c_str(), BUF_LEN);
strncpy(yStrArg, yStr->c_str(), BUF_LEN); strncpy(yStrArg, yStr->c_str(), BUF_LEN);
...@@ -202,34 +203,30 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -202,34 +203,30 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
size_t sz = 0; size_t sz = 0;
uint8_t encryptedKey[BUF_LEN]; SAFE_UINT8_BUF(encryptedKey, BUF_LEN);
bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey); bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey, BUF_LEN);
if (!result) { if (!result) {
cerr << "Invalid hex encrypted key" << endl; BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key"));
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
} }
int errStatus = 0; int errStatus = 0;
sgx_status_t status =
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey, sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
sz, xStrArg, yStrArg, signature); sz, xStrArg, yStrArg, signature);
RESTART_END
if (status != SGX_SUCCESS) {
cerr << "SGX enclave call to trustedBlsSignMessage failed with status:" << status << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to trustedBlsSignMessage failed"));
}
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
cerr << "SGX enclave call to trustedBlsSignMessage failed with errStatus:" << errStatus << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to trustedBlsSignMessage failed"));
}
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + hash_with_hint.second; string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + hash_with_hint.second;
std::string sig = signature; string sig = signature;
sig.append(":"); sig.append(":");
sig.append(hint); sig.append(hint);
...@@ -240,36 +237,37 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -240,36 +237,37 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
} }
bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) { bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) {
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _sig); return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _sig);
} }
std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) { string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {
auto keyArray = make_shared<vector<char>>(BUF_LEN, 0); CHECK_STATE(errStatus);
auto encryptedKey = make_shared<vector<uint8_t>>(BUF_LEN, 0); CHECK_STATE(err_string);
auto errMsg = make_shared<vector<char>>(BUF_LEN, 0); CHECK_STATE(_key);
auto keyArray = make_shared < vector < char >> (BUF_LEN, 0);
auto encryptedKey = make_shared < vector < uint8_t >> (BUF_LEN, 0);
strncpy(keyArray->data(), _key, BUF_LEN); vector<char> errMsg(BUF_LEN, 0);
*errStatus = -1;
unsigned int encryptedLen = 0; strncpy(keyArray->data(), _key, BUF_LEN);
*errStatus = 0;
status = trustedEncryptKeyAES(eid, errStatus, errMsg->data(), keyArray->data(), encryptedKey->data(), &encryptedLen); uint64_t encryptedLen = 0;
spdlog::debug("errStatus is {}", *errStatus); sgx_status_t status = SGX_SUCCESS;
spdlog::debug("errMsg is ", errMsg->data());
if (*errStatus != 0) { RESTART_BEGIN
throw SGXException(-666, errMsg->data()); status = trustedEncryptKey(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(),
} &encryptedLen);
RESTART_END_POINTER
if (status != SGX_SUCCESS) { HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());
*errStatus = -1;
return "";
}
std::string result(2 * BUF_LEN, '\0'); SAFE_CHAR_BUF(resultBuf, 2 * BUF_LEN + 1);
carray2Hex(encryptedKey->data(), encryptedLen, &result.front()); carray2Hex(encryptedKey->data(), encryptedLen, resultBuf, 2 * BUF_LEN + 1);
return result; return string(resultBuf);
} }
...@@ -38,13 +38,10 @@ EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t ...@@ -38,13 +38,10 @@ EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t
EXTERNC int char2int(char _input); EXTERNC int char2int(char _input);
EXTERNC void carray2Hex(const unsigned char *d, int _len, char* _hexArray); EXTERNC void carray2Hex(const unsigned char *d, uint64_t , char* _hexArray,
uint64_t _hexArrayLen);
EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len, EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin ); uint8_t* _bin, uint64_t _max_length );
EXTERNC bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length );
std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key); std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key);
......
...@@ -25,111 +25,109 @@ ...@@ -25,111 +25,109 @@
#include "BLSSignature.h" #include "BLSSignature.h"
#include "BLSutils.h" #include "BLSutils.h"
#include "third_party/spdlog/spdlog.h"
#include "common.h"
#include "secure_enclave_u.h" #include "secure_enclave_u.h"
#include "sgxwallet_common.h" #include "sgxwallet_common.h"
#include "sgxwallet.h" #include "sgxwallet.h"
#include "BLSCrypto.h" #include "BLSCrypto.h"
#include "ServerInit.h" #include "ServerInit.h"
#include "common.h" #include "SEKManager.h"
#include "BLSPrivateKeyShareSGX.h" #include "BLSPrivateKeyShareSGX.h"
std::string *stringFromFq(libff::alt_bn128_Fq*_fq) { string *stringFromFq(libff::alt_bn128_Fq *_fq) {
CHECK_STATE(_fq);
mpz_t t; mpz_t t;
mpz_init(t); mpz_init(t);
_fq->as_bigint().to_mpz(t); _fq->as_bigint().to_mpz(t);
char arr[mpz_sizeinbase(t, 10) + 2]; SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2);
char *tmp = mpz_get_str(arr, 10, t); char *tmp = mpz_get_str(arr, 10, t);
mpz_clear(t); mpz_clear(t);
return new std::string(tmp); return new string(tmp);
} }
std::string *stringFromG1(libff::alt_bn128_G1 *_g1) { string *stringFromG1(libff::alt_bn128_G1 *_g1) {
CHECK_STATE(_g1);
auto sX = stringFromFq(&_g1->X); auto sX = stringFromFq(&_g1->X);
auto sY = stringFromFq(&_g1->Y); auto sY = stringFromFq(&_g1->Y);
auto sZ = stringFromFq(&_g1->Z); auto sZ = stringFromFq(&_g1->Z);
auto sG1 = new std::string(*sX + ":" + *sY + ":" + *sZ); auto sG1 = new string(*sX + ":" + *sY + ":" + *sZ);
delete(sX); delete (sX);
delete(sY); delete (sY);
delete(sZ); delete (sZ);
return sG1; return sG1;
} }
BLSPrivateKeyShareSGX::BLSPrivateKeyShareSGX( BLSPrivateKeyShareSGX::BLSPrivateKeyShareSGX(
shared_ptr<string> _encryptedKeyHex, size_t _requiredSigners, shared_ptr <string> _encryptedKeyHex, size_t _requiredSigners,
size_t _totalSigners) { size_t _totalSigners) {
requiredSigners = _requiredSigners; requiredSigners = _requiredSigners;
totalSigners = _totalSigners; totalSigners = _totalSigners;
if (requiredSigners > totalSigners) { if (requiredSigners > totalSigners) {
throw std::invalid_argument("requiredSigners > totalSigners"); throw invalid_argument("requiredSigners > totalSigners");
} }
if (totalSigners == 0) { if (totalSigners == 0) {
throw std::invalid_argument("totalSigners == 0"); throw invalid_argument("totalSigners == 0");
} }
if (_encryptedKeyHex == nullptr) { if (_encryptedKeyHex == nullptr) {
throw std::invalid_argument("Null key"); throw invalid_argument("Null key");
} }
if (_encryptedKeyHex->size() > 2 * MAX_ENCRYPTED_KEY_LENGTH) { if (_encryptedKeyHex->size() > 2 * MAX_ENCRYPTED_KEY_LENGTH) {
throw std::invalid_argument("Encrypted key size too long"); throw invalid_argument("Encrypted key size too long");
} }
encryptedKeyHex = _encryptedKeyHex; encryptedKeyHex = _encryptedKeyHex;
} }
std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr, shared_ptr <array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex) { size_t _signerIndex) {
shared_ptr<signatures::Bls> obj; shared_ptr <signatures::Bls> obj;
if (hash_byte_arr == nullptr) { CHECK_STATE(hash_byte_arr)
std::cerr << "Hash is null" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Hash is null"));
}
obj = make_shared<signatures::Bls>( obj = make_shared<signatures::Bls>(
signatures::Bls(requiredSigners, totalSigners)); signatures::Bls(requiredSigners, totalSigners));
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint = pair <libff::alt_bn128_G1, string> hash_with_hint =
obj->HashtoG1withHint(hash_byte_arr); obj->HashtoG1withHint(hash_byte_arr);
int errStatus = 0; int errStatus = 0;
string* xStr = stringFromFq(&(hash_with_hint.first.X)); string *xStr = stringFromFq(&(hash_with_hint.first.X));
if (xStr == nullptr) { CHECK_STATE(xStr);
std::cerr << "Null xStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
string* yStr = stringFromFq(&(hash_with_hint.first.Y)); string *yStr = stringFromFq(&(hash_with_hint.first.Y));
if (yStr == nullptr) { if (yStr == nullptr) {
std::cerr << "Null yStr" << std::endl;
delete xStr; delete xStr;
BOOST_THROW_EXCEPTION(runtime_error("Null yStr")); BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
} }
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
char xStrArg[BUF_LEN]; vector<char> errMsg(BUF_LEN, 0);
char yStrArg[BUF_LEN];
char signature [BUF_LEN];
SAFE_CHAR_BUF(xStrArg, BUF_LEN)SAFE_CHAR_BUF(yStrArg, BUF_LEN)SAFE_CHAR_BUF(signature, BUF_LEN);
memset(xStrArg, 0, BUF_LEN);
memset(yStrArg, 0, BUF_LEN);
strncpy(xStrArg, xStr->c_str(), BUF_LEN); strncpy(xStrArg, xStr->c_str(), BUF_LEN);
strncpy(yStrArg, yStr->c_str(), BUF_LEN); strncpy(yStrArg, yStr->c_str(), BUF_LEN);
...@@ -139,31 +137,25 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( ...@@ -139,31 +137,25 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
size_t sz = 0; size_t sz = 0;
uint8_t encryptedKey[BUF_LEN]; SAFE_UINT8_BUF(encryptedKey, BUF_LEN);
bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey); bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey,
BUF_LEN);
if (!result) { if (!result) {
cerr << "Invalid hex encrypted key" << endl; spdlog::error("Invalid hex encrypted key");
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key")); BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key"));
} }
cerr << "Key is " + *encryptedKeyHex << endl; sgx_status_t status = SGX_SUCCESS;
sgx_status_t status = RESTART_BEGIN
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey, status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature); encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
RESTART_END
printf("sig is: %s\n", signature); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
if (status != SGX_SUCCESS) {
gmp_printf("SGX enclave call to trustedBlsSignMessage failed: 0x%04x\n", status);
BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to trustedBlsSignMessage failed"));
}
if (errStatus != 0) {
BOOST_THROW_EXCEPTION(runtime_error("Enclave trustedBlsSignMessage failed:" + to_string(errStatus) + ":" + errMsg ));
}
int sigLen; int sigLen;
...@@ -171,10 +163,10 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( ...@@ -171,10 +163,10 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
BOOST_THROW_EXCEPTION(runtime_error("Signature is too short:" + to_string(sigLen))); BOOST_THROW_EXCEPTION(runtime_error("Signature is too short:" + to_string(sigLen)));
} }
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second; hash_with_hint.second;
std::string sig = signature; string sig = signature;
sig.append(":"); sig.append(":");
sig.append(hint); sig.append(hint);
...@@ -182,14 +174,17 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( ...@@ -182,14 +174,17 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
return sig; return sig;
} }
std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX( shared_ptr <BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr, shared_ptr <array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex) { size_t _signerIndex) {
std::string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
CHECK_STATE(hash_byte_arr);
string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
auto sig = make_shared<string>(signature); auto sig = make_shared<string>(signature);
std::shared_ptr<BLSSigShare> s = std::make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners, shared_ptr <BLSSigShare> s = make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners,
totalSigners); totalSigners);
return s; return s;
......
...@@ -20,7 +20,7 @@ add_executable(sgxwallet ...@@ -20,7 +20,7 @@ add_executable(sgxwallet
secure_enclave/DHDkg.h secure_enclave/DHDkg.h
secure_enclave/DKGUtils.cpp secure_enclave/DKGUtils.cpp
secure_enclave/DKGUtils.h secure_enclave/DKGUtils.h
secure_enclave/DomainParameters.c secure_enclave/DomainParameters.cpp
secure_enclave/DomainParameters.h secure_enclave/DomainParameters.h
secure_enclave/EnclaveConstants.h secure_enclave/EnclaveConstants.h
secure_enclave/NumberTheory.c secure_enclave/NumberTheory.c
......
...@@ -21,25 +21,27 @@ ...@@ -21,25 +21,27 @@
@date 2019 @date 2019
*/ */
#include "DKGCrypto.h"
#include "BLSCrypto.h"
#include "sgxwallet.h"
#include <iostream>
#include <iostream>
#include <memory> #include <memory>
#include "SGXWalletServer.hpp"
#include "SGXException.h"
#include "third_party/spdlog/spdlog.h" #include "third_party/spdlog/spdlog.h"
#include "common.h" #include "common.h"
#include "sgxwallet.h"
#include "SGXException.h"
#include "SGXWalletServer.hpp"
#include "BLSCrypto.h"
#include "SEKManager.h"
#include "DKGCrypto.h"
vector <string> splitString(const char *coeffs, const char symbol) {
vector<string> splitString(const char *coeffs, const char symbol) { CHECK_STATE(coeffs);
string str(coeffs); string str(coeffs);
string delim; string delim;
delim.push_back(symbol); delim.push_back(symbol);
vector<string> G2_strings; vector <string> G2_strings;
size_t prev = 0, pos = 0; size_t prev = 0, pos = 0;
do { do {
pos = str.find(delim, prev); pos = str.find(delim, prev);
...@@ -55,13 +57,14 @@ vector<string> splitString(const char *coeffs, const char symbol) { ...@@ -55,13 +57,14 @@ vector<string> splitString(const char *coeffs, const char symbol) {
return G2_strings; return G2_strings;
} }
template<class T> string ConvertToString(T field_elem, int base = 10) { template<class T>
string ConvertToString(T field_elem, int base = 10) {
mpz_t t; mpz_t t;
mpz_init(t); mpz_init(t);
field_elem.as_bigint().to_mpz(t); field_elem.as_bigint().to_mpz(t);
char arr[mpz_sizeinbase(t, base) + 2]; SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, base) + 2);
mpz_get_str(arr, base, t); mpz_get_str(arr, base, t);
mpz_clear(t); mpz_clear(t);
...@@ -71,7 +74,7 @@ template<class T> string ConvertToString(T field_elem, int base = 10) { ...@@ -71,7 +74,7 @@ template<class T> string ConvertToString(T field_elem, int base = 10) {
return output; return output;
} }
string convertHexToDec(const string& hex_str) { string convertHexToDec(const string &hex_str) {
mpz_t dec; mpz_t dec;
mpz_init(dec); mpz_init(dec);
...@@ -83,7 +86,7 @@ string convertHexToDec(const string& hex_str) { ...@@ -83,7 +86,7 @@ string convertHexToDec(const string& hex_str) {
return ret; return ret;
} }
char arr[mpz_sizeinbase(dec, 10) + 2]; SAFE_CHAR_BUF(arr, mpz_sizeinbase(dec, 10) + 2);
mpz_get_str(arr, 10, dec); mpz_get_str(arr, 10, dec);
ret = arr; ret = arr;
} catch (exception &e) { } catch (exception &e) {
...@@ -97,7 +100,7 @@ string convertHexToDec(const string& hex_str) { ...@@ -97,7 +100,7 @@ string convertHexToDec(const string& hex_str) {
return ret; return ret;
} }
string convertG2ToString(const libff::alt_bn128_G2& elem, int base, const string& delim) { string convertG2ToString(const libff::alt_bn128_G2 &elem, int base, const string &delim) {
string result = ""; string result = "";
try { try {
...@@ -123,109 +126,102 @@ string convertG2ToString(const libff::alt_bn128_G2& elem, int base, const string ...@@ -123,109 +126,102 @@ string convertG2ToString(const libff::alt_bn128_G2& elem, int base, const string
} }
string gen_dkg_poly(int _t) { string gen_dkg_poly(int _t) {
vector<char> errMsg(1024, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint64_t enc_len = 0;
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0); vector <uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
uint32_t enc_len = 0; sgx_status_t status = SGX_SUCCESS;
status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
if (errStatus != 0) { RESTART_BEGIN
spdlog::debug("trustedGenDkgSecret, status {}", errStatus, " err msg ", errMsg.data()); status = trustedGenDkgSecret(
spdlog::debug("in DKGCrypto encr len is {}", enc_len); eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
throw SGXException(-666, errMsg.data()); RESTART_END
}
if (status != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
spdlog::debug("trustedGenDkgSecret, status {}", status, " err msg ", errMsg.data());
spdlog::debug("in DKGCrypto encr len is {}", enc_len);
throw SGXException(-666, errMsg.data());
}
uint64_t length = enc_len;; uint64_t length = enc_len;;
vector<char> hexEncrPoly(2 * length + 1, 0); vector<char> hexEncrPoly(BUF_LEN, 0);
CHECK_STATE(encrypted_dkg_secret.size() >= length); CHECK_STATE(encrypted_dkg_secret.size() >= length);
carray2Hex(encrypted_dkg_secret.data(), length, hexEncrPoly.data()); carray2Hex(encrypted_dkg_secret.data(), length, hexEncrPoly.data(), BUF_LEN);
string result(hexEncrPoly.data()); string result(hexEncrPoly.data());
return result; return result;
} }
vector<vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n) { vector <vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n) {
CHECK_STATE(encryptedPolyHex);
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
spdlog::debug("got encr poly size {}", char_traits<char>::length(encryptedPolyHex));
vector<char> pubShares(10000, 0); vector<char> pubShares(10000, 0);
uint64_t encLen = 0; uint64_t encLen = 0;
vector<uint8_t> encrDKGPoly(2 * BUF_LEN, 0); vector <uint8_t> encrDKGPoly(2 * BUF_LEN, 0);
if (!hex2carray2(encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) { if (!hex2carray(encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
} }
spdlog::debug("hex_encr_poly length is {}", strlen(encryptedPolyHex));
spdlog::debug("enc len {}", encLen);
status = trustedGetPublicSharesAES(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), encLen,
pubShares.data(), t, n);
if (errStatus != 0) { sgx_status_t status = SGX_SUCCESS;
throw SGXException(-666, errMsg.data());
}
if (status != 0) {
throw SGXException(-666, errMsg.data());
}
spdlog::debug("err msg is {}", errMsg.data()); RESTART_BEGIN
status = trustedGetPublicShares(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), encLen,
pubShares.data(), t, n);
RESTART_END
spdlog::debug("public_shares:"); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
spdlog::debug("{}", pubShares.data());;
spdlog::debug("trustedGetPublicShares status: {}", errStatus);
vector<string> g2Strings = splitString(pubShares.data(), ','); vector <string> g2Strings = splitString(pubShares.data(), ',');
vector<vector<string>> pubSharesVect; vector <vector<string>> pubSharesVect;
for (uint64_t i = 0; i < g2Strings.size(); i++) { for (uint64_t i = 0; i < g2Strings.size(); i++) {
vector<string> coeffStr = splitString(g2Strings.at(i).c_str(), ':'); vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
pubSharesVect.push_back(coeffStr); pubSharesVect.push_back(coeffStr);
} }
return pubSharesVect; return pubSharesVect;
} }
string trustedGetSecretShares(const string &_polyName, const char *_encryptedPolyHex, const vector<string> &_publicKeys, string
getSecretShares(const string &_polyName, const char *_encryptedPolyHex, const vector <string> &_publicKeys,
int _t, int _t,
int _n) { int _n) {
CHECK_STATE(_encryptedPolyHex);
vector<char> hexEncrKey(BUF_LEN, 0); vector<char> hexEncrKey(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0); vector<char> errMsg1(BUF_LEN, 0);
vector <uint8_t> encrDKGPoly(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint64_t encLen = 0; uint64_t encLen = 0;
vector<uint8_t> encrDKGPoly(BUF_LEN, 0);
if (!hex2carray2(_encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) { if (!hex2carray(_encryptedPolyHex, &encLen, encrDKGPoly.data(), BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
} }
status = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen); sgx_status_t status = SGX_SUCCESS;
if (status != SGX_SUCCESS || errStatus != 0) { READ_LOCK(initMutex);
throw SGXException(-666, errMsg1.data());
} status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
string result; string result;
for (int i = 0; i < _n; i++) { for (int i = 0; i < _n; i++) {
vector<uint8_t> encryptedSkey(BUF_LEN, 0); vector <uint8_t> encryptedSkey(BUF_LEN, 0);
uint32_t decLen; uint64_t decLen;
vector<char> currentShare(193, 0); vector<char> currentShare(193, 0);
vector<char> sShareG2(320, 0); vector<char> sShareG2(320, 0);
...@@ -237,129 +233,135 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol ...@@ -237,129 +233,135 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol
spdlog::debug("pubKeyB is {}", pub_keyB); spdlog::debug("pubKeyB is {}", pub_keyB);
trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen, sgx_status_t status = SGX_SUCCESS;
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1); status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n,
i + 1);
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
throw SGXException(-666, errMsg1.data());
}
spdlog::debug("cur_share is {}", currentShare.data()); spdlog::debug("cur_share is {}", currentShare.data());
result += string(currentShare.data()); result += string(currentShare.data());
spdlog::debug("dec len is {}", decLen); spdlog::debug("dec len is {}", decLen);
carray2Hex(encryptedSkey.data(), decLen, hexEncrKey.data()); carray2Hex(encryptedSkey.data(), decLen, hexEncrKey.data(), BUF_LEN);
string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":"; string dhKeyName = "DKG_DH_KEY_" + _polyName + "_" + to_string(i) + ":";
spdlog::debug("hexEncr DH Key: { }", hexEncrKey.data()); spdlog::debug("hexEncr DH Key: { }", hexEncrKey.data());
spdlog::debug("name to write to db is {}", dhKeyName); spdlog::debug("name to write to db is {}", dhKeyName);
SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data());
string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":"; string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
spdlog::debug("name to write to db is {}", shareG2_name); spdlog::debug("name to write to db is {}", shareG2_name);
spdlog::debug("s_shareG2: {}", sShareG2.data()); spdlog::debug("s_shareG2: {}", sShareG2.data());
SGXWalletServer::writeDataToDB(dhKeyName, hexEncrKey.data());
SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data()); SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data());
spdlog::debug("errMsg: {}", errMsg1.data());
} }
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
SGXWalletServer::writeDataToDB(encryptedSecretShareName, result);
return result; return result;
} }
bool bool
verifyShares(const char *publicShares, const char *encr_sshare, const char *encryptedKeyHex, int t, int n, int ind) { verifyShares(const char *publicShares, const char *encr_sshare, const char *encryptedKeyHex, int t, int n, int ind) {
char errMsg[BUF_LEN];
CHECK_STATE(publicShares);
CHECK_STATE(encr_sshare);
CHECK_STATE(encryptedKeyHex);
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint64_t decKeyLen = 0;
int result = 0;
uint64_t decKeyLen; SAFE_UINT8_BUF(encr_key, BUF_LEN);
uint8_t encr_key[BUF_LEN]; if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) {
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
} }
int result;
spdlog::debug("publicShares length is {}", char_traits<char>::length(publicShares)); SAFE_CHAR_BUF(pshares, 8193);
char pshares[8193];
memset(pshares, 0, 8193);
strncpy(pshares, publicShares, strlen(publicShares)); strncpy(pshares, publicShares, strlen(publicShares));
trustedDkgVerifyAES(eid, &errStatus, errMsg, pshares, encr_sshare, encr_key, decKeyLen, t, ind, &result); sgx_status_t status = SGX_SUCCESS;
if (errStatus != 0) { RESTART_BEGIN
throw SGXException(-666, errMsg); status = trustedDkgVerify(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
} ind, &result);
RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
if (result == 2) { if (result == 2) {
throw SGXException(INVALID_HEX, "Invalid public shares"); throw SGXException(INVALID_HEX, "Invalid public shares");
} }
spdlog::debug("errMsg1: {}", errMsg);
spdlog::debug("result is: {}", result);
return result; return result;
} }
bool CreateBLSShare(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) { bool createBLSShare(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) {
spdlog::debug("ENTER CreateBLSShare");
CHECK_STATE(s_shares);
CHECK_STATE(encryptedKeyHex);
char errMsg[BUF_LEN]; vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint64_t decKeyLen; uint64_t decKeyLen;SAFE_UINT8_BUF(encr_bls_key, BUF_LEN);SAFE_UINT8_BUF(encr_key, BUF_LEN);
uint8_t encr_bls_key[BUF_LEN]; if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) {
memset(encr_bls_key, 0, BUF_LEN);
uint8_t encr_key[BUF_LEN];
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
uint32_t enc_bls_len = 0; uint64_t enc_bls_len = 0;
sgx_status_t status = SGX_SUCCESS;
trustedCreateBlsKeyAES(eid, &errStatus, errMsg, s_shares, encr_key, decKeyLen, encr_bls_key, &enc_bls_len); RESTART_BEGIN
status = trustedCreateBlsKey(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key,
&enc_bls_len);
RESTART_END
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
spdlog::error(errMsg);
spdlog::error("status {}", errStatus);
throw SGXException(ERROR_IN_ENCLAVE, "Create BLS private key failed in enclave");
} else {
char hexBLSKey[2 * BUF_LEN];
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey); SAFE_CHAR_BUF(hexBLSKey, 2 * BUF_LEN)
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey, 2 * BUF_LEN);
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey); SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey);
return true; return true;
}
} }
vector<string> GetBLSPubKey(const char *encryptedKeyHex) { vector <string> getBLSPubKey(const char *encryptedKeyHex) {
char errMsg1[BUF_LEN];
CHECK_STATE(encryptedKeyHex);
vector<char> errMsg1(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint64_t decKeyLen = 0;
uint64_t decKeyLen; SAFE_UINT8_BUF(encrKey, BUF_LEN);
uint8_t encrKey[BUF_LEN]; if (!hex2carray(encryptedKeyHex, &decKeyLen, encrKey, BUF_LEN)) {
if (!hex2carray(encryptedKeyHex, &decKeyLen, encrKey)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
char pubKey[320]; SAFE_CHAR_BUF(pubKey, 320)
spdlog::debug("decKeyLen is {}", decKeyLen);
trustedGetBlsPubKeyAES(eid, &errStatus, errMsg1, encrKey, decKeyLen, pubKey);
if (errStatus != 0) { sgx_status_t status = SGX_SUCCESS;
spdlog::error(string(errMsg1) + " . Status is {}", errStatus);
throw SGXException(ERROR_IN_ENCLAVE, "Failed to get BLS public key in enclave"); RESTART_BEGIN
} status = trustedGetBlsPubKey(eid, &errStatus, errMsg1.data(), encrKey, decKeyLen, pubKey);
vector<string> pubKeyVect = splitString(pubKey, ':'); RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
vector <string> pubKeyVect = splitString(pubKey, ':');
spdlog::debug("errMsg1 is {}", errMsg1);
spdlog::debug("pub key is "); spdlog::debug("pub key is ");
for (int i = 0; i < 4; i++) for (int i = 0; i < 4; i++)
spdlog::debug("{}", pubKeyVect.at(i)); spdlog::debug("{}", pubKeyVect.at(i));
...@@ -367,15 +369,15 @@ vector<string> GetBLSPubKey(const char *encryptedKeyHex) { ...@@ -367,15 +369,15 @@ vector<string> GetBLSPubKey(const char *encryptedKeyHex) {
return pubKeyVect; return pubKeyVect;
} }
vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) { vector <string> calculateAllBlsPublicKeys(const vector <string> &public_shares) {
size_t n = public_shares.size(); size_t n = public_shares.size();
size_t t = public_shares[0].length() / 256; size_t t = public_shares[0].length() / 256;
uint64_t share_length = 256; uint64_t share_length = 256;
uint8_t coord_length = 64; uint8_t coord_length = 64;
vector<libff::alt_bn128_G2> public_keys(n, libff::alt_bn128_G2::zero()); vector <libff::alt_bn128_G2> public_keys(n, libff::alt_bn128_G2::zero());
vector<libff::alt_bn128_G2> public_values(t, libff::alt_bn128_G2::zero()); vector <libff::alt_bn128_G2> public_values(t, libff::alt_bn128_G2::zero());
for (size_t i = 0; i < n; ++i) { for (size_t i = 0; i < n; ++i) {
for (size_t j = 0; j < t; ++j) { for (size_t j = 0; j < t; ++j) {
libff::alt_bn128_G2 public_share; libff::alt_bn128_G2 public_share;
...@@ -408,7 +410,7 @@ vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) { ...@@ -408,7 +410,7 @@ vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) {
public_keys[i].to_affine_coordinates(); public_keys[i].to_affine_coordinates();
} }
vector<string> result(n); vector <string> result(n);
for (size_t i = 0; i < n; ++i) { for (size_t i = 0; i < n; ++i) {
result[i] = convertG2ToString(public_keys[i]); result[i] = convertG2ToString(public_keys[i]);
} }
...@@ -417,37 +419,37 @@ vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) { ...@@ -417,37 +419,37 @@ vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) {
} }
string decryptDHKey(const string &polyName, int ind) { string decryptDHKey(const string &polyName, int ind) {
vector<char> errMsg1(1024, 0); vector<char> errMsg1(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
string DH_key_name = polyName + "_" + to_string(ind) + ":"; string DH_key_name = polyName + "_" + to_string(ind) + ":";
shared_ptr<string> hexEncrKeyPtr = SGXWalletServer::readFromDb(DH_key_name, "DKG_DH_KEY_"); shared_ptr <string> hexEncrKeyPtr = SGXWalletServer::readFromDb(DH_key_name, "DKG_DH_KEY_");
spdlog::debug("encr DH key is {}", *hexEncrKeyPtr); spdlog::debug("encr DH key is {}", *hexEncrKeyPtr);
vector<char> hexEncrKey(2 * BUF_LEN, 0); vector<char> hexEncrKey(2 * BUF_LEN, 0);
uint64_t dhEncLen = 0; uint64_t dhEncLen = 0;SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN);
uint8_t encryptedDHKey[BUF_LEN]; if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey, BUF_LEN)) {
if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey)) {
throw SGXException(INVALID_HEX, "Invalid hexEncrKey"); throw SGXException(INVALID_HEX, "Invalid hexEncrKey");
} }
spdlog::debug("encr DH key length is {}", dhEncLen); spdlog::debug("encr DH key length is {}", dhEncLen);
spdlog::debug("hex encr DH key length is {}", hexEncrKeyPtr->length()); spdlog::debug("hex encr DH key length is {}", hexEncrKeyPtr->length());
char DHKey[ECDSA_SKEY_LEN]; SAFE_CHAR_BUF(DHKey, ECDSA_SKEY_LEN);
trustedDecryptKeyAES(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey); sgx_status_t status = SGX_SUCCESS;
if (errStatus != 0) { RESTART_BEGIN
throw SGXException(errStatus, "decrypt key failed in enclave"); status = trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
} RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
return DHKey; return DHKey;
} }
vector<string> mult_G2(const string &x) { vector <string> mult_G2(const string &x) {
vector<string> result(4); vector <string> result(4);
libff::alt_bn128_Fr el(x.c_str()); libff::alt_bn128_Fr el(x.c_str());
libff::alt_bn128_G2 elG2 = el * libff::alt_bn128_G2::one(); libff::alt_bn128_G2 elG2 = el * libff::alt_bn128_G2::one();
elG2.to_affine_coordinates(); elG2.to_affine_coordinates();
......
...@@ -37,15 +37,15 @@ vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int ...@@ -37,15 +37,15 @@ vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int
vector<string> splitString(const char* coeffs, const char symbol); vector<string> splitString(const char* coeffs, const char symbol);
string trustedGetSecretShares(const string& _polyName, const char* _encryptedPolyHex, const vector<string>& _publicKeys, int _t, int _n); string getSecretShares(const string& _polyName, const char* _encryptedPolyHex, const vector<string>& _publicKeys, int _t, int _n);
bool verifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind); bool verifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
string decryptDHKey(const string& polyName, int ind); string decryptDHKey(const string& polyName, int ind);
bool CreateBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex); bool createBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
vector<string> GetBLSPubKey(const char * encryptedKeyHex); vector<string> getBLSPubKey(const char * encryptedKeyHex);
vector<string> mult_G2(const string& x); vector<string> mult_G2(const string& x);
...@@ -55,6 +55,6 @@ string convertG2ToString(const libff::alt_bn128_G2& elem, int base = 10, const s ...@@ -55,6 +55,6 @@ string convertG2ToString(const libff::alt_bn128_G2& elem, int base = 10, const s
vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares); vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares);
bool TestCreateBLSShare( const char * s_shares); bool testCreateBLSShare( const char * s_shares);
#endif //SGXD_DKGCRYPTO_H #endif //SGXD_DKGCRYPTO_H
...@@ -38,6 +38,7 @@ ...@@ -38,6 +38,7 @@
#include "BLSCrypto.h" #include "BLSCrypto.h"
#include "SEKManager.h"
#include "ECDSACrypto.h" #include "ECDSACrypto.h"
void fillRandomBuffer(vector<unsigned char> &_buffer) { void fillRandomBuffer(vector<unsigned char> &_buffer) {
...@@ -48,36 +49,39 @@ void fillRandomBuffer(vector<unsigned char> &_buffer) { ...@@ -48,36 +49,39 @@ void fillRandomBuffer(vector<unsigned char> &_buffer) {
} }
vector <string> genECDSAKey() { vector <string> genECDSAKey() {
vector<char> errMsg(1024, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
vector <uint8_t> encr_pr_key(1024, 0); vector <uint8_t> encr_pr_key(BUF_LEN, 0);
vector<char> pub_key_x(1024, 0); vector<char> pub_key_x(BUF_LEN, 0);
vector<char> pub_key_y(1024, 0); vector<char> pub_key_y(BUF_LEN, 0);
uint64_t enc_len = 0;
uint32_t enc_len = 0; sgx_status_t status = SGX_SUCCESS;
status = trustedGenerateEcdsaKeyAES(eid, &errStatus, RESTART_BEGIN
status = trustedGenerateEcdsaKey(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len, errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data()); pub_key_x.data(), pub_key_y.data());
RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data());
if (status != SGX_SUCCESS || errStatus != 0) {
spdlog::error("RPCException thrown with status {}", status);
throw SGXException(status, errMsg.data());
}
vector <string> keys(3); vector <string> keys(3);
vector<char> hexEncrKey(BUF_LEN * 2, 0); vector<char> hexEncrKey(BUF_LEN * 2, 0);
carray2Hex(encr_pr_key.data(), enc_len, hexEncrKey.data()); carray2Hex(encr_pr_key.data(), enc_len, hexEncrKey.data(),
BUF_LEN * 2);
keys.at(0) = hexEncrKey.data(); keys.at(0) = hexEncrKey.data();
keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data()); keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data());
vector<unsigned char> randBuffer(32, 0); vector<unsigned char> randBuffer(32, 0);
fillRandomBuffer(randBuffer); fillRandomBuffer(randBuffer);
vector<char> rand_str(64, 0); vector<char> rand_str(BUF_LEN, 0);
carray2Hex(randBuffer.data(), 32, rand_str.data()); carray2Hex(randBuffer.data(), 32, rand_str.data(), BUF_LEN);
keys.at(2) = rand_str.data(); keys.at(2) = rand_str.data();
...@@ -95,22 +99,20 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) { ...@@ -95,22 +99,20 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) {
int errStatus = 0; int errStatus = 0;
uint64_t enc_len = 0; uint64_t enc_len = 0;
if (!hex2carray(_encryptedKeyHex.c_str(), &enc_len, encrPrKey.data())) { if (!hex2carray(_encryptedKeyHex.c_str(), &enc_len, encrPrKey.data(),
BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
status = trustedGetPublicEcdsaKeyAES(eid, &errStatus, sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedGetPublicEcdsaKey(eid, &errStatus,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data()); errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
RESTART_END
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data())
spdlog::error("failed to get ECDSA public key {}", status);
throw SGXException(-666, errMsg.data());
}
if (status != SGX_SUCCESS) {
spdlog::error("failed to get ECDSA public key {}", status);
throw SGXException(666, "failed to get ECDSA public key");
}
string pubKey = string(pubKeyX.data()) + string(pubKeyY.data()); string pubKey = string(pubKeyX.data()) + string(pubKeyY.data());
if (pubKey.size() != 128) { if (pubKey.size() != 128) {
...@@ -123,6 +125,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) { ...@@ -123,6 +125,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) {
bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatureR, bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatureR,
const char *signatureS, int base) { const char *signatureS, int base) {
CHECK_STATE(hashHex)
CHECK_STATE(signatureR)
CHECK_STATE(signatureS)
auto x = pubKeyStr.substr(0, 64); auto x = pubKeyStr.substr(0, 64);
auto y = pubKeyStr.substr(64, 128); auto y = pubKeyStr.substr(64, 128);
...@@ -166,38 +173,40 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur ...@@ -166,38 +173,40 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur
} }
vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *hashHex, int base) { vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *hashHex, int base) {
CHECK_STATE(hashHex);
vector <string> signatureVector(3); vector <string> signatureVector(3);
vector<char> errMsg(1024, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
vector<char> signatureR(1024, 0); vector<char> signatureR(BUF_LEN, 0);
vector<char> signatureS(1024, 0); vector<char> signatureS(BUF_LEN, 0);
vector<uint8_t> encryptedKey(1024, 0); vector<uint8_t> encryptedKey(BUF_LEN, 0);
uint8_t signatureV = 0; uint8_t signatureV = 0;
uint64_t decLen = 0; uint64_t decLen = 0;
string pubKeyStr = ""; string pubKeyStr = "";
if (!hex2carray(encryptedKeyHex.c_str(), &decLen, encryptedKey.data())) { if (!hex2carray(encryptedKeyHex.c_str(), &decLen, encryptedKey.data(),
BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
status = trustedEcdsaSignAES(eid, &errStatus, sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedEcdsaSign(eid, &errStatus,
errMsg.data(), encryptedKey.data(), decLen, hashHex, errMsg.data(), encryptedKey.data(), decLen, hashHex,
signatureR.data(), signatureR.data(),
signatureS.data(), &signatureV, base); signatureS.data(), &signatureV, base);
RESTART_END
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
spdlog::error("failed to sign {}", errStatus);
throw SGXException(666, errMsg.data());
}
if (status != SGX_SUCCESS) {
spdlog::error("failed to sign in enclave {}", status);
throw SGXException(666, "failed to sign");
}
signatureVector.at(0) = to_string(signatureV); signatureVector.at(0) = to_string(signatureV);
if (base == 16) { if (base == 16) {
signatureVector.at(1) = "0x" + string(signatureR.data()); signatureVector.at(1) = "0x" + string(signatureR.data());
signatureVector.at(2) = "0x" + string(signatureS.data()); signatureVector.at(2) = "0x" + string(signatureS.data());
......
#include "secure_enclave/Point.c" #include "secure_enclave/Point.c"
#include "secure_enclave/DomainParameters.c" #include "secure_enclave/DomainParameters.cpp"
#include "secure_enclave/NumberTheory.c" #include "secure_enclave/NumberTheory.c"
#include "secure_enclave/Signature.c" #include "secure_enclave/Signature.c"
#include "secure_enclave/Curves.c" #include "secure_enclave/Curves.c"
...@@ -154,17 +154,16 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){ ...@@ -154,17 +154,16 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
return keys; return keys;
} }
void LevelDB::writeDataUnique(const string & Name, const string &value) { void LevelDB::writeDataUnique(const string & name, const string &value) {
auto key = Name; auto key = name;
if (readString(Name) != nullptr) { if (readString(name)) {
spdlog::debug("name {}",Name, " already exists"); spdlog::debug("Name {} already exists", name);
throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists"); throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
} }
writeString(key, value); writeString(key, value);
} }
......
...@@ -64,6 +64,7 @@ bin_PROGRAMS = sgxwallet testw cert_util ...@@ -64,6 +64,7 @@ bin_PROGRAMS = sgxwallet testw cert_util
## You can't use $(wildcard ...) with automake so all source files ## You can't use $(wildcard ...) with automake so all source files
## have to be explicitly listed. ## have to be explicitly listed.
## have to be explicitly listed
COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \ COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \
SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp \ SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp \
......
...@@ -21,21 +21,25 @@ ...@@ -21,21 +21,25 @@
@date 2020 @date 2020
*/ */
#include "SEKManager.h"
#include "SGXException.h"
#include "BLSCrypto.h"
#include "LevelDB.h"
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <algorithm> #include <algorithm>
#include "third_party/spdlog/spdlog.h"
#include "sgxwallet_common.h" #include "sgxwallet_common.h"
#include "common.h" #include "common.h"
#include "sgxwallet.h" #include "sgxwallet.h"
#include "SGXException.h"
#include "BLSCrypto.h"
#include "LevelDB.h"
#include "ServerDataChecker.h" #include "ServerDataChecker.h"
#include "third_party/spdlog/spdlog.h" #include "ServerInit.h"
#include "SEKManager.h"
using namespace std; using namespace std;
...@@ -52,82 +56,90 @@ bool case_insensitive_match(string s1, string s2) { ...@@ -52,82 +56,90 @@ bool case_insensitive_match(string s1, string s2) {
void create_test_key() { void create_test_key() {
int errStatus = 0; int errStatus = 0;
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
uint32_t enc_len; uint64_t enc_len;
uint8_t encrypted_key[BUF_LEN]; SAFE_UINT8_BUF(encrypted_key, BUF_LEN);
memset(encrypted_key, 0, BUF_LEN);
string key = TEST_VALUE; string key = TEST_VALUE;
status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len); sgx_status_t status = SGX_SUCCESS;
if (status != SGX_SUCCESS) {
cerr << "encrypt test key failed with status " << status << endl;
throw SGXException(status, errMsg.data());
}
if (errStatus != 0) { {
cerr << "encrypt test key failed with status " << errStatus << endl; READ_LOCK(initMutex);
throw SGXException(errStatus, errMsg.data()); status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len);
} }
vector<char> hexEncrKey(2 * enc_len + 1, 0); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
carray2Hex(encrypted_key, enc_len, hexEncrKey.data()); vector<char> hexEncrKey(2 * enc_len + 1, 0);
uint64_t test_len; carray2Hex(encrypted_key, enc_len, hexEncrKey.data(), 2 * enc_len + 1);
vector <uint8_t> test_encr_key(1024, 0);
if (!hex2carray(hexEncrKey.data(), &test_len, test_encr_key.data())) {
cerr << "wrong encrypted test key" << endl;
}
LevelDB::getLevelDb()->writeDataUnique("TEST_KEY", hexEncrKey.data()); LevelDB::getLevelDb()->writeDataUnique("TEST_KEY", hexEncrKey.data());
} }
shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) { void validate_SEK() {
shared_ptr <string> test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY"); shared_ptr <string> test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY");
vector <uint8_t> encr_test_key(BUF_LEN, 0); vector <uint8_t> encr_test_key(BUF_LEN, 0);
uint64_t len; vector<char> decr_key(BUF_LEN, 0);
if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data())) { uint64_t len = 0;
spdlog::error("wrong test key"); vector<char> errMsg(BUF_LEN, 0);
exit(-1);
}
vector<char> decr_key(1024, 0);
vector<char> errMsg(1024, 0);
int err_status = 0; int err_status = 0;
auto encrypted_SEK = make_shared < vector < uint8_t >> (1024, 0); if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data(),
BUF_LEN)) {
uint32_t l = len; spdlog::error("Corrupt test key is LevelDB");
status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l, SEK.c_str());
if (status != SGX_SUCCESS) {
spdlog::error("trustedSetSEK_backup failed with error code {}", status);
exit(-1); exit(-1);
} }
if (err_status != 0) { sgx_status_t status = SGX_SUCCESS;
spdlog::error("trustedSetSEK_backup failed with error status {}", status);
exit(-1);
}
status = trustedDecryptKeyAES(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data()); {
if (status != SGX_SUCCESS || err_status != 0) { READ_LOCK(initMutex);
spdlog::error("Failed to decrypt test key"); status = trustedDecryptKey(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data());
spdlog::error(errMsg.data());
exit(-1);
} }
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
string test_key = TEST_VALUE; string test_key = TEST_VALUE;
if (test_key.compare(decr_key.data()) != 0) { if (test_key.compare(decr_key.data()) != 0) {
spdlog::error("Invalid SEK"); spdlog::error("Invalid storage key. You need to recover using backup key");
spdlog::error("Set the correct backup key into sgx_datasgxwallet_backup_key.txt");
spdlog::error("Then run sgxwallet using backup flag");
exit(-1); exit(-1);
} }
}
shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) {
vector<char> decr_key(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int err_status = 0;
auto encrypted_SEK = make_shared < vector < uint8_t >> (BUF_LEN, 0);
uint64_t l = 0;
sgx_status_t status = SGX_SUCCESS;
{
READ_LOCK(initMutex);
status = trustedSetSEKBackup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l,
SEK.c_str());
}
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
encrypted_SEK->resize(l); encrypted_SEK->resize(l);
validate_SEK();
return encrypted_SEK; return encrypted_SEK;
} }
...@@ -135,30 +147,31 @@ void gen_SEK() { ...@@ -135,30 +147,31 @@ void gen_SEK() {
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
int err_status = 0; int err_status = 0;
vector <uint8_t> encrypted_SEK(1024, 0); vector <uint8_t> encrypted_SEK(1024, 0);
uint32_t enc_len = 0; uint64_t enc_len = 0;
char SEK[65]; SAFE_CHAR_BUF(SEK, 65);
memset(SEK, 0, 65);
spdlog::info("Generating backup key. Will be stored in backup_key.txt ... "); spdlog::info("Generating backup key. Will be stored in backup_key.txt ... ");
status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK);
if (status != SGX_SUCCESS) { sgx_status_t status = SGX_SUCCESS;
throw SGXException(status, errMsg.data()); {
}
if (err_status != 0) { status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK);
throw SGXException(err_status, errMsg.data());
} }
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
if (strnlen(SEK, 33) != 32) { if (strnlen(SEK, 33) != 32) {
throw SGXException(-1, "strnlen(SEK,33) != 32"); throw SGXException(-1, "strnlen(SEK,33) != 32");
} }
vector<char> hexEncrKey(2 * enc_len + 1, 0); vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_SEK.data(), enc_len, hexEncrKey.data()); carray2Hex(encrypted_SEK.data(), enc_len, hexEncrKey.data(), 2 * enc_len + 1);
spdlog::info(string("Encrypted storage encryption key:") + hexEncrKey.data());
ofstream sek_file(BACKUP_PATH); ofstream sek_file(BACKUP_PATH);
sek_file.clear(); sek_file.clear();
...@@ -185,31 +198,51 @@ void gen_SEK() { ...@@ -185,31 +198,51 @@ void gen_SEK() {
LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data()); LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data());
create_test_key(); create_test_key();
validate_SEK();
shared_ptr <string> encrypted_SEK_ptr = LevelDB::getLevelDb()->readString("SEK");
setSEK(encrypted_SEK_ptr);
validate_SEK();
}
void reinitEnclave() {
// unfortunately process needs to be restarted to reinit enclave
// exiting with error code 3 (SGX_OUT_OF_MEMORY), so docker container can restart the
// wallet
exit(3);
} }
void trustedSetSEK(shared_ptr <string> hex_encrypted_SEK) { void setSEK(shared_ptr <string> hex_encrypted_SEK) {
CHECK_STATE(hex_encrypted_SEK);
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
int err_status = 0; int err_status = 0;
uint8_t encrypted_SEK[BUF_LEN]; SAFE_UINT8_BUF(encrypted_SEK, BUF_LEN);
memset(encrypted_SEK, 0, BUF_LEN);
uint64_t len; uint64_t len = 0;
if (!hex2carray(hex_encrypted_SEK->c_str(), &len, encrypted_SEK)) { if (!hex2carray(hex_encrypted_SEK->c_str(), &len, encrypted_SEK,
BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encrypted SEK Hex"); throw SGXException(INVALID_HEX, "Invalid encrypted SEK Hex");
} }
sgx_status_t status = SGX_SUCCESS;
{
status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK); status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK);
if (status != SGX_SUCCESS) {
cerr << "RPCException thrown" << endl;
throw SGXException(status, errMsg.data());
} }
if (err_status != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
cerr << "RPCException thrown" << endl;
throw SGXException(err_status, errMsg.data());
} validate_SEK();
} }
#include "experimental/filesystem" #include "experimental/filesystem"
...@@ -218,7 +251,6 @@ void trustedSetSEK(shared_ptr <string> hex_encrypted_SEK) { ...@@ -218,7 +251,6 @@ void trustedSetSEK(shared_ptr <string> hex_encrypted_SEK) {
void enter_SEK() { void enter_SEK() {
shared_ptr <string> test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY"); shared_ptr <string> test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY");
if (test_key_ptr == nullptr) { if (test_key_ptr == nullptr) {
spdlog::error("Error: corrupt or empty LevelDB database"); spdlog::error("Error: corrupt or empty LevelDB database");
...@@ -251,7 +283,8 @@ void enter_SEK() { ...@@ -251,7 +283,8 @@ void enter_SEK() {
vector<char> hexEncrKey(BUF_LEN, 0); vector<char> hexEncrKey(BUF_LEN, 0);
carray2Hex(encrypted_SEK->data(), encrypted_SEK->size(), hexEncrKey.data()); carray2Hex(encrypted_SEK->data(), encrypted_SEK->size(), hexEncrKey.data(),
BUF_LEN);
spdlog::info("Got sealed storage encryption key."); spdlog::info("Got sealed storage encryption key.");
...@@ -274,7 +307,7 @@ void initSEK() { ...@@ -274,7 +307,7 @@ void initSEK() {
spdlog::warn("SEK was not created yet. Going to create SEK"); spdlog::warn("SEK was not created yet. Going to create SEK");
gen_SEK(); gen_SEK();
} else { } else {
trustedSetSEK(encrypted_SEK_ptr); setSEK(encrypted_SEK_ptr);
} }
} }
} }
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
void gen_SEK(); void gen_SEK();
#ifdef __cplusplus #ifdef __cplusplus
void trustedSetSEK(std::shared_ptr<std::string> hex_encr_SEK); void setSEK(std::shared_ptr<std::string> hex_encr_SEK);
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
...@@ -45,4 +45,11 @@ EXTERNC void enter_SEK(); ...@@ -45,4 +45,11 @@ EXTERNC void enter_SEK();
EXTERNC void initSEK(); EXTERNC void initSEK();
EXTERNC void setSEK();
EXTERNC void reinitEnclave();
#endif //SGXD_SEKMANAGER_H #endif //SGXD_SEKMANAGER_H
...@@ -54,6 +54,9 @@ ...@@ -54,6 +54,9 @@
using namespace std; using namespace std;
std::shared_timed_mutex initMutex;
uint64_t initTime;
void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) { void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) {
spdlog::info("Entering {}", __FUNCTION__); spdlog::info("Entering {}", __FUNCTION__);
...@@ -243,6 +246,7 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin ...@@ -243,6 +246,7 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin
} }
value = readFromDb(_keyShareName); value = readFromDb(_keyShareName);
if (!bls_sign(value->c_str(), _messageHash.c_str(), t, n, signature.data())) { if (!bls_sign(value->c_str(), _messageHash.c_str(), t, n, signature.data())) {
throw SGXException(-1, "Could not sign data "); throw SGXException(-1, "Could not sign data ");
} }
...@@ -402,7 +406,6 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J ...@@ -402,7 +406,6 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
spdlog::info("Entering {}", __FUNCTION__); spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result); INIT_RESULT(result);
result["secretShare"] = ""; result["secretShare"] = "";
result["SecretShare"] = "";
try { try {
if (_pubKeys.size() != (uint64_t) _n) { if (_pubKeys.size() != (uint64_t) _n) {
...@@ -425,9 +428,15 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J ...@@ -425,9 +428,15 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
pubKeysStrs.push_back(_pubKeys[i].asString()); pubKeysStrs.push_back(_pubKeys[i].asString());
} }
string s = trustedGetSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n); string secret_share_name = "encryptedSecretShare:" + _polyName;
shared_ptr <string> encryptedSecretShare = checkDataFromDb(secret_share_name);
if (encryptedSecretShare != nullptr) {
result["secretShare"] = *encryptedSecretShare.get();
} else {
string s = getSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n);
result["secretShare"] = s; result["secretShare"] = s;
result["SecretShare"] = s; }
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result) RETURN_SUCCESS(result)
...@@ -489,7 +498,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string ...@@ -489,7 +498,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName); shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
bool res = CreateBLSShare(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str()); bool res = createBLSShare(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str());
if (res) { if (res) {
spdlog::info("BLS KEY SHARE CREATED "); spdlog::info("BLS KEY SHARE CREATED ");
} else { } else {
...@@ -504,6 +513,9 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string ...@@ -504,6 +513,9 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
} }
LevelDB::getLevelDb()->deleteKey(_polyName); LevelDB::getLevelDb()->deleteKey(_polyName);
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName);
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result); RETURN_SUCCESS(result);
...@@ -519,7 +531,7 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) ...@@ -519,7 +531,7 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName)
} }
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_blsKeyName); shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_blsKeyName);
vector <string> public_key_vect = GetBLSPubKey(encryptedKeyHex_ptr->c_str()); vector <string> public_key_vect = getBLSPubKey(encryptedKeyHex_ptr->c_str());
for (uint8_t i = 0; i < 4; i++) { for (uint8_t i = 0; i < 4; i++) {
result["blsPublicKeyShare"][i] = public_key_vect.at(i); result["blsPublicKeyShare"][i] = public_key_vect.at(i);
} }
...@@ -562,7 +574,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu ...@@ -562,7 +574,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu
vector<string> public_keys = calculateAllBlsPublicKeys(public_shares); vector<string> public_keys = calculateAllBlsPublicKeys(public_shares);
if (public_keys.size() != n) { if (public_keys.size() != (uint64_t)n) {
throw SGXException(UNKNOWN_ERROR, ""); throw SGXException(UNKNOWN_ERROR, "");
} }
...@@ -590,6 +602,18 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int ...@@ -590,6 +602,18 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int
result["share*G2"] = *shareG2_ptr; result["share*G2"] = *shareG2_ptr;
result["dhKey"] = DHKey; result["dhKey"] = DHKey;
// TODO: delete dh keys
// for (int i = 0; i < _n; i++) {
// string name = _polyName + "_" + to_string(i) + ":";
// LevelDB::getLevelDb()->deleteDHDKGKey(name);
// string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
// LevelDB::getLevelDb()->deleteKey(shareG2_name);
// }
LevelDB::getLevelDb()->deleteKey(_polyName);
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName);
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result); RETURN_SUCCESS(result);
...@@ -738,7 +762,7 @@ Json::Value SGXWalletServer::deleteBlsKey(const string &name) { ...@@ -738,7 +762,7 @@ Json::Value SGXWalletServer::deleteBlsKey(const string &name) {
} }
shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) { shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) {
auto dataStr = LevelDB::getLevelDb()->readString(prefix + name); auto dataStr = checkDataFromDb(prefix + name);
if (dataStr == nullptr) { if (dataStr == nullptr) {
throw SGXException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exist"); throw SGXException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exist");
...@@ -747,6 +771,12 @@ shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string ...@@ -747,6 +771,12 @@ shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string
return dataStr; return dataStr;
} }
shared_ptr <string> SGXWalletServer::checkDataFromDb(const string &name, const string &prefix) {
auto dataStr = LevelDB::getLevelDb()->readString(prefix + name);
return dataStr;
}
void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_value) { void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_value) {
if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) { if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) {
throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists"); throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
......
...@@ -90,6 +90,8 @@ public: ...@@ -90,6 +90,8 @@ public:
static shared_ptr<string> readFromDb(const string &name, const string &prefix = ""); static shared_ptr<string> readFromDb(const string &name, const string &prefix = "");
static shared_ptr <string> checkDataFromDb(const string &name, const string &prefix = "");
static void writeDataToDB(const string &Name, const string &value); static void writeDataToDB(const string &Name, const string &value);
static void writeKeyShare(const string &_keyShareName, const string &_value); static void writeKeyShare(const string &_keyShareName, const string &_value);
......
...@@ -72,7 +72,7 @@ bool checkECDSAKeyName(const string& keyName) { ...@@ -72,7 +72,7 @@ bool checkECDSAKeyName(const string& keyName) {
bool checkHex(const string& hex, const uint32_t sizeInBytes){ bool checkHex(const string& hex, const uint32_t sizeInBytes){
if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){ if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){
spdlog::error("key is too long or zero - ", hex.length()); spdlog::error("key is too long or zero {} ", hex.length());
return false; return false;
} }
......
...@@ -57,6 +57,8 @@ ...@@ -57,6 +57,8 @@
#include "SGXException.h" #include "SGXException.h"
#include "SGXWalletServer.hpp" #include "SGXWalletServer.hpp"
uint32_t enclaveLogLevel = 0;
void initUserSpace() { void initUserSpace() {
libff::inhibit_profiling_counters = true; libff::inhibit_profiling_counters = true;
...@@ -66,9 +68,8 @@ void initUserSpace() { ...@@ -66,9 +68,8 @@ void initUserSpace() {
LevelDB::initDataFolderAndDBs(); LevelDB::initDataFolderAndDBs();
} }
void initEnclave(uint32_t _logLevel) { uint64_t initEnclave() {
eid = 0;
updated = 0;
#ifndef SGX_HW_SIM #ifndef SGX_HW_SIM
unsigned long support; unsigned long support;
...@@ -81,6 +82,21 @@ void initEnclave(uint32_t _logLevel) { ...@@ -81,6 +82,21 @@ void initEnclave(uint32_t _logLevel) {
spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG); spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG);
sgx_status_t status = SGX_SUCCESS;
{
WRITE_LOCK(initMutex);
if (eid != 0) {
if (sgx_destroy_enclave(eid) != SGX_SUCCESS) {
spdlog::error("Could not destroy enclave");
}
}
eid = 0;
updated = 0;
status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token, status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token,
&updated, &eid, 0); &updated, &eid, 0);
...@@ -96,20 +112,27 @@ void initEnclave(uint32_t _logLevel) { ...@@ -96,20 +112,27 @@ void initEnclave(uint32_t _logLevel) {
spdlog::info("Enclave created and started successfully"); spdlog::info("Enclave created and started successfully");
status = trustedEnclaveInit(eid, _logLevel); status = trustedEnclaveInit(eid, enclaveLogLevel);
}
if (status != SGX_SUCCESS) { if (status != SGX_SUCCESS) {
spdlog::error("trustedEnclaveInit failed: {}", status); spdlog::error("trustedEnclaveInit failed: {}", status);
exit(1); return status;
} }
spdlog::info("Enclave libtgmp library and logging initialized successfully"); spdlog::info("Enclave libtgmp library and logging initialized successfully");
return SGX_SUCCESS;
} }
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) { void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
static atomic<bool> sgxServerInited(false); static atomic<bool> sgxServerInited(false);
static mutex initMutex; static mutex initMutex;
enclaveLogLevel = _logLevel;
lock_guard <mutex> lock(initMutex); lock_guard <mutex> lock(initMutex);
...@@ -122,7 +145,19 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) { ...@@ -122,7 +145,19 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
CHECK_STATE(sgxServerInited != 1) CHECK_STATE(sgxServerInited != 1)
sgxServerInited = 1; sgxServerInited = 1;
initEnclave(_logLevel);
uint64_t counter = 0;
uint64_t initResult = 0;
while ((initResult = initEnclave()) != 0 && counter < 10){
sleep(1);
counter ++;
}
if (initResult != 0) {
spdlog::error("Coult not init enclave");
}
initUserSpace(); initUserSpace();
initSEK(); initSEK();
...@@ -136,12 +171,15 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) { ...@@ -136,12 +171,15 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
sgxServerInited = true; sgxServerInited = true;
} catch (SGXException &_e) { } catch (SGXException &_e) {
spdlog::error(_e.getMessage()); spdlog::error(_e.getMessage());
exit(-1);
} catch (exception &_e) { } catch (exception &_e) {
spdlog::error(_e.what()); spdlog::error(_e.what());
exit(-1);
} }
catch (...) { catch (...) {
exception_ptr p = current_exception(); exception_ptr p = current_exception();
printf("Exception %s \n", p.__cxa_exception_type()->name()); printf("Exception %s \n", p.__cxa_exception_type()->name());
spdlog::error("Unknown exception"); spdlog::error("Unknown exception");
exit(-1);
} }
}; };
...@@ -36,7 +36,7 @@ EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign); ...@@ -36,7 +36,7 @@ EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign);
EXTERNC void initUserSpace(); EXTERNC void initUserSpace();
EXTERNC void initEnclave(uint32_t _logLevel); EXTERNC uint64_t initEnclave();
......
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
#include "third_party/intel/create_enclave.h" #include "third_party/intel/create_enclave.h"
#include "secure_enclave_u.h" #include "secure_enclave_u.h"
#include "third_party/intel/sgx_detect.h" #include "third_party/intel/sgx_detect.h"
#include "third_party/spdlog/spdlog.h"
#include <gmp.h> #include <gmp.h>
#include <sgx_urts.h> #include <sgx_urts.h>
#include <stdio.h> #include <stdio.h>
...@@ -218,7 +219,7 @@ void TestUtils::sendRPCRequest() { ...@@ -218,7 +219,7 @@ void TestUtils::sendRPCRequest() {
auto hash_arr = make_shared < array < uint8_t, 32 >> (); auto hash_arr = make_shared < array < uint8_t, 32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) { if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
...@@ -351,7 +352,7 @@ void TestUtils::doDKG(StubClient &c, int n, int t, ...@@ -351,7 +352,7 @@ void TestUtils::doDKG(StubClient &c, int n, int t,
auto hash_arr = make_shared<array<uint8_t, 32 >>(); auto hash_arr = make_shared<array<uint8_t, 32 >>();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) { if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
......
1.58.0 1.58.5
\ No newline at end of file \ No newline at end of file
...@@ -32,6 +32,8 @@ using namespace std; ...@@ -32,6 +32,8 @@ using namespace std;
#include <map> #include <map>
#include <memory> #include <memory>
#include <boost/throw_exception.hpp>
#include <gmp.h> #include <gmp.h>
#include "secure_enclave/Verify.h" #include "secure_enclave/Verify.h"
#include "InvalidStateException.h" #include "InvalidStateException.h"
...@@ -50,10 +52,64 @@ inline std::string className(const std::string &prettyFunction) { ...@@ -50,10 +52,64 @@ inline std::string className(const std::string &prettyFunction) {
#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ ) #define __CLASS_NAME__ className( __PRETTY_FUNCTION__ )
#include <execinfo.h>
inline void print_stack() {
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr
fprintf(stderr, "Error: signal \n");
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
#define CHECK_STATE(_EXPRESSION_) \ #define CHECK_STATE(_EXPRESSION_) \
if (!(_EXPRESSION_)) { \ if (!(_EXPRESSION_)) { \
auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + std::string(__FILE__) + ":" + std::to_string(__LINE__); \ auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + std::string(__FILE__) + ":" + std::to_string(__LINE__); \
print_stack(); \
throw InvalidStateException(__msg__, __CLASS_NAME__);} throw InvalidStateException(__msg__, __CLASS_NAME__);}
#define HANDLE_TRUSTED_FUNCTION_ERROR(__STATUS__, __ERR_STATUS__, __ERR_MSG__) \
if (__STATUS__ != SGX_SUCCESS) { \
string __ERR_STRING__ = string("SGX enclave call to ") + \
__FUNCTION__ + " failed with status:" \
+ to_string(__STATUS__) + \
" Err message:" + __ERR_MSG__; \
BOOST_THROW_EXCEPTION(runtime_error(__ERR_MSG__)); \
}\
\
if (__ERR_STATUS__ != 0) {\
string __ERR_STRING__ = string("SGX enclave call to ") +\
__FUNCTION__ + " failed with errStatus:" + \
to_string(__ERR_STATUS__) + \
" Err message:" + __ERR_MSG__;\
BOOST_THROW_EXCEPTION(runtime_error(__ERR_STRING__)); \
}
#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
#define SAFE_UINT8_BUF(__X__, __Y__) ;uint8_t __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
#include <shared_mutex>
extern std::shared_timed_mutex initMutex;
extern uint64_t initTime;
#if SGX_MODE == SIM
#define ENCLAVE_RESTART_PERIOD_S 5
#else
#define ENCLAVE_RESTART_PERIOD_S 60 * 10
#endif
#define READ_LOCK(__X__) std::shared_lock<std::shared_timed_mutex> __LOCK__(__X__);
#define WRITE_LOCK(__X__) std::unique_lock<std::shared_timed_mutex> __LOCK__(__X__);
#endif //SGXWALLET_COMMON_H #endif //SGXWALLET_COMMON_H
...@@ -43,8 +43,10 @@ fi ...@@ -43,8 +43,10 @@ fi
if [[ "$1" == "-t" ]]; then if [[ "$1" == "-t" ]]; then
echo "Test run requested" echo "Test run requested"
sleep 5
./testw.py ./testw.py
else else
sleep 3
./sgxwallet $1 $2 $3 $4 $5 ./sgxwallet $1 $2 $3 $4 $5
fi fi
...@@ -2,12 +2,12 @@ ...@@ -2,12 +2,12 @@
# SGXWallet Backup Procedure # SGXWallet Backup Procedure
When SGXWallet is initialized, the server will print the backup key. When SGXWallet is initialized, the server will write the backup key into `sgx_data/sgxwallet_backup_key.txt`.
**This key must be securely recorded and stored.** **This key must be securely recorded and stored.**
Be sure to store this key in a safe place, then go into a docker container and securely remove it with the following command: Be sure to store this key in a safe place, then go into a docker container and securely remove it with the following command:
```bash ```bash
docker exec -it <SGX_CONTAINER_NAME> bash && apt-get install secure-delete && srm -vz backup_key.txt docker exec -it <SGX_CONTAINER_NAME> bash && srm -vz ./sgx_data/sgxwallet_backup_key.txt
``` ```
Master-Slave replication is recommended to support the SGXWallet backup strategy. Below are general instructions for a basic backup and recovery process. Master-Slave replication is recommended to support the SGXWallet backup strategy. Below are general instructions for a basic backup and recovery process.
...@@ -30,24 +30,12 @@ docker-compose down ...@@ -30,24 +30,12 @@ docker-compose down
command: -s -y -d -b command: -s -y -d -b
``` ```
2. Edit the `docker-compose.yml` and add `stdin_open: true` option. For example: 2. Copy the backed up `sgx_data` directory to the recovery `sgx_data` directory.
3. Create file `sgx_data/sgxwallet_backup_key.txt` in the recovery directory and write the backup key into it.
```yaml
version: "3"
services:
sgxwallet:
image: skalenetwork/sgxwallet:latest
stdin_open: true
```
3. Copy the backed up `sgx_data` directory to the recovery `sgx_data` directory.
4. Execute: 4. Execute:
```bash ```bash
docker-compose up -d docker-compose up -d
``` ```
5. Open another terminal window and run `docker attach container_name` there. 5. Edit the `docker-compose.yml` file, remove the `-b` flag.
6. Enter the backup key when prompted.
7. Edit the `docker-compose.yml` file, remove the `-b` flag and `stdin_open: true` option.
...@@ -2,6 +2,7 @@ version: '3' ...@@ -2,6 +2,7 @@ version: '3'
services: services:
sgxwallet: sgxwallet:
image: skalenetwork/sgxwallet:latest image: skalenetwork/sgxwallet:latest
restart: always
ports: ports:
- "1026:1026" - "1026:1026"
- "1027:1027" - "1027:1027"
......
...@@ -2,6 +2,7 @@ version: '3' ...@@ -2,6 +2,7 @@ version: '3'
services: services:
sgxwallet: sgxwallet:
image: skalenetwork/sgxwallet_sim:develop-latest image: skalenetwork/sgxwallet_sim:develop-latest
restart: always
ports: ports:
- "1026:1026" - "1026:1026"
- "1027:1027" - "1027:1027"
......
...@@ -27,9 +27,23 @@ ...@@ -27,9 +27,23 @@
#include "stdlib.h" #include "stdlib.h"
#include <string.h> #include <string.h>
#include "AESUtils.h" #include "AESUtils.h"
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen) { sgx_aes_gcm_128bit_key_t AES_key[1024];
#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrBufLen, unsigned char type,
unsigned char exportable, uint64_t* resultLen) {
if (!type) {
LOG_ERROR("Null type in AES_encrypt");
return -1;
}
if (!message) { if (!message) {
LOG_ERROR("Null message in AES_encrypt"); LOG_ERROR("Null message in AES_encrypt");
...@@ -41,25 +55,38 @@ int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen) { ...@@ -41,25 +55,38 @@ int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen) {
return -2; return -2;
} }
uint64_t len = strlen(message); uint64_t len = strlen(message) + 1;
if (len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE > encrLen ) { if (2 + len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE > encrBufLen ) {
LOG_ERROR("Output buffer too small"); LOG_ERROR("Output buffer too small");
return -3; return -3;
} }
SAFE_CHAR_BUF(fullMessage, len + 2);
fullMessage[0] = type;
fullMessage[1] = exportable;
strncpy(fullMessage + 2, message, len );
len = len + 2;
message = fullMessage;
sgx_read_rand(encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE); sgx_read_rand(encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE);
sgx_status_t status = sgx_rijndael128GCM_encrypt(&AES_key, (uint8_t*)message, strlen(message), sgx_status_t status = sgx_rijndael128GCM_encrypt(&(AES_key[512]), (uint8_t*)message, len,
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0, NULL, 0,
(sgx_aes_gcm_128bit_tag_t *) encr_message); (sgx_aes_gcm_128bit_tag_t *) encr_message);
*resultLen = len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
return status; return status;
} }
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen) { int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen,
uint8_t *type, uint8_t* exportable){
if (!message) { if (!message) {
LOG_ERROR("Null message in AES_encrypt"); LOG_ERROR("Null message in AES_encrypt");
...@@ -71,6 +98,16 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t ...@@ -71,6 +98,16 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t
return -2; return -2;
} }
if (!type) {
LOG_ERROR("Null type in AES_encrypt");
return -3;
}
if (!encr_message) {
LOG_ERROR("Null exportable in AES_encrypt");
return -4;
}
if (length < SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE) { if (length < SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE) {
LOG_ERROR("length < SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE"); LOG_ERROR("length < SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE");
...@@ -86,12 +123,18 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t ...@@ -86,12 +123,18 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t
return -2; return -2;
} }
sgx_status_t status = sgx_rijndael128GCM_decrypt(&AES_key, sgx_status_t status = sgx_rijndael128GCM_decrypt(&(AES_key[512]),
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len, encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len,
(unsigned char*) message, (unsigned char*) message,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0, NULL, 0,
(sgx_aes_gcm_128bit_tag_t *)encr_message); (sgx_aes_gcm_128bit_tag_t *)encr_message);
*type = message[0];
*exportable = message[1];
for (int i = 2; i < strlen(message) + 1; i++) {
message[i - 2 ] = message[i];
}
return status; return status;
} }
...@@ -24,10 +24,22 @@ ...@@ -24,10 +24,22 @@
#ifndef SGXD_AESUTILS_H #ifndef SGXD_AESUTILS_H
#define SGXD_AESUTILS_H #define SGXD_AESUTILS_H
sgx_aes_gcm_128bit_key_t AES_key; extern sgx_aes_gcm_128bit_key_t AES_key[1024];
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen,
unsigned char type, unsigned char exportable, uint64_t* resultLen);
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen,
uint8_t *type, uint8_t* exportable) ;
#define ECDSA '1'
#define BLS '2'
#define DKG '3'
#define EXPORTABLE '1'
#define NON_EXPORTABLE '2'
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen);
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen) ;
#endif //SGXD_AESUTILS_H #endif //SGXD_AESUTILS_H
...@@ -31,10 +31,13 @@ ...@@ -31,10 +31,13 @@
#include <../tgmp-build/include/sgx_tgmp.h> #include <../tgmp-build/include/sgx_tgmp.h>
#endif #endif
#include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include "EnclaveCommon.h"
#include "Point.h" #include "Point.h"
#include "DomainParameters.h" #include "DomainParameters.h"
#define CHECK_ARG_ABORT(_EXPRESSION_) \ #define CHECK_ARG_ABORT(_EXPRESSION_) \
...@@ -46,17 +49,28 @@ ...@@ -46,17 +49,28 @@
/*Initialize a curve*/ /*Initialize a curve*/
domain_parameters domain_parameters_init() domain_parameters domain_parameters_init()
{ {
domain_parameters curve; domain_parameters curve;
curve = calloc(sizeof(struct domain_parameters_s),1); curve = (domain_parameters) calloc(sizeof(struct domain_parameters_s),1);
CHECK_ARG_ABORT(curve);
//Initialize all members //Initialize all members
mpz_init(curve->p); mpz_init(curve->p);
mpz_init(curve->a); mpz_init(curve->a);
mpz_init(curve->b); mpz_init(curve->b);
curve->G = point_init();
mpz_init(curve->n); mpz_init(curve->n);
mpz_init(curve->h); mpz_init(curve->h);
curve->G = point_init();
CHECK_ARG_ABORT(curve->G);
return curve; return curve;
} }
......
...@@ -173,14 +173,25 @@ void enclave_init() { ...@@ -173,14 +173,25 @@ void enclave_init() {
return; return;
inited = 1; inited = 1;
LOG_INFO("Initing libff"); LOG_INFO("Initing libff");
try { try {
LOG_INFO("Initing params");
libff::init_alt_bn128_params(); libff::init_alt_bn128_params();
LOG_INFO("Initing curve");
curve = domain_parameters_init(); curve = domain_parameters_init();
LOG_INFO("Initing curve domain");
domain_parameters_load_curve(curve, secp256k1); domain_parameters_load_curve(curve, secp256k1);
} catch (exception& e) { } catch (exception& e) {
LOG_ERROR("Exception in libff init"); LOG_ERROR("Exception in libff init");
LOG_ERROR(e.what()); LOG_ERROR(e.what());
abort();
} catch (...) {
LOG_ERROR("Unknown exception in libff");
abort();
} }
LOG_INFO("Inited libff"); LOG_INFO("Inited libff");
} }
...@@ -345,19 +356,19 @@ void logMsg(log_level _level, const char *_msg) { ...@@ -345,19 +356,19 @@ void logMsg(log_level _level, const char *_msg) {
} }
EXTERNC void LOG_INFO(const char *_msg) { void LOG_INFO(const char *_msg) {
logMsg(L_INFO, _msg); logMsg(L_INFO, _msg);
}; };
EXTERNC void LOG_WARN(const char *_msg) { void LOG_WARN(const char *_msg) {
logMsg(L_WARNING, _msg); logMsg(L_WARNING, _msg);
}; };
EXTERNC void LOG_ERROR(const char *_msg) { void LOG_ERROR(const char *_msg) {
logMsg(L_ERROR, _msg); logMsg(L_ERROR, _msg);
}; };
EXTERNC void LOG_DEBUG(const char *_msg) { void LOG_DEBUG(const char *_msg) {
logMsg(L_DEBUG, _msg); logMsg(L_DEBUG, _msg);
}; };
EXTERNC void LOG_TRACE(const char *_msg) { void LOG_TRACE(const char *_msg) {
logMsg(L_TRACE, _msg); logMsg(L_TRACE, _msg);
}; };
...@@ -83,8 +83,8 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h ...@@ -83,8 +83,8 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \ secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \ secure_enclave.c \
Curves.c DomainParameters.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \ Curves.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \
DKGUtils.cpp EnclaveCommon.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \ DKGUtils.cpp EnclaveCommon.cpp DomainParameters.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \ ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG) ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......
...@@ -108,9 +108,9 @@ PROGRAMS = $(libexec_PROGRAMS) ...@@ -108,9 +108,9 @@ PROGRAMS = $(libexec_PROGRAMS)
am__objects_1 = am__objects_1 =
am_secure_enclave_OBJECTS = secure_enclave_t.$(OBJEXT) \ am_secure_enclave_OBJECTS = secure_enclave_t.$(OBJEXT) \
secure_enclave.$(OBJEXT) Curves.$(OBJEXT) \ secure_enclave.$(OBJEXT) Curves.$(OBJEXT) \
DomainParameters.$(OBJEXT) NumberTheory.$(OBJEXT) \ NumberTheory.$(OBJEXT) Point.$(OBJEXT) Signature.$(OBJEXT) \
Point.$(OBJEXT) Signature.$(OBJEXT) DHDkg.$(OBJEXT) \ DHDkg.$(OBJEXT) AESUtils.$(OBJEXT) DKGUtils.$(OBJEXT) \
AESUtils.$(OBJEXT) DKGUtils.$(OBJEXT) EnclaveCommon.$(OBJEXT) \ EnclaveCommon.$(OBJEXT) DomainParameters.$(OBJEXT) \
alt_bn128_init.$(OBJEXT) alt_bn128_g2.$(OBJEXT) \ alt_bn128_init.$(OBJEXT) alt_bn128_g2.$(OBJEXT) \
alt_bn128_g1.$(OBJEXT) $(am__objects_1) $(am__objects_1) alt_bn128_g1.$(OBJEXT) $(am__objects_1) $(am__objects_1)
secure_enclave_OBJECTS = $(am_secure_enclave_OBJECTS) secure_enclave_OBJECTS = $(am_secure_enclave_OBJECTS)
...@@ -337,8 +337,8 @@ ENCLAVE_CONFIG = $(ENCLAVE).config.xml ...@@ -337,8 +337,8 @@ ENCLAVE_CONFIG = $(ENCLAVE).config.xml
ENCLAVE_KEY = test_insecure_private_key.pem #$(ENCLAVE)_private.pem ENCLAVE_KEY = test_insecure_private_key.pem #$(ENCLAVE)_private.pem
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \ secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \ secure_enclave.c \
Curves.c DomainParameters.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \ Curves.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \
DKGUtils.cpp EnclaveCommon.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \ DKGUtils.cpp EnclaveCommon.cpp DomainParameters.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \ ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG) ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......
#define SIGNED_ENCLAVE_VERSION "0" #define SIGNED_ENCLAVE_VERSION "1"
\ No newline at end of file \ No newline at end of file
...@@ -57,6 +57,15 @@ signature signature_init() { ...@@ -57,6 +57,15 @@ signature signature_init() {
return sig; return sig;
} }
/*Release signature*/
void signature_free(signature sig) {
if (!sig)
return;
mpz_clear(sig->r);
mpz_clear(sig->s);
free(sig);
}
/*Set signature from strings of a base from 2-62*/ /*Set signature from strings of a base from 2-62*/
int signature_set_str(signature sig, const char *r, const char *s, int base) { int signature_set_str(signature sig, const char *r, const char *s, int base) {
...@@ -104,10 +113,9 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para ...@@ -104,10 +113,9 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para
return; return;
} }
point Q = point_init();
//Initializing variables //Initializing variables
mpz_t k, x, r, t1, t2, t3, t4, t5, s, n_div_2, rem, neg, seed; point Q = point_init();
mpz_t k, x, r, t1, t2, t3, t4, t5, s, n_div_2, rem, neg, seed, s_mul_2;
mpz_init(k); mpz_init(k);
mpz_init(x); mpz_init(x);
mpz_init(r); mpz_init(r);
...@@ -121,7 +129,6 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para ...@@ -121,7 +129,6 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para
mpz_init(rem); mpz_init(rem);
mpz_init(neg); mpz_init(neg);
mpz_init(seed); mpz_init(seed);
mpz_t s_mul_2;
mpz_init(s_mul_2); mpz_init(s_mul_2);
SAFE_CHAR_BUF(rand_char, 32); SAFE_CHAR_BUF(rand_char, 32);
...@@ -182,32 +189,27 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para ...@@ -182,32 +189,27 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para
point_clear(Q); point_clear(Q);
mpz_clear(k); mpz_clear(k);
mpz_clear(r);
mpz_clear(s); mpz_clear(s);
mpz_clear(r);
mpz_clear(x); mpz_clear(x);
mpz_clear(rem); mpz_clear(rem);
mpz_clear(neg); mpz_clear(neg);
mpz_clear(t1); mpz_clear(t1);
mpz_clear(t2); mpz_clear(t2);
mpz_clear(t3); mpz_clear(t3);
mpz_clear(t4);
mpz_clear(t5);
mpz_clear(seed); mpz_clear(seed);
mpz_clear(n_div_2); mpz_clear(n_div_2);
mpz_clear(s_mul_2); mpz_clear(s_mul_2);
} }
#endif #endif
/*Release signature*/
void signature_free(signature sig) {
if (!sig)
return;
mpz_clear(sig->r);
mpz_clear(sig->s);
free(sig);
}
/*Verify the integrity of a message using it's signature*/ /*Verify the integrity of a message using it's signature*/
bool signature_verify(mpz_t message, signature sig, point public_key, domain_parameters curve) { bool signature_verify(mpz_t message, signature sig, point public_key, domain_parameters curve) {
......
...@@ -111,7 +111,7 @@ void *reallocate_function(void *, size_t, size_t); ...@@ -111,7 +111,7 @@ void *reallocate_function(void *, size_t, size_t);
void free_function(void *, size_t); void free_function(void *, size_t);
unsigned char *globalRandom; unsigned char *globalRandom = NULL;
#define CALL_ONCE \ #define CALL_ONCE \
...@@ -122,7 +122,7 @@ unsigned char *globalRandom; ...@@ -122,7 +122,7 @@ unsigned char *globalRandom;
abort(); \ abort(); \
} else {called = true;}; } else {called = true;};
void trustedEnclaveInit(uint32_t _logLevel) { void trustedEnclaveInit(uint64_t _logLevel) {
CALL_ONCE CALL_ONCE
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
...@@ -136,9 +136,14 @@ void trustedEnclaveInit(uint32_t _logLevel) { ...@@ -136,9 +136,14 @@ void trustedEnclaveInit(uint32_t _logLevel) {
mp_get_memory_functions(NULL, &gmp_realloc_func, &gmp_free_func); mp_get_memory_functions(NULL, &gmp_realloc_func, &gmp_free_func);
mp_set_memory_functions(NULL, oc_realloc_func, oc_free_func); mp_set_memory_functions(NULL, oc_realloc_func, oc_free_func);
LOG_INFO("Reading random"); LOG_INFO("Calling enclave init");
enclave_init();
LOG_INFO("Reading random");
globalRandom = calloc(32,1); globalRandom = calloc(32,1);
int ret = sgx_read_rand(globalRandom, 32); int ret = sgx_read_rand(globalRandom, 32);
...@@ -149,11 +154,6 @@ void trustedEnclaveInit(uint32_t _logLevel) { ...@@ -149,11 +154,6 @@ void trustedEnclaveInit(uint32_t _logLevel) {
abort(); abort();
} }
LOG_INFO("Calling enclave init");
enclave_init();
LOG_INFO("Successfully inited enclave. Signed enclave version:" SIGNED_ENCLAVE_VERSION ); LOG_INFO("Successfully inited enclave. Signed enclave version:" SIGNED_ENCLAVE_VERSION );
#ifndef SGX_DEBUG #ifndef SGX_DEBUG
LOG_INFO("SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!"); LOG_INFO("SECURITY WARNING: sgxwallet is running in INSECURE DEBUG MODE! NEVER USE IN PRODUCTION!");
...@@ -232,7 +232,7 @@ void get_global_random(unsigned char *_randBuff, uint64_t _size) { ...@@ -232,7 +232,7 @@ void get_global_random(unsigned char *_randBuff, uint64_t _size) {
void sealHexSEK(int *errStatus, char *errString, void sealHexSEK(int *errStatus, char *errString,
uint8_t *encrypted_sek, uint32_t *enc_len, char *sek_hex) { uint8_t *encrypted_sek, uint64_t *enc_len, char *sek_hex) {
CALL_ONCE CALL_ONCE
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -242,7 +242,7 @@ void sealHexSEK(int *errStatus, char *errString, ...@@ -242,7 +242,7 @@ void sealHexSEK(int *errStatus, char *errString,
CHECK_STATE(strnlen(sek_hex, 33) == 32) CHECK_STATE(strnlen(sek_hex, 33) == 32)
uint64_t plaintextLen = strlen(sek_hex + 1); uint64_t plaintextLen = strlen(sek_hex) + 1;
uint64_t sealedLen = sgx_calc_sealed_data_size(0, plaintextLen); uint64_t sealedLen = sgx_calc_sealed_data_size(0, plaintextLen);
...@@ -255,7 +255,7 @@ void sealHexSEK(int *errStatus, char *errString, ...@@ -255,7 +255,7 @@ void sealHexSEK(int *errStatus, char *errString,
(sgx_sealed_data_t *) encrypted_sek); (sgx_sealed_data_t *) encrypted_sek);
CHECK_STATUS("seal SEK failed after SEK generation"); CHECK_STATUS("seal SEK failed after SEK generation");
uint32_t encrypt_text_length = sgx_get_encrypt_txt_len((const sgx_sealed_data_t *)encrypted_sek); uint64_t encrypt_text_length = sgx_get_encrypt_txt_len((const sgx_sealed_data_t *)encrypted_sek);
CHECK_STATE(encrypt_text_length = plaintextLen); CHECK_STATE(encrypt_text_length = plaintextLen);
...@@ -263,7 +263,7 @@ void sealHexSEK(int *errStatus, char *errString, ...@@ -263,7 +263,7 @@ void sealHexSEK(int *errStatus, char *errString,
SAFE_CHAR_BUF(unsealedKey, BUF_LEN); SAFE_CHAR_BUF(unsealedKey, BUF_LEN);
uint32_t decLen = BUF_LEN; uint32_t decLen = BUF_LEN;
uint32_t add_text_length = sgx_get_add_mac_txt_len((const sgx_sealed_data_t *)encrypted_sek); uint64_t add_text_length = sgx_get_add_mac_txt_len((const sgx_sealed_data_t *)encrypted_sek);
CHECK_STATE(add_text_length == 0); CHECK_STATE(add_text_length == 0);
CHECK_STATE(sgx_is_within_enclave(encrypted_sek,sizeof(sgx_sealed_data_t))); CHECK_STATE(sgx_is_within_enclave(encrypted_sek,sizeof(sgx_sealed_data_t)));
status = sgx_unseal_data((const sgx_sealed_data_t *)encrypted_sek, NULL, NULL, status = sgx_unseal_data((const sgx_sealed_data_t *)encrypted_sek, NULL, NULL,
...@@ -279,7 +279,7 @@ void sealHexSEK(int *errStatus, char *errString, ...@@ -279,7 +279,7 @@ void sealHexSEK(int *errStatus, char *errString,
} }
void trustedGenerateSEK(int *errStatus, char *errString, void trustedGenerateSEK(int *errStatus, char *errString,
uint8_t *encrypted_sek, uint32_t *enc_len, char *sek_hex) { uint8_t *encrypted_sek, uint64_t *enc_len, char *sek_hex) {
CALL_ONCE CALL_ONCE
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -291,7 +291,8 @@ void trustedGenerateSEK(int *errStatus, char *errString, ...@@ -291,7 +291,8 @@ void trustedGenerateSEK(int *errStatus, char *errString,
RANDOM_CHAR_BUF(SEK_raw, SGX_AESGCM_KEY_SIZE); RANDOM_CHAR_BUF(SEK_raw, SGX_AESGCM_KEY_SIZE);
carray2Hex((uint8_t*) SEK_raw, SGX_AESGCM_KEY_SIZE, sek_hex); carray2Hex((uint8_t*) SEK_raw, SGX_AESGCM_KEY_SIZE, sek_hex);
memcpy(AES_key, SEK_raw, SGX_AESGCM_KEY_SIZE); memcpy(AES_key[512], SEK_raw, SGX_AESGCM_KEY_SIZE);
sealHexSEK(errStatus, errString, encrypted_sek, enc_len, sek_hex); sealHexSEK(errStatus, errString, encrypted_sek, enc_len, sek_hex);
...@@ -330,7 +331,7 @@ void trustedSetSEK(int *errStatus, char *errString, uint8_t *encrypted_sek) { ...@@ -330,7 +331,7 @@ void trustedSetSEK(int *errStatus, char *errString, uint8_t *encrypted_sek) {
uint64_t len; uint64_t len;
hex2carray(aes_key_hex, &len, (uint8_t *) AES_key); hex2carray(aes_key_hex, &len, (uint8_t *) (AES_key[512]));
SET_SUCCESS SET_SUCCESS
clean: clean:
...@@ -338,8 +339,8 @@ void trustedSetSEK(int *errStatus, char *errString, uint8_t *encrypted_sek) { ...@@ -338,8 +339,8 @@ void trustedSetSEK(int *errStatus, char *errString, uint8_t *encrypted_sek) {
LOG_INFO("SGX call completed"); LOG_INFO("SGX call completed");
} }
void trustedSetSEK_backup(int *errStatus, char *errString, void trustedSetSEKBackup(int *errStatus, char *errString,
uint8_t *encrypted_sek, uint32_t *enc_len, const char *sek_hex) { uint8_t *encrypted_sek, uint64_t *enc_len, const char *sek_hex) {
CALL_ONCE CALL_ONCE
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -348,7 +349,8 @@ void trustedSetSEK_backup(int *errStatus, char *errString, ...@@ -348,7 +349,8 @@ void trustedSetSEK_backup(int *errStatus, char *errString,
CHECK_STATE(sek_hex); CHECK_STATE(sek_hex);
uint64_t len; uint64_t len;
hex2carray(sek_hex, &len, (uint8_t *) AES_key); hex2carray(sek_hex, &len, (uint8_t *) (AES_key[512]));
sealHexSEK(errStatus, errString, encrypted_sek, enc_len, (char *)sek_hex); sealHexSEK(errStatus, errString, encrypted_sek, enc_len, (char *)sek_hex);
...@@ -366,8 +368,8 @@ void trustedSetSEK_backup(int *errStatus, char *errString, ...@@ -366,8 +368,8 @@ void trustedSetSEK_backup(int *errStatus, char *errString,
void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString, void trustedGenerateEcdsaKey(int *errStatus, char *errString,
uint8_t *encryptedPrivateKey, uint32_t *enc_len, char *pub_key_x, char *pub_key_y) { uint8_t *encryptedPrivateKey, uint64_t *enc_len, char *pub_key_x, char *pub_key_y) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -407,22 +409,24 @@ void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString, ...@@ -407,22 +409,24 @@ void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString,
} }
strncpy(pub_key_y + n_zeroes, arr_y, 1024 - n_zeroes); strncpy(pub_key_y + n_zeroes, arr_y, 1024 - n_zeroes);
SAFE_CHAR_BUF(skey_str, ECDSA_SKEY_LEN);SAFE_CHAR_BUF(arr_skey_str, mpz_sizeinbase(skey, ECDSA_SKEY_BASE) + 2); SAFE_CHAR_BUF(skey_str, BUF_LEN);
SAFE_CHAR_BUF(arr_skey_str, mpz_sizeinbase(skey, ECDSA_SKEY_BASE) + 2);
mpz_get_str(arr_skey_str, ECDSA_SKEY_BASE, skey); mpz_get_str(arr_skey_str, ECDSA_SKEY_BASE, skey);
n_zeroes = 64 - strlen(arr_skey_str); n_zeroes = 64 - strlen(arr_skey_str);
for (int i = 0; i < n_zeroes; i++) { for (int i = 0; i < n_zeroes; i++) {
skey_str[i] = '0'; skey_str[i] = '0';
} }
strncpy(skey_str + n_zeroes, arr_skey_str, 65 - n_zeroes); strncpy(skey_str + n_zeroes, arr_skey_str, 65 - n_zeroes);
skey_str[ECDSA_SKEY_LEN - 1] = 0;
snprintf(errString, BUF_LEN, "skey len is %d\n", (int) strlen(skey_str)); snprintf(errString, BUF_LEN, "skey len is %d\n", (int) strlen(skey_str));
int status = AES_encrypt((char *) skey_str, encryptedPrivateKey, BUF_LEN); int status = AES_encrypt((char *) skey_str, encryptedPrivateKey, BUF_LEN,
ECDSA, NON_EXPORTABLE, enc_len);
CHECK_STATUS("ecdsa private key encryption failed"); CHECK_STATUS("ecdsa private key encryption failed");
*enc_len = strlen(skey_str) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE; uint8_t type = 0;
uint8_t exportable = 0;
status = AES_decrypt(encryptedPrivateKey, *enc_len, skey_str, ECDSA_SKEY_LEN); status = AES_decrypt(encryptedPrivateKey, *enc_len, skey_str, BUF_LEN, &type, &exportable);
CHECK_STATUS2("ecdsa private key decr failed with status %d"); CHECK_STATUS2("ecdsa private key decr failed with status %d");
...@@ -435,12 +439,12 @@ void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString, ...@@ -435,12 +439,12 @@ void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString,
LOG_INFO("SGX call completed"); LOG_INFO("SGX call completed");
} }
void trustedGetPublicEcdsaKeyAES(int *errStatus, char *errString, void trustedGetPublicEcdsaKey(int *errStatus, char *errString,
uint8_t *encryptedPrivateKey, uint32_t enc_len, char *pub_key_x, char *pub_key_y) { uint8_t *encryptedPrivateKey, uint64_t enc_len, char *pub_key_x, char *pub_key_y) {
LOG_DEBUG(__FUNCTION__); LOG_DEBUG(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
SAFE_CHAR_BUF(skey, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(skey, BUF_LEN);
mpz_t privateKeyMpz; mpz_t privateKeyMpz;
mpz_init(privateKeyMpz); mpz_init(privateKeyMpz);
...@@ -452,7 +456,11 @@ void trustedGetPublicEcdsaKeyAES(int *errStatus, char *errString, ...@@ -452,7 +456,11 @@ void trustedGetPublicEcdsaKeyAES(int *errStatus, char *errString,
CHECK_STATE(pub_key_x); CHECK_STATE(pub_key_x);
CHECK_STATE(pub_key_y); CHECK_STATE(pub_key_y);
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, ECDSA_SKEY_LEN); uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("AES_decrypt failed with status %d"); CHECK_STATUS2("AES_decrypt failed with status %d");
skey[enc_len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE] = '\0'; skey[enc_len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE] = '\0';
...@@ -512,7 +520,7 @@ void trustedGetPublicEcdsaKeyAES(int *errStatus, char *errString, ...@@ -512,7 +520,7 @@ void trustedGetPublicEcdsaKeyAES(int *errStatus, char *errString,
static uint64_t sigCounter = 0; static uint64_t sigCounter = 0;
void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, uint32_t enc_len, void trustedEcdsaSign(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, uint64_t enc_len,
const char *hash, char *sigR, char *sigS, uint8_t *sig_v, int base) { const char *hash, char *sigR, char *sigS, uint8_t *sig_v, int base) {
LOG_DEBUG(__FUNCTION__); LOG_DEBUG(__FUNCTION__);
...@@ -523,7 +531,7 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv ...@@ -523,7 +531,7 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv
CHECK_STATE(sigR); CHECK_STATE(sigR);
CHECK_STATE(sigS); CHECK_STATE(sigS);
SAFE_CHAR_BUF(skey, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(skey, BUF_LEN);
mpz_t privateKeyMpz; mpz_t privateKeyMpz;
mpz_init(privateKeyMpz); mpz_init(privateKeyMpz);
...@@ -531,7 +539,12 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv ...@@ -531,7 +539,12 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv
mpz_init(msgMpz); mpz_init(msgMpz);
signature sign = signature_init(); signature sign = signature_init();
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, ECDSA_SKEY_LEN); uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("aes decrypt failed with status %d"); CHECK_STATUS2("aes decrypt failed with status %d");
...@@ -596,8 +609,8 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv ...@@ -596,8 +609,8 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv
} }
void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, void trustedDecryptKey(int *errStatus, char *errString, uint8_t *encryptedPrivateKey,
uint32_t enc_len, char *key) { uint64_t enc_len, char *key) {
LOG_DEBUG(__FUNCTION__); LOG_DEBUG(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -607,7 +620,16 @@ void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPri ...@@ -607,7 +620,16 @@ void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPri
*errStatus = -9; *errStatus = -9;
int status = AES_decrypt(encryptedPrivateKey, enc_len, key, 3072); uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, enc_len, key, 3072,
&type, &exportable);
if (exportable != EXPORTABLE) {
*errStatus = -11;
snprintf(errString, BUF_LEN, "Key is not exportable");
}
if (status != 0) { if (status != 0) {
*errStatus = status; *errStatus = status;
...@@ -632,8 +654,8 @@ void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPri ...@@ -632,8 +654,8 @@ void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPri
} }
void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key, void trustedEncryptKey(int *errStatus, char *errString, const char *key,
uint8_t *encryptedPrivateKey, uint32_t *enc_len) { uint8_t *encryptedPrivateKey, uint64_t *enc_len) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
*errString = 0; *errString = 0;
...@@ -644,15 +666,18 @@ void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key, ...@@ -644,15 +666,18 @@ void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key,
*errStatus = UNKNOWN_ERROR; *errStatus = UNKNOWN_ERROR;
int status = AES_encrypt((char *)key, encryptedPrivateKey, BUF_LEN); int status = AES_encrypt((char *)key, encryptedPrivateKey, BUF_LEN,
DKG, EXPORTABLE, enc_len);
CHECK_STATUS2("AES encrypt failed with status %d"); CHECK_STATUS2("AES encrypt failed with status %d");
*enc_len = strlen(key) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
SAFE_CHAR_BUF(decryptedKey, BUF_LEN); SAFE_CHAR_BUF(decryptedKey, BUF_LEN);
status = AES_decrypt(encryptedPrivateKey, *enc_len, decryptedKey, BUF_LEN); uint8_t type = 0;
uint8_t exportable = 0;
status = AES_decrypt(encryptedPrivateKey, *enc_len, decryptedKey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("trustedDecryptKey failed with status %d"); CHECK_STATUS2("trustedDecryptKey failed with status %d");
...@@ -668,6 +693,8 @@ void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key, ...@@ -668,6 +693,8 @@ void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key,
if (strncmp(key, decryptedKey, MAX_KEY_LENGTH) != 0) { if (strncmp(key, decryptedKey, MAX_KEY_LENGTH) != 0) {
snprintf(errString, BUF_LEN, "Decrypted key does not match original key"); snprintf(errString, BUF_LEN, "Decrypted key does not match original key");
LOG_ERROR(key);
LOG_ERROR(decryptedKey);
LOG_ERROR(errString); LOG_ERROR(errString);
goto clean; goto clean;
} }
...@@ -680,8 +707,8 @@ void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key, ...@@ -680,8 +707,8 @@ void trustedEncryptKeyAES(int *errStatus, char *errString, const char *key,
} }
void trustedBlsSignMessageAES(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, void trustedBlsSignMessage(int *errStatus, char *errString, uint8_t *encryptedPrivateKey,
uint32_t enc_len, char *_hashX, uint64_t enc_len, char *_hashX,
char *_hashY, char *signature) { char *_hashY, char *signature) {
LOG_DEBUG(__FUNCTION__); LOG_DEBUG(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -693,7 +720,10 @@ void trustedBlsSignMessageAES(int *errStatus, char *errString, uint8_t *encrypte ...@@ -693,7 +720,10 @@ void trustedBlsSignMessageAES(int *errStatus, char *errString, uint8_t *encrypte
SAFE_CHAR_BUF(key, BUF_LEN);SAFE_CHAR_BUF(sig, BUF_LEN); SAFE_CHAR_BUF(key, BUF_LEN);SAFE_CHAR_BUF(sig, BUF_LEN);
int status = AES_decrypt(encryptedPrivateKey, enc_len, key, BUF_LEN); uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, enc_len, key, BUF_LEN, &type, &exportable);
CHECK_STATUS("AES decrypt failed") CHECK_STATUS("AES decrypt failed")
...@@ -723,7 +753,7 @@ void trustedBlsSignMessageAES(int *errStatus, char *errString, uint8_t *encrypte ...@@ -723,7 +753,7 @@ void trustedBlsSignMessageAES(int *errStatus, char *errString, uint8_t *encrypte
} }
void void
trustedGenDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint32_t *enc_len, size_t _t) { trustedGenDkgSecret(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint64_t *enc_len, size_t _t) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -735,16 +765,20 @@ trustedGenDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_s ...@@ -735,16 +765,20 @@ trustedGenDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_s
CHECK_STATUS("gen_dkg_poly failed") CHECK_STATUS("gen_dkg_poly failed")
status = AES_encrypt(dkg_secret, encrypted_dkg_secret, 3 * BUF_LEN); status = AES_encrypt(dkg_secret, encrypted_dkg_secret, 3 * BUF_LEN,
DKG, EXPORTABLE, enc_len);
CHECK_STATUS("SGX AES encrypt DKG poly failed"); CHECK_STATUS("SGX AES encrypt DKG poly failed");
*enc_len = strlen(dkg_secret) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
SAFE_CHAR_BUF(decr_dkg_secret, DKG_BUFER_LENGTH); SAFE_CHAR_BUF(decr_dkg_secret, DKG_BUFER_LENGTH);
uint8_t type = 0;
uint8_t exportable = 0;
status = AES_decrypt(encrypted_dkg_secret, *enc_len, decr_dkg_secret, status = AES_decrypt(encrypted_dkg_secret, *enc_len, decr_dkg_secret,
DKG_BUFER_LENGTH); DKG_BUFER_LENGTH, &type, &exportable);
CHECK_STATUS("aes decrypt dkg poly failed"); CHECK_STATUS("aes decrypt dkg poly failed");
...@@ -764,8 +798,8 @@ trustedGenDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_s ...@@ -764,8 +798,8 @@ trustedGenDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_s
} }
void void
trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, trustedDecryptDkgSecret(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret,
uint32_t enc_len, uint64_t enc_len,
uint8_t *decrypted_dkg_secret) { uint8_t *decrypted_dkg_secret) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -773,8 +807,11 @@ trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_d ...@@ -773,8 +807,11 @@ trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_d
CHECK_STATE(encrypted_dkg_secret); CHECK_STATE(encrypted_dkg_secret);
CHECK_STATE(decrypted_dkg_secret); CHECK_STATE(decrypted_dkg_secret);
uint8_t type;
uint8_t exportable;
int status = AES_decrypt(encrypted_dkg_secret, enc_len, (char *) decrypted_dkg_secret, int status = AES_decrypt(encrypted_dkg_secret, enc_len, (char *) decrypted_dkg_secret,
3072); 3072, &type, &exportable);
CHECK_STATUS2("aes decrypt data - encrypted_dkg_secret failed with status %d") CHECK_STATUS2("aes decrypt data - encrypted_dkg_secret failed with status %d")
...@@ -787,7 +824,7 @@ trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_d ...@@ -787,7 +824,7 @@ trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_d
} }
void trustedSetEncryptedDkgPolyAES(int *errStatus, char *errString, uint8_t *encrypted_poly, uint32_t enc_len) { void trustedSetEncryptedDkgPoly(int *errStatus, char *errString, uint8_t *encrypted_poly, uint64_t enc_len) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
...@@ -795,8 +832,11 @@ void trustedSetEncryptedDkgPolyAES(int *errStatus, char *errString, uint8_t *enc ...@@ -795,8 +832,11 @@ void trustedSetEncryptedDkgPolyAES(int *errStatus, char *errString, uint8_t *enc
memset(getThreadLocalDecryptedDkgPoly(), 0, DKG_BUFER_LENGTH); memset(getThreadLocalDecryptedDkgPoly(), 0, DKG_BUFER_LENGTH);
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encrypted_poly, enc_len, (char *) getThreadLocalDecryptedDkgPoly(), int status = AES_decrypt(encrypted_poly, enc_len, (char *) getThreadLocalDecryptedDkgPoly(),
DKG_BUFER_LENGTH); DKG_BUFER_LENGTH, &type, &exportable);
CHECK_STATUS2("sgx_unseal_data - encrypted_poly failed with status %d") CHECK_STATUS2("sgx_unseal_data - encrypted_poly failed with status %d")
...@@ -807,14 +847,14 @@ void trustedSetEncryptedDkgPolyAES(int *errStatus, char *errString, uint8_t *enc ...@@ -807,14 +847,14 @@ void trustedSetEncryptedDkgPolyAES(int *errStatus, char *errString, uint8_t *enc
LOG_INFO("SGX call completed"); LOG_INFO("SGX call completed");
} }
void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t *encrypted_skey, uint32_t *dec_len, void trustedGetEncryptedSecretShare(int *errStatus, char *errString, uint8_t *encrypted_skey, uint64_t *dec_len,
char *result_str, char *s_shareG2, char *pub_keyB, uint8_t _t, uint8_t _n, char *result_str, char *s_shareG2, char *pub_keyB, uint8_t _t, uint8_t _n,
uint8_t ind) { uint8_t ind) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE INIT_ERROR_STATE
uint32_t enc_len; uint64_t enc_len;
int status; int status;
CHECK_STATE(encrypted_skey); CHECK_STATE(encrypted_skey);
...@@ -824,15 +864,18 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t ...@@ -824,15 +864,18 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t
LOG_DEBUG(__FUNCTION__); LOG_DEBUG(__FUNCTION__);
SAFE_CHAR_BUF(skey, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(skey, BUF_LEN);
SAFE_CHAR_BUF(pub_key_x, BUF_LEN);SAFE_CHAR_BUF(pub_key_y, BUF_LEN); SAFE_CHAR_BUF(pub_key_x, BUF_LEN);SAFE_CHAR_BUF(pub_key_y, BUF_LEN);
trustedGenerateEcdsaKeyAES(&status, errString, encrypted_skey, &enc_len, pub_key_x, pub_key_y); trustedGenerateEcdsaKey(&status, errString, encrypted_skey, &enc_len, pub_key_x, pub_key_y);
CHECK_STATUS("trustedGenerateEcdsaKey failed");
CHECK_STATUS("trustedGenerateEcdsaKeyAES failed"); uint8_t type = 0;
uint8_t exportable = 0;
status = AES_decrypt(encrypted_skey, enc_len, skey, ECDSA_SKEY_LEN); status = AES_decrypt(encrypted_skey, enc_len, skey, BUF_LEN, &type, &exportable);
skey[ECDSA_SKEY_LEN - 1] = 0; skey[ECDSA_SKEY_LEN - 1] = 0;
...@@ -840,13 +883,13 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t ...@@ -840,13 +883,13 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t
*dec_len = enc_len; *dec_len = enc_len;
SAFE_CHAR_BUF(common_key, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(common_key, BUF_LEN);
status = gen_session_key(skey, pub_keyB, common_key); status = gen_session_key(skey, pub_keyB, common_key);
CHECK_STATUS("gen_session_key failed") CHECK_STATUS("gen_session_key failed")
SAFE_CHAR_BUF(s_share, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(s_share, BUF_LEN);
status = calc_secret_share(getThreadLocalDecryptedDkgPoly(), s_share, _t, _n, ind); status = calc_secret_share(getThreadLocalDecryptedDkgPoly(), s_share, _t, _n, ind);
CHECK_STATUS("calc secret share failed") CHECK_STATUS("calc secret share failed")
...@@ -855,7 +898,7 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t ...@@ -855,7 +898,7 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t
status = calc_secret_shareG2(s_share, s_shareG2); status = calc_secret_shareG2(s_share, s_shareG2);
CHECK_STATUS("invalid decr secret share"); CHECK_STATUS("invalid decr secret share");
SAFE_CHAR_BUF(cypher, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(cypher, BUF_LEN);
status=xor_encrypt(common_key, s_share, cypher); status=xor_encrypt(common_key, s_share, cypher);
CHECK_STATUS("xor_encrypt failed") CHECK_STATUS("xor_encrypt failed")
...@@ -872,7 +915,7 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t ...@@ -872,7 +915,7 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t
LOG_INFO("SGX call completed"); LOG_INFO("SGX call completed");
} }
void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint32_t enc_len, void trustedGetPublicShares(int *errStatus, char *errString, uint8_t *encrypted_dkg_secret, uint64_t enc_len,
char *public_shares, char *public_shares,
unsigned _t, unsigned _n) { unsigned _t, unsigned _n) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
...@@ -885,8 +928,11 @@ void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypt ...@@ -885,8 +928,11 @@ void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypt
SAFE_CHAR_BUF(decrypted_dkg_secret, DKG_MAX_SEALED_LEN); SAFE_CHAR_BUF(decrypted_dkg_secret, DKG_MAX_SEALED_LEN);
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encrypted_dkg_secret, enc_len, decrypted_dkg_secret, int status = AES_decrypt(encrypted_dkg_secret, enc_len, decrypted_dkg_secret,
DKG_MAX_SEALED_LEN); DKG_MAX_SEALED_LEN, &type, &exportable);
CHECK_STATUS2("aes decrypt data - encrypted_dkg_secret failed with status %d"); CHECK_STATUS2("aes decrypt data - encrypted_dkg_secret failed with status %d");
...@@ -900,7 +946,7 @@ void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypt ...@@ -900,7 +946,7 @@ void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypt
LOG_INFO("SGX call completed"); LOG_INFO("SGX call completed");
} }
void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_shares, const char *s_share, void trustedDkgVerify(int *errStatus, char *errString, const char *public_shares, const char *s_share,
uint8_t *encryptedPrivateKey, uint64_t enc_len, unsigned _t, int _ind, int *result) { uint8_t *encryptedPrivateKey, uint64_t enc_len, unsigned _t, int _ind, int *result) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
...@@ -910,26 +956,30 @@ void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_sha ...@@ -910,26 +956,30 @@ void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_sha
CHECK_STATE(s_share); CHECK_STATE(s_share);
CHECK_STATE(encryptedPrivateKey); CHECK_STATE(encryptedPrivateKey);
SAFE_CHAR_BUF(skey, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(skey,BUF_LEN);
mpz_t s; mpz_t s;
mpz_init(s); mpz_init(s);
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, ECDSA_SKEY_LEN); uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("AES_decrypt failed (in trustedDkgVerifyAES) with status %d"); CHECK_STATUS2("AES_decrypt failed (in trustedDkgVerifyAES) with status %d");
SAFE_CHAR_BUF(encr_sshare, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(encr_sshare, BUF_LEN);
strncpy(encr_sshare, s_share, ECDSA_SKEY_LEN - 1); strncpy(encr_sshare, s_share, ECDSA_SKEY_LEN - 1);
SAFE_CHAR_BUF(common_key, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(common_key, BUF_LEN);
status = session_key_recover(skey, s_share, common_key); status = session_key_recover(skey, s_share, common_key);
CHECK_STATUS("session_key_recover failed"); CHECK_STATUS("session_key_recover failed");
SAFE_CHAR_BUF(decr_sshare, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(decr_sshare, BUF_LEN);
status=xor_decrypt(common_key, encr_sshare, decr_sshare); status=xor_decrypt(common_key, encr_sshare, decr_sshare);
...@@ -949,9 +999,9 @@ void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_sha ...@@ -949,9 +999,9 @@ void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_sha
LOG_INFO("SGX call completed"); LOG_INFO("SGX call completed");
} }
void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_shares, void trustedCreateBlsKey(int *errStatus, char *errString, const char *s_shares,
uint8_t *encryptedPrivateKey, uint64_t key_len, uint8_t *encr_bls_key, uint8_t *encryptedPrivateKey, uint64_t key_len, uint8_t *encr_bls_key,
uint32_t *enc_bls_key_len) { uint64_t *enc_bls_key_len) {
LOG_INFO(__FUNCTION__); LOG_INFO(__FUNCTION__);
...@@ -961,7 +1011,7 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share ...@@ -961,7 +1011,7 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
CHECK_STATE(encryptedPrivateKey); CHECK_STATE(encryptedPrivateKey);
CHECK_STATE(encr_bls_key); CHECK_STATE(encr_bls_key);
SAFE_CHAR_BUF(skey, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(skey, BUF_LEN);
mpz_t sum; mpz_t sum;
mpz_init(sum); mpz_init(sum);
...@@ -974,8 +1024,12 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share ...@@ -974,8 +1024,12 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
mpz_t bls_key; mpz_t bls_key;
mpz_init(bls_key); mpz_init(bls_key);
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, key_len, skey, ECDSA_SKEY_LEN); int status = AES_decrypt(encryptedPrivateKey, key_len, skey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("aes decrypt failed with status %d"); CHECK_STATUS2("aes decrypt failed with status %d");
skey[ECDSA_SKEY_LEN - 1] = 0; skey[ECDSA_SKEY_LEN - 1] = 0;
...@@ -1035,12 +1089,10 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share ...@@ -1035,12 +1089,10 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
strncpy(key_share + n_zeroes, arr_skey_str, 65 - n_zeroes); strncpy(key_share + n_zeroes, arr_skey_str, 65 - n_zeroes);
key_share[BLS_KEY_LENGTH - 1] = 0; key_share[BLS_KEY_LENGTH - 1] = 0;
status = AES_encrypt(key_share, encr_bls_key, BUF_LEN); status = AES_encrypt(key_share, encr_bls_key, BUF_LEN, BLS, NON_EXPORTABLE, enc_bls_key_len);
CHECK_STATUS2("aes encrypt bls private key failed with status %d "); CHECK_STATUS2("aes encrypt bls private key failed with status %d ");
*enc_bls_key_len = strlen(key_share) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
SET_SUCCESS SET_SUCCESS
clean: clean:
...@@ -1052,7 +1104,7 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share ...@@ -1052,7 +1104,7 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
} }
void void
trustedGetBlsPubKeyAES(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, uint64_t key_len, trustedGetBlsPubKey(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, uint64_t key_len,
char *bls_pub_key) { char *bls_pub_key) {
LOG_DEBUG(__FUNCTION__); LOG_DEBUG(__FUNCTION__);
...@@ -1061,9 +1113,15 @@ trustedGetBlsPubKeyAES(int *errStatus, char *errString, uint8_t *encryptedPrivat ...@@ -1061,9 +1113,15 @@ trustedGetBlsPubKeyAES(int *errStatus, char *errString, uint8_t *encryptedPrivat
CHECK_STATE(bls_pub_key); CHECK_STATE(bls_pub_key);
CHECK_STATE(encryptedPrivateKey); CHECK_STATE(encryptedPrivateKey);
SAFE_CHAR_BUF(skey_hex, ECDSA_SKEY_LEN); SAFE_CHAR_BUF(skey_hex, BUF_LEN);
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, key_len, skey_hex, ECDSA_SKEY_LEN); int status = AES_decrypt(encryptedPrivateKey, key_len, skey_hex, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("AES decrypt failed %d"); CHECK_STATUS2("AES decrypt failed %d");
......
<EnclaveConfiguration> <EnclaveConfiguration>
<ProdID>0</ProdID> <ProdID>0</ProdID>
<ISVSVN>0</ISVSVN> <ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize> <StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x100000000</HeapMaxSize> <HeapMaxSize>0x100000000</HeapMaxSize>
<TCSNum>128</TCSNum> <TCSNum>128</TCSNum>
......
<EnclaveConfiguration> <EnclaveConfiguration>
<ProdID>0</ProdID> <ProdID>0</ProdID>
<ISVSVN>0</ISVSVN> <ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize> <StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x100000000</HeapMaxSize> <HeapMaxSize>0x100000000</HeapMaxSize>
<TCSNum>128</TCSNum> <TCSNum>128</TCSNum>
......
<EnclaveConfiguration> <EnclaveConfiguration>
<ProdID>0</ProdID> <ProdID>0</ProdID>
<ISVSVN>0</ISVSVN> <ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize> <StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x10000000</HeapMaxSize> <HeapMaxSize>0x1000000</HeapMaxSize>
<TCSNum>32</TCSNum> <TCSNum>16</TCSNum>
<TCSMaxNum>32</TCSMaxNum> <TCSMaxNum>16</TCSMaxNum>
<TCSMinPool>32</TCSMinPool> <TCSMinPool>16</TCSMinPool>
<TCSPolicy>0</TCSPolicy> <TCSPolicy>0</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release --> <!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug> <DisableDebug>0</DisableDebug>
......
...@@ -11,14 +11,14 @@ enclave { ...@@ -11,14 +11,14 @@ enclave {
trusted { trusted {
include "sgx_tgmp.h" include "sgx_tgmp.h"
public void trustedEnclaveInit(uint32_t _logLevel); public void trustedEnclaveInit(uint64_t _logLevel);
public void trustedGenerateSEK( public void trustedGenerateSEK(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK, [out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK,
[out] uint32_t *enc_len, [out] uint64_t *enc_len,
[out, count = 65] char* hex_SEK); [out, count = 65] char* hex_SEK);
public void trustedSetSEK( public void trustedSetSEK(
...@@ -26,79 +26,79 @@ enclave { ...@@ -26,79 +26,79 @@ enclave {
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[in, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK); [in, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK);
public void trustedSetSEK_backup( public void trustedSetSEKBackup(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK, [out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK,
[out] uint32_t *enc_len, [out] uint64_t *enc_len,
[in, string] const char* SEK_hex); [in, string] const char* SEK_hex);
public void trustedGenerateEcdsaKeyAES ( public void trustedGenerateEcdsaKey (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
[out] uint32_t *enc_len, [out] uint64_t *enc_len,
[out, count = SMALL_BUF_SIZE] char * pub_key_x, [out, count = SMALL_BUF_SIZE] char * pub_key_x,
[out, count = SMALL_BUF_SIZE] char * pub_key_y); [out, count = SMALL_BUF_SIZE] char * pub_key_y);
public void trustedGetPublicEcdsaKeyAES( public void trustedGetPublicEcdsaKey(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint32_t dec_len, uint64_t dec_len,
[out, count = SMALL_BUF_SIZE] char * pub_key_x, [out, count = SMALL_BUF_SIZE] char * pub_key_x,
[out, count = SMALL_BUF_SIZE] char * pub_key_y); [out, count = SMALL_BUF_SIZE] char * pub_key_y);
public void trustedEcdsaSignAES( public void trustedEcdsaSign(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint32_t enc_len, uint64_t enc_len,
[in, string] const char* hash, [in, string] const char* hash,
[out, count = SMALL_BUF_SIZE] char* sig_r, [out, count = SMALL_BUF_SIZE] char* sig_r,
[out, count = SMALL_BUF_SIZE] char* sig_s, [out, count = SMALL_BUF_SIZE] char* sig_s,
[out] uint8_t* sig_v, [out] uint8_t* sig_v,
int base); int base);
public void trustedEncryptKeyAES ( public void trustedEncryptKey (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] const char* key, [in, count = SMALL_BUF_SIZE] const char* key,
[out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
[out] uint32_t *enc_len); [out] uint64_t *enc_len);
public void trustedDecryptKeyAES ( public void trustedDecryptKey (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint32_t enc_len, uint64_t enc_len,
[out, count = SMALL_BUF_SIZE] char* key ); [out, count = SMALL_BUF_SIZE] char* key );
public void trustedGenDkgSecretAES ( public void trustedGenDkgSecret (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[out, count = 3072] uint8_t* encrypted_dkg_secret, [out, count = 3072] uint8_t* encrypted_dkg_secret,
[out] uint32_t * enc_len, size_t _t); [out] uint64_t * enc_len, size_t _t);
public void trustedDecryptDkgSecretAES ( public void trustedDecryptDkgSecret (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 3050] uint8_t* encrypted_dkg_secret, [in, count = 3050] uint8_t* encrypted_dkg_secret,
uint32_t enc_len, uint64_t enc_len,
[out, count = 3072] uint8_t* decrypted_dkg_secret [out, count = 3072] uint8_t* decrypted_dkg_secret
); );
public void trustedSetEncryptedDkgPolyAES( public void trustedSetEncryptedDkgPoly(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 3050] uint8_t* encrypted_poly, [in, count = 3050] uint8_t* encrypted_poly,
uint32_t enc_len); uint64_t enc_len);
public void trustedGetEncryptedSecretShareAES( public void trustedGetEncryptedSecretShare(
[out]int *errStatus, [out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_skey, [out, count = SMALL_BUF_SIZE] uint8_t *encrypted_skey,
[out] uint32_t* dec_len, [out] uint64_t* dec_len,
[out, count = 193] char* result_str, [out, count = 193] char* result_str,
[out, count = 320] char* s_shareG2, [out, count = 320] char* s_shareG2,
[in, string] char* pub_keyB, [in, string] char* pub_keyB,
...@@ -106,16 +106,16 @@ enclave { ...@@ -106,16 +106,16 @@ enclave {
uint8_t _n, uint8_t _n,
uint8_t ind); uint8_t ind);
public void trustedGetPublicSharesAES( public void trustedGetPublicShares(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 3050] uint8_t* encrypted_dkg_secret, [in, count = 3050] uint8_t* encrypted_dkg_secret,
uint32_t enc_len, uint64_t enc_len,
[out, count = 10000] char* public_shares, [out, count = 10000] char* public_shares,
unsigned _t, unsigned _t,
unsigned _n); unsigned _n);
public void trustedDkgVerifyAES( public void trustedDkgVerify(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, string] const char* public_shares, [in, string] const char* public_shares,
...@@ -126,25 +126,25 @@ enclave { ...@@ -126,25 +126,25 @@ enclave {
int _ind, int _ind,
[out] int* result); [out] int* result);
public void trustedCreateBlsKeyAES( public void trustedCreateBlsKey(
[out]int *errStatus, [out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 6145] const char* s_shares, [in, count = 6145] const char* s_shares,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint64_t key_len, uint64_t key_len,
[out, count = SMALL_BUF_SIZE] uint8_t * encr_bls_key, [out, count = SMALL_BUF_SIZE] uint8_t * encr_bls_key,
[out] uint32_t *enc_bls_key_len); [out] uint64_t *enc_bls_key_len);
public void trustedBlsSignMessageAES ( public void trustedBlsSignMessage (
[out] int *errStatus, [out] int *errStatus,
[out, count = TINY_BUF_SIZE] char* err_string, [out, count = TINY_BUF_SIZE] char* err_string,
[in, count = TINY_BUF_SIZE] uint8_t* encrypted_key, [in, count = TINY_BUF_SIZE] uint8_t* encrypted_key,
uint32_t enc_len, uint64_t enc_len,
[in, string] char* hashX , [in, string] char* hashX ,
[in, string] char* hashY, [in, string] char* hashY,
[out, count = SMALL_BUF_SIZE] char* signature); [out, count = SMALL_BUF_SIZE] char* signature);
public void trustedGetBlsPubKeyAES( public void trustedGetBlsPubKey(
[out]int *errStatus, [out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
......
...@@ -36,6 +36,5 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -36,6 +36,5 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sgxwallet.h" #include "sgxwallet.h"
sgx_launch_token_t token = {0}; sgx_launch_token_t token = {0};
sgx_enclave_id_t eid; sgx_enclave_id_t eid = 0;
sgx_status_t status; int updated = 0;
int updated;
...@@ -47,7 +47,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -47,7 +47,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
extern sgx_enclave_id_t eid; extern sgx_enclave_id_t eid;
extern int updated; extern int updated;
extern sgx_launch_token_t token; extern sgx_launch_token_t token;
extern sgx_status_t status;
#define ENCLAVE_NAME "secure_enclave.signed.so" #define ENCLAVE_NAME "secure_enclave.signed.so"
......
...@@ -109,4 +109,34 @@ extern bool autoconfirm; ...@@ -109,4 +109,34 @@ extern bool autoconfirm;
#define TEST_VALUE "1234567890" #define TEST_VALUE "1234567890"
#define RESTART_BEGIN \
int __ATTEMPTS__ = 0; \
do {\
__ATTEMPTS__++; \
{\
READ_LOCK(initMutex);
#define RESTART_END \
} \
if (status != SGX_SUCCESS || errStatus == 3) { \
spdlog::error(__FUNCTION__); \
spdlog::error("Restarting sgx on status errStatus... {} {}", status, errStatus); \
reinitEnclave(); \
} \
} while ((status != SGX_SUCCESS || errStatus == 3) && __ATTEMPTS__ < 2);
#define RESTART_END_POINTER \
} \
if (status != SGX_SUCCESS || *errStatus == 3) { \
spdlog::error(__FUNCTION__);\
spdlog::error("Restarting sgx on status errStatus... {} {}", status, *errStatus); \
reinitEnclave(); \
} \
} while ((status != SGX_SUCCESS || *errStatus == 3) && __ATTEMPTS__ < 2);
#endif //SGXWALLET_SGXWALLET_COMMON_H #endif //SGXWALLET_SGXWALLET_COMMON_H
...@@ -98,7 +98,7 @@ public: ...@@ -98,7 +98,7 @@ public:
class TestFixtureNoResetFromBackup { class TestFixtureNoResetFromBackup {
public: public:
TestFixtureNoResetFromBackup() { TestFixtureNoResetFromBackup() {
setFullOptions(L_INFO, false, true, true ); setFullOptions(L_INFO, false, true, true);
initAll(L_INFO, false, true); initAll(L_INFO, false, true);
} }
...@@ -123,13 +123,13 @@ public: ...@@ -123,13 +123,13 @@ public:
TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes-key-sig-gen]") { TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes-key-sig-gen]") {
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
vector<uint8_t> encrPrivKey(BUF_LEN, 0); vector <uint8_t> encrPrivKey(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0); vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0); vector<char> pubKeyY(BUF_LEN, 0);
uint32_t encLen = 0; uint64_t encLen = 0;
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedGenerateEcdsaKeyAES(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen, auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen,
pubKeyX.data(), pubKeyX.data(),
pubKeyY.data()); pubKeyY.data());
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
...@@ -141,27 +141,28 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes ...@@ -141,27 +141,28 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes
uint8_t signatureV = 0; uint8_t signatureV = 0;
for (int i=0; i < 50; i++) { for (int i = 0; i < 50; i++) {
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedEcdsaSignAES(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen, status = trustedEcdsaSign(eid, &errStatus, errMsg.data(), encrPrivKey.data(), encLen,
hex.data(), hex.data(),
signatureR.data(), signatureR.data(),
signatureS.data(), &signatureV, 16); signatureS.data(), &signatureV, 16);
}
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
}
} }
TEST_CASE_METHOD(TestFixture, "ECDSA AES key gen", "[ecdsa-aes-key-gen]") { TEST_CASE_METHOD(TestFixture, "ECDSA AES key gen", "[ecdsa-aes-key-gen]") {
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
vector<uint8_t> encrPrivKey(BUF_LEN, 0); vector <uint8_t> encrPrivKey(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0); vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0); vector<char> pubKeyY(BUF_LEN, 0);
uint32_t encLen = 0; uint64_t encLen = 0;
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedGenerateEcdsaKeyAES(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen, auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encrPrivKey.data(), &encLen,
pubKeyX.data(), pubKeyX.data(),
pubKeyY.data()); pubKeyY.data());
...@@ -173,13 +174,14 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES key gen", "[ecdsa-aes-key-gen]") { ...@@ -173,13 +174,14 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES key gen", "[ecdsa-aes-key-gen]") {
TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", "[ecdsa-aes-get-pub-key]") { TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", "[ecdsa-aes-get-pub-key]") {
int errStatus = 0; int errStatus = 0;
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
vector<uint8_t> encPrivKey(BUF_LEN, 0); vector <uint8_t> encPrivKey(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0); vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0); vector<char> pubKeyY(BUF_LEN, 0);
uint32_t encLen = 0;
uint64_t encLen = 0;
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedGenerateEcdsaKeyAES(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(), auto status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), &encLen, pubKeyX.data(),
pubKeyY.data()); pubKeyY.data());
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
...@@ -189,7 +191,7 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", "[ecdsa-aes-get-pub-ke ...@@ -189,7 +191,7 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES get public key", "[ecdsa-aes-get-pub-ke
vector<char> receivedPubKeyY(BUF_LEN, 0); vector<char> receivedPubKeyY(BUF_LEN, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedGetPublicEcdsaKeyAES(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen, status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encPrivKey.data(), encLen,
receivedPubKeyX.data(), receivedPubKeyX.data(),
receivedPubKeyY.data()); receivedPubKeyY.data());
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
...@@ -259,8 +261,7 @@ TEST_CASE_METHOD(TestFixture, "ECDSA key gen API", "[ecdsa-key-gen-api]") { ...@@ -259,8 +261,7 @@ TEST_CASE_METHOD(TestFixture, "ECDSA key gen API", "[ecdsa-key-gen-api]") {
auto keyName = genECDSAKeyAPI(c); auto keyName = genECDSAKeyAPI(c);
Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH); Json::Value sig = c.ecdsaSignMessageHash(10, keyName, SAMPLE_HASH);
for (int i = 0; i <= 20; i++) { for (int i = 0; i <= 20; i++) {
...@@ -287,21 +288,21 @@ TEST_CASE_METHOD(TestFixture, "BLS key encrypt", "[bls-key-encrypt]") { ...@@ -287,21 +288,21 @@ TEST_CASE_METHOD(TestFixture, "BLS key encrypt", "[bls-key-encrypt]") {
TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") { TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") {
vector<uint8_t> encryptedDKGSecret(BUF_LEN, 0); vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint32_t encLen = 0; uint64_t encLen = 0;
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32); auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 32);
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
vector<char> secret(BUF_LEN, 0); vector<char> secret(BUF_LEN, 0);
vector<char> errMsg1(BUF_LEN, 0); vector<char> errMsg1(BUF_LEN, 0);
status = trustedDecryptDkgSecretAES(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(),
encLen, (uint8_t *) secret.data()); encLen, (uint8_t *) secret.data());
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
...@@ -309,17 +310,16 @@ TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") { ...@@ -309,17 +310,16 @@ TEST_CASE_METHOD(TestFixture, "DKG AES gen test", "[dkg-aes-gen]") {
} }
TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares]") { TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares]") {
vector<uint8_t> encryptedDKGSecret(BUF_LEN, 0); vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint32_t encLen = 0; uint64_t encLen = 0;
unsigned t = 32, n = 32; unsigned t = 32, n = 32;
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n); auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, n);
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
...@@ -328,30 +328,30 @@ TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares ...@@ -328,30 +328,30 @@ TEST_CASE_METHOD(TestFixture, "DKG AES public shares test", "[dkg-aes-pub-shares
char colon = ':'; char colon = ':';
vector<char> pubShares(10000, 0); vector<char> pubShares(10000, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedGetPublicSharesAES(eid, &errStatus, errMsg1.data(), status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(),
encryptedDKGSecret.data(), encLen, pubShares.data(), t, n); encryptedDKGSecret.data(), encLen, pubShares.data(), t, n);
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
vector<string> g2Strings = splitString(pubShares.data(), ','); vector <string> g2Strings = splitString(pubShares.data(), ',');
vector<libff::alt_bn128_G2> pubSharesG2; vector <libff::alt_bn128_G2> pubSharesG2;
for (u_int64_t i = 0; i < g2Strings.size(); i++) { for (u_int64_t i = 0; i < g2Strings.size(); i++) {
vector<string> coeffStr = splitString(g2Strings.at(i).c_str(), ':'); vector <string> coeffStr = splitString(g2Strings.at(i).c_str(), ':');
pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr)); pubSharesG2.push_back(TestUtils::vectStringToG2(coeffStr));
} }
vector<char> secret(BUF_LEN, 0); vector<char> secret(BUF_LEN, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedDecryptDkgSecretAES(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen, status = trustedDecryptDkgSecret(eid, &errStatus, errMsg1.data(), encryptedDKGSecret.data(), encLen,
(uint8_t *) secret.data()); (uint8_t *) secret.data());
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
signatures::Dkg dkgObj(t, n); signatures::Dkg dkgObj(t, n);
vector<libff::alt_bn128_Fr> poly = TestUtils::splitStringToFr(secret.data(), colon); vector <libff::alt_bn128_Fr> poly = TestUtils::splitStringToFr(secret.data(), colon);
vector<libff::alt_bn128_G2> pubSharesDkg = dkgObj.VerificationVector(poly); vector <libff::alt_bn128_G2> pubSharesDkg = dkgObj.VerificationVector(poly);
for (uint32_t i = 0; i < pubSharesDkg.size(); i++) { for (uint32_t i = 0; i < pubSharesDkg.size(); i++) {
libff::alt_bn128_G2 el = pubSharesDkg.at(i); libff::alt_bn128_G2 el = pubSharesDkg.at(i);
el.to_affine_coordinates(); el.to_affine_coordinates();
...@@ -364,28 +364,28 @@ TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", "[dkg-aes- ...@@ -364,28 +364,28 @@ TEST_CASE_METHOD(TestFixture, "DKG AES encrypted secret shares test", "[dkg-aes-
vector<char> result(BUF_LEN, 0); vector<char> result(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
uint32_t encLen = 0; uint64_t encLen = 0;
vector<uint8_t> encryptedDKGSecret(BUF_LEN, 0); vector <uint8_t> encryptedDKGSecret(BUF_LEN, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2); auto status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), &encLen, 2);
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
uint64_t enc_len = encLen; uint64_t enc_len = encLen;
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), enc_len); status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg.data(), encryptedDKGSecret.data(), enc_len);
REQUIRE(status == SGX_SUCCESS); REQUIRE(status == SGX_SUCCESS);
REQUIRE(errStatus == SGX_SUCCESS); REQUIRE(errStatus == SGX_SUCCESS);
vector<uint8_t> encrPRDHKey(BUF_LEN, 0); vector <uint8_t> encrPRDHKey(BUF_LEN, 0);
string pub_keyB = SAMPLE_PUBLIC_KEY_B; string pub_keyB = SAMPLE_PUBLIC_KEY_B;
vector<char> s_shareG2(BUF_LEN, 0); vector<char> s_shareG2(BUF_LEN, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &encLen, status = trustedGetEncryptedSecretShare(eid, &errStatus, errMsg.data(), encrPRDHKey.data(), &encLen,
result.data(), result.data(),
s_shareG2.data(), s_shareG2.data(),
(char *) pub_keyB.data(), 2, 2, 1); (char *) pub_keyB.data(), 2, 2, 1);
...@@ -419,8 +419,8 @@ TEST_CASE_METHOD(TestFixture, "DKG_BLS test", "[dkg-bls]") { ...@@ -419,8 +419,8 @@ TEST_CASE_METHOD(TestFixture, "DKG_BLS test", "[dkg-bls]") {
HttpClient client(RPC_ENDPOINT); HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2); StubClient c(client, JSONRPC_CLIENT_V2);
vector<string> ecdsaKeyNames; vector <string> ecdsaKeyNames;
vector<string> blsKeyNames; vector <string> blsKeyNames;
int schainID = TestUtils::randGen(); int schainID = TestUtils::randGen();
int dkgID = TestUtils::randGen(); int dkgID = TestUtils::randGen();
...@@ -440,7 +440,8 @@ TEST_CASE_METHOD(TestFixture, "Delete Bls Key", "[delete-bls-key]") { ...@@ -440,7 +440,8 @@ TEST_CASE_METHOD(TestFixture, "Delete Bls Key", "[delete-bls-key]") {
HttpClient client(RPC_ENDPOINT); HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2); StubClient c(client, JSONRPC_CLIENT_V2);
std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0"; std::string name = "BLS_KEY:SCHAIN_ID:123456789:NODE_ID:0:DKG_ID:0";
libff::alt_bn128_Fr key = libff::alt_bn128_Fr("6507625568967977077291849236396320012317305261598035438182864059942098934847"); libff::alt_bn128_Fr key = libff::alt_bn128_Fr(
"6507625568967977077291849236396320012317305261598035438182864059942098934847");
std::string key_str = TestUtils::stringFromFr(key); std::string key_str = TestUtils::stringFromFr(key);
PRINT_SRC_LINE PRINT_SRC_LINE
c.importBLSKeyShare(key_str, name); c.importBLSKeyShare(key_str, name);
...@@ -473,7 +474,6 @@ TEST_CASE_METHOD(TestFixture, "Get ServerVersion", "[get-server-version]") { ...@@ -473,7 +474,6 @@ TEST_CASE_METHOD(TestFixture, "Get ServerVersion", "[get-server-version]") {
} }
TEST_CASE_METHOD(TestFixtureHTTPS, "Cert request sign", "[cert-sign]") { TEST_CASE_METHOD(TestFixtureHTTPS, "Cert request sign", "[cert-sign]") {
PRINT_SRC_LINE PRINT_SRC_LINE
...@@ -552,7 +552,13 @@ TEST_CASE_METHOD(TestFixture, "DKG API test", "[dkg-api]") { ...@@ -552,7 +552,13 @@ TEST_CASE_METHOD(TestFixture, "DKG API test", "[dkg-api]") {
//wrong verif //wrong verif
Json::Value Skeys = c.getSecretShare(polyName, publicKeys, 2, 2); Json::Value Skeys = c.getSecretShare(polyName, publicKeys, 2, 2);
REQUIRE_NOTHROW(c.getSecretShare(polyName, publicKeys, 2, 2));
REQUIRE(Skeys == c.getSecretShare(polyName, publicKeys, 2, 2));
Json::Value verifVect = c.getVerificationVector(polyName, 2, 2); Json::Value verifVect = c.getVerificationVector(polyName, 2, 2);
REQUIRE_NOTHROW(c.getVerificationVector(polyName, 2, 2));
REQUIRE(verifVect == c.getVerificationVector(polyName, 2, 2));
Json::Value verificationWrongSkeys = c.dkgVerification("", "", "", 2, 2, 1); Json::Value verificationWrongSkeys = c.dkgVerification("", "", "", 2, 2, 1);
REQUIRE(verificationWrongSkeys["status"].asInt() != 0); REQUIRE(verificationWrongSkeys["status"].asInt() != 0);
} }
...@@ -587,8 +593,8 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") { ...@@ -587,8 +593,8 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
Json::Value secretShares[n]; Json::Value secretShares[n];
Json::Value pubBLSKeys[n]; Json::Value pubBLSKeys[n];
Json::Value blsSigShares[n]; Json::Value blsSigShares[n];
vector<string> pubShares(n); vector <string> pubShares(n);
vector<string> polyNames(n); vector <string> polyNames(n);
int schainID = TestUtils::randGen(); int schainID = TestUtils::randGen();
int dkgID = TestUtils::randGen(); int dkgID = TestUtils::randGen();
...@@ -623,7 +629,7 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") { ...@@ -623,7 +629,7 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
} }
int k = 0; int k = 0;
vector<string> secShares(n); vector <string> secShares(n);
for (int i = 0; i < n; i++) for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) { for (int j = 0; j < n; j++) {
...@@ -644,15 +650,16 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") { ...@@ -644,15 +650,16 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
string hash = SAMPLE_HASH; string hash = SAMPLE_HASH;
auto hash_arr = make_shared<array<uint8_t, 32 >>(); auto hash_arr = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) { if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
map<size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map; map <size_t, shared_ptr<BLSPublicKeyShare>> coeffs_pkeys_map;
for (int i = 0; i < t; i++) { for (int i = 0; i < t; i++) {
string endName = polyNames[i].substr(4); string endName = polyNames[i].substr(4);
...@@ -669,43 +676,44 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") { ...@@ -669,43 +676,44 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n); blsSigShares[i] = c.blsSignMessageHash(blsName, hash, t, n);
REQUIRE(blsSigShares[i]["status"] == 0); REQUIRE(blsSigShares[i]["status"] == 0);
shared_ptr<string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString()); shared_ptr <string> sig_share_ptr = make_shared<string>(blsSigShares[i]["signatureShare"].asString());
BLSSigShare sig(sig_share_ptr, i + 1, t, n); BLSSigShare sig(sig_share_ptr, i + 1, t, n);
sigShareSet.addSigShare(make_shared<BLSSigShare>(sig)); sigShareSet.addSigShare(make_shared<BLSSigShare>(sig));
vector<string> pubKey_vect; vector <string> pubKey_vect;
for (uint8_t j = 0; j < 4; j++) { for (uint8_t j = 0; j < 4; j++) {
pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString()); pubKey_vect.push_back(pubBLSKeys[i]["blsPublicKeyShare"][j].asString());
} }
BLSPublicKeyShare pubKey(make_shared<vector<string >>(pubKey_vect), t, n); BLSPublicKeyShare pubKey(make_shared < vector < string >> (pubKey_vect), t, n);
PRINT_SRC_LINE PRINT_SRC_LINE
REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n)); REQUIRE(pubKey.VerifySigWithHelper(hash_arr, make_shared<BLSSigShare>(sig), t, n));
coeffs_pkeys_map[i + 1] = make_shared<BLSPublicKeyShare>(pubKey); coeffs_pkeys_map[i + 1] = make_shared<BLSPublicKeyShare>(pubKey);
} }
shared_ptr<BLSSignature> commonSig = sigShareSet.merge(); shared_ptr <BLSSignature> commonSig = sigShareSet.merge();
BLSPublicKey common_public(make_shared<map<size_t, shared_ptr<BLSPublicKeyShare >>>(coeffs_pkeys_map), t, BLSPublicKey
common_public(make_shared < map < size_t, shared_ptr < BLSPublicKeyShare >>>(coeffs_pkeys_map), t,
n); n);
REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n)); REQUIRE(common_public.VerifySigWithHelper(hash_arr, commonSig, t, n));
} }
TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") { TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
int errStatus = -1; int errStatus = 0;
vector<char> errMsg(BUF_LEN, 0); vector<char> errMsg(BUF_LEN, 0);
uint32_t encLen; uint64_t encLen;
string key = SAMPLE_AES_KEY; string key = SAMPLE_AES_KEY;
vector<uint8_t> encrypted_key(BUF_LEN, 0); vector <uint8_t> encrypted_key(BUF_LEN, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
auto status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen); auto status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key.data(), &encLen);
REQUIRE(status == 0); REQUIRE(status == 0);
REQUIRE(errStatus == 0); REQUIRE(errStatus == 0);
vector<char> decr_key(BUF_LEN, 0); vector<char> decr_key(BUF_LEN, 0);
PRINT_SRC_LINE PRINT_SRC_LINE
status = trustedDecryptKeyAES(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data()); status = trustedDecryptKey(eid, &errStatus, errMsg.data(), encrypted_key.data(), encLen, decr_key.data());
REQUIRE(status == 0); REQUIRE(status == 0);
REQUIRE(errStatus == 0); REQUIRE(errStatus == 0);
...@@ -714,7 +722,7 @@ TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") { ...@@ -714,7 +722,7 @@ TEST_CASE_METHOD(TestFixture, "AES encrypt/decrypt", "[aes-encrypt-decrypt]") {
TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypto]") { TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypto]") {
vector<thread> threads; vector <thread> threads;
int num_threads = 4; int num_threads = 4;
for (int i = 0; i < num_threads; i++) { for (int i = 0; i < num_threads; i++) {
threads.push_back(thread(TestUtils::sendRPCRequest)); threads.push_back(thread(TestUtils::sendRPCRequest));
...@@ -726,10 +734,45 @@ TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypt ...@@ -726,10 +734,45 @@ TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg bls", "[many-threads-crypt
} }
TEST_CASE_METHOD(TestFixture, "First run", "[first-run]") { TEST_CASE_METHOD(TestFixture, "First run", "[first-run]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
try {
PRINT_SRC_LINE
auto keyName = genECDSAKeyAPI(c);
ofstream namefile("/tmp/keyname");
namefile << keyName;
PRINT_SRC_LINE
} catch (JsonRpcException & e)
{
cerr << e.what() << endl;
throw;
}
} }
TEST_CASE_METHOD(TestFixtureNoReset, "Second run", "[second-run]") { TEST_CASE_METHOD(TestFixtureNoReset, "Second run", "[second-run]") {
HttpClient client(RPC_ENDPOINT);
StubClient c(client, JSONRPC_CLIENT_V2);
try {
PRINT_SRC_LINE
string keyName;
ifstream namefile("/tmp/keyname");
getline(namefile, keyName);
Json::Value sig = c.ecdsaSignMessageHash(16, keyName, SAMPLE_HASH);
REQUIRE(sig["status"].asInt() == 0);
Json::Value getPubKey = c.getPublicECDSAKey(keyName);
REQUIRE(getPubKey["status"].asInt() == 0);
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
throw;
}
} }
TEST_CASE_METHOD(TestFixtureNoResetFromBackup, "Backup restore", "[backup-restore]") { TEST_CASE_METHOD(TestFixtureNoResetFromBackup, "Backup restore", "[backup-restore]") {
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment