26 Commits

Author SHA1 Message Date
shimunn
f3717ce132 Streamlined Dockerfile [CI SKIP] 2019-04-03 01:42:23 +02:00
shimunn
aff9648e00 Streamlined Dockerfile 2019-04-03 01:42:05 +02:00
5976ddecdf source --log option via env
Some checks are pending
continuous-integration/drone/push Build is failing
2019-04-02 18:38:45 +02:00
8ea6d6e78d complete oxidation
Some checks are pending
continuous-integration/drone/push Build was killed
2019-03-31 18:07:32 +02:00
819eb7d362 integrate old code
Some checks are pending
continuous-integration/drone/push Build is running
2019-03-31 18:04:01 +02:00
fb7d706dae implemented Display [CI SKIP] 2019-03-30 23:45:22 +01:00
b72ca91423 replaced Duration with SystemTime where applicable, implemented Display 2019-03-30 23:44:09 +01:00
a6af494cb9 progress [CI SKIP] 2019-03-30 17:53:27 +01:00
a8be702e88 added interface function [CI SKIP] 2019-03-30 14:30:55 +01:00
0f50dc3e00 figure out why no peers are being produced [CI SKIP] 2019-03-30 14:29:05 +01:00
90f9d4cd36 basic main loop [CI SKIP] 2019-03-30 14:28:30 +01:00
9c5e14cd4e upload script [CI SKIP] 2019-03-30 14:23:39 +01:00
1255a0ed7b parse psk [CI SKIP] 2019-03-30 13:41:22 +01:00
d363fb2401 abstract over base64 [CI SKIP] 2019-03-30 13:41:03 +01:00
shimunn
90d35895e2 switch to boringtun
Some checks are pending
continuous-integration/drone/push Build encountered an error
2019-03-27 21:32:57 +01:00
Drone CI
9993a8f7a4 Compiles [WIP][CI SKIP] 2019-03-20 16:28:16 +01:00
Drone CI
fac5c7c442 closer [CI SKIP] 2019-03-19 15:23:06 +01:00
Drone CI
7491902b34 basic strcuture [CI SKIP] 2019-03-19 12:05:31 +01:00
shimunn
fc494fe4c0 WIP [CI SKIP] 2019-03-19 11:09:10 +01:00
shimunn
22dd07cc14 fail on socket error per default
Some checks are pending
continuous-integration/drone/push Build is passing
2019-03-16 20:34:16 +01:00
shimunn
3b4f13aa44 Merge branch 'structop' 2019-01-25 23:12:21 +01:00
shimunn
0e7ff7293b addrem feature 2019-01-25 23:11:58 +01:00
shimunn
7cf669e619 cargo-fmt 2019-01-25 23:11:30 +01:00
shimunn
804a7fec47 removed unused
Some checks are pending
continuous-integration/drone/push Build encountered an error
2019-01-19 21:00:18 +01:00
shimunn
67cda61245 removed legacy code 2019-01-19 20:56:22 +01:00
shimunn
11411b9d13 lil alias 2019-01-19 20:30:43 +01:00
17 changed files with 580 additions and 325 deletions

View File

@@ -19,15 +19,15 @@ steps:
image: alpine/git
commands:
- git submodule update --recursive --remote --init
- name: wireguard-go
- name: boringtun
image: plugins/docker
settings:
repo: repo.shimun.net/shimun/wireguard-user
tag: build-wireguard-go
tag: build-boringtun
registry: repo.shimun.net
cache_from: ["repo.shimun.net/shimun/wireguard-user:build-wireguard-go", "repo.shimun.net/shimun/wireguard-user:build-event-gen"]
cache_from: ["repo.shimun.net/shimun/wireguard-user:build-boringtun", "repo.shimun.net/shimun/wireguard-user:build-event-gen"]
storage_path: "/drone/docker"
target: build
target: boringbuild
username:
from_secret: docker_username
password:
@@ -37,7 +37,7 @@ steps:
settings:
repo: repo.shimun.net/shimun/wireguard-user
registry: repo.shimun.net
cache_from: ["repo.shimun.net/shimun/wireguard-user:build-wireguard-go", "repo.shimun.net/shimun/wireguard-user:build-event-gen", "repo.shimun.net/shimun/wireguard-user"]
cache_from: ["repo.shimun.net/shimun/wireguard-user:build-boringtun", "repo.shimun.net/shimun/wireguard-user:build-event-gen", "repo.shimun.net/shimun/wireguard-user"]
storage_path: "/drone/docker"
username:
from_secret: docker_username

6
.gitmodules vendored
View File

@@ -1,3 +1,3 @@
[submodule "wireguard-go"]
path = wireguard-go
url = https://git.zx2c4.com/wireguard-go
[submodule "boringtun"]
path = boringtun
url = https://github.com/cloudflare/boringtun.git

