gotatun 0.4.0

an implementation of the WireGuard® protocol designed for portability and speed
Documentation
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Copyright (c) 2025 Mullvad VPN AB. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause

#![deny(clippy::unwrap_used)]
use std::fmt::{self, Debug};
use std::mem::offset_of;
use std::ops::Deref;

use eyre::{bail, eyre};
use zerocopy::{FromBytes, FromZeros, Immutable, IntoBytes, KnownLayout, Unaligned, little_endian};

use crate::packet::util::size_must_be;
use crate::packet::{CheckedPayload, Packet};

#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C, packed)]
pub(crate) struct Wg {
    pub packet_type: WgPacketType,
    rest: [u8],
}

impl Debug for Wg {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Wg")
            .field("packet_type", &self.packet_type)
            .finish()
    }
}

/// An owned WireGuard [`Packet`] whose [`WgPacketType`] is known. See [`Packet::try_into_wg`].
pub enum WgKind {
    /// An owned [`WgHandshakeInit`] packet.
    HandshakeInit(Packet<WgHandshakeInit>),

    /// An owned [`WgHandshakeResp`] packet.
    HandshakeResp(Packet<WgHandshakeResp>),

    /// An owned [`WgCookieReply`] packet.
    CookieReply(Packet<WgCookieReply>),

    /// An owned [`WgData`] packet.
    Data(Packet<WgData>),
}

impl Debug for WgKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HandshakeInit(_) => f.debug_tuple("HandshakeInit").finish(),
            Self::HandshakeResp(_) => f.debug_tuple("HandshakeResp").finish(),
            Self::CookieReply(_) => f.debug_tuple("CookieReply").finish(),
            Self::Data(_) => f.debug_tuple("Data").finish(),
        }
    }
}

impl From<Packet<WgHandshakeInit>> for WgKind {
    fn from(p: Packet<WgHandshakeInit>) -> Self {
        WgKind::HandshakeInit(p)
    }
}

impl From<Packet<WgHandshakeResp>> for WgKind {
    fn from(p: Packet<WgHandshakeResp>) -> Self {
        WgKind::HandshakeResp(p)
    }
}

impl From<Packet<WgCookieReply>> for WgKind {
    fn from(p: Packet<WgCookieReply>) -> Self {
        WgKind::CookieReply(p)
    }
}

impl From<Packet<WgData>> for WgKind {
    fn from(p: Packet<WgData>) -> Self {
        WgKind::Data(p)
    }
}

impl From<WgKind> for Packet {
    fn from(kind: WgKind) -> Self {
        match kind {
            WgKind::HandshakeInit(packet) => packet.into(),
            WgKind::HandshakeResp(packet) => packet.into(),
            WgKind::CookieReply(packet) => packet.into(),
            WgKind::Data(packet) => packet.into(),
        }
    }
}

/// The first byte of a WireGuard packet. This identifies its type.
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable, PartialEq, Eq, Clone, Copy)]
#[repr(transparent)]
pub struct WgPacketType(pub u8);

impl WgPacketType {
    #![allow(non_upper_case_globals)]

    /// The type discriminant of a [`WgHandshakeInit`] packet.
    pub const HandshakeInit: WgPacketType = WgPacketType(1);

    /// The type discriminant of a [`WgHandshakeResp`] packet.
    pub const HandshakeResp: WgPacketType = WgPacketType(2);

    /// The type discriminant of a [`WgCookieReply`] packet.
    pub const CookieReply: WgPacketType = WgPacketType(3);

    /// The type discriminant of a [`WgData`] packet.
    pub const Data: WgPacketType = WgPacketType(4);
}

/// Header of [`WgData`].
/// See section 5.4.6 of the [whitepaper](https://www.wireguard.com/papers/wireguard.pdf).
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C)]
pub struct WgDataHeader {
    // INVARIANT: Must be WgPacketType::Data
    packet_type: WgPacketType,
    _reserved_zeros: [u8; 4 - size_of::<WgPacketType>()],

    /// An integer that identifies the WireGuard session for the receiving peer.
    pub receiver_idx: little_endian::U32,

    /// A counter that must be incremented for every data packet to prevent replay attacks.
    pub counter: little_endian::U64,
}

impl WgDataHeader {
    /// Header length
    pub const LEN: usize = size_must_be::<Self>(16);
}

/// WireGuard data packet.
/// See section 5.4.6 of the [whitepaper](https://www.wireguard.com/papers/wireguard.pdf).
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C, packed)]
pub struct WgData {
    /// Data packet header.
    pub header: WgDataHeader,

