Skip to content

Commit

Permalink
update signature tool
Browse files Browse the repository at this point in the history
  • Loading branch information
vshymanskyy committed Oct 12, 2012
1 parent f9fe682 commit d3ea93c
Show file tree
Hide file tree
Showing 12 changed files with 2,398 additions and 28 deletions.
19 changes: 11 additions & 8 deletions CMakeLists.txt
Expand Up @@ -5,15 +5,15 @@ project (Kademlia)
set(CMAKE_BUILD_TYPE "Debug")
if (WIN32)
else (WIN32)
set(CMAKE_CXX_FLAGS_DEBUG "-g3 -W -Wall -Wvla -Wextra -Wshadow -Winline -Wconversion -Wcast-align -Wno-long-long -Wwrite-strings -Wpointer-arith -Wredundant-decls -Wunsafe-loop-optimizations -Wno-variadic-macros -Wno-unused-parameter -Woverloaded-virtual -fstack-protector-all")
set(CMAKE_CXX_FLAGS_DEBUG "-g3 -rdynamic -W -Wall -Wvla -Wextra -Wshadow -Winline -Wconversion -Wcast-align -Wno-long-long -Wwrite-strings -Wpointer-arith -Wredundant-decls -Wunsafe-loop-optimizations -Wno-variadic-macros -Wno-unused-parameter -Woverloaded-virtual -fstack-protector-all")
set(CMAKE_CXX_FLAGS_RELEASE "-O4 -fno-stack-protector")
endif (WIN32)

# The version number.
set (KAD_VERSION_MAJOR 0)
set (KAD_VERSION_MINOR 0)
set (KAD_VERSION_PATCH 1)

set (KAD_VERSION_MINOR 1)
set (KAD_VERSION_PATCH 0)
configure_file (
"${PROJECT_SOURCE_DIR}/src/KadConfig.h.in"
"${PROJECT_BINARY_DIR}/KadConfig.h"
Expand Down Expand Up @@ -45,11 +45,14 @@ add_subdirectory (xplat)
add_library (kad ${kad_src})
target_link_libraries (kad xplat udt msgpack cryptopp) # Win32: cryptlib

add_executable(kad_test ${CMAKE_BINARY_DIR}/kad_test.cpp)
target_link_libraries (kad_test kad)
#add_executable(kad_test ${CMAKE_BINARY_DIR}/kad_test.cpp)
#target_link_libraries (kad_test kad)

#add_executable(kad_sim kad_sim.cpp)
#target_link_libraries (kad_sim kad)

add_executable(kad_sim kad_sim.cpp)
target_link_libraries (kad_sim kad)
add_executable(sign sign.cpp)
target_link_libraries (sign msgpack cryptopp) # Win32: cryptlib

add_executable(kad_node kad_node.cpp)
target_link_libraries (kad_node kad)
1 change: 1 addition & 0 deletions bsp.cfg
@@ -0,0 +1 @@
vshymanskyy.org.ua:7777
Binary file removed docs/p2p_topology.png
Binary file not shown.
2,104 changes: 2,104 additions & 0 deletions ip.prefix

Large diffs are not rendered by default.

122 changes: 107 additions & 15 deletions kad_node.cpp
Expand Up @@ -21,43 +21,127 @@ int FindNode(int argc, char* argv[])
return 0;
}

