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}
......@@ -29,17 +29,24 @@
#include "SGXWalletServer.h"
#include "SGXWalletServer.hpp"
#include "ServerDataChecker.h"
#include <algorithm>
#include <stdlib.h>
//#if __cplusplus < 201412L
//#error expecting C++17 standard
//#endif
#include <boost/filesystem.hpp>
bool isStringDec( std::string & str){
auto res = std::find_if_not(str.begin(), str.end(), [](char c)->bool{
return std::isdigit(c);
});
return !str.empty() && res == str.end();
// bool res =tr
// for (int i = 0; i < str.length; i++){
// }
}
SGXWalletServer::SGXWalletServer(AbstractServerConnector &connector,
......@@ -51,7 +58,25 @@ SGXWalletServer::SGXWalletServer(AbstractServerConnector &connector,
int init_server() {
hs = new HttpServer(1025);
std::string certPath = "cert/SGXServerCertificate.crt";
std::string keyPath = "cert/SGXServerCertificate.key";
if (!boost::filesystem::exists(certPath) ){
std::cerr << "NO!!! " << std::endl;
std::cerr << "CERTIFICATE IS GOING TO BE CREATED" << std::endl;
std::string genCert = "cd cert && ./self-signed-tls -c=US -s=California -l=San-Francisco -o=\"Skale Labs\" -u=\"Department of Software Engineering\" -n=\"SGXServerCertificate\" -e=info@skalelabs.com";
if (system(genCert.c_str()) == 0){
std::cerr << "CERTIFICATE IS SUCCESSFULLY GENERATED" << std::endl;
}
else{
std::cerr << "CERTIFICATE GENERATION FAILED" << std::endl;
exit(-1);
}
}
hs = new HttpServer(1026, certPath, keyPath);
s = new SGXWalletServer(*hs,
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
......@@ -63,7 +88,7 @@ int init_server() {
}
Json::Value
importBLSKeyShareImpl(int index, const std::string &_keyShare, const std::string &_keyShareName, int n, int t) {
importBLSKeyShareImpl(const std::string &_keyShare, const std::string &_keyShareName, int n, int t, int index) {
Json::Value result;
int errStatus = UNKNOWN_ERROR;
......@@ -75,7 +100,9 @@ importBLSKeyShareImpl(int index, const std::string &_keyShare, const std::string
result["encryptedKeyShare"] = "";
try {
// if ( !checkName(_keyShare, "BLS_KEY")){
// throw RPCException(INVALID_POLY_NAME, "Invalid BLSKey name");
// }
char *encryptedKeyShareHex = encryptBLSKeyShare2Hex(&errStatus, errMsg, _keyShare.c_str());
if (encryptedKeyShareHex == nullptr) {
......@@ -115,7 +142,11 @@ Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::s
try {
value = readKeyShare(keyShareName);
if ( !checkName(keyShareName, "BLS_KEY")){
throw RPCException(INVALID_POLY_NAME, "Invalid BLSKey name");
}
value = readFromDb(keyShareName);
} catch (RPCException _e) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
......@@ -170,11 +201,16 @@ Json::Value generateECDSAKeyImpl() {
try {
keys = gen_ecdsa_key();
if (keys.size() == 0 ) {
throw RPCException(UNKNOWN_ERROR, "");
throw RPCException(UNKNOWN_ERROR, "key was not generated");
}
// std::cerr << "write encr key" << keys.at(0) << std::endl;
std::string keyName = "tmp_NEK:" + keys.at(2);
std::string keyName = "NEK:" + keys.at(2);
std::cerr << "keyname length is " << keyName.length() << std::endl;
std::cerr <<"key name generated: " << keyName << std::endl;
//writeECDSAKey(keyName, keys.at(0));
writeDataToDB(keyName, keys.at(0));
......@@ -247,18 +283,32 @@ Json::Value ecdsaSignMessageHashImpl(int base, const std::string &_keyName, cons
}
std::cerr << "Hash handled " << cutHash << std::endl;
try {
if ( !checkECDSAKeyName(_keyName)){
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
if ( !checkHex(cutHash)){
throw RPCException(INVALID_HEX, "Invalid hash");
}
if ( base <= 0 || base > 32){
throw RPCException(-22, "Invalid base");
}
std::shared_ptr<std::string> key_ptr = readFromDb(_keyName,"");
// std::cerr << "read encr key" << *key_ptr << std::endl;
sign_vect = ecdsa_sign_hash(key_ptr->c_str(),cutHash.c_str(), base);
std::cerr << "got signature_s " << sign_vect.at(2) << std::endl;
result["signature_v"] = sign_vect.at(0);
result["signature_r"] = sign_vect.at(1);
result["signature_s"] = sign_vect.at(2);
} catch (RPCException &_e) {
std::cerr << "err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
std::cerr << "got signature_s " << sign_vect.at(2) << std::endl;
result["signature_v"] = sign_vect.at(0);
result["signature_r"] = sign_vect.at(1);
result["signature_s"] = sign_vect.at(2);
return result;
}
......@@ -275,14 +325,18 @@ Json::Value getPublicECDSAKeyImpl(const std::string& keyName){
std::string Pkey;
try {
std::shared_ptr<std::string> key_ptr = readFromDb(keyName,"");
if ( !checkECDSAKeyName(keyName)){
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
std::shared_ptr<std::string> key_ptr = readFromDb(keyName);
Pkey = get_ecdsa_pubkey( key_ptr->c_str());
std::cerr << "PublicKey" << Pkey << std::endl;
result["PublicKey"] = Pkey;
} catch (RPCException &_e) {
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
std::cerr << "PublicKey" << Pkey << std::endl;
result["PublicKey"] = Pkey;
//std::cerr << "in SGXWalletServer encr key x " << keys.at(0) << std::endl;
......@@ -299,15 +353,23 @@ Json::Value generateDKGPolyImpl(const std::string& polyName, int t) {
std::string encrPolyHex;
try {
if ( !checkPolyName(polyName)){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
if ( t <= 0){
throw RPCException(INVALID_DKG_PARAMS, "Invalid parameters: n or t ");
}
encrPolyHex = gen_dkg_poly(t);
writeDKGPoly(polyName, encrPolyHex);
writeDataToDB(polyName, encrPolyHex);
//writeDKGPoly(polyName, encrPolyHex);
//result["encryptedPoly"] = encrPolyHex;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
//result["encryptedPoly"] = encrPolyHex;
return result;
}
......@@ -320,10 +382,25 @@ Json::Value getVerificationVectorImpl(const std::string& polyName, int n, int t)
std::vector <std::vector<std::string>> verifVector;
try {
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName, "DKGPoly:");
if ( !checkPolyName(polyName)){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
if( !check_n_t(n, t)){
throw RPCException(INVALID_DKG_PARAMS, "Invalid parameters: n or t ");
}
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName);
verifVector = get_verif_vect(encr_poly_ptr->c_str(), n, t);
std::cerr << "verif vect size " << verifVector.size() << std::endl;
//std::cerr << "verif vect size " << verifVector.size() << std::endl;
for ( int i = 0; i < t; i++){
std::vector<std::string> cur_coef = verifVector.at(i);
for ( int j = 0; j < 4; j++ ){
result["Verification Vector"][i][j] = cur_coef.at(j);
}
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
......@@ -331,14 +408,6 @@ Json::Value getVerificationVectorImpl(const std::string& polyName, int n, int t)
result["Verification Vector"] = "";
}
for ( int i = 0; i < t; i++){
std::vector<std::string> cur_coef = verifVector.at(i);
for ( int j = 0; j < 4; j++ ){
result["Verification Vector"][i][j] = cur_coef.at(j);
}
}
return result;
}
......@@ -353,11 +422,20 @@ Json::Value getSecretShareImpl(const std::string& polyName, const Json::Value& p
result["errorMessage"] = "wrong number of public keys";
return result;
}
if ( !checkPolyName(polyName)){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
if( !check_n_t(n, t)){
throw RPCException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName, "DKGPoly:");
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName);
std::vector<std::string> pubKeys_vect;
for ( int i = 0; i < n ; i++) {
if ( !checkHex(publicKeys[i].asString(), 64)){
throw RPCException(INVALID_HEX, "Invalid public key");
}
pubKeys_vect.push_back(publicKeys[i].asString());
}
......@@ -386,6 +464,17 @@ Json::Value DKGVerificationImpl(const std::string& publicShares, const std::stri
result["result"] = true;
try {
if ( !checkECDSAKeyName(EthKeyName)){
throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
}
if( !check_n_t(n, t) || ind > n || ind < 0){
throw RPCException(INVALID_DKG_PARAMS, "Invalid DKG parameters: n or t ");
}
// if ( !checkHex(SecretShare, SECRET_SHARE_NUM_BYTES)){
// throw RPCException(INVALID_HEX, "Invalid Secret share");
// }
//std::string keyName = polyName + "_" + std::to_string(ind);
//std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(EthKeyName, "");
std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(EthKeyName);
......@@ -409,7 +498,6 @@ Json::Value DKGVerificationImpl(const std::string& publicShares, const std::stri
Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::string& EthKeyName, const std::string& polyName, const std::string & SecretShare, int t, int n){
std::cerr << "CreateBLSPrivateKeyImpl entered" << std::endl;
std::cerr << " enter DKGVerificationImpl" << std::endl;
Json::Value result;
result["status"] = 0;
......@@ -421,11 +509,23 @@ Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::s
result["errorMessage"] = "wrong length of secret shares";
return result;
}
// if ( !checkECDSAKeyName(EthKeyName)){
// throw RPCException(INVALID_ECDSA_KEY_NAME, "Invalid ECDSA key name");
// }
if ( !checkName(polyName, "POLY")){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
if ( !checkName(BLSKeyName, "BLS_KEY")){
throw RPCException(INVALID_POLY_NAME, "Invalid BLS key name");
}
std::vector<std::string> sshares_vect;
//std::cerr << "sshares are " << std::endl;
std::cerr << "sshares are " << SecretShare << std::endl;
char sshares[192 * n + 1];
for ( int i = 0; i < n ; i++){
std::string cur_share = SecretShare.substr(192*i, 192*i + 192);
// if ( !checkHex(SecretShare, SECRET_SHARE_NUM_BYTES)){
// throw RPCException(INVALID_HEX, "Invalid Secret share");
// }
// std::cerr << " share " << i << " is " << cur_share << std::endl;
sshares_vect.push_back(cur_share);
// std::cerr << sshares_vect[i] << " ";
......@@ -443,7 +543,7 @@ Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::s
}
else {
std::cerr << "error " << std::endl;
throw RPCException(-122, "Error while creating BLS key share");
}
for ( int i = 0; i < n; i++){
......@@ -468,9 +568,16 @@ Json::Value GetBLSPublicKeyShareImpl(const std::string & BLSKeyName){
result["errorMessage"] = "";
try {
std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(BLSKeyName, "");
std::string public_key = GetBLSPubKey(encryptedKeyHex_ptr->c_str());
result["BLSPublicKeyShare"] = public_key;
if ( !checkName(BLSKeyName, "BLS_KEY")){
throw RPCException(INVALID_POLY_NAME, "Invalid BLSKey name");
}
std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(BLSKeyName);
std::cerr << "encr_bls_key_share is " << *encryptedKeyHex_ptr << std::endl;
std::cerr << "length is " << encryptedKeyHex_ptr->length()<< std::endl;
std::vector<std::string> public_key_vect = GetBLSPubKey(encryptedKeyHex_ptr->c_str());
for ( uint8_t i = 0; i < 4; i++) {
result["BLSPublicKeyShare"][i] = public_key_vect.at(i);
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
......@@ -481,16 +588,21 @@ Json::Value GetBLSPublicKeyShareImpl(const std::string & BLSKeyName){
return result;
}
Json::Value ComplaintResponseImpl(const std::string& polyName, int n, int t, int ind){
Json::Value ComplaintResponseImpl(const std::string& polyName, int ind){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName, "DKGPoly:");
std::pair<std::string, std::string> response = response_to_complaint(polyName, encr_poly_ptr->c_str(), n, t, ind);
if ( !checkName(polyName, "POLY")){
throw RPCException(INVALID_POLY_NAME, "Invalid polynomial name");
}
std::string shareG2_name = "shareG2_" + polyName + "_" + std::to_string(ind) + ":";
std::shared_ptr<std::string> shareG2_ptr = readFromDb(shareG2_name);
result["share*G2"] = response.second;
result["DHKey"] = response.first;
std::string DHKey = decrypt_DHKey(polyName, ind);
result["share*G2"] = *shareG2_ptr;
result["DHKey"] = DHKey;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
......@@ -561,10 +673,10 @@ Json::Value SGXWalletServer::ecdsaSignMessageHash(int base, const std::string &_
Json::Value
SGXWalletServer::importBLSKeyShare(int index, const std::string &_keyShare, const std::string &_keyShareName, int n,
int t) {
SGXWalletServer::importBLSKeyShare(const std::string &_keyShare, const std::string &_keyShareName, int n,
int t, int index) {
lock_guard<recursive_mutex> lock(m);
return importBLSKeyShareImpl(index, _keyShare, _keyShareName, n, t);
return importBLSKeyShareImpl(_keyShare, _keyShareName, n, t, index );
}
Json::Value SGXWalletServer::blsSignMessageHash(const std::string &keyShareName, const std::string &messageHash,int n,
......@@ -578,9 +690,9 @@ Json::Value SGXWalletServer::importECDSAKey(const std::string &key, const std::s
return importECDSAKeyImpl(key, keyName);
}
Json::Value SGXWalletServer::ComplaintResponse(const std::string& polyName, int n, int t, int ind){
Json::Value SGXWalletServer::ComplaintResponse(const std::string& polyName, int ind){
lock_guard<recursive_mutex> lock(m);
return ComplaintResponseImpl(polyName, n, t, ind);
return ComplaintResponseImpl(polyName, ind);
}
......@@ -622,54 +734,12 @@ void writeKeyShare(const string &_keyShareName, const string &value, int index,
auto key = "BLSKEYSHARE:" + _keyShareName;
if (levelDb->readString(_keyShareName) != nullptr) {
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
}
levelDb->writeString(key, value);
}
shared_ptr <std::string> readECDSAKey(const string &_keyName) {
auto keyStr = levelDb->readString("ECDSAKEY:" + _keyName);
if (keyStr == nullptr) {
throw RPCException(KEY_SHARE_DOES_NOT_EXIST, "Key with this name does not exists");
}
return keyStr;
}
void writeECDSAKey(const string &_keyName, const string &value) {
Json::Value val;
Json::FastWriter writer;
val["value"] = value;
std::string json = writer.write(val);
auto key = "ECDSAKEY:" + _keyName;
if (levelDb->readString(_keyName) != nullptr) {
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Key with this name already exists");
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
}
levelDb->writeString(key, value);
}
void writeDKGPoly(const string &_polyName, const string &value) {
Json::Value val;
Json::FastWriter writer;
val["value"] = value;
std::string json = writer.write(val);
auto key = "DKGPoly:" + _polyName;
if (levelDb->readString(_polyName) != nullptr) {
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Poly with this name already exists");
}
levelDb->writeString(key, value);
}
void writeDataToDB(const string & Name, const string &value) {
Json::Value val;
Json::FastWriter writer;
......@@ -681,7 +751,7 @@ void writeDataToDB(const string & Name, const string &value) {
if (levelDb->readString(Name) != nullptr) {
std::cerr << "name " << Name << " already exists" << std::endl;
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
throw RPCException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
}
levelDb->writeString(key, value);
......
......@@ -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
......@@ -183,6 +183,7 @@ void generate_ecdsa_key(int *err_status, char *err_string,
sgx_status_t status = sgx_seal_data(0, NULL, ECDSA_SKEY_LEN, (uint8_t *)skey_str, sealedLen,(sgx_sealed_data_t*)encrypted_key);
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"seal ecsdsa private key failed");
*err_status = status;
return;
}
......@@ -209,6 +210,7 @@ void get_public_ecdsa_key(int *err_status, char *err_string,
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
*err_status = status;
return;
}
......@@ -219,6 +221,7 @@ void get_public_ecdsa_key(int *err_status, char *err_string,
// mpz_import(skey_mpz, 32, 1, sizeof(skey[0]), 0, 0, skey);
if (mpz_set_str(skey_mpz, skey, ECDSA_SKEY_BASE) == -1){
snprintf(err_string, BUF_LEN,"wrong string to init private key");
*err_status = -10;
}
//Public key
......@@ -231,6 +234,7 @@ void get_public_ecdsa_key(int *err_status, char *err_string,
if (!point_cmp(Pkey, Pkey_test)){
snprintf(err_string, BUF_LEN,"Points are not equal");
*err_status = -11;
}
int base = 16;
......@@ -264,7 +268,7 @@ void get_public_ecdsa_key(int *err_status, char *err_string,
void encrypt_key(int *err_status, char *err_string, char *key,
uint8_t *encrypted_key, uint32_t *enc_len) {
init();
//init();
*err_status = UNKNOWN_ERROR;
......@@ -290,10 +294,10 @@ void encrypt_key(int *err_status, char *err_string, char *key,
memset(encrypted_key, 0, BUF_LEN);
if (sgx_seal_data(0, NULL, MAX_KEY_LENGTH, (uint8_t *) key, sealedLen, (sgx_sealed_data_t *) encrypted_key) !=
SGX_SUCCESS) {
sgx_status_t status = sgx_seal_data(0, NULL, MAX_KEY_LENGTH, (uint8_t *) key, sealedLen, (sgx_sealed_data_t *) encrypted_key);
if ( status != SGX_SUCCESS) {
*err_status = SEAL_KEY_FAILED;
snprintf(err_string, BUF_LEN, "SGX seal data failed");
snprintf(err_string, BUF_LEN, "SGX seal data failed with status %d", status);
return;
}
......@@ -332,7 +336,6 @@ void decrypt_key(int *err_status, char *err_string, uint8_t *encrypted_key,
init();
uint32_t decLen;
*err_status = -9;
......@@ -345,9 +348,10 @@ void decrypt_key(int *err_status, char *err_string, uint8_t *encrypted_key,
return;
}
//snprintf(err_string, BUF_LEN, "decr key is %s", key);
if (decLen != MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "decLen != MAX_KEY_LENGTH");
if (decLen > MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "wrong decLen");//"decLen != MAX_KEY_LENGTH");
return;
}
......@@ -364,12 +368,14 @@ void decrypt_key(int *err_status, char *err_string, uint8_t *encrypted_key,
// check that key is padded with 0s
for (int i = keyLen; i < MAX_KEY_LENGTH; i++) {
if (key[i] != 0) {
snprintf(err_string, BUF_LEN, "Unpadded key");
return;
}
}
// for (int i = keyLen; i < MAX_KEY_LENGTH; i++) {
// if (key[i] != 0) {
// snprintf(err_string, BUF_LEN, "Unpadded key");
// return;
// }
// }
//strncpy(key, "2f993bb09f16c402a27dae868c02791bca7fcf564f1c9e2ba50b142b843a4b60", BUF_LEN);
*err_status = 0;
return;
......@@ -392,6 +398,7 @@ void bls_sign_message(int *err_status, char *err_string, uint8_t *encrypted_key,
decrypt_key(err_status, err_string, encrypted_key, enc_len, key);
if (*err_status != 0) {
strncpy(signature, err_string, BUF_LEN);
return;
}
......@@ -435,7 +442,7 @@ void decrypt_dkg_secret (int *err_status, char* err_string, uint8_t* encrypted_d
(const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, decrypted_dkg_secret, &decr_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_dkg_secret failed with status %d", status);
return;
}
......@@ -455,7 +462,7 @@ void get_secret_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg
// (const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, (uint8_t*)decrypted_dkg_secret, &decr_len);
if (*err_status != 0) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", *err_status);
snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_dkg_secret failed with status %d", *err_status);
return;
}
......@@ -493,7 +500,7 @@ void ecdsa_sign1(int *err_status, char *err_string, uint8_t *encrypted_key, uint
(const sgx_sealed_data_t *)encrypted_key, NULL, 0, skey, &dec_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed - encrypted_key with status %d", status);
return;
}
......@@ -561,14 +568,14 @@ void set_encrypted_dkg_poly(int *err_status, char *err_string, uint8_t* encrypte
(const sgx_sealed_data_t *)encrypted_poly, NULL, 0, Decrypted_dkg_poly, &decr_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_poly failed with status %d", status);
return;
}
}
void get_encr_sshare(int *err_status, char *err_string, uint8_t *encrypted_skey, uint32_t* dec_len,
char* result_str, char* pub_keyB, uint8_t _t, uint8_t _n, uint8_t ind ){
char* result_str, char * s_shareG2, char* pub_keyB, uint8_t _t, uint8_t _n, uint8_t ind ){
char skey[ECDSA_SKEY_LEN];
char *pub_key_x = (char *)calloc(1024, 1);
......@@ -579,11 +586,13 @@ void get_encr_sshare(int *err_status, char *err_string, uint8_t *encrypted_skey,
generate_ecdsa_key(err_status, err_string, encrypted_skey, &enc_len, pub_key_x, pub_key_y);
// snprintf(err_string, BUF_LEN,"pub_key_x is %s", pub_key_x);
*dec_len = enc_len;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_skey, NULL, 0, (uint8_t *)skey, &enc_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed - encrypted_skey with status %d", status);
return;
}
snprintf(err_string, BUF_LEN,"unsealed random skey is %s\n", skey);
......@@ -599,6 +608,8 @@ void get_encr_sshare(int *err_status, char *err_string, uint8_t *encrypted_skey,
calc_secret_share(Decrypted_dkg_poly, s_share, _t, _n, ind);
snprintf(err_string + 88, BUF_LEN,"\nsecret share is %s", s_share);
calc_secret_shareG2(s_share, s_shareG2);
char* cypher = (char *)malloc(65);
xor_encrypt(common_key, s_share, cypher);
//snprintf(err_string, BUF_LEN ,"cypher is %s length is %d", cypher, strlen(cypher));
......@@ -623,22 +634,27 @@ void complaint_response(int *err_status, char *err_string, uint8_t *encrypted_DH
uint32_t enc_len;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_DHkey, NULL, 0, (uint8_t *)DH_key, &enc_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
// sgx_status_t status = sgx_unseal_data(
// (const sgx_sealed_data_t *)encrypted_DHkey, NULL, 0, (uint8_t *)DH_key, &enc_len);
// if (status != SGX_SUCCESS) {
// snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_DHkey failed with status %d", status);
// return;
// }
char* decrypted_dkg_secret = (char*)malloc(DKG_BUFER_LENGTH);
uint32_t decr_len;
decrypt_dkg_secret(err_status, err_string, encrypted_dkg_secret, (uint8_t*)decrypted_dkg_secret, &decr_len);
if (*err_status != 0) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", *err_status);
snprintf(err_string, BUF_LEN,"sgx_unseal_data - encrypted_dkg_secret failed with status %d", *err_status);
return;
}
calc_secret_shareG2(decrypted_dkg_secret, s_shareG2, _t, ind1);
calc_secret_shareG2_old(decrypted_dkg_secret, s_shareG2, _t, ind1);
//snprintf(err_string, BUF_LEN,"poly:%s", decrypted_dkg_secret);
// snprintf(err_string, BUF_LEN,"what the ...");
//snprintf(err_string, BUF_LEN,"s_shareG2:%s", s_shareG2);
free(decrypted_dkg_secret);
}
......@@ -686,7 +702,7 @@ void dkg_verification(int *err_status, char* err_string, const char * public_sha
}
void create_bls_key(int *err_status, char* err_string, const char* s_shares,
uint8_t* encrypted_key, uint64_t key_len, uint8_t * encr_bls_key){
uint8_t* encrypted_key, uint64_t key_len, uint8_t * encr_bls_key, uint32_t *enc_bls_key_len){
//uint32_t dec_len = 625;
char skey[ECDSA_SKEY_LEN];
......@@ -762,18 +778,19 @@ void create_bls_key(int *err_status, char* err_string, const char* s_shares,
mpz_mod(bls_key, sum, q);
char key_share[mpz_sizeinbase(bls_key, 10) + 2];
char *key = mpz_get_str(key_share, 10, bls_key);
char key_share[mpz_sizeinbase(bls_key, 16) + 2];
char *key = mpz_get_str(key_share, 16, bls_key);
snprintf(err_string, BUF_LEN,"bls private key is %s", key_share);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, ECDSA_SKEY_LEN);
status = sgx_seal_data(0, NULL, ECDSA_SKEY_LEN, (uint8_t *)key_share, sealedLen,(sgx_sealed_data_t*)encr_bls_key);
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"seal bls private key failed with status %d ", status);
return;
}
*enc_bls_key_len = sealedLen;
//snprintf(err_string, BUF_LEN,"sshare is %s", decr_sshare);
//snprintf(err_string, BUF_LEN,"encr_share is %s", encr_sshare);
//snprintf(err_string, BUF_LEN,"common_key is %s", common_key);
......@@ -793,18 +810,18 @@ void create_bls_key(int *err_status, char* err_string, const char* s_shares,
void get_bls_pub_key(int *err_status, char* err_string, uint8_t* encrypted_key, uint64_t key_len, char* bls_pub_key){
char skey[ECDSA_SKEY_LEN];
char skey_hex[ECDSA_SKEY_LEN];
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_key, NULL, 0, (uint8_t *)skey, &key_len);
uint32_t len = key_len;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_key, NULL, 0, (uint8_t *)skey_hex, &len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
calc_bls_public_key(skey, bls_pub_key);
calc_bls_public_key(skey_hex, bls_pub_key);
}
......
......@@ -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_
......@@ -172,7 +172,7 @@ TEST_CASE("BLS key import", "[bls-key-import]") {
auto result = importBLSKeyShareImpl(1, TEST_BLS_KEY_SHARE, TEST_BLS_KEY_NAME, 2, 2);
auto result = importBLSKeyShareImpl(TEST_BLS_KEY_SHARE, TEST_BLS_KEY_NAME, 2, 2, 1);
REQUIRE(result["status"] == 0);
......@@ -212,7 +212,7 @@ TEST_CASE("Server BLS sign test", "[bls-server-sign]") {
init_all();
auto result = importBLSKeyShareImpl(1, TEST_BLS_KEY_SHARE, TEST_BLS_KEY_NAME, 2, 2);
auto result = importBLSKeyShareImpl( TEST_BLS_KEY_SHARE, TEST_BLS_KEY_NAME, 2, 2, 1);
REQUIRE(result["status"] == 0);
......@@ -524,8 +524,8 @@ TEST_CASE( "DKG encrypted secret shares test", "[dkg-encr_sshares]" ) {
char *pub_key_y = (char *)calloc(1024, 1);
char *pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
status = get_encr_sshare(eid, &err_status, errMsg, encr_pr_DHkey, &enc_len, result,
char s_shareG2[320];
status = get_encr_sshare(eid, &err_status, errMsg, encr_pr_DHkey, &enc_len, result, s_shareG2,
pub_keyB, 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg);
......@@ -563,7 +563,8 @@ TEST_CASE( "DKG verification test", "[dkg-verify]" ) {
char *pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
status = get_encr_sshare(eid, &err_status, errMsg, encr_pr_DHkey, &enc_len, result,
char s_shareG2[320];
status = get_encr_sshare(eid, &err_status, errMsg, encr_pr_DHkey, &enc_len, result, s_shareG2,
pub_keyB, 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg);
......@@ -700,13 +701,51 @@ TEST_CASE("get public ECDSA key", "[get_pub_ecdsa_key_test]") {
}*/
TEST_CASE( "pub_bls_key", "[pub_bls]" ) {
init_daemon();
init_enclave();
char *encryptedKeyHex =
"04000200000000000406ffffff02000000000000000000000b000000000000ff0000000000000000813f8390f6228a568e181a4dadb6508e3e66f5247175d65dbd0d8c7fbfa4df45000000f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000008000000000000000000000000000000000dc044ae0cd79faaf41e8a7abb412790476738a98b5b6ce95fa1a32db5551b0a0d867305f4de558c64fee730a1f62394633c7d4ca65e3a40b7883e89c2801c61918b01c5de8624a52963df6f4de8581bcbdd2f9b69720d4cc764e03a04c7a99314bfdb5d2d55deda2ca40cd691f093fb2ecbae24cdacdd4d5de93189c6dfd6792d7b95bd5e330aec3538e7a85d15793"; // encryptTestKey();
//writeDataToDB("test_bls_key0", encryptedKeyHex);
std::vector<std::string> result = GetBLSPubKey(encryptedKeyHex);
//std::cerr << "pub key " << result << std::endl;
sgx_destroy_enclave(eid);
}
#include "stubclient.h"
#include <jsonrpccpp/client/connectors/httpclient.h>
using namespace jsonrpc;
using namespace std;
TEST_CASE("BLS_DKG test", "[bls_dkg]") {
init_all();
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1026");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
int n = 2, t = 2;
Json::Value EthKeys[n];
Json::Value Polys[n];
Json::Value VerifVects[n];
Json::Value pubEthKeys;
for ( uint8_t i = 0; i < n; i++){
EthKeys[i] = c.generateECDSAKey();
std::string polyName = "POLY:SCHAIN_ID:1:NODE_ID:" + std::to_string(i) + ":DKG_ID:0";
Polys[i] = c.generateDKGPoly(polyName, t);
VerifVects[i] = c.getVerificationVector(polyName, n, t);
pubEthKeys.append(EthKeys[i]["PublicKey"]);
}
}
TEST_CASE("API test", "[api_test]") {
std::cerr << __GNUC__ << std::endl;
cerr << "API test started" << endl;
init_all();
//HttpServer httpserver(1025);
......@@ -714,7 +753,7 @@ TEST_CASE("API test", "[api_test]") {
// JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
// s.StartListening();
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1025");
HttpClient client("http://localhost:1026");
StubClient c(client, JSONRPC_CLIENT_V2);
cerr << "Client inited" << endl;
......@@ -722,17 +761,29 @@ TEST_CASE("API test", "[api_test]") {
try {
//levelDb->deleteOlegKey("0");
//levelDb->deleteOlegKey("1");
levelDb->deleteDHDKGKey("p2_0:");
levelDb->deleteDHDKGKey("p2_1:");
// levelDb->deleteDHDKGKey("p2_0:");
//levelDb->deleteDHDKGKey("p2_1:");
for ( uint8_t i = 0; i < 2; i++) {
levelDb->deleteKey("POLY:SCHAIN_ID:0:NODE_ID:" + std::to_string(i) +
":DKG_ID:0");
levelDb->deleteKey(" DKG_DH_KEY_POLY:SCHAIN_ID:0:NODE_ID:" + std::to_string(i)+ ":DKG_ID:0_0");
levelDb->deleteKey(" DKG_DH_KEY_POLY:SCHAIN_ID:0:NODE_ID:" + std::to_string(i)+ ":DKG_ID:0_1");
}
//cout << c.generateECDSAKey() << endl;
cout << c.importBLSKeyShare("4160780231445160889237664391382223604184857153814275770598791864649971919844","BLS_KEY:SCHAIN_ID:2660016693368503500803087136248943520694587309641817:NODE_ID:33909:DKG_ID:3522960548719023733985054069487289468077787284706573", 4, 3,1);
// cout << c.generateECDSAKey() << endl;
// cout << c.renameESDSAKey("NODE_1CHAIN_1","tmp_NEK:bcacde0d26c0ea2c7e649992e7f791e1fba2492f5b7ae63dadb799075167c7fc");
//cout<<c.getPublicECDSAKey("test_key1");
// cout<<c.getPublicECDSAKey("NEK:697fadfc597bdbfae9ffb7412b80939e848c9c2fec2657bb2122b6d0d4a0dca8");
//cout << c.ecdsaSignMessageHash(16, "NEK:697fadfc597bdbfae9ffb7412b80939e848c9c2fec2657bb2122b6d0d4a0dca8","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
//cout << c.ecdsaSignMessageHash(16, "known_key1","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
// cout << c.blsSignMessageHash(TEST_BLS_KEY_NAME, "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db", 2,2,1 );
// cout << c.generateDKGPoly("p2", 2);
//cout << c.getVerificationVector("polyy", 5, 5);
// cout << c.generateDKGPoly("pp2", 2);
// cout << c.generateDKGPoly("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", 2);
//cout << c.getVerificationVector("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:2", 2, 2);
// cout << c.getVerificationVector("polyy", 5, 5);
// cout << c.getSecretShare("p2",
// "505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e232d69c361f0bc9e05f1cf8ef387122dc1d2f7cee7b6cda3537fc9427c02328b01f02fd94ec933134dc795a642864f8cb41ae263e11abaf992e21fcf9be732deb",
......@@ -744,8 +795,8 @@ TEST_CASE("API test", "[api_test]") {
Json::Value publicKeys;
publicKeys.append("505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e2");
publicKeys.append("378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25e6e");
cout << c.getSecretShare("p2", publicKeys, 2, 2);
publicKeys.append("378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25");
// cout << c.getSecretShare("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", publicKeys, 2, 2);
// cout << c.generateDKGPoly("p3", 3);
// cout << c.getSecretShare("p3",
// "669aa790e1c5f5199af82ab0b6f1965c382d23a2ebdda581454adba3fd082a30edab62b545f78f1e402ceef7340a0364a7046633d6151fe7e657d8b8a6352378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25e6e9d43f1c88581f53af993da1654c9f91829c1fe5344c4452ef8d2d8675c6a051c19029f6e4f82b035fb3552058cf22c5bbafd9e6456d579634987281765d130b0",
......@@ -770,12 +821,21 @@ TEST_CASE("API test", "[api_test]") {
// std::string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76df831dbef474cfc38be1c980130a8d273ff410fbf87deece9d7756a1b08ba9e954c1676cc7f2cac16e16cff0c877d8cf967381321fb4cc78e3638245a1dc85419766d281aff4935cc6eac25c9842032c8f7fae567c57622969599a72c42d2e1e";
std::string shares = "252122c309ed1f32faa897ede140c5b9c1bc07d5d9c94b7a22d4eeb13da7b7142aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b7637092c06c423b627c38ff86d1e66608bdc1496ef855b86e9f773441ac0b285d92aa466376a6008de4aab9858aa34848775282c4c3b56370bf25827321619c6e47701c8a32e3f4bb28f5a3b12a09800f318c550cedff6150e9a673ea56ece8b76";
// cout << c.CreateBLSPrivateKey( "test_bls","key0", "oleh1", shares, 2, 2 );
//cout << c.CreateBLSPrivateKey( "test_bls1","key0", "oleh1", shares, 2, 2 );
// cout << c.GetBLSPublicKeyShare("test_bls_key");
//cout << c.GetBLSPublicKeyShare("test_bls_key0");
std::string s_share = "13b871ad5025fed10a41388265b19886e78f449f758fe8642ade51440fcf850bb2083f87227d8fb53fdfb2854e2d0abec4f47e2197b821b564413af96124cd84a8700f8eb9ed03161888c9ef58d6e5896403de3608e634e23e92fba041aa283484427d0e6de20922216c65865cfe26edd2cf9cbfc3116d007710e8d82feafd9135c497bef0c800ca310ba6044763572681510dad5e043ebd87ffaa1a4cd45a899222207f3d05dec8110d132ad34c62d6a3b40bf8e9f40f875125c3035062d2ca";
std::string EthKeyName = "tmp_NEK:8abc8e8280fb060988b65da4b8cb00779a1e816ec42f8a40ae2daa520e484a01";
//cout << c.CreateBLSPrivateKey( "test_blskey", EthKeyName, "JCGMt", s_share, 2, 2 );
//cout << c.GetBLSPublicKeyShare("test_blskey");
// cout << c.blsSignMessageHash("dOsRY","38433e5ce087dcc1be82fcc834eae83c256b3db87d34f84440d0b708daa0c6f7", 2, 2, 1);
// cout << c.ComplaintResponse("POLY:SCHAIN_ID:1:NODE_ID:1:DKG_ID:1", 0);
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
}
sgx_destroy_enclave(eid);
}
......@@ -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