Skip to content

Commit

Permalink
Add client and server examples
Browse files Browse the repository at this point in the history
* Add examples
  • Loading branch information
dzania committed Sep 12, 2023
2 parents b5a5496 + f298376 commit 04bd392
Show file tree
Hide file tree
Showing 6 changed files with 278 additions and 1 deletion.
128 changes: 128 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ thiserror = "1.0"
tokio = "1.32"
boringtun = { version = "0.4", optional = true }

[dev-dependencies]
x25519-dalek = { version = "2.0.0-rc.3", features = [
"getrandom",
"static_secrets",
] }

[target.'cfg(target_os = "freebsd")'.dependencies]
nix = { version = "0.26", features = ["ioctl", "socket"] }

Expand Down
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,27 @@
# defguard-wireguard
<p align="center">
<img src="docs/header.png" alt="defguard">
</p>

**wireguard-rs** is a library providing Rust interface for working with wireguard which can
be used to create your own [Wireguard:tm:](https://www.wireguard.com/) VPN servers or clients for secure and private networking with native FreeBSD and wireguard-go support.

To learn more about the system see our [documentation](https://defguard.gitbook.io).

## Quick start

If you already have your defguard instance running you can set up a gateway by following our [deployment guide](https://defguard.gitbook.io/defguard/features/setting-up-your-instance/gateway).

## Documentation

See the [documentation](https://defguard.gitbook.io) for more information.

## Community and Support

Find us on Matrix: [#defguard:teonite.com](https://matrix.to/#/#defguard:teonite.com)

## Contribution

Please review the [Contributing guide](https://defguard.gitbook.io/defguard/for-developers/contributing) for information on how to get started contributing to the project. You might also find our [environment setup guide](https://defguard.gitbook.io/defguard/for-developers/dev-env-setup) handy.

# Legal
WireGuard is [registered trademarks](https://www.wireguard.com/trademark-policy/) of Jason A. Donenfeld.
Binary file added docs/header.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
65 changes: 65 additions & 0 deletions examples/client.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::{net::SocketAddr, str::FromStr};

#[cfg(target_os = "linux")]
use wireguard_rs::netlink::{address_interface, create_interface, delete_interface};
use wireguard_rs::{wgapi::WGApi, Host, IpAddrMask, Key, Peer};
use x25519_dalek::{EphemeralSecret, PublicKey, StaticSecret};

fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(target_os = "linux")]
{
log::info!("create interface");
create_interface("wg0")?;
log::info!("address interface");
// Set interface address
let addr = IpAddrMask::from_str("10.6.0.30").unwrap();
address_interface("wg0", &addr)?;
}
// Create new api object for interface
let api = if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
WGApi::new("wg0".into(), false)
} else {
WGApi::new("utun3".into(), true)
};
// host
let secret = StaticSecret::random();
let host = Host::new(12345, secret.to_bytes().as_ref().try_into().unwrap());

// Peer configuration
let secret = EphemeralSecret::random();
let key = PublicKey::from(&secret);
// Peer secret key
let peer_key: Key = key.as_ref().try_into().unwrap();
let mut peer = Peer::new(peer_key.clone());

log::info!("endpoint");
// Your wireguard server endpoint which peer connects too
let endpoint: SocketAddr = "<server_ip>:<server_port>".parse().unwrap();
// Peer endpoint and interval
peer.endpoint = Some(endpoint);
peer.persistent_keepalive_interval = Some(25);

// Peer allowed ips
let allowed_ips = vec!["10.6.0.0/24", "192.168.2.0/24"];
for allowed_ip in allowed_ips {
let addr = IpAddrMask::from_str(allowed_ip)?;
peer.allowed_ips.push(addr);
// Add a route for the allowed IP using the `ip -4 route add` command
let output = std::process::Command::new("ip")
.args(&["-4", "route", "add", allowed_ip, "dev", "wg0"])
.output()?;

if output.status.success() {
log::info!("Added route for {}", allowed_ip);
} else {
log::error!("Failed to add route for {}: {:?}", allowed_ip, output);
}
}
api.write_host(&host)?;
api.write_peer(&peer)?;

// Remove interface
delete_interface("wg0")?;

Ok(())
}
52 changes: 52 additions & 0 deletions examples/server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use std::str::FromStr;

use log;
#[cfg(target_os = "linux")]
use wireguard_rs::netlink::{address_interface, create_interface};
use wireguard_rs::{wgapi::WGApi, Host, IpAddrMask, Key, Peer};
use x25519_dalek::{EphemeralSecret, PublicKey, StaticSecret};

fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(target_os = "linux")]
{
log::debug!("create interface");
create_interface("wg0")?;
log::debug!("address interface");
let addr = IpAddrMask::from_str("10.20.30.40/24").unwrap();
address_interface("wg0", &addr)?;
}
let api = if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") {
WGApi::new("wg0".into(), false)
} else {
WGApi::new("utun3".into(), true)
};
let host = api.read_host()?;
log::debug!("{host:#?}");

// host
let secret = StaticSecret::random();
let mut host = Host::new(12345, secret.to_bytes().as_ref().try_into().unwrap());

let secret = EphemeralSecret::random();
let key = PublicKey::from(&secret);
let peer_key: Key = key.as_ref().try_into().unwrap();
let mut peer = Peer::new(peer_key.clone());
let addr = IpAddrMask::from_str("10.20.30.40/24").unwrap();
peer.allowed_ips.push(addr);
// Insert peers to host
host.peers.insert(peer_key, peer);

// Create host interfaces
api.write_host(&host)?;

// Create peers
for _ in 0..32 {
let secret = EphemeralSecret::random();
let key = PublicKey::from(&secret);
let peer = Peer::new(key.as_ref().try_into().unwrap());
api.write_peer(&peer)?;
api.delete_peer(&peer)?;
}

Ok(())
}

0 comments on commit 04bd392

Please sign in to comment.