wgctrl_rs/
config.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
extern crate libc;
extern crate wgctrl_sys;

use self::wgctrl_sys::wg_device_flags as wgdf;
use self::wgctrl_sys::wg_peer_flags as wgpf;
use device::{AllowedIp, PeerConfig};
use key::{Key, KeyPair};

use std::ffi::CString;
use std::io;
use std::mem;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::ptr;

fn encode_allowedips(
    allowed_ips: &[AllowedIp],
) -> (*mut wgctrl_sys::wg_allowedip, *mut wgctrl_sys::wg_allowedip) {
    if allowed_ips.is_empty() {
        return (ptr::null_mut(), ptr::null_mut());
    }

    let mut first_ip = ptr::null_mut();
    let mut last_ip: *mut wgctrl_sys::wg_allowedip = ptr::null_mut();

    for ip in allowed_ips {
        let mut wg_allowedip = Box::new(wgctrl_sys::wg_allowedip {
            family: 0,
            __bindgen_anon_1: unsafe { mem::uninitialized() },
            cidr: ip.cidr,
            next_allowedip: first_ip,
        });

        match ip.address {
            IpAddr::V4(a) => {
                wg_allowedip.family = libc::AF_INET as u16;
                unsafe { wg_allowedip.__bindgen_anon_1.ip4.s_addr = u32::to_be(a.into()) };
            }
            IpAddr::V6(a) => {
                wg_allowedip.family = libc::AF_INET6 as u16;
                unsafe { wg_allowedip.__bindgen_anon_1.ip6.s6_addr = a.octets() };
            }
        }

        first_ip = Box::into_raw(wg_allowedip);
        if last_ip.is_null() {
            last_ip = first_ip;
        }
    }

    (first_ip, last_ip)
}

fn encode_endpoint(endpoint: Option<SocketAddr>) -> wgctrl_sys::wg_peer__bindgen_ty_1 {
    match endpoint {
        Some(SocketAddr::V4(s)) => wgctrl_sys::wg_peer__bindgen_ty_1 {
            addr4: libc::sockaddr_in {
                sin_family: libc::AF_INET as u16,
                sin_addr: libc::in_addr {
                    s_addr: u32::from_be(s.ip().clone().into()),
                },
                sin_port: u16::to_be(s.port()),
                sin_zero: [0; 8],
            },
        },
        Some(SocketAddr::V6(s)) => {
            let mut result = wgctrl_sys::wg_peer__bindgen_ty_1 {
                addr6: libc::sockaddr_in6 {
                    sin6_family: libc::AF_INET6 as u16,
                    sin6_addr: unsafe { mem::uninitialized() },
                    sin6_port: u16::to_be(s.port()),
                    sin6_flowinfo: 0,
                    sin6_scope_id: 0,
                },
            };
            unsafe { result.addr6.sin6_addr.s6_addr = s.ip().octets() };
            result
        }
        None => wgctrl_sys::wg_peer__bindgen_ty_1 {
            addr6: unsafe { mem::zeroed() },
        },
    }
}

fn encode_peers(peers: Vec<PeerConfigBuilder>) -> (*mut wgctrl_sys::wg_peer, *mut wgctrl_sys::wg_peer) {
    let mut first_peer = ptr::null_mut();
    let mut last_peer: *mut wgctrl_sys::wg_peer = ptr::null_mut();

    for peer in peers {
        let (first_allowedip, last_allowedip) = encode_allowedips(&peer.allowed_ips);

        let mut wg_peer = Box::new(wgctrl_sys::wg_peer {
            public_key: peer.public_key.0,
            preshared_key: wgctrl_sys::wg_key::default(),
            endpoint: encode_endpoint(peer.endpoint),
            last_handshake_time: libc::timespec {
                tv_sec: 0,
                tv_nsec: 0,
            },
            tx_bytes: 0,
            rx_bytes: 0,
            persistent_keepalive_interval: 0,
            first_allowedip,
            last_allowedip,
            next_peer: first_peer,
            flags: peer.flags,
        });

        if let Some(Key(k)) = peer.preshared_key {
            wg_peer.preshared_key = k;
        }

        if let Some(n) = peer.persistent_keepalive_interval {
            wg_peer.persistent_keepalive_interval = n;
        }

        first_peer = Box::into_raw(wg_peer);
        if last_peer.is_null() {
            last_peer = first_peer;
        }
    }

    (first_peer, last_peer)
}