    /// Data packet payload and tag.
    pub encrypted_encapsulated_packet_and_tag: WgDataAndTag,
}

/// WireGuard data payload with a trailing tag.
///
/// This is essentially a byte slice that is at least [`WgData::TAG_LEN`] long.
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C)]
pub struct WgDataAndTag {
    // Don't access these field directly. The tag is actually at the end of the struct.
    _tag_size: [u8; WgData::TAG_LEN],
    _extra: [u8],
}

/// An encrypted value with an attached Poly1305 authentication tag.
#[derive(Clone, Copy, FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable, PartialEq, Eq)]
#[repr(C)]
pub struct EncryptedWithTag<T: Sized> {
    /// The encrypted value.
    pub encrypted: T,
    /// The Poly1305 authentication tag attached to `encrypted`.
    pub tag: [u8; 16],
}

impl WgData {
    /// Data packet overhead: header and tag, `16+16` bytes.
    pub const OVERHEAD: usize = WgDataHeader::LEN + WgData::TAG_LEN;

    /// Length of the trailing `tag` field, in bytes.
    pub const TAG_LEN: usize = 16;

    /// Strip the tag from the encapsulated packet.
    fn split_encapsulated_packet_and_tag(&self) -> (&[u8], &[u8; WgData::TAG_LEN]) {
        self.encrypted_encapsulated_packet_and_tag
            .split_last_chunk::<{ WgData::TAG_LEN }>()
            .expect("WgDataAndTag is at least TAG_LEN bytes long")
    }

    /// Strip the tag from the encapsulated packet.
    fn split_encapsulated_packet_and_tag_mut(&mut self) -> (&mut [u8], &mut [u8; WgData::TAG_LEN]) {
        self.encrypted_encapsulated_packet_and_tag
            .split_last_chunk_mut::<{ WgData::TAG_LEN }>()
            .expect("WgDataAndTag is at least TAG_LEN bytes long")
    }

    /// Get a reference to the encapsulated packet, without the trailing tag.
    pub fn encrypted_encapsulated_packet(&self) -> &[u8] {
        let (encrypted_encapsulated_packet, _) = self.split_encapsulated_packet_and_tag();
        encrypted_encapsulated_packet
    }

    /// Get a mutable reference to the encapsulated packet, without the trailing tag.
    pub fn encrypted_encapsulated_packet_mut(&mut self) -> &mut [u8] {
        let (encrypted_encapsulated_packet, _) = self.split_encapsulated_packet_and_tag_mut();
        encrypted_encapsulated_packet
    }

    /// Get a reference to the tag of the encapsulated packet.
    ///
    /// Returns None if if the encapsulated packet + tag is less than 16 bytes.
    pub fn tag(&mut self) -> &[u8; WgData::TAG_LEN] {
        let (_, tag) = self.split_encapsulated_packet_and_tag();
        tag
    }

    /// Get a mutable reference to the tag of the encapsulated packet.
    ///
    /// Returns None if if the encapsulated packet + tag is less than 16 bytes.
    pub fn tag_mut(&mut self) -> &mut [u8; WgData::TAG_LEN] {
        let (_, tag) = self.split_encapsulated_packet_and_tag_mut();
        tag
    }

    /// Returns true if the payload is empty.
    pub const fn is_empty(&self) -> bool {
        self.encrypted_encapsulated_packet_and_tag._extra.is_empty()
    }

    /// [`Self::is_empty`]. Keepalive packets are just data packets with no payload.
    pub const fn is_keepalive(&self) -> bool {
        self.is_empty()
    }
}

impl WgDataHeader {
    /// Construct a [`WgDataHeader`] where all fields except `packet_type` are zeroed.
    pub fn new() -> Self {
        Self {
            packet_type: WgPacketType::Data,
            ..WgDataHeader::new_zeroed()
        }
    }

    /// Set `receiver_idx`.
    pub const fn with_receiver_idx(mut self, receiver_idx: u32) -> Self {
        self.receiver_idx = little_endian::U32::new(receiver_idx);
        self
    }

    /// Set `counter`.
    pub const fn with_counter(mut self, counter: u64) -> Self {
        self.counter = little_endian::U64::new(counter);
        self
    }
}

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

impl Deref for WgDataAndTag {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.as_bytes()
    }
}

impl std::ops::DerefMut for WgDataAndTag {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_bytes()
    }
}

