aboutsummaryrefslogtreecommitdiffstats
path: root/src/configuration/config.rs
blob: d68084cef5b823896eacff4fccfb892a4328144c (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
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
use spin::Mutex;
use std::net::{IpAddr, SocketAddr};
use x25519_dalek::{PublicKey, StaticSecret};

use super::*;
use bind::Owner;

/// The goal of the configuration interface is, among others,
/// to hide the IO implementations (over which the WG device is generic),
/// from the configuration and UAPI code.

/// Describes a snapshot of the state of a peer
pub struct PeerState {
    rx_bytes: u64,
    tx_bytes: u64,
    last_handshake_time_sec: u64,
    last_handshake_time_nsec: u64,
    public_key: PublicKey,
    allowed_ips: Vec<(IpAddr, u32)>,
}

pub struct WireguardConfig<T: tun::Tun, B: bind::Platform> {
    wireguard: Wireguard<T, B>,
    network: Mutex<Option<B::Owner>>,
}

impl<T: tun::Tun, B: bind::Platform> WireguardConfig<T, B> {
    fn new(wg: Wireguard<T, B>) -> WireguardConfig<T, B> {
        WireguardConfig {
            wireguard: wg,
            network: Mutex::new(None),
        }
    }
}

pub enum ConfigError {
    NoSuchPeer,
    NotListening,
    FailedToBind,
}

impl ConfigError {
    fn errno(&self) -> i32 {
        // TODO: obtain the correct error values
        match self {
            ConfigError::NoSuchPeer => 1,
            ConfigError::NotListening => 2,
            ConfigError::FailedToBind => 3,
        }
    }
}

/// Exposed configuration interface
pub trait Configuration {
    /// Updates the private key of the device
    ///
    /// # Arguments
    ///
    /// - `sk`: The new private key (or None, if the private key should be cleared)
    fn set_private_key(&self, sk: Option<StaticSecret>);

    /// Returns the private key of the device
    ///
    /// # Returns
    ///
    /// The private if set, otherwise None.
    fn get_private_key(&self) -> Option<StaticSecret>;

    /// Returns the protocol version of the device
    ///
    /// # Returns
    ///
    /// An integer indicating the protocol version
    fn get_protocol_version(&self) -> usize;

    fn set_listen_port(&self, port: Option<u16>) -> Option<ConfigError>;

    /// Set the firewall mark (or similar, depending on platform)
    ///
    /// # Arguments
    ///
    /// - `mark`: The fwmark value
    ///
    /// # Returns
    ///
    /// An error if this operation is not supported by the underlying
    /// "bind" implementation.
    fn set_fwmark(&self, mark: Option<u32>) -> Option<ConfigError>;

    /// Removes all peers from the device
    fn replace_peers(&self);

    /// Remove the peer from the
    ///
    /// # Arguments
    ///
    /// - `peer`: The public key of the peer to remove
    ///
    /// # Returns
    ///
    /// If the peer does not exists this operation is a noop
    fn remove_peer(&self, peer: &PublicKey);

    /// Adds a new peer to the device
    ///
    /// # Arguments
    ///
    /// - `peer`: The public key of the peer to add
    ///
    /// # Returns
    ///
    /// A bool indicating if the peer was added.
    ///
    /// If the peer already exists this operation is a noop
    fn add_peer(&self, peer: &PublicKey) -> bool;

    /// Update the psk of a peer
    ///
    /// # Arguments
    ///
    /// - `peer`: The public key of the peer
    /// - `psk`: The new psk or None if the psk should be unset
    ///
    /// # Returns
    ///
    /// An error if no such peer exists
    fn set_preshared_key(&self, peer: &PublicKey, psk: Option<[u8; 32]>) -> Option<ConfigError>;

    /// Update the endpoint of the
    ///
    /// # Arguments
    ///
    /// - `peer': The public key of the peer
    /// - `psk`
    fn set_endpoint(&self, peer: &PublicKey, addr: SocketAddr) -> Option<ConfigError>;

    /// Update the endpoint of the
    ///
    /// # Arguments
    ///
    /// - `peer': The public key of the peer
    /// - `psk`
    fn set_persistent_keepalive_interval(
        &self,
        peer: &PublicKey,
        interval: usize,
    ) -> Option<ConfigError>;

    /// Remove all allowed IPs from the peer
    ///
    /// # Arguments
    ///
    /// - `peer': The public key of the peer
    ///
    /// # Returns
    ///
    /// An error if no such peer exists
    fn replace_allowed_ips(&self, peer: &PublicKey) -> Option<ConfigError>;

    /// Add a new allowed subnet to the peer
    ///
    /// # Arguments
    ///
    /// - `peer`: The public key of the peer
    /// - `ip`: Subnet mask
    /// - `masklen`:
    ///
    /// # Returns
    ///
    /// An error if the peer does not exist
    ///
    /// # Note:
    ///
    /// The API must itself sanitize the (ip, masklen) set:
    /// The ip should be masked to remove any set bits right of the first "masklen" bits.
    fn add_allowed_ip(&self, peer: &PublicKey, ip: IpAddr, masklen: u32) -> Option<ConfigError>;

    /// Returns the state of all peers
    ///
    /// # Returns
    ///
    /// A list of structures describing the state of each peer
    fn get_peers(&self) -> Vec<PeerState>;
}

impl<T: tun::Tun, B: bind::Platform> Configuration for WireguardConfig<T, B> {
    fn set_private_key(&self, sk: Option<StaticSecret>) {
        self.wireguard.set_key(sk)
    }

    fn get_private_key(&self) -> Option<StaticSecret> {
        self.wireguard.get_sk()
    }

    fn get_protocol_version(&self) -> usize {
        1
    }

    fn set_listen_port(&self, port: Option<u16>) -> Option<ConfigError> {
        let mut bind = self.network.lock();

        // close the current listener
        *bind = None;

        // bind to new port
        if let Some(port) = port {
            // create new listener
            let (mut readers, writer, owner) = match B::bind(port) {
                Ok(r) => r,
                Err(_) => {
                    return Some(ConfigError::FailedToBind);
                }
            };

            // add readers/writer to wireguard
            self.wireguard.set_writer(writer);
            while let Some(reader) = readers.pop() {
                self.wireguard.add_reader(reader);
            }

            // create new UDP state
            *bind = Some(owner);
        }

        None
    }

    fn set_fwmark(&self, mark: Option<u32>) -> Option<ConfigError> {
        match self.network.lock().as_mut() {
            Some(bind) => {
                bind.set_fwmark(mark).unwrap(); // TODO: handle
                None
            }
            None => Some(ConfigError::NotListening),
        }
    }

    fn replace_peers(&self) {
        self.wireguard.clear_peers();
    }

    fn remove_peer(&self, peer: &PublicKey) {
        self.wireguard.remove_peer(peer);
    }

    fn add_peer(&self, peer: &PublicKey) -> bool {
        self.wireguard.new_peer(*peer);
        false
    }

    fn set_preshared_key(&self, peer: &PublicKey, psk: Option<[u8; 32]>) -> Option<ConfigError> {
        if self.wireguard.set_psk(*peer, psk) {
            None
        } else {
            Some(ConfigError::NoSuchPeer)
        }
    }

    fn set_endpoint(&self, peer: &PublicKey, addr: SocketAddr) -> Option<ConfigError> {
        match self.wireguard.lookup_peer(peer) {
            Some(peer) => {
                peer.router.set_endpoint(B::Endpoint::from_address(addr));
                None
            }
            None => Some(ConfigError::NoSuchPeer),
        }
    }

    fn set_persistent_keepalive_interval(
        &self,
        peer: &PublicKey,
        interval: usize,
    ) -> Option<ConfigError> {
        match self.wireguard.lookup_peer(peer) {
            Some(peer) => {
                peer.set_persistent_keepalive_interval(interval);
                None
            }
            None => Some(ConfigError::NoSuchPeer),
        }
    }

    fn replace_allowed_ips(&self, peer: &PublicKey) -> Option<ConfigError> {
        match self.wireguard.lookup_peer(peer) {
            Some(peer) => {
                peer.router.remove_allowed_ips();
                None
            }
            None => Some(ConfigError::NoSuchPeer),
        }
    }

    fn add_allowed_ip(&self, peer: &PublicKey, ip: IpAddr, masklen: u32) -> Option<ConfigError> {
        match self.wireguard.lookup_peer(peer) {
            Some(peer) => {
                peer.router.add_allowed_ip(ip, masklen);
                None
            }
            None => Some(ConfigError::NoSuchPeer),
        }
    }

    fn get_peers(&self) -> Vec<PeerState> {
        vec![]
    }
}