fn encode_name(name: &str) -> [i8; 16] {
    let mut bytes: Vec<_> = name.bytes().collect();
    bytes.resize(16, 0);

    let mut result = [0u8; 16];
    result.copy_from_slice(&bytes[..]);

    unsafe { mem::transmute(result) }
}

/// Builds and represents a configuration that can be applied to a WireGuard interface.
///
/// This is the primary way of changing the settings of an interface.
///
/// Note that if an interface exists, the configuration is applied _on top_ of the existing
/// settings, and missing parts are not overwritten or set to defaults.
///
/// If this is not what you want, use [`delete_interface`](delete_interface)
/// to remove the interface entirely before applying the new configuration.
///
/// # Example
/// ```rust
/// # use wgctrl_rs::*;
/// # use std::net::AddrParseError;
/// # fn try_main() -> Result<(), AddrParseError> {
/// let our_keypair = KeyPair::generate();
/// let peer_keypair = KeyPair::generate();
/// let server_addr = "192.168.1.1".parse()?;
///
/// DeviceConfigBuilder::new()
///     .set_keypair(our_keypair)
///     .replace_peers()
///     .add_peer_with(&peer_keypair.public, |peer| {
///         peer.set_endpoint(server_addr, 51820)
///             .replace_allowed_ips()
///             .allow_all_ips()
///     }).apply("wg-example");
///
/// println!("Send these keys to your peer: {:#?}", peer_keypair);
///
/// # Ok(())
/// # }
/// # fn main() { try_main(); }
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct DeviceConfigBuilder {
    public_key: Option<Key>,
    private_key: Option<Key>,
    fwmark: Option<u32>,
    listen_port: Option<u16>,
    peers: Vec<PeerConfigBuilder>,
    flags: wgdf,
}

impl DeviceConfigBuilder {
    /// Creates a new `DeviceConfigBuilder` that does nothing when applied.
    pub fn new() -> Self {
        DeviceConfigBuilder {
            public_key: None,
            private_key: None,
            fwmark: None,
            listen_port: None,
            peers: vec![],
            flags: wgdf(0),
        }
    }

    /// Sets a new keypair to be applied to the interface.
    ///
    /// This is a convenience method that simply wraps
    /// [`set_public_key`](DeviceConfigBuilder::set_public_key)
    /// and [`set_private_key`](DeviceConfigBuilder::set_private_key).
    pub fn set_keypair(self, keypair: KeyPair) -> Self {
        self.set_public_key(keypair.public)
            .set_private_key(keypair.private)
    }

    /// Specifies a new public key to be applied to the interface.
    pub fn set_public_key(mut self, key: Key) -> Self {
        self.public_key = Some(key);
        self.flags |= wgdf::WGDEVICE_HAS_PUBLIC_KEY;
        self
    }

    /// Specifies that the public key for this interface should be unset.
    pub fn unset_public_key(self) -> Self {
        self.set_public_key(Key::zero())
    }

    /// Sets a new private key to be applied to the interface.
    pub fn set_private_key(mut self, key: Key) -> Self {
        self.private_key = Some(key);
        self.flags |= wgdf::WGDEVICE_HAS_PRIVATE_KEY;
        self
    }

    /// Specifies that the private key for this interface should be unset.
    pub fn unset_private_key(self) -> Self {
        self.set_private_key(Key::zero())
    }

    /// Specifies the fwmark value that should be applied to packets coming from the interface.
    pub fn set_fwmark(mut self, fwmark: u32) -> Self {
        self.fwmark = Some(fwmark);
        self.flags |= wgdf::WGDEVICE_HAS_FWMARK;
        self
    }

    /// Specifies that fwmark should not be set on packets from the interface.
    pub fn unset_fwmark(self) -> Self {
        self.set_fwmark(0)
    }

    /// Specifies the port to listen for incoming packets on.
    ///
    /// This is useful for a server configuration that listens on a fixed endpoint.
    pub fn set_listen_port(mut self, port: u16) -> Self {
        self.listen_port = Some(port);
        self.flags |= wgdf::WGDEVICE_HAS_LISTEN_PORT;
        self
    }

    /// Specifies that a random port should be used for incoming packets.
    ///
    /// This is probably what you want in client configurations.
    pub fn randomize_listen_port(self) -> Self {
        self.set_listen_port(0)
    }