XList<XSockAddr> LoadBspFromFile(const char*) {
static
int Update(int argc, char* argv[])
{
return 0;
}

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

XList<XSockAddr> LoadBspFromFile(const char* fn)
{
XList<XSockAddr> bsps;
string sLine = "";
ifstream infile;
infile.open(fn);
if (infile.is_open()) {
while (!infile.eof()) {
getline(infile, sLine);
bsps.Append(XSockAddr(sLine.c_str()));
}
infile.close();
}
return bsps;
}

void SaveBspToFile(const char* fn, const XList<XSockAddr>& bsps)
{
ofstream outfile;
outfile.open(fn);
if (outfile.is_open()) {
for (XList<XSockAddr>::It it = bsps.First(); it != bsps.End(); ++it) {
//XString name = bsps[it].ResolveName();
//if (name.Length()) {
// outfile << name << ":" << bsps[it].Port() << endl;
//} else {
outfile << bsps[it].ToString() << endl;
//}
}
outfile.close();
}
}

#include <sys/stat.h>
#include <unistd.h>

bool FileExists(const char* fn) {
struct stat sts;
if (stat(fn, &sts) == -1)
{
if (errno == ENOENT) {
return false;
}
X_FATAL("stat failed: %d (%s)", errno, strerror(errno));
}
return true;
}

bool FileDelete(const char* fn) {
if (unlink(fn) == -1)
{
if (errno != ENOENT) {
return false;
}
}
return true;
}

KadRSA* TryLoadKeys() {
if (FileExists("key.priv") && FileExists("key.pub")) {
KadRSA* rsa = new KadRSA("key.priv", "key.pub");
printf("RSA keys loaded\n");

if (rsa->ValidateKeys()) {
return rsa;
} else {
FileDelete("key.priv");
FileDelete("key.pub");
printf("Invalid RSA keys deleted\n");
delete rsa;
}
}
return NULL;
}

int main(int argc, char *argv[])
{
const char* bindaddr = "[::]:7777";
if (argc == 2) {
bindaddr = argv[1];
}

/************************************************
* General initialization
*/
XStackTrace();
RandInit();
XLogManager::Get().SetDefaultLogger(new XFileLogger("log.txt"));
//XLogManager::Get().SetDefaultLogger(new XFileLogger("log.txt"));

/************************************************
* Generate/Load Local identification data
*/
KadRSA* rsa = new KadRSA();

/*if (key files exist) {
rsa = new KadRSA("key.priv", "key.pub");
LOG(NULL, "RSA keys loaded");
} else {
LOG(NULL, "Generating RSA keys");
KadRSA* rsa = NULL; //TryLoadKeys();
if (!rsa) {
printf("Generating new RSA keys\n");
rsa = new KadRSA();
rsa->SaveKeys("key.priv", "key.pub");
LOG(NULL, "RSA keys saved");
}*/

if (!rsa->ValidateKeys()) {
X_FATAL("Invalid private/public keys!");
if (!rsa->ValidateKeys()) {
X_FATAL("Invalid RSA keys generated!");
}

rsa->SaveKeys("key.priv", "key.pub");
printf("RSA keys saved\n");
}

std::string pubKeyStr = KadRSA::PubEncode(rsa->GetPublicKey());
KadId localId = KadId::FromHash(pubKeyStr.c_str(), pubKeyStr.size());

printf ("LocalID: %s\n", (char*)localId.ToString());
gMgr = new KadOpMgr(localId, XSockAddr("::"));
gMgr = new KadOpMgr(localId, XSockAddr(bindaddr));
printf ("Address: %s\n", (char*)gMgr->BindAddr().ToString());

/************************************************
Expand Down Expand Up @@ -85,11 +169,19 @@ int main(int argc, char *argv[])
XShell sh("kad");
sh.RegisterCommand("peers", &Peers);
sh.RegisterCommand("find", &FindNode);
sh.RegisterCommand("update", &Update);
sh.Run();

/************************************************
* Leave the network
*/
printf ("Leaving the network...");
bspLst = gMgr->Leave();

/************************************************
* Save bootstrap contacts (bsp.txt)
*/
SaveBspToFile("bsp.txt", bspLst);

return 0;
}
1 change: 1 addition & 0 deletions kad_sim.cpp
Expand Up @@ -181,6 +181,7 @@ int RemoveCli(int argc, char* argv[])

int main(int argc, char *argv[])
{
XStackTrace();
RandInit();

//XLogManager::Get().SetDefaultLogger(new XFileLogger("log.txt"));
Expand Down
Binary file added master_key.pub
Binary file not shown.
156 changes: 156 additions & 0 deletions sign.cpp
@@ -0,0 +1,156 @@
#include <KadConfig.h>

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#include <msgpack.hpp>

#include <cryptopp/rsa.h>
#include <cryptopp/pssr.h>
#include <cryptopp/osrng.h>
#include <cryptopp/files.h>

using CryptoPP::AutoSeededRandomPool;
using CryptoPP::PSS;

using namespace CryptoPP;

#define KADEMLIA_VERSION (KADEMLIA_VERSION_MAJOR*100000 + KADEMLIA_VERSION_MINOR*1000 + KADEMLIA_VERSION_PATCH)

int main(int argc, char *argv[])
{
if (argc != 3) {
printf("Files not specified\n");
return 1;
}
const char* packIn = argv[1];
const char* packSigned = argv[2];

// Compute sha1 checksum for input file

// Prepare msgpack header
// [ Magic | Version | Data checksum | Random seed | Header signature ]
msgpack::sbuffer sbuff;
msgpack::packer<msgpack::sbuffer> pk(&sbuff);
pk.pack_map(4);
pk.pack_raw(3).pack_raw_body("ver", 3); pk.pack_uint64(KADEMLIA_VERSION);
pk.pack_raw(4).pack_raw_body("seed", 4); pk.pack_raw(6).pack_raw_body("random", 6);
pk.pack_raw(4).pack_raw_body("size", 4); pk.pack_uint32(4096);
pk.pack_raw(4).pack_raw_body("sha1", 4); pk.pack_raw(16).pack_raw_body("ccccccccccccccccccccccccc", 16);
AutoSeededRandomPool rng;

{ // Generate header signature

ByteQueue queue;
FileSource file("master_key.priv", true);
file.TransferTo(queue);
queue.MessageEnd();

RSA::PrivateKey privateKey;
privateKey.BERDecodePrivateKey(queue, false, queue.MaxRetrievable());
if (!privateKey.Validate(rng, 3)) {
printf("RSA Private key not validated!\n");
return 1;
}

RSASS<PSS, SHA1>::Signer signer(privateKey);
size_t length = signer.MaxSignatureLength();
SecByteBlock signature(length);
signer.SignMessage(rng, (const byte*)sbuff.data(), sbuff.size(), signature);

if (signature.size() != 4096/8) {
printf("RSA Signature size mismatch: %ld!\n", signature.size());
return 1;
}
// Sign header
pk.pack_raw(signature.size()).pack_raw_body((char*)signature.BytePtr(), signature.size());
}

/*{ // Print header
msgpack::unpacker pac;
pac.reserve_buffer(sbuff.size());
memcpy(pac.buffer(), sbuff.data(), sbuff.size());
pac.buffer_consumed(sbuff.size());
msgpack::unpacked msg;
while (pac.next(&msg)) {
msgpack_object_print(stdout, msg.get());
puts("");
}
}*/

// Write output file
ofstream outfile;
outfile.open(packSigned, iostream::binary);
if (outfile.is_open()) {
// Write header
outfile.write(sbuff.data(), sbuff.size());
// Write archive

outfile.close();
printf("Finished.\n");
} else {
printf("Could not open output file\n");
return 1;
}

{ // Verify
ByteQueue queue;
FileSource file("master_key.pub", true);
file.TransferTo(queue);
queue.MessageEnd();

RSA::PublicKey publicKey;
publicKey.BERDecodePublicKey(queue, false, queue.MaxRetrievable());
if (!publicKey.Validate(rng, 3)) {
printf("RSA Public key not validated!\n");
return 1;
}
// Verifier object
RSASS<PSS, SHA1>::Verifier verifier(publicKey);

/*{ // Verify header
msgpack::unpacker pac;
pac.reserve_buffer(sbuff.size());
memcpy(pac.buffer(), sbuff.data(), sbuff.size());
pac.buffer_consumed(sbuff.size());
msgpack::unpacked msg;
size_t headerSize = 50; //pac.message_size();
if (pac.next(&msg) && msg.get().type == msgpack::type::MAP) {
// header
if (pac.next(&msg) && msg.get().type == msgpack::type::RAW) {
// signature
if (verifier.VerifyMessage((const byte*)sbuff.data(), headerSize, (const byte*)msg.get().via.raw.ptr, msg.get().via.raw.size)) {
printf("Header verification OK.\n");
} else {
printf("Header verification FAILED!\n");
return 1;
}
}
}
}*/

msgpack_unpacked msg;
size_t offset = 0;
msgpack_unpacked_init(&msg);
if (msgpack_unpack_next(&msg, sbuff.data(), sbuff.size(), &offset)) {
// header
size_t headerSize = offset;
if (msgpack_unpack_next(&msg, sbuff.data(), sbuff.size(), &offset)) {
// signature

if (verifier.VerifyMessage((const byte*)sbuff.data(), headerSize, (const byte*)msg.data.via.raw.ptr, msg.data.via.raw.size)) {
printf("Header verification OK.\n");
} else {
printf("Header verification FAILED!\n");
return 1;
}
}
}


}
return 0;
}
5 changes: 3 additions & 2 deletions src/KadMsg.h
Expand Up @@ -125,9 +125,10 @@ struct KadMsg
KadMsg() {}
KadMsg(Type t) : mMsgType (t) {}

uint16_t mMsgType;
unsigned mVersion;
unsigned mMsgType;
uint64_t mMsgId;
KadId mSrcId;
KadId mSrcId;

MSGPACK_DEFINE(mMsgType, mMsgId, mSrcId);
};
Expand Down

0 comments on commit d3ea93c

Please sign in to comment.