aboutsummaryrefslogtreecommitdiffstats
path: root/src/wireguard/workers.rs
blob: 62d531d0ca5290d16ae1d71016d40262ce53291a (plain) (blame)
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
use std::sync::atomic::Ordering;
use std::time::Instant;

use byteorder::{ByteOrder, LittleEndian};
use crossbeam_channel::Receiver;
use log::debug;
use rand::rngs::OsRng;
use x25519_dalek::PublicKey;

// IO traits
use super::Endpoint;

use super::tun::Reader as TunReader;
use super::tun::Tun;

use super::udp::Reader as UDPReader;
use super::udp::Writer as UDPWriter;
use super::udp::UDP;

// constants
use super::constants::{
    DURATION_UNDER_LOAD, MAX_QUEUED_INCOMING_HANDSHAKES, MESSAGE_PADDING_MULTIPLE,
    THRESHOLD_UNDER_LOAD, TIME_HORIZON,
};
use super::handshake::MAX_HANDSHAKE_MSG_SIZE;
use super::handshake::{TYPE_COOKIE_REPLY, TYPE_INITIATION, TYPE_RESPONSE};
use super::router::{CAPACITY_MESSAGE_POSTFIX, SIZE_MESSAGE_PREFIX, TYPE_TRANSPORT};

use super::wireguard::WireGuard;

pub enum HandshakeJob<E> {
    Message(Vec<u8>, E),
    New(PublicKey),
}

/* Returns the padded length of a message:
 *
 * # Arguments
 *
 * - `size` : Size of unpadded message
 * - `mtu` : Maximum transmission unit of the device
 *
 * # Returns
 *
 * The padded length (always less than or equal to the MTU)
 */
#[inline(always)]
const fn padding(size: usize, mtu: usize) -> usize {
    #[inline(always)]
    const fn min(a: usize, b: usize) -> usize {
        let m = (a < b) as usize;
        a * m + (1 - m) * b
    }
    let pad = MESSAGE_PADDING_MULTIPLE;
    min(mtu, size + (pad - size % pad) % pad)
}

pub fn tun_worker<T: Tun, B: UDP>(wg: &WireGuard<T, B>, reader: T::Reader) {
    loop {
        // create vector big enough for any transport message (based on MTU)
        let mtu = wg.mtu.load(Ordering::Relaxed);
        let size = mtu + SIZE_MESSAGE_PREFIX + 1;
        let mut msg: Vec<u8> = vec![0; size + CAPACITY_MESSAGE_POSTFIX];

        // read a new IP packet
        let payload = match reader.read(&mut msg[..], SIZE_MESSAGE_PREFIX) {
            Ok(payload) => payload,
            Err(e) => {
                debug!("TUN worker, failed to read from tun device: {}", e);
                break;
            }
        };
        debug!("TUN worker, IP packet of {} bytes (MTU = {})", payload, mtu);

        // check if device is down
        if mtu == 0 {
            continue;
        }

        // truncate padding
        let padded = padding(payload, mtu);
        log::trace!(
            "TUN worker, payload length = {}, padded length = {}",
            payload,
            padded
        );
        msg.truncate(SIZE_MESSAGE_PREFIX + padded);
        debug_assert!(padded <= mtu);
        debug_assert_eq!(
            if padded < mtu {
                (msg.len() - SIZE_MESSAGE_PREFIX) % MESSAGE_PADDING_MULTIPLE
            } else {
                0
            },
            0
        );

        // crypt-key route
        let e = wg.router.send(msg);
        debug!("TUN worker, router returned {:?}", e);
    }
}

pub fn udp_worker<T: Tun, B: UDP>(wg: &WireGuard<T, B>, reader: B::Reader) {
    let mut last_under_load = Instant::now() - TIME_HORIZON;

    loop {
        // create vector big enough for any message given current MTU
        let mtu = wg.mtu.load(Ordering::Relaxed);
        let size = mtu + MAX_HANDSHAKE_MSG_SIZE;
        let mut msg: Vec<u8> = vec![0; size];

        // read UDP packet into vector
        let (size, src) = match reader.read(&mut msg) {
            Err(e) => {
                debug!("Bind reader closed with {}", e);
                return;
            }
            Ok(v) => v,
        };
        msg.truncate(size);

        // TODO: start device down
        if mtu == 0 {
            continue;
        }

        // message type de-multiplexer
        if msg.len() < std::mem::size_of::<u32>() {
            continue;
        }
        match LittleEndian::read_u32(&msg[..]) {
            TYPE_COOKIE_REPLY | TYPE_INITIATION | TYPE_RESPONSE => {
                debug!("{} : reader, received handshake message", wg);
                wg.pending.fetch_add(1, Ordering::SeqCst);
                wg.queue.send(HandshakeJob::Message(msg, src));
            }
            TYPE_TRANSPORT => {
                debug!("{} : reader, received transport message", wg);

                // transport message
                let _ = wg.router.recv(src, msg).map_err(|e| {
                    debug!("Failed to handle incoming transport message: {}", e);
                });
            }
            _ => (),
        }
    }
}