    /// Specifies a new peer configuration to be added to the interface.
    ///
    /// See [`PeerConfigBuilder`](PeerConfigBuilder) for details on building
    /// peer configurations. This method can be called more than once, and all
    /// peers will be added to the configuration.
    pub fn add_peer(mut self, peer: PeerConfigBuilder) -> Self {
        self.peers.push(peer);
        self
    }

    /// Specifies a new peer configuration using a builder function.
    ///
    /// This is simply a convenience method to make adding peers more fluent.
    /// This method can be called more than once, and all peers will be added
    /// to the configuration.
    pub fn add_peer_with(
        self,
        pubkey: &Key,
        builder: impl Fn(PeerConfigBuilder) -> PeerConfigBuilder,
    ) -> Self {
        self.add_peer(builder(PeerConfigBuilder::new(pubkey)))
    }

    /// Specifies multiple peer configurations to be added to the interface.
    pub fn add_peers(mut self, peers: &[PeerConfigBuilder]) -> Self {
        self.peers.extend_from_slice(peers);
        self
    }

    /// Specifies that the peer configurations in this `DeviceConfigBuilder` should
    /// replace the existing configurations on the interface, not modify or append to them.
    pub fn replace_peers(mut self) -> Self {
        self.flags |= wgdf::WGDEVICE_REPLACE_PEERS;
        self
    }

    /// Specifies that the peer with this public key should be removed from the interface.
    pub fn remove_peer_by_key(self, public_key: &Key) -> Self {
        let mut peer = PeerConfigBuilder::new(public_key);
        peer.flags |= wgpf::WGPEER_REMOVE_ME;
        self.add_peer(peer)
    }

    /// Build and apply the configuration to a WireGuard interface by name.
    ///
    /// An interface with the provided name will be created if one does not exist already.
    pub fn apply(self, iface: &str) -> io::Result<()> {
        let (first_peer, last_peer) = encode_peers(self.peers);

        let iface_str = CString::new(iface)?;
        let result = unsafe { wgctrl_sys::wg_add_device(iface_str.as_ptr()) };
        match result {
            0 | -17 => {}
            _ => return Err(io::Error::last_os_error()),
        };

        let mut wg_device = Box::new(wgctrl_sys::wg_device {
            name: encode_name(iface),
            ifindex: 0,
            public_key: wgctrl_sys::wg_key::default(),
            private_key: wgctrl_sys::wg_key::default(),
            fwmark: 0,
            listen_port: 0,
            first_peer,
            last_peer,
            flags: self.flags,
        });

        if let Some(Key(k)) = self.public_key {
            wg_device.public_key = k;
        }

        if let Some(Key(k)) = self.private_key {
            wg_device.private_key = k;
        }

        if let Some(f) = self.fwmark {
            wg_device.fwmark = f;
        }

        if let Some(f) = self.listen_port {
            wg_device.listen_port = f;
        }

        let ptr = Box::into_raw(wg_device);
        let result = unsafe { wgctrl_sys::wg_set_device(ptr) };

        unsafe { wgctrl_sys::wg_free_device(ptr) };

        if result == 0 {
            Ok(())
        } else {
            Err(io::Error::last_os_error())
        }
    }
}

impl Default for DeviceConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builds and represents a single peer in a WireGuard interface configuration.
///
/// Note that if a peer with that public key already exists on the interface,
/// the settings specified here will be applied _on top_ of the existing settings,
/// similarly to interface-wide settings.
///
/// If this is not what you want, use [`DeviceConfigBuilder::replace_peers`](DeviceConfigBuilder::replace_peers)
/// to replace all peer settings on the interface, or use
/// [`DeviceConfigBuilder::remove_peer_by_key`](DeviceConfigBuilder::remove_peer_by_key) first
/// to remove the peer from the interface, and then apply a second configuration to re-add it.
///
/// # Example
/// ```rust
/// # use wgctrl_rs::*;
/// # use std::net::AddrParseError;
/// # fn try_main() -> Result<(), AddrParseError> {
/// let peer_keypair = KeyPair::generate();
///
/// // create a new peer and allow it to connect from 192.168.1.2
/// let peer = PeerConfigBuilder::new(&peer_keypair.public)
///     .replace_allowed_ips()
///     .add_allowed_ip("192.168.1.2".parse()?, 32);
///
/// // update our existing configuration with the new peer
/// DeviceConfigBuilder::new().add_peer(peer).apply("wg-example");
///
/// println!("Send these keys to your peer: {:#?}", peer_keypair);
///
/// # Ok(())
/// # }
/// # fn main() { try_main(); }
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct PeerConfigBuilder {
    public_key: Key,
    preshared_key: Option<Key>,
    endpoint: Option<SocketAddr>,
    persistent_keepalive_interval: Option<u16>,
    allowed_ips: Vec<AllowedIp>,
    flags: wgpf,
}