/// Trait for fields common to both [`WgHandshakeInit`] and [`WgHandshakeResp`].
pub trait WgHandshakeBase:
    FromBytes + IntoBytes + KnownLayout + Unaligned + Immutable + CheckedPayload
{
    /// Length of the handshake packet, in bytes.
    const LEN: usize;

    /// Offset of the `mac1` field.
    /// This is used for getting a byte slice up until `mac1`, i.e. `&packet[..MAC1_OFF]`.
    const MAC1_OFF: usize;

    /// Offset of the `mac2` field.
    /// This is used for getting a byte slice up until `mac2`, i.e. `&packet[..MAC2_OFF]`.
    const MAC2_OFF: usize;

    /// Get `sender_id`.
    fn sender_idx(&self) -> u32;

    /// Get a mutable reference to `mac1`.
    fn mac1_mut(&mut self) -> &mut [u8; 16];

    /// Get a mutable reference to `mac2`.
    fn mac2_mut(&mut self) -> &mut [u8; 16];

    /// Get `mac1`.
    fn mac1(&self) -> &[u8; 16];

    /// Get `mac2`.
    fn mac2(&self) -> &[u8; 16];

    /// Get packet until MAC1. Precisely equivalent to `packet[0..offsetof(packet.mac1)]`.
    #[inline(always)]
    fn until_mac1(&self) -> &[u8] {
        &self.as_bytes()[..Self::MAC1_OFF]
    }

    /// Get packet until MAC2. Precisely equivalent to `packet[0..offsetof(packet.mac2)]`.
    #[inline(always)]
    fn until_mac2(&self) -> &[u8] {
        &self.as_bytes()[..Self::MAC2_OFF]
    }
}

/// WireGuard handshake initialization packet.
/// See section 5.4.2 of the [whitepaper](https://www.wireguard.com/papers/wireguard.pdf).
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C, packed)]
pub struct WgHandshakeInit {
    // INVARIANT: Must be WgPacketType::HandshakeInit
    packet_type: WgPacketType,
    _reserved_zeros: [u8; 4 - size_of::<WgPacketType>()],

    /// An integer that identifies the WireGuard session for the initiating peer.
    pub sender_idx: little_endian::U32,

    /// Ephemeral public key of the initiating peer.
    pub unencrypted_ephemeral: [u8; 32],

    /// Encrypted static public key.
    pub encrypted_static: EncryptedWithTag<[u8; 32]>,

    /// A TAI64N timestamp. Used to avoid replay attacks.
    pub timestamp: EncryptedWithTag<[u8; 12]>,

    /// Message authentication code 1.
    pub mac1: [u8; 16],

    /// Message authentication code 2.
    pub mac2: [u8; 16],
}

impl WgHandshakeInit {
    /// Length of the packet, in bytes.
    pub const LEN: usize = size_must_be::<Self>(148);

    /// Construct a [`WgHandshakeInit`] where all fields except `packet_type` are zeroed.
    pub fn new() -> Self {
        Self {
            packet_type: WgPacketType::HandshakeInit,
            ..WgHandshakeInit::new_zeroed()
        }
    }
}

impl WgHandshakeBase for WgHandshakeInit {
    const LEN: usize = Self::LEN;
    const MAC1_OFF: usize = offset_of!(Self, mac1);
    const MAC2_OFF: usize = offset_of!(Self, mac2);

    fn sender_idx(&self) -> u32 {
        self.sender_idx.get()
    }

    fn mac1_mut(&mut self) -> &mut [u8; 16] {
        &mut self.mac1
    }

    fn mac2_mut(&mut self) -> &mut [u8; 16] {
        &mut self.mac2
    }

    fn mac1(&self) -> &[u8; 16] {
        &self.mac1
    }

    fn mac2(&self) -> &[u8; 16] {
        &self.mac2
    }
}

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

/// WireGuard handshake response packet.
/// See section 5.4.3 of the [whitepaper](https://www.wireguard.com/papers/wireguard.pdf).
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C, packed)]
pub struct WgHandshakeResp {
    // INVARIANT: Must be WgPacketType::HandshakeResp
    packet_type: WgPacketType,
    _reserved_zeros: [u8; 4 - size_of::<WgPacketType>()],

    /// An integer that identifies the WireGuard session for the responding peer.
    pub sender_idx: little_endian::U32,

    /// An integer that identifies the WireGuard session for the initiating peer.
    pub receiver_idx: little_endian::U32,