pub fn handshake_worker<T: Tun, B: UDP>(
    wg: &WireGuard<T, B>,
    rx: Receiver<HandshakeJob<B::Endpoint>>,
) {
    debug!("{} : handshake worker, started", wg);

    // prepare OsRng instance for this thread
    let mut rng = OsRng::new().expect("Unable to obtain a CSPRNG");

    // process elements from the handshake queue
    for job in rx {
        // check if under load
        let job: HandshakeJob<B::Endpoint> = job;
        let pending = wg.pending.fetch_sub(1, Ordering::SeqCst);
        let mut under_load = false;

        debug_assert!(pending < MAX_QUEUED_INCOMING_HANDSHAKES + (1 << 16));

        // immediate go under load if too many handshakes pending
        if pending > THRESHOLD_UNDER_LOAD {
            *wg.last_under_load.lock() = Instant::now();
            under_load = true;
        }

        // remain under load for a while
        if !under_load {
            let elapsed = wg.last_under_load.lock().elapsed();
            if elapsed > DURATION_UNDER_LOAD {
                under_load = true;
            }
        }
        log::trace!("{} : handshake worker, under_load = {}", wg, under_load);

        // de-multiplex staged handshake jobs and handshake messages
        match job {
            HandshakeJob::Message(msg, src) => {
                // process message
                let device = wg.handshake.read();
                match device.process(
                    &mut rng,
                    &msg[..],
                    if under_load {
                        Some(src.into_address())
                    } else {
                        None
                    },
                ) {
                    Ok((pk, resp, keypair)) => {
                        // send response (might be cookie reply or handshake response)
                        let mut resp_len: u64 = 0;
                        if let Some(msg) = resp {
                            resp_len = msg.len() as u64;
                            let send: &Option<B::Writer> = &*wg.send.read();
                            if let Some(writer) = send.as_ref() {
                                debug!(
                                    "{} : handshake worker, send response ({} bytes)",
                                    wg, resp_len
                                );
                                let _ = writer.write(&msg[..], &src).map_err(|e| {
                                    debug!(
                                        "{} : handshake worker, failed to send response, error = {}",
                                        wg,
                                        e
                                    )
                                });
                            }
                        }

                        // update peer state
                        if let Some(pk) = pk {
                            // authenticated handshake packet received
                            if let Some(peer) = wg.peers.read().get(pk.as_bytes()) {
                                // add to rx_bytes and tx_bytes
                                let req_len = msg.len() as u64;
                                peer.rx_bytes.fetch_add(req_len, Ordering::Relaxed);
                                peer.tx_bytes.fetch_add(resp_len, Ordering::Relaxed);

                                // update endpoint
                                peer.router.set_endpoint(src);

                                if resp_len > 0 {
                                    // update timers after sending handshake response
                                    debug!("{} : handshake worker, handshake response sent", wg);
                                    peer.state.sent_handshake_response();
                                } else {
                                    // update timers after receiving handshake response
                                    debug!(
                                        "{} : handshake worker, handshake response was received",
                                        wg
                                    );
                                    peer.state.timers_handshake_complete();
                                }

                                // add any new keypair to peer
                                keypair.map(|kp| {
                                    debug!("{} : handshake worker, new keypair for {}", wg, peer);

                                    // this means that a handshake response was processed or sent
                                    peer.timers_session_derived();

                                    // free any unused ids
                                    for id in peer.router.add_keypair(kp) {
                                        device.release(id);
                                    }
                                });
                            }
                        }
                    }
                    Err(e) => debug!("{} : handshake worker, error = {:?}", wg, e),
                }
            }
            HandshakeJob::New(pk) => {
                if let Some(peer) = wg.peers.read().get(pk.as_bytes()) {
                    debug!(
                        "{} : handshake worker, new handshake requested for {}",
                        wg, peer
                    );
                    let device = wg.handshake.read();
                    let _ = device.begin(&mut rng, &peer.pk).map(|msg| {
                        let _ = peer.router.send(&msg[..]).map_err(|e| {
                            debug!("{} : handshake worker, failed to send handshake initiation, error = {}", wg, e)
                        });
                        peer.state.sent_handshake_initiation();
                    });
                    peer.handshake_queued.store(false, Ordering::SeqCst);
                }
            }
        }
    }
}