Unverified Commit ef4d86c5 authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #169 from skalenetwork/bug/SKALE-3213-improve-error-handling

Bug/skale 3213 improve error handling
parents 4c8a3998 b82888f2
...@@ -22,47 +22,44 @@ ...@@ -22,47 +22,44 @@
*/ */
#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.h"
#include "sgxwallet_common.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 "BLSCrypto.h"
#include "ServerInit.h" #include "ServerInit.h"
#include "SGXException.h"
#include "third_party/spdlog/spdlog.h" string *FqToString(libff::alt_bn128_Fq *_fq) {
#include "common.h"
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) {
...@@ -167,32 +164,24 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -167,32 +164,24 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
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);
char yStrArg[BUF_LEN]; SAFE_CHAR_BUF(yStrArg,BUF_LEN);
char signature[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);
...@@ -202,34 +191,23 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -202,34 +191,23 @@ 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);
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 = sgx_status_t status =
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey, trustedBlsSignMessageAES(eid, &errStatus, errMsg.data(), encryptedKey,
sz, xStrArg, yStrArg, signature); sz, xStrArg, yStrArg, signature);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
if (status != SGX_SUCCESS) { string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + hash_with_hint.second;
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) { string sig = signature;
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;
std::string sig = signature;
sig.append(":"); sig.append(":");
sig.append(hint); sig.append(hint);
...@@ -240,34 +218,29 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -240,34 +218,29 @@ 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) {
CHECK_STATE(errStatus);
CHECK_STATE(err_string);
CHECK_STATE(_key);
auto keyArray = make_shared<vector<char>>(BUF_LEN, 0); auto keyArray = make_shared<vector<char>>(BUF_LEN, 0);
auto encryptedKey = make_shared<vector<uint8_t>>(BUF_LEN, 0); auto encryptedKey = make_shared<vector<uint8_t>>(BUF_LEN, 0);
auto errMsg = make_shared<vector<char>>(BUF_LEN, 0);
strncpy(keyArray->data(), _key, BUF_LEN); vector<char> errMsg(BUF_LEN, 0);
*errStatus = -1;
strncpy(keyArray->data(), _key, BUF_LEN);
*errStatus = 0;
unsigned int encryptedLen = 0; unsigned int encryptedLen = 0;
status = trustedEncryptKeyAES(eid, errStatus, errMsg->data(), keyArray->data(), encryptedKey->data(), &encryptedLen); sgx_status_t status = trustedEncryptKeyAES(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(), &encryptedLen);
spdlog::debug("errStatus is {}", *errStatus); HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());
spdlog::debug("errMsg is ", errMsg->data());
if (*errStatus != 0) {
throw SGXException(-666, errMsg->data());
}
if (status != SGX_SUCCESS) {
*errStatus = -1;
return "";
}
std::string result(2 * BUF_LEN, '\0'); string result(2 * BUF_LEN, '\0');
carray2Hex(encryptedKey->data(), encryptedLen, &result.front()); carray2Hex(encryptedKey->data(), encryptedLen, &result.front());
......
...@@ -25,6 +25,8 @@ ...@@ -25,6 +25,8 @@
#include "BLSSignature.h" #include "BLSSignature.h"
#include "BLSutils.h" #include "BLSutils.h"
#include "third_party/spdlog/spdlog.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"
...@@ -35,101 +37,98 @@ ...@@ -35,101 +37,98 @@
#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 +138,21 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( ...@@ -139,31 +138,21 @@ 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);
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_status_t status =
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey, trustedBlsSignMessageAES(eid, &errStatus, errMsg.data(), encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature); encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
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 +160,10 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( ...@@ -171,10 +160,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 +171,17 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr( ...@@ -182,14 +171,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;
......
...@@ -21,25 +21,34 @@ ...@@ -21,25 +21,34 @@
@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 "sgxwallet.h"
#include "SGXException.h"
#include "common.h" #include "common.h"
#include "SGXWalletServer.hpp"
#include "DKGCrypto.h"
#include "BLSCrypto.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 +64,14 @@ vector<string> splitString(const char *coeffs, const char symbol) { ...@@ -55,13 +64,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 +81,7 @@ template<class T> string ConvertToString(T field_elem, int base = 10) { ...@@ -71,7 +81,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 +93,7 @@ string convertHexToDec(const string& hex_str) { ...@@ -83,7 +93,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 +107,7 @@ string convertHexToDec(const string& hex_str) { ...@@ -97,7 +107,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,26 +133,16 @@ string convertG2ToString(const libff::alt_bn128_G2& elem, int base, const string ...@@ -123,26 +133,16 @@ 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;
vector<uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
uint32_t enc_len = 0; uint32_t enc_len = 0;
status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t); vector <uint8_t> encrypted_dkg_secret(BUF_LEN, 0);
if (errStatus != 0) {
spdlog::debug("trustedGenDkgSecret, status {}", errStatus, " err msg ", errMsg.data());
spdlog::debug("in DKGCrypto encr len is {}", enc_len);
throw SGXException(-666, errMsg.data());
}
if (status != 0) {
spdlog::debug("trustedGenDkgSecret, status {}", status, " err msg ", errMsg.data()); sgx_status_t status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
spdlog::debug("in DKGCrypto encr len is {}", enc_len); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
throw SGXException(-666, errMsg.data());
}
uint64_t length = enc_len;; uint64_t length = enc_len;;
...@@ -154,77 +154,65 @@ string gen_dkg_poly(int _t) { ...@@ -154,77 +154,65 @@ string gen_dkg_poly(int _t) {
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 (!hex2carray2(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) {
throw SGXException(-666, errMsg.data());
}
if (status != 0) {
throw SGXException(-666, errMsg.data());
}
spdlog::debug("err msg is {}", errMsg.data());
spdlog::debug("public_shares:"); sgx_status_t status = trustedGetPublicSharesAES(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), encLen,
spdlog::debug("{}", pubShares.data());; pubShares.data(), t, n);
spdlog::debug("trustedGetPublicShares status: {}", errStatus); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
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);
int errStatus = 0; int errStatus = 0;
uint64_t encLen = 0; uint64_t encLen = 0;
vector<uint8_t> encrDKGPoly(BUF_LEN, 0); vector <uint8_t> encrDKGPoly(BUF_LEN, 0);
if (!hex2carray2(_encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) { if (!hex2carray2(_encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) {
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 = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
if (status != SGX_SUCCESS || errStatus != 0) {
throw SGXException(-666, 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; uint32_t decLen;
vector<char> currentShare(193, 0); vector<char> currentShare(193, 0);
vector<char> sShareG2(320, 0); vector<char> sShareG2(320, 0);
...@@ -237,12 +225,9 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol ...@@ -237,12 +225,9 @@ 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 = trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1); currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
if (errStatus != 0) {
throw SGXException(-666, errMsg1.data());
}
spdlog::debug("cur_share is {}", currentShare.data()); spdlog::debug("cur_share is {}", currentShare.data());
...@@ -262,7 +247,7 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol ...@@ -262,7 +247,7 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol
SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data()); SGXWalletServer::writeDataToDB(shareG2_name, sShareG2.data());
spdlog::debug("errMsg: {}", errMsg1.data());
} }
return result; return result;
...@@ -270,96 +255,88 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol ...@@ -270,96 +255,88 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol
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];
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key)) { 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 = trustedDkgVerifyAES(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
ind, &result);
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
throw SGXException(-666, errMsg);
}
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");
char errMsg[BUF_LEN]; CHECK_STATE(s_shares);
CHECK_STATE(encryptedKeyHex);
vector<char> errMsg(BUF_LEN,0);
int errStatus = 0; int errStatus = 0;
uint64_t decKeyLen; uint64_t decKeyLen;
uint8_t encr_bls_key[BUF_LEN]; SAFE_UINT8_BUF(encr_bls_key,BUF_LEN);
memset(encr_bls_key, 0, BUF_LEN); SAFE_UINT8_BUF(encr_key,BUF_LEN);
uint8_t encr_key[BUF_LEN];
memset(encr_key, 0, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key)) { if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
uint32_t enc_bls_len = 0; uint32_t enc_bls_len = 0;
trustedCreateBlsKeyAES(eid, &errStatus, errMsg, s_shares, encr_key, decKeyLen, encr_bls_key, &enc_bls_len); sgx_status_t status = trustedCreateBlsKeyAES(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key,
&enc_bls_len);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
if (errStatus != 0) { SAFE_CHAR_BUF(hexBLSKey,2 * BUF_LEN)
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); carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey);
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; uint64_t decKeyLen;
uint8_t encrKey[BUF_LEN];
SAFE_UINT8_BUF(encrKey, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encrKey)) { 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); sgx_status_t status = trustedGetBlsPubKeyAES(eid, &errStatus, errMsg1.data(), encrKey, decKeyLen, pubKey);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
if (errStatus != 0) { vector <string> pubKeyVect = splitString(pubKey, ':');
spdlog::error(string(errMsg1) + " . Status is {}", errStatus);
throw SGXException(ERROR_IN_ENCLAVE, "Failed to get BLS public key in enclave");
}
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 +344,15 @@ vector<string> GetBLSPubKey(const char *encryptedKeyHex) { ...@@ -367,15 +344,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 +385,7 @@ vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) { ...@@ -408,7 +385,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 +394,34 @@ vector<string> calculateAllBlsPublicKeys(const vector<string>& public_shares) { ...@@ -417,37 +394,34 @@ 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;
uint8_t encryptedDHKey[BUF_LEN]; SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN);
if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey)) { 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);
if (errStatus != 0) { sgx_status_t status = trustedDecryptKeyAES(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
throw SGXException(errStatus, "decrypt key failed in enclave"); 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
...@@ -48,22 +48,20 @@ void fillRandomBuffer(vector<unsigned char> &_buffer) { ...@@ -48,22 +48,20 @@ 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);
uint32_t enc_len = 0; uint32_t enc_len = 0;
status = trustedGenerateEcdsaKeyAES(eid, &errStatus, sgx_status_t status = trustedGenerateEcdsaKeyAES(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());
if (status != SGX_SUCCESS || errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data());
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);
...@@ -99,18 +97,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) { ...@@ -99,18 +97,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
status = trustedGetPublicEcdsaKeyAES(eid, &errStatus, sgx_status_t status = trustedGetPublicEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data()); errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
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 +114,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) { ...@@ -123,6 +114,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,13 +162,16 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur ...@@ -166,13 +162,16 @@ 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;
...@@ -182,22 +181,16 @@ vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *ha ...@@ -182,22 +181,16 @@ vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *ha
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
status = trustedEcdsaSignAES(eid, &errStatus, sgx_status_t status = trustedEcdsaSignAES(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);
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());
......
...@@ -54,32 +54,18 @@ void create_test_key() { ...@@ -54,32 +54,18 @@ void create_test_key() {
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
uint32_t enc_len; uint32_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 = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len);
if (status != SGX_SUCCESS) {
cerr << "encrypt test key failed with status " << status << endl;
throw SGXException(status, errMsg.data());
}
if (errStatus != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
cerr << "encrypt test key failed with status " << errStatus << endl;
throw SGXException(errStatus, errMsg.data());
}
vector<char> hexEncrKey(2 * enc_len + 1, 0); vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_key, enc_len, hexEncrKey.data()); carray2Hex(encrypted_key, enc_len, hexEncrKey.data());
uint64_t test_len;
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());
} }
...@@ -88,8 +74,9 @@ shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) { ...@@ -88,8 +74,9 @@ shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &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; uint64_t len;
if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data())) { if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data())) {
spdlog::error("wrong test key"); spdlog::error("Corrupt test key is LevelDB");
exit(-1); exit(-1);
} }
...@@ -101,28 +88,20 @@ shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) { ...@@ -101,28 +88,20 @@ shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) {
uint32_t l = len; uint32_t l = len;
status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l, SEK.c_str()); sgx_status_t 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);
}
if (err_status != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
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()); status = trustedDecryptKeyAES(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data());
if (status != SGX_SUCCESS || err_status != 0) {
spdlog::error("Failed to decrypt test key"); HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
spdlog::error(errMsg.data());
exit(-1);
}
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);
} }
...@@ -137,20 +116,14 @@ void gen_SEK() { ...@@ -137,20 +116,14 @@ void gen_SEK() {
vector <uint8_t> encrypted_SEK(1024, 0); vector <uint8_t> encrypted_SEK(1024, 0);
uint32_t enc_len = 0; uint32_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); sgx_status_t status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK);
if (status != SGX_SUCCESS) { HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
throw SGXException(status, errMsg.data());
}
if (err_status != 0) {
throw SGXException(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");
...@@ -187,29 +160,25 @@ void gen_SEK() { ...@@ -187,29 +160,25 @@ void gen_SEK() {
create_test_key(); create_test_key();
} }
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)) {
throw SGXException(INVALID_HEX, "Invalid encrypted SEK Hex"); throw SGXException(INVALID_HEX, "Invalid encrypted SEK Hex");
} }
status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK); sgx_status_t status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK);
if (status != SGX_SUCCESS) {
cerr << "RPCException thrown" << endl; HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
throw SGXException(status, errMsg.data());
}
if (err_status != 0) {
cerr << "RPCException thrown" << endl;
throw SGXException(err_status, errMsg.data());
}
} }
#include "experimental/filesystem" #include "experimental/filesystem"
...@@ -218,7 +187,6 @@ void trustedSetSEK(shared_ptr <string> hex_encrypted_SEK) { ...@@ -218,7 +187,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");
...@@ -274,7 +242,7 @@ void initSEK() { ...@@ -274,7 +242,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
......
...@@ -425,7 +425,7 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J ...@@ -425,7 +425,7 @@ 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 s = getSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n);
result["secretShare"] = s; result["secretShare"] = s;
result["SecretShare"] = s; result["SecretShare"] = s;
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
...@@ -489,7 +489,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string ...@@ -489,7 +489,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 {
...@@ -519,7 +519,7 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) ...@@ -519,7 +519,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);
} }
......
...@@ -81,7 +81,7 @@ void initEnclave(uint32_t _logLevel) { ...@@ -81,7 +81,7 @@ void initEnclave(uint32_t _logLevel) {
spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG); spdlog::info("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG);
status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token, sgx_status_t status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token,
&updated, &eid, 0); &updated, &eid, 0);
if (status != SGX_SUCCESS) { if (status != SGX_SUCCESS) {
...@@ -97,6 +97,7 @@ void initEnclave(uint32_t _logLevel) { ...@@ -97,6 +97,7 @@ 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, _logLevel);
if (status != SGX_SUCCESS) { if (status != SGX_SUCCESS) {
spdlog::error("trustedEnclaveInit failed: {}", status); spdlog::error("trustedEnclaveInit failed: {}", status);
exit(1); exit(1);
......
1.58.0 1.58.1
\ 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"
...@@ -56,4 +58,26 @@ inline std::string className(const std::string &prettyFunction) { ...@@ -56,4 +58,26 @@ inline std::string className(const std::string &prettyFunction) {
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__);
#endif //SGXWALLET_COMMON_H #endif //SGXWALLET_COMMON_H
...@@ -37,5 +37,4 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -37,5 +37,4 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
sgx_launch_token_t token = {0}; sgx_launch_token_t token = {0};
sgx_enclave_id_t eid; sgx_enclave_id_t eid;
sgx_status_t status;
int updated; 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"
......
...@@ -147,9 +147,10 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes ...@@ -147,9 +147,10 @@ TEST_CASE_METHOD(TestFixture, "ECDSA AES keygen and signature test", "[ecdsa-aes
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);
}
} }
...@@ -691,7 +692,7 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") { ...@@ -691,7 +692,7 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG test", "[aes-dkg]") {
} }
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; uint32_t encLen;
string key = SAMPLE_AES_KEY; string key = SAMPLE_AES_KEY;
......
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