    /// Ephemeral public key of the responding peer.
    pub unencrypted_ephemeral: [u8; 32],

    /// A Poly1305 authentication tag generated from an empty message.
    pub encrypted_nothing: EncryptedWithTag<()>,

    /// Message authentication code 1.
    pub mac1: [u8; 16],

    /// Message authentication code 2.
    pub mac2: [u8; 16],
}

impl WgHandshakeResp {
    /// Length of the packet, in bytes.
    pub const LEN: usize = size_must_be::<Self>(92);

    /// Construct a [`WgHandshakeResp`].
    pub fn new(sender_idx: u32, receiver_idx: u32, unencrypted_ephemeral: [u8; 32]) -> Self {
        Self {
            packet_type: WgPacketType::HandshakeResp,
            _reserved_zeros: [0; 3],
            sender_idx: sender_idx.into(),
            receiver_idx: receiver_idx.into(),
            unencrypted_ephemeral,
            encrypted_nothing: EncryptedWithTag::new_zeroed(),
            mac1: [0u8; 16],
            mac2: [0u8; 16],
        }
    }
}

impl WgHandshakeBase for WgHandshakeResp {
    const LEN: usize = Self::LEN;
    const MAC1_OFF: usize = offset_of!(Self, mac1);
    const MAC2_OFF: usize = offset_of!(Self, mac2);

    fn sender_idx(&self) -> u32 {
        self.sender_idx.get()
    }

    fn mac1_mut(&mut self) -> &mut [u8; 16] {
        &mut self.mac1
    }

    fn mac2_mut(&mut self) -> &mut [u8; 16] {
        &mut self.mac2
    }

    fn mac1(&self) -> &[u8; 16] {
        &self.mac1
    }

    fn mac2(&self) -> &[u8; 16] {
        &self.mac2
    }
}

/// WireGuard cookie reply packet.
/// See section 5.4.7 of the [whitepaper](https://www.wireguard.com/papers/wireguard.pdf).
#[derive(FromBytes, IntoBytes, KnownLayout, Unaligned, Immutable)]
#[repr(C, packed)]
pub struct WgCookieReply {
    // INVARIANT: Must be WgPacketType::CookieReply
    packet_type: WgPacketType,
    _reserved_zeros: [u8; 4 - size_of::<WgPacketType>()],

    /// An integer that identifies the WireGuard session for the handshake-initiating peer.
    pub receiver_idx: little_endian::U32,

    /// Number only used once.
    pub nonce: [u8; 24],

    /// An encrypted 16-byte value that identifies the [`WgHandshakeInit`] that this packet is in
    /// response to.
    pub encrypted_cookie: EncryptedWithTag<[u8; 16]>,
}

impl WgCookieReply {
    /// Length of the packet, in bytes.
    pub const LEN: usize = size_must_be::<Self>(64);

    /// Construct a [`WgCookieReply`] where all fields except `packet_type` are zeroed.
    pub fn new() -> Self {
        Self {
            packet_type: WgPacketType::CookieReply,
            ..Self::new_zeroed()
        }
    }
}

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

impl Packet {
    /// Try to cast to a WireGuard packet while sanity-checking packet type and size.
    pub fn try_into_wg(self) -> eyre::Result<WgKind> {
        let wg = Wg::ref_from_bytes(self.as_bytes())
            .map_err(|_| eyre!("Not a wireguard packet, too small."))?;

        let len = wg.as_bytes().len();
        match (wg.packet_type, len) {
            (WgPacketType::HandshakeInit, WgHandshakeInit::LEN) => {
                Ok(WgKind::HandshakeInit(self.cast()))
            }
            (WgPacketType::HandshakeResp, WgHandshakeResp::LEN) => {
                Ok(WgKind::HandshakeResp(self.cast()))
            }
            (WgPacketType::CookieReply, WgCookieReply::LEN) => Ok(WgKind::CookieReply(self.cast())),
            (WgPacketType::Data, WgData::OVERHEAD..) => Ok(WgKind::Data(self.cast())),
            _ => bail!("Not a wireguard packet, bad type/size."),
        }
    }
}

impl Debug for WgPacketType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            &WgPacketType::HandshakeInit => "HandshakeInit",
            &WgPacketType::HandshakeResp => "HandshakeResp",
            &WgPacketType::CookieReply => "CookieReply",
            &WgPacketType::Data => "Data",

            WgPacketType(t) => return Debug::fmt(t, f),
        };

        f.debug_tuple(name).finish()
    }
}