Unverified Commit 03b0f0c9 authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge branch 'develop' into bug/SKALE-3662-mining-stuck

parents 8b164df0 fcd33724
......@@ -129,36 +129,6 @@ bool hex2carray(const char *_hex, uint64_t *_bin_len,
return true;
}
bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) {
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) {
throw SGXException(SIGN_FUNCTION_INVALID_HEX, string(__FUNCTION__) + ":Invalid hash");
}
auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
auto sigShareStr = sigShare->toString();
strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
return true;
}
bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) {
CHECK_STATE(_encryptedKeyHex);
......@@ -214,10 +184,8 @@ bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, siz
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
sz, xStrArg, yStrArg, signature);
SEMAPHORE_END
status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
sz, xStrArg, yStrArg, signature);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -256,10 +224,8 @@ string encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedEncryptKey(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(),
&encryptedLen);
SEMAPHORE_END
status = trustedEncryptKey(eid, errStatus, errMsg.data(), keyArray->data(), encryptedKey->data(),
&encryptedLen);
HANDLE_TRUSTED_FUNCTION_ERROR(status, *errStatus, errMsg.data());
......
......@@ -149,10 +149,8 @@ string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
SEMAPHORE_END
status = trustedBlsSignMessage(eid, &errStatus, errMsg.data(), encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......
......@@ -136,11 +136,8 @@ string gen_dkg_poly(int _t) {
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedGenDkgSecret(
eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(), &enc_len, _t);
SEMAPHORE_END
status = trustedGenDkgSecret(eid, &errStatus, errMsg.data(), encrypted_dkg_secret.data(),
&enc_len, _t);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -176,11 +173,8 @@ vector <vector<string>> get_verif_vect(const string &encryptedPolyHex, int t, in
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedGetPublicShares(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), encLen,
pubShares.data(), t, n);
SEMAPHORE_END
status = trustedGetPublicShares(eid, &errStatus, errMsg.data(), encrDKGPoly.data(), encLen,
pubShares.data(), t, n);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -369,10 +363,8 @@ verifyShares(const char *publicShares, const char *encr_sshare, const char *encr
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedDkgVerify(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
ind, &result);
SEMAPHORE_END
status = trustedDkgVerify(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
ind, &result);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -406,10 +398,8 @@ verifySharesV2(const char *publicShares, const char *encr_sshare, const char *en
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedDkgVerifyV2(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
ind, &result);
SEMAPHORE_END
status = trustedDkgVerifyV2(eid, &errStatus, errMsg.data(), pshares, encr_sshare, encr_key, decKeyLen, t,
ind, &result);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -437,10 +427,38 @@ bool createBLSShare(const string &blsKeyName, const char *s_shares, const char *
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedCreateBlsKey(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key,
&enc_bls_len);
SEMAPHORE_END
status = trustedCreateBlsKey(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key,
&enc_bls_len);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
vector<char> hexBLSKey = carray2Hex(encr_bls_key, enc_bls_len);
SGXWalletServer::writeDataToDB(blsKeyName, hexBLSKey.data());
return true;
}
bool createBLSShareV2(const string &blsKeyName, const char *s_shares, const char *encryptedKeyHex) {
CHECK_STATE(s_shares);
CHECK_STATE(encryptedKeyHex);
vector<char> errMsg(BUF_LEN, 0);
int errStatus = 0;
uint64_t decKeyLen;SAFE_UINT8_BUF(encr_bls_key, BUF_LEN);SAFE_UINT8_BUF(encr_key, BUF_LEN);
if (!hex2carray(encryptedKeyHex, &decKeyLen, encr_key, BUF_LEN)) {
throw SGXException(CREATE_BLS_SHARE_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid encryptedKeyHex");
}
uint64_t enc_bls_len = 0;
sgx_status_t status = SGX_SUCCESS;
status = trustedCreateBlsKeyV2(eid, &errStatus, errMsg.data(), s_shares, encr_key, decKeyLen, encr_bls_key,
&enc_bls_len);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -471,9 +489,7 @@ vector <string> getBLSPubKey(const char *encryptedKeyHex) {
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedGetBlsPubKey(eid, &errStatus, errMsg1.data(), encrKey, decKeyLen, pubKey);
SEMAPHORE_END
status = trustedGetBlsPubKey(eid, &errStatus, errMsg1.data(), encrKey, decKeyLen, pubKey);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data());
......@@ -547,7 +563,8 @@ string decryptDHKey(const string &polyName, int ind) {
vector<char> hexEncrKey(2 * BUF_LEN, 0);
uint64_t dhEncLen = 0;SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN)
uint64_t dhEncLen = 0;
SAFE_UINT8_BUF(encryptedDHKey, BUF_LEN);
if (!hex2carray(hexEncrKeyPtr->c_str(), &dhEncLen, encryptedDHKey, BUF_LEN)) {
throw SGXException(DECRYPT_DH_KEY_INVALID_KEY_HEX, string(__FUNCTION__) + ":Invalid hexEncrKey");
}
......@@ -557,9 +574,8 @@ string decryptDHKey(const string &polyName, int ind) {
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
SEMAPHORE_END
status = trustedDecryptKey(eid, &errStatus, errMsg1.data(), encryptedDHKey, dhEncLen, DHKey);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg1.data())
return DHKey;
......
......@@ -51,6 +51,8 @@ string decryptDHKey(const string& polyName, int ind);
bool createBLSShare( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
bool createBLSShareV2( const string& blsKeyName, const char * s_shares, const char * encryptedKeyHex);
vector<string> getBLSPubKey(const char * encryptedKeyHex);
vector<string> mult_G2(const string& x);
......
......@@ -59,11 +59,9 @@ vector <string> genECDSAKey() {
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedGenerateEcdsaKey(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
SEMAPHORE_END
status = trustedGenerateEcdsaKey(eid, &errStatus,
errMsg.data(), encr_pr_key.data(), &enc_len,
pub_key_x.data(), pub_key_y.data());
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus,errMsg.data());
......@@ -101,10 +99,8 @@ string getECDSAPubKey(const std::string& _encryptedKeyHex) {
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedGetPublicEcdsaKey(eid, &errStatus,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
SEMAPHORE_END
status = trustedGetPublicEcdsaKey(eid, &errStatus,
errMsg.data(), encrPrKey.data(), enc_len, pubKeyX.data(), pubKeyY.data());
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data())
......@@ -190,12 +186,10 @@ vector <string> ecdsaSignHash(const std::string& encryptedKeyHex, const char *ha
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedEcdsaSign(eid, &errStatus,
errMsg.data(), encryptedKey.data(), decLen, hashHex,
signatureR.data(),
signatureS.data(), &signatureV, base);
SEMAPHORE_END
status = trustedEcdsaSign(eid, &errStatus,
errMsg.data(), encryptedKey.data(), decLen, hashHex,
signatureR.data(),
signatureS.data(), &signatureV, base);
HANDLE_TRUSTED_FUNCTION_ERROR(status, errStatus, errMsg.data());
......@@ -242,10 +236,9 @@ string encryptECDSAKey(const string& _key) {
uint64_t enc_len = 0;
sgx_status_t status = SGX_SUCCESS;
SEMAPHORE_BEGIN
status = trustedEncryptKey(eid, &errStatus, errString.data(), key.data(),
encryptedKey.data(), &enc_len);
SEMAPHORE_END
status = trustedEncryptKey(eid, &errStatus, errString.data(), key.data(),
encryptedKey.data(), &enc_len);
if (status != 0) {
throw SGXException(status, string("Could not encrypt ECDSA key: " + string(errString.begin(), errString.end())).c_str());
......
......@@ -27,6 +27,7 @@
#include <iostream>
#include "leveldb/db.h"
#include <jsonrpccpp/client.h>
#include "sgxwallet_common.h"
#include "SGXException.h"
......@@ -42,6 +43,14 @@ using namespace leveldb;
static WriteOptions writeOptions;
static ReadOptions readOptions;
shared_ptr<string> LevelDB::readNewStyleValue(const string& value) {
Json::Value key_data;
Json::Reader reader;
reader.parse(value.c_str(), key_data);
return std::make_shared<string>(key_data["value"].asString());
}
std::shared_ptr<string> LevelDB::readString(const string &_key) {
auto result = std::make_shared<string>();
......@@ -56,17 +65,26 @@ std::shared_ptr<string> LevelDB::readString(const string &_key) {
return nullptr;
}
if (result->at(0) == '{') {
return readNewStyleValue(*result);
}
return result;
}
void LevelDB::writeString(const string &_key, const string &_value) {
Json::Value writerData;
writerData["value"] = _value;
writerData["timestamp"] = std::to_string(std::time(nullptr));
Json::FastWriter fastWriter;
std::string output = fastWriter.write(writerData);
auto status = db->Put(writeOptions, Slice(_key), Slice(_value));
auto status = db->Put(writeOptions, Slice(_key), Slice(output));
throwExceptionOnError(status);
}
void LevelDB::deleteDHDKGKey(const string &_key) {
string full_key = "DKG_DH_KEY_" + _key;
......@@ -94,18 +112,6 @@ void LevelDB::deleteKey(const string &_key) {
}
void LevelDB::writeByteArray(string &_key, const char *value,
size_t _valueLen) {
CHECK_STATE(value);
auto status = db->Put(writeOptions, Slice(_key), Slice(value, _valueLen));
throwExceptionOnError(status);
}
void LevelDB::throwExceptionOnError(Status _status) {
if (_status.IsNotFound())
return;
......@@ -155,15 +161,65 @@ std::vector<string> LevelDB::writeKeysToVector1(uint64_t _maxKeysToVisit){
}
void LevelDB::writeDataUnique(const string & name, const string &value) {
auto key = name;
if (readString(name)) {
spdlog::debug("Name {} already exists", name);
throw SGXException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
}
writeString(key, value);
writeString(name, value);
}
pair<stringstream, uint64_t> LevelDB::getAllKeys() {
stringstream keysInfo;
leveldb::Iterator *it = db->NewIterator(readOptions);
uint64_t counter = 0;
for (it->SeekToFirst(); it->Valid(); it->Next()) {
++counter;
string key = it->key().ToString();
string value;
if (it->value().ToString()[0] == '{') {
// new style keys
Json::Value key_data;
Json::Reader reader;
reader.parse(it->value().ToString().c_str(), key_data);
string timestamp_to_date_command = "date -d @" + key_data["timestamp"].asString();
value = " VALUE: " + key_data["value"].asString() + ", TIMESTAMP: " + exec(timestamp_to_date_command.c_str()) + '\n';
} else {
// old style keys
value = " VALUE: " + it->value().ToString();
}
keysInfo << "KEY: " << key << ',' << value;
}
return {std::move(keysInfo), counter};
}
pair<string, uint64_t> LevelDB::getLatestCreatedKey() {
leveldb::Iterator *it = db->NewIterator(readOptions);
int64_t latest_timestamp = 0;
string latest_created_key_name = "";
for (it->SeekToFirst(); it->Valid(); it->Next()) {
if (it->value().ToString()[0] == '{') {
// new style keys
Json::Value key_data;
Json::Reader reader;
reader.parse(it->value().ToString().c_str(), key_data);
if (std::stoi(key_data["timestamp"].asString()) > latest_timestamp) {
latest_timestamp = std::stoi(key_data["timestamp"].asString());
latest_created_key_name = it->key().ToString();
}
} else {
// old style keys
// assuming server has at least one new-style key created
continue;
}
}
return {latest_created_key_name, latest_timestamp};
}
......
......@@ -26,10 +26,12 @@
#define SGXWALLET_LEVELDB_H
#include <memory>
#include <sstream>
#include <string>
#include <mutex>
#include <vector>
#include "common.h"
namespace leveldb {
class DB;
class Status;
......@@ -55,7 +57,6 @@ class LevelDB {
public:
static void initDataFolderAndDBs();
static const shared_ptr<LevelDB> &getLevelDb();
......@@ -66,20 +67,17 @@ public:
public:
shared_ptr<string> readString(const string& _key);
shared_ptr<string> readNewStyleValue(const string& value);
void writeString(const string &key1, const string &value1);
pair<stringstream, uint64_t> getAllKeys();
void writeDataUnique(const string & Name, const string &value);
void writeByteArray(const char *_key, size_t _keyLen, const char *value,
size_t _valueLen);
pair<string, uint64_t> getLatestCreatedKey();
void writeString(const string &key1, const string &value1);
void writeByteArray(string& _key, const char *value,
size_t _valueLen);
void writeDataUnique(const string & Name, const string &value);
void deleteDHDKGKey (const string &_key);
......@@ -89,15 +87,10 @@ public:
public:
void throwExceptionOnError(leveldb::Status result);
LevelDB(string& filename);
class KeyVisitor {
public:
virtual void visitDBKey(const char* _data) = 0;
......
......@@ -62,19 +62,17 @@ CLEANFILES = $(COMMON_ENCLAVE_SRC) secure_enclave.edl secure_enclave.signed.so
## The build target
bin_PROGRAMS = sgxwallet testw cert_util
bin_PROGRAMS = sgxwallet testw sgx_util
## You can't use $(wildcard ...) with automake so all source files
## have to be explicitly listed.
## have to be explicitly listed
COMMON_SRC = ECDSASignReqMessage.cpp BLSSignReqMessage.cpp ZMQMessage.cpp ZMQServer.cpp ServerWorker.cpp InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \
SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp \
ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp SEKManager.cpp \
third_party/intel/sgx_stub.c third_party/intel/sgx_detect_linux.c third_party/intel/create_enclave.c third_party/intel/oc_alloc.c \
ECDSAImpl.c TestUtils.cpp sgxwallet.c
ECDSACrypto.cpp
COMMON_ENCLAVE_SRC = secure_enclave_u.c secure_enclave_u.h
sgxwallet_SOURCES = sgxwall.cpp $(COMMON_SRC)
......@@ -116,11 +114,12 @@ nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
cert_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp cert_util.cpp stubclient.cpp LevelDB.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp
sgx_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp cert_util.cpp stubclient.cpp LevelDB.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp
cert_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \
sgx_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \
-LlibBLS/build/libff/libff \
-Llibzmq/build/lib/ \
-l:libzmq.a \
-l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -ldl
......@@ -9,3 +9,7 @@ You can report security bugs by emailing us directly at security@skalelabs.com.
## Comments on This Policy
If you have suggestions on how this process could be improved, please submit a pull request.
## Bug Reporting Bounty
Please check out the SKALE Network's HackerOne program for any bug bounties related to SGX Wallet: <https://hackerone.com/skale_network>
/*
Copyright (C) 2020-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file SGXInfoServer.cpp
@author Oleh Nikolaiev
@date 2020
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <stdio.h>
#include "sgxwallet_common.h"
#include "SGXException.h"
#include "LevelDB.h"
#include "SGXInfoServer.h"
#include "LevelDB.h"
#include "Log.h"
#include "common.h"
shared_ptr <SGXInfoServer> SGXInfoServer::server = nullptr;
shared_ptr <HttpServer> SGXInfoServer::httpServer = nullptr;
SGXInfoServer::SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type,
uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys)
: AbstractInfoServer(connector, type) {
logLevel_ = _logLevel;
autoSign_ = _autoSign;
checkCerts_ = _checkCerts;
generateTestKeys_ = _generateTestKeys;
}
Json::Value SGXInfoServer::getAllKeysInfo() {
Json::Value result;
try {
auto allKeysInfo = LevelDB::getLevelDb()->getAllKeys();
result["allKeys"] = allKeysInfo.first.str();
result["keysNumber"] = std::to_string(allKeysInfo.second);
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXInfoServer::getLatestCreatedKey() {
Json::Value result;
try {
pair<string, uint64_t> key = LevelDB::getLevelDb()->getLatestCreatedKey();
result["keyName"] = key.first;
result["creationTime"] = std::to_string(key.second);
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXInfoServer::getServerConfiguration() {
Json::Value result;
try {
result["autoConfirm"] = autoconfirm;
result["logLevel"] = logLevel_;
result["enterBackupKey"] = enterBackupKey;
result["useHTTPS"] = useHTTPS;
result["autoSign"] = autoSign_;
result["checkCerts"] = checkCerts_;
result["generateTestKeys"] = generateTestKeys_;
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXInfoServer::isKeyExist(const string& key) {
Json::Value result;
result["isExists"] = false;
try {
shared_ptr <string> keyPtr = LevelDB::getLevelDb()->readString(key);
if (keyPtr != nullptr) {
result["IsExist"] = true;
}
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
int SGXInfoServer::initInfoServer(uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys) {
httpServer = make_shared<HttpServer>(BASE_PORT + 4);
server = make_shared<SGXInfoServer>(*httpServer, JSONRPC_SERVER_V2, _logLevel, _autoSign, _checkCerts, _generateTestKeys); // hybrid server (json-rpc 1.0 & 2.0)
if (!server->StartListening()) {
spdlog::error("Info server could not start listening on port {}", BASE_PORT + 4);
exit(-10);
} else {
spdlog::info("Info server started on port {}", BASE_PORT + 4);
}
return 0;
}
shared_ptr<SGXInfoServer> SGXInfoServer::getServer() {
CHECK_STATE(server);
return server;
}
/*
Copyright (C) 2020-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file SGXInfoServer.h
@author Oleh Nikolaiev
@date 2020
*/
#ifndef SGXINFOSERVER_H
#define SGXINFOSERVER_H
#include <mutex>
#include "abstractinfoserver.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
using namespace jsonrpc;
using namespace std;
class SGXInfoServer : public AbstractInfoServer {
recursive_mutex m;
uint32_t logLevel_;
bool autoSign_;
bool checkCerts_;
bool generateTestKeys_;
static shared_ptr <HttpServer> httpServer;
static shared_ptr <SGXInfoServer> server;
public:
static shared_ptr <SGXInfoServer> getServer();
SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type,
uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys);
virtual Json::Value getAllKeysInfo();
virtual Json::Value getLatestCreatedKey();
virtual Json::Value getServerConfiguration();
virtual Json::Value isKeyExist(const string& key);
static int initInfoServer(uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys);
};
#endif // SGXINFOSERVER_H
......@@ -53,10 +53,6 @@ using namespace std;
std::shared_timed_mutex sgxInitMutex;
// MAX 200 threads can call enclave
boost::interprocess::interprocess_semaphore enclaveSemaphore(200);
uint64_t initTime;
void setFullOptions(uint64_t _logLevel, int _useHTTPS, int _autoconfirm, int _enterBackupKey) {
......@@ -119,7 +115,7 @@ void SGXWalletServer::printDB() {
#ifdef SGX_HW_SIM
#define NUM_THREADS 16
#else
#define NUM_THREADS 1024
#define NUM_THREADS 200
#endif
......@@ -162,7 +158,6 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
}
}
httpServer = make_shared<HttpServer>(BASE_PORT, certPath, keyPath, rootCAPath, _checkCerts,
NUM_THREADS);
......@@ -902,6 +897,66 @@ Json::Value SGXWalletServer::dkgVerificationV2Impl(const string &_publicShares,
RETURN_SUCCESS(result)
}
Json::Value
SGXWalletServer::createBLSPrivateKeyV2Impl(const string &_blsKeyName, const string &_ethKeyName, const string &_polyName,
const string &_secretShare, int _t, int _n) {
COUNT_STATISTICS
spdlog::info("Entering {}", __FUNCTION__);
INIT_RESULT(result)
try {
if (_secretShare.length() != (uint64_t) _n * 192) {
throw SGXException(INVALID_CREATE_BLS_KEY_SECRET_SHARES_LENGTH,
string(__FUNCTION__) + ":Invalid secret share length");
}
if (!checkECDSAKeyName(_ethKeyName)) {
throw SGXException(INVALID_CREATE_BLS_ECDSA_KEY_NAME,
string(__FUNCTION__) + ":Invalid ECDSA key name");
}
if (!checkName(_polyName, "POLY")) {
throw SGXException(INVALID_CREATE_BLS_POLY_NAME, string(__FUNCTION__) +
":Invalid polynomial name");
}
if (!checkName(_blsKeyName, "BLS_KEY")) {
throw SGXException(INVALID_CREATE_BLS_KEY_NAME, string(__FUNCTION__) +
":Invalid BLS key name");
}
if (!check_n_t(_t, _n)) {
throw SGXException(INVALID_CREATE_BLS_DKG_PARAMS,
string(__FUNCTION__) + ":Invalid DKG parameters: n or t ");
}
vector <string> sshares_vect;
shared_ptr <string> encryptedKeyHex_ptr = readFromDb(_ethKeyName);
CHECK_STATE(encryptedKeyHex_ptr);
bool res = createBLSShareV2(_blsKeyName, _secretShare.c_str(), encryptedKeyHex_ptr->c_str());
if (res) {
spdlog::info("BLS KEY SHARE CREATED ");
} else {
throw SGXException(INVALID_CREATE_BLS_SHARE,
string(__FUNCTION__) + ":Error while creating BLS key share");
}
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)
RETURN_SUCCESS(result);
}
Json::Value SGXWalletServer::generateDKGPoly(const string &_polyName, int _t) {
return generateDKGPolyImpl(_polyName, _t);
}
......@@ -996,6 +1051,12 @@ SGXWalletServer::dkgVerificationV2(const string &_publicShares, const string &et
return dkgVerificationV2Impl(_publicShares, ethKeyName, SecretShare, t, n, index);
}
Json::Value
SGXWalletServer::createBLSPrivateKeyV2(const string &blsKeyName, const string &ethKeyName, const string &polyName,
const string &SecretShare, int t, int n) {
return createBLSPrivateKeyV2Impl(blsKeyName, ethKeyName, polyName, SecretShare, t, n);
}
shared_ptr <string> SGXWalletServer::readFromDb(const string &name, const string &prefix) {
auto dataStr = checkDataFromDb(prefix + name);
......
......@@ -112,6 +112,8 @@ public:
virtual Json::Value dkgVerificationV2(const string &_publicShares, const string &ethKeyName, const string &SecretShare, int t, int n, int index);
virtual Json::Value createBLSPrivateKeyV2(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
static shared_ptr<string> readFromDb(const string &name, const string &prefix = "");
static shared_ptr <string> checkDataFromDb(const string &name, const string &prefix = "");
......@@ -168,6 +170,8 @@ public:
static Json::Value dkgVerificationV2Impl(const string &_publicShares, const string &_ethKeyName, const string &_secretShare, int _t, int _n, int _index);
virtual Json::Value createBLSPrivateKeyV2Impl(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
static void printDB();
static int initHttpServer();
......
......@@ -52,6 +52,7 @@
#include "LevelDB.h"
#include "SGXWalletServer.h"
#include "SGXRegistrationServer.h"
#include "SGXInfoServer.h"
#include "SEKManager.h"
#include "CSRManagerServer.h"
#include "BLSCrypto.h"
......@@ -62,26 +63,7 @@
uint32_t enclaveLogLevel = 0;
using namespace std;
// Copy from libconsensus
string exec( const char* cmd ) {
CHECK_STATE( cmd );
std::array< char, 128 > buffer;
std::string result;
std::unique_ptr< FILE, decltype( &pclose ) > pipe( popen( cmd, "r" ), pclose );
if ( !pipe ) {
BOOST_THROW_EXCEPTION( std::runtime_error( "popen() failed!" ) );
}
while ( fgets( buffer.data(), buffer.size(), pipe.get() ) != nullptr ) {
result += buffer.data();
}
return result;
}
using namespace std;
void systemHealthCheck() {
string ulimit;
......@@ -202,7 +184,8 @@ uint64_t initEnclave() {
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign, bool _generateTestKeys) {
static atomic<bool> sgxServerInited(false);
static mutex initMutex;
......@@ -220,7 +203,7 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
CHECK_STATE(sgxServerInited != 1)
sgxServerInited = 1;
uint64_t counter = 0;
uint64_t counter = 0;
uint64_t initResult = 0;
while ((initResult = initEnclave()) != 0 && counter < 10){
......@@ -242,6 +225,8 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
} else {
SGXWalletServer::initHttpServer();
}
SGXInfoServer::initInfoServer(_logLevel, _checkCert, _autoSign, _generateTestKeys);
sgxServerInited = true;
} catch (SGXException &_e) {
spdlog::error(_e.getMessage());
......
......@@ -32,7 +32,7 @@
#define EXTERNC
#endif
EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign);
EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign, bool _generateTestKeys);
EXTERNC void initUserSpace();
......
......@@ -371,7 +371,7 @@ void TestUtils::sendRPCRequestV2() {
string blsName = "BLS_KEY" + polyNames[i].substr(4);
string secretShare = secretShares[i]["secretShare"].asString();
auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t, n);
auto response = c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t, n);
CHECK_STATE(response["status"] == 0);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
CHECK_STATE(pubBLSKeys[i]["status"] == 0);
......@@ -638,7 +638,7 @@ void TestUtils::doDKGV2(StubClient &c, int n, int t,
_blsKeyNames.push_back(blsName);
string secretShare = secretShares[i]["secretShare"].asString();
auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
auto response = c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
n);
CHECK_STATE(response["status"] == 0);
pubBLSKeys[i] = c.getBLSPublicKeyShare(blsName);
......
1.65.1
\ No newline at end of file
1.66.1
/*
Copyright (C) 2020-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file abstractinfoserver.h
@author Oleh Nikolaiev
@date 2020
*/
#ifndef ABSTRACTINFOSERVER_H
#define ABSTRACTINFOSERVER_H
#include <jsonrpccpp/server.h>
#include <iostream>
class AbstractInfoServer : public jsonrpc::AbstractServer<AbstractInfoServer>
{
public:
AbstractInfoServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer<AbstractInfoServer>(conn, type)
{
this->bindAndAddMethod(jsonrpc::Procedure("getAllKeysInfo", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getAllKeysInfoI);
this->bindAndAddMethod(jsonrpc::Procedure("getLatestCreatedKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getLatestCreatedKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getServerConfiguration", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getServerConfigurationI);
this->bindAndAddMethod(jsonrpc::Procedure("isKeyExist", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractInfoServer::isKeyExistI);
}
inline virtual void getAllKeysInfoI(const Json::Value &request, Json::Value &response)
{
response = this->getAllKeysInfo();
}
inline virtual void getLatestCreatedKeyI(const Json::Value &request, Json::Value &response)
{
response = this->getLatestCreatedKey();
}
inline virtual void getServerConfigurationI(const Json::Value &request, Json::Value &response)
{
response = this->getServerConfiguration();
}
inline virtual void isKeyExistI(const Json::Value &request, Json::Value &response)
{
response = this->isKeyExist(request["keyName"].asString());
}
virtual Json::Value getAllKeysInfo() = 0;
virtual Json::Value getLatestCreatedKey() = 0;
virtual Json::Value getServerConfiguration() = 0;
virtual Json::Value isKeyExist(const std::string& key) = 0;
};
#endif // ABSTRACTINFOSERVER_H
......@@ -61,6 +61,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("getSecretShareV2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"publicKeys",jsonrpc::JSON_ARRAY, "n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getSecretShareV2I);
this->bindAndAddMethod(jsonrpc::Procedure("dkgVerificationV2", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "publicShares",jsonrpc::JSON_STRING, "ethKeyName",jsonrpc::JSON_STRING, "secretShare",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::dkgVerificationV2I);
this->bindAndAddMethod(jsonrpc::Procedure("createBLSPrivateKeyV2", 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::createBLSPrivateKeyV2I);
}
inline virtual void importBLSKeyShareI(const Json::Value &request, Json::Value &response)
......@@ -155,6 +156,10 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->dkgVerificationV2(request["publicShares"].asString(), request["ethKeyName"].asString(), request["secretShare"].asString(), request["t"].asInt(), request["n"].asInt(), request["index"].asInt());
}
inline virtual void createBLSPrivateKeyV2I(const Json::Value &request, Json::Value &response)
{
response = this->createBLSPrivateKeyV2(request["blsKeyName"].asString(), request["ethKeyName"].asString(), request["polyName"].asString(),request["secretShare"].asString(),request["t"].asInt(), request["n"].asInt());
}
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;
......@@ -167,8 +172,8 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
virtual Json::Value getVerificationVector(const std::string& polyName, int t, int n) = 0;
virtual Json::Value getSecretShare(const std::string& polyName, const Json::Value& publicKeys, int t, int n) = 0;
virtual Json::Value dkgVerification( const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index) = 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 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 calculateAllBLSPublicKeys(const Json::Value& publicShares, int t, int n) = 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;
......@@ -180,6 +185,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
virtual Json::Value getSecretShareV2(const std::string& polyName, const Json::Value& publicKeys, int t, int n) = 0;
virtual Json::Value dkgVerificationV2( const std::string& publicShares, const std::string& ethKeyName, const std::string& SecretShare, int t, int n, int index) = 0;
virtual Json::Value createBLSPrivateKeyV2(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n) = 0;
};
#endif //JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file cert_util.cpp
@author Stan Kladko
@date 2019
*/
#include <iostream>
#include <cstring>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include "stubclient.h"
#include <unistd.h>
int print_hashes(){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.getUnsignedCSRs() << std::endl;
exit(0);
}
void sign_by_hash(std::string & hash, int status){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.signByHash(hash, status) << std::endl;
exit(0);
}
int main(int argc, char *argv[]) {
int opt;
if (argc > 1 && strlen(argv[1]) == 1) {
fprintf(stderr, "option is too short %s\n", argv[1]);
exit(1);
}
if (argc == 1) {
std::cout << "You may use following flags:" << std::endl;
std::cout << " -p print all unsigned csr hashes " << std::endl;
std::cout << " -s [hash] sign csr by hash" << std::endl;
std::cout << " -r [hash] reject csr by hash" << std::endl;
exit(0);
}
std::string hash;
while ((opt = getopt(argc, argv, "ps:r:")) != -1) {
switch (opt) {
case 'p': print_hashes();
break;
case 's': hash = optarg;
sign_by_hash(hash, 0);
break;
case 'r': hash = optarg;
sign_by_hash(hash, 2);
break;
case '?': // fprintf(stderr, "unknown flag\n");
exit(1);
}
}
return 0;
}
......@@ -98,6 +98,24 @@ 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__);
// Copy from libconsensus
inline string exec( const char* cmd ) {
CHECK_STATE( cmd );
std::array< char, 128 > buffer;
std::string result;
std::unique_ptr< FILE, decltype( &pclose ) > pipe( popen( cmd, "r" ), pclose );
if ( !pipe ) {
BOOST_THROW_EXCEPTION( std::runtime_error( "popen() failed!" ) );
}
while ( fgets( buffer.data(), buffer.size(), pipe.get() ) != nullptr ) {
result += buffer.data();
}
return result;
}
#include <shared_mutex>
extern std::shared_timed_mutex sgxInitMutex;
......
......@@ -8,6 +8,7 @@ services:
- "1027:1027"
- "1028:1028"
- "1029:1029"
- "1030:1030"
devices:
- "/dev/isgx"
- "/dev/mei0"
......
......@@ -8,6 +8,7 @@ services:
- "1027:1027"
- "1028:1028"
- "1029:1029"
- "1030:1030"
volumes:
- ./sgx_data:/usr/src/sdk/sgx_data
- /dev/urandom:/dev/random
......
......@@ -1244,6 +1244,117 @@ void trustedCreateBlsKey(int *errStatus, char *errString, const char *s_shares,
LOG_INFO("SGX call completed");
}
void trustedCreateBlsKeyV2(int *errStatus, char *errString, const char *s_shares,
uint8_t *encryptedPrivateKey, uint64_t key_len, uint8_t *encr_bls_key,
uint64_t *enc_bls_key_len) {
LOG_INFO(__FUNCTION__);
INIT_ERROR_STATE
CHECK_STATE(s_shares);
CHECK_STATE(encryptedPrivateKey);
CHECK_STATE(encr_bls_key);
SAFE_CHAR_BUF(skey, BUF_LEN);
mpz_t sum;
mpz_init(sum);
mpz_set_ui(sum, 0);
mpz_t q;
mpz_init(q);
mpz_set_str(q, "21888242871839275222246405745257275088548364400416034343698204186575808495617", 10);
mpz_t bls_key;
mpz_init(bls_key);
uint8_t type = 0;
uint8_t exportable = 0;
int status = AES_decrypt(encryptedPrivateKey, key_len, skey, BUF_LEN,
&type, &exportable);
CHECK_STATUS2("aes decrypt failed with status %d");
skey[ECDSA_SKEY_LEN - 1] = 0;
int num_shares = strlen(s_shares) / 192;
for (int i = 0; i < num_shares; i++) {
SAFE_CHAR_BUF(encr_sshare, 65);
strncpy(encr_sshare, s_shares + 192 * i, 64);
encr_sshare[64] = 0;
SAFE_CHAR_BUF(s_share, 193);
strncpy(s_share, s_shares + 192 * i, 192);
s_share[192] = 0;
SAFE_CHAR_BUF(common_key, 65);
status = session_key_recover(skey, s_share, common_key);
CHECK_STATUS("session_key_recover failed");
common_key[64] = 0;
SAFE_CHAR_BUF(derived_key, BUF_LEN);
status = hash_key(common_key, derived_key);
CHECK_STATUS("hash key failed")
derived_key[ECDSA_BIN_LEN - 1] = 0;
SAFE_CHAR_BUF(decr_sshare, 65);
status = xor_decrypt_v2(derived_key, encr_sshare, decr_sshare);
CHECK_STATUS("xor_decrypt failed");
decr_sshare[64] = 0;
mpz_t decr_secret_share;
mpz_init(decr_secret_share);
if (mpz_set_str(decr_secret_share, decr_sshare, 16) == -1) {
*errStatus = 111;
snprintf(errString, BUF_LEN, "invalid decrypted secret share");
LOG_ERROR(errString);
mpz_clear(decr_secret_share);
goto clean;
}
mpz_addmul_ui(sum, decr_secret_share, 1);
mpz_clear(decr_secret_share);
}
mpz_mod(bls_key, sum, q);
SAFE_CHAR_BUF(key_share, BLS_KEY_LENGTH);
SAFE_CHAR_BUF(arr_skey_str, BUF_LEN);
mpz_get_str(arr_skey_str, 16, bls_key);
int n_zeroes = 64 - strlen(arr_skey_str);
for (int i = 0; i < n_zeroes; i++) {
key_share[i] = '0';
}
strncpy(key_share + n_zeroes, arr_skey_str, 65 - n_zeroes);
key_share[BLS_KEY_LENGTH - 1] = 0;
status = AES_encrypt(key_share, encr_bls_key, BUF_LEN, BLS, NON_EXPORTABLE, enc_bls_key_len);
CHECK_STATUS2("aes encrypt bls private key failed with status %d ");
SET_SUCCESS
clean:
mpz_clear(bls_key);
mpz_clear(sum);
mpz_clear(q);
LOG_INFO(__FUNCTION__ );
LOG_INFO("SGX call completed");
}
void
trustedGetBlsPubKey(int *errStatus, char *errString, uint8_t *encryptedPrivateKey, uint64_t key_len,
char *bls_pub_key) {
......
......@@ -156,6 +156,15 @@ enclave {
[out, count = SMALL_BUF_SIZE] uint8_t * encr_bls_key,
[out] uint64_t *enc_bls_key_len);
public void trustedCreateBlsKeyV2(
[out]int *errStatus,
[out, count = SMALL_BUF_SIZE] char* err_string,
[in, count = 6145] const char* s_shares,
[in, count = SMALL_BUF_SIZE] uint8_t* encrypted_key,
uint64_t key_len,
[out, count = SMALL_BUF_SIZE] uint8_t * encr_bls_key,
[out] uint64_t *enc_bls_key_len);
public void trustedBlsSignMessage (
[out] int *errStatus,
[out, count = TINY_BUF_SIZE] char* err_string,
......
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file sgx_util.cpp
@author Stan Kladko
@date 2019
*/
#include <iostream>
#include <cstring>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include "stubclient.h"
#include "common.h"
#include <unistd.h>
int print_hashes(){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.getUnsignedCSRs() << std::endl;
exit(0);
}
void sign_by_hash(std::string & hash, int status){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.signByHash(hash, status) << std::endl;
exit(0);
}
void getNumberOfKeysCreated() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
std::cout << c.getAllKeysInfo()["keysNumber"].asString() << std::endl;
exit(0);
}
void getAllKeysInfo() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
std::cout << c.getAllKeysInfo()["allKeys"].asString() << std::endl;
std::cout << "TOTAL KEYS IN DATABASE: " << c.getAllKeysInfo()["keysNumber"].asString() << std::endl;
exit(0);
}
void getLatestCreatedKey() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
Json::Value lastCreatedKey = c.getLatestCreatedKey();
std::cout << "Last created key name: " << lastCreatedKey["keyName"] << std::endl;
std::string timestamp_to_date_command = "date -d @" + lastCreatedKey["creationTime"].asString();
std::cout << "Last created key creation time: " << exec(timestamp_to_date_command.c_str());
exit(0);
}
void getServerConfiguration() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
Json::Value response = c.getServerConfiguration();
std::cout << "OPTION autoConfirm certificates switched to " << response["autoConfirm"] << '\n';
uint32_t logLevel = response["logLevel"].asInt();
std::string logLevelStr;
switch(logLevel) {
case 0:
logLevelStr = "trace";
break;
case 1:
logLevelStr = "debug";
break;
case 2:
logLevelStr = "info";
break;
case 3:
logLevelStr = "warning";
break;
case 4:
logLevelStr = "error";
break;
}
std::cout << "OPTION logLevel switched to " << logLevelStr << '\n';
std::cout << "OPTION enterBackupKey switched to " << response["enterBackupKey"] << '\n';
std::cout << "OPTION useHTTPS switched to " << response["useHTTPS"] << '\n';
std::cout << "OPTION autoSign certificates switched to " << response["autoSign"] << '\n';
std::cout << "OPTION checkCerts switched to " << response["checkCerts"] << '\n';
std::cout << "OPTION generateTestKeys switched to " << response["generateTestKeys"] << '\n';
exit(0);
}
void isKeyExists(const std::string& key) {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
if (c.isKeyExist(key)["IsExist"].asBool()) {
std::cout << "Key with name " << key << " presents in server database.\n";
} else {
std::cout << "Key with name " << key << " does not exist in server's database.\n";
}
exit(0);
}
int main(int argc, char *argv[]) {
int opt;
if (argc > 1 && strlen(argv[1]) == 1) {
fprintf(stderr, "option is too short %s\n", argv[1]);
exit(1);
}
if (argc == 1) {
std::cout << "You may use following flags:" << std::endl;
std::cout << " -p print all unsigned csr hashes " << std::endl;
std::cout << " -s [hash] sign csr by hash" << std::endl;
std::cout << " -r [hash] reject csr by hash" << std::endl;
std::cout << " -a print all keys" << std::endl;
std::cout << " -l print latest created key" << std::endl;
std::cout << " -n print number of keys stored in database" << std::endl;
std::cout << " -c print server's config" << std::endl;
std::cout << " -i [name] check if key with such name presents in database" << std::endl;
exit(0);
}
std::string hash;
std::string key;
while ((opt = getopt(argc, argv, "ps:r:alci:n")) != -1) {
switch (opt) {
case 'p': print_hashes();
break;
case 's': hash = optarg;
sign_by_hash(hash, 0);
break;
case 'r': hash = optarg;
sign_by_hash(hash, 2);
break;
case 'a':
getAllKeysInfo();
break;
case 'l':
getLatestCreatedKey();
break;
case 'c':
getServerConfiguration();
break;
case 'i': key = optarg;
isKeyExists(key);
break;
case 'n':
getNumberOfKeysCreated();
break;
case '?': // fprintf(stderr, "unknown flag\n");
exit(1);
}
}
return 0;
}
......@@ -174,7 +174,7 @@ int main(int argc, char *argv[]) {
enclaveLogLevel = L_TRACE;
}
initAll(enclaveLogLevel, checkClientCertOption, autoSignClientCertOption);
initAll(enclaveLogLevel, checkClientCertOption, autoSignClientCertOption, generateTestKeys);
ifstream is("sgx_data/4node.json");
......
......@@ -113,7 +113,7 @@ extern bool autoconfirm;
#define FILE_NOT_FOUND -44
#define INVALID_DKG_GETSS_PARAMS -45
#define INVALID_DKG_GETSS_PUB_KEY_COUNT -46
#define INVALID_DKG_GETSS_KEY_HEX -47
#define INVALID_DKG_GETSS_KEY_HEX -47
#define INVALID_DKG_VERIFY_ECDSA_KEY_NAME -48
#define INVALID_DKG_VERIFY_PARAMS -49
#define INVALID_DKG_VERIFY_SS_HEX -50
......@@ -125,14 +125,14 @@ extern bool autoconfirm;
#define INVALID_CREATE_BLS_KEY_NAME -56
#define INVALID_CREATE_BLS_DKG_PARAMS -57
#define INVALID_CREATE_BLS_SHARE -58
#define INVALID_GET_BLS_PUBKEY_NAME -59
#define INVALID_GET_BLS_PUBKEY_NAME -59
#define INVALID_DKG_CALCULATE_ALL_PARAMS -60
#define INVALID_DKG_CALCULATE_ALL_PUBSHARES -61
#define INVALID_DKG_CALCULATE_ALL_PUBSHARES_SIZE -62
#define INVALID_DKG_CALCULATE_ALL_PUBSHARES_STRING -63
#define INVALID_DKG_CALCULATE_ALL_STRING_PUBSHARES_SLENGTH -64
#define INVALID_DKG_CALCULATE_ALL_STRING_PUBKEYS_SIZE -65
#define INVALID_COMPLAINT_RESPONSE_POLY_NAME -66
#define INVALID_COMPLAINT_RESPONSE_POLY_NAME -66
#define INVALID_DKG_GETSS_V2_PARAMS -63
#define INVALID_DKG_GETSS_V2_POLY_NAME -64
#define INVALID_DKG_GETSS_V2_PUBKEY_COUNT -65
......@@ -147,7 +147,7 @@ extern bool autoconfirm;
#define CONVERT_G2_INCORRECT_STRING_CONVERSION -74
#define DELETE_BLS_KEY_INVALID_KEYNAME -75
#define DELETE_BLS_KEY_NOT_FOUND -76
#define VERIFY_SHARES_INVALID_PUBLIC_SHARES -77
#define VERIFY_SHARES_INVALID_PUBLIC_SHARES -77
#define VERIFY_SHARES_V2_INVALID_POLY_HEX -78
#define VERIFY_SHARES_V2_INVALID_PUBLIC_SHARES -79
#define CREATE_BLS_SHARE_INVALID_KEY_HEX -80
......@@ -158,7 +158,7 @@ extern bool autoconfirm;
#define GET_ECDSA_PUB_KEY_INVALID_KEY_HEX -85
#define ECDSA_SIGN_INVALID_KEY_HEX -86
#define SET_SEK_INVALID_SEK_HEX -87
#define TEST_INVALID_HEX -88
#define TEST_INVALID_HEX -88
#define SGX_ENCLAVE_ERROR -666
......@@ -173,10 +173,5 @@ extern bool autoconfirm;
#define TEST_VALUE "1234567890"
#define SEMAPHORE_BEGIN { semaphore_guard __ENCLAVE__GUARD__(enclaveSemaphore) ;
#define SEMAPHORE_END }
#endif //SGXWALLET_SGXWALLET_COMMON_H
......@@ -187,6 +187,22 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value createBLSPrivateKeyV2(const std::string& blsKeyName, const std::string& ethKeyName, const std::string& polyName, const std::string& SecretShare, int t, int n)
{
Json::Value p;
p["blsKeyName"] = blsKeyName;
p["ethKeyName"] = ethKeyName;
p["polyName"] = polyName;
p["secretShare"] = SecretShare;
p["n"] = n;
p["t"] = t;
Json::Value result = this->CallMethod("createBLSPrivateKeyV2",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getBLSPublicKeyShare(const std::string & blsKeyName)
{
Json::Value p;
......@@ -263,55 +279,99 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerStatus()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerStatus",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerVersion() {
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerVersion",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
////CSRManagerServer
Json::Value getUnsignedCSRs()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getUnsignedCSRs",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value signByHash(const std::string& hash, int status)
{
Json::Value p;
p["hash"] = hash;
p["status"] = status;
Json::Value result = this->CallMethod("signByHash",p);
if (result.isObject())
Json::Value getUnsignedCSRs()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getUnsignedCSRs",p);
if (result.isObject())
return result;
else
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
}
Json::Value signByHash(const std::string& hash, int status)
{
Json::Value p;
p["hash"] = hash;
p["status"] = status;
Json::Value result = this->CallMethod("signByHash",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerStatus()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerStatus",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
/// InfoServer
Json::Value getServerVersion() {
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerVersion",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getAllKeysInfo()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getAllKeysInfo", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getLatestCreatedKey()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getLatestCreatedKey", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerConfiguration()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerConfiguration", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value isKeyExist(const std::string& key)
{
Json::Value p;
p["keyName"] = key;
Json::Value result = this->CallMethod("isKeyExist", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
};
......
......@@ -72,7 +72,7 @@ public:
TestFixture() {
TestUtils::resetDB();
setOptions(L_INFO, false, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixture() {
......@@ -85,7 +85,7 @@ public:
TestFixtureHTTPS() {
TestUtils::resetDB();
setOptions(L_INFO, true, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixtureHTTPS() {
......@@ -98,7 +98,7 @@ class TestFixtureNoResetFromBackup {
public:
TestFixtureNoResetFromBackup() {
setFullOptions(L_INFO, false, true, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixtureNoResetFromBackup() {
......@@ -112,7 +112,7 @@ class TestFixtureNoReset {
public:
TestFixtureNoReset() {
setOptions(L_INFO, false, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixtureNoReset() {
......@@ -1002,7 +1002,7 @@ TEST_CASE_METHOD(TestFixture, "AES_DKG V2 test", "[aes-dkg-v2]") {
for (int i = 0; i < t; i++) {
string endName = polyNames[i].substr(4);
string blsName = "BLS_KEY" + polyNames[i].substr(4);
auto response = c.createBLSPrivateKey(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
auto response = c.createBLSPrivateKeyV2(blsName, ethKeys[i]["keyName"].asString(), polyNames[i], secShares[i], t,
n);
REQUIRE(response["status"] == 0);
......@@ -1074,7 +1074,7 @@ TEST_CASE_METHOD(TestFixture, "Many threads ecdsa dkg v2 bls", "[many-threads-cr
vector <thread> threads;
int num_threads = 4;
for (int i = 0; i < num_threads; i++) {
threads.push_back(thread(TestUtils::sendRPCRequest));
threads.push_back(thread(TestUtils::sendRPCRequestV2));
}
for (auto &thread : threads) {
......
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