View File

@@ -1,32 +1,38 @@
FROM rust:1.32-slim AS eventbuild
FROM rust:1.33-slim AS rustbuild
FROM rustbuild AS eventbuild
ARG MODE=--release
WORKDIR /build
COPY wg-event-gen/Cargo.* /build/
RUN rustup target add x86_64-unknown-linux-musl
RUN mkdir -p src && echo "fn main() {}" > src/main.rs && cargo build --release --target x86_64-unknown-linux-musl
COPY wg-event-gen/Cargo.* /build/
RUN mkdir -p src && echo "fn main() {}" > src/main.rs && cargo build $MODE --target x86_64-unknown-linux-musl
COPY wg-event-gen/ /build
RUN cargo build --target x86_64-unknown-linux-musl
RUN cargo build --target x86_64-unknown-linux-musl $MODE
FROM frolvlad/alpine-glibc AS test
COPY --from=eventbuild /build/target/x86_64-unknown-linux-musl/debug/wg-event-gen /usr/bin/
FROM rustbuild AS boringbuild
RUN echo "d41d8cd98f00b204e9800998ecf8427e -" > test.md5 && wg-event-gen | md5sum -c test.md5
ARG MODE=--release
FROM golang AS build
WORKDIR /build
COPY wireguard-go /go/src/wireguard
RUN rustup target add x86_64-unknown-linux-musl
WORKDIR /go/src/wireguard
COPY boringtun/Cargo.* /build/
RUN echo "package main" > ./donotuseon_linux.go && go get
RUN mkdir -p src && echo "fn main() {}" > src/main.rs && touch src/lib.rs && cargo build $MODE #--target x86_64-unknown-linux-musl #Ring won't compile https://github.com/briansmith/ring/issues/713
COPY boringtun/ /build
RUN cargo build $MODE #--target x86_64-unknown-linux-musl
RUN go build
FROM frolvlad/alpine-glibc
@@ -34,13 +40,15 @@ RUN echo http://nl.alpinelinux.org/alpine/edge/testing >> /etc/apk/repositories
ENV WG_I_PREFER_BUGGY_USERSPACE_TO_POLISHED_KMOD=1
COPY --from=build /go/bin/wireguard /usr/bin/wireguard-go
ARG MODE=--release
COPY --from=eventbuild /build/target/x86_64-unknown-linux-musl/debug/wg-event-gen /usr/bin/
COPY --from=eventbuild /build/target/x86_64-unknown-linux-musl/*/wg-event-gen /usr/bin/
COPY --from=boringbuild /build/target/*/boringtun /usr/bin/
COPY init.sh /init.sh
RUN chmod +x /init.sh
RUN chmod +x /init.sh && echo 'alias nload="nload ${WG_INTERFACE:-wg0}"' >> /root/.bashrc
VOLUME /etc/wireguard/

View File

@@ -5,3 +5,8 @@ build:
push: build
docker push ${REPO}
pull:
docker pull ${REPO}
docker pull ${REPO}:build-event-gen
docker pull ${REPO}:build-boringtun

1
boringtun Submodule

Submodule boringtun added at cabd969874

View File

@@ -27,7 +27,7 @@ function setup_iptables() {
iptables -t nat -$1 POSTROUTING -s $ADDRESS -o $PHY_IF -j MASQUERADE;
}
/usr/bin/wireguard-go $WG_IF
/usr/bin/boringtun $WG_IF
if [ ! -f "/etc/wireguard/$WG_IF.conf" ]; then
mkdir -p /etc/wireguard/keys

View File

