Unverified Commit 0c65f553 authored by Oleh Nikolaiev's avatar Oleh Nikolaiev Committed by GitHub

Merge pull request #252 from skalenetwork/feature/SKALE-3023-comand-for-sgx-keys-information

Feature/skale 3023 comand for sgx keys information
parents c43fbed6 66238465
......@@ -129,36 +129,6 @@ bool hex2carray(const char *_hex, uint64_t *_bin_len,
return true;
}
bool sign(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, size_t _signerIndex,
char *_sig) {
CHECK_STATE(_encryptedKeyHex);
CHECK_STATE(_hashHex);
CHECK_STATE(_sig);
auto keyStr = make_shared<string>(_encryptedKeyHex);
auto hash = make_shared < array < uint8_t,
32 >> ();
uint64_t binLen;
if (!hex2carray(_hashHex, &binLen, hash->data(), hash->size())) {
throw SGXException(SIGN_FUNCTION_INVALID_HEX, string(__FUNCTION__) + ":Invalid hash");
}
auto keyShare = make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
auto sigShareStr = sigShare->toString();
strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
return true;
}
bool sign_aes(const char *_encryptedKeyHex, const char *_hashHex, size_t _t, size_t _n, char *_sig) {
CHECK_STATE(_encryptedKeyHex);
......
......@@ -27,6 +27,7 @@
#include <iostream>
#include "leveldb/db.h"
#include <jsonrpccpp/client.h>
#include "sgxwallet_common.h"
#include "SGXException.h"
......@@ -42,6 +43,14 @@ using namespace leveldb;
static WriteOptions writeOptions;
static ReadOptions readOptions;
shared_ptr<string> LevelDB::readNewStyleValue(const string& value) {
Json::Value key_data;
Json::Reader reader;
reader.parse(value.c_str(), key_data);
return std::make_shared<string>(key_data["value"].asString());
}
std::shared_ptr<string> LevelDB::readString(const string &_key) {
auto result = std::make_shared<string>();
......@@ -56,17 +65,26 @@ std::shared_ptr<string> LevelDB::readString(const string &_key) {
return nullptr;
}
if (result->at(0) == '{') {
return readNewStyleValue(*result);
}
return result;
}
void LevelDB::writeString(const string &_key, const string &_value) {
Json::Value writerData;
writerData["value"] = _value;
writerData["timestamp"] = std::to_string(std::time(nullptr));
Json::FastWriter fastWriter;
std::string output = fastWriter.write(writerData);
auto status = db->Put(writeOptions, Slice(_key), Slice(_value));
auto status = db->Put(writeOptions, Slice(_key), Slice(output));
throwExceptionOnError(status);
}
void LevelDB::deleteDHDKGKey(const string &_key) {
string full_key = "DKG_DH_KEY_" + _key;
......@@ -94,18 +112,6 @@ void LevelDB::deleteKey(const string &_key) {
}
void LevelDB::writeByteArray(string &_key, const char *value,
size_t _valueLen) {
CHECK_STATE(value);
auto status = db->Put(writeOptions, Slice(_key), Slice(value, _valueLen));
throwExceptionOnError(status);
}
void LevelDB::throwExceptionOnError(Status _status) {
if (_status.IsNotFound())
return;
......@@ -163,7 +169,59 @@ void LevelDB::writeDataUnique(const string & name, const string &value) {
}
writeString(key, value);
}
pair<stringstream, uint64_t> LevelDB::getAllKeys() {
stringstream keysInfo;
leveldb::Iterator *it = db->NewIterator(readOptions);
uint64_t counter = 0;
for (it->SeekToFirst(); it->Valid(); it->Next()) {
++counter;
string key = it->key().ToString();
string value;
if (it->value().ToString()[0] == '{') {
// new style keys
Json::Value key_data;
Json::Reader reader;
reader.parse(it->value().ToString().c_str(), key_data);
string timestamp_to_date_command = "date -d @" + key_data["timestamp"].asString();
value = " VALUE: " + key_data["value"].asString() + ", TIMESTAMP: " + exec(timestamp_to_date_command.c_str()) + '\n';
} else {
// old style keys
value = " VALUE: " + it->value().ToString();
}
keysInfo << "KEY: " << key << ',' << value;
}
return {std::move(keysInfo), counter};
}
pair<string, uint64_t> LevelDB::getLatestCreatedKey() {
leveldb::Iterator *it = db->NewIterator(readOptions);
int64_t latest_timestamp = 0;
string latest_created_key_name = "";
for (it->SeekToFirst(); it->Valid(); it->Next()) {
if (it->value().ToString()[0] == '{') {
// new style keys
Json::Value key_data;
Json::Reader reader;
reader.parse(it->value().ToString().c_str(), key_data);
if (std::stoi(key_data["timestamp"].asString()) > latest_timestamp) {
latest_timestamp = std::stoi(key_data["timestamp"].asString());
latest_created_key_name = it->key().ToString();
}
} else {
// old style keys
// assuming server has at least one new-style key created
continue;
}
}
return {latest_created_key_name, latest_timestamp};
}
......
......@@ -26,10 +26,12 @@
#define SGXWALLET_LEVELDB_H
#include <memory>
#include <sstream>
#include <string>
#include <mutex>
#include <vector>
#include "common.h"
namespace leveldb {
class DB;
class Status;
......@@ -55,7 +57,6 @@ class LevelDB {
public:
static void initDataFolderAndDBs();
static const shared_ptr<LevelDB> &getLevelDb();
......@@ -66,20 +67,17 @@ public:
public:
shared_ptr<string> readString(const string& _key);
shared_ptr<string> readNewStyleValue(const string& value);
void writeString(const string &key1, const string &value1);
pair<stringstream, uint64_t> getAllKeys();
void writeDataUnique(const string & Name, const string &value);
void writeByteArray(const char *_key, size_t _keyLen, const char *value,
size_t _valueLen);
pair<string, uint64_t> getLatestCreatedKey();
void writeString(const string &key1, const string &value1);
void writeByteArray(string& _key, const char *value,
size_t _valueLen);
void writeDataUnique(const string & Name, const string &value);
void deleteDHDKGKey (const string &_key);
......@@ -89,15 +87,10 @@ public:
public:
void throwExceptionOnError(leveldb::Status result);
LevelDB(string& filename);
class KeyVisitor {
public:
virtual void visitDBKey(const char* _data) = 0;
......
......@@ -59,16 +59,16 @@ CLEANFILES = $(COMMON_ENCLAVE_SRC) secure_enclave.edl secure_enclave.signed.so
## The build target
bin_PROGRAMS = sgxwallet testw cert_util
bin_PROGRAMS = sgxwallet testw sgx_util
## You can't use $(wildcard ...) with automake so all source files
## have to be explicitly listed.
## have to be explicitly listed
COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \
SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp BLSCrypto.cpp \
ECDSACrypto.cpp \
COMMON_SRC = InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp \
SGXWalletServer.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp SGXInfoServer.cpp \
BLSCrypto.cpp ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp ServerDataChecker.cpp SEKManager.cpp \
third_party/intel/sgx_stub.c third_party/intel/sgx_detect_linux.c third_party/intel/create_enclave.c third_party/intel/oc_alloc.c \
ECDSAImpl.c TestUtils.cpp sgxwallet.c
......@@ -111,8 +111,10 @@ nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
cert_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp cert_util.cpp stubclient.cpp LevelDB.cpp SGXRegistrationServer.cpp CSRManagerServer.cpp
cert_util_LDADD=-LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \
-LlibBLS/build/libff/libff \
-l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -ldl
sgx_util_SOURCES= InvalidStateException.cpp Exception.cpp InvalidArgumentException.cpp Log.cpp sgx_util.cpp stubclient.cpp LevelDB.cpp \
SGXRegistrationServer.cpp CSRManagerServer.cpp SGXInfoServer.cpp
sgx_util_LDADD= -LlibBLS/deps/deps_inst/x86_or_x64/lib -Lleveldb/build -LlibBLS/build \
-LlibBLS/build/libff/libff \
-l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ljsonrpccpp-stub -ljsonrpccpp-server -ljsonrpccpp-client -ljsonrpccpp-common -ljsoncpp -lmicrohttpd -lgnutls -lgcrypt -lidn2 -lcurl -lssl -lcrypto -lz -lpthread -ldl
/*
Copyright (C) 2020-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file SGXInfoServer.cpp
@author Oleh Nikolaiev
@date 2020
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <jsonrpccpp/server/connectors/httpserver.h>
#include <stdio.h>
#include "sgxwallet_common.h"
#include "SGXException.h"
#include "LevelDB.h"
#include "SGXInfoServer.h"
#include "LevelDB.h"
#include "Log.h"
#include "common.h"
shared_ptr <SGXInfoServer> SGXInfoServer::server = nullptr;
shared_ptr <HttpServer> SGXInfoServer::httpServer = nullptr;
SGXInfoServer::SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type,
uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys)
: AbstractInfoServer(connector, type) {
logLevel_ = _logLevel;
autoSign_ = _autoSign;
checkCerts_ = _checkCerts;
generateTestKeys_ = _generateTestKeys;
}
Json::Value SGXInfoServer::getAllKeysInfo() {
Json::Value result;
try {
auto allKeysInfo = LevelDB::getLevelDb()->getAllKeys();
result["allKeys"] = allKeysInfo.first.str();
result["keysNumber"] = std::to_string(allKeysInfo.second);
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXInfoServer::getLatestCreatedKey() {
Json::Value result;
try {
pair<string, uint64_t> key = LevelDB::getLevelDb()->getLatestCreatedKey();
result["keyName"] = key.first;
result["creationTime"] = std::to_string(key.second);
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXInfoServer::getServerConfiguration() {
Json::Value result;
try {
result["autoConfirm"] = autoconfirm;
result["logLevel"] = logLevel_;
result["enterBackupKey"] = enterBackupKey;
result["useHTTPS"] = useHTTPS;
result["autoSign"] = autoSign_;
result["checkCerts"] = checkCerts_;
result["generateTestKeys"] = generateTestKeys_;
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
Json::Value SGXInfoServer::isKeyExist(const string& key) {
Json::Value result;
result["isExists"] = false;
try {
shared_ptr <string> keyPtr = LevelDB::getLevelDb()->readString(key);
if (keyPtr != nullptr) {
result["IsExist"] = true;
}
} HANDLE_SGX_EXCEPTION(result)
RETURN_SUCCESS(result)
}
int SGXInfoServer::initInfoServer(uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys) {
httpServer = make_shared<HttpServer>(BASE_PORT + 4);
server = make_shared<SGXInfoServer>(*httpServer, JSONRPC_SERVER_V2, _logLevel, _autoSign, _checkCerts, _generateTestKeys); // hybrid server (json-rpc 1.0 & 2.0)
if (!server->StartListening()) {
spdlog::error("Info server could not start listening on port {}", BASE_PORT + 4);
exit(-10);
} else {
spdlog::info("Info server started on port {}", BASE_PORT + 4);
}
return 0;
}
shared_ptr<SGXInfoServer> SGXInfoServer::getServer() {
CHECK_STATE(server);
return server;
}
/*
Copyright (C) 2020-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file SGXInfoServer.h
@author Oleh Nikolaiev
@date 2020
*/
#ifndef SGXINFOSERVER_H
#define SGXINFOSERVER_H
#include <mutex>
#include "abstractinfoserver.h"
#include <jsonrpccpp/server/connectors/httpserver.h>
using namespace jsonrpc;
using namespace std;
class SGXInfoServer : public AbstractInfoServer {
recursive_mutex m;
uint32_t logLevel_;
bool autoSign_;
bool checkCerts_;
bool generateTestKeys_;
static shared_ptr <HttpServer> httpServer;
static shared_ptr <SGXInfoServer> server;
public:
static shared_ptr <SGXInfoServer> getServer();
SGXInfoServer(AbstractServerConnector &connector, serverVersion_t type,
uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys);
virtual Json::Value getAllKeysInfo();
virtual Json::Value getLatestCreatedKey();
virtual Json::Value getServerConfiguration();
virtual Json::Value isKeyExist(const string& key);
static int initInfoServer(uint32_t _logLevel, bool _autoSign, bool _checkCerts, bool _generateTestKeys);
};
#endif // SGXINFOSERVER_H
......@@ -166,7 +166,6 @@ int SGXWalletServer::initHttpsServer(bool _checkCerts) {
}
}
httpServer = make_shared<HttpServer>(BASE_PORT, certPath, keyPath, rootCAPath, _checkCerts,
NUM_THREADS);
......
......@@ -52,6 +52,7 @@
#include "LevelDB.h"
#include "SGXWalletServer.h"
#include "SGXRegistrationServer.h"
#include "SGXInfoServer.h"
#include "SEKManager.h"
#include "CSRManagerServer.h"
#include "BLSCrypto.h"
......@@ -61,26 +62,7 @@
uint32_t enclaveLogLevel = 0;
using namespace std;
// Copy from libconsensus
string exec( const char* cmd ) {
CHECK_STATE( cmd );
std::array< char, 128 > buffer;
std::string result;
std::unique_ptr< FILE, decltype( &pclose ) > pipe( popen( cmd, "r" ), pclose );
if ( !pipe ) {
BOOST_THROW_EXCEPTION( std::runtime_error( "popen() failed!" ) );
}
while ( fgets( buffer.data(), buffer.size(), pipe.get() ) != nullptr ) {
result += buffer.data();
}
return result;
}
using namespace std;
void systemHealthCheck() {
string ulimit;
......@@ -181,7 +163,7 @@ uint64_t initEnclave() {
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign, bool _generateTestKeys) {
static atomic<bool> sgxServerInited(false);
static mutex initMutex;
......@@ -199,7 +181,7 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
CHECK_STATE(sgxServerInited != 1)
sgxServerInited = 1;
uint64_t counter = 0;
uint64_t counter = 0;
uint64_t initResult = 0;
while ((initResult = initEnclave()) != 0 && counter < 10){
......@@ -221,6 +203,8 @@ void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign) {
} else {
SGXWalletServer::initHttpServer();
}
SGXInfoServer::initInfoServer(_logLevel, _checkCert, _autoSign, _generateTestKeys);
sgxServerInited = true;
} catch (SGXException &_e) {
spdlog::error(_e.getMessage());
......
......@@ -32,7 +32,7 @@
#define EXTERNC
#endif
EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign);
EXTERNC void initAll(uint32_t _logLevel, bool _checkCert, bool _autoSign, bool _generateTestKeys);
EXTERNC void initUserSpace();
......
/*
Copyright (C) 2020-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file abstractinfoserver.h
@author Oleh Nikolaiev
@date 2020
*/
#ifndef ABSTRACTINFOSERVER_H
#define ABSTRACTINFOSERVER_H
#include <jsonrpccpp/server.h>
#include <iostream>
class AbstractInfoServer : public jsonrpc::AbstractServer<AbstractInfoServer>
{
public:
AbstractInfoServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer<AbstractInfoServer>(conn, type)
{
this->bindAndAddMethod(jsonrpc::Procedure("getAllKeysInfo", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getAllKeysInfoI);
this->bindAndAddMethod(jsonrpc::Procedure("getLatestCreatedKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getLatestCreatedKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getServerConfiguration", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, NULL), &AbstractInfoServer::getServerConfigurationI);
this->bindAndAddMethod(jsonrpc::Procedure("isKeyExist", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractInfoServer::isKeyExistI);
}
inline virtual void getAllKeysInfoI(const Json::Value &request, Json::Value &response)
{
response = this->getAllKeysInfo();
}
inline virtual void getLatestCreatedKeyI(const Json::Value &request, Json::Value &response)
{
response = this->getLatestCreatedKey();
}
inline virtual void getServerConfigurationI(const Json::Value &request, Json::Value &response)
{
response = this->getServerConfiguration();
}
inline virtual void isKeyExistI(const Json::Value &request, Json::Value &response)
{
response = this->isKeyExist(request["keyName"].asString());
}
virtual Json::Value getAllKeysInfo() = 0;
virtual Json::Value getLatestCreatedKey() = 0;
virtual Json::Value getServerConfiguration() = 0;
virtual Json::Value isKeyExist(const std::string& key) = 0;
};
#endif // ABSTRACTINFOSERVER_H
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file cert_util.cpp
@author Stan Kladko
@date 2019
*/
#include <iostream>
#include <cstring>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include "stubclient.h"
#include <unistd.h>
int print_hashes(){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.getUnsignedCSRs() << std::endl;
exit(0);
}
void sign_by_hash(std::string & hash, int status){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.signByHash(hash, status) << std::endl;
exit(0);
}
int main(int argc, char *argv[]) {
int opt;
if (argc > 1 && strlen(argv[1]) == 1) {
fprintf(stderr, "option is too short %s\n", argv[1]);
exit(1);
}
if (argc == 1) {
std::cout << "You may use following flags:" << std::endl;
std::cout << " -p print all unsigned csr hashes " << std::endl;
std::cout << " -s [hash] sign csr by hash" << std::endl;
std::cout << " -r [hash] reject csr by hash" << std::endl;
exit(0);
}
std::string hash;
while ((opt = getopt(argc, argv, "ps:r:")) != -1) {
switch (opt) {
case 'p': print_hashes();
break;
case 's': hash = optarg;
sign_by_hash(hash, 0);
break;
case 'r': hash = optarg;
sign_by_hash(hash, 2);
break;
case '?': // fprintf(stderr, "unknown flag\n");
exit(1);
}
}
return 0;
}
......@@ -96,6 +96,24 @@ BOOST_THROW_EXCEPTION(runtime_error(__ERR_STRING__)); \
#define SAFE_CHAR_BUF(__X__, __Y__) ;char __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
#define SAFE_UINT8_BUF(__X__, __Y__) ;uint8_t __X__ [ __Y__ ]; memset(__X__, 0, __Y__);
// Copy from libconsensus
inline string exec( const char* cmd ) {
CHECK_STATE( cmd );
std::array< char, 128 > buffer;
std::string result;
std::unique_ptr< FILE, decltype( &pclose ) > pipe( popen( cmd, "r" ), pclose );
if ( !pipe ) {
BOOST_THROW_EXCEPTION( std::runtime_error( "popen() failed!" ) );
}
while ( fgets( buffer.data(), buffer.size(), pipe.get() ) != nullptr ) {
result += buffer.data();
}
return result;
}
#include <shared_mutex>
extern std::shared_timed_mutex sgxInitMutex;
......
......@@ -8,6 +8,7 @@ services:
- "1027:1027"
- "1028:1028"
- "1029:1029"
- "1030:1030"
devices:
- "/dev/isgx"
- "/dev/mei0"
......
......@@ -8,6 +8,7 @@ services:
- "1027:1027"
- "1028:1028"
- "1029:1029"
- "1030:1030"
volumes:
- ./sgx_data:/usr/src/sdk/sgx_data
- /dev/urandom:/dev/random
......
/*
Copyright (C) 2019-Present SKALE Labs
This file is part of sgxwallet.
sgxwallet is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
sgxwallet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with sgxwallet. If not, see <https://www.gnu.org/licenses/>.
@file sgx_util.cpp
@author Stan Kladko
@date 2019
*/
#include <iostream>
#include <cstring>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include "stubclient.h"
#include "common.h"
#include <unistd.h>
int print_hashes(){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.getUnsignedCSRs() << std::endl;
exit(0);
}
void sign_by_hash(std::string & hash, int status){
jsonrpc::HttpClient client("http://localhost:1028");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Client inited" << std::endl;
std::cout << c.signByHash(hash, status) << std::endl;
exit(0);
}
void getNumberOfKeysCreated() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
std::cout << c.getAllKeysInfo()["keysNumber"].asString() << std::endl;
exit(0);
}
void getAllKeysInfo() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
std::cout << c.getAllKeysInfo()["allKeys"].asString() << std::endl;
std::cout << "TOTAL KEYS IN DATABASE: " << c.getAllKeysInfo()["keysNumber"].asString() << std::endl;
exit(0);
}
void getLatestCreatedKey() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
Json::Value lastCreatedKey = c.getLatestCreatedKey();
std::cout << "Last created key name: " << lastCreatedKey["keyName"] << std::endl;
std::string timestamp_to_date_command = "date -d @" + lastCreatedKey["creationTime"].asString();
std::cout << "Last created key creation time: " << exec(timestamp_to_date_command.c_str());
exit(0);
}
void getServerConfiguration() {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
Json::Value response = c.getServerConfiguration();
std::cout << "OPTION autoConfirm certificates switched to " << response["autoConfirm"] << '\n';
uint32_t logLevel = response["logLevel"].asInt();
std::string logLevelStr;
switch(logLevel) {
case 0:
logLevelStr = "trace";
break;
case 1:
logLevelStr = "debug";
break;
case 2:
logLevelStr = "info";
break;
case 3:
logLevelStr = "warning";
break;
case 4:
logLevelStr = "error";
break;
}
std::cout << "OPTION logLevel switched to " << logLevelStr << '\n';
std::cout << "OPTION enterBackupKey switched to " << response["enterBackupKey"] << '\n';
std::cout << "OPTION useHTTPS switched to " << response["useHTTPS"] << '\n';
std::cout << "OPTION autoSign certificates switched to " << response["autoSign"] << '\n';
std::cout << "OPTION checkCerts switched to " << response["checkCerts"] << '\n';
std::cout << "OPTION generateTestKeys switched to " << response["generateTestKeys"] << '\n';
exit(0);
}
void isKeyExists(const std::string& key) {
jsonrpc::HttpClient client("http://localhost:1030");
StubClient c(client, jsonrpc::JSONRPC_CLIENT_V2);
std::cout << "Info client inited" << std::endl;
if (c.isKeyExist(key)["IsExist"].asBool()) {
std::cout << "Key with name " << key << " presents in server database.\n";
} else {
std::cout << "Key with name " << key << " does not exist in server's database.\n";
}
exit(0);
}
int main(int argc, char *argv[]) {
int opt;
if (argc > 1 && strlen(argv[1]) == 1) {
fprintf(stderr, "option is too short %s\n", argv[1]);
exit(1);
}
if (argc == 1) {
std::cout << "You may use following flags:" << std::endl;
std::cout << " -p print all unsigned csr hashes " << std::endl;
std::cout << " -s [hash] sign csr by hash" << std::endl;
std::cout << " -r [hash] reject csr by hash" << std::endl;
std::cout << " -a print all keys" << std::endl;
std::cout << " -l print latest created key" << std::endl;
std::cout << " -n print number of keys stored in database" << std::endl;
std::cout << " -c print server's config" << std::endl;
std::cout << " -i [name] check if key with such name presents in database" << std::endl;
exit(0);
}
std::string hash;
std::string key;
while ((opt = getopt(argc, argv, "ps:r:alci:n")) != -1) {
switch (opt) {
case 'p': print_hashes();
break;
case 's': hash = optarg;
sign_by_hash(hash, 0);
break;
case 'r': hash = optarg;
sign_by_hash(hash, 2);
break;
case 'a':
getAllKeysInfo();
break;
case 'l':
getLatestCreatedKey();
break;
case 'c':
getServerConfiguration();
break;
case 'i': key = optarg;
isKeyExists(key);
break;
case 'n':
getNumberOfKeysCreated();
break;
case '?': // fprintf(stderr, "unknown flag\n");
exit(1);
}
}
return 0;
}
......@@ -171,7 +171,7 @@ int main(int argc, char *argv[]) {
enclaveLogLevel = L_TRACE;
}
initAll(enclaveLogLevel, checkClientCertOption, autoSignClientCertOption);
initAll(enclaveLogLevel, checkClientCertOption, autoSignClientCertOption, generateTestKeys);
ifstream is("sgx_data/4node.json");
......
......@@ -263,55 +263,99 @@ class StubClient : public jsonrpc::Client
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerStatus()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerStatus",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerVersion() {
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerVersion",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
////CSRManagerServer
Json::Value getUnsignedCSRs()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getUnsignedCSRs",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value signByHash(const std::string& hash, int status)
{
Json::Value p;
p["hash"] = hash;
p["status"] = status;
Json::Value result = this->CallMethod("signByHash",p);
if (result.isObject())
Json::Value getUnsignedCSRs()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getUnsignedCSRs",p);
if (result.isObject())
return result;
else
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
}
Json::Value signByHash(const std::string& hash, int status)
{
Json::Value p;
p["hash"] = hash;
p["status"] = status;
Json::Value result = this->CallMethod("signByHash",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerStatus()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerStatus",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerVersion() {
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerVersion",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
/// InfoServer
Json::Value getAllKeysInfo()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getAllKeysInfo", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getLatestCreatedKey()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getLatestCreatedKey", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getServerConfiguration()
{
Json::Value p;
p = Json::nullValue;
Json::Value result = this->CallMethod("getServerConfiguration", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value isKeyExist(const std::string& key)
{
Json::Value p;
p["keyName"] = key;
Json::Value result = this->CallMethod("isKeyExist", p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
};
......
......@@ -72,7 +72,7 @@ public:
TestFixture() {
TestUtils::resetDB();
setOptions(L_INFO, false, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixture() {
......@@ -85,7 +85,7 @@ public:
TestFixtureHTTPS() {
TestUtils::resetDB();
setOptions(L_INFO, true, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixtureHTTPS() {
......@@ -97,7 +97,7 @@ class TestFixtureNoResetFromBackup {
public:
TestFixtureNoResetFromBackup() {
setFullOptions(L_INFO, false, true, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixtureNoResetFromBackup() {
......@@ -110,7 +110,7 @@ class TestFixtureNoReset {
public:
TestFixtureNoReset() {
setOptions(L_INFO, false, true);
initAll(L_INFO, false, true);
initAll(L_INFO, false, true, false);
}
~TestFixtureNoReset() {
......
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