Unverified Commit 780aebbe authored by Stan Kladko's avatar Stan Kladko Committed by GitHub

Merge pull request #10 from skalenetwork/enhancement/SKALE-1762-Add-SSL-to-SGX-server-and-client

Enhancement/skale 1762 add ssl to sgx server and client
parents 5ef86e52 c33bb55a
......@@ -28,6 +28,8 @@
#include "BLSCrypto.h"
#include "ServerInit.h"
#include "RPCException.h"
int char2int(char _input) {
......@@ -159,13 +161,16 @@ char *encryptBLSKeyShare2Hex(int *errStatus, char *err_string, const char *_key)
status = encrypt_key(eid, errStatus, errMsg, keyArray, encryptedKey, &encryptedLen);
std::cerr << "errStatus is " << *errStatus << " errMsg is " << errMsg << std::endl;
if (status != SGX_SUCCESS) {
*errStatus = -1;
return nullptr;
}
if (*errStatus != 0) {
return nullptr;
throw RPCException(-666, errMsg);
}
......
......@@ -165,7 +165,7 @@ std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
// strncpy(signature, "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855", 1024);
printf("---: %s\n", signature);
printf("sig is: %s\n", signature);
if (status != SGX_SUCCESS) {
......@@ -301,6 +301,7 @@ std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
auto sig = make_shared<string>(signature);
//BLSSigShare* sig_test = new BLSSigShare(sig, _signerIndex, requiredSigners, totalSigners);
......
......@@ -9,6 +9,7 @@
#include <memory>
#include "SGXWalletServer.hpp"
#include "RPCException.h"
#include <../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <../trusted_libff/libff/algebra/fields/fp.hpp>
......@@ -88,6 +89,9 @@ std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyH
uint32_t len;
status = get_public_shares(eid, &err_status, errMsg1, encr_dkg_poly, len, public_shares, t, n);
if ( status != 0){
}
std::cerr << "err msg " << errMsg1 << std::endl;
std::cerr << "public_shares:" << std::endl;
......@@ -128,22 +132,31 @@ std::string get_secret_shares(const std::string& polyName, const char* encrypted
uint32_t dec_len;
char cur_share[193];
char s_shareG2[320];
std::string pub_keyB = publicKeys.at(i);//publicKeys.substr(128*i, 128*i + 128);
std::cerr << "pub_keyB is " << pub_keyB << std::endl;
char pubKeyB[129];
strncpy(pubKeyB, pub_keyB.c_str(), 128);
pubKeyB[128] = 0;
get_encr_sshare(eid, &err_status, errMsg1, encrypted_skey, &dec_len,
cur_share, pubKeyB, t, n, i + 1 );
cur_share, s_shareG2, pubKeyB, t, n, i + 1 );
result += cur_share;
uint32_t enc_len = BUF_LEN;
carray2Hex(encrypted_skey, enc_len, hexEncrKey);
//std::cerr << "hexEncrKey: " << hexEncrKey << std::endl;
//uint32_t enc_len = BUF_LEN;
std::cerr << "dec len is " << dec_len << std::endl;
carray2Hex(encrypted_skey, dec_len, hexEncrKey);
std::string name = "DKG_DH_KEY_" + polyName + "_" + std::to_string(i) + ":";
//writeDataToDB(name, hexEncrKey);
// std::string DHKey_name = "DKG_DH_KEY_" + polyName + "_" + std::to_string(i) + ":";
// std::cerr << "name to write to db is " << DHKey_name << std::endl;
// std::cerr << "hexEncrKey: " << hexEncrKey << std::endl;
// writeDataToDB(DHKey_name, hexEncrKey);
//
// std::string shareG2_name = "shareG2_" + polyName + "_" + std::to_string(i) + ":";
// std::cerr << "name to write to db is " << shareG2_name << std::endl;
// std::cerr << "s_shareG2: " << s_shareG2 << std::endl;
// writeDataToDB(shareG2_name, s_shareG2);
std::cerr << errMsg1 << std::endl << std::endl;
//std::cerr << "iteration " << i <<" result length is " << result.length() << std::endl ;
......@@ -197,9 +210,10 @@ bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const
uint8_t encr_bls_key[BUF_LEN];
uint8_t encr_key[BUF_LEN];
hex2carray(encryptedKeyHex, &dec_key_len, encr_key);
uint32_t enc_bls_len = 0;
//std::cerr << " key hex is " << encryptedKeyHex << std::endl;
create_bls_key(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key);
create_bls_key(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key, &enc_bls_len);
std::cerr << "er msg is " << errMsg1 << std::endl;
if ( err_status != 0){
......@@ -207,16 +221,19 @@ bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const
}
else {
char *hexBLSKey = (char *) calloc(2 * BUF_LEN, 1);
uint32_t enc_len = BUF_LEN;
carray2Hex(encr_bls_key, enc_len, hexBLSKey);
writeDataToDB(BLSKeyName, hexBLSKey);
std::cerr << "enc_bls_len " << enc_bls_len << std::endl;
carray2Hex(encr_bls_key, enc_bls_len, hexBLSKey);
writeDataToDB(BLSKeyName, hexBLSKey);
std::cerr << "hexBLSKey length is " << strlen(hexBLSKey) << std::endl;
std::cerr << "bls key " << BLSKeyName << " is " << hexBLSKey << std::endl;
free(hexBLSKey);
return true;
}
}
std::string GetBLSPubKey(const char * encryptedKeyHex){
std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
......@@ -224,27 +241,28 @@ std::string GetBLSPubKey(const char * encryptedKeyHex){
uint8_t encr_bls_key[BUF_LEN];
uint8_t encr_key[BUF_LEN];
hex2carray(encryptedKeyHex, &dec_key_len, encr_key);
// for ( int i = 0; i < BUF_LEN; i++ )
// std::cerr << encr_key[i] << " ";
char pub_key[320];
std::cerr << "dec_key_len is " << dec_key_len << std::endl;
get_bls_pub_key(eid, &err_status, errMsg1, encr_key, dec_key_len, pub_key);
std::string result = pub_key;
std::cerr << "errMsg1 is " << errMsg1 << std::endl;
std::vector<std::string> pub_key_vect = SplitString(pub_key, ':');
std::cerr << "pub key is" << std::endl;
for ( int i = 0; i < 4; i++)
std::cerr << pub_key_vect.at(i) << std::endl;
return pub_key_vect;
}
std::pair<std::string, std::string> response_to_complaint(const std::string& polyName, const char* encryptedPolyHex, int n, int t, int ind){
std::string decrypt_DHKey(const std::string& polyName, int ind){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
uint64_t enc_len = 0;
uint8_t* encr_dkg_poly = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
hex2carray2(encryptedPolyHex, &enc_len, encr_dkg_poly, 6100);
status = set_encrypted_dkg_poly(eid, &err_status, errMsg1, encr_dkg_poly);
std::string DH_key_name = polyName + "_" + std::to_string(ind) + ":";
std::shared_ptr<std::string> hexEncrKey_ptr = readFromDb(DH_key_name, "DKG_DH_KEY_");
std::cerr << "encr DH key is " << hexEncrKey_ptr << std::endl;
char *hexEncrKey = (char *) calloc(2 * BUF_LEN, 1);
......@@ -252,28 +270,14 @@ std::pair<std::string, std::string> response_to_complaint(const std::string& pol
uint8_t encrypted_DHkey[BUF_LEN];
hex2carray(hexEncrKey_ptr->c_str(), &DH_enc_len, encrypted_DHkey);
char DHKey[ECDSA_SKEY_LEN];
uint32_t dec_len;
char decrpyted_DHkey[ECDSA_SKEY_LEN];
char s_shareG2[257];
status = complaint_response(eid, &err_status, errMsg1, encrypted_DHkey, encr_dkg_poly, &dec_len,
decrpyted_DHkey, s_shareG2, t, n, ind);
std::pair<std::string, std::string> result;
result.first = decrpyted_DHkey;
result.second = s_shareG2;
//std::cerr << errMsg1 << std::endl << std::endl;
//std::cerr << "iteration " << i <<" result length is " << result.length() << std::endl ;
//std::cerr << "iteration " << i <<" share length is " << strlen(cur_share) << std::endl;
//std::cerr << "iteration " << i <<" share is " << cur_share << std::endl;
decrypt_key(eid, &err_status, errMsg1, encrypted_DHkey, DH_enc_len, DHKey);
//result += '\0';
free(encr_dkg_poly);
free(errMsg1);
free(hexEncrKey);
return result;
}
\ No newline at end of file
return DHKey;
}
......@@ -18,12 +18,11 @@ std::string get_secret_shares(const std::string& polyName, const char* encrypted
bool VerifyShares(const char* publicShares, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
std::pair<std::string, std::string> response_to_complaint(const std::string& polyName, const char* encryptedPolyHex, int n, int t, int ind);
std::string decrypt_DHKey(const std::string& polyName, int ind);
bool CreateBLSShare( const std::string& BLSKeyName, const char * s_shares, const char * encryptedKeyHex);
std::string GetBLSPubKey(const char * encryptedKeyHex);
std::vector<std::string> GetBLSPubKey(const char * encryptedKeyHex);
#endif //SGXD_DKGCRYPTO_H
......@@ -5,8 +5,10 @@
#include "ECDSACrypto.h"
#include "BLSCrypto.h"
#include "sgxwallet.h"
#include <iostream>
#include "RPCException.h"
#include <iostream>
#include <gmp.h>
#include <random>
......@@ -21,6 +23,10 @@ std::vector<std::string> gen_ecdsa_key(){
uint32_t enc_len = 0;
status = generate_ecdsa_key(eid, &err_status, errMsg, encr_pr_key, &enc_len, pub_key_x, pub_key_y );
if ( err_status != 0 ){
std::cerr << "RPCException thrown" << std::endl;
throw RPCException(-666, errMsg) ;
}
std::vector<std::string> keys(3);
std::cerr << "account key is " << errMsg << std::endl;
char *hexEncrKey = (char *) calloc(2*BUF_LEN, 1);
......@@ -40,13 +46,15 @@ std::vector<std::string> gen_ecdsa_key(){
mpz_t rand32;
mpz_init(rand32);
mpz_urandomb(rand32, state, 257);
mpz_urandomb(rand32, state, 256);
char arr[mpz_sizeinbase (rand32, 16) + 2];
char * rand_str = mpz_get_str(arr, 16, rand32);
keys.at(2) = rand_str;
std::cerr << "rand_str length is " << strlen(rand_str) << std::endl;
gmp_randclear(state);
mpz_clear(rand32);
......@@ -70,6 +78,9 @@ std::string get_ecdsa_pubkey(const char* encryptedKeyHex){
hex2carray(encryptedKeyHex, &enc_len, encr_pr_key);
status = get_public_ecdsa_key(eid, &err_status, errMsg, encr_pr_key, enc_len, pub_key_x, pub_key_y );
if ( err_status != 0){
throw RPCException(-666, errMsg) ;
}
std::string pubKey = std::string(pub_key_x) + std::string(pub_key_y);
std::cerr << "err str " << errMsg << std::endl;
......@@ -100,6 +111,9 @@ std::vector<std::string> ecdsa_sign_hash(const char* encryptedKeyHex, const char
std::cerr << "encrypted len" << dec_len << std::endl;
status = ecdsa_sign1(eid, &err_status, errMsg, encr_key, ECDSA_ENCR_LEN, (unsigned char*)hashHex, signature_r, signature_s, &signature_v, base );
if ( err_status != 0){
throw RPCException(-666, errMsg ) ;
}
std::cerr << "signature r in ecdsa_sign_hash "<< signature_r << std::endl;
std::cerr << "signature s in ecdsa_sign_hash "<< signature_s << std::endl;
......
......@@ -119,6 +119,17 @@ void LevelDB::deleteTempNEK(const std::string &_key){
std::cerr << "key deleted " << _key << std::endl;
}
void LevelDB::deleteKey(const std::string &_key){
std::lock_guard<std::recursive_mutex> lock(mutex);
auto status = db->Delete(writeOptions, Slice(_key));
throwExceptionOnError(status);
std::cerr << "key deleted " << _key << std::endl;
}
void LevelDB::writeByteArray(const char *_key, size_t _keyLen, const char *value,
......
......@@ -64,6 +64,8 @@ public:
void deleteTempNEK (const std::string &_key);
void deleteKey(const std::string &_key);
public:
......
......@@ -28,6 +28,7 @@ include $(top_srcdir)/build-aux/sgx_app.am
SUBDIRS=secure_enclave
## Supply additional flags to edger8r here.
##
## SGX_EDGER8R_FLAGS=
......@@ -66,7 +67,7 @@ COMMON_SRC = sgx_stub.c sgx_detect_linux.c create_enclave.c oc_alloc.c
COMMON_ENCLAVE_SRC = secure_enclave_u.c secure_enclave_u.h
sgxwallet_SOURCES = sgxwallet.c SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp $(COMMON_SRC)
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp $(COMMON_SRC)
nodist_sgxwallet_SOURCES = $(COMMON_ENCLAVE_SRC)
......@@ -93,12 +94,12 @@ secure_enclave.signed.so: secure_enclave/secure_enclave.signed.so
sgxwallet_LDADD=-l$(SGX_URTS_LIB) -Lleveldb/build -LlibBLS/build -LlibBLS/build/libff/libff -l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ldl -l:libsgx_capable.a -l:libsgx_tprotected_fs.a -ljsonrpccpp-stub -lpthread -ljsonrpccpp-common \
-ljsonrpccpp-server -ljsonrpccpp-client -ljsoncpp -lcurl -lprocps intel-sgx-ssl/Linux/package/lib64/libsgx_usgxssl.a \
intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a
intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a -lboost_system -lboost_filesystem
testw_SOURCES=testw.cpp stubclient.cpp SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ServerInit.cpp LevelDB.cpp \
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp $(COMMON_SRC)
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp ServerDataChecker.cpp $(COMMON_SRC)
nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
This diff is collapsed.
......@@ -20,7 +20,7 @@ class SGXWalletServer : public AbstractStubServer {
public:
SGXWalletServer(AbstractServerConnector &connector, serverVersion_t type);
virtual Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t);
virtual Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName, int n, int t, int index);
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int t, int signerIndex);
virtual Json::Value importECDSAKey(const std::string& key, const std::string& keyName);
......@@ -35,7 +35,7 @@ public:
virtual Json::Value DKGVerification(const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index);
virtual Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
virtual Json::Value GetBLSPublicKeyShare(const std::string & BLSKeyName);
virtual Json::Value ComplaintResponse(const std::string& polyName, int n, int t, int ind);
virtual Json::Value ComplaintResponse(const std::string& polyName, int ind);
};
......@@ -45,13 +45,7 @@ void writeDataToDB(const string & Name, const string &value);
void writeKeyShare(const string &_keyShareName, const string &value, int index, int n, int t);
shared_ptr<std::string> readKeyShare(const string& _keyShare);
void writeECDSAKey(const string& _keyName, const string& value);
shared_ptr<std::string> readECDSAKey(const string& _key);
void writeDKGPoly(const string &_polyName, const string &value);
Json::Value importBLSKeyShareImpl(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t);
Json::Value importBLSKeyShareImpl(const std::string& keyShare, const std::string& keyShareName, int n, int t, int index);
Json::Value blsSignMessageHashImpl(const std::string& keyShareName, const std::string& messageHash, int n, int t, int signerIndex);
Json::Value importECDSAKeyImpl(const std::string& key, const std::string& keyName);
......@@ -66,6 +60,6 @@ Json::Value getSecretShareImpl(const std::string& polyName, const Json::Value& p
Json::Value DKGVerificationImpl(const std::string& publicShares, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index);
Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n);
Json::Value GetBLSPublicKeyShareImpl(const std::string & BLSKeyName);
Json::Value ComplaintResponseImpl(const std::string& polyName, int n, int t, int ind);
Json::Value ComplaintResponseImpl(const std::string& polyName, int ind);
#endif //SGXWALLET_SGXWALLETSERVER_HPP
\ No newline at end of file
//
// Created by kladko on 11/19/19.
//
#include <vector>
#include "ServerDataChecker.h"
#include <gmp.h>
#include <iostream>
std::vector<std::string> SplitString(const std::string& str, const std::string& delim = ":"){
std::vector<std::string> tokens;
size_t prev = 0, pos = 0;
do {
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (!token.empty()) tokens.push_back(token);
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}
bool checkECDSAKeyName(const std::string& keyName) {
std::vector<std::string> parts = SplitString(keyName);
if (parts.size() != 2) {
std::cerr << "num parts != 2" << std::endl;
return false;
}
if (parts.at(0) != "NEK") {
std::cerr << "key doesn't start from NEK" << std::endl;
return false;
}
if ( parts.at(1).length() > 64 || parts.at(1).length() < 1){
std::cerr << "wrong key length" << std::endl;
return false;
}
mpz_t num;
mpz_init(num);
if ( mpz_set_str(num, parts.at(1).c_str(), 16) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
return true;
}
bool checkHex(const std::string& hex, const uint32_t sizeInBytes){
if ( hex.length() > sizeInBytes * 2 || hex.length() == 0){
return false;
}
mpz_t num;
mpz_init(num);
if ( mpz_set_str(num, hex.c_str(), 16) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
return true;
}
bool checkPolyName (const std::string& polyName){
std::vector<std::string> parts = SplitString(polyName);
if ( parts.size() != 7) {
return false;
}
if ( parts.at(0) != "POLY") {
return false;
}
if ( parts.at(1) != "SCHAIN_ID"){
return false;
}
if ( parts.at(3) != "NODE_ID"){
return false;
}
if ( parts.at(5) != "DKG_ID"){
return false;
}
if ( parts.at(2).length() > 64 || parts.at(2).length() < 1){
return false;
}
if (parts.at(4).length() > 5 || parts.at(4).length() < 1){
return false;
}
if ( parts.at(6).length() > 64 || parts.at(6).length() < 1){
return false;
}
mpz_t num;
mpz_init(num);
if ( mpz_set_str(num, parts.at(2).c_str(), 16) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
mpz_init(num);
if ( mpz_set_str(num, parts.at(4).c_str(), 10) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
mpz_init(num);
if ( mpz_set_str(num, parts.at(6).c_str(),16) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
return true;
}
bool checkName (const std::string& Name, const std::string& prefix){
std::vector<std::string> parts = SplitString(Name);
if ( parts.size() != 7) {
return false;
}
if ( parts.at(0) != prefix ) {
return false;
}
if ( parts.at(1) != "SCHAIN_ID"){
return false;
}
if ( parts.at(3) != "NODE_ID"){
return false;
}
if ( parts.at(5) != "DKG_ID"){
return false;
}
if ( parts.at(2).length() > 78 || parts.at(2).length() < 1){
return false;
}
if (parts.at(4).length() > 5 || parts.at(4).length() < 1){
return false;
}
if ( parts.at(6).length() > 78 || parts.at(6).length() < 1){
return false;
}
mpz_t num;
mpz_init(num);
if ( mpz_set_str(num, parts.at(2).c_str(), 10) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
mpz_init(num);
if ( mpz_set_str(num, parts.at(4).c_str(), 10) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
mpz_init(num);
if ( mpz_set_str(num, parts.at(6).c_str(),10) == -1){
mpz_clear(num);
return false;
}
mpz_clear(num);
return true;
}
bool check_n_t ( const int n, const int t){
if (t > n){
return false;
}
if ( t == 0 || n == 0){
return false;
}
if ( t < 0 || n < 0){
return false;
}
return true;
}
\ No newline at end of file
//
// Created by kladko on 11/19/19.
//
#ifndef SGXD_SERVERDATACHECKER_H
#define SGXD_SERVERDATACHECKER_H
#include <string>
bool checkECDSAKeyName(const std::string& keyName);
bool checkHex(const std::string& hash, const uint32_t sizeInBytes = 32);
bool checkPolyName (const std::string& polyName);
bool checkName (const std::string& Name, const std::string& prefix);
bool check_n_t ( const int n, const int t);
#endif // SGXD_SERVERDATACHECKER_H
......@@ -30,7 +30,7 @@
#include "BLSCrypto.h"
#include "ServerInit.h"
#include <iostream>
......@@ -42,6 +42,7 @@ void init_daemon() {
static std::string dbName("./" WALLETDB_NAME);
levelDb = new LevelDB(dbName);
}
......@@ -63,6 +64,8 @@ void init_enclave() {
}
#endif
std::cerr << "SGX_DEBUG_FLAG = " << SGX_DEBUG_FLAG << std::endl;
status = sgx_create_enclave_search(ENCLAVE_NAME, SGX_DEBUG_FLAG, &token,
&updated, &eid, 0);
......
......@@ -12,7 +12,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
public:
AbstractStubServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer<AbstractStubServer>(conn, type)
{
this->bindAndAddMethod(jsonrpc::Procedure("importBLSKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "index",jsonrpc::JSON_INTEGER,"keyShare",jsonrpc::JSON_STRING,"keyShareName",jsonrpc::JSON_STRING,"n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::importBLSKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("importBLSKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyShare",jsonrpc::JSON_STRING,"keyShareName",jsonrpc::JSON_STRING,"n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::importBLSKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("blsSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyShareName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING,"n",jsonrpc::JSON_INTEGER,"signerIndex",jsonrpc::JSON_INTEGER,"t",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);
......@@ -27,16 +27,17 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("DKGVerification", 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::DKGVerificationI);
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("ComplaintResponse", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"ind",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::ComplaintResponseI);
}
}
inline virtual void importBLSKeyShareI(const Json::Value &request, Json::Value &response)
{
response = this->importBLSKeyShare(request["index"].asInt(), request["keyShare"].asString(), request["keyShareName"].asString(), request["n"].asInt(), request["t"].asInt());
response = this->importBLSKeyShare( request["keyShare"].asString(), request["keyShareName"].asString(), request["n"].asInt(), request["t"].asInt(), request["index"].asInt());
}
inline virtual void blsSignMessageHashI(const Json::Value &request, Json::Value &response)
{
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["n"].asInt(), request["signerIndex"].asInt(), request["t"].asInt());
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["n"].asInt(), request["t"].asInt(), request["signerIndex"].asInt());
}
inline virtual void importECDSAKeyI(const Json::Value &request, Json::Value &response)
{
......@@ -83,8 +84,12 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->GetBLSPublicKeyShare(request["BLSKeyName"].asString());
}
inline virtual void ComplaintResponseI(const Json::Value &request, Json::Value &response)
{
response = this->ComplaintResponse( request["polyName"].asString(), request["ind"].asInt());
}
virtual Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t) = 0;
virtual Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName, int n, int t, int index) = 0;
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int signerIndex, int t) = 0;
virtual Json::Value importECDSAKey(const std::string& key, const std::string& keyName) = 0;
virtual Json::Value generateECDSAKey() = 0;
......@@ -98,6 +103,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
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 ComplaintResponse(const std::string& polyName, int ind) = 0;
};
#endif //JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_
#!/bin/bash
# Directories
cur=$(pwd)
tmp=$(mktemp -d)
scriptName=$(basename "$0")
# Certificate Variables
OUTPATH="./"
VERBOSE=0
DURATION=3650 # 10 years
safeExit() {
if [ -d "$tmp" ]; then
if [ $VERBOSE -eq 1 ]; then
echo "Removing temporary directory '${tmp}'"
fi
rm -rf "$tmp"
fi
trap - INT TERM EXIT
exit
}
# Help Screen
help() {
echo -n "${scriptName} [OPTIONS] -c=US --state=California
Generate self-signed TLS certificate using OpenSSL
Options:
-c|--country Country Name (2 letter code)
-s|--state State or Province Name (full name)
-l|--locality Locality Name (eg, city)
-o|--organization Organization Name (eg, company)
-u|--unit Organizational Unit Name (eg, section)
-n|--common-name Common Name (e.g. server FQDN or YOUR name)
-e|--email Email Address
-p|--path Path to output generated keys
-d|--duration Validity duration of the certificate (in days)
-h|--help Display this help and exit
-v|--verbose Verbose output
"
}
# Test output path is valid
testPath() {
if [ ! -d $OUTPATH ]; then
echo "The specified directory \"${OUTPATH}\" does not exist"
exit 1
fi
}
# Process Arguments
while [ "$1" != "" ]; do
PARAM=$(echo "$1" | awk -F= '{print $1}')
VALUE=$(echo "$1" | awk -F= '{print $2}')
case $PARAM in
-h|--help) help; safeExit ;;
-c|--country) C=$VALUE ;;
-s|--state) ST=$VALUE ;;
-l|--locality) L=$VALUE ;;
-o|--organization) O=$VALUE ;;
-u|--unit) OU=$VALUE ;;
-n|--common-name) CN=$VALUE ;;
-e|--email) emailAddress=$VALUE ;;
-p|--path) OUTPATH=$VALUE; testPath ;;
-d|--duration) DURATION=$VALUE ;;
-v|--verbose) VERBOSE=1 ;;
*) echo "ERROR: unknown parameter \"$PARAM\""; help; exit 1 ;;
esac
shift
done
# Prompt for variables that were not provided in arguments
checkVariables() {
# Country
if [ -z "$C" ]; then
echo -n "Country Name (2 letter code) [AU]:"
read -r C
fi
# State
if [ -z "$ST" ]; then
echo -n "State or Province Name (full name) [Some-State]:"
read -r ST
fi
# Locality
if [ -z "$L" ]; then
echo -n "Locality Name (eg, city) []:"
read -r L
fi
# Organization
if [ -z "$O" ]; then
echo -n "Organization Name (eg, company) [Internet Widgits Pty Ltd]:"
read -r O
fi
# Organizational Unit
if [ -z "$OU" ]; then
echo -n "Organizational Unit Name (eg, section) []:"
read -r OU
fi
# Common Name
if [ -z "$CN" ]; then
echo -n "Common Name (e.g. server FQDN or YOUR name) []:"
read -r CN
fi
# Email Address
if [ -z "$emailAddress" ]; then
echo -n "Email Address []:"
read -r emailAddress
fi
}
# Show variable values
showVals() {
echo "Country: ${C}";
echo "State: ${ST}";
echo "Locality: ${L}";
echo "Organization: ${O}";
echo "Organization Unit: ${OU}";
echo "Common Name: ${CN}";
echo "Email: ${emailAddress}";
echo "Output Path: ${OUTPATH}";
echo "Certificate Duration (Days): ${DURATION}";
echo "Verbose: ${VERBOSE}";
}
# Init
init() {
cd "$tmp" || exit
pwd
}
# Cleanup
cleanup() {
echo "Cleaning up"
cd "$cur" || exit
rm -rf "$tmp"
}
buildCsrCnf() {
cat << EOF > "${tmp}/tmp.csr.cnf"
[req]
default_bits = 2048
prompt = no
default_md = sha256
distinguished_name = dn
[dn]
C=${C}
ST=${ST}
L=${L}
O=${O}
OU=${OU}
CN=${CN}
emailAddress=${emailAddress}
EOF
}
buildExtCnf() {
cat << EOF > "${tmp}/v3.ext"
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = ${CN}
EOF
}
# Build TLS Certificate
build() {
# Santizie domain name for file name
FILENAME=${CN/\*\./}
# Generate CA key & crt
openssl genrsa -out "${tmp}/tmp.key" 2048
openssl req -x509 -new -nodes -key "${tmp}/tmp.key" -sha256 -days "${DURATION}" -out "${OUTPATH}${FILENAME}_CA.pem" -subj "/C=${C}/ST=${ST}/L=${L}/O=${O}/OU=${OU}/CN=${CN}/emailAddress=${emailAddress}"
# CSR Configuration
buildCsrCnf
# Create v3.ext configuration file
buildExtCnf
# Server key
openssl req -new -sha256 -nodes -out "${OUTPATH}${FILENAME}.csr" -newkey rsa:2048 -keyout "${OUTPATH}${FILENAME}.key" -config <( cat "${tmp}/tmp.csr.cnf" )
# Server certificate
openssl x509 -req -in "${OUTPATH}${FILENAME}.csr" -CA "${OUTPATH}${FILENAME}_CA.pem" -CAkey "${tmp}/tmp.key" -CAcreateserial -out "${OUTPATH}${FILENAME}.crt" -days "${DURATION}" -sha256 -extfile "${tmp}/v3.ext"
}
checkVariables
build
# showVals
safeExit
......@@ -61,9 +61,15 @@ std::string *stringFromG1(libff::alt_bn128_G1 *_g1) {
}
libff::alt_bn128_Fr *keyFromString(const char *_keyString) {
libff::alt_bn128_Fr *keyFromString(const char *_keyStringHex) {
mpz_t skey;
mpz_init(skey);
mpz_set_str(skey, _keyStringHex, 16);
return new libff::alt_bn128_Fr(_keyString);
char skey_dec[mpz_sizeinbase (skey, 10) + 2];
char * skey_str = mpz_get_str(skey_dec, 10, skey);
return new libff::alt_bn128_Fr(skey_dec);
}
......@@ -98,7 +104,7 @@ void checkKey(int *err_status, char *err_string, const char *_keyString) {
*err_status = -3;
// check that key is padded with 0s
//check that key is padded with 0s
for (int i = keyLen; i < MAX_KEY_LENGTH; i++) {
if (_keyString[i] != 0) {
......@@ -106,22 +112,22 @@ void checkKey(int *err_status, char *err_string, const char *_keyString) {
}
}
std::string ks(_keyString);
// std::string keyString =
// "4160780231445160889237664391382223604184857153814275770598791864649971919844";
auto key = keyFromString(ks.c_str());
auto s1 = stringFromKey(key);
if (s1->compare(ks) != 0) {
throw std::exception();
}
// std::string ks(_keyString);
//
// // std::string keyString =
// // "4160780231445160889237664391382223604184857153814275770598791864649971919844";
//
// auto key = keyFromString(ks.c_str());
//
// auto s1 = stringFromKey(key);
//
// if (s1->compare(ks) != 0) {
// throw std::exception();
// }
*err_status = 0;
return;
// return;
}
......@@ -145,9 +151,6 @@ bool enclave_sign(const char *_keyString, const char *_hashXString, const char *
libff::alt_bn128_G1 hash(hashX, hashY, hashZ);
libff::alt_bn128_G1 sign = key->as_bigint() * hash; // sign
sign.to_affine_coordinates();
......
......@@ -100,19 +100,24 @@ void gen_dkg_poly( char* secret, unsigned _t ){
result += ":";
}
strncpy(secret, result.c_str(), result.length() + 1);
if (strlen(secret) == 0){
throw std::exception();
}
}
libff::alt_bn128_Fr PolynomialValue(const std::vector<libff::alt_bn128_Fr>& pol, libff::alt_bn128_Fr point, unsigned _t) {
libff::alt_bn128_Fr value = libff::alt_bn128_Fr::zero();
libff::alt_bn128_Fr pow = libff::alt_bn128_Fr::one();
for (size_t i = 0; i < _t; ++i) {
if (i == _t - 1 && pol[i] == libff::alt_bn128_Fr::zero()) {
//snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status
}
value += pol[i] * pow;
pow *= point;
for (unsigned i = 0; i < pol.size(); ++i) {
// if (i == _t - 1 && pol[i] == libff::alt_bn128_Fr::zero()) {
// //snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status
// }
value += pol[i] * pow;
pow *= point;
}
return value;
......@@ -149,11 +154,16 @@ void calc_secret_share(const char* decrypted_koefs, char * s_share,
}
void calc_secret_shareG2(const char* decrypted_koefs, char * s_shareG2,
void calc_secret_shareG2_old(const char* decrypted_koefs, char * s_shareG2,
unsigned _t, unsigned ind){
libff::init_alt_bn128_params();
char symbol = ':';
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, symbol);
// if ( poly.size() != _t){
// //"t != poly.size()" +
// //strncpy(s_shareG2, std::to_string(poly.size()).c_str(), 18);
// }
libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(ind), _t);
......@@ -161,7 +171,27 @@ void calc_secret_shareG2(const char* decrypted_koefs, char * s_shareG2,
std::string secret_shareG2_str = ConvertG2ToString(secret_shareG2);
strncpy(s_shareG2, secret_shareG2_str.c_str(), secret_shareG2_str.length());
strncpy(s_shareG2, secret_shareG2_str.c_str(), secret_shareG2_str.length() + 1);
//strncpy(s_shareG2, decrypted_koefs, 320);
}
void calc_secret_shareG2(const char* s_share, char * s_shareG2){
libff::init_alt_bn128_params();
mpz_t share;
mpz_init(share);
mpz_set_str(share, s_share, 16);
char arr[mpz_sizeinbase (share, 10) + 2];
char * share_str = mpz_get_str(arr, 10, share);
libff::alt_bn128_Fr secret_share(share_str);
libff::alt_bn128_G2 secret_shareG2 = secret_share * libff::alt_bn128_G2::one();
std::string secret_shareG2_str = ConvertG2ToString(secret_shareG2);
strncpy(s_shareG2, secret_shareG2_str.c_str(), secret_shareG2_str.length() + 1);
}
void calc_public_shares(const char* decrypted_koefs, char * public_shares,
......@@ -238,11 +268,6 @@ int Verification ( char * public_shares, mpz_t decr_secret_share, int _t, int in
char * tmp = mpz_get_str(arr, 10, decr_secret_share);
libff::alt_bn128_Fr sshare(tmp);
// strncpy(public_shares, tmp, strlen(tmp));
// std::string res = ConvertHexToDec("fe43567238abcdef98760");
// strncpy(public_shares, res.c_str(), res.length());
......@@ -273,8 +298,18 @@ int Verification ( char * public_shares, mpz_t decr_secret_share, int _t, int in
}
void calc_bls_public_key(char* skey, char* pub_key){
libff::alt_bn128_Fr bls_skey(skey);
void calc_bls_public_key(char* skey_hex, char* pub_key){
libff::init_alt_bn128_params();
mpz_t skey;
mpz_init(skey);
mpz_set_str(skey, skey_hex, 16);
char skey_dec[mpz_sizeinbase (skey, 10) + 2];
char * skey_str = mpz_get_str(skey_dec, 10, skey);
libff::alt_bn128_Fr bls_skey(skey_dec);
libff::alt_bn128_G2 public_key = bls_skey * libff::alt_bn128_G2::one();
public_key.to_affine_coordinates();
......
......@@ -28,7 +28,9 @@ EXTERNC int Verification ( char * public_shares, mpz_t decr_secret_share, int _t
EXTERNC void calc_bls_public_key(char* skey, char* pub_key);
EXTERNC void calc_secret_shareG2(const char* public_shares, char * s_shareG2,
EXTERNC void calc_secret_shareG2_old(const char* public_shares, char * s_shareG2,
unsigned _t, unsigned ind);
EXTERNC void calc_secret_shareG2(const char* s_share, char * s_shareG2);
#endif //SGXD_DKGUTILS_H
This diff is collapsed.
......@@ -113,6 +113,7 @@ enclave {
[out, count = 1024] uint8_t *encrypted_skey,
[user_check] uint32_t* dec_len,
[out, count = 193] char* result_str,
[out, count = 320] char* s_shareG2,
[in, count = 129] char* pub_keyB,
uint8_t _t,
uint8_t _n,
......@@ -135,7 +136,8 @@ enclave {
[in, count = 6145] const char* s_shares,
[in, count = 1024] uint8_t* encrypted_key,
uint64_t key_len,
[out, count = 1024] uint8_t * encr_bls_key);
[out, count = 1024] uint8_t * encr_bls_key,
[user_check] uint32_t *enc_bls_key_len);
public void get_bls_pub_key(
[user_check]int *err_status,
......@@ -151,7 +153,7 @@ enclave {
[in, count = 3050] uint8_t *encrypted_dkg_secret,
[user_check] uint32_t* dec_len,
[out, count = 65] char* DH_key,
[out, count = 257] char* s_shareG2,
[out, count = 320] char* s_shareG2,
uint8_t _t,
uint8_t _n,
uint8_t ind1);
......
......@@ -29,6 +29,8 @@
#define DKG_BUFER_LENGTH 2490//3060
#define DKG_MAX_SEALED_LEN 3050
#define SECRET_SHARE_NUM_BYTES 96
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
#define ECDSA_ENCR_LEN 625
......@@ -46,7 +48,15 @@
#define COULD_NOT_ACCESS_DATABASE -9
#define NULL_DATABASE -10
#define WALLETDB_NAME "sgxwallet.db"
#define INVALID_POLY_NAME -11
#define INVALID_DKG_PARAMS -12
#define INVALID_ECDSA_KEY_NAME -20
#define INVALID_HEX -21
#define SGX_ENCLAVE_ERROR -666;
#define WALLETDB_NAME "test_sgxwallet.db"//"sgxwallet.db" //
#define ENCLAVE_NAME "secure_enclave.signed.so"
......
......@@ -98,7 +98,7 @@
{
"name": "generateDKGPoly",
"params": {
"polyName": "key1",
"polyName": "POLY:SCHAIN_ID :NODE_ID :DKG_ID",
"t": 3
},
"returns": {
......@@ -139,7 +139,7 @@
"name": "DKGVerification",
"params": {
"publicShares": "123",
"EthKeyName":"key_j",
"EthKeyName":"NEK:hex",
"SecretShare": "f_ij",
"n": 3,
"t": 3,
......@@ -154,9 +154,9 @@
{
"name": "CreateBLSPrivateKey",
"params": {
"BLSKeyName": "key",
"EthKeyName":"key1",
"polyName":"p1",
"BLSKeyName": "BLS_KEY:SCHAIN_ID :NODE_ID :DKG_ID: ",
"EthKeyName":"NEK:hex",
"polyName":"POLY:SCHAIN_ID :NODE_ID :DKG_ID: ",
"SecretShare": "122",
"n": 3,
"t": 3
......@@ -171,12 +171,12 @@
{
"name": "GetBLSPublicKeyShare",
"params": {
"BLSKeyName": "key"
"BLSKeyName": "BLS_KEY:SCHAIN_ID :NODE_ID :DKG_ID"
},
"returns": {
"status": 0,
"errorMessage": "12345",
"BLSPublicKeyShare": "123"
"BLSPublicKeyShare": []
}
},
......
......@@ -12,7 +12,7 @@ class StubClient : public jsonrpc::Client
public:
StubClient(jsonrpc::IClientConnector &conn, jsonrpc::clientVersion_t type = jsonrpc::JSONRPC_CLIENT_V2) : jsonrpc::Client(conn, type) {}
Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t) throw (jsonrpc::JsonRpcException)
Json::Value importBLSKeyShare(const std::string& keyShare, const std::string& keyShareName, int n, int t, int index) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["index"] = index;
......@@ -26,7 +26,7 @@ class StubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int signerIndex, int t) throw (jsonrpc::JsonRpcException)
Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int t, int signerIndex) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["keyShareName"] = keyShareName;
......@@ -173,6 +173,18 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value ComplaintResponse(const std::string& polyName, int ind) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["polyName"] = polyName;
p["ind"] = ind;
Json::Value result = this->CallMethod("ComplaintResponse",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
};
#endif //JSONRPC_CPP_STUB_STUBCLIENT_H_
This diff is collapsed.
......@@ -13,6 +13,8 @@
#include <sgx_tgmp.h>
namespace libff {
template<mp_size_t n> class bigint;
......
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