@@ -48,6 +48,65 @@ dependencies = [
"vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "darling"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"darling_core 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)",
"darling_macro 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "darling_core"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)",
"ident_case 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "darling_macro"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"darling_core 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "derive_builder"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"darling 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)",
"derive_builder_core 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "derive_builder_core"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"darling 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "fnv"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "heck"
version = "0.3.1"
@@ -61,6 +120,11 @@ name = "hex"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "libc"
version = "0.2.47"
@@ -68,7 +132,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "proc-macro2"
version = "0.4.25"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -79,7 +143,7 @@ name = "quote"
version = "0.6.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"proc-macro2 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -115,7 +179,7 @@ version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -125,7 +189,7 @@ name = "syn"
version = "0.15.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"proc-macro2 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)",
"proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)",
"quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)",
"unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -183,6 +247,7 @@ name = "wg-event-gen"
version = "0.1.0"
dependencies = [
"base64 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)",
"derive_builder 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
"hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)",
"structopt 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)",
"structopt-derive 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -215,10 +280,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12"
"checksum byteorder 1.2.7 (registry+https://github.com/rust-lang/crates.io-index)" = "94f88df23a25417badc922ab0f5716cc1330e87f71ddd9203b3a3ccd9cedf75d"
"checksum clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b957d88f4b6a63b9d70d5f454ac8011819c6efa7727858f458ab71c756ce2d3e"
"checksum darling 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)" = "9158d690bc62a3a57c3e45b85e4d50de2008b39345592c64efd79345c7e24be0"
"checksum darling_core 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)" = "d2a368589465391e127e10c9e3a08efc8df66fd49b87dc8524c764bbe7f2ef82"
"checksum darling_macro 0.8.6 (registry+https://github.com/rust-lang/crates.io-index)" = "244e8987bd4e174385240cde20a3657f607fb0797563c28255c353b5819a07b1"
"checksum derive_builder 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a0ca533e6abb78f9108585535ce2ae0b14c8b4504e138a9a28eaf8ba2b270c1d"
"checksum derive_builder_core 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fb484fe06ba1dc5b82f88aff700191dfc127e02b06b35e302c169706168e2528"
"checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3"
"checksum heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
"checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77"
"checksum ident_case 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
"checksum libc 0.2.47 (registry+https://github.com/rust-lang/crates.io-index)" = "48450664a984b25d5b479554c29cc04e3150c97aa4c01da5604a2d4ed9151476"
"checksum proc-macro2 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)" = "d3797b7142c9aa74954e351fc089bbee7958cebbff6bf2815e7ffff0b19f547d"
"checksum proc-macro2 0.4.27 (registry+https://github.com/rust-lang/crates.io-index)" = "4d317f9caece796be1980837fd5cb3dfec5613ebdb04ad0956deea83ce168915"
"checksum quote 0.6.10 (registry+https://github.com/rust-lang/crates.io-index)" = "53fa22a1994bd0f9372d7a816207d8a2677ad0325b073f5c5332760f0fb62b5c"
"checksum redox_syscall 0.1.50 (registry+https://github.com/rust-lang/crates.io-index)" = "52ee9a534dc1301776eff45b4fa92d2c39b1d8c3d3357e6eb593e0d795506fc2"
"checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76"

View File

@@ -10,10 +10,13 @@ base64 = "0.10.0"
time = "0.1.42"
structopt = "0.2.14"
structopt-derive = "0.2.14"
derive_builder = "0.7.1"
[profile.release]
lto = true
[features]
default = ["addrem"]
addrem = []

View File

@@ -0,0 +1,138 @@
use crate::model::{
Base64Backed, ECCKey, Interface, Peer, PeerBuilder, SharedKey, WireguardController,
};
use std::io::{BufRead, BufReader, Error, ErrorKind, Result, Write};
use std::net::{IpAddr, SocketAddr};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::time::{Duration, Instant};
pub struct Userspace(PathBuf);
impl Userspace {
pub fn new<P: Into<PathBuf>>(path: P) -> Userspace {
Userspace(path.into())
}
}
impl WireguardController for Userspace {
fn peers<'a>(&'a mut self) -> Result<Box<Iterator<Item = Result<Peer>> + 'a>> {
let mut stream = UnixStream::connect(&self.0)?;
stream.write_all(b"get=1\n")?;
fn build_peer(builder: &mut PeerBuilder, line: Result<String>) -> Result<Option<Peer>> {
let line = line?;
fn parse_err<O, E: Into<Box<dyn std::error::Error + Sync + Send>>>(
res: std::result::Result<O, E>,
) -> Result<O> {
res.map_err(|err| Error::new(ErrorKind::InvalidData, err))
}
let mut iter = line.chars();
let key = iter.by_ref().take_while(|c| c != &'=').collect::<String>();
let value = iter.collect::<String>();
let value_as_num = || parse_err(value.parse::<u64>());
let mut peer: Option<Peer> = None;
let build_peer = |peer: &mut Option<Peer>, builder: &mut PeerBuilder| -> Result<()> {
let built: Result<Peer> = parse_err(builder.build());
*peer = Some(built?);
*builder = PeerBuilder::default();
Ok(())
};
let mut add_key = |peer: &mut Option<Peer>, key: ECCKey| -> Result<()> {
if builder.is_whole() {
build_peer(peer, builder)?;
} else {
*peer = None
}
builder.key(key);
Ok(())
};
match key.as_ref() {
"" => {
//Empty line means end of data
build_peer(&mut peer, builder)?; //TODO: handle possible actual error case
}
"public_key" => {
add_key(&mut peer, parse_err(ECCKey::from_base64(value))?)?;
}
"private_key" => {
add_key(&mut peer, ECCKey::from_base64(value)?)?;
}
"preshared_key" => {
builder.shared_key(Some(SharedKey::from_base64(value)?));
}
"endpoint" => {
builder.endpoint(Some(parse_err(value.parse::<SocketAddr>())?));
}
"last_handshake_time_sec" => {
builder.add_last_handshake(Duration::from_secs(value_as_num()?));
}
"last_handshake_time_nsec" => {
builder.add_last_handshake(Duration::from_nanos(value_as_num()?.into()));
}
"persistent_keepalive_interval" => {
builder.persistent_keepalive(Some(Duration::from_secs(value_as_num()?.into())));
}
"rx_bytes" => {
builder.add_traffic((parse_err(value.parse::<u64>())?, 0));
}
"tx_bytes" => {
builder.add_traffic((0, (parse_err(value.parse::<u64>())?)));
}
"allowed_ip" => {
let mut parts = value.split("/").into_iter();
let net = match (
parts.next().and_then(|addr| addr.parse::<IpAddr>().ok()),
parts.next().and_then(|mask| mask.parse::<u8>().ok()),
) {
(Some(addr), Some(mask)) => Some((addr, mask)),
(Some(addr), None) if addr.is_ipv6() => Some((addr, 128)),
(Some(addr), None) => Some((addr, 32)),
_ => None,
};
if let Some(net) = net {
builder.add_allowed_ip(net);
}
}
"errno" => match value_as_num()? {
0 => build_peer(&mut peer, builder)?,
code => Err(Error::new(
ErrorKind::Other,
format!("Returned error code: {}", code),
))?,
},
"listen_port" | "fwmark" | "private_key" => (), //Ignore for now
_ => Err(Error::new(
ErrorKind::InvalidData,
["Unknown key: \"", &key, "\""].join(""),
))?,
}
Ok(peer)
}
let peers = BufReader::new(stream)
.lines()
.scan(PeerBuilder::default(), |builder, line| {
match build_peer(builder, line) {
Ok(Some(value)) => Some(Some(Ok(value))),
Err(err) => {
eprintln!("{:?}", err);
None
} //TODO: propagate
_ => Some(None),
}
})
.flatten();
Ok(Box::new(peers))
}
fn interface(&mut self) -> Result<Interface> {
let mut stream = UnixStream::connect(&self.0)?;
stream.write_all(b"get=1\n")?;
unimplemented!("TODO: return iface")
}
fn update_peer(&mut self, peer: &Peer) -> Result<()> {
loop {}
}
}

