1
1
Fork 0
mirror of https://github.com/oxen-io/lokinet synced 2023-12-14 06:53:00 +01:00

Initial No-Op Crypto implementation

This commit is contained in:
Michael 2019-05-28 01:19:25 +01:00
parent 755a232982
commit 8323725509
No known key found for this signature in database
GPG key ID: 2D51757B47E2434C
9 changed files with 257 additions and 121 deletions

View file

@ -12,23 +12,23 @@ import os
import sys
import requests
from pylokinet import rc
from pylokinet import rc
lib_file = os.path.join(os.path.realpath('.'), 'liblokinet-shared.so')
def log(msg):
sys.stderr.write("lokinet: {}\n".format(msg))
sys.stderr.flush()
class LokiNET(threading.Thread):
lib = None
ctx = 0
failed = False
up = False
asRouter = True
def configure(self, lib, conf, ip=None, port=None, ifname=None, seedfile=None, lokid_host=None, lokid_port=None):
@ -43,7 +43,8 @@ class LokiNET(threading.Thread):
if self.lib.llarp_ensure_config(conf.encode('utf-8'), os.path.dirname(conf).encode('utf-8'), True, self.asRouter):
config = configparser.ConfigParser()
config.read(conf)
log('overwrite ip="{}" port="{}" ifname="{}" seedfile="{}" lokid=("{}", "{}")'.format(ip, port, ifname, seedfile, lokid_host, lokid_port))
log('overwrite ip="{}" port="{}" ifname="{}" seedfile="{}" lokid=("{}", "{}")'.format(
ip, port, ifname, seedfile, lokid_host, lokid_port))
if seedfile and lokid_host and lokid_port:
if not os.path.exists(seedfile):
log('cannot access service node seed at "{}"'.format(seedfile))
@ -66,8 +67,7 @@ class LokiNET(threading.Thread):
self.ctx = self.lib.llarp_main_init(conf.encode('utf-8'))
else:
return False
return self.lib.llarp_main_setup(self.ctx) == 0
return self.lib.llarp_main_setup(self.ctx, False) == 0
def inform_fail(self):
"""
@ -79,7 +79,7 @@ class LokiNET(threading.Thread):
def inform_up(self):
self.up = True
self._inform()
def _inform(self):
"""
inform waiter
@ -105,14 +105,16 @@ class LokiNET(threading.Thread):
self.inform_fail()
self.up = False
# self._up.release()
def close(self):
if self.lib and self.ctx:
self.lib.llarp_main_free(self.ctx)
def getconf(name, fallback=None):
return name in os.environ and os.environ[name] or fallback
def run_main(args):
seedfile = getconf("LOKI_SEED_FILE")
if seedfile is None:
@ -126,12 +128,12 @@ def run_main(args):
if root is None:
print("LOKINET_ROOT was not set")
return
rc_callback = getconf("LOKINET_SUBMIT_URL")
if rc_callback is None:
print("LOKINET_SUBMIT_URL was not set")
return
bootstrap = getconf("LOKINET_BOOTSTRAP_URL")
if bootstrap is None:
print("LOKINET_BOOTSTRAP_URL was not set")
@ -172,7 +174,7 @@ def run_main(args):
return
if loki.configure(lib, conf, ip, port, ifname, seedfile, lokid_host, lokid_port):
log("configured")
loki.start()
try:
log("waiting for spawn")
@ -187,7 +189,8 @@ def run_main(args):
log("submitting rc")
try:
with open(os.path.join(root, 'self.signed'), 'rb') as f:
r = requests.put(rc_callback, data=f.read(), headers={"content-type": "application/octect-stream"})
r = requests.put(rc_callback, data=f.read(), headers={
"content-type": "application/octect-stream"})
log('submit rc reply: HTTP {}'.format(r.status_code))
except Exception as ex:
log("failed to submit rc: {}".format(ex))
@ -212,8 +215,10 @@ def run_main(args):
else:
loki.close()
def main():
run_main(sys.argv[1:])
if __name__ == "__main__":
main()
main()

View file

