Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

net: WireGuard secure network tunnel

WireGuard is a layer 3 secure networking tunnel made specifically for
the kernel, that aims to be much simpler and easier to audit than IPsec.
Extensive documentation and description of the protocol and
considerations, along with formal proofs of the cryptography, are
available at:

* https://www.wireguard.com/
* https://www.wireguard.com/papers/wireguard.pdf

This commit implements WireGuard as a simple network device driver,
accessible in the usual RTNL way used by virtual network drivers. It
makes use of the udp_tunnel APIs, GRO, GSO, NAPI, and the usual set of
networking subsystem APIs. It has a somewhat novel multicore queueing
system designed for maximum throughput and minimal latency of encryption
operations, but it is implemented modestly using workqueues and NAPI.
Configuration is done via generic Netlink, and following a review from
the Netlink maintainer a year ago, several high profile userspace tools
have already implemented the API.

This commit also comes with several different tests, both in-kernel
tests and out-of-kernel tests based on network namespaces, taking profit
of the fact that sockets used by WireGuard intentionally stay in the
namespace the WireGuard interface was originally created, exactly like
the semantics of userspace tun devices. See wireguard.com/netns/ for
pictures and examples.

The source code is fairly short, but rather than combining everything
into a single file, WireGuard is developed as cleanly separable files,
making auditing and comprehension easier. Things are laid out as
follows:

* noise.[ch], cookie.[ch], messages.h: These implement the bulk of the
cryptographic aspects of the protocol, and are mostly data-only in
nature, taking in buffers of bytes and spitting out buffers of
bytes. They also handle reference counting for their various shared
pieces of data, like keys and key lists.

* ratelimiter.[ch]: Used as an integral part of cookie.[ch] for
ratelimiting certain types of cryptographic operations in accordance
with particular WireGuard semantics.

* allowedips.[ch], peerlookup.[ch]: The main lookup structures of
WireGuard, the former being trie-like with particular semantics, an
integral part of the design of the protocol, and the latter just
being nice helper functions around the various hashtables we use.

* device.[ch]: Implementation of functions for the netdevice and for
rtnl, responsible for maintaining the life of a given interface and
wiring it up to the rest of WireGuard.

* peer.[ch]: Each interface has a list of peers, with helper functions
available here for creation, destruction, and reference counting.

* socket.[ch]: Implementation of functions related to udp_socket and
the general set of kernel socket APIs, for sending and receiving
ciphertext UDP packets, and taking care of WireGuard-specific sticky
socket routing semantics for the automatic roaming.

* netlink.[ch]: Userspace API entry point for configuring WireGuard
peers and devices. The API has been implemented by several userspace
tools and network management utility, and the WireGuard project
distributes the basic wg(8) tool.

* queueing.[ch]: Shared function on the rx and tx path for handling
the various queues used in the multicore algorithms.

* send.c: Handles encrypting outgoing packets in parallel on
multiple cores, before sending them in order on a single core, via
workqueues and ring buffers. Also handles sending handshake and cookie
messages as part of the protocol, in parallel.

* receive.c: Handles decrypting incoming packets in parallel on
multiple cores, before passing them off in order to be ingested via
the rest of the networking subsystem with GRO via the typical NAPI
poll function. Also handles receiving handshake and cookie messages
as part of the protocol, in parallel.

* timers.[ch]: Uses the timer wheel to implement protocol particular
event timeouts, and gives a set of very simple event-driven entry
point functions for callers.

* main.c, version.h: Initialization and deinitialization of the module.

* selftest/*.h: Runtime unit tests for some of the most security
sensitive functions.

* tools/testing/selftests/wireguard/netns.sh: Aforementioned testing
script using network namespaces.

This commit aims to be as self-contained as possible, implementing
WireGuard as a standalone module not needing much special handling or
coordination from the network subsystem. I expect for future
optimizations to the network stack to positively improve WireGuard, and
vice-versa, but for the time being, this exists as intentionally
standalone.

We introduce a menu option for CONFIG_WIREGUARD, as well as providing a
verbose debug log and self-tests via CONFIG_WIREGUARD_DEBUG.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Cc: David Miller <davem@davemloft.net>
Cc: Greg KH <gregkh@linuxfoundation.org>
Cc: Linus Torvalds <torvalds@linux-foundation.org>
Cc: Herbert Xu <herbert@gondor.apana.org.au>
Cc: linux-crypto@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: netdev@vger.kernel.org
Signed-off-by: David S. Miller <davem@davemloft.net>

authored by

Jason A. Donenfeld and committed by
David S. Miller
e7096c13 e42617b8

+7755
+8
MAINTAINERS
··· 17850 17850 S: Maintained 17851 17851 F: drivers/gpio/gpio-ws16c48.c 17852 17852 17853 + WIREGUARD SECURE NETWORK TUNNEL 17854 + M: Jason A. Donenfeld <Jason@zx2c4.com> 17855 + S: Maintained 17856 + F: drivers/net/wireguard/ 17857 + F: tools/testing/selftests/wireguard/ 17858 + L: wireguard@lists.zx2c4.com 17859 + L: netdev@vger.kernel.org 17860 + 17853 17861 WISTRON LAPTOP BUTTON DRIVER 17854 17862 M: Miloslav Trmac <mitr@volny.cz> 17855 17863 S: Maintained
+41
drivers/net/Kconfig
··· 71 71 To compile this driver as a module, choose M here: the module 72 72 will be called dummy. 73 73 74 + config WIREGUARD 75 + tristate "WireGuard secure network tunnel" 76 + depends on NET && INET 77 + depends on IPV6 || !IPV6 78 + select NET_UDP_TUNNEL 79 + select DST_CACHE 80 + select CRYPTO 81 + select CRYPTO_LIB_CURVE25519 82 + select CRYPTO_LIB_CHACHA20POLY1305 83 + select CRYPTO_LIB_BLAKE2S 84 + select CRYPTO_CHACHA20_X86_64 if X86 && 64BIT 85 + select CRYPTO_POLY1305_X86_64 if X86 && 64BIT 86 + select CRYPTO_BLAKE2S_X86 if X86 && 64BIT 87 + select CRYPTO_CURVE25519_X86 if X86 && 64BIT 88 + select CRYPTO_CHACHA20_NEON if (ARM || ARM64) && KERNEL_MODE_NEON 89 + select CRYPTO_POLY1305_NEON if ARM64 && KERNEL_MODE_NEON 90 + select CRYPTO_POLY1305_ARM if ARM 91 + select CRYPTO_CURVE25519_NEON if ARM && KERNEL_MODE_NEON 92 + select CRYPTO_CHACHA_MIPS if CPU_MIPS32_R2 93 + select CRYPTO_POLY1305_MIPS if CPU_MIPS32 || (CPU_MIPS64 && 64BIT) 94 + help 95 + WireGuard is a secure, fast, and easy to use replacement for IPSec 96 + that uses modern cryptography and clever networking tricks. It's 97 + designed to be fairly general purpose and abstract enough to fit most 98 + use cases, while at the same time remaining extremely simple to 99 + configure. See www.wireguard.com for more info. 100 + 101 + It's safe to say Y or M here, as the driver is very lightweight and 102 + is only in use when an administrator chooses to add an interface. 103 + 104 + config WIREGUARD_DEBUG 105 + bool "Debugging checks and verbose messages" 106 + depends on WIREGUARD 107 + help 108 + This will write log messages for handshake and other events 109 + that occur for a WireGuard interface. It will also perform some 110 + extra validation checks and unit tests at various points. This is 111 + only useful for debugging. 112 + 113 + Say N here unless you know what you're doing. 114 + 74 115 config EQUALIZER 75 116 tristate "EQL (serial line load balancing) support" 76 117 ---help---
+1
drivers/net/Makefile
··· 10 10 obj-$(CONFIG_IPVLAN) += ipvlan/ 11 11 obj-$(CONFIG_IPVTAP) += ipvlan/ 12 12 obj-$(CONFIG_DUMMY) += dummy.o 13 + obj-$(CONFIG_WIREGUARD) += wireguard/ 13 14 obj-$(CONFIG_EQUALIZER) += eql.o 14 15 obj-$(CONFIG_IFB) += ifb.o 15 16 obj-$(CONFIG_MACSEC) += macsec.o
+18
drivers/net/wireguard/Makefile
··· 1 + ccflags-y := -O3 2 + ccflags-y += -D'pr_fmt(fmt)=KBUILD_MODNAME ": " fmt' 3 + ccflags-$(CONFIG_WIREGUARD_DEBUG) += -DDEBUG 4 + wireguard-y := main.o 5 + wireguard-y += noise.o 6 + wireguard-y += device.o 7 + wireguard-y += peer.o 8 + wireguard-y += timers.o 9 + wireguard-y += queueing.o 10 + wireguard-y += send.o 11 + wireguard-y += receive.o 12 + wireguard-y += socket.o 13 + wireguard-y += peerlookup.o 14 + wireguard-y += allowedips.o 15 + wireguard-y += ratelimiter.o 16 + wireguard-y += cookie.o 17 + wireguard-y += netlink.o 18 + obj-$(CONFIG_WIREGUARD) := wireguard.o
+381
drivers/net/wireguard/allowedips.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "allowedips.h" 7 + #include "peer.h" 8 + 9 + static void swap_endian(u8 *dst, const u8 *src, u8 bits) 10 + { 11 + if (bits == 32) { 12 + *(u32 *)dst = be32_to_cpu(*(const __be32 *)src); 13 + } else if (bits == 128) { 14 + ((u64 *)dst)[0] = be64_to_cpu(((const __be64 *)src)[0]); 15 + ((u64 *)dst)[1] = be64_to_cpu(((const __be64 *)src)[1]); 16 + } 17 + } 18 + 19 + static void copy_and_assign_cidr(struct allowedips_node *node, const u8 *src, 20 + u8 cidr, u8 bits) 21 + { 22 + node->cidr = cidr; 23 + node->bit_at_a = cidr / 8U; 24 + #ifdef __LITTLE_ENDIAN 25 + node->bit_at_a ^= (bits / 8U - 1U) % 8U; 26 + #endif 27 + node->bit_at_b = 7U - (cidr % 8U); 28 + node->bitlen = bits; 29 + memcpy(node->bits, src, bits / 8U); 30 + } 31 + #define CHOOSE_NODE(parent, key) \ 32 + parent->bit[(key[parent->bit_at_a] >> parent->bit_at_b) & 1] 33 + 34 + static void node_free_rcu(struct rcu_head *rcu) 35 + { 36 + kfree(container_of(rcu, struct allowedips_node, rcu)); 37 + } 38 + 39 + static void push_rcu(struct allowedips_node **stack, 40 + struct allowedips_node __rcu *p, unsigned int *len) 41 + { 42 + if (rcu_access_pointer(p)) { 43 + WARN_ON(IS_ENABLED(DEBUG) && *len >= 128); 44 + stack[(*len)++] = rcu_dereference_raw(p); 45 + } 46 + } 47 + 48 + static void root_free_rcu(struct rcu_head *rcu) 49 + { 50 + struct allowedips_node *node, *stack[128] = { 51 + container_of(rcu, struct allowedips_node, rcu) }; 52 + unsigned int len = 1; 53 + 54 + while (len > 0 && (node = stack[--len])) { 55 + push_rcu(stack, node->bit[0], &len); 56 + push_rcu(stack, node->bit[1], &len); 57 + kfree(node); 58 + } 59 + } 60 + 61 + static void root_remove_peer_lists(struct allowedips_node *root) 62 + { 63 + struct allowedips_node *node, *stack[128] = { root }; 64 + unsigned int len = 1; 65 + 66 + while (len > 0 && (node = stack[--len])) { 67 + push_rcu(stack, node->bit[0], &len); 68 + push_rcu(stack, node->bit[1], &len); 69 + if (rcu_access_pointer(node->peer)) 70 + list_del(&node->peer_list); 71 + } 72 + } 73 + 74 + static void walk_remove_by_peer(struct allowedips_node __rcu **top, 75 + struct wg_peer *peer, struct mutex *lock) 76 + { 77 + #define REF(p) rcu_access_pointer(p) 78 + #define DEREF(p) rcu_dereference_protected(*(p), lockdep_is_held(lock)) 79 + #define PUSH(p) ({ \ 80 + WARN_ON(IS_ENABLED(DEBUG) && len >= 128); \ 81 + stack[len++] = p; \ 82 + }) 83 + 84 + struct allowedips_node __rcu **stack[128], **nptr; 85 + struct allowedips_node *node, *prev; 86 + unsigned int len; 87 + 88 + if (unlikely(!peer || !REF(*top))) 89 + return; 90 + 91 + for (prev = NULL, len = 0, PUSH(top); len > 0; prev = node) { 92 + nptr = stack[len - 1]; 93 + node = DEREF(nptr); 94 + if (!node) { 95 + --len; 96 + continue; 97 + } 98 + if (!prev || REF(prev->bit[0]) == node || 99 + REF(prev->bit[1]) == node) { 100 + if (REF(node->bit[0])) 101 + PUSH(&node->bit[0]); 102 + else if (REF(node->bit[1])) 103 + PUSH(&node->bit[1]); 104 + } else if (REF(node->bit[0]) == prev) { 105 + if (REF(node->bit[1])) 106 + PUSH(&node->bit[1]); 107 + } else { 108 + if (rcu_dereference_protected(node->peer, 109 + lockdep_is_held(lock)) == peer) { 110 + RCU_INIT_POINTER(node->peer, NULL); 111 + list_del_init(&node->peer_list); 112 + if (!node->bit[0] || !node->bit[1]) { 113 + rcu_assign_pointer(*nptr, DEREF( 114 + &node->bit[!REF(node->bit[0])])); 115 + call_rcu(&node->rcu, node_free_rcu); 116 + node = DEREF(nptr); 117 + } 118 + } 119 + --len; 120 + } 121 + } 122 + 123 + #undef REF 124 + #undef DEREF 125 + #undef PUSH 126 + } 127 + 128 + static unsigned int fls128(u64 a, u64 b) 129 + { 130 + return a ? fls64(a) + 64U : fls64(b); 131 + } 132 + 133 + static u8 common_bits(const struct allowedips_node *node, const u8 *key, 134 + u8 bits) 135 + { 136 + if (bits == 32) 137 + return 32U - fls(*(const u32 *)node->bits ^ *(const u32 *)key); 138 + else if (bits == 128) 139 + return 128U - fls128( 140 + *(const u64 *)&node->bits[0] ^ *(const u64 *)&key[0], 141 + *(const u64 *)&node->bits[8] ^ *(const u64 *)&key[8]); 142 + return 0; 143 + } 144 + 145 + static bool prefix_matches(const struct allowedips_node *node, const u8 *key, 146 + u8 bits) 147 + { 148 + /* This could be much faster if it actually just compared the common 149 + * bits properly, by precomputing a mask bswap(~0 << (32 - cidr)), and 150 + * the rest, but it turns out that common_bits is already super fast on 151 + * modern processors, even taking into account the unfortunate bswap. 152 + * So, we just inline it like this instead. 153 + */ 154 + return common_bits(node, key, bits) >= node->cidr; 155 + } 156 + 157 + static struct allowedips_node *find_node(struct allowedips_node *trie, u8 bits, 158 + const u8 *key) 159 + { 160 + struct allowedips_node *node = trie, *found = NULL; 161 + 162 + while (node && prefix_matches(node, key, bits)) { 163 + if (rcu_access_pointer(node->peer)) 164 + found = node; 165 + if (node->cidr == bits) 166 + break; 167 + node = rcu_dereference_bh(CHOOSE_NODE(node, key)); 168 + } 169 + return found; 170 + } 171 + 172 + /* Returns a strong reference to a peer */ 173 + static struct wg_peer *lookup(struct allowedips_node __rcu *root, u8 bits, 174 + const void *be_ip) 175 + { 176 + /* Aligned so it can be passed to fls/fls64 */ 177 + u8 ip[16] __aligned(__alignof(u64)); 178 + struct allowedips_node *node; 179 + struct wg_peer *peer = NULL; 180 + 181 + swap_endian(ip, be_ip, bits); 182 + 183 + rcu_read_lock_bh(); 184 + retry: 185 + node = find_node(rcu_dereference_bh(root), bits, ip); 186 + if (node) { 187 + peer = wg_peer_get_maybe_zero(rcu_dereference_bh(node->peer)); 188 + if (!peer) 189 + goto retry; 190 + } 191 + rcu_read_unlock_bh(); 192 + return peer; 193 + } 194 + 195 + static bool node_placement(struct allowedips_node __rcu *trie, const u8 *key, 196 + u8 cidr, u8 bits, struct allowedips_node **rnode, 197 + struct mutex *lock) 198 + { 199 + struct allowedips_node *node = rcu_dereference_protected(trie, 200 + lockdep_is_held(lock)); 201 + struct allowedips_node *parent = NULL; 202 + bool exact = false; 203 + 204 + while (node && node->cidr <= cidr && prefix_matches(node, key, bits)) { 205 + parent = node; 206 + if (parent->cidr == cidr) { 207 + exact = true; 208 + break; 209 + } 210 + node = rcu_dereference_protected(CHOOSE_NODE(parent, key), 211 + lockdep_is_held(lock)); 212 + } 213 + *rnode = parent; 214 + return exact; 215 + } 216 + 217 + static int add(struct allowedips_node __rcu **trie, u8 bits, const u8 *key, 218 + u8 cidr, struct wg_peer *peer, struct mutex *lock) 219 + { 220 + struct allowedips_node *node, *parent, *down, *newnode; 221 + 222 + if (unlikely(cidr > bits || !peer)) 223 + return -EINVAL; 224 + 225 + if (!rcu_access_pointer(*trie)) { 226 + node = kzalloc(sizeof(*node), GFP_KERNEL); 227 + if (unlikely(!node)) 228 + return -ENOMEM; 229 + RCU_INIT_POINTER(node->peer, peer); 230 + list_add_tail(&node->peer_list, &peer->allowedips_list); 231 + copy_and_assign_cidr(node, key, cidr, bits); 232 + rcu_assign_pointer(*trie, node); 233 + return 0; 234 + } 235 + if (node_placement(*trie, key, cidr, bits, &node, lock)) { 236 + rcu_assign_pointer(node->peer, peer); 237 + list_move_tail(&node->peer_list, &peer->allowedips_list); 238 + return 0; 239 + } 240 + 241 + newnode = kzalloc(sizeof(*newnode), GFP_KERNEL); 242 + if (unlikely(!newnode)) 243 + return -ENOMEM; 244 + RCU_INIT_POINTER(newnode->peer, peer); 245 + list_add_tail(&newnode->peer_list, &peer->allowedips_list); 246 + copy_and_assign_cidr(newnode, key, cidr, bits); 247 + 248 + if (!node) { 249 + down = rcu_dereference_protected(*trie, lockdep_is_held(lock)); 250 + } else { 251 + down = rcu_dereference_protected(CHOOSE_NODE(node, key), 252 + lockdep_is_held(lock)); 253 + if (!down) { 254 + rcu_assign_pointer(CHOOSE_NODE(node, key), newnode); 255 + return 0; 256 + } 257 + } 258 + cidr = min(cidr, common_bits(down, key, bits)); 259 + parent = node; 260 + 261 + if (newnode->cidr == cidr) { 262 + rcu_assign_pointer(CHOOSE_NODE(newnode, down->bits), down); 263 + if (!parent) 264 + rcu_assign_pointer(*trie, newnode); 265 + else 266 + rcu_assign_pointer(CHOOSE_NODE(parent, newnode->bits), 267 + newnode); 268 + } else { 269 + node = kzalloc(sizeof(*node), GFP_KERNEL); 270 + if (unlikely(!node)) { 271 + kfree(newnode); 272 + return -ENOMEM; 273 + } 274 + INIT_LIST_HEAD(&node->peer_list); 275 + copy_and_assign_cidr(node, newnode->bits, cidr, bits); 276 + 277 + rcu_assign_pointer(CHOOSE_NODE(node, down->bits), down); 278 + rcu_assign_pointer(CHOOSE_NODE(node, newnode->bits), newnode); 279 + if (!parent) 280 + rcu_assign_pointer(*trie, node); 281 + else 282 + rcu_assign_pointer(CHOOSE_NODE(parent, node->bits), 283 + node); 284 + } 285 + return 0; 286 + } 287 + 288 + void wg_allowedips_init(struct allowedips *table) 289 + { 290 + table->root4 = table->root6 = NULL; 291 + table->seq = 1; 292 + } 293 + 294 + void wg_allowedips_free(struct allowedips *table, struct mutex *lock) 295 + { 296 + struct allowedips_node __rcu *old4 = table->root4, *old6 = table->root6; 297 + 298 + ++table->seq; 299 + RCU_INIT_POINTER(table->root4, NULL); 300 + RCU_INIT_POINTER(table->root6, NULL); 301 + if (rcu_access_pointer(old4)) { 302 + struct allowedips_node *node = rcu_dereference_protected(old4, 303 + lockdep_is_held(lock)); 304 + 305 + root_remove_peer_lists(node); 306 + call_rcu(&node->rcu, root_free_rcu); 307 + } 308 + if (rcu_access_pointer(old6)) { 309 + struct allowedips_node *node = rcu_dereference_protected(old6, 310 + lockdep_is_held(lock)); 311 + 312 + root_remove_peer_lists(node); 313 + call_rcu(&node->rcu, root_free_rcu); 314 + } 315 + } 316 + 317 + int wg_allowedips_insert_v4(struct allowedips *table, const struct in_addr *ip, 318 + u8 cidr, struct wg_peer *peer, struct mutex *lock) 319 + { 320 + /* Aligned so it can be passed to fls */ 321 + u8 key[4] __aligned(__alignof(u32)); 322 + 323 + ++table->seq; 324 + swap_endian(key, (const u8 *)ip, 32); 325 + return add(&table->root4, 32, key, cidr, peer, lock); 326 + } 327 + 328 + int wg_allowedips_insert_v6(struct allowedips *table, const struct in6_addr *ip, 329 + u8 cidr, struct wg_peer *peer, struct mutex *lock) 330 + { 331 + /* Aligned so it can be passed to fls64 */ 332 + u8 key[16] __aligned(__alignof(u64)); 333 + 334 + ++table->seq; 335 + swap_endian(key, (const u8 *)ip, 128); 336 + return add(&table->root6, 128, key, cidr, peer, lock); 337 + } 338 + 339 + void wg_allowedips_remove_by_peer(struct allowedips *table, 340 + struct wg_peer *peer, struct mutex *lock) 341 + { 342 + ++table->seq; 343 + walk_remove_by_peer(&table->root4, peer, lock); 344 + walk_remove_by_peer(&table->root6, peer, lock); 345 + } 346 + 347 + int wg_allowedips_read_node(struct allowedips_node *node, u8 ip[16], u8 *cidr) 348 + { 349 + const unsigned int cidr_bytes = DIV_ROUND_UP(node->cidr, 8U); 350 + swap_endian(ip, node->bits, node->bitlen); 351 + memset(ip + cidr_bytes, 0, node->bitlen / 8U - cidr_bytes); 352 + if (node->cidr) 353 + ip[cidr_bytes - 1U] &= ~0U << (-node->cidr % 8U); 354 + 355 + *cidr = node->cidr; 356 + return node->bitlen == 32 ? AF_INET : AF_INET6; 357 + } 358 + 359 + /* Returns a strong reference to a peer */ 360 + struct wg_peer *wg_allowedips_lookup_dst(struct allowedips *table, 361 + struct sk_buff *skb) 362 + { 363 + if (skb->protocol == htons(ETH_P_IP)) 364 + return lookup(table->root4, 32, &ip_hdr(skb)->daddr); 365 + else if (skb->protocol == htons(ETH_P_IPV6)) 366 + return lookup(table->root6, 128, &ipv6_hdr(skb)->daddr); 367 + return NULL; 368 + } 369 + 370 + /* Returns a strong reference to a peer */ 371 + struct wg_peer *wg_allowedips_lookup_src(struct allowedips *table, 372 + struct sk_buff *skb) 373 + { 374 + if (skb->protocol == htons(ETH_P_IP)) 375 + return lookup(table->root4, 32, &ip_hdr(skb)->saddr); 376 + else if (skb->protocol == htons(ETH_P_IPV6)) 377 + return lookup(table->root6, 128, &ipv6_hdr(skb)->saddr); 378 + return NULL; 379 + } 380 + 381 + #include "selftest/allowedips.c"
+59
drivers/net/wireguard/allowedips.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_ALLOWEDIPS_H 7 + #define _WG_ALLOWEDIPS_H 8 + 9 + #include <linux/mutex.h> 10 + #include <linux/ip.h> 11 + #include <linux/ipv6.h> 12 + 13 + struct wg_peer; 14 + 15 + struct allowedips_node { 16 + struct wg_peer __rcu *peer; 17 + struct allowedips_node __rcu *bit[2]; 18 + /* While it may seem scandalous that we waste space for v4, 19 + * we're alloc'ing to the nearest power of 2 anyway, so this 20 + * doesn't actually make a difference. 21 + */ 22 + u8 bits[16] __aligned(__alignof(u64)); 23 + u8 cidr, bit_at_a, bit_at_b, bitlen; 24 + 25 + /* Keep rarely used list at bottom to be beyond cache line. */ 26 + union { 27 + struct list_head peer_list; 28 + struct rcu_head rcu; 29 + }; 30 + }; 31 + 32 + struct allowedips { 33 + struct allowedips_node __rcu *root4; 34 + struct allowedips_node __rcu *root6; 35 + u64 seq; 36 + }; 37 + 38 + void wg_allowedips_init(struct allowedips *table); 39 + void wg_allowedips_free(struct allowedips *table, struct mutex *mutex); 40 + int wg_allowedips_insert_v4(struct allowedips *table, const struct in_addr *ip, 41 + u8 cidr, struct wg_peer *peer, struct mutex *lock); 42 + int wg_allowedips_insert_v6(struct allowedips *table, const struct in6_addr *ip, 43 + u8 cidr, struct wg_peer *peer, struct mutex *lock); 44 + void wg_allowedips_remove_by_peer(struct allowedips *table, 45 + struct wg_peer *peer, struct mutex *lock); 46 + /* The ip input pointer should be __aligned(__alignof(u64))) */ 47 + int wg_allowedips_read_node(struct allowedips_node *node, u8 ip[16], u8 *cidr); 48 + 49 + /* These return a strong reference to a peer: */ 50 + struct wg_peer *wg_allowedips_lookup_dst(struct allowedips *table, 51 + struct sk_buff *skb); 52 + struct wg_peer *wg_allowedips_lookup_src(struct allowedips *table, 53 + struct sk_buff *skb); 54 + 55 + #ifdef DEBUG 56 + bool wg_allowedips_selftest(void); 57 + #endif 58 + 59 + #endif /* _WG_ALLOWEDIPS_H */
+236
drivers/net/wireguard/cookie.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "cookie.h" 7 + #include "peer.h" 8 + #include "device.h" 9 + #include "messages.h" 10 + #include "ratelimiter.h" 11 + #include "timers.h" 12 + 13 + #include <crypto/blake2s.h> 14 + #include <crypto/chacha20poly1305.h> 15 + 16 + #include <net/ipv6.h> 17 + #include <crypto/algapi.h> 18 + 19 + void wg_cookie_checker_init(struct cookie_checker *checker, 20 + struct wg_device *wg) 21 + { 22 + init_rwsem(&checker->secret_lock); 23 + checker->secret_birthdate = ktime_get_coarse_boottime_ns(); 24 + get_random_bytes(checker->secret, NOISE_HASH_LEN); 25 + checker->device = wg; 26 + } 27 + 28 + enum { COOKIE_KEY_LABEL_LEN = 8 }; 29 + static const u8 mac1_key_label[COOKIE_KEY_LABEL_LEN] = "mac1----"; 30 + static const u8 cookie_key_label[COOKIE_KEY_LABEL_LEN] = "cookie--"; 31 + 32 + static void precompute_key(u8 key[NOISE_SYMMETRIC_KEY_LEN], 33 + const u8 pubkey[NOISE_PUBLIC_KEY_LEN], 34 + const u8 label[COOKIE_KEY_LABEL_LEN]) 35 + { 36 + struct blake2s_state blake; 37 + 38 + blake2s_init(&blake, NOISE_SYMMETRIC_KEY_LEN); 39 + blake2s_update(&blake, label, COOKIE_KEY_LABEL_LEN); 40 + blake2s_update(&blake, pubkey, NOISE_PUBLIC_KEY_LEN); 41 + blake2s_final(&blake, key); 42 + } 43 + 44 + /* Must hold peer->handshake.static_identity->lock */ 45 + void wg_cookie_checker_precompute_device_keys(struct cookie_checker *checker) 46 + { 47 + if (likely(checker->device->static_identity.has_identity)) { 48 + precompute_key(checker->cookie_encryption_key, 49 + checker->device->static_identity.static_public, 50 + cookie_key_label); 51 + precompute_key(checker->message_mac1_key, 52 + checker->device->static_identity.static_public, 53 + mac1_key_label); 54 + } else { 55 + memset(checker->cookie_encryption_key, 0, 56 + NOISE_SYMMETRIC_KEY_LEN); 57 + memset(checker->message_mac1_key, 0, NOISE_SYMMETRIC_KEY_LEN); 58 + } 59 + } 60 + 61 + void wg_cookie_checker_precompute_peer_keys(struct wg_peer *peer) 62 + { 63 + precompute_key(peer->latest_cookie.cookie_decryption_key, 64 + peer->handshake.remote_static, cookie_key_label); 65 + precompute_key(peer->latest_cookie.message_mac1_key, 66 + peer->handshake.remote_static, mac1_key_label); 67 + } 68 + 69 + void wg_cookie_init(struct cookie *cookie) 70 + { 71 + memset(cookie, 0, sizeof(*cookie)); 72 + init_rwsem(&cookie->lock); 73 + } 74 + 75 + static void compute_mac1(u8 mac1[COOKIE_LEN], const void *message, size_t len, 76 + const u8 key[NOISE_SYMMETRIC_KEY_LEN]) 77 + { 78 + len = len - sizeof(struct message_macs) + 79 + offsetof(struct message_macs, mac1); 80 + blake2s(mac1, message, key, COOKIE_LEN, len, NOISE_SYMMETRIC_KEY_LEN); 81 + } 82 + 83 + static void compute_mac2(u8 mac2[COOKIE_LEN], const void *message, size_t len, 84 + const u8 cookie[COOKIE_LEN]) 85 + { 86 + len = len - sizeof(struct message_macs) + 87 + offsetof(struct message_macs, mac2); 88 + blake2s(mac2, message, cookie, COOKIE_LEN, len, COOKIE_LEN); 89 + } 90 + 91 + static void make_cookie(u8 cookie[COOKIE_LEN], struct sk_buff *skb, 92 + struct cookie_checker *checker) 93 + { 94 + struct blake2s_state state; 95 + 96 + if (wg_birthdate_has_expired(checker->secret_birthdate, 97 + COOKIE_SECRET_MAX_AGE)) { 98 + down_write(&checker->secret_lock); 99 + checker->secret_birthdate = ktime_get_coarse_boottime_ns(); 100 + get_random_bytes(checker->secret, NOISE_HASH_LEN); 101 + up_write(&checker->secret_lock); 102 + } 103 + 104 + down_read(&checker->secret_lock); 105 + 106 + blake2s_init_key(&state, COOKIE_LEN, checker->secret, NOISE_HASH_LEN); 107 + if (skb->protocol == htons(ETH_P_IP)) 108 + blake2s_update(&state, (u8 *)&ip_hdr(skb)->saddr, 109 + sizeof(struct in_addr)); 110 + else if (skb->protocol == htons(ETH_P_IPV6)) 111 + blake2s_update(&state, (u8 *)&ipv6_hdr(skb)->saddr, 112 + sizeof(struct in6_addr)); 113 + blake2s_update(&state, (u8 *)&udp_hdr(skb)->source, sizeof(__be16)); 114 + blake2s_final(&state, cookie); 115 + 116 + up_read(&checker->secret_lock); 117 + } 118 + 119 + enum cookie_mac_state wg_cookie_validate_packet(struct cookie_checker *checker, 120 + struct sk_buff *skb, 121 + bool check_cookie) 122 + { 123 + struct message_macs *macs = (struct message_macs *) 124 + (skb->data + skb->len - sizeof(*macs)); 125 + enum cookie_mac_state ret; 126 + u8 computed_mac[COOKIE_LEN]; 127 + u8 cookie[COOKIE_LEN]; 128 + 129 + ret = INVALID_MAC; 130 + compute_mac1(computed_mac, skb->data, skb->len, 131 + checker->message_mac1_key); 132 + if (crypto_memneq(computed_mac, macs->mac1, COOKIE_LEN)) 133 + goto out; 134 + 135 + ret = VALID_MAC_BUT_NO_COOKIE; 136 + 137 + if (!check_cookie) 138 + goto out; 139 + 140 + make_cookie(cookie, skb, checker); 141 + 142 + compute_mac2(computed_mac, skb->data, skb->len, cookie); 143 + if (crypto_memneq(computed_mac, macs->mac2, COOKIE_LEN)) 144 + goto out; 145 + 146 + ret = VALID_MAC_WITH_COOKIE_BUT_RATELIMITED; 147 + if (!wg_ratelimiter_allow(skb, dev_net(checker->device->dev))) 148 + goto out; 149 + 150 + ret = VALID_MAC_WITH_COOKIE; 151 + 152 + out: 153 + return ret; 154 + } 155 + 156 + void wg_cookie_add_mac_to_packet(void *message, size_t len, 157 + struct wg_peer *peer) 158 + { 159 + struct message_macs *macs = (struct message_macs *) 160 + ((u8 *)message + len - sizeof(*macs)); 161 + 162 + down_write(&peer->latest_cookie.lock); 163 + compute_mac1(macs->mac1, message, len, 164 + peer->latest_cookie.message_mac1_key); 165 + memcpy(peer->latest_cookie.last_mac1_sent, macs->mac1, COOKIE_LEN); 166 + peer->latest_cookie.have_sent_mac1 = true; 167 + up_write(&peer->latest_cookie.lock); 168 + 169 + down_read(&peer->latest_cookie.lock); 170 + if (peer->latest_cookie.is_valid && 171 + !wg_birthdate_has_expired(peer->latest_cookie.birthdate, 172 + COOKIE_SECRET_MAX_AGE - COOKIE_SECRET_LATENCY)) 173 + compute_mac2(macs->mac2, message, len, 174 + peer->latest_cookie.cookie); 175 + else 176 + memset(macs->mac2, 0, COOKIE_LEN); 177 + up_read(&peer->latest_cookie.lock); 178 + } 179 + 180 + void wg_cookie_message_create(struct message_handshake_cookie *dst, 181 + struct sk_buff *skb, __le32 index, 182 + struct cookie_checker *checker) 183 + { 184 + struct message_macs *macs = (struct message_macs *) 185 + ((u8 *)skb->data + skb->len - sizeof(*macs)); 186 + u8 cookie[COOKIE_LEN]; 187 + 188 + dst->header.type = cpu_to_le32(MESSAGE_HANDSHAKE_COOKIE); 189 + dst->receiver_index = index; 190 + get_random_bytes_wait(dst->nonce, COOKIE_NONCE_LEN); 191 + 192 + make_cookie(cookie, skb, checker); 193 + xchacha20poly1305_encrypt(dst->encrypted_cookie, cookie, COOKIE_LEN, 194 + macs->mac1, COOKIE_LEN, dst->nonce, 195 + checker->cookie_encryption_key); 196 + } 197 + 198 + void wg_cookie_message_consume(struct message_handshake_cookie *src, 199 + struct wg_device *wg) 200 + { 201 + struct wg_peer *peer = NULL; 202 + u8 cookie[COOKIE_LEN]; 203 + bool ret; 204 + 205 + if (unlikely(!wg_index_hashtable_lookup(wg->index_hashtable, 206 + INDEX_HASHTABLE_HANDSHAKE | 207 + INDEX_HASHTABLE_KEYPAIR, 208 + src->receiver_index, &peer))) 209 + return; 210 + 211 + down_read(&peer->latest_cookie.lock); 212 + if (unlikely(!peer->latest_cookie.have_sent_mac1)) { 213 + up_read(&peer->latest_cookie.lock); 214 + goto out; 215 + } 216 + ret = xchacha20poly1305_decrypt( 217 + cookie, src->encrypted_cookie, sizeof(src->encrypted_cookie), 218 + peer->latest_cookie.last_mac1_sent, COOKIE_LEN, src->nonce, 219 + peer->latest_cookie.cookie_decryption_key); 220 + up_read(&peer->latest_cookie.lock); 221 + 222 + if (ret) { 223 + down_write(&peer->latest_cookie.lock); 224 + memcpy(peer->latest_cookie.cookie, cookie, COOKIE_LEN); 225 + peer->latest_cookie.birthdate = ktime_get_coarse_boottime_ns(); 226 + peer->latest_cookie.is_valid = true; 227 + peer->latest_cookie.have_sent_mac1 = false; 228 + up_write(&peer->latest_cookie.lock); 229 + } else { 230 + net_dbg_ratelimited("%s: Could not decrypt invalid cookie response\n", 231 + wg->dev->name); 232 + } 233 + 234 + out: 235 + wg_peer_put(peer); 236 + }
+59
drivers/net/wireguard/cookie.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_COOKIE_H 7 + #define _WG_COOKIE_H 8 + 9 + #include "messages.h" 10 + #include <linux/rwsem.h> 11 + 12 + struct wg_peer; 13 + 14 + struct cookie_checker { 15 + u8 secret[NOISE_HASH_LEN]; 16 + u8 cookie_encryption_key[NOISE_SYMMETRIC_KEY_LEN]; 17 + u8 message_mac1_key[NOISE_SYMMETRIC_KEY_LEN]; 18 + u64 secret_birthdate; 19 + struct rw_semaphore secret_lock; 20 + struct wg_device *device; 21 + }; 22 + 23 + struct cookie { 24 + u64 birthdate; 25 + bool is_valid; 26 + u8 cookie[COOKIE_LEN]; 27 + bool have_sent_mac1; 28 + u8 last_mac1_sent[COOKIE_LEN]; 29 + u8 cookie_decryption_key[NOISE_SYMMETRIC_KEY_LEN]; 30 + u8 message_mac1_key[NOISE_SYMMETRIC_KEY_LEN]; 31 + struct rw_semaphore lock; 32 + }; 33 + 34 + enum cookie_mac_state { 35 + INVALID_MAC, 36 + VALID_MAC_BUT_NO_COOKIE, 37 + VALID_MAC_WITH_COOKIE_BUT_RATELIMITED, 38 + VALID_MAC_WITH_COOKIE 39 + }; 40 + 41 + void wg_cookie_checker_init(struct cookie_checker *checker, 42 + struct wg_device *wg); 43 + void wg_cookie_checker_precompute_device_keys(struct cookie_checker *checker); 44 + void wg_cookie_checker_precompute_peer_keys(struct wg_peer *peer); 45 + void wg_cookie_init(struct cookie *cookie); 46 + 47 + enum cookie_mac_state wg_cookie_validate_packet(struct cookie_checker *checker, 48 + struct sk_buff *skb, 49 + bool check_cookie); 50 + void wg_cookie_add_mac_to_packet(void *message, size_t len, 51 + struct wg_peer *peer); 52 + 53 + void wg_cookie_message_create(struct message_handshake_cookie *src, 54 + struct sk_buff *skb, __le32 index, 55 + struct cookie_checker *checker); 56 + void wg_cookie_message_consume(struct message_handshake_cookie *src, 57 + struct wg_device *wg); 58 + 59 + #endif /* _WG_COOKIE_H */
+458
drivers/net/wireguard/device.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "queueing.h" 7 + #include "socket.h" 8 + #include "timers.h" 9 + #include "device.h" 10 + #include "ratelimiter.h" 11 + #include "peer.h" 12 + #include "messages.h" 13 + 14 + #include <linux/module.h> 15 + #include <linux/rtnetlink.h> 16 + #include <linux/inet.h> 17 + #include <linux/netdevice.h> 18 + #include <linux/inetdevice.h> 19 + #include <linux/if_arp.h> 20 + #include <linux/icmp.h> 21 + #include <linux/suspend.h> 22 + #include <net/icmp.h> 23 + #include <net/rtnetlink.h> 24 + #include <net/ip_tunnels.h> 25 + #include <net/addrconf.h> 26 + 27 + static LIST_HEAD(device_list); 28 + 29 + static int wg_open(struct net_device *dev) 30 + { 31 + struct in_device *dev_v4 = __in_dev_get_rtnl(dev); 32 + struct inet6_dev *dev_v6 = __in6_dev_get(dev); 33 + struct wg_device *wg = netdev_priv(dev); 34 + struct wg_peer *peer; 35 + int ret; 36 + 37 + if (dev_v4) { 38 + /* At some point we might put this check near the ip_rt_send_ 39 + * redirect call of ip_forward in net/ipv4/ip_forward.c, similar 40 + * to the current secpath check. 41 + */ 42 + IN_DEV_CONF_SET(dev_v4, SEND_REDIRECTS, false); 43 + IPV4_DEVCONF_ALL(dev_net(dev), SEND_REDIRECTS) = false; 44 + } 45 + if (dev_v6) 46 + dev_v6->cnf.addr_gen_mode = IN6_ADDR_GEN_MODE_NONE; 47 + 48 + ret = wg_socket_init(wg, wg->incoming_port); 49 + if (ret < 0) 50 + return ret; 51 + mutex_lock(&wg->device_update_lock); 52 + list_for_each_entry(peer, &wg->peer_list, peer_list) { 53 + wg_packet_send_staged_packets(peer); 54 + if (peer->persistent_keepalive_interval) 55 + wg_packet_send_keepalive(peer); 56 + } 57 + mutex_unlock(&wg->device_update_lock); 58 + return 0; 59 + } 60 + 61 + #ifdef CONFIG_PM_SLEEP 62 + static int wg_pm_notification(struct notifier_block *nb, unsigned long action, 63 + void *data) 64 + { 65 + struct wg_device *wg; 66 + struct wg_peer *peer; 67 + 68 + /* If the machine is constantly suspending and resuming, as part of 69 + * its normal operation rather than as a somewhat rare event, then we 70 + * don't actually want to clear keys. 71 + */ 72 + if (IS_ENABLED(CONFIG_PM_AUTOSLEEP) || IS_ENABLED(CONFIG_ANDROID)) 73 + return 0; 74 + 75 + if (action != PM_HIBERNATION_PREPARE && action != PM_SUSPEND_PREPARE) 76 + return 0; 77 + 78 + rtnl_lock(); 79 + list_for_each_entry(wg, &device_list, device_list) { 80 + mutex_lock(&wg->device_update_lock); 81 + list_for_each_entry(peer, &wg->peer_list, peer_list) { 82 + del_timer(&peer->timer_zero_key_material); 83 + wg_noise_handshake_clear(&peer->handshake); 84 + wg_noise_keypairs_clear(&peer->keypairs); 85 + } 86 + mutex_unlock(&wg->device_update_lock); 87 + } 88 + rtnl_unlock(); 89 + rcu_barrier(); 90 + return 0; 91 + } 92 + 93 + static struct notifier_block pm_notifier = { .notifier_call = wg_pm_notification }; 94 + #endif 95 + 96 + static int wg_stop(struct net_device *dev) 97 + { 98 + struct wg_device *wg = netdev_priv(dev); 99 + struct wg_peer *peer; 100 + 101 + mutex_lock(&wg->device_update_lock); 102 + list_for_each_entry(peer, &wg->peer_list, peer_list) { 103 + wg_packet_purge_staged_packets(peer); 104 + wg_timers_stop(peer); 105 + wg_noise_handshake_clear(&peer->handshake); 106 + wg_noise_keypairs_clear(&peer->keypairs); 107 + wg_noise_reset_last_sent_handshake(&peer->last_sent_handshake); 108 + } 109 + mutex_unlock(&wg->device_update_lock); 110 + skb_queue_purge(&wg->incoming_handshakes); 111 + wg_socket_reinit(wg, NULL, NULL); 112 + return 0; 113 + } 114 + 115 + static netdev_tx_t wg_xmit(struct sk_buff *skb, struct net_device *dev) 116 + { 117 + struct wg_device *wg = netdev_priv(dev); 118 + struct sk_buff_head packets; 119 + struct wg_peer *peer; 120 + struct sk_buff *next; 121 + sa_family_t family; 122 + u32 mtu; 123 + int ret; 124 + 125 + if (unlikely(wg_skb_examine_untrusted_ip_hdr(skb) != skb->protocol)) { 126 + ret = -EPROTONOSUPPORT; 127 + net_dbg_ratelimited("%s: Invalid IP packet\n", dev->name); 128 + goto err; 129 + } 130 + 131 + peer = wg_allowedips_lookup_dst(&wg->peer_allowedips, skb); 132 + if (unlikely(!peer)) { 133 + ret = -ENOKEY; 134 + if (skb->protocol == htons(ETH_P_IP)) 135 + net_dbg_ratelimited("%s: No peer has allowed IPs matching %pI4\n", 136 + dev->name, &ip_hdr(skb)->daddr); 137 + else if (skb->protocol == htons(ETH_P_IPV6)) 138 + net_dbg_ratelimited("%s: No peer has allowed IPs matching %pI6\n", 139 + dev->name, &ipv6_hdr(skb)->daddr); 140 + goto err; 141 + } 142 + 143 + family = READ_ONCE(peer->endpoint.addr.sa_family); 144 + if (unlikely(family != AF_INET && family != AF_INET6)) { 145 + ret = -EDESTADDRREQ; 146 + net_dbg_ratelimited("%s: No valid endpoint has been configured or discovered for peer %llu\n", 147 + dev->name, peer->internal_id); 148 + goto err_peer; 149 + } 150 + 151 + mtu = skb_dst(skb) ? dst_mtu(skb_dst(skb)) : dev->mtu; 152 + 153 + __skb_queue_head_init(&packets); 154 + if (!skb_is_gso(skb)) { 155 + skb_mark_not_on_list(skb); 156 + } else { 157 + struct sk_buff *segs = skb_gso_segment(skb, 0); 158 + 159 + if (unlikely(IS_ERR(segs))) { 160 + ret = PTR_ERR(segs); 161 + goto err_peer; 162 + } 163 + dev_kfree_skb(skb); 164 + skb = segs; 165 + } 166 + 167 + skb_list_walk_safe(skb, skb, next) { 168 + skb_mark_not_on_list(skb); 169 + 170 + skb = skb_share_check(skb, GFP_ATOMIC); 171 + if (unlikely(!skb)) 172 + continue; 173 + 174 + /* We only need to keep the original dst around for icmp, 175 + * so at this point we're in a position to drop it. 176 + */ 177 + skb_dst_drop(skb); 178 + 179 + PACKET_CB(skb)->mtu = mtu; 180 + 181 + __skb_queue_tail(&packets, skb); 182 + } 183 + 184 + spin_lock_bh(&peer->staged_packet_queue.lock); 185 + /* If the queue is getting too big, we start removing the oldest packets 186 + * until it's small again. We do this before adding the new packet, so 187 + * we don't remove GSO segments that are in excess. 188 + */ 189 + while (skb_queue_len(&peer->staged_packet_queue) > MAX_STAGED_PACKETS) { 190 + dev_kfree_skb(__skb_dequeue(&peer->staged_packet_queue)); 191 + ++dev->stats.tx_dropped; 192 + } 193 + skb_queue_splice_tail(&packets, &peer->staged_packet_queue); 194 + spin_unlock_bh(&peer->staged_packet_queue.lock); 195 + 196 + wg_packet_send_staged_packets(peer); 197 + 198 + wg_peer_put(peer); 199 + return NETDEV_TX_OK; 200 + 201 + err_peer: 202 + wg_peer_put(peer); 203 + err: 204 + ++dev->stats.tx_errors; 205 + if (skb->protocol == htons(ETH_P_IP)) 206 + icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); 207 + else if (skb->protocol == htons(ETH_P_IPV6)) 208 + icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_ADDR_UNREACH, 0); 209 + kfree_skb(skb); 210 + return ret; 211 + } 212 + 213 + static const struct net_device_ops netdev_ops = { 214 + .ndo_open = wg_open, 215 + .ndo_stop = wg_stop, 216 + .ndo_start_xmit = wg_xmit, 217 + .ndo_get_stats64 = ip_tunnel_get_stats64 218 + }; 219 + 220 + static void wg_destruct(struct net_device *dev) 221 + { 222 + struct wg_device *wg = netdev_priv(dev); 223 + 224 + rtnl_lock(); 225 + list_del(&wg->device_list); 226 + rtnl_unlock(); 227 + mutex_lock(&wg->device_update_lock); 228 + wg->incoming_port = 0; 229 + wg_socket_reinit(wg, NULL, NULL); 230 + /* The final references are cleared in the below calls to destroy_workqueue. */ 231 + wg_peer_remove_all(wg); 232 + destroy_workqueue(wg->handshake_receive_wq); 233 + destroy_workqueue(wg->handshake_send_wq); 234 + destroy_workqueue(wg->packet_crypt_wq); 235 + wg_packet_queue_free(&wg->decrypt_queue, true); 236 + wg_packet_queue_free(&wg->encrypt_queue, true); 237 + rcu_barrier(); /* Wait for all the peers to be actually freed. */ 238 + wg_ratelimiter_uninit(); 239 + memzero_explicit(&wg->static_identity, sizeof(wg->static_identity)); 240 + skb_queue_purge(&wg->incoming_handshakes); 241 + free_percpu(dev->tstats); 242 + free_percpu(wg->incoming_handshakes_worker); 243 + if (wg->have_creating_net_ref) 244 + put_net(wg->creating_net); 245 + kvfree(wg->index_hashtable); 246 + kvfree(wg->peer_hashtable); 247 + mutex_unlock(&wg->device_update_lock); 248 + 249 + pr_debug("%s: Interface deleted\n", dev->name); 250 + free_netdev(dev); 251 + } 252 + 253 + static const struct device_type device_type = { .name = KBUILD_MODNAME }; 254 + 255 + static void wg_setup(struct net_device *dev) 256 + { 257 + struct wg_device *wg = netdev_priv(dev); 258 + enum { WG_NETDEV_FEATURES = NETIF_F_HW_CSUM | NETIF_F_RXCSUM | 259 + NETIF_F_SG | NETIF_F_GSO | 260 + NETIF_F_GSO_SOFTWARE | NETIF_F_HIGHDMA }; 261 + 262 + dev->netdev_ops = &netdev_ops; 263 + dev->hard_header_len = 0; 264 + dev->addr_len = 0; 265 + dev->needed_headroom = DATA_PACKET_HEAD_ROOM; 266 + dev->needed_tailroom = noise_encrypted_len(MESSAGE_PADDING_MULTIPLE); 267 + dev->type = ARPHRD_NONE; 268 + dev->flags = IFF_POINTOPOINT | IFF_NOARP; 269 + dev->priv_flags |= IFF_NO_QUEUE; 270 + dev->features |= NETIF_F_LLTX; 271 + dev->features |= WG_NETDEV_FEATURES; 272 + dev->hw_features |= WG_NETDEV_FEATURES; 273 + dev->hw_enc_features |= WG_NETDEV_FEATURES; 274 + dev->mtu = ETH_DATA_LEN - MESSAGE_MINIMUM_LENGTH - 275 + sizeof(struct udphdr) - 276 + max(sizeof(struct ipv6hdr), sizeof(struct iphdr)); 277 + 278 + SET_NETDEV_DEVTYPE(dev, &device_type); 279 + 280 + /* We need to keep the dst around in case of icmp replies. */ 281 + netif_keep_dst(dev); 282 + 283 + memset(wg, 0, sizeof(*wg)); 284 + wg->dev = dev; 285 + } 286 + 287 + static int wg_newlink(struct net *src_net, struct net_device *dev, 288 + struct nlattr *tb[], struct nlattr *data[], 289 + struct netlink_ext_ack *extack) 290 + { 291 + struct wg_device *wg = netdev_priv(dev); 292 + int ret = -ENOMEM; 293 + 294 + wg->creating_net = src_net; 295 + init_rwsem(&wg->static_identity.lock); 296 + mutex_init(&wg->socket_update_lock); 297 + mutex_init(&wg->device_update_lock); 298 + skb_queue_head_init(&wg->incoming_handshakes); 299 + wg_allowedips_init(&wg->peer_allowedips); 300 + wg_cookie_checker_init(&wg->cookie_checker, wg); 301 + INIT_LIST_HEAD(&wg->peer_list); 302 + wg->device_update_gen = 1; 303 + 304 + wg->peer_hashtable = wg_pubkey_hashtable_alloc(); 305 + if (!wg->peer_hashtable) 306 + return ret; 307 + 308 + wg->index_hashtable = wg_index_hashtable_alloc(); 309 + if (!wg->index_hashtable) 310 + goto err_free_peer_hashtable; 311 + 312 + dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats); 313 + if (!dev->tstats) 314 + goto err_free_index_hashtable; 315 + 316 + wg->incoming_handshakes_worker = 317 + wg_packet_percpu_multicore_worker_alloc( 318 + wg_packet_handshake_receive_worker, wg); 319 + if (!wg->incoming_handshakes_worker) 320 + goto err_free_tstats; 321 + 322 + wg->handshake_receive_wq = alloc_workqueue("wg-kex-%s", 323 + WQ_CPU_INTENSIVE | WQ_FREEZABLE, 0, dev->name); 324 + if (!wg->handshake_receive_wq) 325 + goto err_free_incoming_handshakes; 326 + 327 + wg->handshake_send_wq = alloc_workqueue("wg-kex-%s", 328 + WQ_UNBOUND | WQ_FREEZABLE, 0, dev->name); 329 + if (!wg->handshake_send_wq) 330 + goto err_destroy_handshake_receive; 331 + 332 + wg->packet_crypt_wq = alloc_workqueue("wg-crypt-%s", 333 + WQ_CPU_INTENSIVE | WQ_MEM_RECLAIM, 0, dev->name); 334 + if (!wg->packet_crypt_wq) 335 + goto err_destroy_handshake_send; 336 + 337 + ret = wg_packet_queue_init(&wg->encrypt_queue, wg_packet_encrypt_worker, 338 + true, MAX_QUEUED_PACKETS); 339 + if (ret < 0) 340 + goto err_destroy_packet_crypt; 341 + 342 + ret = wg_packet_queue_init(&wg->decrypt_queue, wg_packet_decrypt_worker, 343 + true, MAX_QUEUED_PACKETS); 344 + if (ret < 0) 345 + goto err_free_encrypt_queue; 346 + 347 + ret = wg_ratelimiter_init(); 348 + if (ret < 0) 349 + goto err_free_decrypt_queue; 350 + 351 + ret = register_netdevice(dev); 352 + if (ret < 0) 353 + goto err_uninit_ratelimiter; 354 + 355 + list_add(&wg->device_list, &device_list); 356 + 357 + /* We wait until the end to assign priv_destructor, so that 358 + * register_netdevice doesn't call it for us if it fails. 359 + */ 360 + dev->priv_destructor = wg_destruct; 361 + 362 + pr_debug("%s: Interface created\n", dev->name); 363 + return ret; 364 + 365 + err_uninit_ratelimiter: 366 + wg_ratelimiter_uninit(); 367 + err_free_decrypt_queue: 368 + wg_packet_queue_free(&wg->decrypt_queue, true); 369 + err_free_encrypt_queue: 370 + wg_packet_queue_free(&wg->encrypt_queue, true); 371 + err_destroy_packet_crypt: 372 + destroy_workqueue(wg->packet_crypt_wq); 373 + err_destroy_handshake_send: 374 + destroy_workqueue(wg->handshake_send_wq); 375 + err_destroy_handshake_receive: 376 + destroy_workqueue(wg->handshake_receive_wq); 377 + err_free_incoming_handshakes: 378 + free_percpu(wg->incoming_handshakes_worker); 379 + err_free_tstats: 380 + free_percpu(dev->tstats); 381 + err_free_index_hashtable: 382 + kvfree(wg->index_hashtable); 383 + err_free_peer_hashtable: 384 + kvfree(wg->peer_hashtable); 385 + return ret; 386 + } 387 + 388 + static struct rtnl_link_ops link_ops __read_mostly = { 389 + .kind = KBUILD_MODNAME, 390 + .priv_size = sizeof(struct wg_device), 391 + .setup = wg_setup, 392 + .newlink = wg_newlink, 393 + }; 394 + 395 + static int wg_netdevice_notification(struct notifier_block *nb, 396 + unsigned long action, void *data) 397 + { 398 + struct net_device *dev = ((struct netdev_notifier_info *)data)->dev; 399 + struct wg_device *wg = netdev_priv(dev); 400 + 401 + ASSERT_RTNL(); 402 + 403 + if (action != NETDEV_REGISTER || dev->netdev_ops != &netdev_ops) 404 + return 0; 405 + 406 + if (dev_net(dev) == wg->creating_net && wg->have_creating_net_ref) { 407 + put_net(wg->creating_net); 408 + wg->have_creating_net_ref = false; 409 + } else if (dev_net(dev) != wg->creating_net && 410 + !wg->have_creating_net_ref) { 411 + wg->have_creating_net_ref = true; 412 + get_net(wg->creating_net); 413 + } 414 + return 0; 415 + } 416 + 417 + static struct notifier_block netdevice_notifier = { 418 + .notifier_call = wg_netdevice_notification 419 + }; 420 + 421 + int __init wg_device_init(void) 422 + { 423 + int ret; 424 + 425 + #ifdef CONFIG_PM_SLEEP 426 + ret = register_pm_notifier(&pm_notifier); 427 + if (ret) 428 + return ret; 429 + #endif 430 + 431 + ret = register_netdevice_notifier(&netdevice_notifier); 432 + if (ret) 433 + goto error_pm; 434 + 435 + ret = rtnl_link_register(&link_ops); 436 + if (ret) 437 + goto error_netdevice; 438 + 439 + return 0; 440 + 441 + error_netdevice: 442 + unregister_netdevice_notifier(&netdevice_notifier); 443 + error_pm: 444 + #ifdef CONFIG_PM_SLEEP 445 + unregister_pm_notifier(&pm_notifier); 446 + #endif 447 + return ret; 448 + } 449 + 450 + void wg_device_uninit(void) 451 + { 452 + rtnl_link_unregister(&link_ops); 453 + unregister_netdevice_notifier(&netdevice_notifier); 454 + #ifdef CONFIG_PM_SLEEP 455 + unregister_pm_notifier(&pm_notifier); 456 + #endif 457 + rcu_barrier(); 458 + }
+73
drivers/net/wireguard/device.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_DEVICE_H 7 + #define _WG_DEVICE_H 8 + 9 + #include "noise.h" 10 + #include "allowedips.h" 11 + #include "peerlookup.h" 12 + #include "cookie.h" 13 + 14 + #include <linux/types.h> 15 + #include <linux/netdevice.h> 16 + #include <linux/workqueue.h> 17 + #include <linux/mutex.h> 18 + #include <linux/net.h> 19 + #include <linux/ptr_ring.h> 20 + 21 + struct wg_device; 22 + 23 + struct multicore_worker { 24 + void *ptr; 25 + struct work_struct work; 26 + }; 27 + 28 + struct crypt_queue { 29 + struct ptr_ring ring; 30 + union { 31 + struct { 32 + struct multicore_worker __percpu *worker; 33 + int last_cpu; 34 + }; 35 + struct work_struct work; 36 + }; 37 + }; 38 + 39 + struct wg_device { 40 + struct net_device *dev; 41 + struct crypt_queue encrypt_queue, decrypt_queue; 42 + struct sock __rcu *sock4, *sock6; 43 + struct net *creating_net; 44 + struct noise_static_identity static_identity; 45 + struct workqueue_struct *handshake_receive_wq, *handshake_send_wq; 46 + struct workqueue_struct *packet_crypt_wq; 47 + struct sk_buff_head incoming_handshakes; 48 + int incoming_handshake_cpu; 49 + struct multicore_worker __percpu *incoming_handshakes_worker; 50 + struct cookie_checker cookie_checker; 51 + struct pubkey_hashtable *peer_hashtable; 52 + struct index_hashtable *index_hashtable; 53 + struct allowedips peer_allowedips; 54 + struct mutex device_update_lock, socket_update_lock; 55 + struct list_head device_list, peer_list; 56 + unsigned int num_peers, device_update_gen; 57 + u32 fwmark; 58 + u16 incoming_port; 59 + bool have_creating_net_ref; 60 + }; 61 + 62 + int wg_device_init(void); 63 + void wg_device_uninit(void); 64 + 65 + /* Later after the dust settles, this can be moved into include/linux/skbuff.h, 66 + * where virtually all code that deals with GSO segs can benefit, around ~30 67 + * drivers as of writing. 68 + */ 69 + #define skb_list_walk_safe(first, skb, next) \ 70 + for (skb = first, next = skb->next; skb; \ 71 + skb = next, next = skb ? skb->next : NULL) 72 + 73 + #endif /* _WG_DEVICE_H */
+64
drivers/net/wireguard/main.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "version.h" 7 + #include "device.h" 8 + #include "noise.h" 9 + #include "queueing.h" 10 + #include "ratelimiter.h" 11 + #include "netlink.h" 12 + 13 + #include <uapi/linux/wireguard.h> 14 + 15 + #include <linux/version.h> 16 + #include <linux/init.h> 17 + #include <linux/module.h> 18 + #include <linux/genetlink.h> 19 + #include <net/rtnetlink.h> 20 + 21 + static int __init mod_init(void) 22 + { 23 + int ret; 24 + 25 + #ifdef DEBUG 26 + if (!wg_allowedips_selftest() || !wg_packet_counter_selftest() || 27 + !wg_ratelimiter_selftest()) 28 + return -ENOTRECOVERABLE; 29 + #endif 30 + wg_noise_init(); 31 + 32 + ret = wg_device_init(); 33 + if (ret < 0) 34 + goto err_device; 35 + 36 + ret = wg_genetlink_init(); 37 + if (ret < 0) 38 + goto err_netlink; 39 + 40 + pr_info("WireGuard " WIREGUARD_VERSION " loaded. See www.wireguard.com for information.\n"); 41 + pr_info("Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.\n"); 42 + 43 + return 0; 44 + 45 + err_netlink: 46 + wg_device_uninit(); 47 + err_device: 48 + return ret; 49 + } 50 + 51 + static void __exit mod_exit(void) 52 + { 53 + wg_genetlink_uninit(); 54 + wg_device_uninit(); 55 + } 56 + 57 + module_init(mod_init); 58 + module_exit(mod_exit); 59 + MODULE_LICENSE("GPL v2"); 60 + MODULE_DESCRIPTION("WireGuard secure network tunnel"); 61 + MODULE_AUTHOR("Jason A. Donenfeld <Jason@zx2c4.com>"); 62 + MODULE_VERSION(WIREGUARD_VERSION); 63 + MODULE_ALIAS_RTNL_LINK(KBUILD_MODNAME); 64 + MODULE_ALIAS_GENL_FAMILY(WG_GENL_NAME);
+128
drivers/net/wireguard/messages.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_MESSAGES_H 7 + #define _WG_MESSAGES_H 8 + 9 + #include <crypto/curve25519.h> 10 + #include <crypto/chacha20poly1305.h> 11 + #include <crypto/blake2s.h> 12 + 13 + #include <linux/kernel.h> 14 + #include <linux/param.h> 15 + #include <linux/skbuff.h> 16 + 17 + enum noise_lengths { 18 + NOISE_PUBLIC_KEY_LEN = CURVE25519_KEY_SIZE, 19 + NOISE_SYMMETRIC_KEY_LEN = CHACHA20POLY1305_KEY_SIZE, 20 + NOISE_TIMESTAMP_LEN = sizeof(u64) + sizeof(u32), 21 + NOISE_AUTHTAG_LEN = CHACHA20POLY1305_AUTHTAG_SIZE, 22 + NOISE_HASH_LEN = BLAKE2S_HASH_SIZE 23 + }; 24 + 25 + #define noise_encrypted_len(plain_len) ((plain_len) + NOISE_AUTHTAG_LEN) 26 + 27 + enum cookie_values { 28 + COOKIE_SECRET_MAX_AGE = 2 * 60, 29 + COOKIE_SECRET_LATENCY = 5, 30 + COOKIE_NONCE_LEN = XCHACHA20POLY1305_NONCE_SIZE, 31 + COOKIE_LEN = 16 32 + }; 33 + 34 + enum counter_values { 35 + COUNTER_BITS_TOTAL = 2048, 36 + COUNTER_REDUNDANT_BITS = BITS_PER_LONG, 37 + COUNTER_WINDOW_SIZE = COUNTER_BITS_TOTAL - COUNTER_REDUNDANT_BITS 38 + }; 39 + 40 + enum limits { 41 + REKEY_AFTER_MESSAGES = 1ULL << 60, 42 + REJECT_AFTER_MESSAGES = U64_MAX - COUNTER_WINDOW_SIZE - 1, 43 + REKEY_TIMEOUT = 5, 44 + REKEY_TIMEOUT_JITTER_MAX_JIFFIES = HZ / 3, 45 + REKEY_AFTER_TIME = 120, 46 + REJECT_AFTER_TIME = 180, 47 + INITIATIONS_PER_SECOND = 50, 48 + MAX_PEERS_PER_DEVICE = 1U << 20, 49 + KEEPALIVE_TIMEOUT = 10, 50 + MAX_TIMER_HANDSHAKES = 90 / REKEY_TIMEOUT, 51 + MAX_QUEUED_INCOMING_HANDSHAKES = 4096, /* TODO: replace this with DQL */ 52 + MAX_STAGED_PACKETS = 128, 53 + MAX_QUEUED_PACKETS = 1024 /* TODO: replace this with DQL */ 54 + }; 55 + 56 + enum message_type { 57 + MESSAGE_INVALID = 0, 58 + MESSAGE_HANDSHAKE_INITIATION = 1, 59 + MESSAGE_HANDSHAKE_RESPONSE = 2, 60 + MESSAGE_HANDSHAKE_COOKIE = 3, 61 + MESSAGE_DATA = 4 62 + }; 63 + 64 + struct message_header { 65 + /* The actual layout of this that we want is: 66 + * u8 type 67 + * u8 reserved_zero[3] 68 + * 69 + * But it turns out that by encoding this as little endian, 70 + * we achieve the same thing, and it makes checking faster. 71 + */ 72 + __le32 type; 73 + }; 74 + 75 + struct message_macs { 76 + u8 mac1[COOKIE_LEN]; 77 + u8 mac2[COOKIE_LEN]; 78 + }; 79 + 80 + struct message_handshake_initiation { 81 + struct message_header header; 82 + __le32 sender_index; 83 + u8 unencrypted_ephemeral[NOISE_PUBLIC_KEY_LEN]; 84 + u8 encrypted_static[noise_encrypted_len(NOISE_PUBLIC_KEY_LEN)]; 85 + u8 encrypted_timestamp[noise_encrypted_len(NOISE_TIMESTAMP_LEN)]; 86 + struct message_macs macs; 87 + }; 88 + 89 + struct message_handshake_response { 90 + struct message_header header; 91 + __le32 sender_index; 92 + __le32 receiver_index; 93 + u8 unencrypted_ephemeral[NOISE_PUBLIC_KEY_LEN]; 94 + u8 encrypted_nothing[noise_encrypted_len(0)]; 95 + struct message_macs macs; 96 + }; 97 + 98 + struct message_handshake_cookie { 99 + struct message_header header; 100 + __le32 receiver_index; 101 + u8 nonce[COOKIE_NONCE_LEN]; 102 + u8 encrypted_cookie[noise_encrypted_len(COOKIE_LEN)]; 103 + }; 104 + 105 + struct message_data { 106 + struct message_header header; 107 + __le32 key_idx; 108 + __le64 counter; 109 + u8 encrypted_data[]; 110 + }; 111 + 112 + #define message_data_len(plain_len) \ 113 + (noise_encrypted_len(plain_len) + sizeof(struct message_data)) 114 + 115 + enum message_alignments { 116 + MESSAGE_PADDING_MULTIPLE = 16, 117 + MESSAGE_MINIMUM_LENGTH = message_data_len(0) 118 + }; 119 + 120 + #define SKB_HEADER_LEN \ 121 + (max(sizeof(struct iphdr), sizeof(struct ipv6hdr)) + \ 122 + sizeof(struct udphdr) + NET_SKB_PAD) 123 + #define DATA_PACKET_HEAD_ROOM \ 124 + ALIGN(sizeof(struct message_data) + SKB_HEADER_LEN, 4) 125 + 126 + enum { HANDSHAKE_DSCP = 0x88 /* AF41, plus 00 ECN */ }; 127 + 128 + #endif /* _WG_MESSAGES_H */
+642
drivers/net/wireguard/netlink.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "netlink.h" 7 + #include "device.h" 8 + #include "peer.h" 9 + #include "socket.h" 10 + #include "queueing.h" 11 + #include "messages.h" 12 + 13 + #include <uapi/linux/wireguard.h> 14 + 15 + #include <linux/if.h> 16 + #include <net/genetlink.h> 17 + #include <net/sock.h> 18 + #include <crypto/algapi.h> 19 + 20 + static struct genl_family genl_family; 21 + 22 + static const struct nla_policy device_policy[WGDEVICE_A_MAX + 1] = { 23 + [WGDEVICE_A_IFINDEX] = { .type = NLA_U32 }, 24 + [WGDEVICE_A_IFNAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ - 1 }, 25 + [WGDEVICE_A_PRIVATE_KEY] = { .type = NLA_EXACT_LEN, .len = NOISE_PUBLIC_KEY_LEN }, 26 + [WGDEVICE_A_PUBLIC_KEY] = { .type = NLA_EXACT_LEN, .len = NOISE_PUBLIC_KEY_LEN }, 27 + [WGDEVICE_A_FLAGS] = { .type = NLA_U32 }, 28 + [WGDEVICE_A_LISTEN_PORT] = { .type = NLA_U16 }, 29 + [WGDEVICE_A_FWMARK] = { .type = NLA_U32 }, 30 + [WGDEVICE_A_PEERS] = { .type = NLA_NESTED } 31 + }; 32 + 33 + static const struct nla_policy peer_policy[WGPEER_A_MAX + 1] = { 34 + [WGPEER_A_PUBLIC_KEY] = { .type = NLA_EXACT_LEN, .len = NOISE_PUBLIC_KEY_LEN }, 35 + [WGPEER_A_PRESHARED_KEY] = { .type = NLA_EXACT_LEN, .len = NOISE_SYMMETRIC_KEY_LEN }, 36 + [WGPEER_A_FLAGS] = { .type = NLA_U32 }, 37 + [WGPEER_A_ENDPOINT] = { .type = NLA_MIN_LEN, .len = sizeof(struct sockaddr) }, 38 + [WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL] = { .type = NLA_U16 }, 39 + [WGPEER_A_LAST_HANDSHAKE_TIME] = { .type = NLA_EXACT_LEN, .len = sizeof(struct __kernel_timespec) }, 40 + [WGPEER_A_RX_BYTES] = { .type = NLA_U64 }, 41 + [WGPEER_A_TX_BYTES] = { .type = NLA_U64 }, 42 + [WGPEER_A_ALLOWEDIPS] = { .type = NLA_NESTED }, 43 + [WGPEER_A_PROTOCOL_VERSION] = { .type = NLA_U32 } 44 + }; 45 + 46 + static const struct nla_policy allowedip_policy[WGALLOWEDIP_A_MAX + 1] = { 47 + [WGALLOWEDIP_A_FAMILY] = { .type = NLA_U16 }, 48 + [WGALLOWEDIP_A_IPADDR] = { .type = NLA_MIN_LEN, .len = sizeof(struct in_addr) }, 49 + [WGALLOWEDIP_A_CIDR_MASK] = { .type = NLA_U8 } 50 + }; 51 + 52 + static struct wg_device *lookup_interface(struct nlattr **attrs, 53 + struct sk_buff *skb) 54 + { 55 + struct net_device *dev = NULL; 56 + 57 + if (!attrs[WGDEVICE_A_IFINDEX] == !attrs[WGDEVICE_A_IFNAME]) 58 + return ERR_PTR(-EBADR); 59 + if (attrs[WGDEVICE_A_IFINDEX]) 60 + dev = dev_get_by_index(sock_net(skb->sk), 61 + nla_get_u32(attrs[WGDEVICE_A_IFINDEX])); 62 + else if (attrs[WGDEVICE_A_IFNAME]) 63 + dev = dev_get_by_name(sock_net(skb->sk), 64 + nla_data(attrs[WGDEVICE_A_IFNAME])); 65 + if (!dev) 66 + return ERR_PTR(-ENODEV); 67 + if (!dev->rtnl_link_ops || !dev->rtnl_link_ops->kind || 68 + strcmp(dev->rtnl_link_ops->kind, KBUILD_MODNAME)) { 69 + dev_put(dev); 70 + return ERR_PTR(-EOPNOTSUPP); 71 + } 72 + return netdev_priv(dev); 73 + } 74 + 75 + static int get_allowedips(struct sk_buff *skb, const u8 *ip, u8 cidr, 76 + int family) 77 + { 78 + struct nlattr *allowedip_nest; 79 + 80 + allowedip_nest = nla_nest_start(skb, 0); 81 + if (!allowedip_nest) 82 + return -EMSGSIZE; 83 + 84 + if (nla_put_u8(skb, WGALLOWEDIP_A_CIDR_MASK, cidr) || 85 + nla_put_u16(skb, WGALLOWEDIP_A_FAMILY, family) || 86 + nla_put(skb, WGALLOWEDIP_A_IPADDR, family == AF_INET6 ? 87 + sizeof(struct in6_addr) : sizeof(struct in_addr), ip)) { 88 + nla_nest_cancel(skb, allowedip_nest); 89 + return -EMSGSIZE; 90 + } 91 + 92 + nla_nest_end(skb, allowedip_nest); 93 + return 0; 94 + } 95 + 96 + struct dump_ctx { 97 + struct wg_device *wg; 98 + struct wg_peer *next_peer; 99 + u64 allowedips_seq; 100 + struct allowedips_node *next_allowedip; 101 + }; 102 + 103 + #define DUMP_CTX(cb) ((struct dump_ctx *)(cb)->args) 104 + 105 + static int 106 + get_peer(struct wg_peer *peer, struct sk_buff *skb, struct dump_ctx *ctx) 107 + { 108 + 109 + struct nlattr *allowedips_nest, *peer_nest = nla_nest_start(skb, 0); 110 + struct allowedips_node *allowedips_node = ctx->next_allowedip; 111 + bool fail; 112 + 113 + if (!peer_nest) 114 + return -EMSGSIZE; 115 + 116 + down_read(&peer->handshake.lock); 117 + fail = nla_put(skb, WGPEER_A_PUBLIC_KEY, NOISE_PUBLIC_KEY_LEN, 118 + peer->handshake.remote_static); 119 + up_read(&peer->handshake.lock); 120 + if (fail) 121 + goto err; 122 + 123 + if (!allowedips_node) { 124 + const struct __kernel_timespec last_handshake = { 125 + .tv_sec = peer->walltime_last_handshake.tv_sec, 126 + .tv_nsec = peer->walltime_last_handshake.tv_nsec 127 + }; 128 + 129 + down_read(&peer->handshake.lock); 130 + fail = nla_put(skb, WGPEER_A_PRESHARED_KEY, 131 + NOISE_SYMMETRIC_KEY_LEN, 132 + peer->handshake.preshared_key); 133 + up_read(&peer->handshake.lock); 134 + if (fail) 135 + goto err; 136 + 137 + if (nla_put(skb, WGPEER_A_LAST_HANDSHAKE_TIME, 138 + sizeof(last_handshake), &last_handshake) || 139 + nla_put_u16(skb, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, 140 + peer->persistent_keepalive_interval) || 141 + nla_put_u64_64bit(skb, WGPEER_A_TX_BYTES, peer->tx_bytes, 142 + WGPEER_A_UNSPEC) || 143 + nla_put_u64_64bit(skb, WGPEER_A_RX_BYTES, peer->rx_bytes, 144 + WGPEER_A_UNSPEC) || 145 + nla_put_u32(skb, WGPEER_A_PROTOCOL_VERSION, 1)) 146 + goto err; 147 + 148 + read_lock_bh(&peer->endpoint_lock); 149 + if (peer->endpoint.addr.sa_family == AF_INET) 150 + fail = nla_put(skb, WGPEER_A_ENDPOINT, 151 + sizeof(peer->endpoint.addr4), 152 + &peer->endpoint.addr4); 153 + else if (peer->endpoint.addr.sa_family == AF_INET6) 154 + fail = nla_put(skb, WGPEER_A_ENDPOINT, 155 + sizeof(peer->endpoint.addr6), 156 + &peer->endpoint.addr6); 157 + read_unlock_bh(&peer->endpoint_lock); 158 + if (fail) 159 + goto err; 160 + allowedips_node = 161 + list_first_entry_or_null(&peer->allowedips_list, 162 + struct allowedips_node, peer_list); 163 + } 164 + if (!allowedips_node) 165 + goto no_allowedips; 166 + if (!ctx->allowedips_seq) 167 + ctx->allowedips_seq = peer->device->peer_allowedips.seq; 168 + else if (ctx->allowedips_seq != peer->device->peer_allowedips.seq) 169 + goto no_allowedips; 170 + 171 + allowedips_nest = nla_nest_start(skb, WGPEER_A_ALLOWEDIPS); 172 + if (!allowedips_nest) 173 + goto err; 174 + 175 + list_for_each_entry_from(allowedips_node, &peer->allowedips_list, 176 + peer_list) { 177 + u8 cidr, ip[16] __aligned(__alignof(u64)); 178 + int family; 179 + 180 + family = wg_allowedips_read_node(allowedips_node, ip, &cidr); 181 + if (get_allowedips(skb, ip, cidr, family)) { 182 + nla_nest_end(skb, allowedips_nest); 183 + nla_nest_end(skb, peer_nest); 184 + ctx->next_allowedip = allowedips_node; 185 + return -EMSGSIZE; 186 + } 187 + } 188 + nla_nest_end(skb, allowedips_nest); 189 + no_allowedips: 190 + nla_nest_end(skb, peer_nest); 191 + ctx->next_allowedip = NULL; 192 + ctx->allowedips_seq = 0; 193 + return 0; 194 + err: 195 + nla_nest_cancel(skb, peer_nest); 196 + return -EMSGSIZE; 197 + } 198 + 199 + static int wg_get_device_start(struct netlink_callback *cb) 200 + { 201 + struct wg_device *wg; 202 + 203 + wg = lookup_interface(genl_dumpit_info(cb)->attrs, cb->skb); 204 + if (IS_ERR(wg)) 205 + return PTR_ERR(wg); 206 + DUMP_CTX(cb)->wg = wg; 207 + return 0; 208 + } 209 + 210 + static int wg_get_device_dump(struct sk_buff *skb, struct netlink_callback *cb) 211 + { 212 + struct wg_peer *peer, *next_peer_cursor; 213 + struct dump_ctx *ctx = DUMP_CTX(cb); 214 + struct wg_device *wg = ctx->wg; 215 + struct nlattr *peers_nest; 216 + int ret = -EMSGSIZE; 217 + bool done = true; 218 + void *hdr; 219 + 220 + rtnl_lock(); 221 + mutex_lock(&wg->device_update_lock); 222 + cb->seq = wg->device_update_gen; 223 + next_peer_cursor = ctx->next_peer; 224 + 225 + hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, 226 + &genl_family, NLM_F_MULTI, WG_CMD_GET_DEVICE); 227 + if (!hdr) 228 + goto out; 229 + genl_dump_check_consistent(cb, hdr); 230 + 231 + if (!ctx->next_peer) { 232 + if (nla_put_u16(skb, WGDEVICE_A_LISTEN_PORT, 233 + wg->incoming_port) || 234 + nla_put_u32(skb, WGDEVICE_A_FWMARK, wg->fwmark) || 235 + nla_put_u32(skb, WGDEVICE_A_IFINDEX, wg->dev->ifindex) || 236 + nla_put_string(skb, WGDEVICE_A_IFNAME, wg->dev->name)) 237 + goto out; 238 + 239 + down_read(&wg->static_identity.lock); 240 + if (wg->static_identity.has_identity) { 241 + if (nla_put(skb, WGDEVICE_A_PRIVATE_KEY, 242 + NOISE_PUBLIC_KEY_LEN, 243 + wg->static_identity.static_private) || 244 + nla_put(skb, WGDEVICE_A_PUBLIC_KEY, 245 + NOISE_PUBLIC_KEY_LEN, 246 + wg->static_identity.static_public)) { 247 + up_read(&wg->static_identity.lock); 248 + goto out; 249 + } 250 + } 251 + up_read(&wg->static_identity.lock); 252 + } 253 + 254 + peers_nest = nla_nest_start(skb, WGDEVICE_A_PEERS); 255 + if (!peers_nest) 256 + goto out; 257 + ret = 0; 258 + /* If the last cursor was removed via list_del_init in peer_remove, then 259 + * we just treat this the same as there being no more peers left. The 260 + * reason is that seq_nr should indicate to userspace that this isn't a 261 + * coherent dump anyway, so they'll try again. 262 + */ 263 + if (list_empty(&wg->peer_list) || 264 + (ctx->next_peer && list_empty(&ctx->next_peer->peer_list))) { 265 + nla_nest_cancel(skb, peers_nest); 266 + goto out; 267 + } 268 + lockdep_assert_held(&wg->device_update_lock); 269 + peer = list_prepare_entry(ctx->next_peer, &wg->peer_list, peer_list); 270 + list_for_each_entry_continue(peer, &wg->peer_list, peer_list) { 271 + if (get_peer(peer, skb, ctx)) { 272 + done = false; 273 + break; 274 + } 275 + next_peer_cursor = peer; 276 + } 277 + nla_nest_end(skb, peers_nest); 278 + 279 + out: 280 + if (!ret && !done && next_peer_cursor) 281 + wg_peer_get(next_peer_cursor); 282 + wg_peer_put(ctx->next_peer); 283 + mutex_unlock(&wg->device_update_lock); 284 + rtnl_unlock(); 285 + 286 + if (ret) { 287 + genlmsg_cancel(skb, hdr); 288 + return ret; 289 + } 290 + genlmsg_end(skb, hdr); 291 + if (done) { 292 + ctx->next_peer = NULL; 293 + return 0; 294 + } 295 + ctx->next_peer = next_peer_cursor; 296 + return skb->len; 297 + 298 + /* At this point, we can't really deal ourselves with safely zeroing out 299 + * the private key material after usage. This will need an additional API 300 + * in the kernel for marking skbs as zero_on_free. 301 + */ 302 + } 303 + 304 + static int wg_get_device_done(struct netlink_callback *cb) 305 + { 306 + struct dump_ctx *ctx = DUMP_CTX(cb); 307 + 308 + if (ctx->wg) 309 + dev_put(ctx->wg->dev); 310 + wg_peer_put(ctx->next_peer); 311 + return 0; 312 + } 313 + 314 + static int set_port(struct wg_device *wg, u16 port) 315 + { 316 + struct wg_peer *peer; 317 + 318 + if (wg->incoming_port == port) 319 + return 0; 320 + list_for_each_entry(peer, &wg->peer_list, peer_list) 321 + wg_socket_clear_peer_endpoint_src(peer); 322 + if (!netif_running(wg->dev)) { 323 + wg->incoming_port = port; 324 + return 0; 325 + } 326 + return wg_socket_init(wg, port); 327 + } 328 + 329 + static int set_allowedip(struct wg_peer *peer, struct nlattr **attrs) 330 + { 331 + int ret = -EINVAL; 332 + u16 family; 333 + u8 cidr; 334 + 335 + if (!attrs[WGALLOWEDIP_A_FAMILY] || !attrs[WGALLOWEDIP_A_IPADDR] || 336 + !attrs[WGALLOWEDIP_A_CIDR_MASK]) 337 + return ret; 338 + family = nla_get_u16(attrs[WGALLOWEDIP_A_FAMILY]); 339 + cidr = nla_get_u8(attrs[WGALLOWEDIP_A_CIDR_MASK]); 340 + 341 + if (family == AF_INET && cidr <= 32 && 342 + nla_len(attrs[WGALLOWEDIP_A_IPADDR]) == sizeof(struct in_addr)) 343 + ret = wg_allowedips_insert_v4( 344 + &peer->device->peer_allowedips, 345 + nla_data(attrs[WGALLOWEDIP_A_IPADDR]), cidr, peer, 346 + &peer->device->device_update_lock); 347 + else if (family == AF_INET6 && cidr <= 128 && 348 + nla_len(attrs[WGALLOWEDIP_A_IPADDR]) == sizeof(struct in6_addr)) 349 + ret = wg_allowedips_insert_v6( 350 + &peer->device->peer_allowedips, 351 + nla_data(attrs[WGALLOWEDIP_A_IPADDR]), cidr, peer, 352 + &peer->device->device_update_lock); 353 + 354 + return ret; 355 + } 356 + 357 + static int set_peer(struct wg_device *wg, struct nlattr **attrs) 358 + { 359 + u8 *public_key = NULL, *preshared_key = NULL; 360 + struct wg_peer *peer = NULL; 361 + u32 flags = 0; 362 + int ret; 363 + 364 + ret = -EINVAL; 365 + if (attrs[WGPEER_A_PUBLIC_KEY] && 366 + nla_len(attrs[WGPEER_A_PUBLIC_KEY]) == NOISE_PUBLIC_KEY_LEN) 367 + public_key = nla_data(attrs[WGPEER_A_PUBLIC_KEY]); 368 + else 369 + goto out; 370 + if (attrs[WGPEER_A_PRESHARED_KEY] && 371 + nla_len(attrs[WGPEER_A_PRESHARED_KEY]) == NOISE_SYMMETRIC_KEY_LEN) 372 + preshared_key = nla_data(attrs[WGPEER_A_PRESHARED_KEY]); 373 + 374 + if (attrs[WGPEER_A_FLAGS]) 375 + flags = nla_get_u32(attrs[WGPEER_A_FLAGS]); 376 + ret = -EOPNOTSUPP; 377 + if (flags & ~__WGPEER_F_ALL) 378 + goto out; 379 + 380 + ret = -EPFNOSUPPORT; 381 + if (attrs[WGPEER_A_PROTOCOL_VERSION]) { 382 + if (nla_get_u32(attrs[WGPEER_A_PROTOCOL_VERSION]) != 1) 383 + goto out; 384 + } 385 + 386 + peer = wg_pubkey_hashtable_lookup(wg->peer_hashtable, 387 + nla_data(attrs[WGPEER_A_PUBLIC_KEY])); 388 + ret = 0; 389 + if (!peer) { /* Peer doesn't exist yet. Add a new one. */ 390 + if (flags & (WGPEER_F_REMOVE_ME | WGPEER_F_UPDATE_ONLY)) 391 + goto out; 392 + 393 + /* The peer is new, so there aren't allowed IPs to remove. */ 394 + flags &= ~WGPEER_F_REPLACE_ALLOWEDIPS; 395 + 396 + down_read(&wg->static_identity.lock); 397 + if (wg->static_identity.has_identity && 398 + !memcmp(nla_data(attrs[WGPEER_A_PUBLIC_KEY]), 399 + wg->static_identity.static_public, 400 + NOISE_PUBLIC_KEY_LEN)) { 401 + /* We silently ignore peers that have the same public 402 + * key as the device. The reason we do it silently is 403 + * that we'd like for people to be able to reuse the 404 + * same set of API calls across peers. 405 + */ 406 + up_read(&wg->static_identity.lock); 407 + ret = 0; 408 + goto out; 409 + } 410 + up_read(&wg->static_identity.lock); 411 + 412 + peer = wg_peer_create(wg, public_key, preshared_key); 413 + if (IS_ERR(peer)) { 414 + /* Similar to the above, if the key is invalid, we skip 415 + * it without fanfare, so that services don't need to 416 + * worry about doing key validation themselves. 417 + */ 418 + ret = PTR_ERR(peer) == -EKEYREJECTED ? 0 : PTR_ERR(peer); 419 + peer = NULL; 420 + goto out; 421 + } 422 + /* Take additional reference, as though we've just been 423 + * looked up. 424 + */ 425 + wg_peer_get(peer); 426 + } 427 + 428 + if (flags & WGPEER_F_REMOVE_ME) { 429 + wg_peer_remove(peer); 430 + goto out; 431 + } 432 + 433 + if (preshared_key) { 434 + down_write(&peer->handshake.lock); 435 + memcpy(&peer->handshake.preshared_key, preshared_key, 436 + NOISE_SYMMETRIC_KEY_LEN); 437 + up_write(&peer->handshake.lock); 438 + } 439 + 440 + if (attrs[WGPEER_A_ENDPOINT]) { 441 + struct sockaddr *addr = nla_data(attrs[WGPEER_A_ENDPOINT]); 442 + size_t len = nla_len(attrs[WGPEER_A_ENDPOINT]); 443 + 444 + if ((len == sizeof(struct sockaddr_in) && 445 + addr->sa_family == AF_INET) || 446 + (len == sizeof(struct sockaddr_in6) && 447 + addr->sa_family == AF_INET6)) { 448 + struct endpoint endpoint = { { { 0 } } }; 449 + 450 + memcpy(&endpoint.addr, addr, len); 451 + wg_socket_set_peer_endpoint(peer, &endpoint); 452 + } 453 + } 454 + 455 + if (flags & WGPEER_F_REPLACE_ALLOWEDIPS) 456 + wg_allowedips_remove_by_peer(&wg->peer_allowedips, peer, 457 + &wg->device_update_lock); 458 + 459 + if (attrs[WGPEER_A_ALLOWEDIPS]) { 460 + struct nlattr *attr, *allowedip[WGALLOWEDIP_A_MAX + 1]; 461 + int rem; 462 + 463 + nla_for_each_nested(attr, attrs[WGPEER_A_ALLOWEDIPS], rem) { 464 + ret = nla_parse_nested(allowedip, WGALLOWEDIP_A_MAX, 465 + attr, allowedip_policy, NULL); 466 + if (ret < 0) 467 + goto out; 468 + ret = set_allowedip(peer, allowedip); 469 + if (ret < 0) 470 + goto out; 471 + } 472 + } 473 + 474 + if (attrs[WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL]) { 475 + const u16 persistent_keepalive_interval = nla_get_u16( 476 + attrs[WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL]); 477 + const bool send_keepalive = 478 + !peer->persistent_keepalive_interval && 479 + persistent_keepalive_interval && 480 + netif_running(wg->dev); 481 + 482 + peer->persistent_keepalive_interval = persistent_keepalive_interval; 483 + if (send_keepalive) 484 + wg_packet_send_keepalive(peer); 485 + } 486 + 487 + if (netif_running(wg->dev)) 488 + wg_packet_send_staged_packets(peer); 489 + 490 + out: 491 + wg_peer_put(peer); 492 + if (attrs[WGPEER_A_PRESHARED_KEY]) 493 + memzero_explicit(nla_data(attrs[WGPEER_A_PRESHARED_KEY]), 494 + nla_len(attrs[WGPEER_A_PRESHARED_KEY])); 495 + return ret; 496 + } 497 + 498 + static int wg_set_device(struct sk_buff *skb, struct genl_info *info) 499 + { 500 + struct wg_device *wg = lookup_interface(info->attrs, skb); 501 + u32 flags = 0; 502 + int ret; 503 + 504 + if (IS_ERR(wg)) { 505 + ret = PTR_ERR(wg); 506 + goto out_nodev; 507 + } 508 + 509 + rtnl_lock(); 510 + mutex_lock(&wg->device_update_lock); 511 + 512 + if (info->attrs[WGDEVICE_A_FLAGS]) 513 + flags = nla_get_u32(info->attrs[WGDEVICE_A_FLAGS]); 514 + ret = -EOPNOTSUPP; 515 + if (flags & ~__WGDEVICE_F_ALL) 516 + goto out; 517 + 518 + ret = -EPERM; 519 + if ((info->attrs[WGDEVICE_A_LISTEN_PORT] || 520 + info->attrs[WGDEVICE_A_FWMARK]) && 521 + !ns_capable(wg->creating_net->user_ns, CAP_NET_ADMIN)) 522 + goto out; 523 + 524 + ++wg->device_update_gen; 525 + 526 + if (info->attrs[WGDEVICE_A_FWMARK]) { 527 + struct wg_peer *peer; 528 + 529 + wg->fwmark = nla_get_u32(info->attrs[WGDEVICE_A_FWMARK]); 530 + list_for_each_entry(peer, &wg->peer_list, peer_list) 531 + wg_socket_clear_peer_endpoint_src(peer); 532 + } 533 + 534 + if (info->attrs[WGDEVICE_A_LISTEN_PORT]) { 535 + ret = set_port(wg, 536 + nla_get_u16(info->attrs[WGDEVICE_A_LISTEN_PORT])); 537 + if (ret) 538 + goto out; 539 + } 540 + 541 + if (flags & WGDEVICE_F_REPLACE_PEERS) 542 + wg_peer_remove_all(wg); 543 + 544 + if (info->attrs[WGDEVICE_A_PRIVATE_KEY] && 545 + nla_len(info->attrs[WGDEVICE_A_PRIVATE_KEY]) == 546 + NOISE_PUBLIC_KEY_LEN) { 547 + u8 *private_key = nla_data(info->attrs[WGDEVICE_A_PRIVATE_KEY]); 548 + u8 public_key[NOISE_PUBLIC_KEY_LEN]; 549 + struct wg_peer *peer, *temp; 550 + 551 + if (!crypto_memneq(wg->static_identity.static_private, 552 + private_key, NOISE_PUBLIC_KEY_LEN)) 553 + goto skip_set_private_key; 554 + 555 + /* We remove before setting, to prevent race, which means doing 556 + * two 25519-genpub ops. 557 + */ 558 + if (curve25519_generate_public(public_key, private_key)) { 559 + peer = wg_pubkey_hashtable_lookup(wg->peer_hashtable, 560 + public_key); 561 + if (peer) { 562 + wg_peer_put(peer); 563 + wg_peer_remove(peer); 564 + } 565 + } 566 + 567 + down_write(&wg->static_identity.lock); 568 + wg_noise_set_static_identity_private_key(&wg->static_identity, 569 + private_key); 570 + list_for_each_entry_safe(peer, temp, &wg->peer_list, 571 + peer_list) { 572 + if (wg_noise_precompute_static_static(peer)) 573 + wg_noise_expire_current_peer_keypairs(peer); 574 + else 575 + wg_peer_remove(peer); 576 + } 577 + wg_cookie_checker_precompute_device_keys(&wg->cookie_checker); 578 + up_write(&wg->static_identity.lock); 579 + } 580 + skip_set_private_key: 581 + 582 + if (info->attrs[WGDEVICE_A_PEERS]) { 583 + struct nlattr *attr, *peer[WGPEER_A_MAX + 1]; 584 + int rem; 585 + 586 + nla_for_each_nested(attr, info->attrs[WGDEVICE_A_PEERS], rem) { 587 + ret = nla_parse_nested(peer, WGPEER_A_MAX, attr, 588 + peer_policy, NULL); 589 + if (ret < 0) 590 + goto out; 591 + ret = set_peer(wg, peer); 592 + if (ret < 0) 593 + goto out; 594 + } 595 + } 596 + ret = 0; 597 + 598 + out: 599 + mutex_unlock(&wg->device_update_lock); 600 + rtnl_unlock(); 601 + dev_put(wg->dev); 602 + out_nodev: 603 + if (info->attrs[WGDEVICE_A_PRIVATE_KEY]) 604 + memzero_explicit(nla_data(info->attrs[WGDEVICE_A_PRIVATE_KEY]), 605 + nla_len(info->attrs[WGDEVICE_A_PRIVATE_KEY])); 606 + return ret; 607 + } 608 + 609 + static const struct genl_ops genl_ops[] = { 610 + { 611 + .cmd = WG_CMD_GET_DEVICE, 612 + .start = wg_get_device_start, 613 + .dumpit = wg_get_device_dump, 614 + .done = wg_get_device_done, 615 + .flags = GENL_UNS_ADMIN_PERM 616 + }, { 617 + .cmd = WG_CMD_SET_DEVICE, 618 + .doit = wg_set_device, 619 + .flags = GENL_UNS_ADMIN_PERM 620 + } 621 + }; 622 + 623 + static struct genl_family genl_family __ro_after_init = { 624 + .ops = genl_ops, 625 + .n_ops = ARRAY_SIZE(genl_ops), 626 + .name = WG_GENL_NAME, 627 + .version = WG_GENL_VERSION, 628 + .maxattr = WGDEVICE_A_MAX, 629 + .module = THIS_MODULE, 630 + .policy = device_policy, 631 + .netnsok = true 632 + }; 633 + 634 + int __init wg_genetlink_init(void) 635 + { 636 + return genl_register_family(&genl_family); 637 + } 638 + 639 + void __exit wg_genetlink_uninit(void) 640 + { 641 + genl_unregister_family(&genl_family); 642 + }
+12
drivers/net/wireguard/netlink.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_NETLINK_H 7 + #define _WG_NETLINK_H 8 + 9 + int wg_genetlink_init(void); 10 + void wg_genetlink_uninit(void); 11 + 12 + #endif /* _WG_NETLINK_H */
+828
drivers/net/wireguard/noise.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "noise.h" 7 + #include "device.h" 8 + #include "peer.h" 9 + #include "messages.h" 10 + #include "queueing.h" 11 + #include "peerlookup.h" 12 + 13 + #include <linux/rcupdate.h> 14 + #include <linux/slab.h> 15 + #include <linux/bitmap.h> 16 + #include <linux/scatterlist.h> 17 + #include <linux/highmem.h> 18 + #include <crypto/algapi.h> 19 + 20 + /* This implements Noise_IKpsk2: 21 + * 22 + * <- s 23 + * ****** 24 + * -> e, es, s, ss, {t} 25 + * <- e, ee, se, psk, {} 26 + */ 27 + 28 + static const u8 handshake_name[37] = "Noise_IKpsk2_25519_ChaChaPoly_BLAKE2s"; 29 + static const u8 identifier_name[34] = "WireGuard v1 zx2c4 Jason@zx2c4.com"; 30 + static u8 handshake_init_hash[NOISE_HASH_LEN] __ro_after_init; 31 + static u8 handshake_init_chaining_key[NOISE_HASH_LEN] __ro_after_init; 32 + static atomic64_t keypair_counter = ATOMIC64_INIT(0); 33 + 34 + void __init wg_noise_init(void) 35 + { 36 + struct blake2s_state blake; 37 + 38 + blake2s(handshake_init_chaining_key, handshake_name, NULL, 39 + NOISE_HASH_LEN, sizeof(handshake_name), 0); 40 + blake2s_init(&blake, NOISE_HASH_LEN); 41 + blake2s_update(&blake, handshake_init_chaining_key, NOISE_HASH_LEN); 42 + blake2s_update(&blake, identifier_name, sizeof(identifier_name)); 43 + blake2s_final(&blake, handshake_init_hash); 44 + } 45 + 46 + /* Must hold peer->handshake.static_identity->lock */ 47 + bool wg_noise_precompute_static_static(struct wg_peer *peer) 48 + { 49 + bool ret = true; 50 + 51 + down_write(&peer->handshake.lock); 52 + if (peer->handshake.static_identity->has_identity) 53 + ret = curve25519( 54 + peer->handshake.precomputed_static_static, 55 + peer->handshake.static_identity->static_private, 56 + peer->handshake.remote_static); 57 + else 58 + memset(peer->handshake.precomputed_static_static, 0, 59 + NOISE_PUBLIC_KEY_LEN); 60 + up_write(&peer->handshake.lock); 61 + return ret; 62 + } 63 + 64 + bool wg_noise_handshake_init(struct noise_handshake *handshake, 65 + struct noise_static_identity *static_identity, 66 + const u8 peer_public_key[NOISE_PUBLIC_KEY_LEN], 67 + const u8 peer_preshared_key[NOISE_SYMMETRIC_KEY_LEN], 68 + struct wg_peer *peer) 69 + { 70 + memset(handshake, 0, sizeof(*handshake)); 71 + init_rwsem(&handshake->lock); 72 + handshake->entry.type = INDEX_HASHTABLE_HANDSHAKE; 73 + handshake->entry.peer = peer; 74 + memcpy(handshake->remote_static, peer_public_key, NOISE_PUBLIC_KEY_LEN); 75 + if (peer_preshared_key) 76 + memcpy(handshake->preshared_key, peer_preshared_key, 77 + NOISE_SYMMETRIC_KEY_LEN); 78 + handshake->static_identity = static_identity; 79 + handshake->state = HANDSHAKE_ZEROED; 80 + return wg_noise_precompute_static_static(peer); 81 + } 82 + 83 + static void handshake_zero(struct noise_handshake *handshake) 84 + { 85 + memset(&handshake->ephemeral_private, 0, NOISE_PUBLIC_KEY_LEN); 86 + memset(&handshake->remote_ephemeral, 0, NOISE_PUBLIC_KEY_LEN); 87 + memset(&handshake->hash, 0, NOISE_HASH_LEN); 88 + memset(&handshake->chaining_key, 0, NOISE_HASH_LEN); 89 + handshake->remote_index = 0; 90 + handshake->state = HANDSHAKE_ZEROED; 91 + } 92 + 93 + void wg_noise_handshake_clear(struct noise_handshake *handshake) 94 + { 95 + wg_index_hashtable_remove( 96 + handshake->entry.peer->device->index_hashtable, 97 + &handshake->entry); 98 + down_write(&handshake->lock); 99 + handshake_zero(handshake); 100 + up_write(&handshake->lock); 101 + wg_index_hashtable_remove( 102 + handshake->entry.peer->device->index_hashtable, 103 + &handshake->entry); 104 + } 105 + 106 + static struct noise_keypair *keypair_create(struct wg_peer *peer) 107 + { 108 + struct noise_keypair *keypair = kzalloc(sizeof(*keypair), GFP_KERNEL); 109 + 110 + if (unlikely(!keypair)) 111 + return NULL; 112 + keypair->internal_id = atomic64_inc_return(&keypair_counter); 113 + keypair->entry.type = INDEX_HASHTABLE_KEYPAIR; 114 + keypair->entry.peer = peer; 115 + kref_init(&keypair->refcount); 116 + return keypair; 117 + } 118 + 119 + static void keypair_free_rcu(struct rcu_head *rcu) 120 + { 121 + kzfree(container_of(rcu, struct noise_keypair, rcu)); 122 + } 123 + 124 + static void keypair_free_kref(struct kref *kref) 125 + { 126 + struct noise_keypair *keypair = 127 + container_of(kref, struct noise_keypair, refcount); 128 + 129 + net_dbg_ratelimited("%s: Keypair %llu destroyed for peer %llu\n", 130 + keypair->entry.peer->device->dev->name, 131 + keypair->internal_id, 132 + keypair->entry.peer->internal_id); 133 + wg_index_hashtable_remove(keypair->entry.peer->device->index_hashtable, 134 + &keypair->entry); 135 + call_rcu(&keypair->rcu, keypair_free_rcu); 136 + } 137 + 138 + void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now) 139 + { 140 + if (unlikely(!keypair)) 141 + return; 142 + if (unlikely(unreference_now)) 143 + wg_index_hashtable_remove( 144 + keypair->entry.peer->device->index_hashtable, 145 + &keypair->entry); 146 + kref_put(&keypair->refcount, keypair_free_kref); 147 + } 148 + 149 + struct noise_keypair *wg_noise_keypair_get(struct noise_keypair *keypair) 150 + { 151 + RCU_LOCKDEP_WARN(!rcu_read_lock_bh_held(), 152 + "Taking noise keypair reference without holding the RCU BH read lock"); 153 + if (unlikely(!keypair || !kref_get_unless_zero(&keypair->refcount))) 154 + return NULL; 155 + return keypair; 156 + } 157 + 158 + void wg_noise_keypairs_clear(struct noise_keypairs *keypairs) 159 + { 160 + struct noise_keypair *old; 161 + 162 + spin_lock_bh(&keypairs->keypair_update_lock); 163 + 164 + /* We zero the next_keypair before zeroing the others, so that 165 + * wg_noise_received_with_keypair returns early before subsequent ones 166 + * are zeroed. 167 + */ 168 + old = rcu_dereference_protected(keypairs->next_keypair, 169 + lockdep_is_held(&keypairs->keypair_update_lock)); 170 + RCU_INIT_POINTER(keypairs->next_keypair, NULL); 171 + wg_noise_keypair_put(old, true); 172 + 173 + old = rcu_dereference_protected(keypairs->previous_keypair, 174 + lockdep_is_held(&keypairs->keypair_update_lock)); 175 + RCU_INIT_POINTER(keypairs->previous_keypair, NULL); 176 + wg_noise_keypair_put(old, true); 177 + 178 + old = rcu_dereference_protected(keypairs->current_keypair, 179 + lockdep_is_held(&keypairs->keypair_update_lock)); 180 + RCU_INIT_POINTER(keypairs->current_keypair, NULL); 181 + wg_noise_keypair_put(old, true); 182 + 183 + spin_unlock_bh(&keypairs->keypair_update_lock); 184 + } 185 + 186 + void wg_noise_expire_current_peer_keypairs(struct wg_peer *peer) 187 + { 188 + struct noise_keypair *keypair; 189 + 190 + wg_noise_handshake_clear(&peer->handshake); 191 + wg_noise_reset_last_sent_handshake(&peer->last_sent_handshake); 192 + 193 + spin_lock_bh(&peer->keypairs.keypair_update_lock); 194 + keypair = rcu_dereference_protected(peer->keypairs.next_keypair, 195 + lockdep_is_held(&peer->keypairs.keypair_update_lock)); 196 + if (keypair) 197 + keypair->sending.is_valid = false; 198 + keypair = rcu_dereference_protected(peer->keypairs.current_keypair, 199 + lockdep_is_held(&peer->keypairs.keypair_update_lock)); 200 + if (keypair) 201 + keypair->sending.is_valid = false; 202 + spin_unlock_bh(&peer->keypairs.keypair_update_lock); 203 + } 204 + 205 + static void add_new_keypair(struct noise_keypairs *keypairs, 206 + struct noise_keypair *new_keypair) 207 + { 208 + struct noise_keypair *previous_keypair, *next_keypair, *current_keypair; 209 + 210 + spin_lock_bh(&keypairs->keypair_update_lock); 211 + previous_keypair = rcu_dereference_protected(keypairs->previous_keypair, 212 + lockdep_is_held(&keypairs->keypair_update_lock)); 213 + next_keypair = rcu_dereference_protected(keypairs->next_keypair, 214 + lockdep_is_held(&keypairs->keypair_update_lock)); 215 + current_keypair = rcu_dereference_protected(keypairs->current_keypair, 216 + lockdep_is_held(&keypairs->keypair_update_lock)); 217 + if (new_keypair->i_am_the_initiator) { 218 + /* If we're the initiator, it means we've sent a handshake, and 219 + * received a confirmation response, which means this new 220 + * keypair can now be used. 221 + */ 222 + if (next_keypair) { 223 + /* If there already was a next keypair pending, we 224 + * demote it to be the previous keypair, and free the 225 + * existing current. Note that this means KCI can result 226 + * in this transition. It would perhaps be more sound to 227 + * always just get rid of the unused next keypair 228 + * instead of putting it in the previous slot, but this 229 + * might be a bit less robust. Something to think about 230 + * for the future. 231 + */ 232 + RCU_INIT_POINTER(keypairs->next_keypair, NULL); 233 + rcu_assign_pointer(keypairs->previous_keypair, 234 + next_keypair); 235 + wg_noise_keypair_put(current_keypair, true); 236 + } else /* If there wasn't an existing next keypair, we replace 237 + * the previous with the current one. 238 + */ 239 + rcu_assign_pointer(keypairs->previous_keypair, 240 + current_keypair); 241 + /* At this point we can get rid of the old previous keypair, and 242 + * set up the new keypair. 243 + */ 244 + wg_noise_keypair_put(previous_keypair, true); 245 + rcu_assign_pointer(keypairs->current_keypair, new_keypair); 246 + } else { 247 + /* If we're the responder, it means we can't use the new keypair 248 + * until we receive confirmation via the first data packet, so 249 + * we get rid of the existing previous one, the possibly 250 + * existing next one, and slide in the new next one. 251 + */ 252 + rcu_assign_pointer(keypairs->next_keypair, new_keypair); 253 + wg_noise_keypair_put(next_keypair, true); 254 + RCU_INIT_POINTER(keypairs->previous_keypair, NULL); 255 + wg_noise_keypair_put(previous_keypair, true); 256 + } 257 + spin_unlock_bh(&keypairs->keypair_update_lock); 258 + } 259 + 260 + bool wg_noise_received_with_keypair(struct noise_keypairs *keypairs, 261 + struct noise_keypair *received_keypair) 262 + { 263 + struct noise_keypair *old_keypair; 264 + bool key_is_new; 265 + 266 + /* We first check without taking the spinlock. */ 267 + key_is_new = received_keypair == 268 + rcu_access_pointer(keypairs->next_keypair); 269 + if (likely(!key_is_new)) 270 + return false; 271 + 272 + spin_lock_bh(&keypairs->keypair_update_lock); 273 + /* After locking, we double check that things didn't change from 274 + * beneath us. 275 + */ 276 + if (unlikely(received_keypair != 277 + rcu_dereference_protected(keypairs->next_keypair, 278 + lockdep_is_held(&keypairs->keypair_update_lock)))) { 279 + spin_unlock_bh(&keypairs->keypair_update_lock); 280 + return false; 281 + } 282 + 283 + /* When we've finally received the confirmation, we slide the next 284 + * into the current, the current into the previous, and get rid of 285 + * the old previous. 286 + */ 287 + old_keypair = rcu_dereference_protected(keypairs->previous_keypair, 288 + lockdep_is_held(&keypairs->keypair_update_lock)); 289 + rcu_assign_pointer(keypairs->previous_keypair, 290 + rcu_dereference_protected(keypairs->current_keypair, 291 + lockdep_is_held(&keypairs->keypair_update_lock))); 292 + wg_noise_keypair_put(old_keypair, true); 293 + rcu_assign_pointer(keypairs->current_keypair, received_keypair); 294 + RCU_INIT_POINTER(keypairs->next_keypair, NULL); 295 + 296 + spin_unlock_bh(&keypairs->keypair_update_lock); 297 + return true; 298 + } 299 + 300 + /* Must hold static_identity->lock */ 301 + void wg_noise_set_static_identity_private_key( 302 + struct noise_static_identity *static_identity, 303 + const u8 private_key[NOISE_PUBLIC_KEY_LEN]) 304 + { 305 + memcpy(static_identity->static_private, private_key, 306 + NOISE_PUBLIC_KEY_LEN); 307 + curve25519_clamp_secret(static_identity->static_private); 308 + static_identity->has_identity = curve25519_generate_public( 309 + static_identity->static_public, private_key); 310 + } 311 + 312 + /* This is Hugo Krawczyk's HKDF: 313 + * - https://eprint.iacr.org/2010/264.pdf 314 + * - https://tools.ietf.org/html/rfc5869 315 + */ 316 + static void kdf(u8 *first_dst, u8 *second_dst, u8 *third_dst, const u8 *data, 317 + size_t first_len, size_t second_len, size_t third_len, 318 + size_t data_len, const u8 chaining_key[NOISE_HASH_LEN]) 319 + { 320 + u8 output[BLAKE2S_HASH_SIZE + 1]; 321 + u8 secret[BLAKE2S_HASH_SIZE]; 322 + 323 + WARN_ON(IS_ENABLED(DEBUG) && 324 + (first_len > BLAKE2S_HASH_SIZE || 325 + second_len > BLAKE2S_HASH_SIZE || 326 + third_len > BLAKE2S_HASH_SIZE || 327 + ((second_len || second_dst || third_len || third_dst) && 328 + (!first_len || !first_dst)) || 329 + ((third_len || third_dst) && (!second_len || !second_dst)))); 330 + 331 + /* Extract entropy from data into secret */ 332 + blake2s256_hmac(secret, data, chaining_key, data_len, NOISE_HASH_LEN); 333 + 334 + if (!first_dst || !first_len) 335 + goto out; 336 + 337 + /* Expand first key: key = secret, data = 0x1 */ 338 + output[0] = 1; 339 + blake2s256_hmac(output, output, secret, 1, BLAKE2S_HASH_SIZE); 340 + memcpy(first_dst, output, first_len); 341 + 342 + if (!second_dst || !second_len) 343 + goto out; 344 + 345 + /* Expand second key: key = secret, data = first-key || 0x2 */ 346 + output[BLAKE2S_HASH_SIZE] = 2; 347 + blake2s256_hmac(output, output, secret, BLAKE2S_HASH_SIZE + 1, 348 + BLAKE2S_HASH_SIZE); 349 + memcpy(second_dst, output, second_len); 350 + 351 + if (!third_dst || !third_len) 352 + goto out; 353 + 354 + /* Expand third key: key = secret, data = second-key || 0x3 */ 355 + output[BLAKE2S_HASH_SIZE] = 3; 356 + blake2s256_hmac(output, output, secret, BLAKE2S_HASH_SIZE + 1, 357 + BLAKE2S_HASH_SIZE); 358 + memcpy(third_dst, output, third_len); 359 + 360 + out: 361 + /* Clear sensitive data from stack */ 362 + memzero_explicit(secret, BLAKE2S_HASH_SIZE); 363 + memzero_explicit(output, BLAKE2S_HASH_SIZE + 1); 364 + } 365 + 366 + static void symmetric_key_init(struct noise_symmetric_key *key) 367 + { 368 + spin_lock_init(&key->counter.receive.lock); 369 + atomic64_set(&key->counter.counter, 0); 370 + memset(key->counter.receive.backtrack, 0, 371 + sizeof(key->counter.receive.backtrack)); 372 + key->birthdate = ktime_get_coarse_boottime_ns(); 373 + key->is_valid = true; 374 + } 375 + 376 + static void derive_keys(struct noise_symmetric_key *first_dst, 377 + struct noise_symmetric_key *second_dst, 378 + const u8 chaining_key[NOISE_HASH_LEN]) 379 + { 380 + kdf(first_dst->key, second_dst->key, NULL, NULL, 381 + NOISE_SYMMETRIC_KEY_LEN, NOISE_SYMMETRIC_KEY_LEN, 0, 0, 382 + chaining_key); 383 + symmetric_key_init(first_dst); 384 + symmetric_key_init(second_dst); 385 + } 386 + 387 + static bool __must_check mix_dh(u8 chaining_key[NOISE_HASH_LEN], 388 + u8 key[NOISE_SYMMETRIC_KEY_LEN], 389 + const u8 private[NOISE_PUBLIC_KEY_LEN], 390 + const u8 public[NOISE_PUBLIC_KEY_LEN]) 391 + { 392 + u8 dh_calculation[NOISE_PUBLIC_KEY_LEN]; 393 + 394 + if (unlikely(!curve25519(dh_calculation, private, public))) 395 + return false; 396 + kdf(chaining_key, key, NULL, dh_calculation, NOISE_HASH_LEN, 397 + NOISE_SYMMETRIC_KEY_LEN, 0, NOISE_PUBLIC_KEY_LEN, chaining_key); 398 + memzero_explicit(dh_calculation, NOISE_PUBLIC_KEY_LEN); 399 + return true; 400 + } 401 + 402 + static void mix_hash(u8 hash[NOISE_HASH_LEN], const u8 *src, size_t src_len) 403 + { 404 + struct blake2s_state blake; 405 + 406 + blake2s_init(&blake, NOISE_HASH_LEN); 407 + blake2s_update(&blake, hash, NOISE_HASH_LEN); 408 + blake2s_update(&blake, src, src_len); 409 + blake2s_final(&blake, hash); 410 + } 411 + 412 + static void mix_psk(u8 chaining_key[NOISE_HASH_LEN], u8 hash[NOISE_HASH_LEN], 413 + u8 key[NOISE_SYMMETRIC_KEY_LEN], 414 + const u8 psk[NOISE_SYMMETRIC_KEY_LEN]) 415 + { 416 + u8 temp_hash[NOISE_HASH_LEN]; 417 + 418 + kdf(chaining_key, temp_hash, key, psk, NOISE_HASH_LEN, NOISE_HASH_LEN, 419 + NOISE_SYMMETRIC_KEY_LEN, NOISE_SYMMETRIC_KEY_LEN, chaining_key); 420 + mix_hash(hash, temp_hash, NOISE_HASH_LEN); 421 + memzero_explicit(temp_hash, NOISE_HASH_LEN); 422 + } 423 + 424 + static void handshake_init(u8 chaining_key[NOISE_HASH_LEN], 425 + u8 hash[NOISE_HASH_LEN], 426 + const u8 remote_static[NOISE_PUBLIC_KEY_LEN]) 427 + { 428 + memcpy(hash, handshake_init_hash, NOISE_HASH_LEN); 429 + memcpy(chaining_key, handshake_init_chaining_key, NOISE_HASH_LEN); 430 + mix_hash(hash, remote_static, NOISE_PUBLIC_KEY_LEN); 431 + } 432 + 433 + static void message_encrypt(u8 *dst_ciphertext, const u8 *src_plaintext, 434 + size_t src_len, u8 key[NOISE_SYMMETRIC_KEY_LEN], 435 + u8 hash[NOISE_HASH_LEN]) 436 + { 437 + chacha20poly1305_encrypt(dst_ciphertext, src_plaintext, src_len, hash, 438 + NOISE_HASH_LEN, 439 + 0 /* Always zero for Noise_IK */, key); 440 + mix_hash(hash, dst_ciphertext, noise_encrypted_len(src_len)); 441 + } 442 + 443 + static bool message_decrypt(u8 *dst_plaintext, const u8 *src_ciphertext, 444 + size_t src_len, u8 key[NOISE_SYMMETRIC_KEY_LEN], 445 + u8 hash[NOISE_HASH_LEN]) 446 + { 447 + if (!chacha20poly1305_decrypt(dst_plaintext, src_ciphertext, src_len, 448 + hash, NOISE_HASH_LEN, 449 + 0 /* Always zero for Noise_IK */, key)) 450 + return false; 451 + mix_hash(hash, src_ciphertext, src_len); 452 + return true; 453 + } 454 + 455 + static void message_ephemeral(u8 ephemeral_dst[NOISE_PUBLIC_KEY_LEN], 456 + const u8 ephemeral_src[NOISE_PUBLIC_KEY_LEN], 457 + u8 chaining_key[NOISE_HASH_LEN], 458 + u8 hash[NOISE_HASH_LEN]) 459 + { 460 + if (ephemeral_dst != ephemeral_src) 461 + memcpy(ephemeral_dst, ephemeral_src, NOISE_PUBLIC_KEY_LEN); 462 + mix_hash(hash, ephemeral_src, NOISE_PUBLIC_KEY_LEN); 463 + kdf(chaining_key, NULL, NULL, ephemeral_src, NOISE_HASH_LEN, 0, 0, 464 + NOISE_PUBLIC_KEY_LEN, chaining_key); 465 + } 466 + 467 + static void tai64n_now(u8 output[NOISE_TIMESTAMP_LEN]) 468 + { 469 + struct timespec64 now; 470 + 471 + ktime_get_real_ts64(&now); 472 + 473 + /* In order to prevent some sort of infoleak from precise timers, we 474 + * round down the nanoseconds part to the closest rounded-down power of 475 + * two to the maximum initiations per second allowed anyway by the 476 + * implementation. 477 + */ 478 + now.tv_nsec = ALIGN_DOWN(now.tv_nsec, 479 + rounddown_pow_of_two(NSEC_PER_SEC / INITIATIONS_PER_SECOND)); 480 + 481 + /* https://cr.yp.to/libtai/tai64.html */ 482 + *(__be64 *)output = cpu_to_be64(0x400000000000000aULL + now.tv_sec); 483 + *(__be32 *)(output + sizeof(__be64)) = cpu_to_be32(now.tv_nsec); 484 + } 485 + 486 + bool 487 + wg_noise_handshake_create_initiation(struct message_handshake_initiation *dst, 488 + struct noise_handshake *handshake) 489 + { 490 + u8 timestamp[NOISE_TIMESTAMP_LEN]; 491 + u8 key[NOISE_SYMMETRIC_KEY_LEN]; 492 + bool ret = false; 493 + 494 + /* We need to wait for crng _before_ taking any locks, since 495 + * curve25519_generate_secret uses get_random_bytes_wait. 496 + */ 497 + wait_for_random_bytes(); 498 + 499 + down_read(&handshake->static_identity->lock); 500 + down_write(&handshake->lock); 501 + 502 + if (unlikely(!handshake->static_identity->has_identity)) 503 + goto out; 504 + 505 + dst->header.type = cpu_to_le32(MESSAGE_HANDSHAKE_INITIATION); 506 + 507 + handshake_init(handshake->chaining_key, handshake->hash, 508 + handshake->remote_static); 509 + 510 + /* e */ 511 + curve25519_generate_secret(handshake->ephemeral_private); 512 + if (!curve25519_generate_public(dst->unencrypted_ephemeral, 513 + handshake->ephemeral_private)) 514 + goto out; 515 + message_ephemeral(dst->unencrypted_ephemeral, 516 + dst->unencrypted_ephemeral, handshake->chaining_key, 517 + handshake->hash); 518 + 519 + /* es */ 520 + if (!mix_dh(handshake->chaining_key, key, handshake->ephemeral_private, 521 + handshake->remote_static)) 522 + goto out; 523 + 524 + /* s */ 525 + message_encrypt(dst->encrypted_static, 526 + handshake->static_identity->static_public, 527 + NOISE_PUBLIC_KEY_LEN, key, handshake->hash); 528 + 529 + /* ss */ 530 + kdf(handshake->chaining_key, key, NULL, 531 + handshake->precomputed_static_static, NOISE_HASH_LEN, 532 + NOISE_SYMMETRIC_KEY_LEN, 0, NOISE_PUBLIC_KEY_LEN, 533 + handshake->chaining_key); 534 + 535 + /* {t} */ 536 + tai64n_now(timestamp); 537 + message_encrypt(dst->encrypted_timestamp, timestamp, 538 + NOISE_TIMESTAMP_LEN, key, handshake->hash); 539 + 540 + dst->sender_index = wg_index_hashtable_insert( 541 + handshake->entry.peer->device->index_hashtable, 542 + &handshake->entry); 543 + 544 + handshake->state = HANDSHAKE_CREATED_INITIATION; 545 + ret = true; 546 + 547 + out: 548 + up_write(&handshake->lock); 549 + up_read(&handshake->static_identity->lock); 550 + memzero_explicit(key, NOISE_SYMMETRIC_KEY_LEN); 551 + return ret; 552 + } 553 + 554 + struct wg_peer * 555 + wg_noise_handshake_consume_initiation(struct message_handshake_initiation *src, 556 + struct wg_device *wg) 557 + { 558 + struct wg_peer *peer = NULL, *ret_peer = NULL; 559 + struct noise_handshake *handshake; 560 + bool replay_attack, flood_attack; 561 + u8 key[NOISE_SYMMETRIC_KEY_LEN]; 562 + u8 chaining_key[NOISE_HASH_LEN]; 563 + u8 hash[NOISE_HASH_LEN]; 564 + u8 s[NOISE_PUBLIC_KEY_LEN]; 565 + u8 e[NOISE_PUBLIC_KEY_LEN]; 566 + u8 t[NOISE_TIMESTAMP_LEN]; 567 + u64 initiation_consumption; 568 + 569 + down_read(&wg->static_identity.lock); 570 + if (unlikely(!wg->static_identity.has_identity)) 571 + goto out; 572 + 573 + handshake_init(chaining_key, hash, wg->static_identity.static_public); 574 + 575 + /* e */ 576 + message_ephemeral(e, src->unencrypted_ephemeral, chaining_key, hash); 577 + 578 + /* es */ 579 + if (!mix_dh(chaining_key, key, wg->static_identity.static_private, e)) 580 + goto out; 581 + 582 + /* s */ 583 + if (!message_decrypt(s, src->encrypted_static, 584 + sizeof(src->encrypted_static), key, hash)) 585 + goto out; 586 + 587 + /* Lookup which peer we're actually talking to */ 588 + peer = wg_pubkey_hashtable_lookup(wg->peer_hashtable, s); 589 + if (!peer) 590 + goto out; 591 + handshake = &peer->handshake; 592 + 593 + /* ss */ 594 + kdf(chaining_key, key, NULL, handshake->precomputed_static_static, 595 + NOISE_HASH_LEN, NOISE_SYMMETRIC_KEY_LEN, 0, NOISE_PUBLIC_KEY_LEN, 596 + chaining_key); 597 + 598 + /* {t} */ 599 + if (!message_decrypt(t, src->encrypted_timestamp, 600 + sizeof(src->encrypted_timestamp), key, hash)) 601 + goto out; 602 + 603 + down_read(&handshake->lock); 604 + replay_attack = memcmp(t, handshake->latest_timestamp, 605 + NOISE_TIMESTAMP_LEN) <= 0; 606 + flood_attack = (s64)handshake->last_initiation_consumption + 607 + NSEC_PER_SEC / INITIATIONS_PER_SECOND > 608 + (s64)ktime_get_coarse_boottime_ns(); 609 + up_read(&handshake->lock); 610 + if (replay_attack || flood_attack) 611 + goto out; 612 + 613 + /* Success! Copy everything to peer */ 614 + down_write(&handshake->lock); 615 + memcpy(handshake->remote_ephemeral, e, NOISE_PUBLIC_KEY_LEN); 616 + if (memcmp(t, handshake->latest_timestamp, NOISE_TIMESTAMP_LEN) > 0) 617 + memcpy(handshake->latest_timestamp, t, NOISE_TIMESTAMP_LEN); 618 + memcpy(handshake->hash, hash, NOISE_HASH_LEN); 619 + memcpy(handshake->chaining_key, chaining_key, NOISE_HASH_LEN); 620 + handshake->remote_index = src->sender_index; 621 + if ((s64)(handshake->last_initiation_consumption - 622 + (initiation_consumption = ktime_get_coarse_boottime_ns())) < 0) 623 + handshake->last_initiation_consumption = initiation_consumption; 624 + handshake->state = HANDSHAKE_CONSUMED_INITIATION; 625 + up_write(&handshake->lock); 626 + ret_peer = peer; 627 + 628 + out: 629 + memzero_explicit(key, NOISE_SYMMETRIC_KEY_LEN); 630 + memzero_explicit(hash, NOISE_HASH_LEN); 631 + memzero_explicit(chaining_key, NOISE_HASH_LEN); 632 + up_read(&wg->static_identity.lock); 633 + if (!ret_peer) 634 + wg_peer_put(peer); 635 + return ret_peer; 636 + } 637 + 638 + bool wg_noise_handshake_create_response(struct message_handshake_response *dst, 639 + struct noise_handshake *handshake) 640 + { 641 + u8 key[NOISE_SYMMETRIC_KEY_LEN]; 642 + bool ret = false; 643 + 644 + /* We need to wait for crng _before_ taking any locks, since 645 + * curve25519_generate_secret uses get_random_bytes_wait. 646 + */ 647 + wait_for_random_bytes(); 648 + 649 + down_read(&handshake->static_identity->lock); 650 + down_write(&handshake->lock); 651 + 652 + if (handshake->state != HANDSHAKE_CONSUMED_INITIATION) 653 + goto out; 654 + 655 + dst->header.type = cpu_to_le32(MESSAGE_HANDSHAKE_RESPONSE); 656 + dst->receiver_index = handshake->remote_index; 657 + 658 + /* e */ 659 + curve25519_generate_secret(handshake->ephemeral_private); 660 + if (!curve25519_generate_public(dst->unencrypted_ephemeral, 661 + handshake->ephemeral_private)) 662 + goto out; 663 + message_ephemeral(dst->unencrypted_ephemeral, 664 + dst->unencrypted_ephemeral, handshake->chaining_key, 665 + handshake->hash); 666 + 667 + /* ee */ 668 + if (!mix_dh(handshake->chaining_key, NULL, handshake->ephemeral_private, 669 + handshake->remote_ephemeral)) 670 + goto out; 671 + 672 + /* se */ 673 + if (!mix_dh(handshake->chaining_key, NULL, handshake->ephemeral_private, 674 + handshake->remote_static)) 675 + goto out; 676 + 677 + /* psk */ 678 + mix_psk(handshake->chaining_key, handshake->hash, key, 679 + handshake->preshared_key); 680 + 681 + /* {} */ 682 + message_encrypt(dst->encrypted_nothing, NULL, 0, key, handshake->hash); 683 + 684 + dst->sender_index = wg_index_hashtable_insert( 685 + handshake->entry.peer->device->index_hashtable, 686 + &handshake->entry); 687 + 688 + handshake->state = HANDSHAKE_CREATED_RESPONSE; 689 + ret = true; 690 + 691 + out: 692 + up_write(&handshake->lock); 693 + up_read(&handshake->static_identity->lock); 694 + memzero_explicit(key, NOISE_SYMMETRIC_KEY_LEN); 695 + return ret; 696 + } 697 + 698 + struct wg_peer * 699 + wg_noise_handshake_consume_response(struct message_handshake_response *src, 700 + struct wg_device *wg) 701 + { 702 + enum noise_handshake_state state = HANDSHAKE_ZEROED; 703 + struct wg_peer *peer = NULL, *ret_peer = NULL; 704 + struct noise_handshake *handshake; 705 + u8 key[NOISE_SYMMETRIC_KEY_LEN]; 706 + u8 hash[NOISE_HASH_LEN]; 707 + u8 chaining_key[NOISE_HASH_LEN]; 708 + u8 e[NOISE_PUBLIC_KEY_LEN]; 709 + u8 ephemeral_private[NOISE_PUBLIC_KEY_LEN]; 710 + u8 static_private[NOISE_PUBLIC_KEY_LEN]; 711 + 712 + down_read(&wg->static_identity.lock); 713 + 714 + if (unlikely(!wg->static_identity.has_identity)) 715 + goto out; 716 + 717 + handshake = (struct noise_handshake *)wg_index_hashtable_lookup( 718 + wg->index_hashtable, INDEX_HASHTABLE_HANDSHAKE, 719 + src->receiver_index, &peer); 720 + if (unlikely(!handshake)) 721 + goto out; 722 + 723 + down_read(&handshake->lock); 724 + state = handshake->state; 725 + memcpy(hash, handshake->hash, NOISE_HASH_LEN); 726 + memcpy(chaining_key, handshake->chaining_key, NOISE_HASH_LEN); 727 + memcpy(ephemeral_private, handshake->ephemeral_private, 728 + NOISE_PUBLIC_KEY_LEN); 729 + up_read(&handshake->lock); 730 + 731 + if (state != HANDSHAKE_CREATED_INITIATION) 732 + goto fail; 733 + 734 + /* e */ 735 + message_ephemeral(e, src->unencrypted_ephemeral, chaining_key, hash); 736 + 737 + /* ee */ 738 + if (!mix_dh(chaining_key, NULL, ephemeral_private, e)) 739 + goto fail; 740 + 741 + /* se */ 742 + if (!mix_dh(chaining_key, NULL, wg->static_identity.static_private, e)) 743 + goto fail; 744 + 745 + /* psk */ 746 + mix_psk(chaining_key, hash, key, handshake->preshared_key); 747 + 748 + /* {} */ 749 + if (!message_decrypt(NULL, src->encrypted_nothing, 750 + sizeof(src->encrypted_nothing), key, hash)) 751 + goto fail; 752 + 753 + /* Success! Copy everything to peer */ 754 + down_write(&handshake->lock); 755 + /* It's important to check that the state is still the same, while we 756 + * have an exclusive lock. 757 + */ 758 + if (handshake->state != state) { 759 + up_write(&handshake->lock); 760 + goto fail; 761 + } 762 + memcpy(handshake->remote_ephemeral, e, NOISE_PUBLIC_KEY_LEN); 763 + memcpy(handshake->hash, hash, NOISE_HASH_LEN); 764 + memcpy(handshake->chaining_key, chaining_key, NOISE_HASH_LEN); 765 + handshake->remote_index = src->sender_index; 766 + handshake->state = HANDSHAKE_CONSUMED_RESPONSE; 767 + up_write(&handshake->lock); 768 + ret_peer = peer; 769 + goto out; 770 + 771 + fail: 772 + wg_peer_put(peer); 773 + out: 774 + memzero_explicit(key, NOISE_SYMMETRIC_KEY_LEN); 775 + memzero_explicit(hash, NOISE_HASH_LEN); 776 + memzero_explicit(chaining_key, NOISE_HASH_LEN); 777 + memzero_explicit(ephemeral_private, NOISE_PUBLIC_KEY_LEN); 778 + memzero_explicit(static_private, NOISE_PUBLIC_KEY_LEN); 779 + up_read(&wg->static_identity.lock); 780 + return ret_peer; 781 + } 782 + 783 + bool wg_noise_handshake_begin_session(struct noise_handshake *handshake, 784 + struct noise_keypairs *keypairs) 785 + { 786 + struct noise_keypair *new_keypair; 787 + bool ret = false; 788 + 789 + down_write(&handshake->lock); 790 + if (handshake->state != HANDSHAKE_CREATED_RESPONSE && 791 + handshake->state != HANDSHAKE_CONSUMED_RESPONSE) 792 + goto out; 793 + 794 + new_keypair = keypair_create(handshake->entry.peer); 795 + if (!new_keypair) 796 + goto out; 797 + new_keypair->i_am_the_initiator = handshake->state == 798 + HANDSHAKE_CONSUMED_RESPONSE; 799 + new_keypair->remote_index = handshake->remote_index; 800 + 801 + if (new_keypair->i_am_the_initiator) 802 + derive_keys(&new_keypair->sending, &new_keypair->receiving, 803 + handshake->chaining_key); 804 + else 805 + derive_keys(&new_keypair->receiving, &new_keypair->sending, 806 + handshake->chaining_key); 807 + 808 + handshake_zero(handshake); 809 + rcu_read_lock_bh(); 810 + if (likely(!READ_ONCE(container_of(handshake, struct wg_peer, 811 + handshake)->is_dead))) { 812 + add_new_keypair(keypairs, new_keypair); 813 + net_dbg_ratelimited("%s: Keypair %llu created for peer %llu\n", 814 + handshake->entry.peer->device->dev->name, 815 + new_keypair->internal_id, 816 + handshake->entry.peer->internal_id); 817 + ret = wg_index_hashtable_replace( 818 + handshake->entry.peer->device->index_hashtable, 819 + &handshake->entry, &new_keypair->entry); 820 + } else { 821 + kzfree(new_keypair); 822 + } 823 + rcu_read_unlock_bh(); 824 + 825 + out: 826 + up_write(&handshake->lock); 827 + return ret; 828 + }
+137
drivers/net/wireguard/noise.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + #ifndef _WG_NOISE_H 6 + #define _WG_NOISE_H 7 + 8 + #include "messages.h" 9 + #include "peerlookup.h" 10 + 11 + #include <linux/types.h> 12 + #include <linux/spinlock.h> 13 + #include <linux/atomic.h> 14 + #include <linux/rwsem.h> 15 + #include <linux/mutex.h> 16 + #include <linux/kref.h> 17 + 18 + union noise_counter { 19 + struct { 20 + u64 counter; 21 + unsigned long backtrack[COUNTER_BITS_TOTAL / BITS_PER_LONG]; 22 + spinlock_t lock; 23 + } receive; 24 + atomic64_t counter; 25 + }; 26 + 27 + struct noise_symmetric_key { 28 + u8 key[NOISE_SYMMETRIC_KEY_LEN]; 29 + union noise_counter counter; 30 + u64 birthdate; 31 + bool is_valid; 32 + }; 33 + 34 + struct noise_keypair { 35 + struct index_hashtable_entry entry; 36 + struct noise_symmetric_key sending; 37 + struct noise_symmetric_key receiving; 38 + __le32 remote_index; 39 + bool i_am_the_initiator; 40 + struct kref refcount; 41 + struct rcu_head rcu; 42 + u64 internal_id; 43 + }; 44 + 45 + struct noise_keypairs { 46 + struct noise_keypair __rcu *current_keypair; 47 + struct noise_keypair __rcu *previous_keypair; 48 + struct noise_keypair __rcu *next_keypair; 49 + spinlock_t keypair_update_lock; 50 + }; 51 + 52 + struct noise_static_identity { 53 + u8 static_public[NOISE_PUBLIC_KEY_LEN]; 54 + u8 static_private[NOISE_PUBLIC_KEY_LEN]; 55 + struct rw_semaphore lock; 56 + bool has_identity; 57 + }; 58 + 59 + enum noise_handshake_state { 60 + HANDSHAKE_ZEROED, 61 + HANDSHAKE_CREATED_INITIATION, 62 + HANDSHAKE_CONSUMED_INITIATION, 63 + HANDSHAKE_CREATED_RESPONSE, 64 + HANDSHAKE_CONSUMED_RESPONSE 65 + }; 66 + 67 + struct noise_handshake { 68 + struct index_hashtable_entry entry; 69 + 70 + enum noise_handshake_state state; 71 + u64 last_initiation_consumption; 72 + 73 + struct noise_static_identity *static_identity; 74 + 75 + u8 ephemeral_private[NOISE_PUBLIC_KEY_LEN]; 76 + u8 remote_static[NOISE_PUBLIC_KEY_LEN]; 77 + u8 remote_ephemeral[NOISE_PUBLIC_KEY_LEN]; 78 + u8 precomputed_static_static[NOISE_PUBLIC_KEY_LEN]; 79 + 80 + u8 preshared_key[NOISE_SYMMETRIC_KEY_LEN]; 81 + 82 + u8 hash[NOISE_HASH_LEN]; 83 + u8 chaining_key[NOISE_HASH_LEN]; 84 + 85 + u8 latest_timestamp[NOISE_TIMESTAMP_LEN]; 86 + __le32 remote_index; 87 + 88 + /* Protects all members except the immutable (after noise_handshake_ 89 + * init): remote_static, precomputed_static_static, static_identity. 90 + */ 91 + struct rw_semaphore lock; 92 + }; 93 + 94 + struct wg_device; 95 + 96 + void wg_noise_init(void); 97 + bool wg_noise_handshake_init(struct noise_handshake *handshake, 98 + struct noise_static_identity *static_identity, 99 + const u8 peer_public_key[NOISE_PUBLIC_KEY_LEN], 100 + const u8 peer_preshared_key[NOISE_SYMMETRIC_KEY_LEN], 101 + struct wg_peer *peer); 102 + void wg_noise_handshake_clear(struct noise_handshake *handshake); 103 + static inline void wg_noise_reset_last_sent_handshake(atomic64_t *handshake_ns) 104 + { 105 + atomic64_set(handshake_ns, ktime_get_coarse_boottime_ns() - 106 + (u64)(REKEY_TIMEOUT + 1) * NSEC_PER_SEC); 107 + } 108 + 109 + void wg_noise_keypair_put(struct noise_keypair *keypair, bool unreference_now); 110 + struct noise_keypair *wg_noise_keypair_get(struct noise_keypair *keypair); 111 + void wg_noise_keypairs_clear(struct noise_keypairs *keypairs); 112 + bool wg_noise_received_with_keypair(struct noise_keypairs *keypairs, 113 + struct noise_keypair *received_keypair); 114 + void wg_noise_expire_current_peer_keypairs(struct wg_peer *peer); 115 + 116 + void wg_noise_set_static_identity_private_key( 117 + struct noise_static_identity *static_identity, 118 + const u8 private_key[NOISE_PUBLIC_KEY_LEN]); 119 + bool wg_noise_precompute_static_static(struct wg_peer *peer); 120 + 121 + bool 122 + wg_noise_handshake_create_initiation(struct message_handshake_initiation *dst, 123 + struct noise_handshake *handshake); 124 + struct wg_peer * 125 + wg_noise_handshake_consume_initiation(struct message_handshake_initiation *src, 126 + struct wg_device *wg); 127 + 128 + bool wg_noise_handshake_create_response(struct message_handshake_response *dst, 129 + struct noise_handshake *handshake); 130 + struct wg_peer * 131 + wg_noise_handshake_consume_response(struct message_handshake_response *src, 132 + struct wg_device *wg); 133 + 134 + bool wg_noise_handshake_begin_session(struct noise_handshake *handshake, 135 + struct noise_keypairs *keypairs); 136 + 137 + #endif /* _WG_NOISE_H */
+240
drivers/net/wireguard/peer.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "peer.h" 7 + #include "device.h" 8 + #include "queueing.h" 9 + #include "timers.h" 10 + #include "peerlookup.h" 11 + #include "noise.h" 12 + 13 + #include <linux/kref.h> 14 + #include <linux/lockdep.h> 15 + #include <linux/rcupdate.h> 16 + #include <linux/list.h> 17 + 18 + static atomic64_t peer_counter = ATOMIC64_INIT(0); 19 + 20 + struct wg_peer *wg_peer_create(struct wg_device *wg, 21 + const u8 public_key[NOISE_PUBLIC_KEY_LEN], 22 + const u8 preshared_key[NOISE_SYMMETRIC_KEY_LEN]) 23 + { 24 + struct wg_peer *peer; 25 + int ret = -ENOMEM; 26 + 27 + lockdep_assert_held(&wg->device_update_lock); 28 + 29 + if (wg->num_peers >= MAX_PEERS_PER_DEVICE) 30 + return ERR_PTR(ret); 31 + 32 + peer = kzalloc(sizeof(*peer), GFP_KERNEL); 33 + if (unlikely(!peer)) 34 + return ERR_PTR(ret); 35 + peer->device = wg; 36 + 37 + if (!wg_noise_handshake_init(&peer->handshake, &wg->static_identity, 38 + public_key, preshared_key, peer)) { 39 + ret = -EKEYREJECTED; 40 + goto err_1; 41 + } 42 + if (dst_cache_init(&peer->endpoint_cache, GFP_KERNEL)) 43 + goto err_1; 44 + if (wg_packet_queue_init(&peer->tx_queue, wg_packet_tx_worker, false, 45 + MAX_QUEUED_PACKETS)) 46 + goto err_2; 47 + if (wg_packet_queue_init(&peer->rx_queue, NULL, false, 48 + MAX_QUEUED_PACKETS)) 49 + goto err_3; 50 + 51 + peer->internal_id = atomic64_inc_return(&peer_counter); 52 + peer->serial_work_cpu = nr_cpumask_bits; 53 + wg_cookie_init(&peer->latest_cookie); 54 + wg_timers_init(peer); 55 + wg_cookie_checker_precompute_peer_keys(peer); 56 + spin_lock_init(&peer->keypairs.keypair_update_lock); 57 + INIT_WORK(&peer->transmit_handshake_work, 58 + wg_packet_handshake_send_worker); 59 + rwlock_init(&peer->endpoint_lock); 60 + kref_init(&peer->refcount); 61 + skb_queue_head_init(&peer->staged_packet_queue); 62 + wg_noise_reset_last_sent_handshake(&peer->last_sent_handshake); 63 + set_bit(NAPI_STATE_NO_BUSY_POLL, &peer->napi.state); 64 + netif_napi_add(wg->dev, &peer->napi, wg_packet_rx_poll, 65 + NAPI_POLL_WEIGHT); 66 + napi_enable(&peer->napi); 67 + list_add_tail(&peer->peer_list, &wg->peer_list); 68 + INIT_LIST_HEAD(&peer->allowedips_list); 69 + wg_pubkey_hashtable_add(wg->peer_hashtable, peer); 70 + ++wg->num_peers; 71 + pr_debug("%s: Peer %llu created\n", wg->dev->name, peer->internal_id); 72 + return peer; 73 + 74 + err_3: 75 + wg_packet_queue_free(&peer->tx_queue, false); 76 + err_2: 77 + dst_cache_destroy(&peer->endpoint_cache); 78 + err_1: 79 + kfree(peer); 80 + return ERR_PTR(ret); 81 + } 82 + 83 + struct wg_peer *wg_peer_get_maybe_zero(struct wg_peer *peer) 84 + { 85 + RCU_LOCKDEP_WARN(!rcu_read_lock_bh_held(), 86 + "Taking peer reference without holding the RCU read lock"); 87 + if (unlikely(!peer || !kref_get_unless_zero(&peer->refcount))) 88 + return NULL; 89 + return peer; 90 + } 91 + 92 + static void peer_make_dead(struct wg_peer *peer) 93 + { 94 + /* Remove from configuration-time lookup structures. */ 95 + list_del_init(&peer->peer_list); 96 + wg_allowedips_remove_by_peer(&peer->device->peer_allowedips, peer, 97 + &peer->device->device_update_lock); 98 + wg_pubkey_hashtable_remove(peer->device->peer_hashtable, peer); 99 + 100 + /* Mark as dead, so that we don't allow jumping contexts after. */ 101 + WRITE_ONCE(peer->is_dead, true); 102 + 103 + /* The caller must now synchronize_rcu() for this to take effect. */ 104 + } 105 + 106 + static void peer_remove_after_dead(struct wg_peer *peer) 107 + { 108 + WARN_ON(!peer->is_dead); 109 + 110 + /* No more keypairs can be created for this peer, since is_dead protects 111 + * add_new_keypair, so we can now destroy existing ones. 112 + */ 113 + wg_noise_keypairs_clear(&peer->keypairs); 114 + 115 + /* Destroy all ongoing timers that were in-flight at the beginning of 116 + * this function. 117 + */ 118 + wg_timers_stop(peer); 119 + 120 + /* The transition between packet encryption/decryption queues isn't 121 + * guarded by is_dead, but each reference's life is strictly bounded by 122 + * two generations: once for parallel crypto and once for serial 123 + * ingestion, so we can simply flush twice, and be sure that we no 124 + * longer have references inside these queues. 125 + */ 126 + 127 + /* a) For encrypt/decrypt. */ 128 + flush_workqueue(peer->device->packet_crypt_wq); 129 + /* b.1) For send (but not receive, since that's napi). */ 130 + flush_workqueue(peer->device->packet_crypt_wq); 131 + /* b.2.1) For receive (but not send, since that's wq). */ 132 + napi_disable(&peer->napi); 133 + /* b.2.1) It's now safe to remove the napi struct, which must be done 134 + * here from process context. 135 + */ 136 + netif_napi_del(&peer->napi); 137 + 138 + /* Ensure any workstructs we own (like transmit_handshake_work or 139 + * clear_peer_work) no longer are in use. 140 + */ 141 + flush_workqueue(peer->device->handshake_send_wq); 142 + 143 + /* After the above flushes, a peer might still be active in a few 144 + * different contexts: 1) from xmit(), before hitting is_dead and 145 + * returning, 2) from wg_packet_consume_data(), before hitting is_dead 146 + * and returning, 3) from wg_receive_handshake_packet() after a point 147 + * where it has processed an incoming handshake packet, but where 148 + * all calls to pass it off to timers fails because of is_dead. We won't 149 + * have new references in (1) eventually, because we're removed from 150 + * allowedips; we won't have new references in (2) eventually, because 151 + * wg_index_hashtable_lookup will always return NULL, since we removed 152 + * all existing keypairs and no more can be created; we won't have new 153 + * references in (3) eventually, because we're removed from the pubkey 154 + * hash table, which allows for a maximum of one handshake response, 155 + * via the still-uncleared index hashtable entry, but not more than one, 156 + * and in wg_cookie_message_consume, the lookup eventually gets a peer 157 + * with a refcount of zero, so no new reference is taken. 158 + */ 159 + 160 + --peer->device->num_peers; 161 + wg_peer_put(peer); 162 + } 163 + 164 + /* We have a separate "remove" function make sure that all active places where 165 + * a peer is currently operating will eventually come to an end and not pass 166 + * their reference onto another context. 167 + */ 168 + void wg_peer_remove(struct wg_peer *peer) 169 + { 170 + if (unlikely(!peer)) 171 + return; 172 + lockdep_assert_held(&peer->device->device_update_lock); 173 + 174 + peer_make_dead(peer); 175 + synchronize_rcu(); 176 + peer_remove_after_dead(peer); 177 + } 178 + 179 + void wg_peer_remove_all(struct wg_device *wg) 180 + { 181 + struct wg_peer *peer, *temp; 182 + LIST_HEAD(dead_peers); 183 + 184 + lockdep_assert_held(&wg->device_update_lock); 185 + 186 + /* Avoid having to traverse individually for each one. */ 187 + wg_allowedips_free(&wg->peer_allowedips, &wg->device_update_lock); 188 + 189 + list_for_each_entry_safe(peer, temp, &wg->peer_list, peer_list) { 190 + peer_make_dead(peer); 191 + list_add_tail(&peer->peer_list, &dead_peers); 192 + } 193 + synchronize_rcu(); 194 + list_for_each_entry_safe(peer, temp, &dead_peers, peer_list) 195 + peer_remove_after_dead(peer); 196 + } 197 + 198 + static void rcu_release(struct rcu_head *rcu) 199 + { 200 + struct wg_peer *peer = container_of(rcu, struct wg_peer, rcu); 201 + 202 + dst_cache_destroy(&peer->endpoint_cache); 203 + wg_packet_queue_free(&peer->rx_queue, false); 204 + wg_packet_queue_free(&peer->tx_queue, false); 205 + 206 + /* The final zeroing takes care of clearing any remaining handshake key 207 + * material and other potentially sensitive information. 208 + */ 209 + kzfree(peer); 210 + } 211 + 212 + static void kref_release(struct kref *refcount) 213 + { 214 + struct wg_peer *peer = container_of(refcount, struct wg_peer, refcount); 215 + 216 + pr_debug("%s: Peer %llu (%pISpfsc) destroyed\n", 217 + peer->device->dev->name, peer->internal_id, 218 + &peer->endpoint.addr); 219 + 220 + /* Remove ourself from dynamic runtime lookup structures, now that the 221 + * last reference is gone. 222 + */ 223 + wg_index_hashtable_remove(peer->device->index_hashtable, 224 + &peer->handshake.entry); 225 + 226 + /* Remove any lingering packets that didn't have a chance to be 227 + * transmitted. 228 + */ 229 + wg_packet_purge_staged_packets(peer); 230 + 231 + /* Free the memory used. */ 232 + call_rcu(&peer->rcu, rcu_release); 233 + } 234 + 235 + void wg_peer_put(struct wg_peer *peer) 236 + { 237 + if (unlikely(!peer)) 238 + return; 239 + kref_put(&peer->refcount, kref_release); 240 + }
+83
drivers/net/wireguard/peer.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_PEER_H 7 + #define _WG_PEER_H 8 + 9 + #include "device.h" 10 + #include "noise.h" 11 + #include "cookie.h" 12 + 13 + #include <linux/types.h> 14 + #include <linux/netfilter.h> 15 + #include <linux/spinlock.h> 16 + #include <linux/kref.h> 17 + #include <net/dst_cache.h> 18 + 19 + struct wg_device; 20 + 21 + struct endpoint { 22 + union { 23 + struct sockaddr addr; 24 + struct sockaddr_in addr4; 25 + struct sockaddr_in6 addr6; 26 + }; 27 + union { 28 + struct { 29 + struct in_addr src4; 30 + /* Essentially the same as addr6->scope_id */ 31 + int src_if4; 32 + }; 33 + struct in6_addr src6; 34 + }; 35 + }; 36 + 37 + struct wg_peer { 38 + struct wg_device *device; 39 + struct crypt_queue tx_queue, rx_queue; 40 + struct sk_buff_head staged_packet_queue; 41 + int serial_work_cpu; 42 + struct noise_keypairs keypairs; 43 + struct endpoint endpoint; 44 + struct dst_cache endpoint_cache; 45 + rwlock_t endpoint_lock; 46 + struct noise_handshake handshake; 47 + atomic64_t last_sent_handshake; 48 + struct work_struct transmit_handshake_work, clear_peer_work; 49 + struct cookie latest_cookie; 50 + struct hlist_node pubkey_hash; 51 + u64 rx_bytes, tx_bytes; 52 + struct timer_list timer_retransmit_handshake, timer_send_keepalive; 53 + struct timer_list timer_new_handshake, timer_zero_key_material; 54 + struct timer_list timer_persistent_keepalive; 55 + unsigned int timer_handshake_attempts; 56 + u16 persistent_keepalive_interval; 57 + bool timer_need_another_keepalive; 58 + bool sent_lastminute_handshake; 59 + struct timespec64 walltime_last_handshake; 60 + struct kref refcount; 61 + struct rcu_head rcu; 62 + struct list_head peer_list; 63 + struct list_head allowedips_list; 64 + u64 internal_id; 65 + struct napi_struct napi; 66 + bool is_dead; 67 + }; 68 + 69 + struct wg_peer *wg_peer_create(struct wg_device *wg, 70 + const u8 public_key[NOISE_PUBLIC_KEY_LEN], 71 + const u8 preshared_key[NOISE_SYMMETRIC_KEY_LEN]); 72 + 73 + struct wg_peer *__must_check wg_peer_get_maybe_zero(struct wg_peer *peer); 74 + static inline struct wg_peer *wg_peer_get(struct wg_peer *peer) 75 + { 76 + kref_get(&peer->refcount); 77 + return peer; 78 + } 79 + void wg_peer_put(struct wg_peer *peer); 80 + void wg_peer_remove(struct wg_peer *peer); 81 + void wg_peer_remove_all(struct wg_device *wg); 82 + 83 + #endif /* _WG_PEER_H */
+221
drivers/net/wireguard/peerlookup.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "peerlookup.h" 7 + #include "peer.h" 8 + #include "noise.h" 9 + 10 + static struct hlist_head *pubkey_bucket(struct pubkey_hashtable *table, 11 + const u8 pubkey[NOISE_PUBLIC_KEY_LEN]) 12 + { 13 + /* siphash gives us a secure 64bit number based on a random key. Since 14 + * the bits are uniformly distributed, we can then mask off to get the 15 + * bits we need. 16 + */ 17 + const u64 hash = siphash(pubkey, NOISE_PUBLIC_KEY_LEN, &table->key); 18 + 19 + return &table->hashtable[hash & (HASH_SIZE(table->hashtable) - 1)]; 20 + } 21 + 22 + struct pubkey_hashtable *wg_pubkey_hashtable_alloc(void) 23 + { 24 + struct pubkey_hashtable *table = kvmalloc(sizeof(*table), GFP_KERNEL); 25 + 26 + if (!table) 27 + return NULL; 28 + 29 + get_random_bytes(&table->key, sizeof(table->key)); 30 + hash_init(table->hashtable); 31 + mutex_init(&table->lock); 32 + return table; 33 + } 34 + 35 + void wg_pubkey_hashtable_add(struct pubkey_hashtable *table, 36 + struct wg_peer *peer) 37 + { 38 + mutex_lock(&table->lock); 39 + hlist_add_head_rcu(&peer->pubkey_hash, 40 + pubkey_bucket(table, peer->handshake.remote_static)); 41 + mutex_unlock(&table->lock); 42 + } 43 + 44 + void wg_pubkey_hashtable_remove(struct pubkey_hashtable *table, 45 + struct wg_peer *peer) 46 + { 47 + mutex_lock(&table->lock); 48 + hlist_del_init_rcu(&peer->pubkey_hash); 49 + mutex_unlock(&table->lock); 50 + } 51 + 52 + /* Returns a strong reference to a peer */ 53 + struct wg_peer * 54 + wg_pubkey_hashtable_lookup(struct pubkey_hashtable *table, 55 + const u8 pubkey[NOISE_PUBLIC_KEY_LEN]) 56 + { 57 + struct wg_peer *iter_peer, *peer = NULL; 58 + 59 + rcu_read_lock_bh(); 60 + hlist_for_each_entry_rcu_bh(iter_peer, pubkey_bucket(table, pubkey), 61 + pubkey_hash) { 62 + if (!memcmp(pubkey, iter_peer->handshake.remote_static, 63 + NOISE_PUBLIC_KEY_LEN)) { 64 + peer = iter_peer; 65 + break; 66 + } 67 + } 68 + peer = wg_peer_get_maybe_zero(peer); 69 + rcu_read_unlock_bh(); 70 + return peer; 71 + } 72 + 73 + static struct hlist_head *index_bucket(struct index_hashtable *table, 74 + const __le32 index) 75 + { 76 + /* Since the indices are random and thus all bits are uniformly 77 + * distributed, we can find its bucket simply by masking. 78 + */ 79 + return &table->hashtable[(__force u32)index & 80 + (HASH_SIZE(table->hashtable) - 1)]; 81 + } 82 + 83 + struct index_hashtable *wg_index_hashtable_alloc(void) 84 + { 85 + struct index_hashtable *table = kvmalloc(sizeof(*table), GFP_KERNEL); 86 + 87 + if (!table) 88 + return NULL; 89 + 90 + hash_init(table->hashtable); 91 + spin_lock_init(&table->lock); 92 + return table; 93 + } 94 + 95 + /* At the moment, we limit ourselves to 2^20 total peers, which generally might 96 + * amount to 2^20*3 items in this hashtable. The algorithm below works by 97 + * picking a random number and testing it. We can see that these limits mean we 98 + * usually succeed pretty quickly: 99 + * 100 + * >>> def calculation(tries, size): 101 + * ... return (size / 2**32)**(tries - 1) * (1 - (size / 2**32)) 102 + * ... 103 + * >>> calculation(1, 2**20 * 3) 104 + * 0.999267578125 105 + * >>> calculation(2, 2**20 * 3) 106 + * 0.0007318854331970215 107 + * >>> calculation(3, 2**20 * 3) 108 + * 5.360489012673497e-07 109 + * >>> calculation(4, 2**20 * 3) 110 + * 3.9261394135792216e-10 111 + * 112 + * At the moment, we don't do any masking, so this algorithm isn't exactly 113 + * constant time in either the random guessing or in the hash list lookup. We 114 + * could require a minimum of 3 tries, which would successfully mask the 115 + * guessing. this would not, however, help with the growing hash lengths, which 116 + * is another thing to consider moving forward. 117 + */ 118 + 119 + __le32 wg_index_hashtable_insert(struct index_hashtable *table, 120 + struct index_hashtable_entry *entry) 121 + { 122 + struct index_hashtable_entry *existing_entry; 123 + 124 + spin_lock_bh(&table->lock); 125 + hlist_del_init_rcu(&entry->index_hash); 126 + spin_unlock_bh(&table->lock); 127 + 128 + rcu_read_lock_bh(); 129 + 130 + search_unused_slot: 131 + /* First we try to find an unused slot, randomly, while unlocked. */ 132 + entry->index = (__force __le32)get_random_u32(); 133 + hlist_for_each_entry_rcu_bh(existing_entry, 134 + index_bucket(table, entry->index), 135 + index_hash) { 136 + if (existing_entry->index == entry->index) 137 + /* If it's already in use, we continue searching. */ 138 + goto search_unused_slot; 139 + } 140 + 141 + /* Once we've found an unused slot, we lock it, and then double-check 142 + * that nobody else stole it from us. 143 + */ 144 + spin_lock_bh(&table->lock); 145 + hlist_for_each_entry_rcu_bh(existing_entry, 146 + index_bucket(table, entry->index), 147 + index_hash) { 148 + if (existing_entry->index == entry->index) { 149 + spin_unlock_bh(&table->lock); 150 + /* If it was stolen, we start over. */ 151 + goto search_unused_slot; 152 + } 153 + } 154 + /* Otherwise, we know we have it exclusively (since we're locked), 155 + * so we insert. 156 + */ 157 + hlist_add_head_rcu(&entry->index_hash, 158 + index_bucket(table, entry->index)); 159 + spin_unlock_bh(&table->lock); 160 + 161 + rcu_read_unlock_bh(); 162 + 163 + return entry->index; 164 + } 165 + 166 + bool wg_index_hashtable_replace(struct index_hashtable *table, 167 + struct index_hashtable_entry *old, 168 + struct index_hashtable_entry *new) 169 + { 170 + if (unlikely(hlist_unhashed(&old->index_hash))) 171 + return false; 172 + spin_lock_bh(&table->lock); 173 + new->index = old->index; 174 + hlist_replace_rcu(&old->index_hash, &new->index_hash); 175 + 176 + /* Calling init here NULLs out index_hash, and in fact after this 177 + * function returns, it's theoretically possible for this to get 178 + * reinserted elsewhere. That means the RCU lookup below might either 179 + * terminate early or jump between buckets, in which case the packet 180 + * simply gets dropped, which isn't terrible. 181 + */ 182 + INIT_HLIST_NODE(&old->index_hash); 183 + spin_unlock_bh(&table->lock); 184 + return true; 185 + } 186 + 187 + void wg_index_hashtable_remove(struct index_hashtable *table, 188 + struct index_hashtable_entry *entry) 189 + { 190 + spin_lock_bh(&table->lock); 191 + hlist_del_init_rcu(&entry->index_hash); 192 + spin_unlock_bh(&table->lock); 193 + } 194 + 195 + /* Returns a strong reference to a entry->peer */ 196 + struct index_hashtable_entry * 197 + wg_index_hashtable_lookup(struct index_hashtable *table, 198 + const enum index_hashtable_type type_mask, 199 + const __le32 index, struct wg_peer **peer) 200 + { 201 + struct index_hashtable_entry *iter_entry, *entry = NULL; 202 + 203 + rcu_read_lock_bh(); 204 + hlist_for_each_entry_rcu_bh(iter_entry, index_bucket(table, index), 205 + index_hash) { 206 + if (iter_entry->index == index) { 207 + if (likely(iter_entry->type & type_mask)) 208 + entry = iter_entry; 209 + break; 210 + } 211 + } 212 + if (likely(entry)) { 213 + entry->peer = wg_peer_get_maybe_zero(entry->peer); 214 + if (likely(entry->peer)) 215 + *peer = entry->peer; 216 + else 217 + entry = NULL; 218 + } 219 + rcu_read_unlock_bh(); 220 + return entry; 221 + }
+64
drivers/net/wireguard/peerlookup.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_PEERLOOKUP_H 7 + #define _WG_PEERLOOKUP_H 8 + 9 + #include "messages.h" 10 + 11 + #include <linux/hashtable.h> 12 + #include <linux/mutex.h> 13 + #include <linux/siphash.h> 14 + 15 + struct wg_peer; 16 + 17 + struct pubkey_hashtable { 18 + /* TODO: move to rhashtable */ 19 + DECLARE_HASHTABLE(hashtable, 11); 20 + siphash_key_t key; 21 + struct mutex lock; 22 + }; 23 + 24 + struct pubkey_hashtable *wg_pubkey_hashtable_alloc(void); 25 + void wg_pubkey_hashtable_add(struct pubkey_hashtable *table, 26 + struct wg_peer *peer); 27 + void wg_pubkey_hashtable_remove(struct pubkey_hashtable *table, 28 + struct wg_peer *peer); 29 + struct wg_peer * 30 + wg_pubkey_hashtable_lookup(struct pubkey_hashtable *table, 31 + const u8 pubkey[NOISE_PUBLIC_KEY_LEN]); 32 + 33 + struct index_hashtable { 34 + /* TODO: move to rhashtable */ 35 + DECLARE_HASHTABLE(hashtable, 13); 36 + spinlock_t lock; 37 + }; 38 + 39 + enum index_hashtable_type { 40 + INDEX_HASHTABLE_HANDSHAKE = 1U << 0, 41 + INDEX_HASHTABLE_KEYPAIR = 1U << 1 42 + }; 43 + 44 + struct index_hashtable_entry { 45 + struct wg_peer *peer; 46 + struct hlist_node index_hash; 47 + enum index_hashtable_type type; 48 + __le32 index; 49 + }; 50 + 51 + struct index_hashtable *wg_index_hashtable_alloc(void); 52 + __le32 wg_index_hashtable_insert(struct index_hashtable *table, 53 + struct index_hashtable_entry *entry); 54 + bool wg_index_hashtable_replace(struct index_hashtable *table, 55 + struct index_hashtable_entry *old, 56 + struct index_hashtable_entry *new); 57 + void wg_index_hashtable_remove(struct index_hashtable *table, 58 + struct index_hashtable_entry *entry); 59 + struct index_hashtable_entry * 60 + wg_index_hashtable_lookup(struct index_hashtable *table, 61 + const enum index_hashtable_type type_mask, 62 + const __le32 index, struct wg_peer **peer); 63 + 64 + #endif /* _WG_PEERLOOKUP_H */
+53
drivers/net/wireguard/queueing.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "queueing.h" 7 + 8 + struct multicore_worker __percpu * 9 + wg_packet_percpu_multicore_worker_alloc(work_func_t function, void *ptr) 10 + { 11 + int cpu; 12 + struct multicore_worker __percpu *worker = 13 + alloc_percpu(struct multicore_worker); 14 + 15 + if (!worker) 16 + return NULL; 17 + 18 + for_each_possible_cpu(cpu) { 19 + per_cpu_ptr(worker, cpu)->ptr = ptr; 20 + INIT_WORK(&per_cpu_ptr(worker, cpu)->work, function); 21 + } 22 + return worker; 23 + } 24 + 25 + int wg_packet_queue_init(struct crypt_queue *queue, work_func_t function, 26 + bool multicore, unsigned int len) 27 + { 28 + int ret; 29 + 30 + memset(queue, 0, sizeof(*queue)); 31 + ret = ptr_ring_init(&queue->ring, len, GFP_KERNEL); 32 + if (ret) 33 + return ret; 34 + if (function) { 35 + if (multicore) { 36 + queue->worker = wg_packet_percpu_multicore_worker_alloc( 37 + function, queue); 38 + if (!queue->worker) 39 + return -ENOMEM; 40 + } else { 41 + INIT_WORK(&queue->work, function); 42 + } 43 + } 44 + return 0; 45 + } 46 + 47 + void wg_packet_queue_free(struct crypt_queue *queue, bool multicore) 48 + { 49 + if (multicore) 50 + free_percpu(queue->worker); 51 + WARN_ON(!__ptr_ring_empty(&queue->ring)); 52 + ptr_ring_cleanup(&queue->ring, NULL); 53 + }
+197
drivers/net/wireguard/queueing.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_QUEUEING_H 7 + #define _WG_QUEUEING_H 8 + 9 + #include "peer.h" 10 + #include <linux/types.h> 11 + #include <linux/skbuff.h> 12 + #include <linux/ip.h> 13 + #include <linux/ipv6.h> 14 + 15 + struct wg_device; 16 + struct wg_peer; 17 + struct multicore_worker; 18 + struct crypt_queue; 19 + struct sk_buff; 20 + 21 + /* queueing.c APIs: */ 22 + int wg_packet_queue_init(struct crypt_queue *queue, work_func_t function, 23 + bool multicore, unsigned int len); 24 + void wg_packet_queue_free(struct crypt_queue *queue, bool multicore); 25 + struct multicore_worker __percpu * 26 + wg_packet_percpu_multicore_worker_alloc(work_func_t function, void *ptr); 27 + 28 + /* receive.c APIs: */ 29 + void wg_packet_receive(struct wg_device *wg, struct sk_buff *skb); 30 + void wg_packet_handshake_receive_worker(struct work_struct *work); 31 + /* NAPI poll function: */ 32 + int wg_packet_rx_poll(struct napi_struct *napi, int budget); 33 + /* Workqueue worker: */ 34 + void wg_packet_decrypt_worker(struct work_struct *work); 35 + 36 + /* send.c APIs: */ 37 + void wg_packet_send_queued_handshake_initiation(struct wg_peer *peer, 38 + bool is_retry); 39 + void wg_packet_send_handshake_response(struct wg_peer *peer); 40 + void wg_packet_send_handshake_cookie(struct wg_device *wg, 41 + struct sk_buff *initiating_skb, 42 + __le32 sender_index); 43 + void wg_packet_send_keepalive(struct wg_peer *peer); 44 + void wg_packet_purge_staged_packets(struct wg_peer *peer); 45 + void wg_packet_send_staged_packets(struct wg_peer *peer); 46 + /* Workqueue workers: */ 47 + void wg_packet_handshake_send_worker(struct work_struct *work); 48 + void wg_packet_tx_worker(struct work_struct *work); 49 + void wg_packet_encrypt_worker(struct work_struct *work); 50 + 51 + enum packet_state { 52 + PACKET_STATE_UNCRYPTED, 53 + PACKET_STATE_CRYPTED, 54 + PACKET_STATE_DEAD 55 + }; 56 + 57 + struct packet_cb { 58 + u64 nonce; 59 + struct noise_keypair *keypair; 60 + atomic_t state; 61 + u32 mtu; 62 + u8 ds; 63 + }; 64 + 65 + #define PACKET_CB(skb) ((struct packet_cb *)((skb)->cb)) 66 + #define PACKET_PEER(skb) (PACKET_CB(skb)->keypair->entry.peer) 67 + 68 + /* Returns either the correct skb->protocol value, or 0 if invalid. */ 69 + static inline __be16 wg_skb_examine_untrusted_ip_hdr(struct sk_buff *skb) 70 + { 71 + if (skb_network_header(skb) >= skb->head && 72 + (skb_network_header(skb) + sizeof(struct iphdr)) <= 73 + skb_tail_pointer(skb) && 74 + ip_hdr(skb)->version == 4) 75 + return htons(ETH_P_IP); 76 + if (skb_network_header(skb) >= skb->head && 77 + (skb_network_header(skb) + sizeof(struct ipv6hdr)) <= 78 + skb_tail_pointer(skb) && 79 + ipv6_hdr(skb)->version == 6) 80 + return htons(ETH_P_IPV6); 81 + return 0; 82 + } 83 + 84 + static inline void wg_reset_packet(struct sk_buff *skb) 85 + { 86 + const int pfmemalloc = skb->pfmemalloc; 87 + 88 + skb_scrub_packet(skb, true); 89 + memset(&skb->headers_start, 0, 90 + offsetof(struct sk_buff, headers_end) - 91 + offsetof(struct sk_buff, headers_start)); 92 + skb->pfmemalloc = pfmemalloc; 93 + skb->queue_mapping = 0; 94 + skb->nohdr = 0; 95 + skb->peeked = 0; 96 + skb->mac_len = 0; 97 + skb->dev = NULL; 98 + #ifdef CONFIG_NET_SCHED 99 + skb->tc_index = 0; 100 + skb_reset_tc(skb); 101 + #endif 102 + skb->hdr_len = skb_headroom(skb); 103 + skb_reset_mac_header(skb); 104 + skb_reset_network_header(skb); 105 + skb_reset_transport_header(skb); 106 + skb_probe_transport_header(skb); 107 + skb_reset_inner_headers(skb); 108 + } 109 + 110 + static inline int wg_cpumask_choose_online(int *stored_cpu, unsigned int id) 111 + { 112 + unsigned int cpu = *stored_cpu, cpu_index, i; 113 + 114 + if (unlikely(cpu == nr_cpumask_bits || 115 + !cpumask_test_cpu(cpu, cpu_online_mask))) { 116 + cpu_index = id % cpumask_weight(cpu_online_mask); 117 + cpu = cpumask_first(cpu_online_mask); 118 + for (i = 0; i < cpu_index; ++i) 119 + cpu = cpumask_next(cpu, cpu_online_mask); 120 + *stored_cpu = cpu; 121 + } 122 + return cpu; 123 + } 124 + 125 + /* This function is racy, in the sense that next is unlocked, so it could return 126 + * the same CPU twice. A race-free version of this would be to instead store an 127 + * atomic sequence number, do an increment-and-return, and then iterate through 128 + * every possible CPU until we get to that index -- choose_cpu. However that's 129 + * a bit slower, and it doesn't seem like this potential race actually 130 + * introduces any performance loss, so we live with it. 131 + */ 132 + static inline int wg_cpumask_next_online(int *next) 133 + { 134 + int cpu = *next; 135 + 136 + while (unlikely(!cpumask_test_cpu(cpu, cpu_online_mask))) 137 + cpu = cpumask_next(cpu, cpu_online_mask) % nr_cpumask_bits; 138 + *next = cpumask_next(cpu, cpu_online_mask) % nr_cpumask_bits; 139 + return cpu; 140 + } 141 + 142 + static inline int wg_queue_enqueue_per_device_and_peer( 143 + struct crypt_queue *device_queue, struct crypt_queue *peer_queue, 144 + struct sk_buff *skb, struct workqueue_struct *wq, int *next_cpu) 145 + { 146 + int cpu; 147 + 148 + atomic_set_release(&PACKET_CB(skb)->state, PACKET_STATE_UNCRYPTED); 149 + /* We first queue this up for the peer ingestion, but the consumer 150 + * will wait for the state to change to CRYPTED or DEAD before. 151 + */ 152 + if (unlikely(ptr_ring_produce_bh(&peer_queue->ring, skb))) 153 + return -ENOSPC; 154 + /* Then we queue it up in the device queue, which consumes the 155 + * packet as soon as it can. 156 + */ 157 + cpu = wg_cpumask_next_online(next_cpu); 158 + if (unlikely(ptr_ring_produce_bh(&device_queue->ring, skb))) 159 + return -EPIPE; 160 + queue_work_on(cpu, wq, &per_cpu_ptr(device_queue->worker, cpu)->work); 161 + return 0; 162 + } 163 + 164 + static inline void wg_queue_enqueue_per_peer(struct crypt_queue *queue, 165 + struct sk_buff *skb, 166 + enum packet_state state) 167 + { 168 + /* We take a reference, because as soon as we call atomic_set, the 169 + * peer can be freed from below us. 170 + */ 171 + struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb)); 172 + 173 + atomic_set_release(&PACKET_CB(skb)->state, state); 174 + queue_work_on(wg_cpumask_choose_online(&peer->serial_work_cpu, 175 + peer->internal_id), 176 + peer->device->packet_crypt_wq, &queue->work); 177 + wg_peer_put(peer); 178 + } 179 + 180 + static inline void wg_queue_enqueue_per_peer_napi(struct sk_buff *skb, 181 + enum packet_state state) 182 + { 183 + /* We take a reference, because as soon as we call atomic_set, the 184 + * peer can be freed from below us. 185 + */ 186 + struct wg_peer *peer = wg_peer_get(PACKET_PEER(skb)); 187 + 188 + atomic_set_release(&PACKET_CB(skb)->state, state); 189 + napi_schedule(&peer->napi); 190 + wg_peer_put(peer); 191 + } 192 + 193 + #ifdef DEBUG 194 + bool wg_packet_counter_selftest(void); 195 + #endif 196 + 197 + #endif /* _WG_QUEUEING_H */
+223
drivers/net/wireguard/ratelimiter.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "ratelimiter.h" 7 + #include <linux/siphash.h> 8 + #include <linux/mm.h> 9 + #include <linux/slab.h> 10 + #include <net/ip.h> 11 + 12 + static struct kmem_cache *entry_cache; 13 + static hsiphash_key_t key; 14 + static spinlock_t table_lock = __SPIN_LOCK_UNLOCKED("ratelimiter_table_lock"); 15 + static DEFINE_MUTEX(init_lock); 16 + static u64 init_refcnt; /* Protected by init_lock, hence not atomic. */ 17 + static atomic_t total_entries = ATOMIC_INIT(0); 18 + static unsigned int max_entries, table_size; 19 + static void wg_ratelimiter_gc_entries(struct work_struct *); 20 + static DECLARE_DEFERRABLE_WORK(gc_work, wg_ratelimiter_gc_entries); 21 + static struct hlist_head *table_v4; 22 + #if IS_ENABLED(CONFIG_IPV6) 23 + static struct hlist_head *table_v6; 24 + #endif 25 + 26 + struct ratelimiter_entry { 27 + u64 last_time_ns, tokens, ip; 28 + void *net; 29 + spinlock_t lock; 30 + struct hlist_node hash; 31 + struct rcu_head rcu; 32 + }; 33 + 34 + enum { 35 + PACKETS_PER_SECOND = 20, 36 + PACKETS_BURSTABLE = 5, 37 + PACKET_COST = NSEC_PER_SEC / PACKETS_PER_SECOND, 38 + TOKEN_MAX = PACKET_COST * PACKETS_BURSTABLE 39 + }; 40 + 41 + static void entry_free(struct rcu_head *rcu) 42 + { 43 + kmem_cache_free(entry_cache, 44 + container_of(rcu, struct ratelimiter_entry, rcu)); 45 + atomic_dec(&total_entries); 46 + } 47 + 48 + static void entry_uninit(struct ratelimiter_entry *entry) 49 + { 50 + hlist_del_rcu(&entry->hash); 51 + call_rcu(&entry->rcu, entry_free); 52 + } 53 + 54 + /* Calling this function with a NULL work uninits all entries. */ 55 + static void wg_ratelimiter_gc_entries(struct work_struct *work) 56 + { 57 + const u64 now = ktime_get_coarse_boottime_ns(); 58 + struct ratelimiter_entry *entry; 59 + struct hlist_node *temp; 60 + unsigned int i; 61 + 62 + for (i = 0; i < table_size; ++i) { 63 + spin_lock(&table_lock); 64 + hlist_for_each_entry_safe(entry, temp, &table_v4[i], hash) { 65 + if (unlikely(!work) || 66 + now - entry->last_time_ns > NSEC_PER_SEC) 67 + entry_uninit(entry); 68 + } 69 + #if IS_ENABLED(CONFIG_IPV6) 70 + hlist_for_each_entry_safe(entry, temp, &table_v6[i], hash) { 71 + if (unlikely(!work) || 72 + now - entry->last_time_ns > NSEC_PER_SEC) 73 + entry_uninit(entry); 74 + } 75 + #endif 76 + spin_unlock(&table_lock); 77 + if (likely(work)) 78 + cond_resched(); 79 + } 80 + if (likely(work)) 81 + queue_delayed_work(system_power_efficient_wq, &gc_work, HZ); 82 + } 83 + 84 + bool wg_ratelimiter_allow(struct sk_buff *skb, struct net *net) 85 + { 86 + /* We only take the bottom half of the net pointer, so that we can hash 87 + * 3 words in the end. This way, siphash's len param fits into the final 88 + * u32, and we don't incur an extra round. 89 + */ 90 + const u32 net_word = (unsigned long)net; 91 + struct ratelimiter_entry *entry; 92 + struct hlist_head *bucket; 93 + u64 ip; 94 + 95 + if (skb->protocol == htons(ETH_P_IP)) { 96 + ip = (u64 __force)ip_hdr(skb)->saddr; 97 + bucket = &table_v4[hsiphash_2u32(net_word, ip, &key) & 98 + (table_size - 1)]; 99 + } 100 + #if IS_ENABLED(CONFIG_IPV6) 101 + else if (skb->protocol == htons(ETH_P_IPV6)) { 102 + /* Only use 64 bits, so as to ratelimit the whole /64. */ 103 + memcpy(&ip, &ipv6_hdr(skb)->saddr, sizeof(ip)); 104 + bucket = &table_v6[hsiphash_3u32(net_word, ip >> 32, ip, &key) & 105 + (table_size - 1)]; 106 + } 107 + #endif 108 + else 109 + return false; 110 + rcu_read_lock(); 111 + hlist_for_each_entry_rcu(entry, bucket, hash) { 112 + if (entry->net == net && entry->ip == ip) { 113 + u64 now, tokens; 114 + bool ret; 115 + /* Quasi-inspired by nft_limit.c, but this is actually a 116 + * slightly different algorithm. Namely, we incorporate 117 + * the burst as part of the maximum tokens, rather than 118 + * as part of the rate. 119 + */ 120 + spin_lock(&entry->lock); 121 + now = ktime_get_coarse_boottime_ns(); 122 + tokens = min_t(u64, TOKEN_MAX, 123 + entry->tokens + now - 124 + entry->last_time_ns); 125 + entry->last_time_ns = now; 126 + ret = tokens >= PACKET_COST; 127 + entry->tokens = ret ? tokens - PACKET_COST : tokens; 128 + spin_unlock(&entry->lock); 129 + rcu_read_unlock(); 130 + return ret; 131 + } 132 + } 133 + rcu_read_unlock(); 134 + 135 + if (atomic_inc_return(&total_entries) > max_entries) 136 + goto err_oom; 137 + 138 + entry = kmem_cache_alloc(entry_cache, GFP_KERNEL); 139 + if (unlikely(!entry)) 140 + goto err_oom; 141 + 142 + entry->net = net; 143 + entry->ip = ip; 144 + INIT_HLIST_NODE(&entry->hash); 145 + spin_lock_init(&entry->lock); 146 + entry->last_time_ns = ktime_get_coarse_boottime_ns(); 147 + entry->tokens = TOKEN_MAX - PACKET_COST; 148 + spin_lock(&table_lock); 149 + hlist_add_head_rcu(&entry->hash, bucket); 150 + spin_unlock(&table_lock); 151 + return true; 152 + 153 + err_oom: 154 + atomic_dec(&total_entries); 155 + return false; 156 + } 157 + 158 + int wg_ratelimiter_init(void) 159 + { 160 + mutex_lock(&init_lock); 161 + if (++init_refcnt != 1) 162 + goto out; 163 + 164 + entry_cache = KMEM_CACHE(ratelimiter_entry, 0); 165 + if (!entry_cache) 166 + goto err; 167 + 168 + /* xt_hashlimit.c uses a slightly different algorithm for ratelimiting, 169 + * but what it shares in common is that it uses a massive hashtable. So, 170 + * we borrow their wisdom about good table sizes on different systems 171 + * dependent on RAM. This calculation here comes from there. 172 + */ 173 + table_size = (totalram_pages() > (1U << 30) / PAGE_SIZE) ? 8192 : 174 + max_t(unsigned long, 16, roundup_pow_of_two( 175 + (totalram_pages() << PAGE_SHIFT) / 176 + (1U << 14) / sizeof(struct hlist_head))); 177 + max_entries = table_size * 8; 178 + 179 + table_v4 = kvzalloc(table_size * sizeof(*table_v4), GFP_KERNEL); 180 + if (unlikely(!table_v4)) 181 + goto err_kmemcache; 182 + 183 + #if IS_ENABLED(CONFIG_IPV6) 184 + table_v6 = kvzalloc(table_size * sizeof(*table_v6), GFP_KERNEL); 185 + if (unlikely(!table_v6)) { 186 + kvfree(table_v4); 187 + goto err_kmemcache; 188 + } 189 + #endif 190 + 191 + queue_delayed_work(system_power_efficient_wq, &gc_work, HZ); 192 + get_random_bytes(&key, sizeof(key)); 193 + out: 194 + mutex_unlock(&init_lock); 195 + return 0; 196 + 197 + err_kmemcache: 198 + kmem_cache_destroy(entry_cache); 199 + err: 200 + --init_refcnt; 201 + mutex_unlock(&init_lock); 202 + return -ENOMEM; 203 + } 204 + 205 + void wg_ratelimiter_uninit(void) 206 + { 207 + mutex_lock(&init_lock); 208 + if (!init_refcnt || --init_refcnt) 209 + goto out; 210 + 211 + cancel_delayed_work_sync(&gc_work); 212 + wg_ratelimiter_gc_entries(NULL); 213 + rcu_barrier(); 214 + kvfree(table_v4); 215 + #if IS_ENABLED(CONFIG_IPV6) 216 + kvfree(table_v6); 217 + #endif 218 + kmem_cache_destroy(entry_cache); 219 + out: 220 + mutex_unlock(&init_lock); 221 + } 222 + 223 + #include "selftest/ratelimiter.c"
+19
drivers/net/wireguard/ratelimiter.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_RATELIMITER_H 7 + #define _WG_RATELIMITER_H 8 + 9 + #include <linux/skbuff.h> 10 + 11 + int wg_ratelimiter_init(void); 12 + void wg_ratelimiter_uninit(void); 13 + bool wg_ratelimiter_allow(struct sk_buff *skb, struct net *net); 14 + 15 + #ifdef DEBUG 16 + bool wg_ratelimiter_selftest(void); 17 + #endif 18 + 19 + #endif /* _WG_RATELIMITER_H */
+595
drivers/net/wireguard/receive.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "queueing.h" 7 + #include "device.h" 8 + #include "peer.h" 9 + #include "timers.h" 10 + #include "messages.h" 11 + #include "cookie.h" 12 + #include "socket.h" 13 + 14 + #include <linux/ip.h> 15 + #include <linux/ipv6.h> 16 + #include <linux/udp.h> 17 + #include <net/ip_tunnels.h> 18 + 19 + /* Must be called with bh disabled. */ 20 + static void update_rx_stats(struct wg_peer *peer, size_t len) 21 + { 22 + struct pcpu_sw_netstats *tstats = 23 + get_cpu_ptr(peer->device->dev->tstats); 24 + 25 + u64_stats_update_begin(&tstats->syncp); 26 + ++tstats->rx_packets; 27 + tstats->rx_bytes += len; 28 + peer->rx_bytes += len; 29 + u64_stats_update_end(&tstats->syncp); 30 + put_cpu_ptr(tstats); 31 + } 32 + 33 + #define SKB_TYPE_LE32(skb) (((struct message_header *)(skb)->data)->type) 34 + 35 + static size_t validate_header_len(struct sk_buff *skb) 36 + { 37 + if (unlikely(skb->len < sizeof(struct message_header))) 38 + return 0; 39 + if (SKB_TYPE_LE32(skb) == cpu_to_le32(MESSAGE_DATA) && 40 + skb->len >= MESSAGE_MINIMUM_LENGTH) 41 + return sizeof(struct message_data); 42 + if (SKB_TYPE_LE32(skb) == cpu_to_le32(MESSAGE_HANDSHAKE_INITIATION) && 43 + skb->len == sizeof(struct message_handshake_initiation)) 44 + return sizeof(struct message_handshake_initiation); 45 + if (SKB_TYPE_LE32(skb) == cpu_to_le32(MESSAGE_HANDSHAKE_RESPONSE) && 46 + skb->len == sizeof(struct message_handshake_response)) 47 + return sizeof(struct message_handshake_response); 48 + if (SKB_TYPE_LE32(skb) == cpu_to_le32(MESSAGE_HANDSHAKE_COOKIE) && 49 + skb->len == sizeof(struct message_handshake_cookie)) 50 + return sizeof(struct message_handshake_cookie); 51 + return 0; 52 + } 53 + 54 + static int prepare_skb_header(struct sk_buff *skb, struct wg_device *wg) 55 + { 56 + size_t data_offset, data_len, header_len; 57 + struct udphdr *udp; 58 + 59 + if (unlikely(wg_skb_examine_untrusted_ip_hdr(skb) != skb->protocol || 60 + skb_transport_header(skb) < skb->head || 61 + (skb_transport_header(skb) + sizeof(struct udphdr)) > 62 + skb_tail_pointer(skb))) 63 + return -EINVAL; /* Bogus IP header */ 64 + udp = udp_hdr(skb); 65 + data_offset = (u8 *)udp - skb->data; 66 + if (unlikely(data_offset > U16_MAX || 67 + data_offset + sizeof(struct udphdr) > skb->len)) 68 + /* Packet has offset at impossible location or isn't big enough 69 + * to have UDP fields. 70 + */ 71 + return -EINVAL; 72 + data_len = ntohs(udp->len); 73 + if (unlikely(data_len < sizeof(struct udphdr) || 74 + data_len > skb->len - data_offset)) 75 + /* UDP packet is reporting too small of a size or lying about 76 + * its size. 77 + */ 78 + return -EINVAL; 79 + data_len -= sizeof(struct udphdr); 80 + data_offset = (u8 *)udp + sizeof(struct udphdr) - skb->data; 81 + if (unlikely(!pskb_may_pull(skb, 82 + data_offset + sizeof(struct message_header)) || 83 + pskb_trim(skb, data_len + data_offset) < 0)) 84 + return -EINVAL; 85 + skb_pull(skb, data_offset); 86 + if (unlikely(skb->len != data_len)) 87 + /* Final len does not agree with calculated len */ 88 + return -EINVAL; 89 + header_len = validate_header_len(skb); 90 + if (unlikely(!header_len)) 91 + return -EINVAL; 92 + __skb_push(skb, data_offset); 93 + if (unlikely(!pskb_may_pull(skb, data_offset + header_len))) 94 + return -EINVAL; 95 + __skb_pull(skb, data_offset); 96 + return 0; 97 + } 98 + 99 + static void wg_receive_handshake_packet(struct wg_device *wg, 100 + struct sk_buff *skb) 101 + { 102 + enum cookie_mac_state mac_state; 103 + struct wg_peer *peer = NULL; 104 + /* This is global, so that our load calculation applies to the whole 105 + * system. We don't care about races with it at all. 106 + */ 107 + static u64 last_under_load; 108 + bool packet_needs_cookie; 109 + bool under_load; 110 + 111 + if (SKB_TYPE_LE32(skb) == cpu_to_le32(MESSAGE_HANDSHAKE_COOKIE)) { 112 + net_dbg_skb_ratelimited("%s: Receiving cookie response from %pISpfsc\n", 113 + wg->dev->name, skb); 114 + wg_cookie_message_consume( 115 + (struct message_handshake_cookie *)skb->data, wg); 116 + return; 117 + } 118 + 119 + under_load = skb_queue_len(&wg->incoming_handshakes) >= 120 + MAX_QUEUED_INCOMING_HANDSHAKES / 8; 121 + if (under_load) 122 + last_under_load = ktime_get_coarse_boottime_ns(); 123 + else if (last_under_load) 124 + under_load = !wg_birthdate_has_expired(last_under_load, 1); 125 + mac_state = wg_cookie_validate_packet(&wg->cookie_checker, skb, 126 + under_load); 127 + if ((under_load && mac_state == VALID_MAC_WITH_COOKIE) || 128 + (!under_load && mac_state == VALID_MAC_BUT_NO_COOKIE)) { 129 + packet_needs_cookie = false; 130 + } else if (under_load && mac_state == VALID_MAC_BUT_NO_COOKIE) { 131 + packet_needs_cookie = true; 132 + } else { 133 + net_dbg_skb_ratelimited("%s: Invalid MAC of handshake, dropping packet from %pISpfsc\n", 134 + wg->dev->name, skb); 135 + return; 136 + } 137 + 138 + switch (SKB_TYPE_LE32(skb)) { 139 + case cpu_to_le32(MESSAGE_HANDSHAKE_INITIATION): { 140 + struct message_handshake_initiation *message = 141 + (struct message_handshake_initiation *)skb->data; 142 + 143 + if (packet_needs_cookie) { 144 + wg_packet_send_handshake_cookie(wg, skb, 145 + message->sender_index); 146 + return; 147 + } 148 + peer = wg_noise_handshake_consume_initiation(message, wg); 149 + if (unlikely(!peer)) { 150 + net_dbg_skb_ratelimited("%s: Invalid handshake initiation from %pISpfsc\n", 151 + wg->dev->name, skb); 152 + return; 153 + } 154 + wg_socket_set_peer_endpoint_from_skb(peer, skb); 155 + net_dbg_ratelimited("%s: Receiving handshake initiation from peer %llu (%pISpfsc)\n", 156 + wg->dev->name, peer->internal_id, 157 + &peer->endpoint.addr); 158 + wg_packet_send_handshake_response(peer); 159 + break; 160 + } 161 + case cpu_to_le32(MESSAGE_HANDSHAKE_RESPONSE): { 162 + struct message_handshake_response *message = 163 + (struct message_handshake_response *)skb->data; 164 + 165 + if (packet_needs_cookie) { 166 + wg_packet_send_handshake_cookie(wg, skb, 167 + message->sender_index); 168 + return; 169 + } 170 + peer = wg_noise_handshake_consume_response(message, wg); 171 + if (unlikely(!peer)) { 172 + net_dbg_skb_ratelimited("%s: Invalid handshake response from %pISpfsc\n", 173 + wg->dev->name, skb); 174 + return; 175 + } 176 + wg_socket_set_peer_endpoint_from_skb(peer, skb); 177 + net_dbg_ratelimited("%s: Receiving handshake response from peer %llu (%pISpfsc)\n", 178 + wg->dev->name, peer->internal_id, 179 + &peer->endpoint.addr); 180 + if (wg_noise_handshake_begin_session(&peer->handshake, 181 + &peer->keypairs)) { 182 + wg_timers_session_derived(peer); 183 + wg_timers_handshake_complete(peer); 184 + /* Calling this function will either send any existing 185 + * packets in the queue and not send a keepalive, which 186 + * is the best case, Or, if there's nothing in the 187 + * queue, it will send a keepalive, in order to give 188 + * immediate confirmation of the session. 189 + */ 190 + wg_packet_send_keepalive(peer); 191 + } 192 + break; 193 + } 194 + } 195 + 196 + if (unlikely(!peer)) { 197 + WARN(1, "Somehow a wrong type of packet wound up in the handshake queue!\n"); 198 + return; 199 + } 200 + 201 + local_bh_disable(); 202 + update_rx_stats(peer, skb->len); 203 + local_bh_enable(); 204 + 205 + wg_timers_any_authenticated_packet_received(peer); 206 + wg_timers_any_authenticated_packet_traversal(peer); 207 + wg_peer_put(peer); 208 + } 209 + 210 + void wg_packet_handshake_receive_worker(struct work_struct *work) 211 + { 212 + struct wg_device *wg = container_of(work, struct multicore_worker, 213 + work)->ptr; 214 + struct sk_buff *skb; 215 + 216 + while ((skb = skb_dequeue(&wg->incoming_handshakes)) != NULL) { 217 + wg_receive_handshake_packet(wg, skb); 218 + dev_kfree_skb(skb); 219 + cond_resched(); 220 + } 221 + } 222 + 223 + static void keep_key_fresh(struct wg_peer *peer) 224 + { 225 + struct noise_keypair *keypair; 226 + bool send = false; 227 + 228 + if (peer->sent_lastminute_handshake) 229 + return; 230 + 231 + rcu_read_lock_bh(); 232 + keypair = rcu_dereference_bh(peer->keypairs.current_keypair); 233 + if (likely(keypair && READ_ONCE(keypair->sending.is_valid)) && 234 + keypair->i_am_the_initiator && 235 + unlikely(wg_birthdate_has_expired(keypair->sending.birthdate, 236 + REJECT_AFTER_TIME - KEEPALIVE_TIMEOUT - REKEY_TIMEOUT))) 237 + send = true; 238 + rcu_read_unlock_bh(); 239 + 240 + if (send) { 241 + peer->sent_lastminute_handshake = true; 242 + wg_packet_send_queued_handshake_initiation(peer, false); 243 + } 244 + } 245 + 246 + static bool decrypt_packet(struct sk_buff *skb, struct noise_symmetric_key *key) 247 + { 248 + struct scatterlist sg[MAX_SKB_FRAGS + 8]; 249 + struct sk_buff *trailer; 250 + unsigned int offset; 251 + int num_frags; 252 + 253 + if (unlikely(!key)) 254 + return false; 255 + 256 + if (unlikely(!READ_ONCE(key->is_valid) || 257 + wg_birthdate_has_expired(key->birthdate, REJECT_AFTER_TIME) || 258 + key->counter.receive.counter >= REJECT_AFTER_MESSAGES)) { 259 + WRITE_ONCE(key->is_valid, false); 260 + return false; 261 + } 262 + 263 + PACKET_CB(skb)->nonce = 264 + le64_to_cpu(((struct message_data *)skb->data)->counter); 265 + 266 + /* We ensure that the network header is part of the packet before we 267 + * call skb_cow_data, so that there's no chance that data is removed 268 + * from the skb, so that later we can extract the original endpoint. 269 + */ 270 + offset = skb->data - skb_network_header(skb); 271 + skb_push(skb, offset); 272 + num_frags = skb_cow_data(skb, 0, &trailer); 273 + offset += sizeof(struct message_data); 274 + skb_pull(skb, offset); 275 + if (unlikely(num_frags < 0 || num_frags > ARRAY_SIZE(sg))) 276 + return false; 277 + 278 + sg_init_table(sg, num_frags); 279 + if (skb_to_sgvec(skb, sg, 0, skb->len) <= 0) 280 + return false; 281 + 282 + if (!chacha20poly1305_decrypt_sg_inplace(sg, skb->len, NULL, 0, 283 + PACKET_CB(skb)->nonce, 284 + key->key)) 285 + return false; 286 + 287 + /* Another ugly situation of pushing and pulling the header so as to 288 + * keep endpoint information intact. 289 + */ 290 + skb_push(skb, offset); 291 + if (pskb_trim(skb, skb->len - noise_encrypted_len(0))) 292 + return false; 293 + skb_pull(skb, offset); 294 + 295 + return true; 296 + } 297 + 298 + /* This is RFC6479, a replay detection bitmap algorithm that avoids bitshifts */ 299 + static bool counter_validate(union noise_counter *counter, u64 their_counter) 300 + { 301 + unsigned long index, index_current, top, i; 302 + bool ret = false; 303 + 304 + spin_lock_bh(&counter->receive.lock); 305 + 306 + if (unlikely(counter->receive.counter >= REJECT_AFTER_MESSAGES + 1 || 307 + their_counter >= REJECT_AFTER_MESSAGES)) 308 + goto out; 309 + 310 + ++their_counter; 311 + 312 + if (unlikely((COUNTER_WINDOW_SIZE + their_counter) < 313 + counter->receive.counter)) 314 + goto out; 315 + 316 + index = their_counter >> ilog2(BITS_PER_LONG); 317 + 318 + if (likely(their_counter > counter->receive.counter)) { 319 + index_current = counter->receive.counter >> ilog2(BITS_PER_LONG); 320 + top = min_t(unsigned long, index - index_current, 321 + COUNTER_BITS_TOTAL / BITS_PER_LONG); 322 + for (i = 1; i <= top; ++i) 323 + counter->receive.backtrack[(i + index_current) & 324 + ((COUNTER_BITS_TOTAL / BITS_PER_LONG) - 1)] = 0; 325 + counter->receive.counter = their_counter; 326 + } 327 + 328 + index &= (COUNTER_BITS_TOTAL / BITS_PER_LONG) - 1; 329 + ret = !test_and_set_bit(their_counter & (BITS_PER_LONG - 1), 330 + &counter->receive.backtrack[index]); 331 + 332 + out: 333 + spin_unlock_bh(&counter->receive.lock); 334 + return ret; 335 + } 336 + 337 + #include "selftest/counter.c" 338 + 339 + static void wg_packet_consume_data_done(struct wg_peer *peer, 340 + struct sk_buff *skb, 341 + struct endpoint *endpoint) 342 + { 343 + struct net_device *dev = peer->device->dev; 344 + unsigned int len, len_before_trim; 345 + struct wg_peer *routed_peer; 346 + 347 + wg_socket_set_peer_endpoint(peer, endpoint); 348 + 349 + if (unlikely(wg_noise_received_with_keypair(&peer->keypairs, 350 + PACKET_CB(skb)->keypair))) { 351 + wg_timers_handshake_complete(peer); 352 + wg_packet_send_staged_packets(peer); 353 + } 354 + 355 + keep_key_fresh(peer); 356 + 357 + wg_timers_any_authenticated_packet_received(peer); 358 + wg_timers_any_authenticated_packet_traversal(peer); 359 + 360 + /* A packet with length 0 is a keepalive packet */ 361 + if (unlikely(!skb->len)) { 362 + update_rx_stats(peer, message_data_len(0)); 363 + net_dbg_ratelimited("%s: Receiving keepalive packet from peer %llu (%pISpfsc)\n", 364 + dev->name, peer->internal_id, 365 + &peer->endpoint.addr); 366 + goto packet_processed; 367 + } 368 + 369 + wg_timers_data_received(peer); 370 + 371 + if (unlikely(skb_network_header(skb) < skb->head)) 372 + goto dishonest_packet_size; 373 + if (unlikely(!(pskb_network_may_pull(skb, sizeof(struct iphdr)) && 374 + (ip_hdr(skb)->version == 4 || 375 + (ip_hdr(skb)->version == 6 && 376 + pskb_network_may_pull(skb, sizeof(struct ipv6hdr))))))) 377 + goto dishonest_packet_type; 378 + 379 + skb->dev = dev; 380 + /* We've already verified the Poly1305 auth tag, which means this packet 381 + * was not modified in transit. We can therefore tell the networking 382 + * stack that all checksums of every layer of encapsulation have already 383 + * been checked "by the hardware" and therefore is unneccessary to check 384 + * again in software. 385 + */ 386 + skb->ip_summed = CHECKSUM_UNNECESSARY; 387 + skb->csum_level = ~0; /* All levels */ 388 + skb->protocol = wg_skb_examine_untrusted_ip_hdr(skb); 389 + if (skb->protocol == htons(ETH_P_IP)) { 390 + len = ntohs(ip_hdr(skb)->tot_len); 391 + if (unlikely(len < sizeof(struct iphdr))) 392 + goto dishonest_packet_size; 393 + if (INET_ECN_is_ce(PACKET_CB(skb)->ds)) 394 + IP_ECN_set_ce(ip_hdr(skb)); 395 + } else if (skb->protocol == htons(ETH_P_IPV6)) { 396 + len = ntohs(ipv6_hdr(skb)->payload_len) + 397 + sizeof(struct ipv6hdr); 398 + if (INET_ECN_is_ce(PACKET_CB(skb)->ds)) 399 + IP6_ECN_set_ce(skb, ipv6_hdr(skb)); 400 + } else { 401 + goto dishonest_packet_type; 402 + } 403 + 404 + if (unlikely(len > skb->len)) 405 + goto dishonest_packet_size; 406 + len_before_trim = skb->len; 407 + if (unlikely(pskb_trim(skb, len))) 408 + goto packet_processed; 409 + 410 + routed_peer = wg_allowedips_lookup_src(&peer->device->peer_allowedips, 411 + skb); 412 + wg_peer_put(routed_peer); /* We don't need the extra reference. */ 413 + 414 + if (unlikely(routed_peer != peer)) 415 + goto dishonest_packet_peer; 416 + 417 + if (unlikely(napi_gro_receive(&peer->napi, skb) == GRO_DROP)) { 418 + ++dev->stats.rx_dropped; 419 + net_dbg_ratelimited("%s: Failed to give packet to userspace from peer %llu (%pISpfsc)\n", 420 + dev->name, peer->internal_id, 421 + &peer->endpoint.addr); 422 + } else { 423 + update_rx_stats(peer, message_data_len(len_before_trim)); 424 + } 425 + return; 426 + 427 + dishonest_packet_peer: 428 + net_dbg_skb_ratelimited("%s: Packet has unallowed src IP (%pISc) from peer %llu (%pISpfsc)\n", 429 + dev->name, skb, peer->internal_id, 430 + &peer->endpoint.addr); 431 + ++dev->stats.rx_errors; 432 + ++dev->stats.rx_frame_errors; 433 + goto packet_processed; 434 + dishonest_packet_type: 435 + net_dbg_ratelimited("%s: Packet is neither ipv4 nor ipv6 from peer %llu (%pISpfsc)\n", 436 + dev->name, peer->internal_id, &peer->endpoint.addr); 437 + ++dev->stats.rx_errors; 438 + ++dev->stats.rx_frame_errors; 439 + goto packet_processed; 440 + dishonest_packet_size: 441 + net_dbg_ratelimited("%s: Packet has incorrect size from peer %llu (%pISpfsc)\n", 442 + dev->name, peer->internal_id, &peer->endpoint.addr); 443 + ++dev->stats.rx_errors; 444 + ++dev->stats.rx_length_errors; 445 + goto packet_processed; 446 + packet_processed: 447 + dev_kfree_skb(skb); 448 + } 449 + 450 + int wg_packet_rx_poll(struct napi_struct *napi, int budget) 451 + { 452 + struct wg_peer *peer = container_of(napi, struct wg_peer, napi); 453 + struct crypt_queue *queue = &peer->rx_queue; 454 + struct noise_keypair *keypair; 455 + struct endpoint endpoint; 456 + enum packet_state state; 457 + struct sk_buff *skb; 458 + int work_done = 0; 459 + bool free; 460 + 461 + if (unlikely(budget <= 0)) 462 + return 0; 463 + 464 + while ((skb = __ptr_ring_peek(&queue->ring)) != NULL && 465 + (state = atomic_read_acquire(&PACKET_CB(skb)->state)) != 466 + PACKET_STATE_UNCRYPTED) { 467 + __ptr_ring_discard_one(&queue->ring); 468 + peer = PACKET_PEER(skb); 469 + keypair = PACKET_CB(skb)->keypair; 470 + free = true; 471 + 472 + if (unlikely(state != PACKET_STATE_CRYPTED)) 473 + goto next; 474 + 475 + if (unlikely(!counter_validate(&keypair->receiving.counter, 476 + PACKET_CB(skb)->nonce))) { 477 + net_dbg_ratelimited("%s: Packet has invalid nonce %llu (max %llu)\n", 478 + peer->device->dev->name, 479 + PACKET_CB(skb)->nonce, 480 + keypair->receiving.counter.receive.counter); 481 + goto next; 482 + } 483 + 484 + if (unlikely(wg_socket_endpoint_from_skb(&endpoint, skb))) 485 + goto next; 486 + 487 + wg_reset_packet(skb); 488 + wg_packet_consume_data_done(peer, skb, &endpoint); 489 + free = false; 490 + 491 + next: 492 + wg_noise_keypair_put(keypair, false); 493 + wg_peer_put(peer); 494 + if (unlikely(free)) 495 + dev_kfree_skb(skb); 496 + 497 + if (++work_done >= budget) 498 + break; 499 + } 500 + 501 + if (work_done < budget) 502 + napi_complete_done(napi, work_done); 503 + 504 + return work_done; 505 + } 506 + 507 + void wg_packet_decrypt_worker(struct work_struct *work) 508 + { 509 + struct crypt_queue *queue = container_of(work, struct multicore_worker, 510 + work)->ptr; 511 + struct sk_buff *skb; 512 + 513 + while ((skb = ptr_ring_consume_bh(&queue->ring)) != NULL) { 514 + enum packet_state state = likely(decrypt_packet(skb, 515 + &PACKET_CB(skb)->keypair->receiving)) ? 516 + PACKET_STATE_CRYPTED : PACKET_STATE_DEAD; 517 + wg_queue_enqueue_per_peer_napi(skb, state); 518 + } 519 + } 520 + 521 + static void wg_packet_consume_data(struct wg_device *wg, struct sk_buff *skb) 522 + { 523 + __le32 idx = ((struct message_data *)skb->data)->key_idx; 524 + struct wg_peer *peer = NULL; 525 + int ret; 526 + 527 + rcu_read_lock_bh(); 528 + PACKET_CB(skb)->keypair = 529 + (struct noise_keypair *)wg_index_hashtable_lookup( 530 + wg->index_hashtable, INDEX_HASHTABLE_KEYPAIR, idx, 531 + &peer); 532 + if (unlikely(!wg_noise_keypair_get(PACKET_CB(skb)->keypair))) 533 + goto err_keypair; 534 + 535 + if (unlikely(READ_ONCE(peer->is_dead))) 536 + goto err; 537 + 538 + ret = wg_queue_enqueue_per_device_and_peer(&wg->decrypt_queue, 539 + &peer->rx_queue, skb, 540 + wg->packet_crypt_wq, 541 + &wg->decrypt_queue.last_cpu); 542 + if (unlikely(ret == -EPIPE)) 543 + wg_queue_enqueue_per_peer_napi(skb, PACKET_STATE_DEAD); 544 + if (likely(!ret || ret == -EPIPE)) { 545 + rcu_read_unlock_bh(); 546 + return; 547 + } 548 + err: 549 + wg_noise_keypair_put(PACKET_CB(skb)->keypair, false); 550 + err_keypair: 551 + rcu_read_unlock_bh(); 552 + wg_peer_put(peer); 553 + dev_kfree_skb(skb); 554 + } 555 + 556 + void wg_packet_receive(struct wg_device *wg, struct sk_buff *skb) 557 + { 558 + if (unlikely(prepare_skb_header(skb, wg) < 0)) 559 + goto err; 560 + switch (SKB_TYPE_LE32(skb)) { 561 + case cpu_to_le32(MESSAGE_HANDSHAKE_INITIATION): 562 + case cpu_to_le32(MESSAGE_HANDSHAKE_RESPONSE): 563 + case cpu_to_le32(MESSAGE_HANDSHAKE_COOKIE): { 564 + int cpu; 565 + 566 + if (skb_queue_len(&wg->incoming_handshakes) > 567 + MAX_QUEUED_INCOMING_HANDSHAKES || 568 + unlikely(!rng_is_initialized())) { 569 + net_dbg_skb_ratelimited("%s: Dropping handshake packet from %pISpfsc\n", 570 + wg->dev->name, skb); 571 + goto err; 572 + } 573 + skb_queue_tail(&wg->incoming_handshakes, skb); 574 + /* Queues up a call to packet_process_queued_handshake_ 575 + * packets(skb): 576 + */ 577 + cpu = wg_cpumask_next_online(&wg->incoming_handshake_cpu); 578 + queue_work_on(cpu, wg->handshake_receive_wq, 579 + &per_cpu_ptr(wg->incoming_handshakes_worker, cpu)->work); 580 + break; 581 + } 582 + case cpu_to_le32(MESSAGE_DATA): 583 + PACKET_CB(skb)->ds = ip_tunnel_get_dsfield(ip_hdr(skb), skb); 584 + wg_packet_consume_data(wg, skb); 585 + break; 586 + default: 587 + net_dbg_skb_ratelimited("%s: Invalid packet from %pISpfsc\n", 588 + wg->dev->name, skb); 589 + goto err; 590 + } 591 + return; 592 + 593 + err: 594 + dev_kfree_skb(skb); 595 + }
+683
drivers/net/wireguard/selftest/allowedips.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + * 5 + * This contains some basic static unit tests for the allowedips data structure. 6 + * It also has two additional modes that are disabled and meant to be used by 7 + * folks directly playing with this file. If you define the macro 8 + * DEBUG_PRINT_TRIE_GRAPHVIZ to be 1, then every time there's a full tree in 9 + * memory, it will be printed out as KERN_DEBUG in a format that can be passed 10 + * to graphviz (the dot command) to visualize it. If you define the macro 11 + * DEBUG_RANDOM_TRIE to be 1, then there will be an extremely costly set of 12 + * randomized tests done against a trivial implementation, which may take 13 + * upwards of a half-hour to complete. There's no set of users who should be 14 + * enabling these, and the only developers that should go anywhere near these 15 + * nobs are the ones who are reading this comment. 16 + */ 17 + 18 + #ifdef DEBUG 19 + 20 + #include <linux/siphash.h> 21 + 22 + static __init void swap_endian_and_apply_cidr(u8 *dst, const u8 *src, u8 bits, 23 + u8 cidr) 24 + { 25 + swap_endian(dst, src, bits); 26 + memset(dst + (cidr + 7) / 8, 0, bits / 8 - (cidr + 7) / 8); 27 + if (cidr) 28 + dst[(cidr + 7) / 8 - 1] &= ~0U << ((8 - (cidr % 8)) % 8); 29 + } 30 + 31 + static __init void print_node(struct allowedips_node *node, u8 bits) 32 + { 33 + char *fmt_connection = KERN_DEBUG "\t\"%p/%d\" -> \"%p/%d\";\n"; 34 + char *fmt_declaration = KERN_DEBUG 35 + "\t\"%p/%d\"[style=%s, color=\"#%06x\"];\n"; 36 + char *style = "dotted"; 37 + u8 ip1[16], ip2[16]; 38 + u32 color = 0; 39 + 40 + if (bits == 32) { 41 + fmt_connection = KERN_DEBUG "\t\"%pI4/%d\" -> \"%pI4/%d\";\n"; 42 + fmt_declaration = KERN_DEBUG 43 + "\t\"%pI4/%d\"[style=%s, color=\"#%06x\"];\n"; 44 + } else if (bits == 128) { 45 + fmt_connection = KERN_DEBUG "\t\"%pI6/%d\" -> \"%pI6/%d\";\n"; 46 + fmt_declaration = KERN_DEBUG 47 + "\t\"%pI6/%d\"[style=%s, color=\"#%06x\"];\n"; 48 + } 49 + if (node->peer) { 50 + hsiphash_key_t key = { { 0 } }; 51 + 52 + memcpy(&key, &node->peer, sizeof(node->peer)); 53 + color = hsiphash_1u32(0xdeadbeef, &key) % 200 << 16 | 54 + hsiphash_1u32(0xbabecafe, &key) % 200 << 8 | 55 + hsiphash_1u32(0xabad1dea, &key) % 200; 56 + style = "bold"; 57 + } 58 + swap_endian_and_apply_cidr(ip1, node->bits, bits, node->cidr); 59 + printk(fmt_declaration, ip1, node->cidr, style, color); 60 + if (node->bit[0]) { 61 + swap_endian_and_apply_cidr(ip2, 62 + rcu_dereference_raw(node->bit[0])->bits, bits, 63 + node->cidr); 64 + printk(fmt_connection, ip1, node->cidr, ip2, 65 + rcu_dereference_raw(node->bit[0])->cidr); 66 + print_node(rcu_dereference_raw(node->bit[0]), bits); 67 + } 68 + if (node->bit[1]) { 69 + swap_endian_and_apply_cidr(ip2, 70 + rcu_dereference_raw(node->bit[1])->bits, 71 + bits, node->cidr); 72 + printk(fmt_connection, ip1, node->cidr, ip2, 73 + rcu_dereference_raw(node->bit[1])->cidr); 74 + print_node(rcu_dereference_raw(node->bit[1]), bits); 75 + } 76 + } 77 + 78 + static __init void print_tree(struct allowedips_node __rcu *top, u8 bits) 79 + { 80 + printk(KERN_DEBUG "digraph trie {\n"); 81 + print_node(rcu_dereference_raw(top), bits); 82 + printk(KERN_DEBUG "}\n"); 83 + } 84 + 85 + enum { 86 + NUM_PEERS = 2000, 87 + NUM_RAND_ROUTES = 400, 88 + NUM_MUTATED_ROUTES = 100, 89 + NUM_QUERIES = NUM_RAND_ROUTES * NUM_MUTATED_ROUTES * 30 90 + }; 91 + 92 + struct horrible_allowedips { 93 + struct hlist_head head; 94 + }; 95 + 96 + struct horrible_allowedips_node { 97 + struct hlist_node table; 98 + union nf_inet_addr ip; 99 + union nf_inet_addr mask; 100 + u8 ip_version; 101 + void *value; 102 + }; 103 + 104 + static __init void horrible_allowedips_init(struct horrible_allowedips *table) 105 + { 106 + INIT_HLIST_HEAD(&table->head); 107 + } 108 + 109 + static __init void horrible_allowedips_free(struct horrible_allowedips *table) 110 + { 111 + struct horrible_allowedips_node *node; 112 + struct hlist_node *h; 113 + 114 + hlist_for_each_entry_safe(node, h, &table->head, table) { 115 + hlist_del(&node->table); 116 + kfree(node); 117 + } 118 + } 119 + 120 + static __init inline union nf_inet_addr horrible_cidr_to_mask(u8 cidr) 121 + { 122 + union nf_inet_addr mask; 123 + 124 + memset(&mask, 0x00, 128 / 8); 125 + memset(&mask, 0xff, cidr / 8); 126 + if (cidr % 32) 127 + mask.all[cidr / 32] = (__force u32)htonl( 128 + (0xFFFFFFFFUL << (32 - (cidr % 32))) & 0xFFFFFFFFUL); 129 + return mask; 130 + } 131 + 132 + static __init inline u8 horrible_mask_to_cidr(union nf_inet_addr subnet) 133 + { 134 + return hweight32(subnet.all[0]) + hweight32(subnet.all[1]) + 135 + hweight32(subnet.all[2]) + hweight32(subnet.all[3]); 136 + } 137 + 138 + static __init inline void 139 + horrible_mask_self(struct horrible_allowedips_node *node) 140 + { 141 + if (node->ip_version == 4) { 142 + node->ip.ip &= node->mask.ip; 143 + } else if (node->ip_version == 6) { 144 + node->ip.ip6[0] &= node->mask.ip6[0]; 145 + node->ip.ip6[1] &= node->mask.ip6[1]; 146 + node->ip.ip6[2] &= node->mask.ip6[2]; 147 + node->ip.ip6[3] &= node->mask.ip6[3]; 148 + } 149 + } 150 + 151 + static __init inline bool 152 + horrible_match_v4(const struct horrible_allowedips_node *node, 153 + struct in_addr *ip) 154 + { 155 + return (ip->s_addr & node->mask.ip) == node->ip.ip; 156 + } 157 + 158 + static __init inline bool 159 + horrible_match_v6(const struct horrible_allowedips_node *node, 160 + struct in6_addr *ip) 161 + { 162 + return (ip->in6_u.u6_addr32[0] & node->mask.ip6[0]) == 163 + node->ip.ip6[0] && 164 + (ip->in6_u.u6_addr32[1] & node->mask.ip6[1]) == 165 + node->ip.ip6[1] && 166 + (ip->in6_u.u6_addr32[2] & node->mask.ip6[2]) == 167 + node->ip.ip6[2] && 168 + (ip->in6_u.u6_addr32[3] & node->mask.ip6[3]) == node->ip.ip6[3]; 169 + } 170 + 171 + static __init void 172 + horrible_insert_ordered(struct horrible_allowedips *table, 173 + struct horrible_allowedips_node *node) 174 + { 175 + struct horrible_allowedips_node *other = NULL, *where = NULL; 176 + u8 my_cidr = horrible_mask_to_cidr(node->mask); 177 + 178 + hlist_for_each_entry(other, &table->head, table) { 179 + if (!memcmp(&other->mask, &node->mask, 180 + sizeof(union nf_inet_addr)) && 181 + !memcmp(&other->ip, &node->ip, 182 + sizeof(union nf_inet_addr)) && 183 + other->ip_version == node->ip_version) { 184 + other->value = node->value; 185 + kfree(node); 186 + return; 187 + } 188 + where = other; 189 + if (horrible_mask_to_cidr(other->mask) <= my_cidr) 190 + break; 191 + } 192 + if (!other && !where) 193 + hlist_add_head(&node->table, &table->head); 194 + else if (!other) 195 + hlist_add_behind(&node->table, &where->table); 196 + else 197 + hlist_add_before(&node->table, &where->table); 198 + } 199 + 200 + static __init int 201 + horrible_allowedips_insert_v4(struct horrible_allowedips *table, 202 + struct in_addr *ip, u8 cidr, void *value) 203 + { 204 + struct horrible_allowedips_node *node = kzalloc(sizeof(*node), 205 + GFP_KERNEL); 206 + 207 + if (unlikely(!node)) 208 + return -ENOMEM; 209 + node->ip.in = *ip; 210 + node->mask = horrible_cidr_to_mask(cidr); 211 + node->ip_version = 4; 212 + node->value = value; 213 + horrible_mask_self(node); 214 + horrible_insert_ordered(table, node); 215 + return 0; 216 + } 217 + 218 + static __init int 219 + horrible_allowedips_insert_v6(struct horrible_allowedips *table, 220 + struct in6_addr *ip, u8 cidr, void *value) 221 + { 222 + struct horrible_allowedips_node *node = kzalloc(sizeof(*node), 223 + GFP_KERNEL); 224 + 225 + if (unlikely(!node)) 226 + return -ENOMEM; 227 + node->ip.in6 = *ip; 228 + node->mask = horrible_cidr_to_mask(cidr); 229 + node->ip_version = 6; 230 + node->value = value; 231 + horrible_mask_self(node); 232 + horrible_insert_ordered(table, node); 233 + return 0; 234 + } 235 + 236 + static __init void * 237 + horrible_allowedips_lookup_v4(struct horrible_allowedips *table, 238 + struct in_addr *ip) 239 + { 240 + struct horrible_allowedips_node *node; 241 + void *ret = NULL; 242 + 243 + hlist_for_each_entry(node, &table->head, table) { 244 + if (node->ip_version != 4) 245 + continue; 246 + if (horrible_match_v4(node, ip)) { 247 + ret = node->value; 248 + break; 249 + } 250 + } 251 + return ret; 252 + } 253 + 254 + static __init void * 255 + horrible_allowedips_lookup_v6(struct horrible_allowedips *table, 256 + struct in6_addr *ip) 257 + { 258 + struct horrible_allowedips_node *node; 259 + void *ret = NULL; 260 + 261 + hlist_for_each_entry(node, &table->head, table) { 262 + if (node->ip_version != 6) 263 + continue; 264 + if (horrible_match_v6(node, ip)) { 265 + ret = node->value; 266 + break; 267 + } 268 + } 269 + return ret; 270 + } 271 + 272 + static __init bool randomized_test(void) 273 + { 274 + unsigned int i, j, k, mutate_amount, cidr; 275 + u8 ip[16], mutate_mask[16], mutated[16]; 276 + struct wg_peer **peers, *peer; 277 + struct horrible_allowedips h; 278 + DEFINE_MUTEX(mutex); 279 + struct allowedips t; 280 + bool ret = false; 281 + 282 + mutex_init(&mutex); 283 + 284 + wg_allowedips_init(&t); 285 + horrible_allowedips_init(&h); 286 + 287 + peers = kcalloc(NUM_PEERS, sizeof(*peers), GFP_KERNEL); 288 + if (unlikely(!peers)) { 289 + pr_err("allowedips random self-test malloc: FAIL\n"); 290 + goto free; 291 + } 292 + for (i = 0; i < NUM_PEERS; ++i) { 293 + peers[i] = kzalloc(sizeof(*peers[i]), GFP_KERNEL); 294 + if (unlikely(!peers[i])) { 295 + pr_err("allowedips random self-test malloc: FAIL\n"); 296 + goto free; 297 + } 298 + kref_init(&peers[i]->refcount); 299 + } 300 + 301 + mutex_lock(&mutex); 302 + 303 + for (i = 0; i < NUM_RAND_ROUTES; ++i) { 304 + prandom_bytes(ip, 4); 305 + cidr = prandom_u32_max(32) + 1; 306 + peer = peers[prandom_u32_max(NUM_PEERS)]; 307 + if (wg_allowedips_insert_v4(&t, (struct in_addr *)ip, cidr, 308 + peer, &mutex) < 0) { 309 + pr_err("allowedips random self-test malloc: FAIL\n"); 310 + goto free_locked; 311 + } 312 + if (horrible_allowedips_insert_v4(&h, (struct in_addr *)ip, 313 + cidr, peer) < 0) { 314 + pr_err("allowedips random self-test malloc: FAIL\n"); 315 + goto free_locked; 316 + } 317 + for (j = 0; j < NUM_MUTATED_ROUTES; ++j) { 318 + memcpy(mutated, ip, 4); 319 + prandom_bytes(mutate_mask, 4); 320 + mutate_amount = prandom_u32_max(32); 321 + for (k = 0; k < mutate_amount / 8; ++k) 322 + mutate_mask[k] = 0xff; 323 + mutate_mask[k] = 0xff 324 + << ((8 - (mutate_amount % 8)) % 8); 325 + for (; k < 4; ++k) 326 + mutate_mask[k] = 0; 327 + for (k = 0; k < 4; ++k) 328 + mutated[k] = (mutated[k] & mutate_mask[k]) | 329 + (~mutate_mask[k] & 330 + prandom_u32_max(256)); 331 + cidr = prandom_u32_max(32) + 1; 332 + peer = peers[prandom_u32_max(NUM_PEERS)]; 333 + if (wg_allowedips_insert_v4(&t, 334 + (struct in_addr *)mutated, 335 + cidr, peer, &mutex) < 0) { 336 + pr_err("allowedips random malloc: FAIL\n"); 337 + goto free_locked; 338 + } 339 + if (horrible_allowedips_insert_v4(&h, 340 + (struct in_addr *)mutated, cidr, peer)) { 341 + pr_err("allowedips random self-test malloc: FAIL\n"); 342 + goto free_locked; 343 + } 344 + } 345 + } 346 + 347 + for (i = 0; i < NUM_RAND_ROUTES; ++i) { 348 + prandom_bytes(ip, 16); 349 + cidr = prandom_u32_max(128) + 1; 350 + peer = peers[prandom_u32_max(NUM_PEERS)]; 351 + if (wg_allowedips_insert_v6(&t, (struct in6_addr *)ip, cidr, 352 + peer, &mutex) < 0) { 353 + pr_err("allowedips random self-test malloc: FAIL\n"); 354 + goto free_locked; 355 + } 356 + if (horrible_allowedips_insert_v6(&h, (struct in6_addr *)ip, 357 + cidr, peer) < 0) { 358 + pr_err("allowedips random self-test malloc: FAIL\n"); 359 + goto free_locked; 360 + } 361 + for (j = 0; j < NUM_MUTATED_ROUTES; ++j) { 362 + memcpy(mutated, ip, 16); 363 + prandom_bytes(mutate_mask, 16); 364 + mutate_amount = prandom_u32_max(128); 365 + for (k = 0; k < mutate_amount / 8; ++k) 366 + mutate_mask[k] = 0xff; 367 + mutate_mask[k] = 0xff 368 + << ((8 - (mutate_amount % 8)) % 8); 369 + for (; k < 4; ++k) 370 + mutate_mask[k] = 0; 371 + for (k = 0; k < 4; ++k) 372 + mutated[k] = (mutated[k] & mutate_mask[k]) | 373 + (~mutate_mask[k] & 374 + prandom_u32_max(256)); 375 + cidr = prandom_u32_max(128) + 1; 376 + peer = peers[prandom_u32_max(NUM_PEERS)]; 377 + if (wg_allowedips_insert_v6(&t, 378 + (struct in6_addr *)mutated, 379 + cidr, peer, &mutex) < 0) { 380 + pr_err("allowedips random self-test malloc: FAIL\n"); 381 + goto free_locked; 382 + } 383 + if (horrible_allowedips_insert_v6( 384 + &h, (struct in6_addr *)mutated, cidr, 385 + peer)) { 386 + pr_err("allowedips random self-test malloc: FAIL\n"); 387 + goto free_locked; 388 + } 389 + } 390 + } 391 + 392 + mutex_unlock(&mutex); 393 + 394 + if (IS_ENABLED(DEBUG_PRINT_TRIE_GRAPHVIZ)) { 395 + print_tree(t.root4, 32); 396 + print_tree(t.root6, 128); 397 + } 398 + 399 + for (i = 0; i < NUM_QUERIES; ++i) { 400 + prandom_bytes(ip, 4); 401 + if (lookup(t.root4, 32, ip) != 402 + horrible_allowedips_lookup_v4(&h, (struct in_addr *)ip)) { 403 + pr_err("allowedips random self-test: FAIL\n"); 404 + goto free; 405 + } 406 + } 407 + 408 + for (i = 0; i < NUM_QUERIES; ++i) { 409 + prandom_bytes(ip, 16); 410 + if (lookup(t.root6, 128, ip) != 411 + horrible_allowedips_lookup_v6(&h, (struct in6_addr *)ip)) { 412 + pr_err("allowedips random self-test: FAIL\n"); 413 + goto free; 414 + } 415 + } 416 + ret = true; 417 + 418 + free: 419 + mutex_lock(&mutex); 420 + free_locked: 421 + wg_allowedips_free(&t, &mutex); 422 + mutex_unlock(&mutex); 423 + horrible_allowedips_free(&h); 424 + if (peers) { 425 + for (i = 0; i < NUM_PEERS; ++i) 426 + kfree(peers[i]); 427 + } 428 + kfree(peers); 429 + return ret; 430 + } 431 + 432 + static __init inline struct in_addr *ip4(u8 a, u8 b, u8 c, u8 d) 433 + { 434 + static struct in_addr ip; 435 + u8 *split = (u8 *)&ip; 436 + 437 + split[0] = a; 438 + split[1] = b; 439 + split[2] = c; 440 + split[3] = d; 441 + return &ip; 442 + } 443 + 444 + static __init inline struct in6_addr *ip6(u32 a, u32 b, u32 c, u32 d) 445 + { 446 + static struct in6_addr ip; 447 + __be32 *split = (__be32 *)&ip; 448 + 449 + split[0] = cpu_to_be32(a); 450 + split[1] = cpu_to_be32(b); 451 + split[2] = cpu_to_be32(c); 452 + split[3] = cpu_to_be32(d); 453 + return &ip; 454 + } 455 + 456 + static __init struct wg_peer *init_peer(void) 457 + { 458 + struct wg_peer *peer = kzalloc(sizeof(*peer), GFP_KERNEL); 459 + 460 + if (!peer) 461 + return NULL; 462 + kref_init(&peer->refcount); 463 + INIT_LIST_HEAD(&peer->allowedips_list); 464 + return peer; 465 + } 466 + 467 + #define insert(version, mem, ipa, ipb, ipc, ipd, cidr) \ 468 + wg_allowedips_insert_v##version(&t, ip##version(ipa, ipb, ipc, ipd), \ 469 + cidr, mem, &mutex) 470 + 471 + #define maybe_fail() do { \ 472 + ++i; \ 473 + if (!_s) { \ 474 + pr_info("allowedips self-test %zu: FAIL\n", i); \ 475 + success = false; \ 476 + } \ 477 + } while (0) 478 + 479 + #define test(version, mem, ipa, ipb, ipc, ipd) do { \ 480 + bool _s = lookup(t.root##version, (version) == 4 ? 32 : 128, \ 481 + ip##version(ipa, ipb, ipc, ipd)) == (mem); \ 482 + maybe_fail(); \ 483 + } while (0) 484 + 485 + #define test_negative(version, mem, ipa, ipb, ipc, ipd) do { \ 486 + bool _s = lookup(t.root##version, (version) == 4 ? 32 : 128, \ 487 + ip##version(ipa, ipb, ipc, ipd)) != (mem); \ 488 + maybe_fail(); \ 489 + } while (0) 490 + 491 + #define test_boolean(cond) do { \ 492 + bool _s = (cond); \ 493 + maybe_fail(); \ 494 + } while (0) 495 + 496 + bool __init wg_allowedips_selftest(void) 497 + { 498 + bool found_a = false, found_b = false, found_c = false, found_d = false, 499 + found_e = false, found_other = false; 500 + struct wg_peer *a = init_peer(), *b = init_peer(), *c = init_peer(), 501 + *d = init_peer(), *e = init_peer(), *f = init_peer(), 502 + *g = init_peer(), *h = init_peer(); 503 + struct allowedips_node *iter_node; 504 + bool success = false; 505 + struct allowedips t; 506 + DEFINE_MUTEX(mutex); 507 + struct in6_addr ip; 508 + size_t i = 0, count = 0; 509 + __be64 part; 510 + 511 + mutex_init(&mutex); 512 + mutex_lock(&mutex); 513 + wg_allowedips_init(&t); 514 + 515 + if (!a || !b || !c || !d || !e || !f || !g || !h) { 516 + pr_err("allowedips self-test malloc: FAIL\n"); 517 + goto free; 518 + } 519 + 520 + insert(4, a, 192, 168, 4, 0, 24); 521 + insert(4, b, 192, 168, 4, 4, 32); 522 + insert(4, c, 192, 168, 0, 0, 16); 523 + insert(4, d, 192, 95, 5, 64, 27); 524 + /* replaces previous entry, and maskself is required */ 525 + insert(4, c, 192, 95, 5, 65, 27); 526 + insert(6, d, 0x26075300, 0x60006b00, 0, 0xc05f0543, 128); 527 + insert(6, c, 0x26075300, 0x60006b00, 0, 0, 64); 528 + insert(4, e, 0, 0, 0, 0, 0); 529 + insert(6, e, 0, 0, 0, 0, 0); 530 + /* replaces previous entry */ 531 + insert(6, f, 0, 0, 0, 0, 0); 532 + insert(6, g, 0x24046800, 0, 0, 0, 32); 533 + /* maskself is required */ 534 + insert(6, h, 0x24046800, 0x40040800, 0xdeadbeef, 0xdeadbeef, 64); 535 + insert(6, a, 0x24046800, 0x40040800, 0xdeadbeef, 0xdeadbeef, 128); 536 + insert(6, c, 0x24446800, 0x40e40800, 0xdeaebeef, 0xdefbeef, 128); 537 + insert(6, b, 0x24446800, 0xf0e40800, 0xeeaebeef, 0, 98); 538 + insert(4, g, 64, 15, 112, 0, 20); 539 + /* maskself is required */ 540 + insert(4, h, 64, 15, 123, 211, 25); 541 + insert(4, a, 10, 0, 0, 0, 25); 542 + insert(4, b, 10, 0, 0, 128, 25); 543 + insert(4, a, 10, 1, 0, 0, 30); 544 + insert(4, b, 10, 1, 0, 4, 30); 545 + insert(4, c, 10, 1, 0, 8, 29); 546 + insert(4, d, 10, 1, 0, 16, 29); 547 + 548 + if (IS_ENABLED(DEBUG_PRINT_TRIE_GRAPHVIZ)) { 549 + print_tree(t.root4, 32); 550 + print_tree(t.root6, 128); 551 + } 552 + 553 + success = true; 554 + 555 + test(4, a, 192, 168, 4, 20); 556 + test(4, a, 192, 168, 4, 0); 557 + test(4, b, 192, 168, 4, 4); 558 + test(4, c, 192, 168, 200, 182); 559 + test(4, c, 192, 95, 5, 68); 560 + test(4, e, 192, 95, 5, 96); 561 + test(6, d, 0x26075300, 0x60006b00, 0, 0xc05f0543); 562 + test(6, c, 0x26075300, 0x60006b00, 0, 0xc02e01ee); 563 + test(6, f, 0x26075300, 0x60006b01, 0, 0); 564 + test(6, g, 0x24046800, 0x40040806, 0, 0x1006); 565 + test(6, g, 0x24046800, 0x40040806, 0x1234, 0x5678); 566 + test(6, f, 0x240467ff, 0x40040806, 0x1234, 0x5678); 567 + test(6, f, 0x24046801, 0x40040806, 0x1234, 0x5678); 568 + test(6, h, 0x24046800, 0x40040800, 0x1234, 0x5678); 569 + test(6, h, 0x24046800, 0x40040800, 0, 0); 570 + test(6, h, 0x24046800, 0x40040800, 0x10101010, 0x10101010); 571 + test(6, a, 0x24046800, 0x40040800, 0xdeadbeef, 0xdeadbeef); 572 + test(4, g, 64, 15, 116, 26); 573 + test(4, g, 64, 15, 127, 3); 574 + test(4, g, 64, 15, 123, 1); 575 + test(4, h, 64, 15, 123, 128); 576 + test(4, h, 64, 15, 123, 129); 577 + test(4, a, 10, 0, 0, 52); 578 + test(4, b, 10, 0, 0, 220); 579 + test(4, a, 10, 1, 0, 2); 580 + test(4, b, 10, 1, 0, 6); 581 + test(4, c, 10, 1, 0, 10); 582 + test(4, d, 10, 1, 0, 20); 583 + 584 + insert(4, a, 1, 0, 0, 0, 32); 585 + insert(4, a, 64, 0, 0, 0, 32); 586 + insert(4, a, 128, 0, 0, 0, 32); 587 + insert(4, a, 192, 0, 0, 0, 32); 588 + insert(4, a, 255, 0, 0, 0, 32); 589 + wg_allowedips_remove_by_peer(&t, a, &mutex); 590 + test_negative(4, a, 1, 0, 0, 0); 591 + test_negative(4, a, 64, 0, 0, 0); 592 + test_negative(4, a, 128, 0, 0, 0); 593 + test_negative(4, a, 192, 0, 0, 0); 594 + test_negative(4, a, 255, 0, 0, 0); 595 + 596 + wg_allowedips_free(&t, &mutex); 597 + wg_allowedips_init(&t); 598 + insert(4, a, 192, 168, 0, 0, 16); 599 + insert(4, a, 192, 168, 0, 0, 24); 600 + wg_allowedips_remove_by_peer(&t, a, &mutex); 601 + test_negative(4, a, 192, 168, 0, 1); 602 + 603 + /* These will hit the WARN_ON(len >= 128) in free_node if something 604 + * goes wrong. 605 + */ 606 + for (i = 0; i < 128; ++i) { 607 + part = cpu_to_be64(~(1LLU << (i % 64))); 608 + memset(&ip, 0xff, 16); 609 + memcpy((u8 *)&ip + (i < 64) * 8, &part, 8); 610 + wg_allowedips_insert_v6(&t, &ip, 128, a, &mutex); 611 + } 612 + 613 + wg_allowedips_free(&t, &mutex); 614 + 615 + wg_allowedips_init(&t); 616 + insert(4, a, 192, 95, 5, 93, 27); 617 + insert(6, a, 0x26075300, 0x60006b00, 0, 0xc05f0543, 128); 618 + insert(4, a, 10, 1, 0, 20, 29); 619 + insert(6, a, 0x26075300, 0x6d8a6bf8, 0xdab1f1df, 0xc05f1523, 83); 620 + insert(6, a, 0x26075300, 0x6d8a6bf8, 0xdab1f1df, 0xc05f1523, 21); 621 + list_for_each_entry(iter_node, &a->allowedips_list, peer_list) { 622 + u8 cidr, ip[16] __aligned(__alignof(u64)); 623 + int family = wg_allowedips_read_node(iter_node, ip, &cidr); 624 + 625 + count++; 626 + 627 + if (cidr == 27 && family == AF_INET && 628 + !memcmp(ip, ip4(192, 95, 5, 64), sizeof(struct in_addr))) 629 + found_a = true; 630 + else if (cidr == 128 && family == AF_INET6 && 631 + !memcmp(ip, ip6(0x26075300, 0x60006b00, 0, 0xc05f0543), 632 + sizeof(struct in6_addr))) 633 + found_b = true; 634 + else if (cidr == 29 && family == AF_INET && 635 + !memcmp(ip, ip4(10, 1, 0, 16), sizeof(struct in_addr))) 636 + found_c = true; 637 + else if (cidr == 83 && family == AF_INET6 && 638 + !memcmp(ip, ip6(0x26075300, 0x6d8a6bf8, 0xdab1e000, 0), 639 + sizeof(struct in6_addr))) 640 + found_d = true; 641 + else if (cidr == 21 && family == AF_INET6 && 642 + !memcmp(ip, ip6(0x26075000, 0, 0, 0), 643 + sizeof(struct in6_addr))) 644 + found_e = true; 645 + else 646 + found_other = true; 647 + } 648 + test_boolean(count == 5); 649 + test_boolean(found_a); 650 + test_boolean(found_b); 651 + test_boolean(found_c); 652 + test_boolean(found_d); 653 + test_boolean(found_e); 654 + test_boolean(!found_other); 655 + 656 + if (IS_ENABLED(DEBUG_RANDOM_TRIE) && success) 657 + success = randomized_test(); 658 + 659 + if (success) 660 + pr_info("allowedips self-tests: pass\n"); 661 + 662 + free: 663 + wg_allowedips_free(&t, &mutex); 664 + kfree(a); 665 + kfree(b); 666 + kfree(c); 667 + kfree(d); 668 + kfree(e); 669 + kfree(f); 670 + kfree(g); 671 + kfree(h); 672 + mutex_unlock(&mutex); 673 + 674 + return success; 675 + } 676 + 677 + #undef test_negative 678 + #undef test 679 + #undef remove 680 + #undef insert 681 + #undef init_peer 682 + 683 + #endif
+104
drivers/net/wireguard/selftest/counter.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifdef DEBUG 7 + bool __init wg_packet_counter_selftest(void) 8 + { 9 + unsigned int test_num = 0, i; 10 + union noise_counter counter; 11 + bool success = true; 12 + 13 + #define T_INIT do { \ 14 + memset(&counter, 0, sizeof(union noise_counter)); \ 15 + spin_lock_init(&counter.receive.lock); \ 16 + } while (0) 17 + #define T_LIM (COUNTER_WINDOW_SIZE + 1) 18 + #define T(n, v) do { \ 19 + ++test_num; \ 20 + if (counter_validate(&counter, n) != (v)) { \ 21 + pr_err("nonce counter self-test %u: FAIL\n", \ 22 + test_num); \ 23 + success = false; \ 24 + } \ 25 + } while (0) 26 + 27 + T_INIT; 28 + /* 1 */ T(0, true); 29 + /* 2 */ T(1, true); 30 + /* 3 */ T(1, false); 31 + /* 4 */ T(9, true); 32 + /* 5 */ T(8, true); 33 + /* 6 */ T(7, true); 34 + /* 7 */ T(7, false); 35 + /* 8 */ T(T_LIM, true); 36 + /* 9 */ T(T_LIM - 1, true); 37 + /* 10 */ T(T_LIM - 1, false); 38 + /* 11 */ T(T_LIM - 2, true); 39 + /* 12 */ T(2, true); 40 + /* 13 */ T(2, false); 41 + /* 14 */ T(T_LIM + 16, true); 42 + /* 15 */ T(3, false); 43 + /* 16 */ T(T_LIM + 16, false); 44 + /* 17 */ T(T_LIM * 4, true); 45 + /* 18 */ T(T_LIM * 4 - (T_LIM - 1), true); 46 + /* 19 */ T(10, false); 47 + /* 20 */ T(T_LIM * 4 - T_LIM, false); 48 + /* 21 */ T(T_LIM * 4 - (T_LIM + 1), false); 49 + /* 22 */ T(T_LIM * 4 - (T_LIM - 2), true); 50 + /* 23 */ T(T_LIM * 4 + 1 - T_LIM, false); 51 + /* 24 */ T(0, false); 52 + /* 25 */ T(REJECT_AFTER_MESSAGES, false); 53 + /* 26 */ T(REJECT_AFTER_MESSAGES - 1, true); 54 + /* 27 */ T(REJECT_AFTER_MESSAGES, false); 55 + /* 28 */ T(REJECT_AFTER_MESSAGES - 1, false); 56 + /* 29 */ T(REJECT_AFTER_MESSAGES - 2, true); 57 + /* 30 */ T(REJECT_AFTER_MESSAGES + 1, false); 58 + /* 31 */ T(REJECT_AFTER_MESSAGES + 2, false); 59 + /* 32 */ T(REJECT_AFTER_MESSAGES - 2, false); 60 + /* 33 */ T(REJECT_AFTER_MESSAGES - 3, true); 61 + /* 34 */ T(0, false); 62 + 63 + T_INIT; 64 + for (i = 1; i <= COUNTER_WINDOW_SIZE; ++i) 65 + T(i, true); 66 + T(0, true); 67 + T(0, false); 68 + 69 + T_INIT; 70 + for (i = 2; i <= COUNTER_WINDOW_SIZE + 1; ++i) 71 + T(i, true); 72 + T(1, true); 73 + T(0, false); 74 + 75 + T_INIT; 76 + for (i = COUNTER_WINDOW_SIZE + 1; i-- > 0;) 77 + T(i, true); 78 + 79 + T_INIT; 80 + for (i = COUNTER_WINDOW_SIZE + 2; i-- > 1;) 81 + T(i, true); 82 + T(0, false); 83 + 84 + T_INIT; 85 + for (i = COUNTER_WINDOW_SIZE + 1; i-- > 1;) 86 + T(i, true); 87 + T(COUNTER_WINDOW_SIZE + 1, true); 88 + T(0, false); 89 + 90 + T_INIT; 91 + for (i = COUNTER_WINDOW_SIZE + 1; i-- > 1;) 92 + T(i, true); 93 + T(0, true); 94 + T(COUNTER_WINDOW_SIZE + 1, true); 95 + 96 + #undef T 97 + #undef T_LIM 98 + #undef T_INIT 99 + 100 + if (success) 101 + pr_info("nonce counter self-tests: pass\n"); 102 + return success; 103 + } 104 + #endif
+226
drivers/net/wireguard/selftest/ratelimiter.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifdef DEBUG 7 + 8 + #include <linux/jiffies.h> 9 + 10 + static const struct { 11 + bool result; 12 + unsigned int msec_to_sleep_before; 13 + } expected_results[] __initconst = { 14 + [0 ... PACKETS_BURSTABLE - 1] = { true, 0 }, 15 + [PACKETS_BURSTABLE] = { false, 0 }, 16 + [PACKETS_BURSTABLE + 1] = { true, MSEC_PER_SEC / PACKETS_PER_SECOND }, 17 + [PACKETS_BURSTABLE + 2] = { false, 0 }, 18 + [PACKETS_BURSTABLE + 3] = { true, (MSEC_PER_SEC / PACKETS_PER_SECOND) * 2 }, 19 + [PACKETS_BURSTABLE + 4] = { true, 0 }, 20 + [PACKETS_BURSTABLE + 5] = { false, 0 } 21 + }; 22 + 23 + static __init unsigned int maximum_jiffies_at_index(int index) 24 + { 25 + unsigned int total_msecs = 2 * MSEC_PER_SEC / PACKETS_PER_SECOND / 3; 26 + int i; 27 + 28 + for (i = 0; i <= index; ++i) 29 + total_msecs += expected_results[i].msec_to_sleep_before; 30 + return msecs_to_jiffies(total_msecs); 31 + } 32 + 33 + static __init int timings_test(struct sk_buff *skb4, struct iphdr *hdr4, 34 + struct sk_buff *skb6, struct ipv6hdr *hdr6, 35 + int *test) 36 + { 37 + unsigned long loop_start_time; 38 + int i; 39 + 40 + wg_ratelimiter_gc_entries(NULL); 41 + rcu_barrier(); 42 + loop_start_time = jiffies; 43 + 44 + for (i = 0; i < ARRAY_SIZE(expected_results); ++i) { 45 + if (expected_results[i].msec_to_sleep_before) 46 + msleep(expected_results[i].msec_to_sleep_before); 47 + 48 + if (time_is_before_jiffies(loop_start_time + 49 + maximum_jiffies_at_index(i))) 50 + return -ETIMEDOUT; 51 + if (wg_ratelimiter_allow(skb4, &init_net) != 52 + expected_results[i].result) 53 + return -EXFULL; 54 + ++(*test); 55 + 56 + hdr4->saddr = htonl(ntohl(hdr4->saddr) + i + 1); 57 + if (time_is_before_jiffies(loop_start_time + 58 + maximum_jiffies_at_index(i))) 59 + return -ETIMEDOUT; 60 + if (!wg_ratelimiter_allow(skb4, &init_net)) 61 + return -EXFULL; 62 + ++(*test); 63 + 64 + hdr4->saddr = htonl(ntohl(hdr4->saddr) - i - 1); 65 + 66 + #if IS_ENABLED(CONFIG_IPV6) 67 + hdr6->saddr.in6_u.u6_addr32[2] = htonl(i); 68 + hdr6->saddr.in6_u.u6_addr32[3] = htonl(i); 69 + if (time_is_before_jiffies(loop_start_time + 70 + maximum_jiffies_at_index(i))) 71 + return -ETIMEDOUT; 72 + if (wg_ratelimiter_allow(skb6, &init_net) != 73 + expected_results[i].result) 74 + return -EXFULL; 75 + ++(*test); 76 + 77 + hdr6->saddr.in6_u.u6_addr32[0] = 78 + htonl(ntohl(hdr6->saddr.in6_u.u6_addr32[0]) + i + 1); 79 + if (time_is_before_jiffies(loop_start_time + 80 + maximum_jiffies_at_index(i))) 81 + return -ETIMEDOUT; 82 + if (!wg_ratelimiter_allow(skb6, &init_net)) 83 + return -EXFULL; 84 + ++(*test); 85 + 86 + hdr6->saddr.in6_u.u6_addr32[0] = 87 + htonl(ntohl(hdr6->saddr.in6_u.u6_addr32[0]) - i - 1); 88 + 89 + if (time_is_before_jiffies(loop_start_time + 90 + maximum_jiffies_at_index(i))) 91 + return -ETIMEDOUT; 92 + #endif 93 + } 94 + return 0; 95 + } 96 + 97 + static __init int capacity_test(struct sk_buff *skb4, struct iphdr *hdr4, 98 + int *test) 99 + { 100 + int i; 101 + 102 + wg_ratelimiter_gc_entries(NULL); 103 + rcu_barrier(); 104 + 105 + if (atomic_read(&total_entries)) 106 + return -EXFULL; 107 + ++(*test); 108 + 109 + for (i = 0; i <= max_entries; ++i) { 110 + hdr4->saddr = htonl(i); 111 + if (wg_ratelimiter_allow(skb4, &init_net) != (i != max_entries)) 112 + return -EXFULL; 113 + ++(*test); 114 + } 115 + return 0; 116 + } 117 + 118 + bool __init wg_ratelimiter_selftest(void) 119 + { 120 + enum { TRIALS_BEFORE_GIVING_UP = 5000 }; 121 + bool success = false; 122 + int test = 0, trials; 123 + struct sk_buff *skb4, *skb6; 124 + struct iphdr *hdr4; 125 + struct ipv6hdr *hdr6; 126 + 127 + if (IS_ENABLED(CONFIG_KASAN) || IS_ENABLED(CONFIG_UBSAN)) 128 + return true; 129 + 130 + BUILD_BUG_ON(MSEC_PER_SEC % PACKETS_PER_SECOND != 0); 131 + 132 + if (wg_ratelimiter_init()) 133 + goto out; 134 + ++test; 135 + if (wg_ratelimiter_init()) { 136 + wg_ratelimiter_uninit(); 137 + goto out; 138 + } 139 + ++test; 140 + if (wg_ratelimiter_init()) { 141 + wg_ratelimiter_uninit(); 142 + wg_ratelimiter_uninit(); 143 + goto out; 144 + } 145 + ++test; 146 + 147 + skb4 = alloc_skb(sizeof(struct iphdr), GFP_KERNEL); 148 + if (unlikely(!skb4)) 149 + goto err_nofree; 150 + skb4->protocol = htons(ETH_P_IP); 151 + hdr4 = (struct iphdr *)skb_put(skb4, sizeof(*hdr4)); 152 + hdr4->saddr = htonl(8182); 153 + skb_reset_network_header(skb4); 154 + ++test; 155 + 156 + #if IS_ENABLED(CONFIG_IPV6) 157 + skb6 = alloc_skb(sizeof(struct ipv6hdr), GFP_KERNEL); 158 + if (unlikely(!skb6)) { 159 + kfree_skb(skb4); 160 + goto err_nofree; 161 + } 162 + skb6->protocol = htons(ETH_P_IPV6); 163 + hdr6 = (struct ipv6hdr *)skb_put(skb6, sizeof(*hdr6)); 164 + hdr6->saddr.in6_u.u6_addr32[0] = htonl(1212); 165 + hdr6->saddr.in6_u.u6_addr32[1] = htonl(289188); 166 + skb_reset_network_header(skb6); 167 + ++test; 168 + #endif 169 + 170 + for (trials = TRIALS_BEFORE_GIVING_UP;;) { 171 + int test_count = 0, ret; 172 + 173 + ret = timings_test(skb4, hdr4, skb6, hdr6, &test_count); 174 + if (ret == -ETIMEDOUT) { 175 + if (!trials--) { 176 + test += test_count; 177 + goto err; 178 + } 179 + msleep(500); 180 + continue; 181 + } else if (ret < 0) { 182 + test += test_count; 183 + goto err; 184 + } else { 185 + test += test_count; 186 + break; 187 + } 188 + } 189 + 190 + for (trials = TRIALS_BEFORE_GIVING_UP;;) { 191 + int test_count = 0; 192 + 193 + if (capacity_test(skb4, hdr4, &test_count) < 0) { 194 + if (!trials--) { 195 + test += test_count; 196 + goto err; 197 + } 198 + msleep(50); 199 + continue; 200 + } 201 + test += test_count; 202 + break; 203 + } 204 + 205 + success = true; 206 + 207 + err: 208 + kfree_skb(skb4); 209 + #if IS_ENABLED(CONFIG_IPV6) 210 + kfree_skb(skb6); 211 + #endif 212 + err_nofree: 213 + wg_ratelimiter_uninit(); 214 + wg_ratelimiter_uninit(); 215 + wg_ratelimiter_uninit(); 216 + /* Uninit one extra time to check underflow detection. */ 217 + wg_ratelimiter_uninit(); 218 + out: 219 + if (success) 220 + pr_info("ratelimiter self-tests: pass\n"); 221 + else 222 + pr_err("ratelimiter self-test %d: FAIL\n", test); 223 + 224 + return success; 225 + } 226 + #endif
+413
drivers/net/wireguard/send.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "queueing.h" 7 + #include "timers.h" 8 + #include "device.h" 9 + #include "peer.h" 10 + #include "socket.h" 11 + #include "messages.h" 12 + #include "cookie.h" 13 + 14 + #include <linux/uio.h> 15 + #include <linux/inetdevice.h> 16 + #include <linux/socket.h> 17 + #include <net/ip_tunnels.h> 18 + #include <net/udp.h> 19 + #include <net/sock.h> 20 + 21 + static void wg_packet_send_handshake_initiation(struct wg_peer *peer) 22 + { 23 + struct message_handshake_initiation packet; 24 + 25 + if (!wg_birthdate_has_expired(atomic64_read(&peer->last_sent_handshake), 26 + REKEY_TIMEOUT)) 27 + return; /* This function is rate limited. */ 28 + 29 + atomic64_set(&peer->last_sent_handshake, ktime_get_coarse_boottime_ns()); 30 + net_dbg_ratelimited("%s: Sending handshake initiation to peer %llu (%pISpfsc)\n", 31 + peer->device->dev->name, peer->internal_id, 32 + &peer->endpoint.addr); 33 + 34 + if (wg_noise_handshake_create_initiation(&packet, &peer->handshake)) { 35 + wg_cookie_add_mac_to_packet(&packet, sizeof(packet), peer); 36 + wg_timers_any_authenticated_packet_traversal(peer); 37 + wg_timers_any_authenticated_packet_sent(peer); 38 + atomic64_set(&peer->last_sent_handshake, 39 + ktime_get_coarse_boottime_ns()); 40 + wg_socket_send_buffer_to_peer(peer, &packet, sizeof(packet), 41 + HANDSHAKE_DSCP); 42 + wg_timers_handshake_initiated(peer); 43 + } 44 + } 45 + 46 + void wg_packet_handshake_send_worker(struct work_struct *work) 47 + { 48 + struct wg_peer *peer = container_of(work, struct wg_peer, 49 + transmit_handshake_work); 50 + 51 + wg_packet_send_handshake_initiation(peer); 52 + wg_peer_put(peer); 53 + } 54 + 55 + void wg_packet_send_queued_handshake_initiation(struct wg_peer *peer, 56 + bool is_retry) 57 + { 58 + if (!is_retry) 59 + peer->timer_handshake_attempts = 0; 60 + 61 + rcu_read_lock_bh(); 62 + /* We check last_sent_handshake here in addition to the actual function 63 + * we're queueing up, so that we don't queue things if not strictly 64 + * necessary: 65 + */ 66 + if (!wg_birthdate_has_expired(atomic64_read(&peer->last_sent_handshake), 67 + REKEY_TIMEOUT) || 68 + unlikely(READ_ONCE(peer->is_dead))) 69 + goto out; 70 + 71 + wg_peer_get(peer); 72 + /* Queues up calling packet_send_queued_handshakes(peer), where we do a 73 + * peer_put(peer) after: 74 + */ 75 + if (!queue_work(peer->device->handshake_send_wq, 76 + &peer->transmit_handshake_work)) 77 + /* If the work was already queued, we want to drop the 78 + * extra reference: 79 + */ 80 + wg_peer_put(peer); 81 + out: 82 + rcu_read_unlock_bh(); 83 + } 84 + 85 + void wg_packet_send_handshake_response(struct wg_peer *peer) 86 + { 87 + struct message_handshake_response packet; 88 + 89 + atomic64_set(&peer->last_sent_handshake, ktime_get_coarse_boottime_ns()); 90 + net_dbg_ratelimited("%s: Sending handshake response to peer %llu (%pISpfsc)\n", 91 + peer->device->dev->name, peer->internal_id, 92 + &peer->endpoint.addr); 93 + 94 + if (wg_noise_handshake_create_response(&packet, &peer->handshake)) { 95 + wg_cookie_add_mac_to_packet(&packet, sizeof(packet), peer); 96 + if (wg_noise_handshake_begin_session(&peer->handshake, 97 + &peer->keypairs)) { 98 + wg_timers_session_derived(peer); 99 + wg_timers_any_authenticated_packet_traversal(peer); 100 + wg_timers_any_authenticated_packet_sent(peer); 101 + atomic64_set(&peer->last_sent_handshake, 102 + ktime_get_coarse_boottime_ns()); 103 + wg_socket_send_buffer_to_peer(peer, &packet, 104 + sizeof(packet), 105 + HANDSHAKE_DSCP); 106 + } 107 + } 108 + } 109 + 110 + void wg_packet_send_handshake_cookie(struct wg_device *wg, 111 + struct sk_buff *initiating_skb, 112 + __le32 sender_index) 113 + { 114 + struct message_handshake_cookie packet; 115 + 116 + net_dbg_skb_ratelimited("%s: Sending cookie response for denied handshake message for %pISpfsc\n", 117 + wg->dev->name, initiating_skb); 118 + wg_cookie_message_create(&packet, initiating_skb, sender_index, 119 + &wg->cookie_checker); 120 + wg_socket_send_buffer_as_reply_to_skb(wg, initiating_skb, &packet, 121 + sizeof(packet)); 122 + } 123 + 124 + static void keep_key_fresh(struct wg_peer *peer) 125 + { 126 + struct noise_keypair *keypair; 127 + bool send = false; 128 + 129 + rcu_read_lock_bh(); 130 + keypair = rcu_dereference_bh(peer->keypairs.current_keypair); 131 + if (likely(keypair && READ_ONCE(keypair->sending.is_valid)) && 132 + (unlikely(atomic64_read(&keypair->sending.counter.counter) > 133 + REKEY_AFTER_MESSAGES) || 134 + (keypair->i_am_the_initiator && 135 + unlikely(wg_birthdate_has_expired(keypair->sending.birthdate, 136 + REKEY_AFTER_TIME))))) 137 + send = true; 138 + rcu_read_unlock_bh(); 139 + 140 + if (send) 141 + wg_packet_send_queued_handshake_initiation(peer, false); 142 + } 143 + 144 + static unsigned int calculate_skb_padding(struct sk_buff *skb) 145 + { 146 + /* We do this modulo business with the MTU, just in case the networking 147 + * layer gives us a packet that's bigger than the MTU. In that case, we 148 + * wouldn't want the final subtraction to overflow in the case of the 149 + * padded_size being clamped. 150 + */ 151 + unsigned int last_unit = skb->len % PACKET_CB(skb)->mtu; 152 + unsigned int padded_size = ALIGN(last_unit, MESSAGE_PADDING_MULTIPLE); 153 + 154 + if (padded_size > PACKET_CB(skb)->mtu) 155 + padded_size = PACKET_CB(skb)->mtu; 156 + return padded_size - last_unit; 157 + } 158 + 159 + static bool encrypt_packet(struct sk_buff *skb, struct noise_keypair *keypair) 160 + { 161 + unsigned int padding_len, plaintext_len, trailer_len; 162 + struct scatterlist sg[MAX_SKB_FRAGS + 8]; 163 + struct message_data *header; 164 + struct sk_buff *trailer; 165 + int num_frags; 166 + 167 + /* Calculate lengths. */ 168 + padding_len = calculate_skb_padding(skb); 169 + trailer_len = padding_len + noise_encrypted_len(0); 170 + plaintext_len = skb->len + padding_len; 171 + 172 + /* Expand data section to have room for padding and auth tag. */ 173 + num_frags = skb_cow_data(skb, trailer_len, &trailer); 174 + if (unlikely(num_frags < 0 || num_frags > ARRAY_SIZE(sg))) 175 + return false; 176 + 177 + /* Set the padding to zeros, and make sure it and the auth tag are part 178 + * of the skb. 179 + */ 180 + memset(skb_tail_pointer(trailer), 0, padding_len); 181 + 182 + /* Expand head section to have room for our header and the network 183 + * stack's headers. 184 + */ 185 + if (unlikely(skb_cow_head(skb, DATA_PACKET_HEAD_ROOM) < 0)) 186 + return false; 187 + 188 + /* Finalize checksum calculation for the inner packet, if required. */ 189 + if (unlikely(skb->ip_summed == CHECKSUM_PARTIAL && 190 + skb_checksum_help(skb))) 191 + return false; 192 + 193 + /* Only after checksumming can we safely add on the padding at the end 194 + * and the header. 195 + */ 196 + skb_set_inner_network_header(skb, 0); 197 + header = (struct message_data *)skb_push(skb, sizeof(*header)); 198 + header->header.type = cpu_to_le32(MESSAGE_DATA); 199 + header->key_idx = keypair->remote_index; 200 + header->counter = cpu_to_le64(PACKET_CB(skb)->nonce); 201 + pskb_put(skb, trailer, trailer_len); 202 + 203 + /* Now we can encrypt the scattergather segments */ 204 + sg_init_table(sg, num_frags); 205 + if (skb_to_sgvec(skb, sg, sizeof(struct message_data), 206 + noise_encrypted_len(plaintext_len)) <= 0) 207 + return false; 208 + return chacha20poly1305_encrypt_sg_inplace(sg, plaintext_len, NULL, 0, 209 + PACKET_CB(skb)->nonce, 210 + keypair->sending.key); 211 + } 212 + 213 + void wg_packet_send_keepalive(struct wg_peer *peer) 214 + { 215 + struct sk_buff *skb; 216 + 217 + if (skb_queue_empty(&peer->staged_packet_queue)) { 218 + skb = alloc_skb(DATA_PACKET_HEAD_ROOM + MESSAGE_MINIMUM_LENGTH, 219 + GFP_ATOMIC); 220 + if (unlikely(!skb)) 221 + return; 222 + skb_reserve(skb, DATA_PACKET_HEAD_ROOM); 223 + skb->dev = peer->device->dev; 224 + PACKET_CB(skb)->mtu = skb->dev->mtu; 225 + skb_queue_tail(&peer->staged_packet_queue, skb); 226 + net_dbg_ratelimited("%s: Sending keepalive packet to peer %llu (%pISpfsc)\n", 227 + peer->device->dev->name, peer->internal_id, 228 + &peer->endpoint.addr); 229 + } 230 + 231 + wg_packet_send_staged_packets(peer); 232 + } 233 + 234 + static void wg_packet_create_data_done(struct sk_buff *first, 235 + struct wg_peer *peer) 236 + { 237 + struct sk_buff *skb, *next; 238 + bool is_keepalive, data_sent = false; 239 + 240 + wg_timers_any_authenticated_packet_traversal(peer); 241 + wg_timers_any_authenticated_packet_sent(peer); 242 + skb_list_walk_safe(first, skb, next) { 243 + is_keepalive = skb->len == message_data_len(0); 244 + if (likely(!wg_socket_send_skb_to_peer(peer, skb, 245 + PACKET_CB(skb)->ds) && !is_keepalive)) 246 + data_sent = true; 247 + } 248 + 249 + if (likely(data_sent)) 250 + wg_timers_data_sent(peer); 251 + 252 + keep_key_fresh(peer); 253 + } 254 + 255 + void wg_packet_tx_worker(struct work_struct *work) 256 + { 257 + struct crypt_queue *queue = container_of(work, struct crypt_queue, 258 + work); 259 + struct noise_keypair *keypair; 260 + enum packet_state state; 261 + struct sk_buff *first; 262 + struct wg_peer *peer; 263 + 264 + while ((first = __ptr_ring_peek(&queue->ring)) != NULL && 265 + (state = atomic_read_acquire(&PACKET_CB(first)->state)) != 266 + PACKET_STATE_UNCRYPTED) { 267 + __ptr_ring_discard_one(&queue->ring); 268 + peer = PACKET_PEER(first); 269 + keypair = PACKET_CB(first)->keypair; 270 + 271 + if (likely(state == PACKET_STATE_CRYPTED)) 272 + wg_packet_create_data_done(first, peer); 273 + else 274 + kfree_skb_list(first); 275 + 276 + wg_noise_keypair_put(keypair, false); 277 + wg_peer_put(peer); 278 + } 279 + } 280 + 281 + void wg_packet_encrypt_worker(struct work_struct *work) 282 + { 283 + struct crypt_queue *queue = container_of(work, struct multicore_worker, 284 + work)->ptr; 285 + struct sk_buff *first, *skb, *next; 286 + 287 + while ((first = ptr_ring_consume_bh(&queue->ring)) != NULL) { 288 + enum packet_state state = PACKET_STATE_CRYPTED; 289 + 290 + skb_list_walk_safe(first, skb, next) { 291 + if (likely(encrypt_packet(skb, 292 + PACKET_CB(first)->keypair))) { 293 + wg_reset_packet(skb); 294 + } else { 295 + state = PACKET_STATE_DEAD; 296 + break; 297 + } 298 + } 299 + wg_queue_enqueue_per_peer(&PACKET_PEER(first)->tx_queue, first, 300 + state); 301 + 302 + } 303 + } 304 + 305 + static void wg_packet_create_data(struct sk_buff *first) 306 + { 307 + struct wg_peer *peer = PACKET_PEER(first); 308 + struct wg_device *wg = peer->device; 309 + int ret = -EINVAL; 310 + 311 + rcu_read_lock_bh(); 312 + if (unlikely(READ_ONCE(peer->is_dead))) 313 + goto err; 314 + 315 + ret = wg_queue_enqueue_per_device_and_peer(&wg->encrypt_queue, 316 + &peer->tx_queue, first, 317 + wg->packet_crypt_wq, 318 + &wg->encrypt_queue.last_cpu); 319 + if (unlikely(ret == -EPIPE)) 320 + wg_queue_enqueue_per_peer(&peer->tx_queue, first, 321 + PACKET_STATE_DEAD); 322 + err: 323 + rcu_read_unlock_bh(); 324 + if (likely(!ret || ret == -EPIPE)) 325 + return; 326 + wg_noise_keypair_put(PACKET_CB(first)->keypair, false); 327 + wg_peer_put(peer); 328 + kfree_skb_list(first); 329 + } 330 + 331 + void wg_packet_purge_staged_packets(struct wg_peer *peer) 332 + { 333 + spin_lock_bh(&peer->staged_packet_queue.lock); 334 + peer->device->dev->stats.tx_dropped += peer->staged_packet_queue.qlen; 335 + __skb_queue_purge(&peer->staged_packet_queue); 336 + spin_unlock_bh(&peer->staged_packet_queue.lock); 337 + } 338 + 339 + void wg_packet_send_staged_packets(struct wg_peer *peer) 340 + { 341 + struct noise_symmetric_key *key; 342 + struct noise_keypair *keypair; 343 + struct sk_buff_head packets; 344 + struct sk_buff *skb; 345 + 346 + /* Steal the current queue into our local one. */ 347 + __skb_queue_head_init(&packets); 348 + spin_lock_bh(&peer->staged_packet_queue.lock); 349 + skb_queue_splice_init(&peer->staged_packet_queue, &packets); 350 + spin_unlock_bh(&peer->staged_packet_queue.lock); 351 + if (unlikely(skb_queue_empty(&packets))) 352 + return; 353 + 354 + /* First we make sure we have a valid reference to a valid key. */ 355 + rcu_read_lock_bh(); 356 + keypair = wg_noise_keypair_get( 357 + rcu_dereference_bh(peer->keypairs.current_keypair)); 358 + rcu_read_unlock_bh(); 359 + if (unlikely(!keypair)) 360 + goto out_nokey; 361 + key = &keypair->sending; 362 + if (unlikely(!READ_ONCE(key->is_valid))) 363 + goto out_nokey; 364 + if (unlikely(wg_birthdate_has_expired(key->birthdate, 365 + REJECT_AFTER_TIME))) 366 + goto out_invalid; 367 + 368 + /* After we know we have a somewhat valid key, we now try to assign 369 + * nonces to all of the packets in the queue. If we can't assign nonces 370 + * for all of them, we just consider it a failure and wait for the next 371 + * handshake. 372 + */ 373 + skb_queue_walk(&packets, skb) { 374 + /* 0 for no outer TOS: no leak. TODO: at some later point, we 375 + * might consider using flowi->tos as outer instead. 376 + */ 377 + PACKET_CB(skb)->ds = ip_tunnel_ecn_encap(0, ip_hdr(skb), skb); 378 + PACKET_CB(skb)->nonce = 379 + atomic64_inc_return(&key->counter.counter) - 1; 380 + if (unlikely(PACKET_CB(skb)->nonce >= REJECT_AFTER_MESSAGES)) 381 + goto out_invalid; 382 + } 383 + 384 + packets.prev->next = NULL; 385 + wg_peer_get(keypair->entry.peer); 386 + PACKET_CB(packets.next)->keypair = keypair; 387 + wg_packet_create_data(packets.next); 388 + return; 389 + 390 + out_invalid: 391 + WRITE_ONCE(key->is_valid, false); 392 + out_nokey: 393 + wg_noise_keypair_put(keypair, false); 394 + 395 + /* We orphan the packets if we're waiting on a handshake, so that they 396 + * don't block a socket's pool. 397 + */ 398 + skb_queue_walk(&packets, skb) 399 + skb_orphan(skb); 400 + /* Then we put them back on the top of the queue. We're not too 401 + * concerned about accidentally getting things a little out of order if 402 + * packets are being added really fast, because this queue is for before 403 + * packets can even be sent and it's small anyway. 404 + */ 405 + spin_lock_bh(&peer->staged_packet_queue.lock); 406 + skb_queue_splice(&packets, &peer->staged_packet_queue); 407 + spin_unlock_bh(&peer->staged_packet_queue.lock); 408 + 409 + /* If we're exiting because there's something wrong with the key, it 410 + * means we should initiate a new handshake. 411 + */ 412 + wg_packet_send_queued_handshake_initiation(peer, false); 413 + }
+437
drivers/net/wireguard/socket.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "device.h" 7 + #include "peer.h" 8 + #include "socket.h" 9 + #include "queueing.h" 10 + #include "messages.h" 11 + 12 + #include <linux/ctype.h> 13 + #include <linux/net.h> 14 + #include <linux/if_vlan.h> 15 + #include <linux/if_ether.h> 16 + #include <linux/inetdevice.h> 17 + #include <net/udp_tunnel.h> 18 + #include <net/ipv6.h> 19 + 20 + static int send4(struct wg_device *wg, struct sk_buff *skb, 21 + struct endpoint *endpoint, u8 ds, struct dst_cache *cache) 22 + { 23 + struct flowi4 fl = { 24 + .saddr = endpoint->src4.s_addr, 25 + .daddr = endpoint->addr4.sin_addr.s_addr, 26 + .fl4_dport = endpoint->addr4.sin_port, 27 + .flowi4_mark = wg->fwmark, 28 + .flowi4_proto = IPPROTO_UDP 29 + }; 30 + struct rtable *rt = NULL; 31 + struct sock *sock; 32 + int ret = 0; 33 + 34 + skb_mark_not_on_list(skb); 35 + skb->dev = wg->dev; 36 + skb->mark = wg->fwmark; 37 + 38 + rcu_read_lock_bh(); 39 + sock = rcu_dereference_bh(wg->sock4); 40 + 41 + if (unlikely(!sock)) { 42 + ret = -ENONET; 43 + goto err; 44 + } 45 + 46 + fl.fl4_sport = inet_sk(sock)->inet_sport; 47 + 48 + if (cache) 49 + rt = dst_cache_get_ip4(cache, &fl.saddr); 50 + 51 + if (!rt) { 52 + security_sk_classify_flow(sock, flowi4_to_flowi(&fl)); 53 + if (unlikely(!inet_confirm_addr(sock_net(sock), NULL, 0, 54 + fl.saddr, RT_SCOPE_HOST))) { 55 + endpoint->src4.s_addr = 0; 56 + *(__force __be32 *)&endpoint->src_if4 = 0; 57 + fl.saddr = 0; 58 + if (cache) 59 + dst_cache_reset(cache); 60 + } 61 + rt = ip_route_output_flow(sock_net(sock), &fl, sock); 62 + if (unlikely(endpoint->src_if4 && ((IS_ERR(rt) && 63 + PTR_ERR(rt) == -EINVAL) || (!IS_ERR(rt) && 64 + rt->dst.dev->ifindex != endpoint->src_if4)))) { 65 + endpoint->src4.s_addr = 0; 66 + *(__force __be32 *)&endpoint->src_if4 = 0; 67 + fl.saddr = 0; 68 + if (cache) 69 + dst_cache_reset(cache); 70 + if (!IS_ERR(rt)) 71 + ip_rt_put(rt); 72 + rt = ip_route_output_flow(sock_net(sock), &fl, sock); 73 + } 74 + if (unlikely(IS_ERR(rt))) { 75 + ret = PTR_ERR(rt); 76 + net_dbg_ratelimited("%s: No route to %pISpfsc, error %d\n", 77 + wg->dev->name, &endpoint->addr, ret); 78 + goto err; 79 + } else if (unlikely(rt->dst.dev == skb->dev)) { 80 + ip_rt_put(rt); 81 + ret = -ELOOP; 82 + net_dbg_ratelimited("%s: Avoiding routing loop to %pISpfsc\n", 83 + wg->dev->name, &endpoint->addr); 84 + goto err; 85 + } 86 + if (cache) 87 + dst_cache_set_ip4(cache, &rt->dst, fl.saddr); 88 + } 89 + 90 + skb->ignore_df = 1; 91 + udp_tunnel_xmit_skb(rt, sock, skb, fl.saddr, fl.daddr, ds, 92 + ip4_dst_hoplimit(&rt->dst), 0, fl.fl4_sport, 93 + fl.fl4_dport, false, false); 94 + goto out; 95 + 96 + err: 97 + kfree_skb(skb); 98 + out: 99 + rcu_read_unlock_bh(); 100 + return ret; 101 + } 102 + 103 + static int send6(struct wg_device *wg, struct sk_buff *skb, 104 + struct endpoint *endpoint, u8 ds, struct dst_cache *cache) 105 + { 106 + #if IS_ENABLED(CONFIG_IPV6) 107 + struct flowi6 fl = { 108 + .saddr = endpoint->src6, 109 + .daddr = endpoint->addr6.sin6_addr, 110 + .fl6_dport = endpoint->addr6.sin6_port, 111 + .flowi6_mark = wg->fwmark, 112 + .flowi6_oif = endpoint->addr6.sin6_scope_id, 113 + .flowi6_proto = IPPROTO_UDP 114 + /* TODO: addr->sin6_flowinfo */ 115 + }; 116 + struct dst_entry *dst = NULL; 117 + struct sock *sock; 118 + int ret = 0; 119 + 120 + skb_mark_not_on_list(skb); 121 + skb->dev = wg->dev; 122 + skb->mark = wg->fwmark; 123 + 124 + rcu_read_lock_bh(); 125 + sock = rcu_dereference_bh(wg->sock6); 126 + 127 + if (unlikely(!sock)) { 128 + ret = -ENONET; 129 + goto err; 130 + } 131 + 132 + fl.fl6_sport = inet_sk(sock)->inet_sport; 133 + 134 + if (cache) 135 + dst = dst_cache_get_ip6(cache, &fl.saddr); 136 + 137 + if (!dst) { 138 + security_sk_classify_flow(sock, flowi6_to_flowi(&fl)); 139 + if (unlikely(!ipv6_addr_any(&fl.saddr) && 140 + !ipv6_chk_addr(sock_net(sock), &fl.saddr, NULL, 0))) { 141 + endpoint->src6 = fl.saddr = in6addr_any; 142 + if (cache) 143 + dst_cache_reset(cache); 144 + } 145 + dst = ipv6_stub->ipv6_dst_lookup_flow(sock_net(sock), sock, &fl, 146 + NULL); 147 + if (unlikely(IS_ERR(dst))) { 148 + ret = PTR_ERR(dst); 149 + net_dbg_ratelimited("%s: No route to %pISpfsc, error %d\n", 150 + wg->dev->name, &endpoint->addr, ret); 151 + goto err; 152 + } else if (unlikely(dst->dev == skb->dev)) { 153 + dst_release(dst); 154 + ret = -ELOOP; 155 + net_dbg_ratelimited("%s: Avoiding routing loop to %pISpfsc\n", 156 + wg->dev->name, &endpoint->addr); 157 + goto err; 158 + } 159 + if (cache) 160 + dst_cache_set_ip6(cache, dst, &fl.saddr); 161 + } 162 + 163 + skb->ignore_df = 1; 164 + udp_tunnel6_xmit_skb(dst, sock, skb, skb->dev, &fl.saddr, &fl.daddr, ds, 165 + ip6_dst_hoplimit(dst), 0, fl.fl6_sport, 166 + fl.fl6_dport, false); 167 + goto out; 168 + 169 + err: 170 + kfree_skb(skb); 171 + out: 172 + rcu_read_unlock_bh(); 173 + return ret; 174 + #else 175 + return -EAFNOSUPPORT; 176 + #endif 177 + } 178 + 179 + int wg_socket_send_skb_to_peer(struct wg_peer *peer, struct sk_buff *skb, u8 ds) 180 + { 181 + size_t skb_len = skb->len; 182 + int ret = -EAFNOSUPPORT; 183 + 184 + read_lock_bh(&peer->endpoint_lock); 185 + if (peer->endpoint.addr.sa_family == AF_INET) 186 + ret = send4(peer->device, skb, &peer->endpoint, ds, 187 + &peer->endpoint_cache); 188 + else if (peer->endpoint.addr.sa_family == AF_INET6) 189 + ret = send6(peer->device, skb, &peer->endpoint, ds, 190 + &peer->endpoint_cache); 191 + else 192 + dev_kfree_skb(skb); 193 + if (likely(!ret)) 194 + peer->tx_bytes += skb_len; 195 + read_unlock_bh(&peer->endpoint_lock); 196 + 197 + return ret; 198 + } 199 + 200 + int wg_socket_send_buffer_to_peer(struct wg_peer *peer, void *buffer, 201 + size_t len, u8 ds) 202 + { 203 + struct sk_buff *skb = alloc_skb(len + SKB_HEADER_LEN, GFP_ATOMIC); 204 + 205 + if (unlikely(!skb)) 206 + return -ENOMEM; 207 + 208 + skb_reserve(skb, SKB_HEADER_LEN); 209 + skb_set_inner_network_header(skb, 0); 210 + skb_put_data(skb, buffer, len); 211 + return wg_socket_send_skb_to_peer(peer, skb, ds); 212 + } 213 + 214 + int wg_socket_send_buffer_as_reply_to_skb(struct wg_device *wg, 215 + struct sk_buff *in_skb, void *buffer, 216 + size_t len) 217 + { 218 + int ret = 0; 219 + struct sk_buff *skb; 220 + struct endpoint endpoint; 221 + 222 + if (unlikely(!in_skb)) 223 + return -EINVAL; 224 + ret = wg_socket_endpoint_from_skb(&endpoint, in_skb); 225 + if (unlikely(ret < 0)) 226 + return ret; 227 + 228 + skb = alloc_skb(len + SKB_HEADER_LEN, GFP_ATOMIC); 229 + if (unlikely(!skb)) 230 + return -ENOMEM; 231 + skb_reserve(skb, SKB_HEADER_LEN); 232 + skb_set_inner_network_header(skb, 0); 233 + skb_put_data(skb, buffer, len); 234 + 235 + if (endpoint.addr.sa_family == AF_INET) 236 + ret = send4(wg, skb, &endpoint, 0, NULL); 237 + else if (endpoint.addr.sa_family == AF_INET6) 238 + ret = send6(wg, skb, &endpoint, 0, NULL); 239 + /* No other possibilities if the endpoint is valid, which it is, 240 + * as we checked above. 241 + */ 242 + 243 + return ret; 244 + } 245 + 246 + int wg_socket_endpoint_from_skb(struct endpoint *endpoint, 247 + const struct sk_buff *skb) 248 + { 249 + memset(endpoint, 0, sizeof(*endpoint)); 250 + if (skb->protocol == htons(ETH_P_IP)) { 251 + endpoint->addr4.sin_family = AF_INET; 252 + endpoint->addr4.sin_port = udp_hdr(skb)->source; 253 + endpoint->addr4.sin_addr.s_addr = ip_hdr(skb)->saddr; 254 + endpoint->src4.s_addr = ip_hdr(skb)->daddr; 255 + endpoint->src_if4 = skb->skb_iif; 256 + } else if (skb->protocol == htons(ETH_P_IPV6)) { 257 + endpoint->addr6.sin6_family = AF_INET6; 258 + endpoint->addr6.sin6_port = udp_hdr(skb)->source; 259 + endpoint->addr6.sin6_addr = ipv6_hdr(skb)->saddr; 260 + endpoint->addr6.sin6_scope_id = ipv6_iface_scope_id( 261 + &ipv6_hdr(skb)->saddr, skb->skb_iif); 262 + endpoint->src6 = ipv6_hdr(skb)->daddr; 263 + } else { 264 + return -EINVAL; 265 + } 266 + return 0; 267 + } 268 + 269 + static bool endpoint_eq(const struct endpoint *a, const struct endpoint *b) 270 + { 271 + return (a->addr.sa_family == AF_INET && b->addr.sa_family == AF_INET && 272 + a->addr4.sin_port == b->addr4.sin_port && 273 + a->addr4.sin_addr.s_addr == b->addr4.sin_addr.s_addr && 274 + a->src4.s_addr == b->src4.s_addr && a->src_if4 == b->src_if4) || 275 + (a->addr.sa_family == AF_INET6 && 276 + b->addr.sa_family == AF_INET6 && 277 + a->addr6.sin6_port == b->addr6.sin6_port && 278 + ipv6_addr_equal(&a->addr6.sin6_addr, &b->addr6.sin6_addr) && 279 + a->addr6.sin6_scope_id == b->addr6.sin6_scope_id && 280 + ipv6_addr_equal(&a->src6, &b->src6)) || 281 + unlikely(!a->addr.sa_family && !b->addr.sa_family); 282 + } 283 + 284 + void wg_socket_set_peer_endpoint(struct wg_peer *peer, 285 + const struct endpoint *endpoint) 286 + { 287 + /* First we check unlocked, in order to optimize, since it's pretty rare 288 + * that an endpoint will change. If we happen to be mid-write, and two 289 + * CPUs wind up writing the same thing or something slightly different, 290 + * it doesn't really matter much either. 291 + */ 292 + if (endpoint_eq(endpoint, &peer->endpoint)) 293 + return; 294 + write_lock_bh(&peer->endpoint_lock); 295 + if (endpoint->addr.sa_family == AF_INET) { 296 + peer->endpoint.addr4 = endpoint->addr4; 297 + peer->endpoint.src4 = endpoint->src4; 298 + peer->endpoint.src_if4 = endpoint->src_if4; 299 + } else if (endpoint->addr.sa_family == AF_INET6) { 300 + peer->endpoint.addr6 = endpoint->addr6; 301 + peer->endpoint.src6 = endpoint->src6; 302 + } else { 303 + goto out; 304 + } 305 + dst_cache_reset(&peer->endpoint_cache); 306 + out: 307 + write_unlock_bh(&peer->endpoint_lock); 308 + } 309 + 310 + void wg_socket_set_peer_endpoint_from_skb(struct wg_peer *peer, 311 + const struct sk_buff *skb) 312 + { 313 + struct endpoint endpoint; 314 + 315 + if (!wg_socket_endpoint_from_skb(&endpoint, skb)) 316 + wg_socket_set_peer_endpoint(peer, &endpoint); 317 + } 318 + 319 + void wg_socket_clear_peer_endpoint_src(struct wg_peer *peer) 320 + { 321 + write_lock_bh(&peer->endpoint_lock); 322 + memset(&peer->endpoint.src6, 0, sizeof(peer->endpoint.src6)); 323 + dst_cache_reset(&peer->endpoint_cache); 324 + write_unlock_bh(&peer->endpoint_lock); 325 + } 326 + 327 + static int wg_receive(struct sock *sk, struct sk_buff *skb) 328 + { 329 + struct wg_device *wg; 330 + 331 + if (unlikely(!sk)) 332 + goto err; 333 + wg = sk->sk_user_data; 334 + if (unlikely(!wg)) 335 + goto err; 336 + wg_packet_receive(wg, skb); 337 + return 0; 338 + 339 + err: 340 + kfree_skb(skb); 341 + return 0; 342 + } 343 + 344 + static void sock_free(struct sock *sock) 345 + { 346 + if (unlikely(!sock)) 347 + return; 348 + sk_clear_memalloc(sock); 349 + udp_tunnel_sock_release(sock->sk_socket); 350 + } 351 + 352 + static void set_sock_opts(struct socket *sock) 353 + { 354 + sock->sk->sk_allocation = GFP_ATOMIC; 355 + sock->sk->sk_sndbuf = INT_MAX; 356 + sk_set_memalloc(sock->sk); 357 + } 358 + 359 + int wg_socket_init(struct wg_device *wg, u16 port) 360 + { 361 + int ret; 362 + struct udp_tunnel_sock_cfg cfg = { 363 + .sk_user_data = wg, 364 + .encap_type = 1, 365 + .encap_rcv = wg_receive 366 + }; 367 + struct socket *new4 = NULL, *new6 = NULL; 368 + struct udp_port_cfg port4 = { 369 + .family = AF_INET, 370 + .local_ip.s_addr = htonl(INADDR_ANY), 371 + .local_udp_port = htons(port), 372 + .use_udp_checksums = true 373 + }; 374 + #if IS_ENABLED(CONFIG_IPV6) 375 + int retries = 0; 376 + struct udp_port_cfg port6 = { 377 + .family = AF_INET6, 378 + .local_ip6 = IN6ADDR_ANY_INIT, 379 + .use_udp6_tx_checksums = true, 380 + .use_udp6_rx_checksums = true, 381 + .ipv6_v6only = true 382 + }; 383 + #endif 384 + 385 + #if IS_ENABLED(CONFIG_IPV6) 386 + retry: 387 + #endif 388 + 389 + ret = udp_sock_create(wg->creating_net, &port4, &new4); 390 + if (ret < 0) { 391 + pr_err("%s: Could not create IPv4 socket\n", wg->dev->name); 392 + return ret; 393 + } 394 + set_sock_opts(new4); 395 + setup_udp_tunnel_sock(wg->creating_net, new4, &cfg); 396 + 397 + #if IS_ENABLED(CONFIG_IPV6) 398 + if (ipv6_mod_enabled()) { 399 + port6.local_udp_port = inet_sk(new4->sk)->inet_sport; 400 + ret = udp_sock_create(wg->creating_net, &port6, &new6); 401 + if (ret < 0) { 402 + udp_tunnel_sock_release(new4); 403 + if (ret == -EADDRINUSE && !port && retries++ < 100) 404 + goto retry; 405 + pr_err("%s: Could not create IPv6 socket\n", 406 + wg->dev->name); 407 + return ret; 408 + } 409 + set_sock_opts(new6); 410 + setup_udp_tunnel_sock(wg->creating_net, new6, &cfg); 411 + } 412 + #endif 413 + 414 + wg_socket_reinit(wg, new4->sk, new6 ? new6->sk : NULL); 415 + return 0; 416 + } 417 + 418 + void wg_socket_reinit(struct wg_device *wg, struct sock *new4, 419 + struct sock *new6) 420 + { 421 + struct sock *old4, *old6; 422 + 423 + mutex_lock(&wg->socket_update_lock); 424 + old4 = rcu_dereference_protected(wg->sock4, 425 + lockdep_is_held(&wg->socket_update_lock)); 426 + old6 = rcu_dereference_protected(wg->sock6, 427 + lockdep_is_held(&wg->socket_update_lock)); 428 + rcu_assign_pointer(wg->sock4, new4); 429 + rcu_assign_pointer(wg->sock6, new6); 430 + if (new4) 431 + wg->incoming_port = ntohs(inet_sk(new4)->inet_sport); 432 + mutex_unlock(&wg->socket_update_lock); 433 + synchronize_rcu(); 434 + synchronize_net(); 435 + sock_free(old4); 436 + sock_free(old6); 437 + }
+44
drivers/net/wireguard/socket.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_SOCKET_H 7 + #define _WG_SOCKET_H 8 + 9 + #include <linux/netdevice.h> 10 + #include <linux/udp.h> 11 + #include <linux/if_vlan.h> 12 + #include <linux/if_ether.h> 13 + 14 + int wg_socket_init(struct wg_device *wg, u16 port); 15 + void wg_socket_reinit(struct wg_device *wg, struct sock *new4, 16 + struct sock *new6); 17 + int wg_socket_send_buffer_to_peer(struct wg_peer *peer, void *data, 18 + size_t len, u8 ds); 19 + int wg_socket_send_skb_to_peer(struct wg_peer *peer, struct sk_buff *skb, 20 + u8 ds); 21 + int wg_socket_send_buffer_as_reply_to_skb(struct wg_device *wg, 22 + struct sk_buff *in_skb, 23 + void *out_buffer, size_t len); 24 + 25 + int wg_socket_endpoint_from_skb(struct endpoint *endpoint, 26 + const struct sk_buff *skb); 27 + void wg_socket_set_peer_endpoint(struct wg_peer *peer, 28 + const struct endpoint *endpoint); 29 + void wg_socket_set_peer_endpoint_from_skb(struct wg_peer *peer, 30 + const struct sk_buff *skb); 31 + void wg_socket_clear_peer_endpoint_src(struct wg_peer *peer); 32 + 33 + #if defined(CONFIG_DYNAMIC_DEBUG) || defined(DEBUG) 34 + #define net_dbg_skb_ratelimited(fmt, dev, skb, ...) do { \ 35 + struct endpoint __endpoint; \ 36 + wg_socket_endpoint_from_skb(&__endpoint, skb); \ 37 + net_dbg_ratelimited(fmt, dev, &__endpoint.addr, \ 38 + ##__VA_ARGS__); \ 39 + } while (0) 40 + #else 41 + #define net_dbg_skb_ratelimited(fmt, skb, ...) 42 + #endif 43 + 44 + #endif /* _WG_SOCKET_H */
+243
drivers/net/wireguard/timers.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #include "timers.h" 7 + #include "device.h" 8 + #include "peer.h" 9 + #include "queueing.h" 10 + #include "socket.h" 11 + 12 + /* 13 + * - Timer for retransmitting the handshake if we don't hear back after 14 + * `REKEY_TIMEOUT + jitter` ms. 15 + * 16 + * - Timer for sending empty packet if we have received a packet but after have 17 + * not sent one for `KEEPALIVE_TIMEOUT` ms. 18 + * 19 + * - Timer for initiating new handshake if we have sent a packet but after have 20 + * not received one (even empty) for `(KEEPALIVE_TIMEOUT + REKEY_TIMEOUT) + 21 + * jitter` ms. 22 + * 23 + * - Timer for zeroing out all ephemeral keys after `(REJECT_AFTER_TIME * 3)` ms 24 + * if no new keys have been received. 25 + * 26 + * - Timer for, if enabled, sending an empty authenticated packet every user- 27 + * specified seconds. 28 + */ 29 + 30 + static inline void mod_peer_timer(struct wg_peer *peer, 31 + struct timer_list *timer, 32 + unsigned long expires) 33 + { 34 + rcu_read_lock_bh(); 35 + if (likely(netif_running(peer->device->dev) && 36 + !READ_ONCE(peer->is_dead))) 37 + mod_timer(timer, expires); 38 + rcu_read_unlock_bh(); 39 + } 40 + 41 + static void wg_expired_retransmit_handshake(struct timer_list *timer) 42 + { 43 + struct wg_peer *peer = from_timer(peer, timer, 44 + timer_retransmit_handshake); 45 + 46 + if (peer->timer_handshake_attempts > MAX_TIMER_HANDSHAKES) { 47 + pr_debug("%s: Handshake for peer %llu (%pISpfsc) did not complete after %d attempts, giving up\n", 48 + peer->device->dev->name, peer->internal_id, 49 + &peer->endpoint.addr, MAX_TIMER_HANDSHAKES + 2); 50 + 51 + del_timer(&peer->timer_send_keepalive); 52 + /* We drop all packets without a keypair and don't try again, 53 + * if we try unsuccessfully for too long to make a handshake. 54 + */ 55 + wg_packet_purge_staged_packets(peer); 56 + 57 + /* We set a timer for destroying any residue that might be left 58 + * of a partial exchange. 59 + */ 60 + if (!timer_pending(&peer->timer_zero_key_material)) 61 + mod_peer_timer(peer, &peer->timer_zero_key_material, 62 + jiffies + REJECT_AFTER_TIME * 3 * HZ); 63 + } else { 64 + ++peer->timer_handshake_attempts; 65 + pr_debug("%s: Handshake for peer %llu (%pISpfsc) did not complete after %d seconds, retrying (try %d)\n", 66 + peer->device->dev->name, peer->internal_id, 67 + &peer->endpoint.addr, REKEY_TIMEOUT, 68 + peer->timer_handshake_attempts + 1); 69 + 70 + /* We clear the endpoint address src address, in case this is 71 + * the cause of trouble. 72 + */ 73 + wg_socket_clear_peer_endpoint_src(peer); 74 + 75 + wg_packet_send_queued_handshake_initiation(peer, true); 76 + } 77 + } 78 + 79 + static void wg_expired_send_keepalive(struct timer_list *timer) 80 + { 81 + struct wg_peer *peer = from_timer(peer, timer, timer_send_keepalive); 82 + 83 + wg_packet_send_keepalive(peer); 84 + if (peer->timer_need_another_keepalive) { 85 + peer->timer_need_another_keepalive = false; 86 + mod_peer_timer(peer, &peer->timer_send_keepalive, 87 + jiffies + KEEPALIVE_TIMEOUT * HZ); 88 + } 89 + } 90 + 91 + static void wg_expired_new_handshake(struct timer_list *timer) 92 + { 93 + struct wg_peer *peer = from_timer(peer, timer, timer_new_handshake); 94 + 95 + pr_debug("%s: Retrying handshake with peer %llu (%pISpfsc) because we stopped hearing back after %d seconds\n", 96 + peer->device->dev->name, peer->internal_id, 97 + &peer->endpoint.addr, KEEPALIVE_TIMEOUT + REKEY_TIMEOUT); 98 + /* We clear the endpoint address src address, in case this is the cause 99 + * of trouble. 100 + */ 101 + wg_socket_clear_peer_endpoint_src(peer); 102 + wg_packet_send_queued_handshake_initiation(peer, false); 103 + } 104 + 105 + static void wg_expired_zero_key_material(struct timer_list *timer) 106 + { 107 + struct wg_peer *peer = from_timer(peer, timer, timer_zero_key_material); 108 + 109 + rcu_read_lock_bh(); 110 + if (!READ_ONCE(peer->is_dead)) { 111 + wg_peer_get(peer); 112 + if (!queue_work(peer->device->handshake_send_wq, 113 + &peer->clear_peer_work)) 114 + /* If the work was already on the queue, we want to drop 115 + * the extra reference. 116 + */ 117 + wg_peer_put(peer); 118 + } 119 + rcu_read_unlock_bh(); 120 + } 121 + 122 + static void wg_queued_expired_zero_key_material(struct work_struct *work) 123 + { 124 + struct wg_peer *peer = container_of(work, struct wg_peer, 125 + clear_peer_work); 126 + 127 + pr_debug("%s: Zeroing out all keys for peer %llu (%pISpfsc), since we haven't received a new one in %d seconds\n", 128 + peer->device->dev->name, peer->internal_id, 129 + &peer->endpoint.addr, REJECT_AFTER_TIME * 3); 130 + wg_noise_handshake_clear(&peer->handshake); 131 + wg_noise_keypairs_clear(&peer->keypairs); 132 + wg_peer_put(peer); 133 + } 134 + 135 + static void wg_expired_send_persistent_keepalive(struct timer_list *timer) 136 + { 137 + struct wg_peer *peer = from_timer(peer, timer, 138 + timer_persistent_keepalive); 139 + 140 + if (likely(peer->persistent_keepalive_interval)) 141 + wg_packet_send_keepalive(peer); 142 + } 143 + 144 + /* Should be called after an authenticated data packet is sent. */ 145 + void wg_timers_data_sent(struct wg_peer *peer) 146 + { 147 + if (!timer_pending(&peer->timer_new_handshake)) 148 + mod_peer_timer(peer, &peer->timer_new_handshake, 149 + jiffies + (KEEPALIVE_TIMEOUT + REKEY_TIMEOUT) * HZ + 150 + prandom_u32_max(REKEY_TIMEOUT_JITTER_MAX_JIFFIES)); 151 + } 152 + 153 + /* Should be called after an authenticated data packet is received. */ 154 + void wg_timers_data_received(struct wg_peer *peer) 155 + { 156 + if (likely(netif_running(peer->device->dev))) { 157 + if (!timer_pending(&peer->timer_send_keepalive)) 158 + mod_peer_timer(peer, &peer->timer_send_keepalive, 159 + jiffies + KEEPALIVE_TIMEOUT * HZ); 160 + else 161 + peer->timer_need_another_keepalive = true; 162 + } 163 + } 164 + 165 + /* Should be called after any type of authenticated packet is sent, whether 166 + * keepalive, data, or handshake. 167 + */ 168 + void wg_timers_any_authenticated_packet_sent(struct wg_peer *peer) 169 + { 170 + del_timer(&peer->timer_send_keepalive); 171 + } 172 + 173 + /* Should be called after any type of authenticated packet is received, whether 174 + * keepalive, data, or handshake. 175 + */ 176 + void wg_timers_any_authenticated_packet_received(struct wg_peer *peer) 177 + { 178 + del_timer(&peer->timer_new_handshake); 179 + } 180 + 181 + /* Should be called after a handshake initiation message is sent. */ 182 + void wg_timers_handshake_initiated(struct wg_peer *peer) 183 + { 184 + mod_peer_timer(peer, &peer->timer_retransmit_handshake, 185 + jiffies + REKEY_TIMEOUT * HZ + 186 + prandom_u32_max(REKEY_TIMEOUT_JITTER_MAX_JIFFIES)); 187 + } 188 + 189 + /* Should be called after a handshake response message is received and processed 190 + * or when getting key confirmation via the first data message. 191 + */ 192 + void wg_timers_handshake_complete(struct wg_peer *peer) 193 + { 194 + del_timer(&peer->timer_retransmit_handshake); 195 + peer->timer_handshake_attempts = 0; 196 + peer->sent_lastminute_handshake = false; 197 + ktime_get_real_ts64(&peer->walltime_last_handshake); 198 + } 199 + 200 + /* Should be called after an ephemeral key is created, which is before sending a 201 + * handshake response or after receiving a handshake response. 202 + */ 203 + void wg_timers_session_derived(struct wg_peer *peer) 204 + { 205 + mod_peer_timer(peer, &peer->timer_zero_key_material, 206 + jiffies + REJECT_AFTER_TIME * 3 * HZ); 207 + } 208 + 209 + /* Should be called before a packet with authentication, whether 210 + * keepalive, data, or handshakem is sent, or after one is received. 211 + */ 212 + void wg_timers_any_authenticated_packet_traversal(struct wg_peer *peer) 213 + { 214 + if (peer->persistent_keepalive_interval) 215 + mod_peer_timer(peer, &peer->timer_persistent_keepalive, 216 + jiffies + peer->persistent_keepalive_interval * HZ); 217 + } 218 + 219 + void wg_timers_init(struct wg_peer *peer) 220 + { 221 + timer_setup(&peer->timer_retransmit_handshake, 222 + wg_expired_retransmit_handshake, 0); 223 + timer_setup(&peer->timer_send_keepalive, wg_expired_send_keepalive, 0); 224 + timer_setup(&peer->timer_new_handshake, wg_expired_new_handshake, 0); 225 + timer_setup(&peer->timer_zero_key_material, 226 + wg_expired_zero_key_material, 0); 227 + timer_setup(&peer->timer_persistent_keepalive, 228 + wg_expired_send_persistent_keepalive, 0); 229 + INIT_WORK(&peer->clear_peer_work, wg_queued_expired_zero_key_material); 230 + peer->timer_handshake_attempts = 0; 231 + peer->sent_lastminute_handshake = false; 232 + peer->timer_need_another_keepalive = false; 233 + } 234 + 235 + void wg_timers_stop(struct wg_peer *peer) 236 + { 237 + del_timer_sync(&peer->timer_retransmit_handshake); 238 + del_timer_sync(&peer->timer_send_keepalive); 239 + del_timer_sync(&peer->timer_new_handshake); 240 + del_timer_sync(&peer->timer_zero_key_material); 241 + del_timer_sync(&peer->timer_persistent_keepalive); 242 + flush_work(&peer->clear_peer_work); 243 + }
+31
drivers/net/wireguard/timers.h
··· 1 + /* SPDX-License-Identifier: GPL-2.0 */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + */ 5 + 6 + #ifndef _WG_TIMERS_H 7 + #define _WG_TIMERS_H 8 + 9 + #include <linux/ktime.h> 10 + 11 + struct wg_peer; 12 + 13 + void wg_timers_init(struct wg_peer *peer); 14 + void wg_timers_stop(struct wg_peer *peer); 15 + void wg_timers_data_sent(struct wg_peer *peer); 16 + void wg_timers_data_received(struct wg_peer *peer); 17 + void wg_timers_any_authenticated_packet_sent(struct wg_peer *peer); 18 + void wg_timers_any_authenticated_packet_received(struct wg_peer *peer); 19 + void wg_timers_handshake_initiated(struct wg_peer *peer); 20 + void wg_timers_handshake_complete(struct wg_peer *peer); 21 + void wg_timers_session_derived(struct wg_peer *peer); 22 + void wg_timers_any_authenticated_packet_traversal(struct wg_peer *peer); 23 + 24 + static inline bool wg_birthdate_has_expired(u64 birthday_nanoseconds, 25 + u64 expiration_seconds) 26 + { 27 + return (s64)(birthday_nanoseconds + expiration_seconds * NSEC_PER_SEC) 28 + <= (s64)ktime_get_coarse_boottime_ns(); 29 + } 30 + 31 + #endif /* _WG_TIMERS_H */
+1
drivers/net/wireguard/version.h
··· 1 + #define WIREGUARD_VERSION "1.0.0"
+196
include/uapi/linux/wireguard.h
··· 1 + /* SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT */ 2 + /* 3 + * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 4 + * 5 + * Documentation 6 + * ============= 7 + * 8 + * The below enums and macros are for interfacing with WireGuard, using generic 9 + * netlink, with family WG_GENL_NAME and version WG_GENL_VERSION. It defines two 10 + * methods: get and set. Note that while they share many common attributes, 11 + * these two functions actually accept a slightly different set of inputs and 12 + * outputs. 13 + * 14 + * WG_CMD_GET_DEVICE 15 + * ----------------- 16 + * 17 + * May only be called via NLM_F_REQUEST | NLM_F_DUMP. The command should contain 18 + * one but not both of: 19 + * 20 + * WGDEVICE_A_IFINDEX: NLA_U32 21 + * WGDEVICE_A_IFNAME: NLA_NUL_STRING, maxlen IFNAMESIZ - 1 22 + * 23 + * The kernel will then return several messages (NLM_F_MULTI) containing the 24 + * following tree of nested items: 25 + * 26 + * WGDEVICE_A_IFINDEX: NLA_U32 27 + * WGDEVICE_A_IFNAME: NLA_NUL_STRING, maxlen IFNAMESIZ - 1 28 + * WGDEVICE_A_PRIVATE_KEY: NLA_EXACT_LEN, len WG_KEY_LEN 29 + * WGDEVICE_A_PUBLIC_KEY: NLA_EXACT_LEN, len WG_KEY_LEN 30 + * WGDEVICE_A_LISTEN_PORT: NLA_U16 31 + * WGDEVICE_A_FWMARK: NLA_U32 32 + * WGDEVICE_A_PEERS: NLA_NESTED 33 + * 0: NLA_NESTED 34 + * WGPEER_A_PUBLIC_KEY: NLA_EXACT_LEN, len WG_KEY_LEN 35 + * WGPEER_A_PRESHARED_KEY: NLA_EXACT_LEN, len WG_KEY_LEN 36 + * WGPEER_A_ENDPOINT: NLA_MIN_LEN(struct sockaddr), struct sockaddr_in or struct sockaddr_in6 37 + * WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL: NLA_U16 38 + * WGPEER_A_LAST_HANDSHAKE_TIME: NLA_EXACT_LEN, struct __kernel_timespec 39 + * WGPEER_A_RX_BYTES: NLA_U64 40 + * WGPEER_A_TX_BYTES: NLA_U64 41 + * WGPEER_A_ALLOWEDIPS: NLA_NESTED 42 + * 0: NLA_NESTED 43 + * WGALLOWEDIP_A_FAMILY: NLA_U16 44 + * WGALLOWEDIP_A_IPADDR: NLA_MIN_LEN(struct in_addr), struct in_addr or struct in6_addr 45 + * WGALLOWEDIP_A_CIDR_MASK: NLA_U8 46 + * 0: NLA_NESTED 47 + * ... 48 + * 0: NLA_NESTED 49 + * ... 50 + * ... 51 + * WGPEER_A_PROTOCOL_VERSION: NLA_U32 52 + * 0: NLA_NESTED 53 + * ... 54 + * ... 55 + * 56 + * It is possible that all of the allowed IPs of a single peer will not 57 + * fit within a single netlink message. In that case, the same peer will 58 + * be written in the following message, except it will only contain 59 + * WGPEER_A_PUBLIC_KEY and WGPEER_A_ALLOWEDIPS. This may occur several 60 + * times in a row for the same peer. It is then up to the receiver to 61 + * coalesce adjacent peers. Likewise, it is possible that all peers will 62 + * not fit within a single message. So, subsequent peers will be sent 63 + * in following messages, except those will only contain WGDEVICE_A_IFNAME 64 + * and WGDEVICE_A_PEERS. It is then up to the receiver to coalesce these 65 + * messages to form the complete list of peers. 66 + * 67 + * Since this is an NLA_F_DUMP command, the final message will always be 68 + * NLMSG_DONE, even if an error occurs. However, this NLMSG_DONE message 69 + * contains an integer error code. It is either zero or a negative error 70 + * code corresponding to the errno. 71 + * 72 + * WG_CMD_SET_DEVICE 73 + * ----------------- 74 + * 75 + * May only be called via NLM_F_REQUEST. The command should contain the 76 + * following tree of nested items, containing one but not both of 77 + * WGDEVICE_A_IFINDEX and WGDEVICE_A_IFNAME: 78 + * 79 + * WGDEVICE_A_IFINDEX: NLA_U32 80 + * WGDEVICE_A_IFNAME: NLA_NUL_STRING, maxlen IFNAMESIZ - 1 81 + * WGDEVICE_A_FLAGS: NLA_U32, 0 or WGDEVICE_F_REPLACE_PEERS if all current 82 + * peers should be removed prior to adding the list below. 83 + * WGDEVICE_A_PRIVATE_KEY: len WG_KEY_LEN, all zeros to remove 84 + * WGDEVICE_A_LISTEN_PORT: NLA_U16, 0 to choose randomly 85 + * WGDEVICE_A_FWMARK: NLA_U32, 0 to disable 86 + * WGDEVICE_A_PEERS: NLA_NESTED 87 + * 0: NLA_NESTED 88 + * WGPEER_A_PUBLIC_KEY: len WG_KEY_LEN 89 + * WGPEER_A_FLAGS: NLA_U32, 0 and/or WGPEER_F_REMOVE_ME if the 90 + * specified peer should not exist at the end of the 91 + * operation, rather than added/updated and/or 92 + * WGPEER_F_REPLACE_ALLOWEDIPS if all current allowed 93 + * IPs of this peer should be removed prior to adding 94 + * the list below and/or WGPEER_F_UPDATE_ONLY if the 95 + * peer should only be set if it already exists. 96 + * WGPEER_A_PRESHARED_KEY: len WG_KEY_LEN, all zeros to remove 97 + * WGPEER_A_ENDPOINT: struct sockaddr_in or struct sockaddr_in6 98 + * WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL: NLA_U16, 0 to disable 99 + * WGPEER_A_ALLOWEDIPS: NLA_NESTED 100 + * 0: NLA_NESTED 101 + * WGALLOWEDIP_A_FAMILY: NLA_U16 102 + * WGALLOWEDIP_A_IPADDR: struct in_addr or struct in6_addr 103 + * WGALLOWEDIP_A_CIDR_MASK: NLA_U8 104 + * 0: NLA_NESTED 105 + * ... 106 + * 0: NLA_NESTED 107 + * ... 108 + * ... 109 + * WGPEER_A_PROTOCOL_VERSION: NLA_U32, should not be set or used at 110 + * all by most users of this API, as the 111 + * most recent protocol will be used when 112 + * this is unset. Otherwise, must be set 113 + * to 1. 114 + * 0: NLA_NESTED 115 + * ... 116 + * ... 117 + * 118 + * It is possible that the amount of configuration data exceeds that of 119 + * the maximum message length accepted by the kernel. In that case, several 120 + * messages should be sent one after another, with each successive one 121 + * filling in information not contained in the prior. Note that if 122 + * WGDEVICE_F_REPLACE_PEERS is specified in the first message, it probably 123 + * should not be specified in fragments that come after, so that the list 124 + * of peers is only cleared the first time but appened after. Likewise for 125 + * peers, if WGPEER_F_REPLACE_ALLOWEDIPS is specified in the first message 126 + * of a peer, it likely should not be specified in subsequent fragments. 127 + * 128 + * If an error occurs, NLMSG_ERROR will reply containing an errno. 129 + */ 130 + 131 + #ifndef _WG_UAPI_WIREGUARD_H 132 + #define _WG_UAPI_WIREGUARD_H 133 + 134 + #define WG_GENL_NAME "wireguard" 135 + #define WG_GENL_VERSION 1 136 + 137 + #define WG_KEY_LEN 32 138 + 139 + enum wg_cmd { 140 + WG_CMD_GET_DEVICE, 141 + WG_CMD_SET_DEVICE, 142 + __WG_CMD_MAX 143 + }; 144 + #define WG_CMD_MAX (__WG_CMD_MAX - 1) 145 + 146 + enum wgdevice_flag { 147 + WGDEVICE_F_REPLACE_PEERS = 1U << 0, 148 + __WGDEVICE_F_ALL = WGDEVICE_F_REPLACE_PEERS 149 + }; 150 + enum wgdevice_attribute { 151 + WGDEVICE_A_UNSPEC, 152 + WGDEVICE_A_IFINDEX, 153 + WGDEVICE_A_IFNAME, 154 + WGDEVICE_A_PRIVATE_KEY, 155 + WGDEVICE_A_PUBLIC_KEY, 156 + WGDEVICE_A_FLAGS, 157 + WGDEVICE_A_LISTEN_PORT, 158 + WGDEVICE_A_FWMARK, 159 + WGDEVICE_A_PEERS, 160 + __WGDEVICE_A_LAST 161 + }; 162 + #define WGDEVICE_A_MAX (__WGDEVICE_A_LAST - 1) 163 + 164 + enum wgpeer_flag { 165 + WGPEER_F_REMOVE_ME = 1U << 0, 166 + WGPEER_F_REPLACE_ALLOWEDIPS = 1U << 1, 167 + WGPEER_F_UPDATE_ONLY = 1U << 2, 168 + __WGPEER_F_ALL = WGPEER_F_REMOVE_ME | WGPEER_F_REPLACE_ALLOWEDIPS | 169 + WGPEER_F_UPDATE_ONLY 170 + }; 171 + enum wgpeer_attribute { 172 + WGPEER_A_UNSPEC, 173 + WGPEER_A_PUBLIC_KEY, 174 + WGPEER_A_PRESHARED_KEY, 175 + WGPEER_A_FLAGS, 176 + WGPEER_A_ENDPOINT, 177 + WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, 178 + WGPEER_A_LAST_HANDSHAKE_TIME, 179 + WGPEER_A_RX_BYTES, 180 + WGPEER_A_TX_BYTES, 181 + WGPEER_A_ALLOWEDIPS, 182 + WGPEER_A_PROTOCOL_VERSION, 183 + __WGPEER_A_LAST 184 + }; 185 + #define WGPEER_A_MAX (__WGPEER_A_LAST - 1) 186 + 187 + enum wgallowedip_attribute { 188 + WGALLOWEDIP_A_UNSPEC, 189 + WGALLOWEDIP_A_FAMILY, 190 + WGALLOWEDIP_A_IPADDR, 191 + WGALLOWEDIP_A_CIDR_MASK, 192 + __WGALLOWEDIP_A_LAST 193 + }; 194 + #define WGALLOWEDIP_A_MAX (__WGALLOWEDIP_A_LAST - 1) 195 + 196 + #endif /* _WG_UAPI_WIREGUARD_H */
+537
tools/testing/selftests/wireguard/netns.sh
··· 1 + #!/bin/bash 2 + # SPDX-License-Identifier: GPL-2.0 3 + # 4 + # Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved. 5 + # 6 + # This script tests the below topology: 7 + # 8 + # ┌─────────────────────┐ ┌──────────────────────────────────┐ ┌─────────────────────┐ 9 + # │ $ns1 namespace │ │ $ns0 namespace │ │ $ns2 namespace │ 10 + # │ │ │ │ │ │ 11 + # │┌────────┐ │ │ ┌────────┐ │ │ ┌────────┐│ 12 + # ││ wg0 │───────────┼───┼────────────│ lo │────────────┼───┼───────────│ wg0 ││ 13 + # │├────────┴──────────┐│ │ ┌───────┴────────┴────────┐ │ │┌──────────┴────────┤│ 14 + # ││192.168.241.1/24 ││ │ │(ns1) (ns2) │ │ ││192.168.241.2/24 ││ 15 + # ││fd00::1/24 ││ │ │127.0.0.1:1 127.0.0.1:2│ │ ││fd00::2/24 ││ 16 + # │└───────────────────┘│ │ │[::]:1 [::]:2 │ │ │└───────────────────┘│ 17 + # └─────────────────────┘ │ └─────────────────────────┘ │ └─────────────────────┘ 18 + # └──────────────────────────────────┘ 19 + # 20 + # After the topology is prepared we run a series of TCP/UDP iperf3 tests between the 21 + # wireguard peers in $ns1 and $ns2. Note that $ns0 is the endpoint for the wg0 22 + # interfaces in $ns1 and $ns2. See https://www.wireguard.com/netns/ for further 23 + # details on how this is accomplished. 24 + set -e 25 + 26 + exec 3>&1 27 + export WG_HIDE_KEYS=never 28 + netns0="wg-test-$$-0" 29 + netns1="wg-test-$$-1" 30 + netns2="wg-test-$$-2" 31 + pretty() { echo -e "\x1b[32m\x1b[1m[+] ${1:+NS$1: }${2}\x1b[0m" >&3; } 32 + pp() { pretty "" "$*"; "$@"; } 33 + maybe_exec() { if [[ $BASHPID -eq $$ ]]; then "$@"; else exec "$@"; fi; } 34 + n0() { pretty 0 "$*"; maybe_exec ip netns exec $netns0 "$@"; } 35 + n1() { pretty 1 "$*"; maybe_exec ip netns exec $netns1 "$@"; } 36 + n2() { pretty 2 "$*"; maybe_exec ip netns exec $netns2 "$@"; } 37 + ip0() { pretty 0 "ip $*"; ip -n $netns0 "$@"; } 38 + ip1() { pretty 1 "ip $*"; ip -n $netns1 "$@"; } 39 + ip2() { pretty 2 "ip $*"; ip -n $netns2 "$@"; } 40 + sleep() { read -t "$1" -N 0 || true; } 41 + waitiperf() { pretty "${1//*-}" "wait for iperf:5201"; while [[ $(ss -N "$1" -tlp 'sport = 5201') != *iperf3* ]]; do sleep 0.1; done; } 42 + waitncatudp() { pretty "${1//*-}" "wait for udp:1111"; while [[ $(ss -N "$1" -ulp 'sport = 1111') != *ncat* ]]; do sleep 0.1; done; } 43 + waitncattcp() { pretty "${1//*-}" "wait for tcp:1111"; while [[ $(ss -N "$1" -tlp 'sport = 1111') != *ncat* ]]; do sleep 0.1; done; } 44 + waitiface() { pretty "${1//*-}" "wait for $2 to come up"; ip netns exec "$1" bash -c "while [[ \$(< \"/sys/class/net/$2/operstate\") != up ]]; do read -t .1 -N 0 || true; done;"; } 45 + 46 + cleanup() { 47 + set +e 48 + exec 2>/dev/null 49 + printf "$orig_message_cost" > /proc/sys/net/core/message_cost 50 + ip0 link del dev wg0 51 + ip1 link del dev wg0 52 + ip2 link del dev wg0 53 + local to_kill="$(ip netns pids $netns0) $(ip netns pids $netns1) $(ip netns pids $netns2)" 54 + [[ -n $to_kill ]] && kill $to_kill 55 + pp ip netns del $netns1 56 + pp ip netns del $netns2 57 + pp ip netns del $netns0 58 + exit 59 + } 60 + 61 + orig_message_cost="$(< /proc/sys/net/core/message_cost)" 62 + trap cleanup EXIT 63 + printf 0 > /proc/sys/net/core/message_cost 64 + 65 + ip netns del $netns0 2>/dev/null || true 66 + ip netns del $netns1 2>/dev/null || true 67 + ip netns del $netns2 2>/dev/null || true 68 + pp ip netns add $netns0 69 + pp ip netns add $netns1 70 + pp ip netns add $netns2 71 + ip0 link set up dev lo 72 + 73 + ip0 link add dev wg0 type wireguard 74 + ip0 link set wg0 netns $netns1 75 + ip0 link add dev wg0 type wireguard 76 + ip0 link set wg0 netns $netns2 77 + key1="$(pp wg genkey)" 78 + key2="$(pp wg genkey)" 79 + key3="$(pp wg genkey)" 80 + pub1="$(pp wg pubkey <<<"$key1")" 81 + pub2="$(pp wg pubkey <<<"$key2")" 82 + pub3="$(pp wg pubkey <<<"$key3")" 83 + psk="$(pp wg genpsk)" 84 + [[ -n $key1 && -n $key2 && -n $psk ]] 85 + 86 + configure_peers() { 87 + ip1 addr add 192.168.241.1/24 dev wg0 88 + ip1 addr add fd00::1/24 dev wg0 89 + 90 + ip2 addr add 192.168.241.2/24 dev wg0 91 + ip2 addr add fd00::2/24 dev wg0 92 + 93 + n1 wg set wg0 \ 94 + private-key <(echo "$key1") \ 95 + listen-port 1 \ 96 + peer "$pub2" \ 97 + preshared-key <(echo "$psk") \ 98 + allowed-ips 192.168.241.2/32,fd00::2/128 99 + n2 wg set wg0 \ 100 + private-key <(echo "$key2") \ 101 + listen-port 2 \ 102 + peer "$pub1" \ 103 + preshared-key <(echo "$psk") \ 104 + allowed-ips 192.168.241.1/32,fd00::1/128 105 + 106 + ip1 link set up dev wg0 107 + ip2 link set up dev wg0 108 + } 109 + configure_peers 110 + 111 + tests() { 112 + # Ping over IPv4 113 + n2 ping -c 10 -f -W 1 192.168.241.1 114 + n1 ping -c 10 -f -W 1 192.168.241.2 115 + 116 + # Ping over IPv6 117 + n2 ping6 -c 10 -f -W 1 fd00::1 118 + n1 ping6 -c 10 -f -W 1 fd00::2 119 + 120 + # TCP over IPv4 121 + n2 iperf3 -s -1 -B 192.168.241.2 & 122 + waitiperf $netns2 123 + n1 iperf3 -Z -t 3 -c 192.168.241.2 124 + 125 + # TCP over IPv6 126 + n1 iperf3 -s -1 -B fd00::1 & 127 + waitiperf $netns1 128 + n2 iperf3 -Z -t 3 -c fd00::1 129 + 130 + # UDP over IPv4 131 + n1 iperf3 -s -1 -B 192.168.241.1 & 132 + waitiperf $netns1 133 + n2 iperf3 -Z -t 3 -b 0 -u -c 192.168.241.1 134 + 135 + # UDP over IPv6 136 + n2 iperf3 -s -1 -B fd00::2 & 137 + waitiperf $netns2 138 + n1 iperf3 -Z -t 3 -b 0 -u -c fd00::2 139 + } 140 + 141 + [[ $(ip1 link show dev wg0) =~ mtu\ ([0-9]+) ]] && orig_mtu="${BASH_REMATCH[1]}" 142 + big_mtu=$(( 34816 - 1500 + $orig_mtu )) 143 + 144 + # Test using IPv4 as outer transport 145 + n1 wg set wg0 peer "$pub2" endpoint 127.0.0.1:2 146 + n2 wg set wg0 peer "$pub1" endpoint 127.0.0.1:1 147 + # Before calling tests, we first make sure that the stats counters and timestamper are working 148 + n2 ping -c 10 -f -W 1 192.168.241.1 149 + { read _; read _; read _; read rx_bytes _; read _; read tx_bytes _; } < <(ip2 -stats link show dev wg0) 150 + (( rx_bytes == 1372 && (tx_bytes == 1428 || tx_bytes == 1460) )) 151 + { read _; read _; read _; read rx_bytes _; read _; read tx_bytes _; } < <(ip1 -stats link show dev wg0) 152 + (( tx_bytes == 1372 && (rx_bytes == 1428 || rx_bytes == 1460) )) 153 + read _ rx_bytes tx_bytes < <(n2 wg show wg0 transfer) 154 + (( rx_bytes == 1372 && (tx_bytes == 1428 || tx_bytes == 1460) )) 155 + read _ rx_bytes tx_bytes < <(n1 wg show wg0 transfer) 156 + (( tx_bytes == 1372 && (rx_bytes == 1428 || rx_bytes == 1460) )) 157 + read _ timestamp < <(n1 wg show wg0 latest-handshakes) 158 + (( timestamp != 0 )) 159 + 160 + tests 161 + ip1 link set wg0 mtu $big_mtu 162 + ip2 link set wg0 mtu $big_mtu 163 + tests 164 + 165 + ip1 link set wg0 mtu $orig_mtu 166 + ip2 link set wg0 mtu $orig_mtu 167 + 168 + # Test using IPv6 as outer transport 169 + n1 wg set wg0 peer "$pub2" endpoint [::1]:2 170 + n2 wg set wg0 peer "$pub1" endpoint [::1]:1 171 + tests 172 + ip1 link set wg0 mtu $big_mtu 173 + ip2 link set wg0 mtu $big_mtu 174 + tests 175 + 176 + # Test that route MTUs work with the padding 177 + ip1 link set wg0 mtu 1300 178 + ip2 link set wg0 mtu 1300 179 + n1 wg set wg0 peer "$pub2" endpoint 127.0.0.1:2 180 + n2 wg set wg0 peer "$pub1" endpoint 127.0.0.1:1 181 + n0 iptables -A INPUT -m length --length 1360 -j DROP 182 + n1 ip route add 192.168.241.2/32 dev wg0 mtu 1299 183 + n2 ip route add 192.168.241.1/32 dev wg0 mtu 1299 184 + n2 ping -c 1 -W 1 -s 1269 192.168.241.1 185 + n2 ip route delete 192.168.241.1/32 dev wg0 mtu 1299 186 + n1 ip route delete 192.168.241.2/32 dev wg0 mtu 1299 187 + n0 iptables -F INPUT 188 + 189 + ip1 link set wg0 mtu $orig_mtu 190 + ip2 link set wg0 mtu $orig_mtu 191 + 192 + # Test using IPv4 that roaming works 193 + ip0 -4 addr del 127.0.0.1/8 dev lo 194 + ip0 -4 addr add 127.212.121.99/8 dev lo 195 + n1 wg set wg0 listen-port 9999 196 + n1 wg set wg0 peer "$pub2" endpoint 127.0.0.1:2 197 + n1 ping6 -W 1 -c 1 fd00::2 198 + [[ $(n2 wg show wg0 endpoints) == "$pub1 127.212.121.99:9999" ]] 199 + 200 + # Test using IPv6 that roaming works 201 + n1 wg set wg0 listen-port 9998 202 + n1 wg set wg0 peer "$pub2" endpoint [::1]:2 203 + n1 ping -W 1 -c 1 192.168.241.2 204 + [[ $(n2 wg show wg0 endpoints) == "$pub1 [::1]:9998" ]] 205 + 206 + # Test that crypto-RP filter works 207 + n1 wg set wg0 peer "$pub2" allowed-ips 192.168.241.0/24 208 + exec 4< <(n1 ncat -l -u -p 1111) 209 + ncat_pid=$! 210 + waitncatudp $netns1 211 + n2 ncat -u 192.168.241.1 1111 <<<"X" 212 + read -r -N 1 -t 1 out <&4 && [[ $out == "X" ]] 213 + kill $ncat_pid 214 + more_specific_key="$(pp wg genkey | pp wg pubkey)" 215 + n1 wg set wg0 peer "$more_specific_key" allowed-ips 192.168.241.2/32 216 + n2 wg set wg0 listen-port 9997 217 + exec 4< <(n1 ncat -l -u -p 1111) 218 + ncat_pid=$! 219 + waitncatudp $netns1 220 + n2 ncat -u 192.168.241.1 1111 <<<"X" 221 + ! read -r -N 1 -t 1 out <&4 || false 222 + kill $ncat_pid 223 + n1 wg set wg0 peer "$more_specific_key" remove 224 + [[ $(n1 wg show wg0 endpoints) == "$pub2 [::1]:9997" ]] 225 + 226 + # Test that we can change private keys keys and immediately handshake 227 + n1 wg set wg0 private-key <(echo "$key1") peer "$pub2" preshared-key <(echo "$psk") allowed-ips 192.168.241.2/32 endpoint 127.0.0.1:2 228 + n2 wg set wg0 private-key <(echo "$key2") listen-port 2 peer "$pub1" preshared-key <(echo "$psk") allowed-ips 192.168.241.1/32 229 + n1 ping -W 1 -c 1 192.168.241.2 230 + n1 wg set wg0 private-key <(echo "$key3") 231 + n2 wg set wg0 peer "$pub3" preshared-key <(echo "$psk") allowed-ips 192.168.241.1/32 peer "$pub1" remove 232 + n1 ping -W 1 -c 1 192.168.241.2 233 + 234 + ip1 link del wg0 235 + ip2 link del wg0 236 + 237 + # Test using NAT. We now change the topology to this: 238 + # ┌────────────────────────────────────────┐ ┌────────────────────────────────────────────────┐ ┌────────────────────────────────────────┐ 239 + # │ $ns1 namespace │ │ $ns0 namespace │ │ $ns2 namespace │ 240 + # │ │ │ │ │ │ 241 + # │ ┌─────┐ ┌─────┐ │ │ ┌──────┐ ┌──────┐ │ │ ┌─────┐ ┌─────┐ │ 242 + # │ │ wg0 │─────────────│vethc│───────────┼────┼────│vethrc│ │vethrs│──────────────┼─────┼──│veths│────────────│ wg0 │ │ 243 + # │ ├─────┴──────────┐ ├─────┴──────────┐│ │ ├──────┴─────────┐ ├──────┴────────────┐ │ │ ├─────┴──────────┐ ├─────┴──────────┐ │ 244 + # │ │192.168.241.1/24│ │192.168.1.100/24││ │ │192.168.1.1/24 │ │10.0.0.1/24 │ │ │ │10.0.0.100/24 │ │192.168.241.2/24│ │ 245 + # │ │fd00::1/24 │ │ ││ │ │ │ │SNAT:192.168.1.0/24│ │ │ │ │ │fd00::2/24 │ │ 246 + # │ └────────────────┘ └────────────────┘│ │ └────────────────┘ └───────────────────┘ │ │ └────────────────┘ └────────────────┘ │ 247 + # └────────────────────────────────────────┘ └────────────────────────────────────────────────┘ └────────────────────────────────────────┘ 248 + 249 + ip1 link add dev wg0 type wireguard 250 + ip2 link add dev wg0 type wireguard 251 + configure_peers 252 + 253 + ip0 link add vethrc type veth peer name vethc 254 + ip0 link add vethrs type veth peer name veths 255 + ip0 link set vethc netns $netns1 256 + ip0 link set veths netns $netns2 257 + ip0 link set vethrc up 258 + ip0 link set vethrs up 259 + ip0 addr add 192.168.1.1/24 dev vethrc 260 + ip0 addr add 10.0.0.1/24 dev vethrs 261 + ip1 addr add 192.168.1.100/24 dev vethc 262 + ip1 link set vethc up 263 + ip1 route add default via 192.168.1.1 264 + ip2 addr add 10.0.0.100/24 dev veths 265 + ip2 link set veths up 266 + waitiface $netns0 vethrc 267 + waitiface $netns0 vethrs 268 + waitiface $netns1 vethc 269 + waitiface $netns2 veths 270 + 271 + n0 bash -c 'printf 1 > /proc/sys/net/ipv4/ip_forward' 272 + n0 bash -c 'printf 2 > /proc/sys/net/netfilter/nf_conntrack_udp_timeout' 273 + n0 bash -c 'printf 2 > /proc/sys/net/netfilter/nf_conntrack_udp_timeout_stream' 274 + n0 iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -d 10.0.0.0/24 -j SNAT --to 10.0.0.1 275 + 276 + n1 wg set wg0 peer "$pub2" endpoint 10.0.0.100:2 persistent-keepalive 1 277 + n1 ping -W 1 -c 1 192.168.241.2 278 + n2 ping -W 1 -c 1 192.168.241.1 279 + [[ $(n2 wg show wg0 endpoints) == "$pub1 10.0.0.1:1" ]] 280 + # Demonstrate n2 can still send packets to n1, since persistent-keepalive will prevent connection tracking entry from expiring (to see entries: `n0 conntrack -L`). 281 + pp sleep 3 282 + n2 ping -W 1 -c 1 192.168.241.1 283 + n1 wg set wg0 peer "$pub2" persistent-keepalive 0 284 + 285 + # Do a wg-quick(8)-style policy routing for the default route, making sure vethc has a v6 address to tease out bugs. 286 + ip1 -6 addr add fc00::9/96 dev vethc 287 + ip1 -6 route add default via fc00::1 288 + ip2 -4 addr add 192.168.99.7/32 dev wg0 289 + ip2 -6 addr add abab::1111/128 dev wg0 290 + n1 wg set wg0 fwmark 51820 peer "$pub2" allowed-ips 192.168.99.7,abab::1111 291 + ip1 -6 route add default dev wg0 table 51820 292 + ip1 -6 rule add not fwmark 51820 table 51820 293 + ip1 -6 rule add table main suppress_prefixlength 0 294 + ip1 -4 route add default dev wg0 table 51820 295 + ip1 -4 rule add not fwmark 51820 table 51820 296 + ip1 -4 rule add table main suppress_prefixlength 0 297 + # suppress_prefixlength only got added in 3.12, and we want to support 3.10+. 298 + if [[ $(ip1 -4 rule show all) == *suppress_prefixlength* ]]; then 299 + # Flood the pings instead of sending just one, to trigger routing table reference counting bugs. 300 + n1 ping -W 1 -c 100 -f 192.168.99.7 301 + n1 ping -W 1 -c 100 -f abab::1111 302 + fi 303 + 304 + n0 iptables -t nat -F 305 + ip0 link del vethrc 306 + ip0 link del vethrs 307 + ip1 link del wg0 308 + ip2 link del wg0 309 + 310 + # Test that saddr routing is sticky but not too sticky, changing to this topology: 311 + # ┌────────────────────────────────────────┐ ┌────────────────────────────────────────┐ 312 + # │ $ns1 namespace │ │ $ns2 namespace │ 313 + # │ │ │ │ 314 + # │ ┌─────┐ ┌─────┐ │ │ ┌─────┐ ┌─────┐ │ 315 + # │ │ wg0 │─────────────│veth1│───────────┼────┼──│veth2│────────────│ wg0 │ │ 316 + # │ ├─────┴──────────┐ ├─────┴──────────┐│ │ ├─────┴──────────┐ ├─────┴──────────┐ │ 317 + # │ │192.168.241.1/24│ │10.0.0.1/24 ││ │ │10.0.0.2/24 │ │192.168.241.2/24│ │ 318 + # │ │fd00::1/24 │ │fd00:aa::1/96 ││ │ │fd00:aa::2/96 │ │fd00::2/24 │ │ 319 + # │ └────────────────┘ └────────────────┘│ │ └────────────────┘ └────────────────┘ │ 320 + # └────────────────────────────────────────┘ └────────────────────────────────────────┘ 321 + 322 + ip1 link add dev wg0 type wireguard 323 + ip2 link add dev wg0 type wireguard 324 + configure_peers 325 + ip1 link add veth1 type veth peer name veth2 326 + ip1 link set veth2 netns $netns2 327 + n1 bash -c 'printf 0 > /proc/sys/net/ipv6/conf/all/accept_dad' 328 + n2 bash -c 'printf 0 > /proc/sys/net/ipv6/conf/all/accept_dad' 329 + n1 bash -c 'printf 0 > /proc/sys/net/ipv6/conf/veth1/accept_dad' 330 + n2 bash -c 'printf 0 > /proc/sys/net/ipv6/conf/veth2/accept_dad' 331 + n1 bash -c 'printf 1 > /proc/sys/net/ipv4/conf/veth1/promote_secondaries' 332 + 333 + # First we check that we aren't overly sticky and can fall over to new IPs when old ones are removed 334 + ip1 addr add 10.0.0.1/24 dev veth1 335 + ip1 addr add fd00:aa::1/96 dev veth1 336 + ip2 addr add 10.0.0.2/24 dev veth2 337 + ip2 addr add fd00:aa::2/96 dev veth2 338 + ip1 link set veth1 up 339 + ip2 link set veth2 up 340 + waitiface $netns1 veth1 341 + waitiface $netns2 veth2 342 + n1 wg set wg0 peer "$pub2" endpoint 10.0.0.2:2 343 + n1 ping -W 1 -c 1 192.168.241.2 344 + ip1 addr add 10.0.0.10/24 dev veth1 345 + ip1 addr del 10.0.0.1/24 dev veth1 346 + n1 ping -W 1 -c 1 192.168.241.2 347 + n1 wg set wg0 peer "$pub2" endpoint [fd00:aa::2]:2 348 + n1 ping -W 1 -c 1 192.168.241.2 349 + ip1 addr add fd00:aa::10/96 dev veth1 350 + ip1 addr del fd00:aa::1/96 dev veth1 351 + n1 ping -W 1 -c 1 192.168.241.2 352 + 353 + # Now we show that we can successfully do reply to sender routing 354 + ip1 link set veth1 down 355 + ip2 link set veth2 down 356 + ip1 addr flush dev veth1 357 + ip2 addr flush dev veth2 358 + ip1 addr add 10.0.0.1/24 dev veth1 359 + ip1 addr add 10.0.0.2/24 dev veth1 360 + ip1 addr add fd00:aa::1/96 dev veth1 361 + ip1 addr add fd00:aa::2/96 dev veth1 362 + ip2 addr add 10.0.0.3/24 dev veth2 363 + ip2 addr add fd00:aa::3/96 dev veth2 364 + ip1 link set veth1 up 365 + ip2 link set veth2 up 366 + waitiface $netns1 veth1 367 + waitiface $netns2 veth2 368 + n2 wg set wg0 peer "$pub1" endpoint 10.0.0.1:1 369 + n2 ping -W 1 -c 1 192.168.241.1 370 + [[ $(n2 wg show wg0 endpoints) == "$pub1 10.0.0.1:1" ]] 371 + n2 wg set wg0 peer "$pub1" endpoint [fd00:aa::1]:1 372 + n2 ping -W 1 -c 1 192.168.241.1 373 + [[ $(n2 wg show wg0 endpoints) == "$pub1 [fd00:aa::1]:1" ]] 374 + n2 wg set wg0 peer "$pub1" endpoint 10.0.0.2:1 375 + n2 ping -W 1 -c 1 192.168.241.1 376 + [[ $(n2 wg show wg0 endpoints) == "$pub1 10.0.0.2:1" ]] 377 + n2 wg set wg0 peer "$pub1" endpoint [fd00:aa::2]:1 378 + n2 ping -W 1 -c 1 192.168.241.1 379 + [[ $(n2 wg show wg0 endpoints) == "$pub1 [fd00:aa::2]:1" ]] 380 + 381 + # What happens if the inbound destination address belongs to a different interface as the default route? 382 + ip1 link add dummy0 type dummy 383 + ip1 addr add 10.50.0.1/24 dev dummy0 384 + ip1 link set dummy0 up 385 + ip2 route add 10.50.0.0/24 dev veth2 386 + n2 wg set wg0 peer "$pub1" endpoint 10.50.0.1:1 387 + n2 ping -W 1 -c 1 192.168.241.1 388 + [[ $(n2 wg show wg0 endpoints) == "$pub1 10.50.0.1:1" ]] 389 + 390 + ip1 link del dummy0 391 + ip1 addr flush dev veth1 392 + ip2 addr flush dev veth2 393 + ip1 route flush dev veth1 394 + ip2 route flush dev veth2 395 + 396 + # Now we see what happens if another interface route takes precedence over an ongoing one 397 + ip1 link add veth3 type veth peer name veth4 398 + ip1 link set veth4 netns $netns2 399 + ip1 addr add 10.0.0.1/24 dev veth1 400 + ip2 addr add 10.0.0.2/24 dev veth2 401 + ip1 addr add 10.0.0.3/24 dev veth3 402 + ip1 link set veth1 up 403 + ip2 link set veth2 up 404 + ip1 link set veth3 up 405 + ip2 link set veth4 up 406 + waitiface $netns1 veth1 407 + waitiface $netns2 veth2 408 + waitiface $netns1 veth3 409 + waitiface $netns2 veth4 410 + ip1 route flush dev veth1 411 + ip1 route flush dev veth3 412 + ip1 route add 10.0.0.0/24 dev veth1 src 10.0.0.1 metric 2 413 + n1 wg set wg0 peer "$pub2" endpoint 10.0.0.2:2 414 + n1 ping -W 1 -c 1 192.168.241.2 415 + [[ $(n2 wg show wg0 endpoints) == "$pub1 10.0.0.1:1" ]] 416 + ip1 route add 10.0.0.0/24 dev veth3 src 10.0.0.3 metric 1 417 + n1 bash -c 'printf 0 > /proc/sys/net/ipv4/conf/veth1/rp_filter' 418 + n2 bash -c 'printf 0 > /proc/sys/net/ipv4/conf/veth4/rp_filter' 419 + n1 bash -c 'printf 0 > /proc/sys/net/ipv4/conf/all/rp_filter' 420 + n2 bash -c 'printf 0 > /proc/sys/net/ipv4/conf/all/rp_filter' 421 + n1 ping -W 1 -c 1 192.168.241.2 422 + [[ $(n2 wg show wg0 endpoints) == "$pub1 10.0.0.3:1" ]] 423 + 424 + ip1 link del veth1 425 + ip1 link del veth3 426 + ip1 link del wg0 427 + ip2 link del wg0 428 + 429 + # We test that Netlink/IPC is working properly by doing things that usually cause split responses 430 + ip0 link add dev wg0 type wireguard 431 + config=( "[Interface]" "PrivateKey=$(wg genkey)" "[Peer]" "PublicKey=$(wg genkey)" ) 432 + for a in {1..255}; do 433 + for b in {0..255}; do 434 + config+=( "AllowedIPs=$a.$b.0.0/16,$a::$b/128" ) 435 + done 436 + done 437 + n0 wg setconf wg0 <(printf '%s\n' "${config[@]}") 438 + i=0 439 + for ip in $(n0 wg show wg0 allowed-ips); do 440 + ((++i)) 441 + done 442 + ((i == 255*256*2+1)) 443 + ip0 link del wg0 444 + ip0 link add dev wg0 type wireguard 445 + config=( "[Interface]" "PrivateKey=$(wg genkey)" ) 446 + for a in {1..40}; do 447 + config+=( "[Peer]" "PublicKey=$(wg genkey)" ) 448 + for b in {1..52}; do 449 + config+=( "AllowedIPs=$a.$b.0.0/16" ) 450 + done 451 + done 452 + n0 wg setconf wg0 <(printf '%s\n' "${config[@]}") 453 + i=0 454 + while read -r line; do 455 + j=0 456 + for ip in $line; do 457 + ((++j)) 458 + done 459 + ((j == 53)) 460 + ((++i)) 461 + done < <(n0 wg show wg0 allowed-ips) 462 + ((i == 40)) 463 + ip0 link del wg0 464 + ip0 link add wg0 type wireguard 465 + config=( ) 466 + for i in {1..29}; do 467 + config+=( "[Peer]" "PublicKey=$(wg genkey)" ) 468 + done 469 + config+=( "[Peer]" "PublicKey=$(wg genkey)" "AllowedIPs=255.2.3.4/32,abcd::255/128" ) 470 + n0 wg setconf wg0 <(printf '%s\n' "${config[@]}") 471 + n0 wg showconf wg0 > /dev/null 472 + ip0 link del wg0 473 + 474 + allowedips=( ) 475 + for i in {1..197}; do 476 + allowedips+=( abcd::$i ) 477 + done 478 + saved_ifs="$IFS" 479 + IFS=, 480 + allowedips="${allowedips[*]}" 481 + IFS="$saved_ifs" 482 + ip0 link add wg0 type wireguard 483 + n0 wg set wg0 peer "$pub1" 484 + n0 wg set wg0 peer "$pub2" allowed-ips "$allowedips" 485 + { 486 + read -r pub allowedips 487 + [[ $pub == "$pub1" && $allowedips == "(none)" ]] 488 + read -r pub allowedips 489 + [[ $pub == "$pub2" ]] 490 + i=0 491 + for _ in $allowedips; do 492 + ((++i)) 493 + done 494 + ((i == 197)) 495 + } < <(n0 wg show wg0 allowed-ips) 496 + ip0 link del wg0 497 + 498 + ! n0 wg show doesnotexist || false 499 + 500 + ip0 link add wg0 type wireguard 501 + n0 wg set wg0 private-key <(echo "$key1") peer "$pub2" preshared-key <(echo "$psk") 502 + [[ $(n0 wg show wg0 private-key) == "$key1" ]] 503 + [[ $(n0 wg show wg0 preshared-keys) == "$pub2 $psk" ]] 504 + n0 wg set wg0 private-key /dev/null peer "$pub2" preshared-key /dev/null 505 + [[ $(n0 wg show wg0 private-key) == "(none)" ]] 506 + [[ $(n0 wg show wg0 preshared-keys) == "$pub2 (none)" ]] 507 + n0 wg set wg0 peer "$pub2" 508 + n0 wg set wg0 private-key <(echo "$key2") 509 + [[ $(n0 wg show wg0 public-key) == "$pub2" ]] 510 + [[ -z $(n0 wg show wg0 peers) ]] 511 + n0 wg set wg0 peer "$pub2" 512 + [[ -z $(n0 wg show wg0 peers) ]] 513 + n0 wg set wg0 private-key <(echo "$key1") 514 + n0 wg set wg0 peer "$pub2" 515 + [[ $(n0 wg show wg0 peers) == "$pub2" ]] 516 + n0 wg set wg0 private-key <(echo "/${key1:1}") 517 + [[ $(n0 wg show wg0 private-key) == "+${key1:1}" ]] 518 + n0 wg set wg0 peer "$pub2" allowed-ips 0.0.0.0/0,10.0.0.0/8,100.0.0.0/10,172.16.0.0/12,192.168.0.0/16 519 + n0 wg set wg0 peer "$pub2" allowed-ips 0.0.0.0/0 520 + n0 wg set wg0 peer "$pub2" allowed-ips ::/0,1700::/111,5000::/4,e000::/37,9000::/75 521 + n0 wg set wg0 peer "$pub2" allowed-ips ::/0 522 + ip0 link del wg0 523 + 524 + declare -A objects 525 + while read -t 0.1 -r line 2>/dev/null || [[ $? -ne 142 ]]; do 526 + [[ $line =~ .*(wg[0-9]+:\ [A-Z][a-z]+\ [0-9]+)\ .*(created|destroyed).* ]] || continue 527 + objects["${BASH_REMATCH[1]}"]+="${BASH_REMATCH[2]}" 528 + done < /dev/kmsg 529 + alldeleted=1 530 + for object in "${!objects[@]}"; do 531 + if [[ ${objects["$object"]} != *createddestroyed ]]; then 532 + echo "Error: $object: merely ${objects["$object"]}" >&3 533 + alldeleted=0 534 + fi 535 + done 536 + [[ $alldeleted -eq 1 ]] 537 + pretty "" "Objects that were created were also destroyed."