View File

@@ -1,19 +1,11 @@
use crate::listener::*;
use crate::*;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fmt;
use std::io::prelude::*;
use std::io::{BufRead, BufReader, Error, ErrorKind, Result};
use std::net::SocketAddr;
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::rc::Rc;
use std::{thread, time};
use std::time;
pub(crate) fn gen_events(
state: &HashMap<String, Peer>,
prev: &HashMap<String, Peer>,
state: &HashMap<ECCKey, Peer>,
prev: &HashMap<ECCKey, Peer>,
listeners: &Vec<Box<EventListener>>,
timeout: time::Duration,
poll_interval: time::Duration,
@@ -21,20 +13,22 @@ pub(crate) fn gen_events(
let side_by_side = {
state
.keys()
.map(String::as_ref)
.chain(prev.keys().map(String::as_ref))
.collect::<HashSet<&str>>()
.chain(prev.keys())
.collect::<HashSet<&ECCKey>>()
.iter()
.map(|p| (*p, (prev.get(*p), state.get(*p))))
.collect::<HashMap<&str, (Option<&Peer>, Option<&Peer>)>>()
.collect::<HashMap<&ECCKey, (Option<&Peer>, Option<&Peer>)>>()
};
for (_id, (prev, cur)) in side_by_side {
match (prev, cur) {
(Some(prev), Some(cur)) => {
let timedout = |peer: &Peer| match peer.last_handshake_rel() {
Some(shake) if shake > timeout && shake + poll_interval < timeout => true,
Some(_) => false,
_ => true,
let timedout = |peer: &Peer| {
peer.last_handshake
.map(|shake| {
shake.elapsed().unwrap() > timeout
|| shake.elapsed().unwrap() + poll_interval < timeout
})
.unwrap_or(true)
};
if let (Some(prev_addr), Some(cur_addr)) = (prev.endpoint, cur.endpoint) {
@@ -115,7 +109,7 @@ mod test {
.push(format!("rem {}", peer.public_key));
}
fn roaming<'a>(&self, peer: &'a Peer, previous_addr: SocketAddr) {
fn roaming<'a>(&self, peer: &'a Peer, _previous_addr: SocketAddr) {
self.calls
.borrow_mut()
.push(format!("rom {}", peer.public_key));
@@ -227,7 +221,7 @@ mod test {
calls.borrow_mut().clear();
let mut peer_prev = peer.clone();
let peer_prev = peer.clone();
peer_cur.last_handshake = Some(time::Duration::from_secs(5));

View File

@@ -3,6 +3,7 @@ use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::Command;
use std::thread;
use std::time::SystemTime;
pub trait EventListener {
fn added<'a>(&self, peer: &'a Peer) {
@@ -50,25 +51,25 @@ pub struct LogListener;
impl EventListener for LogListener {
fn connected<'a>(&self, peer: &'a Peer) {
println!("{} connected!", peer.public_key);
println!("{} connected!", peer.key);
}
fn disconnected<'a>(&self, peer: &'a Peer) {
println!("{} disconnected!", peer.public_key);
println!("{} disconnected!", peer.key);
}
fn added<'a>(&self, peer: &'a Peer) {
println!("{} added!", peer.public_key);
println!("{} added!", peer.key);
}
fn removed<'a>(&self, peer: &'a Peer) {
println!("{} removed!", peer.public_key);
println!("{} removed!", peer.key);
}
fn roaming<'a>(&self, peer: &'a Peer, previous_addr: SocketAddr) {
println!(
"{} roamed {} -> {}!",
peer.public_key,
peer.key,
previous_addr,
peer.endpoint.unwrap()
);
@@ -87,7 +88,7 @@ impl ScriptListener {
fn peer_props<'a>(&self, peer: &'a Peer) -> String {
format!(
"{id} {allowed_ips} {endpoint} {last_handshake} {persistent_keepalive} {traffic}",
id = peer.public_key,
id = peer.key,
allowed_ips = peer
.allowed_ips
.iter()
@@ -100,7 +101,7 @@ impl ScriptListener {
.unwrap_or("0".to_owned()),
last_handshake = peer
.last_handshake
.map(|s| s.as_secs() as i64)
.map(|s| s.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as i64)
.unwrap_or(-1),
persistent_keepalive = peer
.persistent_keepalive

View File

@@ -1,278 +1,83 @@
#[macro_use]
extern crate structopt;
#[macro_use]
extern crate derive_builder;
mod controller;
mod gen;
mod listener;
mod model;
mod opts;
use crate::gen::*;
use crate::gen::gen_events;
use crate::listener::*;
use base64;
use hex;
use crate::model::{ECCKey, Peer};
use controller::Userspace;
use model::WireguardController;
use opts::Opts;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::io::prelude::*;
use std::io::{BufRead, BufReader, Error, ErrorKind, Result};
use std::net::{IpAddr, SocketAddr};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::thread;
use std::time::Duration;
use std::io;
use std::thread::sleep;
use std::time::{Duration, Instant};
use structopt::StructOpt;
use time;
pub type KV = (String, String);
#[derive(Debug, PartialEq, Eq, Hash)]
enum State {
Interface(Vec<KV>),
Peer(Vec<KV>),
fn listeners(opts: &Opts) -> Vec<Box<EventListener>> {
let mut listeners: Vec<Box<EventListener>> = Vec::with_capacity(2);
if let Some(events) = opts.events.clone() {
listeners.push(Box::new(ScriptListener::new(events)))
}
if opts.log {
listeners.push(Box::new(LogListener));
}
listeners
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Peer {
public_key: String,
endpoint: Option<SocketAddr>,
allowed_ips: Vec<(IpAddr, u8)>,
last_handshake: Option<Duration>,
persistent_keepalive: Option<Duration>,
traffic: (u64, u64),
parsed: time::Timespec,
}
fn main() -> io::Result<()> {
let opts = Opts::from_args();
let mut controller: Box<WireguardController> = Box::new(Userspace::new(opts.socket.clone()));
let interval = Duration::from_millis(opts.poll);
let timeout = Duration::from_secs(opts.timeout);
let listeners = listeners(&opts);
impl Peer {
fn from_kv(entries: &Vec<KV>) -> Result<Peer> {
let key = match entries
.iter()
.filter(|(key, _)| key == &"public_key")
.map(|(_, value)| value)
.next()
println!(
"Polling {} every {:?}",
opts.socket.to_str().unwrap(),
interval
);
let mut peers_last: Option<HashMap<ECCKey, Peer>> = None;
loop {
let now = Instant::now();
let peers = controller.peers()?;
/*println!("Connected peers:");
for peer in peers {
let peer = peer?;
if peer
.last_handshake
.map(|h| h.elapsed().unwrap() < timeout)
.unwrap_or(false)
{
Some(key) => key,
None => return Err(Error::new(ErrorKind::Other, "Peer is missing key")),
};
Ok(Peer {
public_key: base64::encode(&hex::decode(key).unwrap()),
endpoint: entries
.iter()
.filter(|(key, _)| key == &"endpoint")
.map(|(_, value)| value.parse::<SocketAddr>().unwrap())
.next(),
allowed_ips: entries
.iter()
.filter(|(key, _)| key == &"allowed_ip")
.map(|(_, value)| {
let mut parts = value.split("/").into_iter();
match (
parts.next().and_then(|addr| addr.parse::<IpAddr>().ok()),
parts.next().and_then(|mask| mask.parse::<u8>().ok()),
) {
(Some(addr), Some(mask)) => Some((addr, mask)),
(Some(addr), None) if addr.is_ipv6() => Some((addr, 128)),
(Some(addr), None) => Some((addr, 32)),
_ => None,
println!("/\\{:?} {}",(timeout - peer.last_handshake.unwrap().elapsed().unwrap()), peer);
}
})
.filter_map(|net| net)
.collect::<Vec<(IpAddr, u8)>>(),
last_handshake: entries
.iter()
.filter_map(|(key, value)| {
let value = || value.parse::<u64>().unwrap();
match key.as_ref() {
"last_handshake_time_sec" if value() != 0 => {
Some(Duration::new(value(), 0))
}
"last_handshake_time_nsec" if value() != 0 => {
Some(Duration::from_nanos(value()))
}
_ => None,
}
})
.fold(None, |acc, add| {
if let Some(dur) = acc {
Some(dur + add)
}*/
let peers = peers
.map(|peer| peer.map(|peer_ok| (peer_ok.key.clone(), peer_ok)))
.collect::<io::Result<HashMap<_, _>>>()?;
if let Some(ref mut peers_last) = peers_last {
gen_events(&peers, &peers_last, &listeners, timeout, interval);
*peers_last = peers;
} else {
Some(add)
peers_last = Some(peers);
}
}),
persistent_keepalive: entries
.iter()
.filter(|(key, _)| key == &"persistent_keepalive")
.map(|(_, value)| Duration::from_secs(value.parse::<u64>().unwrap()))
.next(),
traffic: (0, 0),
parsed: time::get_time(),
})
}
pub fn last_handshake_rel(&self) -> Option<Duration> {
let time = self.parsed;
Some(Duration::new(time.sec as u64, time.nsec as u32) - self.last_handshake?)
}
}
impl State {
pub fn kv(&self) -> &Vec<KV> {
match self {
State::Interface(kv) => kv,
State::Peer(kv) => kv,
}
}
fn kv_mut(&mut self) -> &mut Vec<KV> {
match self {
State::Interface(kv) => kv,
State::Peer(kv) => kv,
}
}
pub fn id<'a>(&'a self) -> Option<String> {
self.kv()
.iter()
.filter(|(key, _)| key == &"private_key" || key == &"public_key")
.map(|(_, value)| base64::encode(&hex::decode(&value).unwrap()))
.next()
}
pub fn addr(&self) -> Option<SocketAddr> {
self.kv()
.iter()
.filter(|(key, _)| key == &"endpoint")
.map(|(_, value)| value.parse::<SocketAddr>().unwrap())
.next()
}
pub fn last_handshake(&self) -> Option<u64> {
self.kv()
.iter()
.filter(|(key, _)| key == &"last_handshake_time_nsec")
.map(|(_, value)| value.parse::<u64>().unwrap())
.next()
}
pub fn push(&mut self, key: String, value: String) {
self.kv_mut().push((key, value));
}
pub fn delta(&self, other: Self) -> Vec<KV> {
let kv = self.kv();
other
.kv()
.iter()
.filter(|pair| !kv.contains(pair))
.map(|p| p.clone())
.collect::<Vec<KV>>()
}
}
impl fmt::Display for State {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (k, v) in self.kv() {
write!(f, "({:10}= {})", k, v)?;
let pause = interval - now.elapsed();
//dbg!(interval - pause);
sleep(if pause > interval / 2 {
pause
} else {
interval
});
}
Ok(())
}
}
impl fmt::Display for Peer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
// write!(f, "peer {}\nshake {} ago\naddr {}\nkeepalive {}\n", self.public_key, self.last_handshake.map(|d|d.to_string()).unwrap_or("-"), self.endpoint.map(|d|d.to_string()).unwrap_or("-"), self.persistent_keepalive.map(|d|d.to_string()).unwrap_or("-"))
}
}
struct Socket {
pub path: PathBuf,
}
impl Socket {
pub fn get(&self) -> Result<Vec<State>> {
let mut stream = UnixStream::connect(&self.path)?;
stream.write_all(b"get=1\n")?;
let mut state: Vec<State> = vec![];
let mut cur = State::Interface(Vec::with_capacity(0));
for line in BufReader::new(stream).lines() {
let line = line?;
let mut iter = line.chars();
let key = iter.by_ref().take_while(|c| c != &'=').collect::<String>();
let value = iter.collect::<String>();
match key.as_ref() {
"errno" if value != "0" => Err(Error::new(
ErrorKind::Other,
format!("Socket said error: {}", value),
))?,
"public_key" | "private_key" => {
state.push(cur);
cur = if key == "private_key" {
State::Interface(Vec::with_capacity(3))
} else {
State::Peer(Vec::with_capacity(5))
};
cur.push(key, value);
}
_ => cur.push(key, value),
}
}
Ok(state)
}
pub fn get_by_id(&self) -> Result<HashMap<String, State>> {
let state = self.get()?;
let mut ided = HashMap::new();
for s in state {
if let Some(id) = s.id() {
ided.insert(id.clone(), s);
}
}
Ok(ided)
}
pub fn get_peers(&self) -> Result<HashMap<String, Peer>> {
let by_id = self.get_by_id()?;
Ok(by_id
.iter()
.filter_map(|(id, state)| {
Peer::from_kv(state.kv())
.ok()
.map(|peer| (id.to_owned(), peer))
})
.collect())
}
}
fn main() {
let opts = Opts::from_args();
let timeout = Duration::from_secs(opts.timeout);
let interval = Duration::from_secs(opts.poll);
let events = opts.events;
let path = opts.socket;
let mut listeners: Vec<Box<EventListener>> = vec![Box::new(LogListener)];
if let Some(events) = events {
listeners.push(Box::new(ScriptListener::new(events)))
}
let sock = Socket { path };
let mut prev_state: Option<HashMap<String, Peer>> = None;
loop {
let state = match sock.get_peers() {
Ok(state) => state,
Err(err) => {
eprintln!("Failed to read from socket: {}", err);
continue;
}
};
if let Some(prev_state) = prev_state {
gen::gen_events(&state, &prev_state, &listeners, timeout, interval);
}
prev_state = Some(state);
thread::sleep(interval);
}
}

205
wg-event-gen/src/model.rs Normal file
View File

@@ -0,0 +1,205 @@
use base64::{decode, encode};
use std::error::Error;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::io;
use std::net::{IpAddr, SocketAddr};
use std::time::Instant;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
const KEY_SIZE: usize = 48; //TODO: use VEC instead of array
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum ECCKey {
PublicKey(Vec<u8>),
PrivateKey(Vec<u8>),
}
impl fmt::Display for ECCKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_base64().unwrap())
}
}
pub trait Base64Backed {
fn from_bytes(bytes: Vec<u8>) -> Self;
fn bytes(&self) -> &Vec<u8>;
fn from_base64<I: AsRef<str>>(key: I) -> io::Result<Self>
where
Self: Sized,
{
let key = match decode(key.as_ref()) {
Ok(key) => key,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Failed to decode base64",
))
}
}; /*.map_err(|err| {
})?;*/
if key.len() != KEY_SIZE {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Mismatched key size. Expected: {}, Got {}",
KEY_SIZE,
key.len()
),
));
}
Ok(Self::from_bytes(key))
}
fn as_base64(&self) -> io::Result<String> {
Ok(encode(self.bytes()))
}
}
impl Base64Backed for ECCKey {
fn bytes(&self) -> &Vec<u8> {
match self {
ECCKey::PublicKey(bytes) => &bytes,
ECCKey::PrivateKey(bytes) => &bytes,
}
}
fn from_bytes(bytes: Vec<u8>) -> ECCKey {
ECCKey::PublicKey(bytes)
}
}
impl ECCKey {
pub fn public_key(&self) -> Option<ECCKey> {
//TODO: Determine whether Self is a private key and only the return public part
Some(self.clone())
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct SharedKey(Vec<u8>);
impl fmt::Display for SharedKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_base64().unwrap())
}
}
impl Base64Backed for SharedKey {
fn bytes(&self) -> &Vec<u8> {
&self.0
}
fn from_bytes(bytes: Vec<u8>) -> SharedKey {
SharedKey(bytes)
}
}
#[derive(Debug, Builder, PartialEq, Eq, Clone)]
pub struct Interface {
pub key: ECCKey,
pub port: usize,
pub fwmark: Option<String>,
}
impl Hash for Interface {
fn hash<H: Hasher>(&self, state: &mut H) {
self.key.public_key().hash(state);
}
}
#[derive(Debug, Builder, PartialEq, Eq, Clone)]
pub struct Peer {
pub key: ECCKey,
#[builder(default = "None")]
pub shared_key: Option<SharedKey>,
#[builder(default = "None")]
pub endpoint: Option<SocketAddr>,
#[builder(default = "Vec::new()")]
pub allowed_ips: Vec<(IpAddr, u8)>,
#[builder(default = "None")]
pub last_handshake: Option<SystemTime>,
#[builder(default = "None")]
pub persistent_keepalive: Option<Duration>,
#[builder(default = "(0u64,0u64)")]
pub traffic: (u64, u64),
#[builder(default = "Instant::now()")]
pub parsed: Instant,
}
impl Hash for Peer {
fn hash<H: Hasher>(&self, state: &mut H) {
self.key.hash(state);
}
}
impl fmt::Display for Peer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fn dis_opt<'a, T: fmt::Display + 'a>(opt: &Option<T>) -> String {
opt.as_ref()
.map(|s| s.to_string())
.unwrap_or(" ".to_string())
}
write!(
f,
"peer {} {}{}{}",
self.key,
dis_opt(&self.shared_key),
dis_opt(&self.endpoint),
self.allowed_ips
.iter()
.map(|(ip, sub)| format!(" {}/{}", ip, sub))
.collect::<Vec<_>>()
.join(",")
)
}
}
impl PeerBuilder {
fn validate(&self) -> Result<(), String> {
if let Some(ref key) = self.key {
Ok(())
} else {
Err("No key supplied".into())
}
}
pub fn is_whole(&self) -> bool {
self.validate().is_ok()
}
pub fn add_allowed_ip(&mut self, ip: (IpAddr, u8)) {
if let Some(ref mut ips) = &mut self.allowed_ips {
ips.push(ip);
} else {
self.allowed_ips = Some(vec![ip]);
}
}
pub fn add_last_handshake(&mut self, d: Duration) {
if !self.last_handshake.is_some() {
self.last_handshake = Some(Some(UNIX_EPOCH + d));
} else {
self.last_handshake = self
.last_handshake
.map(|shake| shake.map(|shake| shake + d));
}
}
pub fn add_traffic(&mut self, txrx: (u64, u64)) {
if let Some(ref mut traffic) = &mut self.traffic {
traffic.0 += txrx.0;
traffic.1 += txrx.1;
} else {
self.traffic = Some(txrx);
}
}
}
pub trait WireguardController {
fn peers<'a>(&'a mut self) -> io::Result<Box<Iterator<Item = io::Result<Peer>> + 'a>>;
fn interface(&mut self) -> io::Result<Interface>;
fn update_peer(&mut self, peer: &Peer) -> io::Result<()>;
}

