Unverified Commit bb63afeb authored by svetaro's avatar svetaro

SKALE-1512-add-DKG-to-SGX Changes

parent 20cd98f5
......@@ -2,3 +2,29 @@
// Created by kladko on 10/3/19.
//
#include "DKGCrypto.h"
#include "BLSCrypto.h"
#include "sgxwallet.h"
#include <iostream>
std::string gen_dkg_poly( int _t){
char *errMsg = (char *)calloc(1024, 1);
int err_status = 0;
uint8_t* encrypted_dkg_secret = (uint8_t *)calloc(2000, 1);
uint32_t enc_len = 0;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, _t);
char *hexEncrPoly = (char *) calloc(4*BUF_LEN, 1);
carray2Hex(encrypted_dkg_secret, enc_len, hexEncrPoly);
std::string result(hexEncrPoly);
//std::cerr << "in DKGCrypto encr key x " << << std::endl;
free(errMsg);
free(encrypted_dkg_secret);
free(hexEncrPoly);
return result;
}
\ No newline at end of file
......@@ -5,4 +5,8 @@
#ifndef SGXD_DKGCRYPTO_H
#define SGXD_DKGCRYPTO_H
#include <string>
std::string gen_dkg_poly( int _t);
#endif //SGXD_DKGCRYPTO_H
......@@ -65,7 +65,8 @@ bin_PROGRAMS = sgxwallet testw
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 ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp $(COMMON_SRC)
sgxwallet_SOURCES = sgxwallet.c SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp $(COMMON_SRC)
nodist_sgxwallet_SOURCES = $(COMMON_ENCLAVE_SRC)
......@@ -97,7 +98,7 @@ sgxwallet_LDADD=-l$(SGX_URTS_LIB) -Lleveldb/build -LlibBLS/build -LlibBLS/build
testw_SOURCES=testw.cpp stubclient.cpp SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ServerInit.cpp LevelDB.cpp \
BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp $(COMMON_SRC)
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp $(COMMON_SRC)
nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
......@@ -24,6 +24,8 @@
#include "LevelDB.h"
#include "BLSCrypto.h"
#include "ECDSACrypto.h"
#include "DKGCrypto.h"
#include "SGXWalletServer.h"
#include "SGXWalletServer.hpp"
......@@ -232,12 +234,39 @@ Json::Value getPublicECDSAKeyImpl(const std::string& keyName){
std::cerr << "PublicKey" << Pkey << std::endl;
result["PublicKey"] = Pkey;
//std::cerr << "in SGXWalletServer encr key x " << keys.at(0) << std::endl;
return result;
}
Json::Value generateDKGPolyImpl(const std::string& polyName, int t) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
//result["encryptedPoly"] = "";
std::string encrPolyHex;
try {
encrPolyHex = gen_dkg_poly(t);
writeDKGPoly(polyName, 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;
}
Json::Value SGXWalletServer::generateDKGPoly(const std::string& polyName, int t){
return generateDKGPolyImpl(polyName, t);
}
Json::Value SGXWalletServer::generateECDSAKey(const std::string &_keyName) {
return generateECDSAKeyImpl(_keyName);
}
......@@ -296,7 +325,7 @@ void writeKeyShare(const string &_keyShareName, const string &value, int index,
auto key = "BLSKEYSHARE:" + _keyShareName;
if (levelDb->readString(_keyShareName) != nullptr) {
throw new RPCException(KEY_SHARE_DOES_NOT_EXIST, "Key share with this name already exists");
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
}
levelDb->writeString(key, value);
......@@ -322,8 +351,24 @@ void writeECDSAKey(const string &_keyName, const string &value) {
auto key = "ECDSAKEY:" + _keyName;
if (levelDb->readString(_keyName) != nullptr) {
throw new RPCException(KEY_SHARE_DOES_NOT_EXIST, "Key with this name already exists");
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Key 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);
}
\ No newline at end of file
......@@ -20,29 +20,35 @@ public:
virtual Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t);
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash);
virtual Json::Value importECDSAKey(const std::string& key, const std::string& keyName);
virtual Json::Value generateECDSAKey(const std::string& keyName);
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyShareName, const std::string& messageHash );
virtual Json::Value getPublicECDSAKey(const std::string& keyName);
virtual Json::Value generateDKGPoly(const std::string& polyName, int t);
};
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 blsSignMessageHashImpl(const std::string& keyShareName, const std::string& messageHash);
Json::Value importECDSAKeyImpl(const std::string& key, const std::string& keyName);
Json::Value generateECDSAKeyImpl(const std::string& keyName);
Json::Value ecdsaSignMessageHashImpl(int base, const std::string& keyName, const std::string& messageHash);
Json::Value getPublicECDSAKeyImpl(const std::string& keyName);
Json::Value generateDKGPolyImpl(const std::string& polyName, int t);
#endif //SGXWALLET_SGXWALLETSERVER_HPP
\ No newline at end of file
......@@ -18,6 +18,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
this->bindAndAddMethod(jsonrpc::Procedure("generateECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::generateECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getPublicECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getPublicECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("ecdsaSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "base",jsonrpc::JSON_INTEGER,"keyName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::ecdsaSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("generateDKGPoly", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::generateDKGPolyI);
}
inline virtual void importBLSKeyShareI(const Json::Value &request, Json::Value &response)
......@@ -44,12 +45,17 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->ecdsaSignMessageHash(request["base"].asInt(), request["keyName"].asString(), request["messageHash"].asString());
}
inline virtual void generateDKGPolyI(const Json::Value &request, Json::Value &response)
{
response = this->generateDKGPoly(request["keyName"].asString(), request["t"].asInt());
}
virtual Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t) = 0;
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash) = 0;
virtual Json::Value importECDSAKey(const std::string& key, const std::string& keyName) = 0;
virtual Json::Value generateECDSAKey(const std::string& keyName) = 0;
virtual Json::Value getPublicECDSAKey(const std::string& keyName) = 0;
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyName, const std::string& messageHash) = 0;
virtual Json::Value generateDKGPoly(const std::string& keyName, int t) = 0;
};
#endif //JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_
......@@ -88,7 +88,8 @@ alt_bn128_init.o: \
../trusted_libff/libff/algebra/fields/fp2.hpp \
../trusted_libff/libff/algebra/fields/fp2.tcc \
../trusted_libff/libff/algebra/curves/curve_utils.hpp \
../trusted_libff/libff/algebra/curves/curve_utils.tcc
../trusted_libff/libff/algebra/curves/curve_utils.tcc \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp:
......@@ -267,3 +268,5 @@ alt_bn128_init.o: \
../trusted_libff/libff/algebra/curves/curve_utils.hpp:
../trusted_libff/libff/algebra/curves/curve_utils.tcc:
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp:
......@@ -27,7 +27,8 @@ secure_enclave.o: secure_enclave.c secure_enclave_t.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdio.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdarg.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h \
domain_parameters.h point.h signature.h curves.h ../sgxwallet_common.h \
domain_parameters.h point.h signature.h curves.h drive_key_dkg.h \
../sgxwallet_common.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/unistd.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/types.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/endian.h
......@@ -98,6 +99,8 @@ signature.h:
curves.h:
drive_key_dkg.h:
../sgxwallet_common.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/unistd.h:
......
......@@ -10,7 +10,7 @@ signature.o: signature.c \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/limits.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/assert.h \
domain_parameters.h point.h signature.h numbertheory.h random.h
domain_parameters.h point.h signature.h numbertheory.h
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdlib.h:
......@@ -41,5 +41,3 @@ point.h:
signature.h:
numbertheory.h:
random.h:
......@@ -111,7 +111,7 @@ void calc_secret_shares(const char* decrypted_koefs, char * secret_shares,
result += ConvertToString(secret_share);//stringFromFr(secret_share);
result += ":";
}
strncpy(secret_shares, result.c_str(), 2000);//result.length());
strncpy(secret_shares, result.c_str(), result.length());
}
void calc_public_shares(const char* decrypted_koefs, char * public_shares,
......@@ -120,7 +120,6 @@ void calc_public_shares(const char* decrypted_koefs, char * public_shares,
std::string result;
char symbol = ':';
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, symbol);
libff::alt_bn128_Fr three = 3;
for (size_t i = 0; i < _t; ++i) {
libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one() ;
pub_share.to_affine_coordinates();
......
## This line must come first when building an Intel SGX enclave.
include $(top_srcdir)/build-aux/sgx_enclave.am
## It sets the following Automake variables:
##
## EXEEXT=.so
## AM_CPPFLAGS = -I$(SGXSDK_INCDIR)
## AM_LDFLAGS = -L$(SGXSDK_LIBDIR)
## libexec_PROGRAMS = $(ENCLAVE)
## CLEANFILES = $(ENCLAVE).signed.so
##
## and places required compiler flags in:
##
## AM_CFLAGS
## AM_CXXFLAGS
##
## It adds a pattern rule for building proxy functions from EDL files:
##
## %_u.h %_u.c: %.edl
##
## And creates build targets for a signed enclave, generating a
## temporary private signing key, and a basic enclave config file:
##
## $(ENCLAVE_CONFIG):
## $(ENCLAVE_KEY):
## $(ENCLAVE).signed$(EXEEXT): $(ENCLAVE)$(EXEEXT)
##
## And sets these Makefile variables:
##
## SGXSDK
## SGXSDK_BINDIR
## SGXSDK_INCDIR
## SGXSDK_LIBDIR
## SGXSSL
## SGXSSL_BINDIR
## SGXSSL_INCDIR
## SGXSSL_LIBDIR
## SGX_TRTS_LIB
## SGX_TSERVICE_LIB
## SGX_EDGER8R
## SGX_SIGN
## The name of your enclave, enclave config file, and private key
## file go in these variables. The ENCLAVE variable creates the
## following automake target defn:
##
## libexec_PROGRAMS=$(ENCLAVE)
ENCLAVE=secure_enclave
ENCLAVE_CONFIG=$(ENCLAVE).config.xml
ENCLAVE_KEY=$(ENCLAVE)_private.pem
## Provide additional flags to sgx_sign when signing the enclave.
## This is almost never necessary. If you don't know if you need
## this, you probably don't.
## SGX_SIGN_FLAGS =
## Additional Automake flags needed to build the enclave.
##
AM_CPPFLAGS += -Wall -Wno-implicit-function-declaration $(TGMP_CPPFLAGS) -I../trusted_libff -I../sgx-sdk-build/sgxsdk/include/libcxx \
-I../intel-sgx-ssl/Linux/package/include
AM_CXXFLAGS += -fno-builtin
## Additional files to remove with 'make clean'. This list needs
## to include your edger8r genreated files.
CLEANFILES+= secure_enclave_t.c secure_enclave_t.h
## Supply additional flags to edger8r here.
##
## SGX_EDGER8R_FLAGS=
## Put your sources here. Don't forget to list the _t.c and _t.h
## files. You can't use the $(ENCLAVE) variable in the build
## target name (i.e., $(ENCLAVE)_SOURCES will not work).
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \
<<<<<<< HEAD
DKGUtils.cpp BLSUtils.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
=======
BLSEnclave.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
>>>>>>> master
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
## Add additional linker flags to AM_LDFLAGS here. Don't put
## libraries flags here (see below).
##
## Be sure to use += to add to, and not replace, the default
## AM_LDFLAGS.
AM_LDFLAGS += $(TGMP_LDFLAGS)
## This line is REQUIRED. It can't be generically defined for
## automake, so you must specify it for your enclave. Note that you
## can't say $(ENCLAVE)_LDADD here: you must spell out the enclave name.
## If you add flags to it, you MUST include @SGX_ENCLAVE_LDADD@ as part
## of the definition to make sure you pick up the right linker flags
## and SGX trusted libraries.
secure_enclave_LDADD = @SGX_ENCLAVE_LDADD@
## Place any additional trusted libraries that your enclave may need in
## SGX_EXTRA_TLIBS. This will ensure they get place inside the
## --startgroup and --endgroup flags. (This would be where you'd add
## SGXSSL libraries, and your trusted c++ library
SGX_EXTRA_TLIBS=-lsgx_tgmp -lsgx_tservice -lsgx_urts -lsgx_tcxx ../intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a
## This line is OPTIONAL, and comes with a WARNING.
##
## In general, you shouldn't need to use the program-specific LDFLAGS
## instead of AM_LDFLAGS. But, if you need to, then you'll need to ensure
## @SGX_ENCLAVE_LDFLAGS@ is included in the definition as this will
## override AM_LDFLAGS.
##
## secure_enclave_LDFLAGS = @SGX_ENCLAVE_LDFLAGS@
##
......@@ -10,12 +10,19 @@
#include "point.h"
#include "numbertheory.h"
void gen_session_keys(mpz_t skey, char* pb_key){
//void gen_session_keys(mpz_t skey, char* pb_keyB){
void gen_session_key(char *skey_str, char* pb_keyB, char* common_key){
char* pb_keyB_x = (char*)malloc(64);
strncpy(pb_keyB_x, pb_keyB, 64);
char* pb_keyB_y = (char*)malloc(64);
strncpy(pb_keyB_y, pb_keyB + 64, 64);
domain_parameters curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
unsigned char* rand_char = (unsigned char*)malloc(32);
/* unsigned char* rand_char = (unsigned char*)malloc(32);
sgx_read_rand( rand_char, 32);
mpz_t seed;
......@@ -33,12 +40,31 @@ void gen_session_keys(mpz_t skey, char* pb_key){
// memcpy(skey, arr, 32);
// strncpy(skey, arr, 1024);
mpz_set(skey, skey_mpz);
mpz_set(skey, skey_mpz);*/
mpz_t skey;
mpz_init(skey);
mpz_set_str(skey, skey_str, 16);
point pub_key = point_init();
point_multiplication(pub_key, skey, curve->G, curve);
point pub_keyB = point_init();
point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y);
mpz_clear(skey_mpz);
point_clear(pub_key);
point session_key = point_init();
point_multiplication(session_key, skey, pub_keyB, curve);
char arr_x[mpz_sizeinbase (session_key->x, 16) + 2];
char* x = mpz_get_str(arr_x, 16, session_key->x);
strncpy(common_key, arr_x, 64);
mpz_clear(skey);
point_clear(pub_keyB);
domain_parameters_clear(curve);
free(pb_keyB_x);
free(pb_keyB_y);
}
void xor_encrypt(char* key, char* message, char* cypher){
for (int i = 0; i < 32; i++){
cypher[i] = message[i] ^ key[i];
}
}
\ No newline at end of file
......@@ -5,8 +5,10 @@
#ifndef SGXD_DRIVE_KEY_DKG_H
#define SGXD_DRIVE_KEY_DKG_H
void gen_session_keys(mpz_t skey, char* pub_key);
//void gen_session_keys(mpz_t skey, char* pub_key);
void gen_session_key(char* skey, char* pub_keyB, char* common_key);
void xor_encrypt(char* key, char* message, char* cypher);
#endif //SGXD_DRIVE_KEY_DKG_H
......@@ -151,7 +151,7 @@ void generate_ecdsa_key(int *err_status, char *err_string,
//mpz_set_str(skey, "4160780231445160889237664391382223604184857153814275770598791864649971919844", 10);
//mpz_set_str(skey, "1", 10);
//mpz_set_str(skey, "ebb2c082fd7727890a28ac82f6bdf97bad8de9f5d7c9028692de1a255cad3e0f", 16);
//mpz_set_str(skey, "D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759", 16);
// mpz_set_str(skey, "D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759", 16);
//Public key
point Pkey = point_init();
......@@ -494,7 +494,6 @@ void ecdsa_sign1(int *err_status, char *err_string, uint8_t *encrypted_key, uint
signature sign = signature_init();
signature_sign( sign, msg_mpz, skey_mpz, curve);
point Pkey = point_init();
......@@ -532,9 +531,9 @@ void ecdsa_sign1(int *err_status, char *err_string, uint8_t *encrypted_key, uint
}
void drive_key(int *err_status, char *err_string, uint8_t *encrypted_skey, uint32_t* enc_len, char* result_str, char* pub_keyB ){
void drive_key(int *err_status, char *err_string, uint8_t *encrypted_skey, uint32_t* dec_len, char* result_str, char* pub_keyB ){
//char* skey = (char*)malloc(1024);
/* //char* skey = (char*)malloc(1024);
char* pub_key = (char*)malloc(1024);
mpz_t skey;
......@@ -550,7 +549,7 @@ void drive_key(int *err_status, char *err_string, uint8_t *encrypted_skey, uint3
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"SGX seal data failed");
}
}*/
/* char arr_r[mpz_sizeinbase (sign->r, base) + 2];
char* r = mpz_get_str(arr_r, base, sign->r);
......@@ -560,10 +559,22 @@ void drive_key(int *err_status, char *err_string, uint8_t *encrypted_skey, uint3
char* s = mpz_get_str(arr_s, base, sign->s);
strncpy(sig_s, arr_s, 1024);*/
char skey[ECDSA_SKEY_LEN];
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_skey, NULL, 0, skey, dec_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
char * common_key = malloc(64*2);
gen_session_key(skey, pub_keyB, common_key);
mpz_clear(skey);
//free(skey);
free(pub_key);
//free(pub_key);
}
/*
Copyright 2018 Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "secure_enclave_t.h"
#include "sgx_tcrypto.h"
#include "sgx_tseal.h"
#include <sgx_tgmp.h>
#include <sgx_trts.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "tSgxSSL_api.h"
#include "../sgxwallet_common.h"
void *(*gmp_realloc_func)(void *, size_t, size_t);
void *(*oc_realloc_func)(void *, size_t, size_t);
void (*gmp_free_func)(void *, size_t);
void (*oc_free_func)(void *, size_t);
void *reallocate_function(void *, size_t, size_t);
void free_function(void *, size_t);
void tgmp_init() {
oc_realloc_func = &reallocate_function;
oc_free_func = &free_function;
mp_get_memory_functions(NULL, &gmp_realloc_func, &gmp_free_func);
mp_set_memory_functions(NULL, oc_realloc_func, oc_free_func);
}
void free_function(void *ptr, size_t sz) {
if (sgx_is_within_enclave(ptr, sz))
gmp_free_func(ptr, sz);
else {
sgx_status_t status;
status = oc_free(ptr, sz);
if (status != SGX_SUCCESS)
abort();
}
}
void *reallocate_function(void *ptr, size_t osize, size_t nsize) {
uint64_t nptr;
sgx_status_t status;
if (sgx_is_within_enclave(ptr, osize)) {
return gmp_realloc_func(ptr, osize, nsize);
}
status = oc_realloc(&nptr, ptr, osize, nsize);
if (status != SGX_SUCCESS)
abort();
/*
* If the entire range of allocated memory is not outside the enclave
* then something truly terrible has happened. In theory, we could
* free() and try again, but would you trust the OS at this point?
*/
if (!sgx_is_outside_enclave((void *) ptr, nsize))
abort();
return (void *) nptr;
}
void e_mpz_add(mpz_t *c_un, mpz_t *a_un, mpz_t *b_un) {}
void e_mpz_mul(mpz_t *c_un, mpz_t *a_un, mpz_t *b_un) {}
void e_mpz_div(mpz_t *c_un, mpz_t *a_un, mpz_t *b_un) {}
void e_mpf_div(mpf_t *c_un, mpf_t *a_un, mpf_t *b_un) {}
void generate_ecdsa_key(int *err_status, char *err_string,
uint8_t *encrypted_key, uint32_t *enc_len) {
}
void encrypt_key(int *err_status, char *err_string, char *key,
uint8_t *encrypted_key, uint32_t *enc_len) {
init();
*err_status = UNKNOWN_ERROR;
memset(err_string, 0, BUF_LEN);
checkKey(err_status, err_string, key);
if (*err_status != 0) {
snprintf(err_string + strlen(err_string), BUF_LEN, "check_key failed");
return;
}
uint32_t sealedLen = sgx_calc_sealed_data_size(0, MAX_KEY_LENGTH);
if (sealedLen > BUF_LEN) {
*err_status = ENCRYPTED_KEY_TOO_LONG;
snprintf(err_string, BUF_LEN, "sealedLen > MAX_ENCRYPTED_KEY_LENGTH");
return;
}
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) {
*err_status = SEAL_KEY_FAILED;
snprintf(err_string, BUF_LEN, "SGX seal data failed");
return;
}
*enc_len = sealedLen;
char decryptedKey[BUF_LEN];
memset(decryptedKey, 0, BUF_LEN);
decrypt_key(err_status, err_string, encrypted_key, sealedLen, decryptedKey);
if (*err_status != 0) {
snprintf(err_string + strlen(err_string), BUF_LEN, ":decrypt_key failed");
return;
}
uint64_t decryptedKeyLen = strnlen(decryptedKey, MAX_KEY_LENGTH);
if (decryptedKeyLen == MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "Decrypted key is not null terminated");
return;
}
*err_status = -8;
if (strncmp(key, decryptedKey, MAX_KEY_LENGTH) != 0) {
snprintf(err_string, BUF_LEN, "Decrypted key does not match original key");
return;
}
*err_status = 0;
}
void decrypt_key(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, char *key) {
init();
uint32_t decLen;
*err_status = -9;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *) encrypted_key, NULL, 0, (uint8_t *) key, &decLen);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN, "sgx_unseal_data failed with status %d", status);
return;
}
if (decLen != MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "decLen != MAX_KEY_LENGTH");
return;
}
*err_status = -10;
uint64_t keyLen = strnlen(key, MAX_KEY_LENGTH);
if (keyLen == MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "Key is not null terminated");
return;
}
// 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;
}
}
*err_status = 0;
return;
}
void bls_sign_message(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, char *_hashX,
char *_hashY, char *signature) {
char key[BUF_LEN];
char* sig = (char*) calloc(BUF_LEN, 1);
init();
decrypt_key(err_status, err_string, encrypted_key, enc_len, key);
if (*err_status != 0) {
return;
}
enclave_sign(key, _hashX, _hashY, sig);
strncpy(signature, sig, BUF_LEN);
if (strnlen(signature, BUF_LEN) < 10) {
*err_status = -1;
return;
}
}
void ecdsa_sign_message(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, uint8_t *message, char *signature) {
*err_status = -1;
char key[BUF_LEN];
decrypt_key(err_status, err_string, encrypted_key, enc_len, key);
if (err_status != 0) {
return;
}
<<<<<<< HEAD
//strncpy(signature, ecdsaSig, MAX_SIG_LEN);
=======
>>>>>>> master
//strncpy(signature, ecdsaSig, MAX_SIG_LEN);
unsigned char entropy_buf[ADD_ENTROPY_SIZE] = {0};
RAND_add(entropy_buf, sizeof(entropy_buf), ADD_ENTROPY_SIZE);
RAND_seed(entropy_buf, sizeof(entropy_buf));
// Initialize SGXSSL crypto
OPENSSL_init_crypto(0, NULL);
RAND_add(entropy_buf, sizeof(entropy_buf), ADD_ENTROPY_SIZE);
RAND_seed(entropy_buf, sizeof(entropy_buf));
EC_KEY *ec = NULL;
int eccgroup;
eccgroup = OBJ_txt2nid("secp384r1");
ec = EC_KEY_new_by_curve_name(eccgroup);
if (ec == NULL) {
return;
}
EC_KEY_set_asn1_flag(ec, OPENSSL_EC_NAMED_CURVE);
int ret = EC_KEY_generate_key(ec);
if (!ret) {
return;
}
EVP_PKEY *ec_pkey = EVP_PKEY_new();
if (ec_pkey == NULL) {
return;
}
EVP_PKEY_assign_EC_KEY(ec_pkey, ec);
// DONE
char buffer[100];
unsigned char sig;
unsigned int siglen;
int i;
for (i = 0; i < 1000; i++) {
// Add context
EVP_MD_CTX *context = EVP_MD_CTX_new();
// Init, update, final
EVP_SignInit_ex(context, EVP_sha1(), NULL);
EVP_SignUpdate(context, &buffer, 100);
EVP_SignFinal(context, &sig, &siglen, ec_pkey);
}
*err_status = 0;
}
void gen_dkg_secret (int *err_status, char *err_string, uint8_t *encrypted_dkg_secret, uint32_t* enc_len, size_t _t){
char* dkg_secret = (char*)malloc(DKG_BUFER_LENGTH);
gen_dkg_poly(dkg_secret, _t);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, DKG_BUFER_LENGTH);//sizeof(sgx_sealed_data_t) + sizeof(dkg_secret);
sgx_status_t status = sgx_seal_data(0, NULL, DKG_BUFER_LENGTH, (uint8_t*)dkg_secret, sealedLen,(sgx_sealed_data_t*)encrypted_dkg_secret);
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"SGX seal data failed");
}
*enc_len = sealedLen;
}
void decrypt_dkg_secret (int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint8_t* decrypted_dkg_secret, uint32_t enc_len){
//uint32_t dec_size = DKG_BUFER_LENGTH;//sgx_get_encrypt_txt_len( ( sgx_sealed_data_t *)encrypted_dkg_secret);
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, decrypted_dkg_secret, &enc_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
}
void get_secret_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t enc_len, char* secret_shares,
unsigned _t, unsigned _n){
char* decrypted_dkg_secret = (char*)malloc(DKG_MAX_SEALED_LEN);
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, enc_len);
calc_secret_shares(decrypted_dkg_secret, secret_shares, _t, _n);
}
void get_public_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t enc_len, char* public_shares,
unsigned _t, unsigned _n){
char* decrypted_dkg_secret = (char*)malloc(DKG_MAX_SEALED_LEN);
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, enc_len);
calc_public_shares(decrypted_dkg_secret, public_shares, _t);
}
......@@ -41,7 +41,8 @@ enclave {
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] char* key,
[out, count = 1024] uint8_t* encrypted_key, [user_check] uint32_t *enc_len);
[out, count = 1024] uint8_t* encrypted_key,
[user_check] uint32_t *enc_len);
public void decrypt_key (
[user_check] int *err_status,
......@@ -62,32 +63,32 @@ enclave {
public void gen_dkg_secret (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[out, count = 2000] uint8_t* encrypted_dkg_secret,
[out, count = 3650] uint8_t* encrypted_dkg_secret,
[user_check] uint32_t * enc_len,
size_t _t);
public void decrypt_dkg_secret (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 2000] uint8_t* encrypted_dkg_secret,
[out, count = 2000] uint8_t* decrypted_dkg_secret,
[in, count = 3650] uint8_t* encrypted_dkg_secret,
[out, count = 3650] uint8_t* decrypted_dkg_secret,
uint32_t enc_len);
public void get_secret_shares (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 2000] uint8_t* encrypted_dkg_secret,
[in, count = 3650] uint8_t* encrypted_dkg_secret,
uint32_t enc_len,
[out, count = 2000] char* secret_shares,
[out, count = 3650] char* secret_shares,
unsigned _t,
unsigned _n);
public void get_public_shares (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 2000] uint8_t* decrypted_dkg_secret,
[in, count = 3650] uint8_t* decrypted_dkg_secret,
uint32_t enc_len,
[out, count = 4000] char* public_shares,
[out, count = 10000] char* public_shares,
unsigned _t,
unsigned _n);
......
......@@ -26,8 +26,8 @@
#define ADD_ENTROPY_SIZE 32
#define DKG_BUFER_LENGTH 1250
#define DKG_MAX_SEALED_LEN 2000
#define DKG_BUFER_LENGTH 3060
#define DKG_MAX_SEALED_LEN 3650
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
......
......@@ -42,7 +42,6 @@
}
},
{
"name": "generateECDSAKey",
"params": {
......@@ -82,5 +81,17 @@
"signature_r": "12345",
"signature_s": "12345"
}
},
{
"name": "generateDKGPoly",
"params": {
"keyName": "key1",
"t": 3
},
"returns": {
"status": 0,
"errorMessage": "12345"
}
}
]
\ No newline at end of file
......@@ -80,6 +80,17 @@ class StubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value generateDKGPoly(const std::string& keyName, int t) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["keyName"] = keyName;
p["t"] = t;
Json::Value result = this->CallMethod("generateDKGPoly",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
};
#endif //JSONRPC_CPP_STUB_STUBCLIENT_H_
......@@ -56,6 +56,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <sgx_tcrypto.h>
#include <dkg/dkg.h>
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch.hpp"
......@@ -250,15 +253,15 @@ TEST_CASE("KeysDB test", "[keys-db]") {
TEST_CASE( "DKG gen test", "[dkg-gen]" ) {
init_all();
//init_all();
init_enclave();
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
char* errMsg = (char*) calloc(1024,1);
int err_status = 0;
uint32_t enc_len = 0;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 16);
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 32);
REQUIRE(status == SGX_SUCCESS);
printf("gen_dkg_secret completed with status: %d %s \n", err_status, errMsg);
printf("\n Length: %d \n", enc_len);
......@@ -351,7 +354,7 @@ libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
int err_status = 0;
uint32_t enc_len = 0;
unsigned t = 3, n = 4;
unsigned t = 32, n = 32;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, n);
REQUIRE(status == SGX_SUCCESS);
......@@ -378,7 +381,7 @@ libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
std::vector < libff::alt_bn128_Fr> s_shares_dkg = dkg_obj.SecretKeyContribution(SplitStringToFr((char*)secret, colon));
/*printf("calculated secret: \n");
printf("calculated secret length %d : \n", s_shares_dkg.size());
for ( int i = 0; i < s_shares_dkg.size(); i++){
libff::alt_bn128_Fr cur_share = s_shares_dkg.at(i);
mpz_t(sshare);
......@@ -388,8 +391,7 @@ libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
char* share_str = mpz_get_str(arr, 10, sshare);
printf(" %s \n", share_str);
mpz_clear(sshare);
}*/
}
REQUIRE(s_shares == s_shares_dkg);
......@@ -411,7 +413,7 @@ TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
int err_status = 0;
uint32_t enc_len = 0;
unsigned t = 3, n = 4;
unsigned t = 32, n = 32;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, n);
REQUIRE(status == SGX_SUCCESS);
......@@ -421,7 +423,7 @@ TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
char* errMsg1 = (char*) calloc(1024,1);
char colon = ':';
char* public_shares = (char*)calloc(4000, 1);
char* public_shares = (char*)calloc(10000, 1);
status = get_public_shares(eid, &err_status, errMsg1, encrypted_dkg_secret, enc_len, public_shares, t, n);
REQUIRE(status == SGX_SUCCESS);
//printf("\nget_public_shares status: %d error %s \n\n", err_status, errMsg1);
......@@ -439,13 +441,13 @@ TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
char* secret = (char*)calloc(DKG_MAX_SEALED_LEN, sizeof(char));
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, enc_len);
REQUIRE(status == SGX_SUCCESS);
//printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1);
printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1);
signatures::Dkg dkg_obj(t,n);
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
std::vector < libff::alt_bn128_G2> pub_shares_dkg = dkg_obj.VerificationVector(poly);
/*printf("calculated public shares (X.c0): \n");
printf("calculated public shares (X.c0): \n");
for ( int i = 0; i < pub_shares_dkg.size(); i++){
libff::alt_bn128_G2 el = pub_shares_dkg.at(i);
el.to_affine_coordinates();
......@@ -457,7 +459,7 @@ TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
char* share_str = mpz_get_str(arr, 10, x_c0);
printf(" %s \n", share_str);
mpz_clear(x_c0);
}*/
}
bool res = (pub_shares_G2 == pub_shares_dkg);
REQUIRE( res == true);
......@@ -516,8 +518,8 @@ TEST_CASE("ECDSA keygen and signature test", "[ecdsa_test]") {
for ( int i = 0; i < 1024 ; i++)
printf("%u ", encr_pr_key[i]);*/
// char* hex = "4b688df40bcedbe641ddb16ff0a1842d9c67ea1c3bf63f3e0471baa664531d1a";
char* hex = "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
char* hex = "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F";
// char* hex = "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
printf("hash length %d ", strlen(hex));
char* signature_r = (char *)calloc(1024, 1);
char* signature_s = (char *)calloc(1024, 1);
......@@ -629,7 +631,9 @@ TEST_CASE("API test", "[api_test]") {
try {
// cout << c.generateECDSAKey("known_key1") << endl;
//cout<<c.getPublicECDSAKey("test_key");
cout << c.ecdsaSignMessageHash(16, "known_key1","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
//cout << c.ecdsaSignMessageHash(16, "known_key1","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
cout << c.generateDKGPoly("poly", 3);
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
}
......
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