impl PeerConfigBuilder {
    /// Creates a new `PeerConfigBuilder` that does nothing when applied.
    pub fn new(public_key: &Key) -> Self {
        PeerConfigBuilder {
            public_key: public_key.clone(),
            preshared_key: None,
            endpoint: None,
            persistent_keepalive_interval: None,
            allowed_ips: vec![],
            flags: wgpf::WGPEER_HAS_PUBLIC_KEY,
        }
    }

    /// Creates a `PeerConfigBuilder` from a [`PeerConfig`](PeerConfig).
    ///
    /// This is mostly a convenience method for cases when you want to copy
    /// some or most of the existing peer configuration to a new configuration.
    ///
    /// This returns a `PeerConfigBuilder`, so you can still call any methods
    /// you need to override the imported settings.
    pub fn from_peer_config(config: PeerConfig) -> Self {
        let mut builder = Self::new(&config.public_key);
        if let Some(k) = config.preshared_key {
            builder = builder.set_preshared_key(k);
        }
        if let Some(e) = config.endpoint {
            builder = builder.set_endpoint(e.ip(), e.port());
        }
        if let Some(k) = config.persistent_keepalive_interval {
            builder = builder.set_persistent_keepalive_interval(k);
        }
        builder
            .replace_allowed_ips()
            .add_allowed_ips(&config.allowed_ips)
    }

    /// Specifies a preshared key to be set for this peer.
    pub fn set_preshared_key(mut self, key: Key) -> Self {
        self.preshared_key = Some(key);
        self.flags |= wgpf::WGPEER_HAS_PRESHARED_KEY;
        self
    }

    /// Specifies that this peer's preshared key should be unset.
    pub fn unset_preshared_key(self) -> Self {
        self.set_preshared_key(Key::zero())
    }

    /// Specifies an exact endpoint that this peer should be allowed to connect from.
    pub fn set_endpoint(mut self, address: IpAddr, port: u16) -> Self {
        self.endpoint = Some(SocketAddr::new(address, port));
        self
    }

    /// Specifies the interval between keepalive packets to be sent to this peer.
    pub fn set_persistent_keepalive_interval(mut self, interval: u16) -> Self {
        self.persistent_keepalive_interval = Some(interval);
        self.flags |= wgpf::WGPEER_HAS_PERSISTENT_KEEPALIVE_INTERVAL;
        self
    }

    /// Specifies that this peer does not require keepalive packets.
    pub fn disable_persistent_keepalive(self) -> Self {
        self.set_persistent_keepalive_interval(0)
    }

    /// Specifies an IP address this peer will be allowed to connect from/to.
    ///
    /// See [`AllowedIp`](AllowedIp) for details. This method can be called
    /// more than once, and all IP addresses will be added to the configuration.
    pub fn add_allowed_ip(mut self, address: IpAddr, cidr: u8) -> Self {
        self.allowed_ips.push(AllowedIp { address, cidr });
        self
    }

    /// Specifies multiple IP addresses this peer will be allowed to connect from/to.
    ///
    /// See [`AllowedIp`](AllowedIp) for details. This method can be called
    /// more than once, and all IP addresses will be added to the configuration.
    pub fn add_allowed_ips(mut self, ips: &[AllowedIp]) -> Self {
        self.allowed_ips.extend_from_slice(ips);
        self
    }

    /// Specifies this peer should be allowed to connect to all IP addresses.
    ///
    /// This is a convenience method for cases when you want to connect to a server
    /// that all traffic should be routed through.
    pub fn allow_all_ips(self) -> Self {
        self.add_allowed_ip(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)
            .add_allowed_ip(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)), 0)
    }

    /// Specifies that the allowed IP addresses in this configuration should replace
    /// the existing configuration of the interface, not be appended to it.
    pub fn replace_allowed_ips(mut self) -> Self {
        self.flags |= wgpf::WGPEER_REPLACE_ALLOWEDIPS;
        self
    }
}

/// Deletes an existing WireGuard interface by name.
pub fn delete_interface(iface: &str) -> io::Result<()> {
    let iface_str = CString::new(iface)?;
    let result = unsafe { wgctrl_sys::wg_del_device(iface_str.as_ptr()) };

    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}