tokio_wireguard/
lib.rs

1//! In-process WireGuard for Tokio
2//!
3//! This crate provides a Tokio-based in-process implementation of WireGuard.
4//! Each [`Interface`] is backed by an independent TCP/IP stack that tunnels all of its traffic
5//! over WireGuard, and can be used to create TCP ([`TcpStream`] and [`TcpListener`])
6//! and UDP ([`UdpSocket`]) sockets, which attempt to follow the API of [`tokio::net`] as closely as
7//! possible.
8//!
9//! The interface can be dynamically configured at runtime, and any number of interfaces can exist
10//! in the same process. This makes it possible for an application to support WireGuard with fine
11//! grained control without root privileges on any platform supported by Tokio.
12//!
13//! Interfaces can also forward traffic to remote WireGuard peers. However, at the moment, they cannot
14//! forward traffic to other interfaces outside of the WireGuard network.
15//!
16//! ```no_run
17//! # #[tokio::main]
18//! # async fn main() {
19//! # let (private_key, remote_public_key) = tokio_wireguard::x25519::keypair();
20//! use tokio::io::AsyncWriteExt;
21//! use tokio_wireguard::{
22//!     config::{Config, Interface, Peer},
23//!     interface::ToInterface,
24//!     TcpStream,
25//! };
26//!
27//! let config = Config {
28//!     interface: Interface {
29//!         private_key,
30//!         // Our address on the WireGuard network
31//!         address: "100.64.0.2/32".parse().unwrap(),
32//!         // Let the interface pick a random port
33//!         listen_port: None,
34//!         // Let the interface pick an appropriate MTU
35//!         mtu: None,
36//!     },
37//!     peers: vec![Peer {
38//!         public_key: remote_public_key,
39//!         // This is where the tunneled WireGuard traffic will be sent
40//!         endpoint: Some("198.51.100.30:51820".parse().unwrap()),
41//!         // IP addresses the peer can handle traffic to and from on the WireGuard network
42//!         // The /32 suffix indicates that the peer only handles traffic for itself
43//!         allowed_ips: vec!["100.64.0.1/32".parse().unwrap()],
44//!         // Send a keepalive packet every 15 seconds
45//!         persistent_keepalive: Some(15),
46//!     }],
47//! };
48//! let interface = config.to_interface().await.unwrap();
49//!
50//! let mut stream = TcpStream::connect("100.64.0.1:8080", &interface)
51//!     .await
52//!     .unwrap();
53//! stream.write_all(b"Bonjour").await.unwrap();
54//! # }
55//! ```
56//!
57//! This library is built on top of [`smoltcp`] and [`boringtun`], and could not exist without these
58//! amazing projects.
59
60pub mod config;
61pub mod interface;
62mod io;
63pub mod tcp;
64pub mod udp;
65pub mod x25519;
66
67pub(crate) type Shared<T> = std::sync::Arc<parking_lot::Mutex<Option<T>>>;
68
69pub use crate::{
70    config::Config,
71    interface::Interface,
72    tcp::{TcpListener, TcpStream},
73    udp::UdpSocket,
74};