View File

@@ -4,15 +4,36 @@ use structopt::StructOpt;
#[derive(StructOpt, Debug)]
#[structopt(name = "event-gen")]
pub struct Opts {
#[structopt(short = "t", long = "timeout", default_value = "120", env = "WG_EVENT_TIMEOUT")]
#[structopt(
short = "t",
long = "timeout",
default_value = "120",
env = "WG_EVENT_TIMEOUT"
)]
pub timeout: u64,
#[structopt(short = "p", long = "poll-interval", default_value = "3000", env = "WG_EVENT_INTERVAL")]
#[structopt(
short = "p",
long = "poll-interval",
default_value = "3000",
env = "WG_EVENT_INTERVAL"
)]
pub poll: u64,
#[structopt(short = "e", long = "event-handler", parse(from_os_str), env = "WG_EVENT_HANDLER")]
#[structopt(
short = "e",
long = "event-handler",
parse(from_os_str),
env = "WG_EVENT_HANDLER"
)]
pub events: Option<PathBuf>,
#[structopt(short = "I", long = "ignore-socket-err", env = "WG_IGNORE_SOCKET_ERR")]
pub ignore_socket_errors: bool,
#[structopt(short = "l", long = "log", env = "WG_LOG_EVENTS")]
pub log: bool,
#[structopt(name = "SOCKET", parse(from_os_str), env = "WG_EVENT_SOCKET")]
pub socket: PathBuf,
}

1
wg-event-gen/upload.sh Executable file
View File

@@ -0,0 +1 @@
cargo build --release && cat target/release/wg-event-gen | ssh core@ks1 "sudo bash -c 'cat > /srv/vpn/wireguard/event-gen'"

Submodule wireguard-go deleted from f49da8b7ad

View File

@@ -21,6 +21,8 @@ ExecStartPre=-/bin/mknod /dev/net/tun c 10 200
#Environment=WG_HOST_INTERFACE=eth0
#Environment=WG_ADDRESS=10.200.200.1/24
#Environment=WG_LOG_EVENTS=1
Environment=ROOT_DIR=/srv/wireguard
Environment=WG_CAPS="CAP_CHOWN,CAP_DAC_OVERRIDE,CAP_FSETID,CAP_FOWNER,CAP_MKNOD,CAP_NET_RAW,CAP_SETGID,CAP_SETUID,CAP_SETFCAP,CAP_SETPCAP,CAP_NET_BIND_SERVICE,CAP_SYS_CHROOT,CAP_KILL,CAP_AUDIT_WRITE,CAP_NET_ADMIN,CAP_SYS_ADMIN"