@ -107,6 +107,7 @@ main(int argc, char *argv[])
("g,generate", "generate client config", cxxopts::value<bool>())
("r,router", "generate router config", cxxopts::value<bool>())
("f,force", "overwrite", cxxopts::value<bool>())
("d,debug", "debug mode - UNENCRYPTED TRAFFIC", cxxopts::value<bool>())
("config","path to configuration file", cxxopts::value<std::string>());
options.parse_positional("config");
@ -115,6 +116,7 @@ main(int argc, char *argv[])
bool genconfigOnly = false;
bool asRouter = false;
bool overWrite = false;
bool debugMode = false;
std::string conffname; // suggestions: confFName? conf_fname?
try
@ -138,6 +140,11 @@ main(int argc, char *argv[])
genconfigOnly = true;
}
if(result.count("debug") > 0)
{
debugMode = true;
}
if(result.count("force") > 0)
{
overWrite = true;
@ -279,7 +286,7 @@ main(int argc, char *argv[])
signal(SIGHUP, handle_signal);
#endif
code = llarp_main_setup(ctx);
code = llarp_main_setup(ctx, debugMode);
if(code == 0)
code = llarp_main_run(ctx);
llarp_main_free(ctx);

View file

@ -41,7 +41,7 @@ extern "C"
/// setup main context, returns 0 on success
int
llarp_main_setup(struct llarp_main *ptr);
llarp_main_setup(struct llarp_main *ptr, bool debugMode);
/// run main context, returns 0 on success, blocks until program end
int

View file

@ -84,7 +84,7 @@ namespace llarp
GetDatabase(const byte_t *pk);
int
Setup();
Setup(bool debug=false);
int
Run();

View file

@ -126,6 +126,7 @@ set(LIB_SRC
context.cpp
crypto/constants.cpp
crypto/crypto_libsodium.cpp
crypto/crypto_noop.cpp
crypto/crypto.cpp
crypto/ec.cpp
crypto/encrypted_frame.cpp

View file

@ -3,6 +3,7 @@
#include <config.hpp>
#include <crypto/crypto_libsodium.hpp>
#include <crypto/crypto_noop.hpp>
#include <dht/context.hpp>
#include <dnsd.hpp>
#include <ev/ev.hpp>
@ -162,9 +163,9 @@ __ ___ ____ _ _ ___ _ _ ____
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
This Lokinet session is not private
This Lokinet session is not private!!
Sending connection metrics to metrictank
Sending connection metrics to metrictank!!
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
@ -246,7 +247,7 @@ __ ___ ____ _ _ ___ _ _ ____
}
int
Context::Setup()
Context::Setup(bool debug)
{
llarp::LogInfo(LLARP_VERSION, " ", LLARP_RELEASE_MOTTO);
llarp::LogInfo("starting up");
@ -268,7 +269,33 @@ __ ___ ____ _ _ ___ _ _ ____
else
logic = std::make_shared< Logic >();
crypto = std::make_unique< sodium::CryptoLibSodium >();
if(debug)
{
static std::string WARNING = R"(
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
This Lokinet session is not private!!
Sending traffic unencrypted!!
__ ___ ____ _ _ ___ _ _ ____
\ \ / / \ | _ \| \ | |_ _| \ | |/ ___|
\ \ /\ / / _ \ | |_) | \| || || \| | | _
\ V V / ___ \| _ <| |\ || || |\ | |_| |
\_/\_/_/ \_\_| \_\_| \_|___|_| \_|\____|
)";
std::cerr << WARNING << '\n';
crypto = std::make_unique< NoOpCrypto >();
}
else
{
crypto = std::make_unique< sodium::CryptoLibSodium >();
}
cryptoManager = std::make_unique< CryptoManager >(crypto.get());
router = std::make_unique< Router >(worker.get(), mainloop, logic);
@ -473,9 +500,9 @@ extern "C"
}
int
llarp_main_setup(struct llarp_main *ptr)
llarp_main_setup(struct llarp_main *ptr, bool debug)
{
return ptr->ctx->Setup();
return ptr->ctx->Setup(debug);
}
int
@ -534,104 +561,6 @@ extern "C"
return ptr->ctx->LoadDatabase();
}
/*
int
llarp_main_iterateDatabase(struct llarp_main *ptr, struct llarp_nodedb_iter i)
{
return ptr->ctx->IterateDatabase(i);
}
bool
llarp_main_putDatabase(struct llarp_main *ptr, llarp::RouterContact &rc)
{
return ptr->ctx->PutDatabase(rc);
}
llarp::RouterContact *
llarp_main_getDatabase(struct llarp_main *ptr, byte_t *pk)
{
return ptr->ctx->GetDatabase(pk);
}
llarp::RouterContact *
llarp_main_getLocalRC(__attribute__((unused)) struct llarp_main *ptr)
{
return nullptr;
}
void
llarp_main_checkOnline(void *u, __attribute__((unused)) uint64_t orig,
uint64_t left)
{
// llarp::Info("checkOnline - check ", left);
if(left)
return;
struct check_online_request *request =
static_cast< struct check_online_request * >(u);
// llarp::Debug("checkOnline - running");
// llarp::Info("checkOnline - DHT nodes ",
// request->ptr->ctx->router->dht->impl.nodes->nodes.size());
request->online = false;
request->nodes =
request->ptr->ctx->router->dht()->impl->Nodes()->nodes.size();
if(request->ptr->ctx->router->dht()->impl->Nodes()->nodes.size())
{
// llarp::Info("checkOnline - Going to say we're online");
request->online = true;
}
request->hook(request);
// reschedue our self
llarp_main_queryDHT(request);
}
void
llarp_main_queryDHT_online(struct check_online_request *request)
{
// Info("llarp_main_queryDHT_online: ", request->online ? "online" :
// "offline");
if(request->online && !request->first)
{
request->first = true;
llarp::LogInfo("llarp_main_queryDHT_online - We're online");
llarp::LogInfo("llarp_main_queryDHT_online - Querying DHT");
llarp_dht_lookup_router(request->ptr->ctx->router->dht(), request->job);
}
}
void
llarp_main_queryDHT(struct check_online_request *request)
{
// llarp::Info("llarp_main_queryDHT - setting up timer");
request->hook = &llarp_main_queryDHT_online;
request->ptr->ctx->router->logic()->call_later(
{1000, request, &llarp_main_checkOnline});
// llarp_dht_lookup_router(ptr->ctx->router->dht, job);
}
llarp::handlers::TunEndpoint *
main_router_getFirstTunEndpoint(struct llarp_main *ptr)
{
if(ptr && ptr->ctx && ptr->ctx->router)
return ptr->ctx->router->hiddenServiceContext().getFirstTun();
return nullptr;
}
bool
main_router_endpoint_iterator(
struct llarp_main *ptr, struct llarp::service::Context::endpoint_iter &i)
{
return ptr->ctx->router->hiddenServiceContext().iterate(i);
}
llarp_tun_io *
main_router_getRange(struct llarp_main *ptr)
{
return ptr->ctx->router->hiddenServiceContext().getRange();
}
*/
const char *
handleBaseCmdLineArgs(int argc, char *argv[])
{

View file

@ -0,0 +1 @@
#include <crypto/crypto_noop.hpp>

View file

@ -0,0 +1,186 @@
#ifndef LLARP_CRYPTO_NOOP_HPP
#define LLARP_CRYPTO_NOOP_HPP
#include <crypto/crypto.hpp>
#include <atomic>
#include <numeric>
namespace llarp
{
struct NoOpCrypto final : public Crypto
{
private:
std::atomic_uint64_t m_value;
static constexpr byte_t MAX_BYTE = std::numeric_limits< byte_t >::max();
public:
NoOpCrypto() : m_value(0)
{
}
~NoOpCrypto() = default;
bool
xchacha20(const llarp_buffer_t &, const SharedSecret &,
const TunnelNonce &) override
{
return true;
}
bool
xchacha20_alt(const llarp_buffer_t &out, const llarp_buffer_t &in,
const SharedSecret &, const byte_t *) override
{
if(in.sz > out.sz)
{
return false;
}
std::copy_n(in.begin(), in.sz, out.begin());
return true;
}
bool
dh_client(SharedSecret &shared, const PubKey &pk, const SecretKey &,
const TunnelNonce &) override
{
std::copy_n(pk.begin(), pk.size(), shared.begin());
return true;
}
bool
dh_server(SharedSecret &shared, const PubKey &pk, const SecretKey &,
const TunnelNonce &) override
{
std::copy_n(pk.begin(), pk.size(), shared.begin());
return true;
}
bool
transport_dh_client(SharedSecret &shared, const PubKey &pk,
const SecretKey &, const TunnelNonce &) override
{
std::copy_n(pk.begin(), pk.size(), shared.begin());
return true;
}
bool
transport_dh_server(SharedSecret &shared, const PubKey &pk,
const SecretKey &, const TunnelNonce &) override
{
std::copy_n(pk.begin(), pk.size(), shared.begin());
return true;
}
bool
shorthash(ShortHash &out, const llarp_buffer_t &buff) override
{
// copy the first 32 bytes of the buffer
if(buff.sz < out.size())
{
std::copy_n(buff.begin(), buff.sz, out.begin());
std::fill(out.begin() + buff.sz, out.end(), 0);
}
else
{
std::copy_n(buff.begin(), out.size(), out.begin());
}
return true;
}
bool
hmac(byte_t *out, const llarp_buffer_t &buff, const SharedSecret &) override
{
if(buff.sz < HMACSIZE)
{
std::copy_n(buff.begin(), buff.sz, out);
std::fill(out + buff.sz, out + (HMACSIZE - buff.sz), 0);
}
else
{
std::copy_n(buff.begin(), HMACSIZE, out);
}
return true;
}
bool
sign(Signature &sig, const SecretKey &key, const llarp_buffer_t &) override
{
static_assert(Signature::SIZE == SecretKey::SIZE, "");
std::copy(key.begin(), key.end(), sig.begin());
return true;
}
bool
verify(const PubKey &, const llarp_buffer_t &, const Signature &) override
{
return true;
}
bool
seed_to_secretkey(SecretKey &key, const IdentitySecret &secret) override
{
static_assert(SecretKey::SIZE == (2 * IdentitySecret::SIZE), "");
std::copy(secret.begin(), secret.end(), key.begin());
std::copy(secret.begin(), secret.end(),
key.begin() + IdentitySecret::SIZE);
return true;
}
void
randomize(const llarp_buffer_t &buff) override
{
std::iota(buff.begin(), buff.end(), m_value.load() % MAX_BYTE);
m_value += buff.sz;
}
void
randbytes(byte_t *ptr, size_t sz) override
{
std::iota(ptr, ptr + sz, m_value.load() % MAX_BYTE);
m_value += sz;
}
void
identity_keygen(SecretKey &key) override
{
std::iota(key.begin(), key.end(), m_value.load() % MAX_BYTE);
m_value += key.size();
}
void
encryption_keygen(SecretKey &key) override
{
std::iota(key.begin(), key.end(), m_value.load() % MAX_BYTE);
m_value += key.size();
}
void
pqe_keygen(PQKeyPair &pair) override
{
std::iota(pair.begin(), pair.end(), m_value.load() % MAX_BYTE);
m_value += pair.size();
}
bool
pqe_decrypt(const PQCipherBlock &block, SharedSecret &secret,
const byte_t *) override
{
std::copy_n(block.begin(), SharedSecret::SIZE, secret.begin());
return true;
}
bool
pqe_encrypt(PQCipherBlock &block, SharedSecret &secret,
const PQPubKey &) override
{
std::copy_n(secret.begin(), SharedSecret::SIZE, block.begin());
return true;
}
};
} // namespace llarp
#endif

View file

@ -114,6 +114,13 @@ struct llarp_buffer_t
{
}
// clang-format off
byte_t * begin() { return base; }
byte_t * begin() const { return base; }
byte_t * end() { return base + sz; }
byte_t * end() const { return base + sz; }
// clang-format on
size_t
size_left() const;