Unverified Commit 9feedf3d authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #202 from skalenetwork/develop

Merge  develop to beta
parents 8fc3fdf3 f53e5094
...@@ -8,9 +8,7 @@ jobs: ...@@ -8,9 +8,7 @@ jobs:
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps: steps:
- name: Login to docker - name: Login to docker
env: run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: submodule update - name: submodule update
run: git submodule update --init --recursive run: git submodule update --init --recursive
......
...@@ -11,14 +11,12 @@ jobs: ...@@ -11,14 +11,12 @@ jobs:
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps: steps:
- name: Login to docker - name: Login to docker
env: run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: submodule update - name: submodule update
run: git submodule update --init --recursive run: git submodule update --init --recursive
- name: Build the Docker image - name: Build the Docker image
run: docker build . --file DockerfileBase --tag skalenetwork/sgxwallet_base:latest run: docker build . --file DockerfileBase --tag skalenetwork/sgxwallet_base:latest && docker push skalenetwork/sgxwallet_base:latest
- name: deploy docker image - name: deploy docker image
if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable') if: contains(github.ref, 'develop') || contains(github.ref, 'beta') || contains(github.ref, 'master') || contains(github.ref, 'stable')
run : | run : |
......
...@@ -8,9 +8,7 @@ jobs: ...@@ -8,9 +8,7 @@ jobs:
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
steps: steps:
- name: Login to docker - name: Login to docker
env: run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: submodule update - name: submodule update
run: git submodule update --init --recursive run: git submodule update --init --recursive
......
...@@ -10,9 +10,7 @@ jobs: ...@@ -10,9 +10,7 @@ jobs:
- name: Check that /dev/urandom exists - name: Check that /dev/urandom exists
run: ls /dev/urandom run: ls /dev/urandom
- name: Login to docker - name: Login to docker
env: run: docker login -u ${DOCKER_USERNAME} -p ${DOCKER_PASSWORD}
GITHUB_TOKEN: ${{ secrets.DOCKER_SECRET }}
run: docker login -u skalelabs -p ${GITHUB_TOKEN}
- uses: actions/checkout@v1 - uses: actions/checkout@v1
- name: submodule update - name: submodule update
run: git submodule update --init --recursive run: git submodule update --init --recursive
......
...@@ -22,47 +22,47 @@ ...@@ -22,47 +22,47 @@
*/ */
#include <memory> #include <memory>
#include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp" #include "libff/algebra/curves/alt_bn128/alt_bn128_init.hpp"
#include "leveldb/db.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
#include "third_party/intel/create_enclave.h"
#include "bls.h" #include "bls.h"
#include <bls/BLSutils.h> #include <bls/BLSutils.h>
#include "leveldb/db.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
#include "BLSPrivateKeyShareSGX.h" #include "BLSPrivateKeyShareSGX.h"
#include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h"
#include "secure_enclave_u.h"
#include "third_party/intel/sgx_detect.h"
#include <gmp.h>
#include <sgx_urts.h>
#include "sgxwallet_common.h"
#include "sgxwallet.h" #include "sgxwallet.h"
#include "SGXException.h"
#include "third_party/spdlog/spdlog.h"
#include "common.h"
#include "SGXWalletServer.h" #include "SGXWalletServer.h"
#include "BLSCrypto.h" #include "SEKManager.h"
#include "LevelDB.h"
#include "ServerInit.h" #include "ServerInit.h"
#include "BLSCrypto.h"
#include "SGXException.h"
#include "third_party/spdlog/spdlog.h" string *FqToString(libff::alt_bn128_Fq *_fq) {
#include "common.h"
CHECK_STATE(_fq);
std::string *FqToString(libff::alt_bn128_Fq *_fq) {
mpz_t t; mpz_t t;
mpz_init(t); mpz_init(t);
_fq->as_bigint().to_mpz(t); _fq->as_bigint().to_mpz(t);
char arr[mpz_sizeinbase(t, 10) + 2]; SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2);
mpz_get_str(arr, 10, t); mpz_get_str(arr, 10, t);
mpz_clear(t); mpz_clear(t);
return new std::string(arr); return new string(arr);
} }
int char2int(char _input) { int char2int(char _input) {
...@@ -75,50 +75,47 @@ int char2int(char _input) { ...@@ -75,50 +75,47 @@ int char2int(char _input) {
return -1; return -1;
} }
void carray2Hex(const unsigned char *d, int _len, char *_hexArray) { vector<char> carray2Hex(const unsigned char *d, uint64_t _len) {
CHECK_STATE(d);
vector<char> _hexArray( 2 * _len + 1);
char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7', char hexval[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
for (int j = 0; j < _len; j++) { for (uint64_t j = 0; j < _len; j++) {
_hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)]; _hexArray[j * 2] = hexval[((d[j] >> 4) & 0xF)];
_hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F]; _hexArray[j * 2 + 1] = hexval[(d[j]) & 0x0F];
} }
_hexArray[_len * 2] = 0; _hexArray[_len * 2] = 0;
return _hexArray;
} }
bool hex2carray(const char *_hex, uint64_t *_bin_len, uint8_t *_bin) {
int len = strnlen(_hex, 2 * BUF_LEN);
if (len == 0 && len % 2 == 1) bool hex2carray(const char *_hex, uint64_t *_bin_len,
return false; uint8_t *_bin, uint64_t _max_length) {
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) { CHECK_STATE(_hex);
int high = char2int((char) _hex[i * 2]); CHECK_STATE(_bin);
int low = char2int((char) _hex[i * 2 + 1]); CHECK_STATE(_bin_len)
if (high < 0 || low < 0) {
return false;
}
_bin[i] = (unsigned char) (high * 16 + low); uint64_t len = strnlen(_hex, 2 * _max_length + 1);
}
return true; CHECK_STATE(len != 2 * _max_length + 1);
}
CHECK_STATE(len <= 2 * _max_length);
bool hex2carray2(const char *_hex, uint64_t *_bin_len,
uint8_t *_bin, const int _max_length) {
int len = strnlen(_hex, _max_length);
if (len == 0 && len % 2 == 1) if (len == 0 && len % 2 == 1)
return false; return false;
*_bin_len = len / 2; *_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) { for (uint64_t i = 0; i < len / 2; i++) {
int high = char2int((char) _hex[i * 2]); int high = char2int((char) _hex[i * 2]);
int low = char2int((char) _hex[i * 2 + 1]); int low = char2int((char) _hex[i * 2 + 1]);
...@@ -134,13 +131,20 @@ bool hex2carray2(const char *_hex, uint64_t *_bin_len, ...@@ -134,13 +131,20 @@ bool hex2carray2(const char *_hex, uint64_t *_bin_len,
bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex, bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) { char *_sig) {
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto keyStr = make_shared<string>(_encryptedKeyHex); auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared<array<uint8_t, 32>>(); auto hash = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())) { if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
...@@ -156,43 +160,38 @@ bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t ...@@ -156,43 +160,38 @@ bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t
} }
bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) { bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) {
auto hash = make_shared<array<uint8_t, 32>>();
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto hash = make_shared < array < uint8_t, 32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data())) { if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
shared_ptr<signatures::Bls> obj; shared_ptr <signatures::Bls> obj;
obj = make_shared<signatures::Bls>(signatures::Bls(_t, _n)); obj = make_shared<signatures::Bls>(signatures::Bls(_t, _n));
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint = obj->HashtoG1withHint(hash); pair <libff::alt_bn128_G1, string> hash_with_hint = obj->HashtoG1withHint(hash);
string *xStr = FqToString(&(hash_with_hint.first.X)); string *xStr = FqToString(&(hash_with_hint.first.X));
if (xStr == nullptr) { CHECK_STATE(xStr);
std::cerr << "Null xStr" << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
string *yStr = FqToString(&(hash_with_hint.first.Y)); string *yStr = FqToString(&(hash_with_hint.first.Y));
if (yStr == nullptr) { if (yStr == nullptr) {
std::cerr << "Null yStr" << std::endl;
delete xStr; delete xStr;
BOOST_THROW_EXCEPTION(runtime_error("Null yStr")); BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
} }
char errMsg[BUF_LEN]; vector<char> errMsg(BUF_LEN, 0);
memset(errMsg, 0, BUF_LEN);
char xStrArg[BUF_LEN];
char yStrArg[BUF_LEN];
char signature[BUF_LEN];
memset(xStrArg, 0, BUF_LEN); SAFE_CHAR_BUF(xStrArg, BUF_LEN);SAFE_CHAR_BUF(yStrArg, BUF_LEN);SAFE_CHAR_BUF(signature, 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 +201,30 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -202,34 +201,30 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
size_t sz = 0; size_t sz = 0;
uint8_t encryptedKey[BUF_LEN]; SAFE_UINT8_BUF(encryptedKey, BUF_LEN);
bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey); bool result = hex2carray(_encryptedKeyHex, &sz, encryptedKey, BUF_LEN);
if (!result) { if (!result) {
cerr << "Invalid hex encrypted key" << endl; BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key"));
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
} }
int errStatus = 0; int errStatus = 0;
sgx_status_t status =
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey,
sz, xStrArg, yStrArg, signature);
if (status != SGX_SUCCESS) { sgx_status_t status = SGX_SUCCESS;
cerr << "SGX enclave call to trustedBlsSignMessage failed with status:" << status << std::endl;
BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to trustedBlsSignMessage failed")); RESTART_BEGIN
} status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
sz, xStrArg, yStrArg, signature);
RESTART_END
if (errStatus != 0) {
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; HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
std::string sig = signature; string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" + hash_with_hint.second;
string sig = signature;
sig.append(":"); sig.append(":");
sig.append(hint); sig.append(hint);
...@@ -240,36 +235,35 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz ...@@ -240,36 +235,35 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
} }
bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) { bool bls_sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) {
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _sig); return sign_aes(_encryptedKeyHex, _hashHex, _t, _n, _sig);
} }
std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) { string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key) {
auto keyArray = make_shared<vector<char>>(BUF_LEN, 0); CHECK_STATE(errStatus);
auto encryptedKey = make_shared<vector<uint8_t>>(BUF_LEN, 0); CHECK_STATE(err_string);
auto errMsg = make_shared<vector<char>>(BUF_LEN, 0); CHECK_STATE(_key);
auto keyArray = make_shared < vector < char >> (BUF_LEN, 0);
strncpy(keyArray->data(), _key, BUF_LEN); auto encryptedKey = make_shared < vector < uint8_t >> (BUF_LEN, 0);
*errStatus = -1;
unsigned int encryptedLen = 0; vector<char> errMsg(BUF_LEN, 0);
status = trustedEncryptKeyAES(eid, errStatus, errMsg->data(), keyArray->data(), encryptedKey->data(), &encryptedLen); strncpy(keyArray->data(), _key, BUF_LEN);
*errStatus = 0;
spdlog::debug("errStatus is {}", *errStatus); uint64_t encryptedLen = 0;
spdlog::debug("errMsg is ", errMsg->data());
if (*errStatus != 0) { sgx_status_t status = SGX_SUCCESS;
throw SGXException(-666, errMsg->data());
}
if (status != SGX_SUCCESS) { RESTART_BEGIN
*errStatus = -1; status = trustedEncryptKey(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(),
return ""; &encryptedLen);
} RESTART_END_POINTER
std::string result(2 * BUF_LEN, '\0'); HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());
carray2Hex(encryptedKey->data(), encryptedLen, &result.front()); vector<char> resultBuf = carray2Hex(encryptedKey->data(), encryptedLen);
return result; return string(resultBuf.begin(), resultBuf.end());
} }
...@@ -33,18 +33,16 @@ ...@@ -33,18 +33,16 @@
#include "stddef.h" #include "stddef.h"
#include "stdint.h" #include "stdint.h"
#include <string> #include <string>
#include <vector>
EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t, size_t n, char* _sig); EXTERNC bool bls_sign(const char* encryptedKeyHex, const char* hashHex, size_t t, size_t n, char* _sig);
EXTERNC int char2int(char _input); EXTERNC int char2int(char _input);
EXTERNC void carray2Hex(const unsigned char *d, int _len, char* _hexArray); EXTERNC std::vector<char> carray2Hex(const unsigned char *d, uint64_t _len);
EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin );
EXTERNC bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length );
EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, uint64_t _max_length );
std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key); std::string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key);
......
...@@ -25,172 +25,167 @@ ...@@ -25,172 +25,167 @@
#include "BLSSignature.h" #include "BLSSignature.h"
#include "BLSutils.h" #include "BLSutils.h"
#include "third_party/spdlog/spdlog.h"
#include "common.h"
#include "secure_enclave_u.h" #include "secure_enclave_u.h"
#include "sgxwallet_common.h" #include "sgxwallet_common.h"
#include "sgxwallet.h" #include "sgxwallet.h"
#include "BLSCrypto.h" #include "BLSCrypto.h"
#include "ServerInit.h" #include "ServerInit.h"
#include "common.h" #include "SEKManager.h"
#include "BLSPrivateKeyShareSGX.h" #include "BLSPrivateKeyShareSGX.h"
std::string *stringFromFq(libff::alt_bn128_Fq*_fq) { string *stringFromFq(libff::alt_bn128_Fq *_fq) {
mpz_t t;
mpz_init(t); CHECK_STATE(_fq);
_fq->as_bigint().to_mpz(t); mpz_t t;
mpz_init(t);
char arr[mpz_sizeinbase(t, 10) + 2]; _fq->as_bigint().to_mpz(t);
char *tmp = mpz_get_str(arr, 10, t); SAFE_CHAR_BUF(arr, mpz_sizeinbase(t, 10) + 2);
mpz_clear(t);
return new std::string(tmp); char *tmp = mpz_get_str(arr, 10, t);
mpz_clear(t);
return new string(tmp);
} }
std::string *stringFromG1(libff::alt_bn128_G1 *_g1) { string *stringFromG1(libff::alt_bn128_G1 *_g1) {
auto sX = stringFromFq(&_g1->X);
auto sY = stringFromFq(&_g1->Y); CHECK_STATE(_g1);
auto sZ = stringFromFq(&_g1->Z);
auto sG1 = new std::string(*sX + ":" + *sY + ":" + *sZ); auto sX = stringFromFq(&_g1->X);
auto sY = stringFromFq(&_g1->Y);
auto sZ = stringFromFq(&_g1->Z);
delete(sX); auto sG1 = new string(*sX + ":" + *sY + ":" + *sZ);
delete(sY);
delete(sZ);
return sG1; delete (sX);
delete (sY);
delete (sZ);
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) {
delete xStr;
BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
}
if (yStr == nullptr) {
std::cerr << "Null yStr" << std::endl;
delete xStr;
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];
char yStrArg[BUF_LEN];
char signature [BUF_LEN];
memset(xStrArg, 0, BUF_LEN); SAFE_CHAR_BUF(xStrArg, BUF_LEN)SAFE_CHAR_BUF(yStrArg, BUF_LEN)SAFE_CHAR_BUF(signature, BUF_LEN);
memset(yStrArg, 0, BUF_LEN);
strncpy(xStrArg, xStr->c_str(), BUF_LEN);
strncpy(yStrArg, yStr->c_str(), BUF_LEN);
delete xStr; strncpy(xStrArg, xStr->c_str(), BUF_LEN);
delete yStr; strncpy(yStrArg, yStr->c_str(), BUF_LEN);
size_t sz = 0; delete xStr;
delete yStr;
uint8_t encryptedKey[BUF_LEN]; size_t sz = 0;
bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey); SAFE_UINT8_BUF(encryptedKey, BUF_LEN);
if (!result) { bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey,
cerr << "Invalid hex encrypted key" << endl; BUF_LEN);
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
}
cerr << "Key is " + *encryptedKeyHex << endl; if (!result) {
spdlog::error("Invalid hex encrypted key");
BOOST_THROW_EXCEPTION(invalid_argument("Invalid hex encrypted key"));
}
sgx_status_t status = sgx_status_t status = SGX_SUCCESS;
trustedBlsSignMessageAES(eid, &errStatus, errMsg, encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
printf("sig is: %s\n", signature); RESTART_BEGIN
status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
RESTART_END
if (status != SGX_SUCCESS) { HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
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;
if ((sigLen = strnlen(signature, 10)) < 10) { if ((sigLen = strnlen(signature, 10)) < 10) {
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);
return sig; return sig;
} }
std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX( shared_ptr <BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr, shared_ptr <array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex) { size_t _signerIndex) {
std::string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
CHECK_STATE(hash_byte_arr);
string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
auto sig = make_shared<string>(signature); auto sig = make_shared<string>(signature);
std::shared_ptr<BLSSigShare> s = std::make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners, shared_ptr <BLSSigShare> s = make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners,
totalSigners); totalSigners);
return s; return s;
} }
...@@ -20,7 +20,7 @@ add_executable(sgxwallet ...@@ -20,7 +20,7 @@ add_executable(sgxwallet
secure_enclave/DHDkg.h secure_enclave/DHDkg.h
secure_enclave/DKGUtils.cpp secure_enclave/DKGUtils.cpp
secure_enclave/DKGUtils.h secure_enclave/DKGUtils.h
secure_enclave/DomainParameters.c secure_enclave/DomainParameters.cpp
secure_enclave/DomainParameters.h secure_enclave/DomainParameters.h
secure_enclave/EnclaveConstants.h secure_enclave/EnclaveConstants.h
secure_enclave/NumberTheory.c secure_enclave/NumberTheory.c
......
This diff is collapsed.
...@@ -33,19 +33,21 @@ using namespace std; ...@@ -33,19 +33,21 @@ using namespace std;
string gen_dkg_poly( int _t); string gen_dkg_poly( int _t);
vector <vector<string>> get_verif_vect(const char* encryptedPolyHex, int t, int n); vector <vector<string>> get_verif_vect(const string& encryptedPolyHex, int t, int n);
vector <vector<string>> getVerificationVectorMult(const std::string& encryptedPolyHex, int t, int n, size_t ind);
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 +57,6 @@ string convertG2ToString(const libff::alt_bn128_G2& elem, int base = 10, const s ...@@ -55,6 +57,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
FROM skalenetwork/sgxwallet_base:latest FROM skalenetwork/sgxwallet_base:latest
COPY . /usr/src/sdk COPY . /usr/src/sdk
RUN apt update && apt install -y curl secure-delete
WORKDIR /usr/src/sdk WORKDIR /usr/src/sdk
RUN apt update && apt install -y curl secure-delete
RUN touch /var/hwmode RUN touch /var/hwmode
RUN ./autoconf.bash RUN ./autoconf.bash
RUN ./configure RUN ./configure
...@@ -10,4 +10,6 @@ RUN bash -c "make -j$(nproc)" ...@@ -10,4 +10,6 @@ RUN bash -c "make -j$(nproc)"
RUN ccache -sz RUN ccache -sz
RUN mkdir -p /usr/src/sdk/sgx_data RUN mkdir -p /usr/src/sdk/sgx_data
COPY docker/start.sh ./ COPY docker/start.sh ./
RUN rm -rf /usr/src/sdk/sgx-sdk-build/
RUN rm /opt/intel/sgxsdk/lib64/*_sim.so
ENTRYPOINT ["/usr/src/sdk/start.sh"] ENTRYPOINT ["/usr/src/sdk/start.sh"]
FROM skalenetwork/sgxwallet_base:latest FROM skalenetwork/sgxwallet_base:latest
COPY . /usr/src/sdk COPY . /usr/src/sdk
WORKDIR /usr/src/sdk
RUN cp -f secure_enclave/secure_enclave.config.xml.release secure_enclave/secure_enclave.config.xml RUN cp -f secure_enclave/secure_enclave.config.xml.release secure_enclave/secure_enclave.config.xml
RUN apt update && apt install -y curl secure-delete RUN apt update && apt install -y curl secure-delete
WORKDIR /usr/src/sdk
#Test signing key generation #Test signing key generation
RUN cd scripts && ./generate_signing_key.bash RUN cd scripts && ./generate_signing_key.bash
RUN touch /var/hwmode RUN touch /var/hwmode
...@@ -14,4 +14,10 @@ RUN cd scripts && ./sign_enclave.bash ...@@ -14,4 +14,10 @@ RUN cd scripts && ./sign_enclave.bash
RUN ccache -sz RUN ccache -sz
RUN mkdir -p /usr/src/sdk/sgx_data RUN mkdir -p /usr/src/sdk/sgx_data
COPY docker/start.sh ./ COPY docker/start.sh ./
RUN rm -rf /usr/src/sdk/sgx-sdk-build/
RUN rm /opt/intel/sgxsdk/lib64/*_sim.so
RUN rm /usr/src/sdk/secure_enclave/secure_enclave*.so
RUN cd /usr/src/sdk/secure_enclave && \
curl --output secure_enclave.signed.so \
https://raw.githubusercontent.com/skalenetwork/signed_sgx_enclaves/master/secure_enclave_signed.so.1
ENTRYPOINT ["/usr/src/sdk/start.sh"] ENTRYPOINT ["/usr/src/sdk/start.sh"]
FROM skalenetwork/sgxwallet_base:latest FROM skalenetwork/sgxwallet_base:latest
RUN apt update && apt install -y curl secure-delete RUN apt update && apt install -y curl secure-delete
RUN ccache -sz RUN ccache -sz
COPY . /usr/src/sdk COPY . /usr/src/sdk
RUN cp -f secure_enclave/secure_enclave.config.xml.sim secure_enclave/secure_enclave.config.xml
WORKDIR /usr/src/sdk WORKDIR /usr/src/sdk
RUN cp -f secure_enclave/secure_enclave.config.xml.sim secure_enclave/secure_enclave.config.xml
RUN ./autoconf.bash && \ RUN ./autoconf.bash && \
./configure --enable-sgx-simulation && \ ./configure --enable-sgx-simulation && \
bash -c "make" && \ bash -c "make" && \
...@@ -15,5 +15,6 @@ RUN ./autoconf.bash && \ ...@@ -15,5 +15,6 @@ RUN ./autoconf.bash && \
mkdir -p /usr/src/sdk/sgx_data mkdir -p /usr/src/sdk/sgx_data
COPY docker/start.sh ./ COPY docker/start.sh ./
RUN rm -rf /usr/src/sdk/sgx-sdk-build/
ENTRYPOINT ["/usr/src/sdk/start.sh"] ENTRYPOINT ["/usr/src/sdk/start.sh"]
...@@ -38,6 +38,7 @@ ...@@ -38,6 +38,7 @@
#include "BLSCrypto.h" #include "BLSCrypto.h"
#include "SEKManager.h"
#include "ECDSACrypto.h" #include "ECDSACrypto.h"
void fillRandomBuffer(vector<unsigned char> &_buffer) { void fillRandomBuffer(vector<unsigned char> &_buffer) {
...@@ -48,36 +49,34 @@ void fillRandomBuffer(vector<unsigned char> &_buffer) { ...@@ -48,36 +49,34 @@ 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; uint64_t enc_len = 0;
status = trustedGenerateEcdsaKeyAES(eid, &errStatus, sgx_status_t status = SGX_SUCCESS;
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
if (status != SGX_SUCCESS || errStatus != 0) { RESTART_BEGIN
spdlog::error("RPCException thrown with status {}", status); status = trustedGenerateEcdsaKey(eid, &errStatus,
throw SGXException(status, errMsg.data()); errMsg.data(), encr_pr_key.data(), &enc_len,
} pub_key_x.data(), pub_key_y.data());
vector <string> keys(3); RESTART_END
vector<char> hexEncrKey(BUF_LEN * 2, 0); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data());
carray2Hex(encr_pr_key.data(), enc_len, hexEncrKey.data()); vector <string> keys(3);
vector<char> hexEncrKey = carray2Hex(encr_pr_key.data(), enc_len);
keys.at(0) = hexEncrKey.data(); keys.at(0) = hexEncrKey.data();
keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data()); keys.at(1) = string(pub_key_x.data()) + string(pub_key_y.data());
vector<unsigned char> randBuffer(32, 0); vector<unsigned char> randBuffer(32, 0);
fillRandomBuffer(randBuffer); fillRandomBuffer(randBuffer);
vector<char> rand_str(64, 0); vector<char> rand_str = carray2Hex(randBuffer.data(), 32);
carray2Hex(randBuffer.data(), 32, rand_str.data());
keys.at(2) = rand_str.data(); keys.at(2) = rand_str.data();
...@@ -95,22 +94,20 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) { ...@@ -95,22 +94,20 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) {
int errStatus = 0; int errStatus = 0;
uint64_t enc_len = 0; uint64_t enc_len = 0;
if (!hex2carray(_encryptedKeyHex.c_str(), &enc_len, encrPrKey.data())) { if (!hex2carray(_encryptedKeyHex.c_str(), &enc_len, encrPrKey.data(),
BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
status = trustedGetPublicEcdsaKeyAES(eid, &errStatus, sgx_status_t status = SGX_SUCCESS;
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
if (errStatus != 0) { RESTART_BEGIN
spdlog::error("failed to get ECDSA public key {}", status); status = trustedGetPublicEcdsaKey(eid, &errStatus,
throw SGXException(-666, errMsg.data()); errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
} RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, 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 +120,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) { ...@@ -123,6 +120,11 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) {
bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatureR, bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatureR,
const char *signatureS, int base) { const char *signatureS, int base) {
CHECK_STATE(hashHex)
CHECK_STATE(signatureR)
CHECK_STATE(signatureS)
auto x = pubKeyStr.substr(0, 64); auto x = pubKeyStr.substr(0, 64);
auto y = pubKeyStr.substr(64, 128); auto y = pubKeyStr.substr(64, 128);
...@@ -166,38 +168,40 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur ...@@ -166,38 +168,40 @@ bool verifyECDSASig(string& pubKeyStr, const char *hashHex, const char *signatur
} }
vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *hashHex, int base) { vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *hashHex, int base) {
CHECK_STATE(hashHex);
vector <string> signatureVector(3); vector <string> signatureVector(3);
vector<char> errMsg(1024, 0); vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0; int errStatus = 0;
vector<char> signatureR(1024, 0); vector<char> signatureR(BUF_LEN, 0);
vector<char> signatureS(1024, 0); vector<char> signatureS(BUF_LEN, 0);
vector<uint8_t> encryptedKey(1024, 0); vector<uint8_t> encryptedKey(BUF_LEN, 0);
uint8_t signatureV = 0; uint8_t signatureV = 0;
uint64_t decLen = 0; uint64_t decLen = 0;
string pubKeyStr = ""; string pubKeyStr = "";
if (!hex2carray(encryptedKeyHex.c_str(), &decLen, encryptedKey.data())) { if (!hex2carray(encryptedKeyHex.c_str(), &decLen, encryptedKey.data(),
BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex"); throw SGXException(INVALID_HEX, "Invalid encryptedKeyHex");
} }
status = trustedEcdsaSignAES(eid, &errStatus, sgx_status_t status = SGX_SUCCESS;
errMsg.data(), encryptedKey.data(), decLen, hashHex,
signatureR.data(),
signatureS.data(), &signatureV, base);
if (errStatus != 0) { RESTART_BEGIN
spdlog::error("failed to sign {}", errStatus); status = trustedEcdsaSign(eid, &errStatus,
throw SGXException(666, errMsg.data()); errMsg.data(), encryptedKey.data(), decLen, hashHex,
} signatureR.data(),
signatureS.data(), &signatureV, base);
RESTART_END
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, 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());
...@@ -224,3 +228,30 @@ vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *ha ...@@ -224,3 +228,30 @@ vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *ha
return signatureVector; return signatureVector;
} }
string encryptECDSAKey(const string& _key) {
vector<char> key(BUF_LEN, 0);
for (size_t i = 0; i < _key.size(); ++i) {
key[i] = _key[i];
}
vector<uint8_t> encryptedKey(BUF_LEN, 0);
int errStatus = 0;
vector<char> errString(BUF_LEN, 0);
uint64_t enc_len = 0;
sgx_status_t status = SGX_SUCCESS;
RESTART_BEGIN
status = trustedEncryptKey(eid, &errStatus, errString.data(), key.data(),
encryptedKey.data(), &enc_len);
RESTART_END
if (status != 0) {
throw SGXException(status, string("Could not encrypt ECDSA key: " + string(errString.begin(), errString.end())).c_str());
}
vector<char> hexEncrKey = carray2Hex(encryptedKey.data(), enc_len);
return string(hexEncrKey.begin(), hexEncrKey.end());
}
...@@ -35,5 +35,7 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex); ...@@ -35,5 +35,7 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex);
vector<string> ecdsaSignHash(const std::string& encryptedKeyHex, const char* hashHex, int base); vector<string> ecdsaSignHash(const std::string& encryptedKeyHex, const char* hashHex, int base);
string encryptECDSAKey(const string& key);
#endif //SGXD_ECDSACRYPTO_H #endif //SGXD_ECDSACRYPTO_H
#include "secure_enclave/Point.c" #include "secure_enclave/Point.c"
#include "secure_enclave/DomainParameters.c" #include "secure_enclave/DomainParameters.cpp"
#include "secure_enclave/NumberTheory.c" #include "secure_enclave/NumberTheory.c"
#include "secure_enclave/Signature.c" #include "secure_enclave/Signature.c"
#include "secure_enclave/Curves.c" #include "secure_enclave/Curves.c"
...@@ -154,17 +154,16 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){ ...@@ -154,17 +154,16 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
return keys; return keys;
} }
void LevelDB::writeDataUnique(const string & Name, const string &value) { void LevelDB::writeDataUnique(const string & name, const string &value) {
auto key = Name; auto key = name;
if (readString(Name) != nullptr) { if (readString(name)) {
spdlog::debug("name {}",Name, " already exists"); spdlog::debug("Name {} already exists", name);
throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists"); throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
} }
writeString(key, value); writeString(key, value);
} }
......
...@@ -64,6 +64,7 @@ bin_PROGRAMS = sgxwallet testw cert_util ...@@ -64,6 +64,7 @@ bin_PROGRAMS = sgxwallet testw cert_util
## You can't use $(wildcard ...) with automake so all source files ## You can't use $(wildcard ...) with automake so all source files
## have to be explicitly listed. ## have to be explicitly listed.
## have to be explicitly listed
COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \ COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \
SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp \ SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp \
...@@ -102,7 +103,7 @@ sgxwallet_LDADD=-l$(SGX_URTS_LIB) -l$(SGX_UAE_SERVICE_LIB) -LlibBLS/deps/deps_in ...@@ -102,7 +103,7 @@ sgxwallet_LDADD=-l$(SGX_URTS_LIB) -l$(SGX_UAE_SERVICE_LIB) -LlibBLS/deps/deps_in
-l:libbls.a -l:libleveldb.a \ -l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ldl -l:libsgx_capable.a -l:libsgx_tprotected_fs.a \ -l:libff.a -lgmp -ldl -l:libsgx_capable.a -l:libsgx_tprotected_fs.a \
-ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd \ -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd \
-lboost_system -lboost_thread -lgnutls -lgcrypt -lcurl -lssl -lcrypto -lz -lpthread -lstdc++fs -lboost_system -lboost_thread -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -lstdc++fs
testw_SOURCES=testw.cpp $(COMMON_SRC) testw_SOURCES=testw.cpp $(COMMON_SRC)
...@@ -114,4 +115,4 @@ cert_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentExcep ...@@ -114,4 +115,4 @@ cert_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentExcep
cert_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \ cert_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \
-LlibBLS/build/libff/libff \ -LlibBLS/build/libff/libff \
-l:libbls.a -l:libleveldb.a \ -l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lcurl -lssl -lcrypto -lz -lpthread -ldl -l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -ldl
...@@ -21,21 +21,25 @@ ...@@ -21,21 +21,25 @@
@date 2020 @date 2020
*/ */
#include "SEKManager.h"
#include "SGXException.h"
#include "BLSCrypto.h"
#include "LevelDB.h"
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <algorithm> #include <algorithm>
#include "third_party/spdlog/spdlog.h"
#include "sgxwallet_common.h" #include "sgxwallet_common.h"
#include "common.h" #include "common.h"
#include "sgxwallet.h" #include "sgxwallet.h"
#include "SGXException.h"
#include "BLSCrypto.h"
#include "LevelDB.h"
#include "ServerDataChecker.h" #include "ServerDataChecker.h"
#include "third_party/spdlog/spdlog.h" #include "ServerInit.h"
#include "SEKManager.h"
using namespace std; using namespace std;
...@@ -52,82 +56,88 @@ bool case_insensitive_match(string s1, string s2) { ...@@ -52,82 +56,88 @@ bool case_insensitive_match(string s1, string s2) {
void create_test_key() { void create_test_key() {
int errStatus = 0; int errStatus = 0;
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
uint32_t enc_len; uint64_t enc_len;
uint8_t encrypted_key[BUF_LEN]; SAFE_UINT8_BUF(encrypted_key, BUF_LEN);
memset(encrypted_key, 0, BUF_LEN);
string key = TEST_VALUE; string key = TEST_VALUE;
status = trustedEncryptKeyAES(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len); sgx_status_t status = SGX_SUCCESS;
if (status != SGX_SUCCESS) {
cerr << "encrypt test key failed with status " << status << endl;
throw SGXException(status, errMsg.data());
}
if (errStatus != 0) { {
cerr << "encrypt test key failed with status " << errStatus << endl; READ_LOCK(sgxInitMutex);
throw SGXException(errStatus, errMsg.data()); status = trustedEncryptKey(eid, &errStatus, errMsg.data(), key.c_str(), encrypted_key, &enc_len);
} }
vector<char> hexEncrKey(2 * enc_len + 1, 0); HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
carray2Hex(encrypted_key, enc_len, hexEncrKey.data()); vector<char> hexEncrKey = carray2Hex(encrypted_key, enc_len);
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());
} }
shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) { void validate_SEK() {
shared_ptr <string> test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY"); shared_ptr <string> test_key_ptr = LevelDB::getLevelDb()->readString("TEST_KEY");
vector <uint8_t> encr_test_key(BUF_LEN, 0); vector <uint8_t> encr_test_key(BUF_LEN, 0);
uint64_t len; vector<char> decr_key(BUF_LEN, 0);
if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data())) { uint64_t len = 0;
spdlog::error("wrong test key"); vector<char> errMsg(BUF_LEN, 0);
exit(-1);
}
vector<char> decr_key(1024, 0);
vector<char> errMsg(1024, 0);
int err_status = 0; int err_status = 0;
auto encrypted_SEK = make_shared < vector < uint8_t >> (1024, 0); if (!hex2carray(test_key_ptr->c_str(), &len, encr_test_key.data(),
BUF_LEN)) {
uint32_t l = len; spdlog::error("Corrupt test key is LevelDB");
status = trustedSetSEK_backup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l, SEK.c_str());
if (status != SGX_SUCCESS) {
spdlog::error("trustedSetSEK_backup failed with error code {}", status);
exit(-1); exit(-1);
} }
if (err_status != 0) { sgx_status_t status = SGX_SUCCESS;
spdlog::error("trustedSetSEK_backup failed with error status {}", status);
exit(-1);
}
status = trustedDecryptKeyAES(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data()); {
if (status != SGX_SUCCESS || err_status != 0) { READ_LOCK(sgxInitMutex);
spdlog::error("Failed to decrypt test key"); status = trustedDecryptKey(eid, &err_status, errMsg.data(), encr_test_key.data(), len, decr_key.data());
spdlog::error(errMsg.data());
exit(-1);
} }
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
string test_key = TEST_VALUE; string test_key = TEST_VALUE;
if (test_key.compare(decr_key.data()) != 0) { if (test_key.compare(decr_key.data()) != 0) {
spdlog::error("Invalid SEK"); spdlog::error("Invalid storage key. You need to recover using backup key");
spdlog::error("Set the correct backup key into sgx_datasgxwallet_backup_key.txt");
spdlog::error("Then run sgxwallet using backup flag");
exit(-1); exit(-1);
} }
}
shared_ptr <vector<uint8_t>> check_and_set_SEK(const string &SEK) {
vector<char> decr_key(BUF_LEN, 0);
vector<char> errMsg(BUF_LEN, 0);
int err_status = 0;
auto encrypted_SEK = make_shared < vector < uint8_t >> (BUF_LEN, 0);
uint64_t l = 0;
sgx_status_t status = SGX_SUCCESS;
{
READ_LOCK(sgxInitMutex);
status = trustedSetSEKBackup(eid, &err_status, errMsg.data(), encrypted_SEK->data(), &l,
SEK.c_str());
}
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
encrypted_SEK->resize(l); encrypted_SEK->resize(l);
validate_SEK();
return encrypted_SEK; return encrypted_SEK;
} }
...@@ -135,30 +145,29 @@ void gen_SEK() { ...@@ -135,30 +145,29 @@ void gen_SEK() {
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
int err_status = 0; int err_status = 0;
vector <uint8_t> encrypted_SEK(1024, 0); vector <uint8_t> encrypted_SEK(1024, 0);
uint32_t enc_len = 0; uint64_t enc_len = 0;
char SEK[65]; SAFE_CHAR_BUF(SEK, 65);
memset(SEK, 0, 65);
spdlog::info("Generating backup key. Will be stored in backup_key.txt ... "); spdlog::info("Generating backup key. Will be stored in backup_key.txt ... ");
status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK);
if (status != SGX_SUCCESS) { sgx_status_t status = SGX_SUCCESS;
throw SGXException(status, errMsg.data()); {
}
if (err_status != 0) { status = trustedGenerateSEK(eid, &err_status, errMsg.data(), encrypted_SEK.data(), &enc_len, SEK);
throw SGXException(err_status, errMsg.data());
} }
HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
if (strnlen(SEK, 33) != 32) { if (strnlen(SEK, 33) != 32) {
throw SGXException(-1, "strnlen(SEK,33) != 32"); throw SGXException(-1, "strnlen(SEK,33) != 32");
} }
vector<char> hexEncrKey(2 * enc_len + 1, 0); vector<char> hexEncrKey = carray2Hex(encrypted_SEK.data(), enc_len);
carray2Hex(encrypted_SEK.data(), enc_len, hexEncrKey.data()); spdlog::info(string("Encrypted storage encryption key:") + hexEncrKey.data());
ofstream sek_file(BACKUP_PATH); ofstream sek_file(BACKUP_PATH);
sek_file.clear(); sek_file.clear();
...@@ -185,31 +194,51 @@ void gen_SEK() { ...@@ -185,31 +194,51 @@ void gen_SEK() {
LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data()); LevelDB::getLevelDb()->writeDataUnique("SEK", hexEncrKey.data());
create_test_key(); create_test_key();
validate_SEK();
shared_ptr <string> encrypted_SEK_ptr = LevelDB::getLevelDb()->readString("SEK");
setSEK(encrypted_SEK_ptr);
validate_SEK();
} }
void trustedSetSEK(shared_ptr <string> hex_encrypted_SEK) { void reinitEnclave() {
// unfortunately process needs to be restarted to reinit enclave
// exiting with error code 3 (SGX_OUT_OF_MEMORY), so docker container can restart the
// wallet
exit(3);
}
void setSEK(shared_ptr <string> hex_encrypted_SEK) {
CHECK_STATE(hex_encrypted_SEK);
vector<char> errMsg(1024, 0); vector<char> errMsg(1024, 0);
int err_status = 0; int err_status = 0;
uint8_t encrypted_SEK[BUF_LEN]; SAFE_UINT8_BUF(encrypted_SEK, BUF_LEN);
memset(encrypted_SEK, 0, BUF_LEN);
uint64_t len; uint64_t len = 0;
if (!hex2carray(hex_encrypted_SEK->c_str(), &len, encrypted_SEK)) { if (!hex2carray(hex_encrypted_SEK->c_str(), &len, encrypted_SEK,
BUF_LEN)) {
throw SGXException(INVALID_HEX, "Invalid encrypted SEK Hex"); throw SGXException(INVALID_HEX, "Invalid encrypted SEK Hex");
} }
status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK); sgx_status_t status = SGX_SUCCESS;
if (status != SGX_SUCCESS) { {
cerr << "RPCException thrown" << endl; status = trustedSetSEK(eid, &err_status, errMsg.data(), encrypted_SEK);
throw SGXException(status, errMsg.data());
} }
if (err_status != 0) { HANDLE_TRUSTED_FUNCTION_ERROR(status, err_status, errMsg.data());
cerr << "RPCException thrown" << endl;
throw SGXException(err_status, errMsg.data());
} validate_SEK();
} }
#include "experimental/filesystem" #include "experimental/filesystem"
...@@ -218,7 +247,6 @@ void trustedSetSEK(shared_ptr <string> hex_encrypted_SEK) { ...@@ -218,7 +247,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");
...@@ -249,9 +277,7 @@ void enter_SEK() { ...@@ -249,9 +277,7 @@ void enter_SEK() {
auto encrypted_SEK = check_and_set_SEK(sek); auto encrypted_SEK = check_and_set_SEK(sek);
vector<char> hexEncrKey(BUF_LEN, 0); vector<char> hexEncrKey = carray2Hex(encrypted_SEK->data(), encrypted_SEK->size());
carray2Hex(encrypted_SEK->data(), encrypted_SEK->size(), hexEncrKey.data());
spdlog::info("Got sealed storage encryption key."); spdlog::info("Got sealed storage encryption key.");
...@@ -274,7 +300,7 @@ void initSEK() { ...@@ -274,7 +300,7 @@ void initSEK() {
spdlog::warn("SEK was not created yet. Going to create SEK"); spdlog::warn("SEK was not created yet. Going to create SEK");
gen_SEK(); gen_SEK();
} else { } else {
trustedSetSEK(encrypted_SEK_ptr); setSEK(encrypted_SEK_ptr);
} }
} }
} }
......
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
void gen_SEK(); void gen_SEK();
#ifdef __cplusplus #ifdef __cplusplus
void trustedSetSEK(std::shared_ptr<std::string> hex_encr_SEK); void setSEK(std::shared_ptr<std::string> hex_encr_SEK);
#endif #endif
#ifdef __cplusplus #ifdef __cplusplus
...@@ -45,4 +45,11 @@ EXTERNC void enter_SEK(); ...@@ -45,4 +45,11 @@ EXTERNC void enter_SEK();
EXTERNC void initSEK(); EXTERNC void initSEK();
EXTERNC void setSEK();
EXTERNC void reinitEnclave();
#endif //SGXD_SEKMANAGER_H #endif //SGXD_SEKMANAGER_H
...@@ -54,6 +54,9 @@ ...@@ -54,6 +54,9 @@
using namespace std; using namespace std;
std::shared_timed_mutex sgxInitMutex;
uint64_t initTime;
void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) { void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) {
spdlog::info("Entering {}", __FUNCTION__); spdlog::info("Entering {}", __FUNCTION__);
...@@ -190,7 +193,16 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k ...@@ -190,7 +193,16 @@ SGXWalletServer::importBLSKeyShareImpl(const string &_keyShare, const string &_k
throw SGXException(INVALID_BLS_NAME, "Invalid BLS key name"); throw SGXException(INVALID_BLS_NAME, "Invalid BLS key name");
} }
encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, (char *) errMsg.data(), _keyShare.c_str()); string hashTmp = _keyShare;
if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) {
hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2);
}
if (!checkHex(hashTmp)) {
throw SGXException(INVALID_HEX, "Invalid BLS key share, please use hex");
}
encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, (char *) errMsg.data(), hashTmp.c_str());
if (errStatus != 0) { if (errStatus != 0) {
throw SGXException(errStatus, errMsg.data()); throw SGXException(errStatus, errMsg.data());
...@@ -243,6 +255,7 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin ...@@ -243,6 +255,7 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin
} }
value = readFromDb(_keyShareName); value = readFromDb(_keyShareName);
if (!bls_sign(value->c_str(), _messageHash.c_str(), t, n, signature.data())) { if (!bls_sign(value->c_str(), _messageHash.c_str(), t, n, signature.data())) {
throw SGXException(-1, "Could not sign data "); throw SGXException(-1, "Could not sign data ");
} }
...@@ -255,6 +268,37 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin ...@@ -255,6 +268,37 @@ SGXWalletServer::blsSignMessageHashImpl(const string &_keyShareName, const strin
} }
Json::Value SGXWalletServer::importECDSAKeyImpl(const string &_keyShare,
const string &_keyShareName) {
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
result["encryptedKey"] = "";
try {
if (!checkECDSAKeyName(_keyShareName)) {
throw SGXException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
string hashTmp = _keyShare;
if (hashTmp[0] == '0' && (hashTmp[1] == 'x' || hashTmp[1] == 'X')) {
hashTmp.erase(hashTmp.begin(), hashTmp.begin() + 2);
}
if (!checkHex(hashTmp)) {
throw SGXException(INVALID_HEX, "Invalid ECDSA key share, please use hex");
}
string encryptedKey = encryptECDSAKey(hashTmp);
writeDataToDB(_keyShareName, encryptedKey);
result["encryptedKey"] = encryptedKey;
result["publicKey"] = getECDSAPubKey(encryptedKey);
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result);
}
Json::Value SGXWalletServer::generateECDSAKeyImpl() { Json::Value SGXWalletServer::generateECDSAKeyImpl() {
spdlog::info("Entering {}", __FUNCTION__); spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result) INIT_RESULT(result)
...@@ -384,7 +428,7 @@ Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName, ...@@ -384,7 +428,7 @@ Json::Value SGXWalletServer::getVerificationVectorImpl(const string &_polyName,
shared_ptr <string> encrPoly = readFromDb(_polyName); shared_ptr <string> encrPoly = readFromDb(_polyName);
verifVector = get_verif_vect(encrPoly->c_str(), _t, _n); verifVector = get_verif_vect(*encrPoly, _t, _n);
for (int i = 0; i < _t; i++) { for (int i = 0; i < _t; i++) {
vector <string> currentCoef = verifVector.at(i); vector <string> currentCoef = verifVector.at(i);
...@@ -402,7 +446,6 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J ...@@ -402,7 +446,6 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
spdlog::info("Entering {}", __FUNCTION__); spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result); INIT_RESULT(result);
result["secretShare"] = ""; result["secretShare"] = "";
result["SecretShare"] = "";
try { try {
if (_pubKeys.size() != (uint64_t) _n) { if (_pubKeys.size() != (uint64_t) _n) {
...@@ -425,9 +468,15 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J ...@@ -425,9 +468,15 @@ Json::Value SGXWalletServer::getSecretShareImpl(const string &_polyName, const J
pubKeysStrs.push_back(_pubKeys[i].asString()); pubKeysStrs.push_back(_pubKeys[i].asString());
} }
string s = trustedGetSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n); string secret_share_name = "encryptedSecretShare:" + _polyName;
result["secretShare"] = s; shared_ptr <string> encryptedSecretShare = checkDataFromDb(secret_share_name);
result["SecretShare"] = s;
if (encryptedSecretShare != nullptr) {
result["secretShare"] = *encryptedSecretShare.get();
} else {
string s = getSecretShares(_polyName, encrPoly->c_str(), pubKeysStrs, _t, _n);
result["secretShare"] = s;
}
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result) RETURN_SUCCESS(result)
...@@ -489,7 +538,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string ...@@ -489,7 +538,7 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName); shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
bool res = CreateBLSShare(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str()); bool res = createBLSShare(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str());
if (res) { if (res) {
spdlog::info("BLS KEY SHARE CREATED "); spdlog::info("BLS KEY SHARE CREATED ");
} else { } else {
...@@ -504,6 +553,9 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string ...@@ -504,6 +553,9 @@ SGXWalletServer::createBLSPrivateKeyImpl(const string &_blsKeyName, const string
} }
LevelDB::getLevelDb()->deleteKey(_polyName); LevelDB::getLevelDb()->deleteKey(_polyName);
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName);
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result); RETURN_SUCCESS(result);
...@@ -519,7 +571,7 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName) ...@@ -519,7 +571,7 @@ Json::Value SGXWalletServer::getBLSPublicKeyShareImpl(const string &_blsKeyName)
} }
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_blsKeyName); shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_blsKeyName);
vector <string> public_key_vect = GetBLSPubKey(encryptedKeyHex_ptr->c_str()); vector <string> public_key_vect = getBLSPubKey(encryptedKeyHex_ptr->c_str());
for (uint8_t i = 0; i < 4; i++) { for (uint8_t i = 0; i < 4; i++) {
result["blsPublicKeyShare"][i] = public_key_vect.at(i); result["blsPublicKeyShare"][i] = public_key_vect.at(i);
} }
...@@ -562,7 +614,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu ...@@ -562,7 +614,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu
vector<string> public_keys = calculateAllBlsPublicKeys(public_shares); vector<string> public_keys = calculateAllBlsPublicKeys(public_shares);
if (public_keys.size() != n) { if (public_keys.size() != (uint64_t)n) {
throw SGXException(UNKNOWN_ERROR, ""); throw SGXException(UNKNOWN_ERROR, "");
} }
...@@ -574,7 +626,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu ...@@ -574,7 +626,7 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeysImpl(const Json::Value& pu
RETURN_SUCCESS(result); RETURN_SUCCESS(result);
} }
Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _ind) { Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int _t, int _n, int _ind) {
spdlog::info("Entering {}", __FUNCTION__); spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result) INIT_RESULT(result)
...@@ -590,6 +642,28 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int ...@@ -590,6 +642,28 @@ Json::Value SGXWalletServer::complaintResponseImpl(const string &_polyName, int
result["share*G2"] = *shareG2_ptr; result["share*G2"] = *shareG2_ptr;
result["dhKey"] = DHKey; result["dhKey"] = DHKey;
shared_ptr <string> encrPoly = readFromDb(_polyName);
auto verificationVectorMult = getVerificationVectorMult(encrPoly->c_str(), _t, _n, _ind);
for (int i = 0; i < _t; i++) {
vector <string> currentCoef = verificationVectorMult.at(i);
for (int j = 0; j < 4; j++) {
result["verificationVectorMult"][i][j] = currentCoef.at(j);
}
}
for (int i = 0; i < _n; i++) {
string name = _polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb()->deleteDHDKGKey(name);
string shareG2_name = "shareG2_" + _polyName + "_" + to_string(i) + ":";
LevelDB::getLevelDb()->deleteKey(shareG2_name);
}
LevelDB::getLevelDb()->deleteKey(_polyName);
string encryptedSecretShareName = "encryptedSecretShare:" + _polyName;
LevelDB::getLevelDb()->deleteKey(encryptedSecretShareName);
} HANDLE_SGX_EXCEPTION(result) } HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result); RETURN_SUCCESS(result);
...@@ -692,6 +766,10 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeys(const Json::Value& public ...@@ -692,6 +766,10 @@ Json::Value SGXWalletServer::calculateAllBLSPublicKeys(const Json::Value& public
return calculateAllBLSPublicKeysImpl(publicShares, t, n); return calculateAllBLSPublicKeysImpl(publicShares, t, n);
} }
Json::Value SGXWalletServer::importECDSAKey(const std::string& keyShare, const std::string& keyShareName) {
return importECDSAKeyImpl(keyShare, keyShareName);
}
Json::Value SGXWalletServer::generateECDSAKey() { Json::Value SGXWalletServer::generateECDSAKey() {
return generateECDSAKeyImpl(); return generateECDSAKeyImpl();
} }
...@@ -713,8 +791,8 @@ Json::Value SGXWalletServer::blsSignMessageHash(const string &_keyShareName, con ...@@ -713,8 +791,8 @@ Json::Value SGXWalletServer::blsSignMessageHash(const string &_keyShareName, con
return blsSignMessageHashImpl(_keyShareName, _messageHash, _t, _n); return blsSignMessageHashImpl(_keyShareName, _messageHash, _t, _n);
} }
Json::Value SGXWalletServer::complaintResponse(const string &polyName, int ind) { Json::Value SGXWalletServer::complaintResponse(const string &polyName, int t, int n, int ind) {
return complaintResponseImpl(polyName, ind); return complaintResponseImpl(polyName, t, n, ind);
} }
Json::Value SGXWalletServer::multG2(const string &x) { Json::Value SGXWalletServer::multG2(const string &x) {
...@@ -738,7 +816,7 @@ Json::Value SGXWalletServer::deleteBlsKey(const string &name) { ...@@ -738,7 +816,7 @@ Json::Value SGXWalletServer::deleteBlsKey(const string &name) {
} }
shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) { shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) {
auto dataStr = LevelDB::getLevelDb()->readString(prefix + name); auto dataStr = checkDataFromDb(prefix + name);
if (dataStr == nullptr) { if (dataStr == nullptr) {
throw SGXException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exist"); throw SGXException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exist");
...@@ -747,6 +825,12 @@ shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string ...@@ -747,6 +825,12 @@ shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string
return dataStr; return dataStr;
} }
shared_ptr <string> SGXWalletServer::checkDataFromDb(const string &name, const string &prefix) {
auto dataStr = LevelDB::getLevelDb()->readString(prefix + name);
return dataStr;
}
void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_value) { void SGXWalletServer::writeKeyShare(const string &_keyShareName, const string &_value) {
if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) { if (LevelDB::getLevelDb()->readString(_keyShareName) != nullptr) {
throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists"); throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
......
...@@ -51,6 +51,9 @@ public: ...@@ -51,6 +51,9 @@ public:
virtual Json::Value virtual Json::Value
blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n); blsSignMessageHash(const string &_keyShareName, const string &_messageHash, int _t, int _n);
virtual Json::Value importECDSAKey(const std::string& keyShare,
const std::string& keyShareName);
virtual Json::Value generateECDSAKey(); virtual Json::Value generateECDSAKey();
virtual Json::Value virtual Json::Value
...@@ -76,7 +79,7 @@ public: ...@@ -76,7 +79,7 @@ public:
virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n); virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n);
virtual Json::Value complaintResponse(const string &polyName, int ind); virtual Json::Value complaintResponse(const string &polyName, int t, int n, int ind);
virtual Json::Value multG2(const string &x); virtual Json::Value multG2(const string &x);
...@@ -90,6 +93,8 @@ public: ...@@ -90,6 +93,8 @@ public:
static shared_ptr<string> readFromDb(const string &name, const string &prefix = ""); static shared_ptr<string> readFromDb(const string &name, const string &prefix = "");
static shared_ptr <string> checkDataFromDb(const string &name, const string &prefix = "");
static void writeDataToDB(const string &Name, const string &value); static void writeDataToDB(const string &Name, const string &value);
static void writeKeyShare(const string &_keyShareName, const string &_value); static void writeKeyShare(const string &_keyShareName, const string &_value);
...@@ -100,6 +105,8 @@ public: ...@@ -100,6 +105,8 @@ public:
static Json::Value static Json::Value
blsSignMessageHashImpl(const string &_keyShareName, const string &_messageHash, int t, int n); blsSignMessageHashImpl(const string &_keyShareName, const string &_messageHash, int t, int n);
static Json::Value importECDSAKeyImpl(const string &_keyShare, const string &_keyShareName);
static Json::Value generateECDSAKeyImpl(); static Json::Value generateECDSAKeyImpl();
static Json::Value ecdsaSignMessageHashImpl(int _base, const string &keyName, const string &_messageHash); static Json::Value ecdsaSignMessageHashImpl(int _base, const string &keyName, const string &_messageHash);
...@@ -124,7 +131,7 @@ public: ...@@ -124,7 +131,7 @@ public:
static Json::Value calculateAllBLSPublicKeysImpl(const Json::Value& publicShares, int t, int n); static Json::Value calculateAllBLSPublicKeysImpl(const Json::Value& publicShares, int t, int n);
static Json::Value complaintResponseImpl(const string &_polyName, int _ind); static Json::Value complaintResponseImpl(const string &_polyName, int t, int n, int _ind);
static Json::Value multG2Impl(const string &_x); static Json::Value multG2Impl(const string &_x);
......
...@@ -72,7 +72,7 @@ bool checkECDSAKeyName(const string& keyName) { ...@@ -72,7 +72,7 @@ bool checkECDSAKeyName(const string& keyName) {
bool checkHex(const string& hex, const uint32_t sizeInBytes){ bool checkHex(const string& hex, const uint32_t sizeInBytes){
if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){ if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){
spdlog::error("key is too long or zero - ", hex.length()); spdlog::error("key is too long or zero {} ", hex.length());
return false; return false;
} }
......
...@@ -57,6 +57,8 @@ ...@@ -57,6 +57,8 @@
#include "SGXException.h" #include "SGXException.h"
#include "SGXWalletServer.hpp" #include "SGXWalletServer.hpp"
uint32_t enclaveLogLevel = 0;
void initUserSpace() { void initUserSpace() {
libff::inhibit_profiling_counters = true; libff::inhibit_profiling_counters = true;
...@@ -66,9 +68,8 @@ void initUserSpace() { ...@@ -66,9 +68,8 @@ void initUserSpace() {
LevelDB::initDataFolderAndDBs(); LevelDB::initDataFolderAndDBs();
} }
void initEnclave(uint32_t _logLevel) { uint64_t initEnclave() {
eid = 0;
updated = 0;
#ifndef SGX_HW_SIM #ifndef SGX_HW_SIM
unsigned long support; unsigned long support;
...@@ -81,35 +82,57 @@ void initEnclave(uint32_t _logLevel) { ...@@ -81,35 +82,57 @@ 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_SUCCESS;
&updated, &eid, 0);
if (status != SGX_SUCCESS) { {
if (status == SGX_ERROR_ENCLAVE_FILE_ACCESS) {
spdlog::error("sgx_create_enclave: {}: file not found", ENCLAVE_NAME); WRITE_LOCK(sgxInitMutex);
spdlog::error("Did you forget to set LD_LIBRARY_PATH?");
} else { if (eid != 0) {
spdlog::error("sgx_create_enclave_search failed {} {}", ENCLAVE_NAME, status); if (sgx_destroy_enclave(eid) != SGX_SUCCESS) {
spdlog::error("Could not destroy enclave");
}
} }
exit(1);
}
spdlog::info("Enclave created and started successfully"); eid = 0;
updated = 0;
status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token,
&updated, &eid, 0);
if (status != SGX_SUCCESS) {
if (status == SGX_ERROR_ENCLAVE_FILE_ACCESS) {
spdlog::error("sgx_create_enclave: {}: file not found", ENCLAVE_NAME);
spdlog::error("Did you forget to set LD_LIBRARY_PATH?");
} else {
spdlog::error("sgx_create_enclave_search failed {} {}", ENCLAVE_NAME, status);
}
exit(1);
}
spdlog::info("Enclave created and started successfully");
status = trustedEnclaveInit(eid, enclaveLogLevel);
}
status = trustedEnclaveInit(eid, _logLevel);
if (status != SGX_SUCCESS) { if (status != SGX_SUCCESS) {
spdlog::error("trustedEnclaveInit failed: {}", status); spdlog::error("trustedEnclaveInit failed: {}", status);
exit(1); return status;
} }
spdlog::info("Enclave libtgmp library and logging initialized successfully"); spdlog::info("Enclave libtgmp library and logging initialized successfully");
return SGX_SUCCESS;
} }
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) { void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
static atomic<bool> sgxServerInited(false); static atomic<bool> sgxServerInited(false);
static mutex initMutex; static mutex initMutex;
enclaveLogLevel = _logLevel;
lock_guard <mutex> lock(initMutex); lock_guard <mutex> lock(initMutex);
...@@ -122,7 +145,19 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) { ...@@ -122,7 +145,19 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
CHECK_STATE(sgxServerInited != 1) CHECK_STATE(sgxServerInited != 1)
sgxServerInited = 1; sgxServerInited = 1;
initEnclave(_logLevel);
uint64_t counter = 0;
uint64_t initResult = 0;
while ((initResult = initEnclave()) != 0 && counter < 10){
sleep(1);
counter ++;
}
if (initResult != 0) {
spdlog::error("Coult not init enclave");
}
initUserSpace(); initUserSpace();
initSEK(); initSEK();
...@@ -136,12 +171,15 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) { ...@@ -136,12 +171,15 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
sgxServerInited = true; sgxServerInited = true;
} catch (SGXException &_e) { } catch (SGXException &_e) {
spdlog::error(_e.getMessage()); spdlog::error(_e.getMessage());
exit(-1);
} catch (exception &_e) { } catch (exception &_e) {
spdlog::error(_e.what()); spdlog::error(_e.what());
exit(-1);
} }
catch (...) { catch (...) {
exception_ptr p = current_exception(); exception_ptr p = current_exception();
printf("Exception %s \n", p.__cxa_exception_type()->name()); printf("Exception %s \n", p.__cxa_exception_type()->name());
spdlog::error("Unknown exception"); spdlog::error("Unknown exception");
exit(-1);
} }
}; };
...@@ -36,7 +36,7 @@ EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign); ...@@ -36,7 +36,7 @@ EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign);
EXTERNC void initUserSpace(); EXTERNC void initUserSpace();
EXTERNC void initEnclave(uint32_t _logLevel); EXTERNC uint64_t initEnclave();
......
...@@ -21,17 +21,15 @@ ...@@ -21,17 +21,15 @@
@date 2020 @date 2020
*/ */
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h> #include <dkg/dkg.h>
#include <jsonrpccpp/server/connectors/httpserver.h> #include <jsonrpccpp/server/connectors/httpserver.h>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp> #include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <libff/algebra/exponentiation/exponentiation.hpp>
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h> #include <dkg/dkg.h>
#include "sgxwallet_common.h" #include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h" #include "third_party/intel/create_enclave.h"
#include "secure_enclave_u.h" #include "secure_enclave_u.h"
#include "third_party/intel/sgx_detect.h" #include "third_party/intel/sgx_detect.h"
#include "third_party/spdlog/spdlog.h"
#include <gmp.h> #include <gmp.h>
#include <sgx_urts.h> #include <sgx_urts.h>
#include <stdio.h> #include <stdio.h>
...@@ -218,7 +216,7 @@ void TestUtils::sendRPCRequest() { ...@@ -218,7 +216,7 @@ void TestUtils::sendRPCRequest() {
auto hash_arr = make_shared < array < uint8_t, 32 >> (); auto hash_arr = make_shared < array < uint8_t, 32 >> ();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) { if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
...@@ -351,7 +349,7 @@ void TestUtils::doDKG(StubClient &c, int n, int t, ...@@ -351,7 +349,7 @@ void TestUtils::doDKG(StubClient &c, int n, int t,
auto hash_arr = make_shared<array<uint8_t, 32 >>(); auto hash_arr = make_shared<array<uint8_t, 32 >>();
uint64_t binLen; uint64_t binLen;
if (!hex2carray(hash.c_str(), &binLen, hash_arr->data())) { if (!hex2carray(hash.c_str(), &binLen, hash_arr->data(), 32)) {
throw SGXException(INVALID_HEX, "Invalid hash"); throw SGXException(INVALID_HEX, "Invalid hash");
} }
...@@ -411,3 +409,126 @@ void TestUtils::doDKG(StubClient &c, int n, int t, ...@@ -411,3 +409,126 @@ void TestUtils::doDKG(StubClient &c, int n, int t,
for (auto&& i : _blsKeyNames) for (auto&& i : _blsKeyNames)
cerr << i << endl; cerr << i << endl;
} }
int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key) {
int ret = -1;
SAFE_CHAR_BUF(pb_keyB_x, 65);
SAFE_CHAR_BUF(pb_keyB_y, 65);
mpz_t skey;
mpz_init(skey);
point pub_keyB = point_init();
point session_key = point_init();
pb_keyB_x[64] = 0;
strncpy(pb_keyB_x, sshare, 64);
strncpy(pb_keyB_y, sshare + 64, 64);
pb_keyB_y[64] = 0;
if (!common_key) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
common_key[0] = 0;
if (!skey_str) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
if (!sshare) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
if (mpz_set_str(skey, skey_str, 16) == -1) {
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
domain_parameters curve;
curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
if (point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y) != 0) {
return ret;
}
point_multiplication(session_key, skey, pub_keyB, curve);
SAFE_CHAR_BUF(arr_x, BUF_LEN);
mpz_get_str(arr_x, 16, session_key->x);
int n_zeroes = 64 - strlen(arr_x);
for (int i = 0; i < n_zeroes; i++) {
common_key[i] = '0';
}
strncpy(common_key + n_zeroes, arr_x, strlen(arr_x));
ret = 0;
mpz_clear(skey);
point_clear(pub_keyB);
point_clear(session_key);
return ret;
}
int xorDecryptDH(char *key, const char *cypher, vector<char>& message) {
int ret = -1;
if (!cypher) {
return ret;
}
if (!key) {
return ret;
}
if (!message.data()) {
return ret;
}
SAFE_CHAR_BUF(msg_bin,33)
SAFE_CHAR_BUF(key_bin,33)
uint64_t key_length;
if (!hex2carray(key, &key_length, (uint8_t*) key_bin, 33)) {
return ret;
}
uint64_t cypher_length;
SAFE_CHAR_BUF(cypher_bin, 33);
if (!hex2carray(cypher, &cypher_length, (uint8_t *) cypher_bin, 33)) {
return ret;
}
for (int i = 0; i < 32; i++) {
msg_bin[i] = cypher_bin[i] ^ key_bin[i];
}
message = carray2Hex((unsigned char*) msg_bin, 32);
ret = 0;
return ret;
}
...@@ -24,12 +24,11 @@ ...@@ -24,12 +24,11 @@
#ifndef SGXWALLET_TESTUTILS_H #ifndef SGXWALLET_TESTUTILS_H
#define SGXWALLET_TESTUTILS_H #define SGXWALLET_TESTUTILS_H
#include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h> #include <dkg/dkg.h>
#include <jsonrpccpp/server/connectors/httpserver.h> #include <jsonrpccpp/server/connectors/httpserver.h>
#include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp> #include <libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <libff/algebra/exponentiation/exponentiation.hpp> // #include <libff/algebra/exponentiation/exponentiation.hpp>
#include <libff/algebra/fields/fp.hpp> // #include <libff/algebra/fields/fp.hpp>
#include <dkg/dkg.h> #include <dkg/dkg.h>
#include "sgxwallet_common.h" #include "sgxwallet_common.h"
#include "third_party/intel/create_enclave.h" #include "third_party/intel/create_enclave.h"
...@@ -78,4 +77,8 @@ public: ...@@ -78,4 +77,8 @@ public:
int schainID, int dkgID); int schainID, int dkgID);
}; };
int sessionKeyRecoverDH(const char *skey_str, const char *sshare, char *common_key);
int xorDecryptDH(char *key, const char *cypher, vector<char>& message);
#endif //SGXWALLET_TESTW_H #endif //SGXWALLET_TESTW_H
1.58.0 1.58.6
\ No newline at end of file \ No newline at end of file
...@@ -39,6 +39,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer> ...@@ -39,6 +39,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("importBLSKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyShare",jsonrpc::JSON_STRING,"keyShareName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importBLSKeyShareI); this->bindAndAddMethod(jsonrpc::Procedure("importBLSKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyShare",jsonrpc::JSON_STRING,"keyShareName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importBLSKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("blsSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyShareName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::blsSignMessageHashI); this->bindAndAddMethod(jsonrpc::Procedure("blsSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyShareName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::blsSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("importECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"key",jsonrpc::JSON_STRING,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("generateECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::generateECDSAKeyI); this->bindAndAddMethod(jsonrpc::Procedure("generateECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractStubServer::generateECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getPublicECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getPublicECDSAKeyI); this->bindAndAddMethod(jsonrpc::Procedure("getPublicECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getPublicECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("ecdsaSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "base",jsonrpc::JSON_INTEGER,"keyName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::ecdsaSignMessageHashI); this->bindAndAddMethod(jsonrpc::Procedure("ecdsaSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "base",jsonrpc::JSON_INTEGER,"keyName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::ecdsaSignMessageHashI);
...@@ -50,7 +51,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer> ...@@ -50,7 +51,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "polyName", jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::createBLSPrivateKeyI); this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "polyName", jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::createBLSPrivateKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getBLSPublicKeyShareI); this->bindAndAddMethod(jsonrpc::Procedure("getBLSPublicKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "blsKeyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getBLSPublicKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("calculateAllBLSPublicKeys", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares", jsonrpc::JSON_ARRAY, "n", jsonrpc::JSON_INTEGER, "t", jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::calculateAllBLSPublicKeysI); this->bindAndAddMethod(jsonrpc::Procedure("calculateAllBLSPublicKeys", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares", jsonrpc::JSON_ARRAY, "n", jsonrpc::JSON_INTEGER, "t", jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::calculateAllBLSPublicKeysI);
this->bindAndAddMethod(jsonrpc::Procedure("complaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::complaintResponseI); this->bindAndAddMethod(jsonrpc::Procedure("complaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::complaintResponseI);
this->bindAndAddMethod(jsonrpc::Procedure("multG2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "x",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::multG2I); this->bindAndAddMethod(jsonrpc::Procedure("multG2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "x",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::multG2I);
this->bindAndAddMethod(jsonrpc::Procedure("isPolyExists", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::isPolyExistsI); this->bindAndAddMethod(jsonrpc::Procedure("isPolyExists", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::isPolyExistsI);
...@@ -68,6 +69,10 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer> ...@@ -68,6 +69,10 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["t"].asInt(), request["n"].asInt()); response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["t"].asInt(), request["n"].asInt());
} }
inline virtual void importECDSAKeyI(const Json::Value &request, Json::Value &response)
{
response = this->importECDSAKey( request["key"].asString(), request["keyName"].asString());
}
inline virtual void generateECDSAKeyI(const Json::Value &request, Json::Value &response) inline virtual void generateECDSAKeyI(const Json::Value &request, Json::Value &response)
{ {
(void)request; (void)request;
...@@ -111,7 +116,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer> ...@@ -111,7 +116,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
} }
inline virtual void complaintResponseI(const Json::Value &request, Json::Value &response) inline virtual void complaintResponseI(const Json::Value &request, Json::Value &response)
{ {
response = this->complaintResponse( request["polyName"].asString(), request["ind"].asInt()); response = this->complaintResponse( request["polyName"].asString(), request["t"].asInt(), request["n"].asInt(), request["ind"].asInt());
} }
inline virtual void multG2I(const Json::Value &request, Json::Value &response) inline virtual void multG2I(const Json::Value &request, Json::Value &response)
{ {
...@@ -141,6 +146,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer> ...@@ -141,6 +146,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
virtual Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName) = 0; virtual Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName) = 0;
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int t, int n ) = 0; virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int t, int n ) = 0;
virtual Json::Value importECDSAKey(const std::string& keyShare, const std::string& keyShareName) = 0;
virtual Json::Value generateECDSAKey() = 0; virtual Json::Value generateECDSAKey() = 0;
virtual Json::Value getPublicECDSAKey(const std::string& keyName) = 0; virtual Json::Value getPublicECDSAKey(const std::string& keyName) = 0;
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyName, const std::string& messageHash) = 0; virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyName, const std::string& messageHash) = 0;
...@@ -152,7 +158,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer> ...@@ -152,7 +158,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
virtual Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0; virtual Json::Value createBLSPrivateKey(const std::string & blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0;
virtual Json::Value getBLSPublicKeyShare(const std::string & blsKeyName) = 0; virtual Json::Value getBLSPublicKeyShare(const std::string & blsKeyName) = 0;
virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) = 0; virtual Json::Value calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) = 0;
virtual Json::Value complaintResponse(const std::string& polyName, int ind) = 0; virtual Json::Value complaintResponse(const std::string& polyName, int t, int n, int ind) = 0;
virtual Json::Value multG2(const std::string & x) = 0; virtual Json::Value multG2(const std::string & x) = 0;
virtual Json::Value isPolyExists(const std::string& polyName) = 0; virtual Json::Value isPolyExists(const std::string& polyName) = 0;
......
...@@ -32,6 +32,8 @@ using namespace std; ...@@ -32,6 +32,8 @@ using namespace std;
#include <map> #include <map>
#include <memory> #include <memory>
#include <boost/throw_exception.hpp>
#include <gmp.h> #include <gmp.h>
#include "secure_enclave/Verify.h" #include "secure_enclave/Verify.h"
#include "InvalidStateException.h" #include "InvalidStateException.h"
...@@ -50,10 +52,64 @@ inline std::string className(const std::string &prettyFunction) { ...@@ -50,10 +52,64 @@ inline std::string className(const std::string &prettyFunction) {
#define __CLASS_NAME__ className( __PRETTY_FUNCTION__ ) #define __CLASS_NAME__ className( __PRETTY_FUNCTION__ )
#include <execinfo.h>
inline void print_stack() {
void *array[10];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, 10);
// print out all the frames to stderr
fprintf(stderr, "Error: signal \n");
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
#define CHECK_STATE(_EXPRESSION_) \ #define CHECK_STATE(_EXPRESSION_) \
if (!(_EXPRESSION_)) { \ if (!(_EXPRESSION_)) { \
auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + std::string(__FILE__) + ":" + std::to_string(__LINE__); \ auto __msg__ = std::string("State check failed::") + #_EXPRESSION_ + " " + std::string(__FILE__) + ":" + std::to_string(__LINE__); \
print_stack(); \
throw InvalidStateException(__msg__, __CLASS_NAME__);} throw InvalidStateException(__msg__, __CLASS_NAME__);}
#define HANDLE_TRUSTED_FUNCTION_ERROR(__STATUS__, __ERR_STATUS__, __ERR_MSG__) \
if (__STATUS__ != SGX_SUCCESS) { \
string __ERR_STRING__ = string("SGX enclave call to ") + \
__FUNCTION__ + " failed with status:" \
+ to_string(__STATUS__) + \
" Err message:" + __ERR_MSG__; \
BOOST_THROW_EXCEPTION(runtime_error(__ERR_MSG__)); \
}\
\
if (__ERR_STATUS__ != 0) {\
string __ERR_STRING__ = string("SGX enclave call to ") +\
__FUNCTION__ + " failed with errStatus:" + \
to_string(__ERR_STATUS__) + \
" Err message:" + __ERR_MSG__;\
BOOST_THROW_EXCEPTION(runtime_error(__ERR_STRING__)); \
}
#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
#define SAFE_UINT8_BUF(__X__, __Y__) ;uint8_t __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
#include <shared_mutex>
extern std::shared_timed_mutex sgxInitMutex;
extern uint64_t initTime;
#if SGX_MODE == SIM
#define ENCLAVE_RESTART_PERIOD_S 5
#else
#define ENCLAVE_RESTART_PERIOD_S 60 * 10
#endif
#define READ_LOCK(__X__) std::shared_lock<std::shared_timed_mutex> __LOCK__(__X__);
#define WRITE_LOCK(__X__) std::unique_lock<std::shared_timed_mutex> __LOCK__(__X__);
#endif //SGXWALLET_COMMON_H #endif //SGXWALLET_COMMON_H
...@@ -28,7 +28,7 @@ cd /usr/src/sdk; ...@@ -28,7 +28,7 @@ cd /usr/src/sdk;
if [[ -f "/var/hwmode" ]] if [[ -f "/var/hwmode" ]]
then then
echo "Running in SGX hardware mode" echo "Running in SGX hardware mode"
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/opt/intel/sgxpsw/aesm/ export LD_LIBRARY_PATH=/usr/src/sdk/secure_enclave:${LD_LIBRARY_PATH}:/opt/intel/sgxpsw/aesm
jhid -d jhid -d
/opt/intel/sgxpsw/aesm/aesm_service & /opt/intel/sgxpsw/aesm/aesm_service &
pid=$! pid=$!
...@@ -43,8 +43,10 @@ fi ...@@ -43,8 +43,10 @@ fi
if [[ "$1" == "-t" ]]; then if [[ "$1" == "-t" ]]; then
echo "Test run requested" echo "Test run requested"
sleep 5
./testw.py ./testw.py
else else
sleep 3
./sgxwallet $1 $2 $3 $4 $5 ./sgxwallet $1 $2 $3 $4 $5
fi fi
...@@ -2,12 +2,12 @@ ...@@ -2,12 +2,12 @@
# SGXWallet Backup Procedure # SGXWallet Backup Procedure
When SGXWallet is initialized, the server will print the backup key. When SGXWallet is initialized, the server will write the backup key into `sgx_data/sgxwallet_backup_key.txt`.
**This key must be securely recorded and stored.** **This key must be securely recorded and stored.**
Be sure to store this key in a safe place, then go into a docker container and securely remove it with the following command: Be sure to store this key in a safe place, then go into a docker container and securely remove it with the following command:
```bash ```bash
docker exec -it <SGX_CONTAINER_NAME> bash && apt-get install secure-delete && srm -vz backup_key.txt docker exec -it <SGX_CONTAINER_NAME> bash && srm -vz ./sgx_data/sgxwallet_backup_key.txt
``` ```
Master-Slave replication is recommended to support the SGXWallet backup strategy. Below are general instructions for a basic backup and recovery process. Master-Slave replication is recommended to support the SGXWallet backup strategy. Below are general instructions for a basic backup and recovery process.
...@@ -30,24 +30,12 @@ docker-compose down ...@@ -30,24 +30,12 @@ docker-compose down
command: -s -y -d -b command: -s -y -d -b
``` ```
2. Edit the `docker-compose.yml` and add `stdin_open: true` option. For example: 2. Copy the backed up `sgx_data` directory to the recovery `sgx_data` directory.
3. Create file `sgx_data/sgxwallet_backup_key.txt` in the recovery directory and write the backup key into it.
```yaml
version: "3"
services:
sgxwallet:
image: skalenetwork/sgxwallet:latest
stdin_open: true
```
3. Copy the backed up `sgx_data` directory to the recovery `sgx_data` directory.
4. Execute: 4. Execute:
```bash ```bash
docker-compose up -d docker-compose up -d
``` ```
5. Open another terminal window and run `docker attach container_name` there. 5. Edit the `docker-compose.yml` file, remove the `-b` flag.
6. Enter the backup key when prompted.
7. Edit the `docker-compose.yml` file, remove the `-b` flag and `stdin_open: true` option.
Subproject commit 78ea56c3b5251e9d840ef65705bb2c5f8f193662 Subproject commit 82884ec89e84539f25af206a0148ca34c35e078f
version: '3' version: '3'
services: services:
sgxwallet: sgxwallet:
image: skalenetwork/sgxwallet:latest image: skalenetwork/sgxwallet_signed:latest
restart: always
ports: ports:
- "1026:1026" - "1026:1026"
- "1027:1027" - "1027:1027"
......
...@@ -2,6 +2,7 @@ version: '3' ...@@ -2,6 +2,7 @@ version: '3'
services: services:
sgxwallet: sgxwallet:
image: skalenetwork/sgxwallet_sim:develop-latest image: skalenetwork/sgxwallet_sim:develop-latest
restart: always
ports: ports:
- "1026:1026" - "1026:1026"
- "1027:1027" - "1027:1027"
......
...@@ -10,14 +10,8 @@ CONTAINER_NAME=$1 ...@@ -10,14 +10,8 @@ CONTAINER_NAME=$1
REPO_NAME=skalenetwork/$CONTAINER_NAME REPO_NAME=skalenetwork/$CONTAINER_NAME
IMAGE_NAME=$REPO_NAME:$VERSION IMAGE_NAME=$REPO_NAME:$VERSION
if [ "${BRANCH}" = "stable" ]; LATEST_IMAGE_NAME=$REPO_NAME:$BRANCH-latest
then docker tag "${IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
LATEST_IMAGE_NAME=$REPO_NAME:latest
docker tag "${IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
else
LATEST_IMAGE_NAME=$REPO_NAME:$BRANCH-latest
docker tag "${IMAGE_NAME}" "${LATEST_IMAGE_NAME}"
fi
: "${DOCKER_USERNAME?Need to set DOCKER_USERNAME}" : "${DOCKER_USERNAME?Need to set DOCKER_USERNAME}"
: "${DOCKER_PASSWORD?Need to set DOCKER_PASSWORD}" : "${DOCKER_PASSWORD?Need to set DOCKER_PASSWORD}"
......
...@@ -27,9 +27,23 @@ ...@@ -27,9 +27,23 @@
#include "stdlib.h" #include "stdlib.h"
#include <string.h> #include <string.h>
#include "AESUtils.h" #include "AESUtils.h"
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen) { sgx_aes_gcm_128bit_key_t AES_key[1024];
#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrBufLen, unsigned char type,
unsigned char exportable, uint64_t* resultLen) {
if (!type) {
LOG_ERROR("Null type in AES_encrypt");
return -1;
}
if (!message) { if (!message) {
LOG_ERROR("Null message in AES_encrypt"); LOG_ERROR("Null message in AES_encrypt");
...@@ -41,25 +55,38 @@ int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen) { ...@@ -41,25 +55,38 @@ int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen) {
return -2; return -2;
} }
uint64_t len = strlen(message); uint64_t len = strlen(message) + 1;
if (len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE > encrLen ) { if (2 + len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE > encrBufLen ) {
LOG_ERROR("Output buffer too small"); LOG_ERROR("Output buffer too small");
return -3; return -3;
} }
SAFE_CHAR_BUF(fullMessage, len + 2);
fullMessage[0] = type;
fullMessage[1] = exportable;
strncpy(fullMessage + 2, message, len );
len = len + 2;
message = fullMessage;
sgx_read_rand(encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE); sgx_read_rand(encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE);
sgx_status_t status = sgx_rijndael128GCM_encrypt(&AES_key, (uint8_t*)message, strlen(message), sgx_status_t status = sgx_rijndael128GCM_encrypt(&(AES_key[512]), (uint8_t*)message, len,
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0, NULL, 0,
(sgx_aes_gcm_128bit_tag_t *) encr_message); (sgx_aes_gcm_128bit_tag_t *) encr_message);
*resultLen = len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE;
return status; return status;
} }
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen) { int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen,
uint8_t *type, uint8_t* exportable){
if (!message) { if (!message) {
LOG_ERROR("Null message in AES_encrypt"); LOG_ERROR("Null message in AES_encrypt");
...@@ -71,6 +98,16 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t ...@@ -71,6 +98,16 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t
return -2; return -2;
} }
if (!type) {
LOG_ERROR("Null type in AES_encrypt");
return -3;
}
if (!encr_message) {
LOG_ERROR("Null exportable in AES_encrypt");
return -4;
}
if (length < SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE) { if (length < SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE) {
LOG_ERROR("length < SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE"); LOG_ERROR("length < SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE");
...@@ -86,12 +123,18 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t ...@@ -86,12 +123,18 @@ int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t
return -2; return -2;
} }
sgx_status_t status = sgx_rijndael128GCM_decrypt(&AES_key, sgx_status_t status = sgx_rijndael128GCM_decrypt(&(AES_key[512]),
encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len, encr_message + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, len,
(unsigned char*) message, (unsigned char*) message,
encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, encr_message + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE,
NULL, 0, NULL, 0,
(sgx_aes_gcm_128bit_tag_t *)encr_message); (sgx_aes_gcm_128bit_tag_t *)encr_message);
*type = message[0];
*exportable = message[1];
for (int i = 2; i < strlen(message) + 1; i++) {
message[i - 2 ] = message[i];
}
return status; return status;
} }
...@@ -24,10 +24,22 @@ ...@@ -24,10 +24,22 @@
#ifndef SGXD_AESUTILS_H #ifndef SGXD_AESUTILS_H
#define SGXD_AESUTILS_H #define SGXD_AESUTILS_H
sgx_aes_gcm_128bit_key_t AES_key; extern sgx_aes_gcm_128bit_key_t AES_key[1024];
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen,
unsigned char type, unsigned char exportable, uint64_t* resultLen);
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen,
uint8_t *type, uint8_t* exportable) ;
#define ECDSA '1'
#define BLS '2'
#define DKG '3'
#define EXPORTABLE '1'
#define NON_EXPORTABLE '2'
int AES_encrypt(char *message, uint8_t *encr_message, uint64_t encrLen);
int AES_decrypt(uint8_t *encr_message, uint64_t length, char *message, uint64_t msgLen) ;
#endif //SGXD_AESUTILS_H #endif //SGXD_AESUTILS_H
...@@ -31,10 +31,13 @@ ...@@ -31,10 +31,13 @@
#include <../tgmp-build/include/sgx_tgmp.h> #include <../tgmp-build/include/sgx_tgmp.h>
#endif #endif
#include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
#include <stdbool.h> #include <stdbool.h>
#include <string.h> #include <string.h>
#include "EnclaveCommon.h"
#include "Point.h" #include "Point.h"
#include "DomainParameters.h" #include "DomainParameters.h"
#define CHECK_ARG_ABORT(_EXPRESSION_) \ #define CHECK_ARG_ABORT(_EXPRESSION_) \
...@@ -46,16 +49,27 @@ ...@@ -46,16 +49,27 @@
/*Initialize a curve*/ /*Initialize a curve*/
domain_parameters domain_parameters_init() domain_parameters domain_parameters_init()
{ {
domain_parameters curve; domain_parameters curve;
curve = calloc(sizeof(struct domain_parameters_s),1); curve = (domain_parameters) calloc(sizeof(struct domain_parameters_s),1);
CHECK_ARG_ABORT(curve);
//Initialize all members //Initialize all members
mpz_init(curve->p); mpz_init(curve->p);
mpz_init(curve->a); mpz_init(curve->a);
mpz_init(curve->b); mpz_init(curve->b);
mpz_init(curve->n);
mpz_init(curve->h);
curve->G = point_init(); curve->G = point_init();
mpz_init(curve->n);
mpz_init(curve->h); CHECK_ARG_ABORT(curve->G);
return curve; return curve;
} }
......
...@@ -173,14 +173,25 @@ void enclave_init() { ...@@ -173,14 +173,25 @@ void enclave_init() {
return; return;
inited = 1; inited = 1;
LOG_INFO("Initing libff"); LOG_INFO("Initing libff");
try { try {
LOG_INFO("Initing params");
libff::init_alt_bn128_params(); libff::init_alt_bn128_params();
LOG_INFO("Initing curve");
curve = domain_parameters_init(); curve = domain_parameters_init();
LOG_INFO("Initing curve domain");
domain_parameters_load_curve(curve, secp256k1); domain_parameters_load_curve(curve, secp256k1);
} catch (exception& e) { } catch (exception& e) {
LOG_ERROR("Exception in libff init"); LOG_ERROR("Exception in libff init");
LOG_ERROR(e.what()); LOG_ERROR(e.what());
abort();
} catch (...) {
LOG_ERROR("Unknown exception in libff");
abort();
} }
LOG_INFO("Inited libff"); LOG_INFO("Inited libff");
} }
...@@ -345,19 +356,19 @@ void logMsg(log_level _level, const char *_msg) { ...@@ -345,19 +356,19 @@ void logMsg(log_level _level, const char *_msg) {
} }
EXTERNC void LOG_INFO(const char *_msg) { void LOG_INFO(const char *_msg) {
logMsg(L_INFO, _msg); logMsg(L_INFO, _msg);
}; };
EXTERNC void LOG_WARN(const char *_msg) { void LOG_WARN(const char *_msg) {
logMsg(L_WARNING, _msg); logMsg(L_WARNING, _msg);
}; };
EXTERNC void LOG_ERROR(const char *_msg) { void LOG_ERROR(const char *_msg) {
logMsg(L_ERROR, _msg); logMsg(L_ERROR, _msg);
}; };
EXTERNC void LOG_DEBUG(const char *_msg) { void LOG_DEBUG(const char *_msg) {
logMsg(L_DEBUG, _msg); logMsg(L_DEBUG, _msg);
}; };
EXTERNC void LOG_TRACE(const char *_msg) { void LOG_TRACE(const char *_msg) {
logMsg(L_TRACE, _msg); logMsg(L_TRACE, _msg);
}; };
...@@ -83,8 +83,8 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h ...@@ -83,8 +83,8 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \ secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \ secure_enclave.c \
Curves.c DomainParameters.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \ Curves.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \
DKGUtils.cpp EnclaveCommon.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \ DKGUtils.cpp EnclaveCommon.cpp DomainParameters.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \ ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG) ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......
...@@ -108,9 +108,9 @@ PROGRAMS = $(libexec_PROGRAMS) ...@@ -108,9 +108,9 @@ PROGRAMS = $(libexec_PROGRAMS)
am__objects_1 = am__objects_1 =
am_secure_enclave_OBJECTS = secure_enclave_t.$(OBJEXT) \ am_secure_enclave_OBJECTS = secure_enclave_t.$(OBJEXT) \
secure_enclave.$(OBJEXT) Curves.$(OBJEXT) \ secure_enclave.$(OBJEXT) Curves.$(OBJEXT) \
DomainParameters.$(OBJEXT) NumberTheory.$(OBJEXT) \ NumberTheory.$(OBJEXT) Point.$(OBJEXT) Signature.$(OBJEXT) \
Point.$(OBJEXT) Signature.$(OBJEXT) DHDkg.$(OBJEXT) \ DHDkg.$(OBJEXT) AESUtils.$(OBJEXT) DKGUtils.$(OBJEXT) \
AESUtils.$(OBJEXT) DKGUtils.$(OBJEXT) EnclaveCommon.$(OBJEXT) \ EnclaveCommon.$(OBJEXT) DomainParameters.$(OBJEXT) \
alt_bn128_init.$(OBJEXT) alt_bn128_g2.$(OBJEXT) \ alt_bn128_init.$(OBJEXT) alt_bn128_g2.$(OBJEXT) \
alt_bn128_g1.$(OBJEXT) $(am__objects_1) $(am__objects_1) alt_bn128_g1.$(OBJEXT) $(am__objects_1) $(am__objects_1)
secure_enclave_OBJECTS = $(am_secure_enclave_OBJECTS) secure_enclave_OBJECTS = $(am_secure_enclave_OBJECTS)
...@@ -337,8 +337,8 @@ ENCLAVE_CONFIG = $(ENCLAVE).config.xml ...@@ -337,8 +337,8 @@ ENCLAVE_CONFIG = $(ENCLAVE).config.xml
ENCLAVE_KEY = test_insecure_private_key.pem #$(ENCLAVE)_private.pem ENCLAVE_KEY = test_insecure_private_key.pem #$(ENCLAVE)_private.pem
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \ secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \ secure_enclave.c \
Curves.c DomainParameters.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \ Curves.c NumberTheory.c Point.c Signature.c DHDkg.c AESUtils.c \
DKGUtils.cpp EnclaveCommon.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \ DKGUtils.cpp EnclaveCommon.cpp DomainParameters.cpp ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \ ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG) ../third_party/SCIPR/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......
#define SIGNED_ENCLAVE_VERSION "0" #define SIGNED_ENCLAVE_VERSION "1"
\ No newline at end of file \ No newline at end of file
...@@ -57,6 +57,15 @@ signature signature_init() { ...@@ -57,6 +57,15 @@ signature signature_init() {
return sig; return sig;
} }
/*Release signature*/
void signature_free(signature sig) {
if (!sig)
return;
mpz_clear(sig->r);
mpz_clear(sig->s);
free(sig);
}
/*Set signature from strings of a base from 2-62*/ /*Set signature from strings of a base from 2-62*/
int signature_set_str(signature sig, const char *r, const char *s, int base) { int signature_set_str(signature sig, const char *r, const char *s, int base) {
...@@ -104,10 +113,9 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para ...@@ -104,10 +113,9 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para
return; return;
} }
point Q = point_init();
//Initializing variables //Initializing variables
mpz_t k, x, r, t1, t2, t3, t4, t5, s, n_div_2, rem, neg, seed; point Q = point_init();
mpz_t k, x, r, t1, t2, t3, t4, t5, s, n_div_2, rem, neg, seed, s_mul_2;
mpz_init(k); mpz_init(k);
mpz_init(x); mpz_init(x);
mpz_init(r); mpz_init(r);
...@@ -121,7 +129,6 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para ...@@ -121,7 +129,6 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para
mpz_init(rem); mpz_init(rem);
mpz_init(neg); mpz_init(neg);
mpz_init(seed); mpz_init(seed);
mpz_t s_mul_2;
mpz_init(s_mul_2); mpz_init(s_mul_2);
SAFE_CHAR_BUF(rand_char, 32); SAFE_CHAR_BUF(rand_char, 32);
...@@ -182,32 +189,27 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para ...@@ -182,32 +189,27 @@ void signature_sign(signature sig, mpz_t message, mpz_t private_key, domain_para
point_clear(Q); point_clear(Q);
mpz_clear(k); mpz_clear(k);
mpz_clear(r);
mpz_clear(s); mpz_clear(s);
mpz_clear(r);
mpz_clear(x); mpz_clear(x);
mpz_clear(rem); mpz_clear(rem);
mpz_clear(neg); mpz_clear(neg);
mpz_clear(t1); mpz_clear(t1);
mpz_clear(t2); mpz_clear(t2);
mpz_clear(t3); mpz_clear(t3);
mpz_clear(t4);
mpz_clear(t5);
mpz_clear(seed); mpz_clear(seed);
mpz_clear(n_div_2); mpz_clear(n_div_2);
mpz_clear(s_mul_2); mpz_clear(s_mul_2);
} }
#endif #endif
/*Release signature*/
void signature_free(signature sig) {
if (!sig)
return;
mpz_clear(sig->r);
mpz_clear(sig->s);
free(sig);
}
/*Verify the integrity of a message using it's signature*/ /*Verify the integrity of a message using it's signature*/
bool signature_verify(mpz_t message, signature sig, point public_key, domain_parameters curve) { bool signature_verify(mpz_t message, signature sig, point public_key, domain_parameters curve) {
......
This diff is collapsed.
<EnclaveConfiguration> <EnclaveConfiguration>
<ProdID>0</ProdID> <ProdID>0</ProdID>
<ISVSVN>0</ISVSVN> <ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize> <StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x100000000</HeapMaxSize> <HeapMaxSize>0x100000000</HeapMaxSize>
<TCSNum>128</TCSNum> <TCSNum>128</TCSNum>
......
<EnclaveConfiguration> <EnclaveConfiguration>
<ProdID>0</ProdID> <ProdID>0</ProdID>
<ISVSVN>0</ISVSVN> <ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize> <StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x100000000</HeapMaxSize> <HeapMaxSize>0x100000000</HeapMaxSize>
<TCSNum>128</TCSNum> <TCSNum>128</TCSNum>
......
<EnclaveConfiguration> <EnclaveConfiguration>
<ProdID>0</ProdID> <ProdID>0</ProdID>
<ISVSVN>0</ISVSVN> <ISVSVN>1</ISVSVN>
<StackMaxSize>0x1000000</StackMaxSize> <StackMaxSize>0x1000000</StackMaxSize>
<HeapMaxSize>0x10000000</HeapMaxSize> <HeapMaxSize>0x1000000</HeapMaxSize>
<TCSNum>32</TCSNum> <TCSNum>16</TCSNum>
<TCSMaxNum>32</TCSMaxNum> <TCSMaxNum>16</TCSMaxNum>
<TCSMinPool>32</TCSMinPool> <TCSMinPool>16</TCSMinPool>
<TCSPolicy>0</TCSPolicy> <TCSPolicy>0</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release --> <!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug> <DisableDebug>0</DisableDebug>
......
...@@ -11,14 +11,14 @@ enclave { ...@@ -11,14 +11,14 @@ enclave {
trusted { trusted {
include "sgx_tgmp.h" include "sgx_tgmp.h"
public void trustedEnclaveInit(uint32_t _logLevel); public void trustedEnclaveInit(uint64_t _logLevel);
public void trustedGenerateSEK( public void trustedGenerateSEK(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK, [out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK,
[out] uint32_t *enc_len, [out] uint64_t *enc_len,
[out, count = 65] char* hex_SEK); [out, count = 65] char* hex_SEK);
public void trustedSetSEK( public void trustedSetSEK(
...@@ -26,79 +26,79 @@ enclave { ...@@ -26,79 +26,79 @@ enclave {
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[in, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK); [in, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK);
public void trustedSetSEK_backup( public void trustedSetSEKBackup(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK, [out, count = SMALL_BUF_SIZE] uint8_t *encrypted_SEK,
[out] uint32_t *enc_len, [out] uint64_t *enc_len,
[in, string] const char* SEK_hex); [in, string] const char* SEK_hex);
public void trustedGenerateEcdsaKeyAES ( public void trustedGenerateEcdsaKey (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
[out] uint32_t *enc_len, [out] uint64_t *enc_len,
[out, count = SMALL_BUF_SIZE] char * pub_key_x, [out, count = SMALL_BUF_SIZE] char * pub_key_x,
[out, count = SMALL_BUF_SIZE] char * pub_key_y); [out, count = SMALL_BUF_SIZE] char * pub_key_y);
public void trustedGetPublicEcdsaKeyAES( public void trustedGetPublicEcdsaKey(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint32_t dec_len, uint64_t dec_len,
[out, count = SMALL_BUF_SIZE] char * pub_key_x, [out, count = SMALL_BUF_SIZE] char * pub_key_x,
[out, count = SMALL_BUF_SIZE] char * pub_key_y); [out, count = SMALL_BUF_SIZE] char * pub_key_y);
public void trustedEcdsaSignAES( public void trustedEcdsaSign(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint32_t enc_len, uint64_t enc_len,
[in, string] const char* hash, [in, string] const char* hash,
[out, count = SMALL_BUF_SIZE] char* sig_r, [out, count = SMALL_BUF_SIZE] char* sig_r,
[out, count = SMALL_BUF_SIZE] char* sig_s, [out, count = SMALL_BUF_SIZE] char* sig_s,
[out] uint8_t* sig_v, [out] uint8_t* sig_v,
int base); int base);
public void trustedEncryptKeyAES ( public void trustedEncryptKey (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] const char* key, [in, count = SMALL_BUF_SIZE] const char* key,
[out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [out, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
[out] uint32_t *enc_len); [out] uint64_t *enc_len);
public void trustedDecryptKeyAES ( public void trustedDecryptKey (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint32_t enc_len, uint64_t enc_len,
[out, count = SMALL_BUF_SIZE] char* key ); [out, count = SMALL_BUF_SIZE] char* key );
public void trustedGenDkgSecretAES ( public void trustedGenDkgSecret (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[out, count = 3072] uint8_t* encrypted_dkg_secret, [out, count = 3072] uint8_t* encrypted_dkg_secret,
[out] uint32_t * enc_len, size_t _t); [out] uint64_t * enc_len, size_t _t);
public void trustedDecryptDkgSecretAES ( public void trustedDecryptDkgSecret (
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 3050] uint8_t* encrypted_dkg_secret, [in, count = 3050] uint8_t* encrypted_dkg_secret,
uint32_t enc_len, uint64_t enc_len,
[out, count = 3072] uint8_t* decrypted_dkg_secret [out, count = 3072] uint8_t* decrypted_dkg_secret
); );
public void trustedSetEncryptedDkgPolyAES( public void trustedSetEncryptedDkgPoly(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 3050] uint8_t* encrypted_poly, [in, count = 3050] uint8_t* encrypted_poly,
uint32_t enc_len); uint64_t enc_len);
public void trustedGetEncryptedSecretShareAES( public void trustedGetEncryptedSecretShare(
[out]int *errStatus, [out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char *err_string, [out, count = SMALL_BUF_SIZE] char *err_string,
[out, count = SMALL_BUF_SIZE] uint8_t *encrypted_skey, [out, count = SMALL_BUF_SIZE] uint8_t *encrypted_skey,
[out] uint32_t* dec_len, [out] uint64_t* dec_len,
[out, count = 193] char* result_str, [out, count = 193] char* result_str,
[out, count = 320] char* s_shareG2, [out, count = 320] char* s_shareG2,
[in, string] char* pub_keyB, [in, string] char* pub_keyB,
...@@ -106,16 +106,16 @@ enclave { ...@@ -106,16 +106,16 @@ enclave {
uint8_t _n, uint8_t _n,
uint8_t ind); uint8_t ind);
public void trustedGetPublicSharesAES( public void trustedGetPublicShares(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 3050] uint8_t* encrypted_dkg_secret, [in, count = 3050] uint8_t* encrypted_dkg_secret,
uint32_t enc_len, uint64_t enc_len,
[out, count = 10000] char* public_shares, [out, count = 10000] char* public_shares,
unsigned _t, unsigned _t,
unsigned _n); unsigned _n);
public void trustedDkgVerifyAES( public void trustedDkgVerify(
[out] int *errStatus, [out] int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, string] const char* public_shares, [in, string] const char* public_shares,
...@@ -126,25 +126,25 @@ enclave { ...@@ -126,25 +126,25 @@ enclave {
int _ind, int _ind,
[out] int* result); [out] int* result);
public void trustedCreateBlsKeyAES( public void trustedCreateBlsKey(
[out]int *errStatus, [out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 6145] const char* s_shares, [in, count = 6145] const char* s_shares,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint64_t key_len, uint64_t key_len,
[out, count = SMALL_BUF_SIZE] uint8_t * encr_bls_key, [out, count = SMALL_BUF_SIZE] uint8_t * encr_bls_key,
[out] uint32_t *enc_bls_key_len); [out] uint64_t *enc_bls_key_len);
public void trustedBlsSignMessageAES ( public void trustedBlsSignMessage (
[out] int *errStatus, [out] int *errStatus,
[out, count = TINY_BUF_SIZE] char* err_string, [out, count = TINY_BUF_SIZE] char* err_string,
[in, count = TINY_BUF_SIZE] uint8_t* encrypted_key, [in, count = TINY_BUF_SIZE] uint8_t* encrypted_key,
uint32_t enc_len, uint64_t enc_len,
[in, string] char* hashX , [in, string] char* hashX ,
[in, string] char* hashY, [in, string] char* hashY,
[out, count = SMALL_BUF_SIZE] char* signature); [out, count = SMALL_BUF_SIZE] char* signature);
public void trustedGetBlsPubKeyAES( public void trustedGetBlsPubKey(
[out]int *errStatus, [out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string, [out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key, [in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
......
...@@ -36,6 +36,5 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -36,6 +36,5 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "sgxwallet.h" #include "sgxwallet.h"
sgx_launch_token_t token = {0}; sgx_launch_token_t token = {0};
sgx_enclave_id_t eid; sgx_enclave_id_t eid = 0;
sgx_status_t status; int updated = 0;
int updated;
...@@ -47,7 +47,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -47,7 +47,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
extern sgx_enclave_id_t eid; extern sgx_enclave_id_t eid;
extern int updated; extern int updated;
extern sgx_launch_token_t token; extern sgx_launch_token_t token;
extern sgx_status_t status;
#define ENCLAVE_NAME "secure_enclave.signed.so" #define ENCLAVE_NAME "secure_enclave.signed.so"
......
...@@ -109,4 +109,34 @@ extern bool autoconfirm; ...@@ -109,4 +109,34 @@ extern bool autoconfirm;
#define TEST_VALUE "1234567890" #define TEST_VALUE "1234567890"
#define RESTART_BEGIN \
int __ATTEMPTS__ = 0; \
do {\
__ATTEMPTS__++; \
{\
READ_LOCK(sgxInitMutex);
#define RESTART_END \
} \
if (status != SGX_SUCCESS || errStatus == 3) { \
spdlog::error(__FUNCTION__); \
spdlog::error("Restarting sgx on status errStatus... {} {}", status, errStatus); \
reinitEnclave(); \
} \
} while ((status != SGX_SUCCESS || errStatus == 3) && __ATTEMPTS__ < 2);
#define RESTART_END_POINTER \
} \
if (status != SGX_SUCCESS || *errStatus == 3) { \
spdlog::error(__FUNCTION__);\
spdlog::error("Restarting sgx on status errStatus... {} {}", status, *errStatus); \
reinitEnclave(); \
} \
} while ((status != SGX_SUCCESS || *errStatus == 3) && __ATTEMPTS__ < 2);
#endif //SGXWALLET_SGXWALLET_COMMON_H #endif //SGXWALLET_SGXWALLET_COMMON_H
...@@ -39,6 +39,18 @@ class StubClient : public jsonrpc::Client ...@@ -39,6 +39,18 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
} }
Json::Value importECDSAKey(const std::string& keyShare, const std::string& keyShareName)
{
Json::Value p;
p["key"] = keyShare;
p["keyName"] = keyShareName;
Json::Value result = this->CallMethod("importECDSAKey",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value generateECDSAKey() Json::Value generateECDSAKey()
{ {
Json::Value p; Json::Value p;
...@@ -171,10 +183,12 @@ class StubClient : public jsonrpc::Client ...@@ -171,10 +183,12 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString()); throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
} }
Json::Value complaintResponse(const std::string& polyName, int ind) Json::Value complaintResponse(const std::string& polyName, int t, int n,int ind)
{ {
Json::Value p; Json::Value p;
p["polyName"] = polyName; p["polyName"] = polyName;
p["t"] = t;
p["n"] = n;
p["ind"] = ind; p["ind"] = ind;
Json::Value result = this->CallMethod("complaintResponse",p); Json::Value result = this->CallMethod("complaintResponse",p);
if (result.isObject()) if (result.isObject())
......
This diff is collapsed.
...@@ -36,6 +36,7 @@ testList = ["[first-run]", ...@@ -36,6 +36,7 @@ testList = ["[first-run]",
"[get-server-version]", "[get-server-version]",
"[backup-key]", "[backup-key]",
"[delete-bls-key]", "[delete-bls-key]",
"[import-ecdsa-key]",
"[ecdsa-aes-key-gen]", "[ecdsa-aes-key-gen]",
"[ecdsa-aes-key-sig-gen]", "[ecdsa-aes-key-sig-gen]",
"[ecdsa-aes-get-pub-key]", "[ecdsa-aes-get-pub-key]",
...@@ -43,7 +44,6 @@ testList = ["[first-run]", ...@@ -43,7 +44,6 @@ testList = ["[first-run]",
"[bls-key-encrypt]", "[bls-key-encrypt]",
"[dkg-aes-gen]", "[dkg-aes-gen]",
"[dkg-aes-encr-sshares]", "[dkg-aes-encr-sshares]",
"[dkg-verify]",
"[dkg-api]", "[dkg-api]",
"[dkg-bls]", "[dkg-bls]",
"[dkg-poly-exists]", "[dkg-poly-exists]",
......
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