Unverified Commit baaf17c7 authored by Oleh Nikolaiev's avatar Oleh Nikolaiev Committed by GitHub

Merge pull request #102 from skalenetwork/feature/SKALE-2002-backup

Feature/skale 2002 backup
parents 343ffc80 e06fc917
......@@ -56,7 +56,6 @@
std::string *FqToString(libff::alt_bn128_Fq *_fq) {
mpz_t t;
mpz_init(t);
......@@ -82,7 +81,6 @@ int char2int(char _input) {
void carray2Hex(const unsigned char *d, int _len, char *_hexArray) {
char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
......@@ -92,13 +90,11 @@ void carray2Hex(const unsigned char *d, int _len, char *_hexArray) {
}
_hexArray[_len * 2] = 0;
}
bool hex2carray(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin) {
int len = strnlen(_hex, 2 * BUF_LEN);
......@@ -119,12 +115,10 @@ bool hex2carray(const char *_hex, uint64_t *_bin_len,
}
return true;
}
bool hex2carray2(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin, const int _max_length) {
int len = strnlen(_hex, _max_length);//2 * BUF_LEN);
......@@ -145,12 +139,10 @@ bool hex2carray2(const char *_hex, uint64_t *_bin_len,
}
return true;
}
bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) {
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared<array<uint8_t, 32>>();
......@@ -161,9 +153,6 @@ bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t
throw SGXException(INVALID_HEX, "Invalid hash");
}
auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
......@@ -184,7 +173,6 @@ 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, size_t _signerIndex,
char *_sig) {
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared<array<uint8_t, 32>>();
......@@ -195,8 +183,6 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
throw SGXException(INVALID_HEX, "Invalid hash");
}
// auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
//
// auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
......@@ -243,7 +229,6 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
size_t sz = 0;
uint8_t encryptedKey[BUF_LEN];
bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey);
......@@ -257,17 +242,14 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey,
sz, xStrArg, yStrArg, signature);
if (status != SGX_SUCCESS) {
cerr << "SGX enclave call to trustedBlsSignMessage failed:" << status << 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(":");
......@@ -289,12 +271,7 @@ 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, size_t _signerIndex,
char *_sig) {
if (!encryptKeys) {
return sign(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
} else {
return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
}
return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _signerIndex, _sig);
}
char *encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {
......@@ -331,8 +308,6 @@ char *encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key)
}
char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encryptedKey) {
*errStatus = -1;
uint64_t decodedLen = 0;
......@@ -345,7 +320,6 @@ char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encry
char *plaintextKey = (char *) calloc(BUF_LEN, 1);
//status = trustedDecryptKey(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
status = trustedDecryptKeyAES(eid, errStatus, errMsg, decoded, decodedLen, plaintextKey);
if (status != SGX_SUCCESS) {
......@@ -357,5 +331,4 @@ char *decryptBLSKeyShareFromHex(int *errStatus, char *errMsg, const char *_encry
}
return plaintextKey;
}
......@@ -39,7 +39,6 @@
std::string *stringFromFq(libff::alt_bn128_Fq*_fq) {
mpz_t t;
mpz_init(t);
......@@ -54,13 +53,10 @@ std::string *stringFromFq(libff::alt_bn128_Fq*_fq) {
}
std::string *stringFromG1(libff::alt_bn128_G1 *_g1) {
auto sX = stringFromFq(&_g1->X);
auto sY = stringFromFq(&_g1->Y);
auto sZ = stringFromFq(&_g1->Z);
auto sG1 = new std::string(*sX + ":" + *sY + ":" + *sZ);
delete(sX);
......@@ -68,7 +64,6 @@ std::string *stringFromG1(libff::alt_bn128_G1 *_g1) {
delete(sZ);
return sG1;
}
......@@ -105,9 +100,6 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
size_t _signerIndex) {
shared_ptr<signatures::Bls> obj;
// if (_signerIndex == 0) {
// BOOST_THROW_EXCEPTION(runtime_error("Zero signer index"));
// }
if (hash_byte_arr == nullptr) {
std::cerr << "Hash is null" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Hash is null"));
......@@ -121,7 +113,6 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
int errStatus = 0;
string* xStr = stringFromFq(&(hash_with_hint.first.X));
if (xStr == nullptr) {
......@@ -136,7 +127,6 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
}
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
......@@ -152,7 +142,6 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
size_t sz = 0;
uint8_t encryptedKey[BUF_LEN];
bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey);
......@@ -168,17 +157,13 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
trustedBlsSignMessage(eid, &errStatus, errMsg, encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
// strncpy(signature, "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855", 1024);
printf("sig is: %s\n", signature);
if (status != SGX_SUCCESS) {
gmp_printf("SGX enclave call to trustedBlsSignMessage failed: 0x%04x\n", status);
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 ));
return nullptr;
......@@ -190,137 +175,26 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
BOOST_THROW_EXCEPTION(runtime_error("Signature is too short:" + to_string(sigLen)));
}
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second;
std::string sig = signature;
sig.append(":");
sig.append(hint);
return sig;
}
std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex) {
/* shared_ptr<signatures::Bls> obj;
if (_signerIndex == 0) {
BOOST_THROW_EXCEPTION(runtime_error("Zero signer index"));
}
if (hash_byte_arr == nullptr) {
BOOST_THROW_EXCEPTION(runtime_error("Hash is null"));
}
obj = make_shared<signatures::Bls>(
signatures::Bls(requiredSigners, totalSigners));
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint =
obj->HashtoG1withHint(hash_byte_arr);
int errStatus = 0;
string* xStr = stringFromFq(&(hash_with_hint.first.X));
if (xStr == nullptr) {
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
string* yStr = stringFromFq(&(hash_with_hint.first.Y));
if (xStr == nullptr) {
BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
}
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
char xStrArg[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(yStrArg, yStr->c_str(), BUF_LEN);
size_t sz = 0;
uint8_t encryptedKey[BUF_LEN];
bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey);
if (!result) {
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
}
cerr << "Key is " + *encryptedKeyHex << endl;
// sgx_status_t status =
// trustedBlsSignMessage(eid, &errStatus, errMsg, encryptedKey,
// encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
strncpy(signature, "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855", 1024);
printf("---: %s\n", signature);
// 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 ));
// return nullptr;
// }
int sigLen;
if ((sigLen = strnlen(signature, 10)) < 10) {
BOOST_THROW_EXCEPTION(runtime_error("Signature too short:" + to_string(sigLen)));
}
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second;
auto sig = make_shared<string>(signature);
sig->append(":");
sig->append(hint);*/
std::string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
auto sig = make_shared<string>(signature);
//BLSSigShare* sig_test = new BLSSigShare(sig, _signerIndex, requiredSigners, totalSigners);
//std::string hello = "hello";
//std::cout << "HINT " << *((void**)&(sig_test->hint)) << std::endl;
//std::shared_ptr<BLSSigShare> s; s.reset( sig_test );//(sig, _signerIndex, requiredSigners,
//totalSigners);
std::shared_ptr<BLSSigShare> s = std::make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners,
totalSigners);
return s;
}
\ No newline at end of file
}
......@@ -47,7 +47,6 @@ shared_ptr<jsonrpc::HttpServer> CSRManagerServer::hs3 = nullptr;
CSRManagerServer::CSRManagerServer(AbstractServerConnector &connector,
serverVersion_t type) : abstractCSRManagerServer(connector, type) {}
Json::Value getUnsignedCSRsImpl() {
spdlog::info(__FUNCTION__);
INIT_RESULT(result)
......@@ -137,4 +136,4 @@ int CSRManagerServer::initCSRManagerServer() {
spdlog::info("CSR manager server started on port {}", BASE_PORT + 2);
}
return 0;
};
\ No newline at end of file
};
......@@ -32,14 +32,10 @@
#include "abstractCSRManagerServer.h"
#include "LevelDB.h"
using namespace jsonrpc;
using namespace std;
class CSRManagerServer : public abstractCSRManagerServer {
recursive_mutex m;
static shared_ptr<HttpServer> hs3;
......
......@@ -83,10 +83,8 @@ string gen_dkg_poly(int _t) {
uint32_t enc_len = 0;
if (!encryptKeys)
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
else
status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
status = trustedGenDkgSecretAES(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
if (errStatus != 0) {
throw SGXException(-666, errMsg.data());
}
......@@ -95,9 +93,7 @@ string gen_dkg_poly(int _t) {
spdlog::debug("in DKGCrypto encr len is {}", enc_len);
uint64_t length = DKG_MAX_SEALED_LEN;
if (encryptKeys) {
length = enc_len;
}
length = enc_len;
vector<char> hexEncrPoly(2 * length + 1, 0);
CHECK_STATE(encrypted_dkg_secret.size() >= length);
......@@ -108,15 +104,12 @@ string gen_dkg_poly(int _t) {
}
vector<vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n) {
vector<char> errMsg1(BUF_LEN, 0);
int errStatus = 0;
spdlog::debug("got encr poly size {}", char_traits<char>::length(encryptedPolyHex));
vector<char> pubShares(10000, 0);
uint64_t encLen = 0;
......@@ -127,26 +120,16 @@ vector<vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
}
spdlog::debug("hex_encr_poly length is {}", strlen(encryptedPolyHex));
spdlog::debug("enc len {}", encLen);
status = trustedGetPublicSharesAES(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen,
pubShares.data(), t, n);
uint32_t len = 0;
if (!encryptKeys)
status = trustedGetPublicShares(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), len, pubShares.data(), t,
n);
else {
status = trustedGetPublicSharesAES(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), encLen,
pubShares.data(), t, n);
}
if (errStatus != 0) {
throw SGXException(-666, errMsg1.data());
}
spdlog::debug("err msg is {}", errMsg1.data());
spdlog::debug("public_shares:");
......@@ -166,24 +149,18 @@ vector<vector<string>> get_verif_vect(const char *encryptedPolyHex, int t, int n
string trustedGetSecretShares(const string &_polyName, const char *_encryptedPolyHex, const vector<string> &_publicKeys,
int _t,
int _n) {
vector<char> errMsg1(BUF_LEN, 0);
vector<char> hexEncrKey(BUF_LEN, 0);
int errStatus = 0;
uint64_t encLen = 0;
vector<uint8_t> encrDKGPoly(BUF_LEN, 0);
if (!hex2carray2(_encryptedPolyHex, &encLen, encrDKGPoly.data(), 6100)) {
throw SGXException(INVALID_HEX, "Invalid encryptedPolyHex");
}
if (!encryptKeys)
status = trustedSetEncryptedDkgPoly(eid, &errStatus, errMsg1.data(), encrDKGPoly.data());
else
status = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), &encLen);
status = trustedSetEncryptedDkgPolyAES(eid, &errStatus, errMsg1.data(), encrDKGPoly.data(), &encLen);
if (status != SGX_SUCCESS || errStatus != 0) {
throw SGXException(-666, errMsg1.data());
......@@ -191,7 +168,6 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol
string result;
for (int i = 0; i < _n; i++) {
vector<uint8_t> encryptedSkey(BUF_LEN, 0);
uint32_t decLen;
......@@ -206,13 +182,9 @@ string trustedGetSecretShares(const string &_polyName, const char *_encryptedPol
spdlog::debug("pubKeyB is {}", pub_keyB);
if (!encryptKeys)
trustedGetEncryptedSecretShare(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1);
else
trustedGetEncryptedSecretShareAES(eid, &errStatus, errMsg1.data(), encryptedSkey.data(), &decLen,
currentShare.data(), sShareG2.data(), pubKeyB.data(), _t, _n, i + 1);
if (errStatus != 0) {
throw SGXException(-666, errMsg1.data());
}
......@@ -261,11 +233,7 @@ verifyShares(const char *publicShares, const char *encr_sshare, const char *encr
memset(pshares, 0, 8193);
strncpy(pshares, publicShares, strlen(publicShares));
if (!encryptKeys)
trustedDkgVerify(eid, &errStatus, errMsg, pshares, encr_sshare, encr_key, decKeyLen, t, ind, &result);
else
trustedDkgVerifyAES(eid, &errStatus, errMsg, pshares, encr_sshare, encr_key, decKeyLen, t, ind, &result);
trustedDkgVerifyAES(eid, &errStatus, errMsg, pshares, encr_sshare, encr_key, decKeyLen, t, ind, &result);
if (result == 2) {
throw SGXException(INVALID_HEX, "Invalid public shares");
......@@ -278,10 +246,8 @@ verifyShares(const char *publicShares, const char *encr_sshare, const char *encr
}
bool CreateBLSShare(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) {
spdlog::debug("ENTER CreateBLSShare");
// char* errMsg1 = (char*) calloc(1024,1);
char errMsg[BUF_LEN];
int errStatus = 0;
......@@ -296,33 +262,24 @@ bool CreateBLSShare(const string &blsKeyName, const char *s_shares, const char *
uint32_t enc_bls_len = 0;
if (!encryptKeys)
trustedCreateBlsKey(eid, &errStatus, errMsg, s_shares, encr_key, decKeyLen, encr_bls_key, &enc_bls_len);
else
trustedCreateBlsKeyAES(eid, &errStatus, errMsg, s_shares, encr_key, decKeyLen, encr_bls_key, &enc_bls_len);
trustedCreateBlsKeyAES(eid, &errStatus, errMsg, s_shares, encr_key, decKeyLen, encr_bls_key, &enc_bls_len);
if (errStatus != 0) {
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);
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey);
return true;
}
}
vector<string> GetBLSPubKey(const char *encryptedKeyHex) {
char errMsg1[BUF_LEN];
int errStatus = 0;
......@@ -336,10 +293,8 @@ vector<string> GetBLSPubKey(const char *encryptedKeyHex) {
char pubKey[320];
spdlog::debug("decKeyLen is {}", decKeyLen);
if (!encryptKeys)
trustedGetBlsPubKey(eid, &errStatus, errMsg1, encrKey, decKeyLen, pubKey);
else
trustedGetBlsPubKeyAES(eid, &errStatus, errMsg1, encrKey, decKeyLen, pubKey);
trustedGetBlsPubKeyAES(eid, &errStatus, errMsg1, encrKey, decKeyLen, pubKey);
if (errStatus != 0) {
spdlog::error(string(errMsg1) + " . Status is {}", errStatus);
throw SGXException(ERROR_IN_ENCLAVE, "Failed to get BLS public key in enclave");
......@@ -355,7 +310,6 @@ vector<string> GetBLSPubKey(const char *encryptedKeyHex) {
}
string decryptDHKey(const string &polyName, int ind) {
vector<char> errMsg1(1024, 0);
int errStatus = 0;
......@@ -374,13 +328,10 @@ string decryptDHKey(const string &polyName, int ind) {
spdlog::debug("encr DH key length is {}", dhEncLen);
spdlog::debug("hex encr DH key length is {}", hexEncrKeyPtr->length());
char DHKey[ECDSA_SKEY_LEN];
if (!encryptKeys)
trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
else
trustedDecryptKeyAES(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
trustedDecryptKeyAES(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
if (errStatus != 0) {
throw SGXException(/*ERROR_IN_ENCLAVE*/ errStatus, "decrypt key failed in enclave");
}
......
......@@ -50,7 +50,6 @@ string concatPubKeyWith0x(char *pub_key_x, char *pub_key_y) {
return result;
}
void fillRandomBuffer(vector<unsigned char> &_buffer) {
ifstream devRandom("/dev/urandom", ios::in | ios::binary);
devRandom.exceptions(ifstream::failbit | ifstream::badbit);
......@@ -67,17 +66,9 @@ vector <string> genECDSAKey() {
uint32_t enc_len = 0;
// status = trustedGenerateEcdsaKeyAES(eid, &errStatus,
// errMsg.data(), encr_pr_key.data(), &enc_len,
// pub_key_x.data(), pub_key_y.data());
if (!encryptKeys)
status = trustedGenerateEcdsaKey(eid, &errStatus, errMsg.data(), encr_pr_key.data(),
&enc_len, pub_key_x.data(), pub_key_y.data());
else
status = trustedGenerateEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
status = trustedGenerateEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
if (status != SGX_SUCCESS || errStatus != 0) {
spdlog::error("RPCException thrown with status {}", status);
......@@ -90,7 +81,6 @@ vector <string> genECDSAKey() {
keys.at(0) = hexEncrKey.data();
keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data());
vector<unsigned char> randBuffer(32, 0);
fillRandomBuffer(randBuffer);
......@@ -106,7 +96,6 @@ vector <string> genECDSAKey() {
}
string getECDSAPubKey(const char *_encryptedKeyHex) {
vector<char> errMsg(BUF_LEN, 0);
vector<char> pubKeyX(BUF_LEN, 0);
vector<char> pubKeyY(BUF_LEN, 0);
......@@ -119,15 +108,9 @@ string getECDSAPubKey(const char *_encryptedKeyHex) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
}
// status = trustedGetPublicEcdsaKeyAES(eid, &errStatus,
// errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
status = trustedGetPublicEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
if (!encryptKeys)
status = trustedGetPublicEcdsaKey(eid, &errStatus, errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(),
pubKeyY.data());
else
status = trustedGetPublicEcdsaKeyAES(eid, &errStatus,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
if (errStatus != 0) {
throw SGXException(-666, errMsg.data());
}
......@@ -154,7 +137,6 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur
domain_parameters_load_curve(curve, secp256k1);
point publicKey = point_init();
mpz_t msgMpz;
mpz_init(msgMpz);
if (mpz_set_str(msgMpz, hashHex, 16) == -1) {
......@@ -180,7 +162,6 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur
signature_free(sig);
return result;
}
vector <string> ecdsaSignHash(const char *encryptedKeyHex, const char *hashHex, int base) {
......@@ -205,30 +186,16 @@ vector <string> ecdsaSignHash(const char *encryptedKeyHex, const char *hashHex,
pubKeyStr = getECDSAPubKey(encryptedKeyHex);
// status = trustedEcdsaSignAES(eid, &errStatus,
// errMsg.data(), encryptedKey.data(), decLen, (unsigned char *) hashHex,
// signatureR.data(),
// signatureS.data(), &signatureV, base);
status = trustedEcdsaSignAES(eid, &errStatus,
errMsg.data(), encryptedKey.data(), decLen, (unsigned char *) hashHex,
signatureR.data(),
signatureS.data(), &signatureV, base);
if (!encryptKeys) {
status = trustedEcdsaSign(eid, &errStatus, errMsg.data(),
encryptedKey.data(), ECDSA_ENCR_LEN, (unsigned char *) hashHex,
signatureR.data(),
signatureS.data(), &signatureV, base);
} else
status = trustedEcdsaSignAES(eid, &errStatus,
errMsg.data(), encryptedKey.data(), decLen, (unsigned char *) hashHex,
signatureR.data(),
signatureS.data(), &signatureV, base);
if (errStatus != 0) {
exception = make_shared<SGXException>(666, errMsg.data());
goto clean;
}
if (status != SGX_SUCCESS) {
spdlog::error("failed to sign {}", status);
exception = make_shared<SGXException>(666, "failed to sign");
......@@ -250,7 +217,6 @@ vector <string> ecdsaSignHash(const char *encryptedKeyHex, const char *hashHex,
goto clean;
}
clean:
if (exception)
......
......@@ -29,7 +29,6 @@ void Exception::logNested(const std::exception &e, int level)
{
string prefix;
if (level == 0) {
prefix = "!Exception:";
} else {
......@@ -46,4 +45,4 @@ void Exception::logNested(const std::exception &e, int level)
} catch(const std::exception& e) {
logNested(e, level + 1);
} catch(...) {}
};
\ No newline at end of file
};
......@@ -39,19 +39,12 @@
#include "spdlog/spdlog.h"
#include "common.h"
using namespace leveldb;
static WriteOptions writeOptions;
static ReadOptions readOptions;
std::shared_ptr<string> LevelDB::readString(const string &_key) {
std::lock_guard<std::recursive_mutex> lock(mutex);
auto result = std::make_shared<string>();
......@@ -62,10 +55,7 @@ std::shared_ptr<string> LevelDB::readString(const string &_key) {
auto status = db->Get(readOptions, _key, &*result);
spdlog::debug("key to read from db: {}",_key );
//std::cerr << "key to read from db: " << _key << std::endl;
spdlog::debug("key to read from db: {}",_key );
throwExceptionOnError(status);
......@@ -76,22 +66,17 @@ std::shared_ptr<string> LevelDB::readString(const string &_key) {
}
void LevelDB::writeString(const string &_key, const string &_value) {
std::lock_guard<std::recursive_mutex> lock(mutex);
auto status = db->Put(writeOptions, Slice(_key), Slice(_value));
throwExceptionOnError(status);
spdlog::debug("written key: {}",_key );
// std::cerr << "written key " << _key << std::endl;
spdlog::debug("written key: {}",_key );
}
void LevelDB::deleteDHDKGKey (const string &_key) {
std::lock_guard<std::recursive_mutex> lock(mutex);
string full_key = "DKG_DH_KEY_" + _key;
......@@ -100,13 +85,10 @@ void LevelDB::deleteDHDKGKey (const string &_key) {
throwExceptionOnError(status);
spdlog::debug("key deleted: {}",full_key );
//std::cerr << "key deleted " << full_key << std::endl;
spdlog::debug("key deleted: {}",full_key );
}
void LevelDB::deleteTempNEK(const string &_key){
void LevelDB::deleteTempNEK(const string &_key) {
std::lock_guard<std::recursive_mutex> lock(mutex);
string prefix = _key.substr(0,8);
......@@ -121,24 +103,20 @@ void LevelDB::deleteTempNEK(const string &_key){
std::cerr << "key deleted " << _key << std::endl;
}
void LevelDB::deleteKey(const string &_key){
void LevelDB::deleteKey(const string &_key) {
std::lock_guard<std::recursive_mutex> lock(mutex);
auto status = db->Delete(writeOptions, Slice(_key));
throwExceptionOnError(status);
spdlog::debug("key deleted: {}",_key );
// std::cerr << "key deleted " << _key << std::endl;
spdlog::debug("key deleted: {}",_key );
}
void LevelDB::writeByteArray(const char *_key, size_t _keyLen, const char *value,
size_t _valueLen) {
std::lock_guard<std::recursive_mutex> lock(mutex);
auto status = db->Put(writeOptions, Slice(_key, _keyLen), Slice(value, _valueLen));
......@@ -149,7 +127,6 @@ void LevelDB::writeByteArray(const char *_key, size_t _keyLen, const char *value
void LevelDB::writeByteArray(string &_key, const char *value,
size_t _valueLen) {
std::lock_guard<std::recursive_mutex> lock(mutex);
auto status = db->Put(writeOptions, Slice(_key), Slice(value, _valueLen));
......@@ -158,18 +135,15 @@ void LevelDB::writeByteArray(string &_key, const char *value,
}
void LevelDB::throwExceptionOnError(Status _status) {
if (_status.IsNotFound())
return;
if (!_status.ok()) {
throw SGXException(COULD_NOT_ACCESS_DATABASE, ("Could not access database database:" + _status.ToString()).c_str());
}
}
uint64_t LevelDB::visitKeys(LevelDB::KeyVisitor *_visitor, uint64_t _maxKeysToVisit) {
uint64_t readCounter = 0;
leveldb::Iterator *it = db->NewIterator(readOptions);
......@@ -194,7 +168,6 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
for (it->SeekToFirst(); it->Valid(); it->Next()) {
string cur_key(it->key().data(), it->key().size());
keys.push_back(cur_key);
// keys.push_back(it->key().data());
readCounter++;
if (readCounter >= _maxKeysToVisit) {
break;
......@@ -207,25 +180,20 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
}
void LevelDB::writeDataUnique(const string & Name, const string &value) {
auto key = Name;
if (readString(Name) != nullptr) {
spdlog::debug("name {}",Name, " already exists");
// std::cerr << "name " << Name << " already exists" << std::endl;
throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
}
writeString(key, value);
spdlog::debug("{}",Name, " is written to db");
spdlog::debug("{}",Name, " is written to db");
}
LevelDB::LevelDB(string &filename) {
leveldb::Options options;
options.create_if_missing = true;
......@@ -236,7 +204,6 @@ LevelDB::LevelDB(string &filename) {
if (db == nullptr) {
throw std::runtime_error("Null levelDB object");
}
}
LevelDB::~LevelDB() {
......@@ -269,16 +236,13 @@ string LevelDB::sgx_data_folder;
bool LevelDB::isInited = false;
void LevelDB::initDataFolderAndDBs() {
CHECK_STATE(!isInited)
isInited = true;
spdlog::info("Initing wallet database ... ");
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) == NULL) {
spdlog::error("could not get current workin directory");
exit(-1);
......@@ -299,7 +263,6 @@ void LevelDB::initDataFolderAndDBs() {
}
}
spdlog::info("Opening wallet databases");
auto dbName = sgx_data_folder + WALLETDB_NAME;
......@@ -312,7 +275,6 @@ void LevelDB::initDataFolderAndDBs() {
csrStatusDb = make_shared<LevelDB>(csr_status_dbname);
spdlog::info("Successfully opened databases");
}
const string &LevelDB::getSgxDataFolder() {
......
......@@ -34,7 +34,6 @@ void Log::setGlobalLogLevel(string &_s) {
}
level_enum Log::logLevelFromString(string &_s) {
level_enum result = trace;
if (_s == "trace")
......
......@@ -59,8 +59,6 @@ void create_test_key(){
throw SGXException(status, errMsg.data()) ;
}
//std::cerr << "enc len is " << enc_len << std::endl;
vector<char> hexEncrKey(2 * enc_len + 1, 0);
carray2Hex(encrypted_key, enc_len, hexEncrKey.data());
......@@ -77,49 +75,41 @@ void create_test_key(){
bool check_SEK(std::string SEK){
std::shared_ptr <std::string> test_key_ptr = LevelDB::getLevelDb() -> readString("TEST_KEY");
// if (test_key_ptr == nullptr){
// spdlog::error("empty db" );
// exit(-1);
// }
// else{
vector<uint8_t> encr_test_key(BUF_LEN, 0);
uint64_t len;
if ( !hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data())){
spdlog::error("wrong test key" );
exit(-1);
}
vector<char> decr_key(1024,0);
vector<char> errMsg(1024,0);
int err_status = 0;
vector<uint8_t> encr_SEK(1024,0);
uint32_t l = len;
std::cerr << " l is " << l << std::endl;
status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encr_SEK.data(), &l, SEK.c_str() );
if (status != SGX_SUCCESS){
cerr << "RPCException thrown with status " << status << endl;
throw SGXException(status, errMsg.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" );
spdlog::error(errMsg.data());
exit(-1);
}
std::string test_key = TEST_VALUE;
if (test_key.compare(decr_key.data())!= 0){
std::cerr << "decrypted key is " << decr_key.data() << std::endl;
spdlog::error("Invalid SEK" );
return false;
}
return true;
// }
vector<uint8_t> encr_test_key(BUF_LEN, 0);
uint64_t len;
if ( !hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data())){
spdlog::error("wrong test key" );
exit(-1);
}
vector<char> decr_key(1024,0);
vector<char> errMsg(1024,0);
int err_status = 0;
vector<uint8_t> encr_SEK(1024,0);
uint32_t l = len;
status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encr_SEK.data(), &l, SEK.c_str() );
if (status != SGX_SUCCESS){
cerr << "RPCException thrown with status " << status << endl;
throw SGXException(status, errMsg.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" );
spdlog::error(errMsg.data());
exit(-1);
}
std::string test_key = TEST_VALUE;
if (test_key.compare(decr_key.data()) != 0){
std::cerr << "decrypted key is " << decr_key.data() << std::endl;
spdlog::error("Invalid SEK" );
return false;
}
return true;
}
void gen_SEK(){
......
......@@ -66,7 +66,6 @@ Json::Value signCertificateImpl(const string &_csr, bool _autoSign = false) {
result["result"] = false;
try {
string hash = cryptlite::sha256::hash_hex(_csr);
if (system("ls " CERT_DIR "/" CERT_CREATE_COMMAND) != 0) {
......@@ -74,7 +73,6 @@ Json::Value signCertificateImpl(const string &_csr, bool _autoSign = false) {
throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED");
}
string csr_name = string(CERT_DIR) + "/" + hash + ".csr";
ofstream outfile(csr_name);
outfile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
......@@ -91,21 +89,16 @@ Json::Value signCertificateImpl(const string &_csr, bool _autoSign = false) {
throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "Incorrect CSR format ");
}
if (_autoSign) {
string genCert = string("cd ") + CERT_DIR + "&& ./"
+ CERT_CREATE_COMMAND + " " + hash ;
if (system(genCert.c_str()) == 0) {
spdlog::info("Client cert " + hash + " generated");
string db_key = "CSR:HASH:" + hash + "STATUS:";
string status = "0";
LevelDB::getCsrStatusDb()->writeDataUnique(db_key, status);
} else {
spdlog::error("Client cert generation failed: {} ", genCert);
throw SGXException(FAIL_TO_CREATE_CERTIFICATE, "CLIENT CERTIFICATE GENERATION FAILED");
}
......@@ -172,7 +165,6 @@ Json::Value SGXRegistrationServer::GetCertificate(const string &hash) {
int SGXRegistrationServer::initRegistrationServer(bool _autoSign) {
httpServer = make_shared<HttpServer>(BASE_PORT + 1);
server = make_shared<SGXRegistrationServer>(*httpServer,
JSONRPC_SERVER_V2,
......@@ -185,7 +177,6 @@ int SGXRegistrationServer::initRegistrationServer(bool _autoSign) {
spdlog::info("Registration server started on port {}", BASE_PORT + 1);
}
return 0;
}
......@@ -194,4 +185,3 @@ shared_ptr<SGXRegistrationServer> SGXRegistrationServer::getServer() {
CHECK_STATE(server);
return server;
}
......@@ -98,7 +98,6 @@ void SGXWalletServer::printDB() {
}
int SGXWalletServer::initHttpsServer(bool _checkCerts) {
string rootCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.pem";
string keyCAPath = string(SGXDATA_FOLDER) + "cert_data/rootCA.key";
......@@ -147,7 +146,6 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
int SGXWalletServer::initHttpServer() { //without ssl
httpServer = make_shared<HttpServer>(BASE_PORT + 3);
server = make_shared<SGXWalletServer>(*httpServer,
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
......@@ -172,7 +170,6 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k
char *encryptedKeyShareHex = nullptr;
try {
encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, errMsg, _keyShare.c_str());
if (encryptedKeyShareHex == nullptr) {
......@@ -186,7 +183,6 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k
result["encryptedKeyShare"] = string(encryptedKeyShareHex);
writeKeyShare(_keyShareName, encryptedKeyShareHex, _index, n, t);
} catch (SGXException &_e) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
......@@ -269,7 +265,6 @@ Json::Value SGXWalletServer::importECDSAKeyImpl(const string &_key, const string
Json::Value SGXWalletServer::generateECDSAKeyImpl() {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -307,7 +302,6 @@ Json::Value SGXWalletServer::renameECDSAKeyImpl(const string &_keyName, const st
result["encryptedKey"] = "";
try {
string prefix = _tempKeyName.substr(0, 8);
if (prefix != "tmp_NEK:") {
throw SGXException(UNKNOWN_ERROR, "invalid temp key name");
......@@ -323,7 +317,6 @@ Json::Value SGXWalletServer::renameECDSAKeyImpl(const string &_keyName, const st
shared_ptr <string> encryptedKey = readFromDb(_tempKeyName);
writeDataToDB(_keyName, *encryptedKey);
LevelDB::getLevelDb()->deleteTempNEK(_tempKeyName);
......@@ -334,10 +327,8 @@ Json::Value SGXWalletServer::renameECDSAKeyImpl(const string &_keyName, const st
Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_keyName, const string &_messageHash) {
INIT_RESULT(result)
result["signature_v"] = "";
result["signature_r"] = "";
result["signature_s"] = "";
......@@ -345,7 +336,6 @@ Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_
vector <string> signatureVector(3);
try {
string hashTmp = _messageHash;
if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) {
hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2);
......@@ -383,7 +373,6 @@ Json::Value SGXWalletServer::ecdsaSignMessageHashImpl(int _base, const string &_
}
Json::Value SGXWalletServer::getPublicECDSAKeyImpl(const string &_keyName) {
INIT_RESULT(result)
result["publicKey"] = "";
......@@ -409,7 +398,6 @@ Json::Value SGXWalletServer::getPublicECDSAKeyImpl(const string &_keyName) {
}
Json::Value SGXWalletServer::generateDKGPolyImpl(const string &_polyName, int _t) {
INIT_RESULT(result)
string encrPolyHex;
......@@ -432,7 +420,6 @@ Json::Value SGXWalletServer::generateDKGPolyImpl(const string &_polyName, int _t
}
Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName, int _t, int _n) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
......@@ -456,7 +443,6 @@ Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName,
result["verificationVector"][i][j] = currentCoef.at(j);
}
}
} catch (SGXException &_e) {
cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
......@@ -494,9 +480,7 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
}
string s = trustedGetSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n);
//cerr << "result is " << s << endl;
result["secretShare"] = s;
} catch (SGXException &_e) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
......@@ -509,14 +493,12 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, const string &_ethKeyName,
const string &_secretShare, int _t, int _n, int _index) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
result["result"] = true;
try {
if (!checkECDSAKeyName(_ethKeyName)) {
throw SGXException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
......@@ -535,9 +517,7 @@ Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, co
if (!verifyShares(_publicShares.c_str(), _secretShare.c_str(), encryptedKeyHex_ptr->c_str(), _t, _n, _index)) {
result["result"] = false;
}
} catch (SGXException &_e) {
//cerr << " err str " << _e.errString << endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["result"] = false;
......@@ -549,14 +529,11 @@ Json::Value SGXWalletServer::dkgVerificationImpl(const string &_publicShares, co
Json::Value
SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string &_ethKeyName, const string &_polyName,
const string &_secretShare, int _t, int _n) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
if (_secretShare.length() != (uint64_t) _n * 192) {
spdlog::error("Invalid secret share length - {}", _secretShare.length());
spdlog::error("Secret share - {}", _secretShare);
......@@ -574,11 +551,11 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
if (!check_n_t(_t, _n)) {
throw SGXException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
vector <string> sshares_vect;
vector< string > sshares_vect;
spdlog::debug("secret shares from json are - {}", _secretShare);
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());
if (res) {
......@@ -600,7 +577,6 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
}
Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) {
INIT_RESULT(result)
try {
......@@ -615,14 +591,12 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName)
for (uint8_t i = 0; i < 4; i++) {
result["blsPublicKeyShare"][i] = public_key_vect.at(i);
}
} HANDLE_SGX_EXCEPTION(result)
return result;
}
Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _ind) {
INIT_RESULT(result)
try {
......@@ -644,7 +618,6 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int
}
Json::Value SGXWalletServer::multG2Impl(const string &_x) {
INIT_RESULT(result)
try {
......@@ -675,7 +648,6 @@ Json::Value SGXWalletServer::isPolyExistsImpl(const string &_polyName) {
}
Json::Value SGXWalletServer::getServerStatusImpl() {
INIT_RESULT(result)
return result;
......@@ -792,7 +764,6 @@ Json::Value SGXWalletServer::getServerVersion() {
}
shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) {
auto dataStr = LevelDB::getLevelDb()->readString(prefix + name);
if (dataStr == nullptr) {
......@@ -803,7 +774,6 @@ shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string
}
shared_ptr <string> SGXWalletServer::readKeyShare(const string &_keyShareName) {
auto keyShareStr = LevelDB::getLevelDb()->readString("BLSKEYSHARE:" + _keyShareName);
if (keyShareStr == nullptr) {
......@@ -811,11 +781,9 @@ shared_ptr <string> SGXWalletServer::readKeyShare(const string &_keyShareName) {
}
return keyShareStr;
}
void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_value, int _index, int _n, int _t) {
Json::Value val;
Json::FastWriter writer;
......@@ -850,6 +818,5 @@ void SGXWalletServer::writeDataToDB(const string &Name, const string &value) {
}
LevelDB::getLevelDb()->writeString(key, value);
}
......@@ -73,7 +73,6 @@ bool checkECDSAKeyName(const string& keyName) {
bool checkHex(const string& hex, const uint32_t sizeInBytes){
if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){
spdlog::error("key is too long or zero - ", hex.length());
std::cerr << "key length is " << hex.length() << std::endl;
return false;
}
......@@ -173,4 +172,4 @@ bool check_n_t ( const int t, const int n){
}
return true;
}
\ No newline at end of file
}
......@@ -60,13 +60,10 @@ void initUserSpace() {
LevelDB::initDataFolderAndDBs();
}
void initEnclave(uint32_t _logLevel) {
eid = 0;
updated = 0;
#ifndef SGX_HW_SIM
unsigned long support;
support = get_sgx_support();
......@@ -78,7 +75,6 @@ void initEnclave(uint32_t _logLevel) {
spdlog::debug("SGX_DEBUG_FLAG = {}", SGX_DEBUG_FLAG);
status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token,
&updated, &eid, 0);
......@@ -101,14 +97,9 @@ void initEnclave(uint32_t _logLevel) {
}
spdlog::info("Enclave libtgmp library and logging initialized successfully");
}
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
static int sgxServerInited;
cout << "Running sgxwallet version:" << SGXWalletServer::getVersion() << endl;
......
1.51.0
\ No newline at end of file
1.51.1
\ No newline at end of file
......@@ -40,6 +40,6 @@ if [[ "$1" == "-t" ]]; then
echo "Test run requested"
./testw.py
else
./sgxwallet $1 $2 $3 $4
./sgxwallet $1 $2 $3 $4 $5
fi
......@@ -90,7 +90,7 @@ void session_key_recover(const char *skey_str, const char* sshare, char* common_
mpz_t skey;
mpz_init(skey);
if (mpz_set_str(skey, skey_str, 16) == -1){
if (mpz_set_str(skey, skey_str, 16) == -1) {
common_key = NULL;
mpz_clear(skey);
......
......@@ -34,18 +34,13 @@
#include <../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp>
//#include "../sgxwallet_common.h"
#include "EnclaveConstants.h"
#include <cstdio>
#include <stdio.h>
#include "DHDkg.h"
using namespace std;
using namespace std;
string stringFromFr(libff::alt_bn128_Fr& _el) {
......@@ -136,15 +131,10 @@ int gen_dkg_poly( char* secret, unsigned _t ){
}
libff::alt_bn128_Fr PolynomialValue(const vector<libff::alt_bn128_Fr>& pol, libff::alt_bn128_Fr point, unsigned _t) {
libff::alt_bn128_Fr value = libff::alt_bn128_Fr::zero();
libff::alt_bn128_Fr pow = libff::alt_bn128_Fr::one();
for (unsigned i = 0; i < pol.size(); ++i) {
// if (i == _t - 1 && pol[i] == libff::alt_bn128_Fr::zero()) {
// //snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status
// }
value += pol[i] * pow;
pow *= point;
}
......@@ -165,12 +155,10 @@ void calc_secret_shares(const char* decrypted_coeffs, char * secret_shares,
result += ":";
}
strncpy(secret_shares, result.c_str(), result.length() + 1);
//strncpy(secret_shares, decrypted_coeffs, 3650);
}
int calc_secret_share(const char* decrypted_coeffs, char * s_share,
unsigned _t, unsigned _n, unsigned ind) {
libff::init_alt_bn128_params();
char symbol = ':';
vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_coeffs, symbol);
......@@ -185,12 +173,10 @@ int calc_secret_share(const char* decrypted_coeffs, char * s_share,
strncpy(s_share, cur_share.c_str(), cur_share.length() + 1);
return 0;
}
void calc_secret_shareG2_old(const char* decrypted_coeffs, char * s_shareG2,
unsigned _t, unsigned ind){
unsigned _t, unsigned ind) {
libff::init_alt_bn128_params();
char symbol = ':';
vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_coeffs, symbol);
......@@ -202,7 +188,6 @@ void calc_secret_shareG2_old(const char* decrypted_coeffs, char * s_shareG2,
string secret_shareG2_str = ConvertG2ToString(secret_shareG2);
strncpy(s_shareG2, secret_shareG2_str.c_str(), secret_shareG2_str.length() + 1);
//strncpy(s_shareG2, decrypted_coeffs, 320);
}
int calc_secret_shareG2(const char* s_share, char * s_shareG2){
......@@ -253,7 +238,6 @@ int calc_public_shares(const char* decrypted_coeffs, char * public_shares,
return 0;
}
//extern "C" int __gmpz_set_str (mpz_ptr, const char *, int);
string ConvertHexToDec(string hex_str){
mpz_t dec;
mpz_init(dec);
......@@ -271,8 +255,7 @@ string ConvertHexToDec(string hex_str){
return result;
}
int Verification ( char * public_shares, mpz_t decr_secret_share, int _t, int ind ){
int Verification ( char * public_shares, mpz_t decr_secret_share, int _t, int ind ) {
string pub_shares_str = public_shares;
libff::init_alt_bn128_params();
......@@ -303,44 +286,25 @@ int Verification ( char * public_shares, mpz_t decr_secret_share, int _t, int in
libff::alt_bn128_G2 val = libff::alt_bn128_G2::zero();
for (int i = 0; i < _t; ++i) {
val = val + power(libff::alt_bn128_Fr(ind + 1), i) * pub_shares[i];
}
}
char arr[mpz_sizeinbase (decr_secret_share, 10) + 2];
char * tmp = mpz_get_str(arr, 10, decr_secret_share);
libff::alt_bn128_Fr sshare(tmp);
// strncpy(public_shares, tmp, strlen(tmp));
// string res = ConvertHexToDec("fe43567238abcdef98760");
// strncpy(public_shares, res.c_str(), res.length());
libff::alt_bn128_G2 val2 = sshare * libff::alt_bn128_G2::one();
memset(public_shares, 0, strlen(public_shares));
memset(public_shares, 0, strlen(public_shares));
strncpy(public_shares, tmp, strlen(tmp));
// strncpy(public_shares, ConvertToString(val2.X.c0).c_str(), ConvertToString(val2.X.c0).length());
// strncpy(public_shares + ConvertToString(val2.X.c0).length(), ":", 1);
// strncpy(public_shares + ConvertToString(val2.X.c0).length() + 1, ConvertToString(val2.X.c1).c_str(), 77);
val.to_affine_coordinates();
val2.to_affine_coordinates();
// strncpy(public_shares + strlen(tmp), ":", 1);
strncpy(public_shares, ConvertToString(val.X.c0).c_str(), ConvertToString(val.X.c0).length());
strncpy(public_shares + ConvertToString(val.X.c0).length(), ":", 1);
strncpy(public_shares + ConvertToString(val.X.c0).length() + 1, ConvertToString(val2.X.c0).c_str(), ConvertToString(val2.X.c0).length());
/*strncpy(public_shares + 77 + 77 + 79, "\n", 1);
strncpy(public_shares + 144 + 79, ConvertToString(val2.X.c0).c_str(), 77);
strncpy(public_shares + 144 + 78, ":", 1);
strncpy(public_shares + 144 + 77, ConvertToString(val2.X.c1).c_str(), 77);*/
return (val == sshare * libff::alt_bn128_G2::one());
}
int calc_bls_public_key(char* skey_hex, char* pub_key){
......@@ -354,7 +318,7 @@ int calc_bls_public_key(char* skey_hex, char* pub_key){
}
char skey_dec[mpz_sizeinbase (skey, 10) + 2];
char * skey_str = mpz_get_str(skey_dec, 10, skey);
mpz_get_str(skey_dec, 10, skey);
libff::alt_bn128_Fr bls_skey(skey_dec);
......
......@@ -26,21 +26,23 @@
#define BUF_LEN 1024
#define MAX_KEY_LENGTH 128
#define MAX_COMPONENT_LENGTH 80
#define MAX_COMPONENT_HEX_LENGTH MAX_COMPONENT_LENGTH * 2
#define MAX_ENCRYPTED_KEY_LENGTH 1024
#define MAX_SIG_LEN 1024
#define MAX_ERR_LEN 1024
#define MAX_KEY_LENGTH 128
#define MAX_COMPONENT_LENGTH 80
#define MAX_COMPONENT_HEX_LENGTH MAX_COMPONENT_LENGTH * 2
#define MAX_ENCRYPTED_KEY_LENGTH 1024
#define MAX_SIG_LEN 1024
#define MAX_ERR_LEN 1024
#define SHA_256_LEN 32
#define ADD_ENTROPY_SIZE 32
#define DKG_BUFER_LENGTH 2490//3060
#define DKG_MAX_SEALED_LEN 3100
#define DKG_BUFER_LENGTH 2490//3060
#define DKG_MAX_SEALED_LEN 3100
#define SECRET_SHARE_NUM_BYTES 96
#define BLS_KEY_LENGTH 65
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
#define ECDSA_ENCR_LEN 93
......
......@@ -362,20 +362,21 @@ char* point_compress(point P)
int l = mpz_sizeinbase(P->x, 16) + 2;
char* result = (char*)calloc(l + 1, 1);
result[l] = '\0';
mpz_t t1;mpz_init(t1);
//Add x coordinat in hex to result
mpz_get_str(result +2, 16, P->x);
mpz_t t1;
mpz_init(t1);
//Determine if it's odd or even
mpz_mod_ui(t1, P->y, 2);
if(mpz_cmp_ui(t1, 0))
strncpy(result, "02", 2);
strncpy(result, "02", 3);
else
strncpy(result, "03", 2);
strncpy(result, "03", 3);
mpz_clear(t1);
//Add x coordinat in hex to result
mpz_get_str(result +2, 16, P->x);
return result;
}
......
......@@ -407,17 +407,17 @@ void trustedEncryptKey(int *errStatus, char *errString, const char *key,
memset(errString, 0, BUF_LEN);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, MAX_KEY_LENGTH);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, ECDSA_SKEY_LEN);
if (sealedLen > BUF_LEN) {
*errStatus = ENCRYPTED_KEY_TOO_LONG;
snprintf(errString, BUF_LEN, "sealedLen > MAX_ENCRYPTED_KEY_LENGTH");
return;
}
if (sealedLen > BUF_LEN) {
*errStatus = ENCRYPTED_KEY_TOO_LONG;
snprintf(errString, BUF_LEN, "sealedLen > MAX_ENCRYPTED_KEY_LENGTH");
return;
}
memset(encryptedPrivateKey, 0, BUF_LEN);
sgx_status_t status = sgx_seal_data(0, NULL, MAX_KEY_LENGTH, (uint8_t *) key, sealedLen,
sgx_status_t status = sgx_seal_data(0, NULL, ECDSA_SKEY_LEN, (uint8_t *) key, sealedLen,
(sgx_sealed_data_t *) encryptedPrivateKey);
if (status != SGX_SUCCESS) {
*errStatus = SEAL_KEY_FAILED;
......@@ -970,8 +970,16 @@ void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString,
pub_key_y[i] = '0';
}
strncpy(pub_key_y + n_zeroes, arr_y, 1024 - n_zeroes);
char skey_str[mpz_sizeinbase(skey, ECDSA_SKEY_BASE) + 2];
mpz_get_str(skey_str, ECDSA_SKEY_BASE, skey);
char skey_str[ECDSA_SKEY_LEN];
//mpz_get_str(skey_str, ECDSA_SKEY_BASE, skey);
char arr_skey_str[mpz_sizeinbase(skey, ECDSA_SKEY_BASE) + 2];
mpz_get_str(arr_skey_str, ECDSA_SKEY_BASE, skey);
n_zeroes = 64 - strlen(arr_skey_str);
for (int i = 0; i < n_zeroes; i++) {
skey_str[i] = '0';
}
strncpy(skey_str + n_zeroes, arr_skey_str, 65 - n_zeroes);
skey_str[ECDSA_SKEY_LEN - 1] = 0;
snprintf(errString, BUF_LEN, "skey is %s len %d\n", skey_str, strlen(skey_str));
int stat = AES_encrypt(skey_str, encryptedPrivateKey);
......@@ -992,7 +1000,7 @@ void trustedGenerateEcdsaKeyAES(int *errStatus, char *errString,
stat = AES_decrypt(encryptedPrivateKey, *enc_len, skey_str);
if (stat != 0) {
snprintf(errString + 19 + strlen(skey_str), BUF_LEN, "ecdsa private key decr failed with status %d", stat);
errStatus = stat;
*errStatus = stat;
return;
}
......@@ -1097,11 +1105,13 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv
if (status != 0) {
*errStatus = status;
snprintf(errString, BUF_LEN, "aes decrypt failed with status %d", status);
domain_parameters_clear(curve);
return;
}
skey[enc_len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE - 1] = '\0';
skey[enc_len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE] = '\0';
snprintf(errString, BUF_LEN, "pr key is %s length %d ", skey, strlen(skey));
mpz_t privateKeyMpz;
......@@ -1109,8 +1119,11 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv
if (mpz_set_str(privateKeyMpz, skey, ECDSA_SKEY_BASE) == -1) {
*errStatus = -1;
snprintf(errString, BUF_LEN, "invalid secret key");
LOG_ERROR(skey);
mpz_clear(privateKeyMpz);
domain_parameters_clear(curve);
return;
}
......@@ -1119,9 +1132,11 @@ void trustedEcdsaSignAES(int *errStatus, char *errString, uint8_t *encryptedPriv
if (mpz_set_str(msgMpz, hash, 16) == -1) {
*errStatus = -1;
snprintf(errString, BUF_LEN, "invalid message hash");
mpz_clear(privateKeyMpz);
mpz_clear(msgMpz);
domain_parameters_clear(curve);
return;
}
......@@ -1219,8 +1234,6 @@ void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPri
uint32_t enc_len, char *key) {
LOG_DEBUG(__FUNCTION__);
uint32_t decLen;
*errStatus = -9;
int status = AES_decrypt(encryptedPrivateKey, enc_len, key);
......@@ -1231,12 +1244,6 @@ void trustedDecryptKeyAES(int *errStatus, char *errString, uint8_t *encryptedPri
return;
}
if (decLen > MAX_KEY_LENGTH) {
*errStatus = 1;
snprintf(errString, BUF_LEN, "wrong decLen");//"decLen != MAX_KEY_LENGTH");
return;
}
*errStatus = -10;
uint64_t keyLen = strnlen(key, MAX_KEY_LENGTH);
......@@ -1325,7 +1332,7 @@ trustedDecryptDkgSecretAES(int *errStatus, char *errString, uint8_t *encrypted_d
uint32_t *dec_len) {
LOG_DEBUG (__FUNCTION__);
int status = AES_decrypt(encrypted_dkg_secret, dec_len, (char *)decrypted_dkg_secret);
int status = AES_decrypt(encrypted_dkg_secret, *dec_len, (char *)decrypted_dkg_secret);
if (status != SGX_SUCCESS) {
snprintf(errString, BUF_LEN, "aes decrypt data - encrypted_dkg_secret failed with status %d", status);
......@@ -1352,7 +1359,7 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t
LOG_DEBUG(__FUNCTION__);
char skey[ECDSA_SKEY_LEN];
memset(skey, 0, BUF_LEN);
memset(skey, 0, ECDSA_SKEY_LEN);
char pub_key_x[BUF_LEN];
memset(pub_key_x, 0, BUF_LEN);
char pub_key_y[BUF_LEN];
......@@ -1382,7 +1389,6 @@ void trustedGetEncryptedSecretShareAES(int *errStatus, char *errString, uint8_t
char *s_share[ECDSA_SKEY_LEN];
if (calc_secret_share(decryptedDkgPoly, s_share, _t, _n, ind) != 0) {
*errStatus = -1;
......@@ -1423,14 +1429,18 @@ void trustedGetPublicSharesAES(int *errStatus, char *errString, uint8_t *encrypt
if (status != SGX_SUCCESS) {
snprintf(errString, BUF_LEN, "aes decrypt data - encrypted_dkg_secret failed with status %d", status);
*errStatus = status;
free(decrypted_dkg_secret);
return;
}
if (calc_public_shares(decrypted_dkg_secret, public_shares, _t) != 0) {
*errStatus = -1;
snprintf(errString, BUF_LEN, "t does not match polynomial in db");
free(decrypted_dkg_secret);
return;
}
free(decrypted_dkg_secret);
}
void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_shares, const char *s_share,
......@@ -1441,7 +1451,6 @@ void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_sha
memset(skey, 0, ECDSA_SKEY_LEN);
int status = AES_decrypt(encryptedPrivateKey, enc_len, skey);
if (status != SGX_SUCCESS) {
snprintf(errString, BUF_LEN, "AES_decrypt failed (in trustedDkgVerifyAES) with status %d", status);
*errStatus = status;
......@@ -1452,7 +1461,6 @@ void trustedDkgVerifyAES(int *errStatus, char *errString, const char *public_sha
memset(encr_sshare, 0, ECDSA_SKEY_LEN);
strncpy(encr_sshare, s_share, ECDSA_SKEY_LEN - 1);
char common_key[ECDSA_SKEY_LEN];
memset(common_key, 0, ECDSA_SKEY_LEN);
......@@ -1522,7 +1530,10 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
if (common_key == NULL) {
*errStatus = 1;
snprintf(errString, BUF_LEN, "invalid common_key");
LOG_ERROR(errString);
mpz_clear(sum);
return;
}
......@@ -1531,7 +1542,11 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
if (decr_sshare == NULL) {
*errStatus = 1;
snprintf(errString, BUF_LEN, "invalid common_key");
LOG_ERROR(common_key);
LOG_ERROR(errString);
mpz_clear(sum);
return;
}
decr_sshare[64] = 0;
......@@ -1541,7 +1556,11 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
if (mpz_set_str(decr_secret_share, decr_sshare, 16) == -1) {
*errStatus = 111;
snprintf(errString, BUF_LEN, decr_sshare);
LOG_ERROR(decr_sshare);
mpz_clear(decr_secret_share);
mpz_clear(sum);
return;
}
......@@ -1558,8 +1577,17 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
mpz_mod(bls_key, sum, q);
char key_share[mpz_sizeinbase(bls_key, 16) + 2];
mpz_get_str(key_share, 16, bls_key);
// char key_share[mpz_sizeinbase(bls_key, 16) + 2];
// mpz_get_str(key_share, 16, bls_key);
char key_share[BLS_KEY_LENGTH];
char arr_skey_str[mpz_sizeinbase(bls_key, 16) + 2];
mpz_get_str(arr_skey_str, 16, bls_key);
int n_zeroes = 64 - strlen(arr_skey_str);
for (int i = 0; i < n_zeroes; i++) {
key_share[i] = '0';
}
strncpy(key_share + n_zeroes, arr_skey_str, 65 - n_zeroes);
key_share[BLS_KEY_LENGTH - 1] = 0;
snprintf(errString, BUF_LEN, " bls private key is %s", key_share);
status = AES_encrypt(key_share, encr_bls_key);
......@@ -1567,9 +1595,11 @@ void trustedCreateBlsKeyAES(int *errStatus, char *errString, const char *s_share
if (status != SGX_SUCCESS) {
*errStatus = -1;
snprintf(errString, BUF_LEN, "aes encrypt bls private key failed with status %d ", status);
mpz_clear(bls_key);
mpz_clear(sum);
mpz_clear(q);
return;
}
*enc_bls_key_len = strlen(key_share) + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
......@@ -1595,6 +1625,7 @@ trustedGetBlsPubKeyAES(int *errStatus, char *errString, uint8_t *encryptedPrivat
skey_hex[ECDSA_SKEY_LEN - 1] = 0;
if (calc_bls_public_key(skey_hex, bls_pub_key) != 0) {
LOG_ERROR(skey_hex);
*errStatus = -1;
snprintf(errString, BUF_LEN, "could not calculate bls public key");
return;
......
......@@ -226,7 +226,6 @@ enclave {
uint32_t enc_len,
[out, count = SMALL_BUF_SIZE] char* key );
public void trustedGenDkgSecretAES (
[user_check] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string,
......@@ -279,7 +278,6 @@ enclave {
int _ind,
[user_check] int* result);
public void trustedCreateBlsKeyAES(
[user_check]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string,
......@@ -304,9 +302,6 @@ enclave {
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint64_t key_len,
[out, count = 320] char* bls_pub_key);
};
......
......@@ -68,7 +68,6 @@ void printUsage() {
enum log_level {L_TRACE = 0, L_DEBUG = 1, L_INFO = 2,L_WARNING = 3, L_ERROR = 4 };
int main(int argc, char *argv[]) {
bool encryptKeysOption = false;
bool useHTTPSOption = true;
bool printDebugInfoOption = false;
......@@ -84,9 +83,6 @@ int main(int argc, char *argv[]) {
exit(1);
}
while ((opt = getopt(argc, argv, "cshd0abyvVn")) != -1) {
switch (opt) {
case 'h':
......
This diff is collapsed.
......@@ -27,31 +27,35 @@ import getpass, os, subprocess
username = getpass.getuser()
topDir = os.getcwd() + "/sgxwallet"
print("Starting build push")
print("Top directory is:" + topDir)
testList = [ "[cert-sign]",
"[get-server-status]",
"[get-server-version]",
"[ecdsa-key-gen]",
"[ecdsa-aes-key-gen]",
"[ecdsa-key-sig-gen]",
"[ecdsa-aes-key-sig-gen]",
"[ecdsa-get-pub-key]",
"[ecdsa-aes-get-pub-key]",
"[ecdsa-key-gen-api]",
"[ecdsa-key-gen-sign-api]",
"[bls-key-encrypt]",
"[dkg-gen]",
"[dkg-aes-gen]",
"[dkg-encr-sshares]",
"[dkg-aes-encr-sshares]",
"[dkg-verify]",
"[dkg-api]",
"[dkg-bls]",
"[dkg-poly-exists]",
"[dkg-pub-shares]",
"[dkg-aes-pub-shares]",
"[many-threads-crypto]",
"[aes-encrypt-decrypt]",
"[sgx-encrypt-decrypt]",
"[aes-dkg]"#,
#"[aes-not-aes]" <- this test doesn't pass for now - will fix it later
"[aes-dkg]",
"[aes-not-aes]"
]
......
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