initial commit
This commit is contained in:
commit
14970dbc7e
9 files changed
+369
No files matched your search
@@ -0,0 +1,4 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
rust-analyzer.log
|
||||
*.pem
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "rns-vpn"
|
||||
description = "Reticulum VPN"
|
||||
version = "0.1.0"
|
||||
license = "MIT"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
clap = { version= "4.*", features= ["derive"] }
|
||||
ed25519-dalek = { version = "2.*", features = ["pem", "pkcs8"] }
|
||||
env_logger = "0.11.*"
|
||||
etherparse = "0.19.*"
|
||||
ipnet = { version = "2.*", features = ["serde"] }
|
||||
log = "0.4.*"
|
||||
nix = "0.23.*"
|
||||
pem = "3.*"
|
||||
rand_core = { version = "0.6.*", features = ["getrandom"] }
|
||||
riptun = { version = "0.1.*", default-features = false, features = ["tokio-impl"] }
|
||||
serde = { version = "1.*", features = ["derive"] }
|
||||
tokio = { version = "1.44.*", features = ["full"] }
|
||||
toml = "0.8.*"
|
||||
x25519-dalek = "2.*"
|
||||
|
||||
[dependencies.reticulum]
|
||||
git = "https://github.com/BeechatNetworkSystemsLtd/Reticulum-rs"
|
||||
#path = "../../remote/Reticulum-rs"
|
||||
version = "0.1.*"
|
||||
@@ -0,0 +1,4 @@
|
||||
vpn_ip = "10.0.0.1/24"
|
||||
|
||||
[peers]
|
||||
"10.0.0.2/24" = "xxx"
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
cargo build
|
||||
RUST_LOG=debug RUST_BACKTRACE=1 \
|
||||
sudo -E nnd target/debug/rns-vpn -p 4242 -f 127.0.0.1:4243 -i "vpn-test-client"
|
||||
|
||||
exit 0
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
openssl genpkey -algorithm ed25519 -out signkey.pem
|
||||
openssl genpkey -algorithm X25519 -out privkey.pem
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e
|
||||
set -x
|
||||
|
||||
cargo build
|
||||
RNS_VPN_PRIVKEY_PATH="./privkey.pem" \
|
||||
RNS_VPN_SIGNKEY_PATH="./signkey.pem" \
|
||||
RUST_LOG=debug RUST_BACKTRACE=1 \
|
||||
sudo -E target/debug/rns-vpn -p 4242 -f 127.0.0.1:4243 #-i "vpn-test-client"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,14 @@
|
||||
with import <nixpkgs> {};
|
||||
let
|
||||
unstable = import
|
||||
(fetchTarball https://github.com/NixOS/nixpkgs/archive/nixos-unstable.tar.gz) {};
|
||||
in
|
||||
mkShell {
|
||||
buildInputs = [
|
||||
gdb
|
||||
openssl
|
||||
protobuf
|
||||
rustup
|
||||
unstable.nnd
|
||||
];
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ipnet::IpNet;
|
||||
use log;
|
||||
use reticulum::destination::DestinationName;
|
||||
use reticulum::destination::link::{LinkEvent, LinkId};
|
||||
use reticulum::hash::AddressHash;
|
||||
use reticulum::identity::PrivateIdentity;
|
||||
use reticulum::transport::Transport;
|
||||
|
||||
use riptun::TokioTun;
|
||||
|
||||
// TODO: config?
|
||||
const TUN_NQUEUES : usize = 1;
|
||||
const MTU: usize = 1500;
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Config {
|
||||
pub vpn_ip: IpNet,
|
||||
/// Map of (IP, destination)
|
||||
// TODO: deserialize AddressHash
|
||||
pub peers: BTreeMap<IpNet, String>
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
config: Config,
|
||||
tun: Tun
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CreateClientError {
|
||||
RiptunError(riptun::Error),
|
||||
IpAddBroadcastError(std::io::Error),
|
||||
IpLinkUpError(std::io::Error),
|
||||
IpRouteAddError(std::io::Error),
|
||||
IptablesError(std::io::Error)
|
||||
}
|
||||
|
||||
struct Tun {
|
||||
tun: TokioTun,
|
||||
read_buf: tokio::sync::Mutex<[u8; MTU]>
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub fn new(config: Config) -> Result<Self, CreateClientError> {
|
||||
let tun = Tun::new(config.vpn_ip)?;
|
||||
Ok(Client { config, tun })
|
||||
}
|
||||
|
||||
pub async fn run(&self, mut transport: Transport, id: PrivateIdentity) {
|
||||
let in_destination = transport
|
||||
.add_destination(id, DestinationName::new("rns_vpn", "client")).await;
|
||||
let in_destination_hash = in_destination.lock().await.desc.address_hash;
|
||||
log::info!("created in destination: {}", in_destination_hash);
|
||||
// send announces
|
||||
let announce_loop = async || loop {
|
||||
transport.send_announce(&in_destination, None).await;
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
};
|
||||
let link_id: Arc<tokio::sync::Mutex<Option<LinkId>>> = Arc::new(tokio::sync::Mutex::new(None));
|
||||
// tun loop
|
||||
let tun_loop = async || while let Ok(bytes) = self.tun.read().await {
|
||||
log::trace!("got tun bytes ({})", bytes.len());
|
||||
let link_id = link_id.lock().await;
|
||||
if let Some(link_id) = link_id.as_ref() {
|
||||
log::trace!("sending on link ({})", link_id);
|
||||
let link = transport.find_in_link(link_id).await.unwrap();
|
||||
let link = link.lock().await;
|
||||
let packet = link.data_packet(&bytes).unwrap();
|
||||
transport.send_packet(packet).await;
|
||||
}
|
||||
};
|
||||
// upstream link data
|
||||
let link_loop = async || {
|
||||
let mut peer_map = BTreeMap::new();
|
||||
for (ip, dest) in self.config.peers.iter() {
|
||||
let dest = match AddressHash::new_from_hex_string(dest.as_str()) {
|
||||
Ok(dest) => dest,
|
||||
Err(err) => {
|
||||
log::error!("error parsing peer destination hash: {err:?}");
|
||||
return
|
||||
}
|
||||
};
|
||||
assert!(peer_map.insert(*ip, dest).is_none());
|
||||
}
|
||||
let mut in_link_events = transport.in_link_events();
|
||||
while let Ok(link_event) = in_link_events.recv().await {
|
||||
match link_event.event {
|
||||
LinkEvent::Data(payload) => if link_event.address_hash == in_destination_hash {
|
||||
log::trace!("link {} payload ({})", link_event.id, payload.len());
|
||||
match self.tun.send(payload.as_slice()).await {
|
||||
Ok(n) => log::trace!("tun sent {n} bytes"),
|
||||
Err(err) => {
|
||||
log::error!("tun error sending bytes: {err:?}");
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
LinkEvent::Activated => if link_event.address_hash == in_destination_hash {
|
||||
log::debug!("link activated {}", link_event.id);
|
||||
let mut link_id = link_id.lock().await;
|
||||
*link_id = Some(link_event.id);
|
||||
}
|
||||
LinkEvent::Closed => if link_event.address_hash == in_destination_hash {
|
||||
log::debug!("link closed {}", link_event.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
tokio::select!{
|
||||
_ = announce_loop() => log::info!("announce loop exited: shutting down"),
|
||||
_ = tun_loop() => log::info!("tun loop exited: shutting down"),
|
||||
_ = link_loop() => log::info!("link loop exited: shutting down"),
|
||||
_ = tokio::signal::ctrl_c() => log::info!("got ctrl-c: shutting down")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Tun {
|
||||
pub fn new(ip: IpNet) -> Result<Self, CreateClientError> {
|
||||
log::debug!("creating tun device");
|
||||
let ip: IpNet = ip.into();
|
||||
let tun = TokioTun::new("rip%d", TUN_NQUEUES).map_err(CreateClientError::RiptunError)?;
|
||||
log::debug!("created tun device: {}", tun.name());
|
||||
log::debug!("adding broadcast ip addr: {}", ip);
|
||||
let output = std::process::Command::new("ip")
|
||||
.arg("addr")
|
||||
.arg("add")
|
||||
.arg(ip.to_string())
|
||||
.arg("brd")
|
||||
.arg(ip.addr().to_string())
|
||||
.arg("dev")
|
||||
.arg(tun.name())
|
||||
.output()
|
||||
.map_err(CreateClientError::IpAddBroadcastError)?;
|
||||
if !output.status.success() {
|
||||
return Err(CreateClientError::IpAddBroadcastError(
|
||||
std::io::Error::other(format!("ip addr add command failed ({:?})",
|
||||
output.status.code())).into()));
|
||||
}
|
||||
log::debug!("{} setting link up", tun.name());
|
||||
let output = std::process::Command::new("ip")
|
||||
.arg("link")
|
||||
.arg("set")
|
||||
.arg("dev")
|
||||
.arg(tun.name())
|
||||
.arg("up")
|
||||
.output()
|
||||
.map_err(CreateClientError::IpLinkUpError)?;
|
||||
if !output.status.success() {
|
||||
return Err(CreateClientError::IpLinkUpError(
|
||||
std::io::Error::other(format!("ip link set command failed ({:?})", output.status.code()))))
|
||||
}
|
||||
let adapter = Tun {
|
||||
tun, read_buf: tokio::sync::Mutex::new([0x0; MTU])
|
||||
};
|
||||
Ok(adapter)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn tun(&self) -> &TokioTun {
|
||||
&self.tun
|
||||
}
|
||||
|
||||
// TODO: can we return a lock of &[u8] to avoid creating vec?
|
||||
pub async fn read(&self) -> Result<Vec<u8>, std::io::Error> {
|
||||
let mut buf = self.read_buf.lock().await;
|
||||
let nbytes = self.tun.recv(&mut buf[..]).await?;
|
||||
Ok(buf[..nbytes].to_vec())
|
||||
}
|
||||
|
||||
pub async fn send(&self, datagram: &[u8]) -> Result<usize, std::io::Error> {
|
||||
self.tun.send(datagram).await
|
||||
}
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
//! Reticulum VPN client
|
||||
|
||||
use std::{fs, process};
|
||||
|
||||
use clap::Parser;
|
||||
use ed25519_dalek;
|
||||
use env_logger;
|
||||
use log;
|
||||
use pem;
|
||||
use reticulum::identity::PrivateIdentity;
|
||||
use reticulum::iface::udp::UdpInterface;
|
||||
use reticulum::transport::{Transport, TransportConfig};
|
||||
use tokio;
|
||||
use x25519_dalek;
|
||||
|
||||
use rns_vpn;
|
||||
|
||||
const CONFIG_PATH: &str = "Config.toml";
|
||||
|
||||
/// Command line arguments
|
||||
#[derive(Parser)]
|
||||
#[command(name = "Reticulum VPN Client", version)]
|
||||
pub struct Command {
|
||||
/// Reticulum UDP listen port number
|
||||
#[arg(short, long)]
|
||||
pub port: u16,
|
||||
/// Reticulum UDP forward link address
|
||||
#[arg(short, long)]
|
||||
pub forward: std::net::SocketAddr,
|
||||
/// [Optional] Reticulum private ID from name string
|
||||
#[arg(short, long)]
|
||||
pub id_string: Option<String>
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// parse command line args
|
||||
let cmd = Command::parse();
|
||||
// load config
|
||||
let config: rns_vpn::Config = {
|
||||
let s = fs::read_to_string(CONFIG_PATH).unwrap();
|
||||
toml::from_str(&s).unwrap()
|
||||
};
|
||||
/*FIXME:debug*/ println!("{:?}", std::env::var("RUST_LOG"));
|
||||
// init logging
|
||||
env_logger::Builder::from_env(env_logger::Env::default()).init();
|
||||
log::info!("client start with port {} and forward IP {}", cmd.port, cmd.forward);
|
||||
// client
|
||||
let client = match rns_vpn::Client::new(config) {
|
||||
Ok(client) => client,
|
||||
Err(err) => match err {
|
||||
rns_vpn::CreateClientError::RiptunError(riptun::Error::Unix {
|
||||
source: nix::errno::Errno::EPERM
|
||||
}) => {
|
||||
log::error!("EPERM error creating VPN client: need to run with root permissions");
|
||||
process::exit(1)
|
||||
}
|
||||
_ => {
|
||||
log::error!("error creating VPN client: {:?}", err);
|
||||
process::exit(1)
|
||||
}
|
||||
}
|
||||
};
|
||||
// start reticulum
|
||||
log::info!("starting reticulum");
|
||||
let id = if let Some(name) = cmd.id_string {
|
||||
log::info!("using identity string to create reticulum private identity: {name:?}");
|
||||
PrivateIdentity::new_from_name(&name)
|
||||
} else {
|
||||
log::info!("loading reticulum private identity parameters");
|
||||
let private_key = {
|
||||
let path = std::env::var("RNS_VPN_PRIVKEY_PATH").map_err(|err|{
|
||||
log::error!("env variable RNS_VPN_PRIVKEY_PATH not found: {err:?}");
|
||||
process::exit(1)
|
||||
}).unwrap();
|
||||
log::info!("loading privkey: {path}");
|
||||
let pem_data = fs::read(&path).map_err(|err|{
|
||||
log::error!("failed to read privkey {path}: {err:?}");
|
||||
process::exit(1)
|
||||
}).unwrap();
|
||||
let pem = pem::parse(pem_data).map_err(|err|{
|
||||
log::error!("failed to parse privkey {path}: {err:?}");
|
||||
process::exit(1)
|
||||
}).unwrap();
|
||||
let pem_bytes: [u8; 32] = pem.contents()[pem.contents().len()-32..].try_into()
|
||||
.map_err(|err|{
|
||||
log::error!("invalid privkey bytes: {err:?}");
|
||||
process::exit(1)
|
||||
}).unwrap();
|
||||
x25519_dalek::StaticSecret::from(pem_bytes)
|
||||
};
|
||||
let sign_key = {
|
||||
use ed25519_dalek::pkcs8::DecodePrivateKey;
|
||||
let path = std::env::var("RNS_VPN_SIGNKEY_PATH").map_err(|err|{
|
||||
log::error!("env variable RNS_VPN_SIGNKEY_PATH not found: {err:?}");
|
||||
process::exit(1)
|
||||
}).unwrap();
|
||||
log::info!("loading signkey: {path}");
|
||||
ed25519_dalek::SigningKey::read_pkcs8_pem_file(&path).map_err(|err|{
|
||||
log::error!("failed to parse signkey {path}: {err:?}");
|
||||
}).unwrap()
|
||||
};
|
||||
PrivateIdentity::new(private_key, sign_key)
|
||||
};
|
||||
let transport = Transport::new(TransportConfig::new("server", &id, true));
|
||||
let _ = transport.iface_manager().lock().await.spawn(
|
||||
UdpInterface::new(format!("0.0.0.0:{}", cmd.port), Some(cmd.forward.to_string())),
|
||||
UdpInterface::spawn);
|
||||
// run
|
||||
client.run(transport, id).await;
|
||||
log::info!("server exit");
|
||||
}
|
||||
Reference in new issue
Block a user