Go Implementation of WireGuard

Go Implementation of WireGuard

This is an implementation of WireGuard in Go.

Usage

Most Linux kernel WireGuard users are used to adding an interface with ip link add wg0 type wireguard. With wireguard-go, instead simply run:

$ wireguard-go wg0

This will create an interface and fork into the background. To remove the interface, use the usual ip link del wg0, or if your system does not support removing interfaces directly, you may instead remove the control socket via rm -f /var/run/wireguard/wg0.sock, which will result in wireguard-go shutting down.

To run wireguard-go without forking to the background, pass -f or --foreground:

$ wireguard-go -f wg0

When an interface is running, you may use wg(8) to configure it, as well as the usual ip(8) and ifconfig(8) commands.

To run with more logging you may set the environment variable LOG_LEVEL=debug.

Platforms

Linux

This will run on Linux; however you should instead use the kernel module, which is faster and better integrated into the OS. See the installation page for instructions.

macOS

This runs on macOS using the utun driver. It does not yet support sticky sockets, and won't support fwmarks because of Darwin limitations. Since the utun driver cannot have arbitrary interface names, you must either use utun[0-9]+ for an explicit interface name or utun to have the kernel select one for you. If you choose utun as the interface name, and the environment variable WG_TUN_NAME_FILE is defined, then the actual name of the interface chosen by the kernel is written to the file specified by that variable.

Windows

This runs on Windows, but you should instead use it from the more fully featured Windows app, which uses this as a module.

FreeBSD

This will run on FreeBSD. It does not yet support sticky sockets. Fwmark is mapped to SO_USER_COOKIE.

OpenBSD

This will run on OpenBSD. It does not yet support sticky sockets. Fwmark is mapped to SO_RTABLE. Since the tun driver cannot have arbitrary interface names, you must either use tun[0-9]+ for an explicit interface name or tun to have the program select one for you. If you choose tun as the interface name, and the environment variable WG_TUN_NAME_FILE is defined, then the actual name of the interface chosen by the kernel is written to the file specified by that variable.

Building

This requires an installation of go ≥ 1.17.

$ git clone https://git.zx2c4.com/wireguard-go
$ cd wireguard-go
$ make

License

Copyright (C) 2017-2021 WireGuard LLC. All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Owner
WireGuard
Mirror of various WireGuard-related projects. See https://www.wireguard.com/repositories/ for official repositories.
WireGuard
Comments
  • Make device.Peer safe for atomic access on 32-bit.

    Make device.Peer safe for atomic access on 32-bit.

    All atomic access must be aligned to 64 bits, even on 32-bit platforms. Go promises that the start of allocated structs is aligned to 64 bits. So, place the atomically-accessed things first in the struct so that they benefit from that alignment.

    As a side bonus, it cleanly separates fields that are accessed by atomic ops, and those that should be accessed under mu.

    Also adds a test that will fail consistently on 32-bit platforms if the struct ever changes again to violate the rules. This is likely not needed because unaligned access crashes reliably, but this will reliably fail even if tests accidentally pass due to lucky alignment.

    Signed-Off-By: David Anderson [email protected]

  • Fix a bug found on the centos7.5.1804 platform

    Fix a bug found on the centos7.5.1804 platform

    If the response message is exactly same to the fscanf()'s second parameter, the fscanf() in the userspace_set_device() cannot get the response and cannot return. This fix has been verified using my environment(CentOS Linux release 7.5.1804 (Core)).

  • Replace direct syscalls on macOS

    Replace direct syscalls on macOS

    This PR replaces all uses of direct syscalls (i.e. unix.Syscall(unix.SYS_*, ...)) on macOS by the respective functionality from the golang.org/x/sys/unix package using macOS libSystem. The support for direct syscalls on macOS is discouraged and was recently removed from golang.org/x/sys/unix, see https://golang.org/cl/250437 (golang/sys@6fcdbc0bbc04dcd9e7dc145879ceaf9bf1c6ff03). This broke the build of wireguard-go against the latest golang.org/x/sys/unix version, as reported in golang/go#41868.

    See individual commit messages for more details.

    Tested on macOS 10.15 against a wireguard server running on Ubuntu Linux 20.04.

    /cc @bradfitz

  • Add nil check before convert typed error back

    Add nil check before convert typed error back

    Since errors.As(err, target) returns false when err is nil, which cause status set to 1 when no error occurs for IpcGetOperation and IpcSetOperation.

    Should be able to fix #17

    Signed-off-by: Wenxuan Zhao [email protected]

  • device: separate logging for floods and replay attacks

    device: separate logging for floods and replay attacks

    Error messages being printed were about floods, but actually what was being detected was a potential "replay attack", ie. a duplicate copy of an incoming handshake. Let's print two separate log messages to differentiate them.

    Signed-off-by: Avery Pennarun [email protected]

  • Add possible to send packets with no IP header if allowed any IP on the device

    Add possible to send packets with no IP header if allowed any IP on the device

    Usecase

    1. Create a WG device wg-0
    2. Set to wg-0 property to allow any IP.
    3. Send packet to wg-0 with no IP header.

    Actual: the device will do nothing. In logs will log the text "Received packet with unknown IP version". Expected: the device will send a packet if the device allows any IP.

  • add ability to specify go build flags via make

    add ability to specify go build flags via make

    allow adding additional inline flags to go build e.g.:

    make GOBUILDFLAGS="-ldflags='-s -w' -trimpath"
    

    results in having the go build command modified to:

    go build -ldflags='-s -w' -trimpath -v -o wireguard-go ...
    
  • Do not hide request to reboot and pass that mark to higher level application

    Do not hide request to reboot and pass that mark to higher level application

    A wintun.dll installs a driver and WindowsOS may indicate that it needs a reboot to complete driver instalation.

    The needReboot mark was lost and no application did not received that indication. Solution is to extend the call, used by the CreateTUNWithRequestedGUID() function with additional return value indicating that. And leave generic interface function CreateTUN() as is.

    Signed-off-by: Antanas Gadeikis [email protected]

  • device: wait for routines to stop before removing peers

    device: wait for routines to stop before removing peers

    Peers are currently removed after Device's goroutines are signaled to stop, but without waiting for them to actually do so, which is racy.

    For example, RoutineHandshake may be in Peer.SendKeepalive when the corresponding peer is removed, which closes its nonce channel. This causes a send on a closed channel, as observed in tailscale/tailscale#487.

    This patch seems to be the correct synchronizing action: Peer's goroutines are receivers and handle channel closure gracefully, so Device's goroutines are the ones that should be fully stopped first.

  • tun/netstack: bump to latest gvisor

    tun/netstack: bump to latest gvisor

    The motivation is to build with go1.19. It needs https://github.com/google/gvisor/commit/99325baf5dfc23e54aea3acf8aaabb1996f5338e

    gvisor.dev/gvisor/pkg/tcpip/buffer is no longer available, so it needs to refactor a bit.

    This PR replaces #47

  • tun/netstack: Update wireguard-go

    tun/netstack: Update wireguard-go

    As discussed on IRC:

    The first commit updates wireguard-go as used in the sub-module wireguard-go/tun/netstack and fixes all callsites for netip.AddrFromSlice (which has changed its signature recently). The second commit adds an error check a linter I had running noticed.

    Please let me know if there's anything else I can/need to do to get this merged. Thanks!

    Cheers, fd0

  • device: make allowedips generic

    device: make allowedips generic

    最新发布的wireguard-go0.0.20220316至wireguard-go0.0.20210212版本发现一个问题,wg-quick up wg0 启动卡在wg setconf wg0 /dev/fd/63,wireguard-go0.0.20201118版本测试正常。微信截图_20221211191458

  • conn, device, tun: implement vectorized I/O on Linux

    conn, device, tun: implement vectorized I/O on Linux

    This commit changes the tun.Device and conn.Bind interfaces to accept packet vectors for reading and writing. Internal plumbing between these interfaces now passes a vector of packets. Vectors move untouched between these interfaces, i.e. if 128 packets are received from conn.Bind.Read(), 128 packets are passed to tun.Device.Write(). There is no internal buffering.

    Platform-specific implementations of tun.Device have been updated to the new tun.Device interface, but only Linux supports passing more than one packet for now. The Linux tun.Device implementation accomplishes this via TSO and GRO, which is made possible by virtio extensions in the TUN driver. Linux TUN offloading can be disabled by setting the WG_DISABLE_OFFLOAD environment variable to 1.

    conn.LinuxSocketEndpoint has been deleted in favor of a collapsed conn.StdNetBind. conn.StdNetBind makes use of recvmmsg() and sendmmsg() on Linux. All platforms fall under conn.StdNetBind, except for Windows, which remains in conn.WinRingBind. Sticky sockets support has been refactored as part of this work to eventually be applicable on platforms other than just Linux, however Linux remains the sole platform that fully implements it. The conn.Bind UDP socket buffer is now being sized to 7MB, whereas it was previously inheriting the system default.

    device.Keypairs locking has been simplified from a RWMutex + atomic to just a Mutex.

    Signed-off-by: Jordan Whited [email protected] Signed-off-by: James Tucker [email protected] Co-authored-by: James Tucker [email protected]

  • [bind] Dont override source address of wg packets

    [bind] Dont override source address of wg packets

    This PR represents a patch I'm working with locally to support a particular use case. I'm creating this upstream to prompt discussion on if this patch should be the upstream functionality.

    I'm trying to create a wireguard tunnel which can seamlessly switch between underlying interfaces (WIFI, ethernet, etc) without having to restart the VPN. This works perfectly well with the kernel implementaiton. When Ethernet goes down (or the routing table is changed to prioritize Wifi), packets for wireguard are sent over the new interface, with the source address correctly set to the configured address of the new interface. The destination will receive the NAT'ed address and be about to route a response back.

    However, in the wireguard-go userspace implementation, the modified code here sets the packets source address to be cached in some way to the initial interface which packets are routed through. Therefore, when the routing table changes to send packets through a different address, the source address is invalid and the connection drops.

    Please let me know if there's anything I'm misunderstanding here. At the very least, this represents a potentially undesirable difference in functionality between the userspace and kernel implementations.

  • device: optimize Peer.String even more so

    device: optimize Peer.String even more so

    name          old time/op    new time/op    delta
    PeerString-8    49.5ns ±17%    32.6ns ±17%  -34.09%  (p=0.000 n=10+10)
    
    name          old alloc/op   new alloc/op   delta
    PeerString-8     24.0B ± 0%     24.0B ± 0%     ~     (all equal)
    
    name          old allocs/op  new allocs/op  delta
    PeerString-8      1.00 ± 0%      1.00 ± 0%     ~     (all equal)
    

    Signed-off-by: Alexander Yastrebov [email protected]

  • Replace mix of atomics and rwmutex with mutex around key material

    Replace mix of atomics and rwmutex with mutex around key material

    This reduces the overhead of various code paths as there are less pipeline delays and more code can be inlined. The mutex fast path is a single atomic operation, and this mutex is never held for very long.

    Microbenchmark results in each commit show no micro-scale difference, macro scale tests demonstrate a slight speed up, though well within the noise of other external effects: small improvement in arm64 test on t4g.nano from 642mbps to 646mbps, x64 test on m6i.xlarge from 975mbps to 1.02gbps.

Related tags
A fork of the simple WireGuard VPN server GUI community maintained
A fork of the simple WireGuard VPN server GUI community maintained

Subspace - A simple WireGuard VPN server GUI Subspace - A simple WireGuard VPN server GUI Slack Screenshots Features Contributing Setup 1. Get a serve

Dec 25, 2022
A flexible configuration manager for Wireguard networks
A flexible configuration manager for Wireguard networks

Drago A flexible configuration manager for WireGuard networks Drago is a flexible configuration manager for WireGuard networks which is designed to ma

Jan 7, 2023
Simple Web based configuration generator for WireGuard. Demo:
Simple Web based configuration generator for WireGuard. Demo:

Wg Gen Web Simple Web based configuration generator for WireGuard. Why another one ? All WireGuard UI implementations are trying to manage the service

Jan 1, 2023
The easiest, most secure way to use WireGuard and 2FA.

This repository contains all the open source Tailscale client code and the tailscaled daemon and tailscale CLI tool. The tailscaled daemon runs primarily on Linux; it also works to varying degrees on FreeBSD, OpenBSD, Darwin, and Windows.

Jan 8, 2023
Connect your devices into a single private WireGuard®-based mesh network.

Wiretrustee A WireGuard®-based mesh network that connects your devices into a single private network. Why using Wiretrustee? Connect multiple devices

Dec 31, 2022
An userspace SORACOM Arc client powered by wireguard-go

soratun An easy-to-use, userspace SORACOM Arc client powered by wireguard-go. For deploying and scaling Linux servers/Raspberry Pi devices working wit

Jun 2, 2022
A Wireguard VPN Server Manager and API to add and remove clients

Wireguard Manager And API A manager and API to add, remove clients as well as other features such as an auto reapplier which deletes and adds back a c

Dec 22, 2022
Layer2 version of wireguard with Floyd Warshall implement in go.

Etherguard 中文版README A Full Mesh Layer2 VPN based on wireguard-go OSPF can find best route based on it's cost. But sometimes the lentancy are differen

Dec 29, 2022
Magic util that "bridges" Wireguard with OpenVPN without a TUN/TAP interface

wg-ovpn Magic util that "bridges" Wireguard with OpenVPN without a TUN/TAP interface Warning: really ugly and unstable code! Building Obtain latest so

Sep 27, 2022
Mount your podman container into WireGuard networks on spawn

wg-pod A tool to quickly join your podman container/pod into a WireGuard network. Explanation wg-pod wires up the tools ip,route,wg and podman. It cre

Aug 14, 2022
A HTTP proxy server tunnelling through wireguard

wg-http-proxy This project hacks together the excellent https://github.com/elazarl/goproxy and https://git.zx2c4.com/wireguard-go into an HTTP proxy s

Dec 30, 2022
NAT puncher for Wireguard mesh networking.

natpunch-go This is a NAT hole punching tool designed for creating Wireguard mesh networks. It was inspired by Tailscale and informed by this example.

Dec 12, 2022
generate Wireguard keypairs with a given prefix string

wireguard-vanity-address Generate Wireguard keypairs with a given prefix string. The Wireguard VPN uses Curve25519 keypairs, and displays the Base64-e

Nov 9, 2022
udppunch hole for wireguard

udppunch udp punch for wireguard, inspired by natpunch-go usage server side ./punch-server-linux-amd64 -port 19993 client side make sure wireguard is

Nov 24, 2022
A go implementation of the STUN client (RFC 3489 and RFC 5389)

go-stun go-stun is a STUN (RFC 3489, 5389) client implementation in golang (a.k.a. UDP hole punching). RFC 3489: STUN - Simple Traversal of User Datag

Jan 5, 2023
A QUIC implementation in pure go
A QUIC implementation in pure go

A QUIC implementation in pure Go quic-go is an implementation of the QUIC protocol in Go. It implements the IETF QUIC draft-29 and draft-32. Version c

Jan 9, 2023
Fast RFC 5389 STUN implementation in go

STUN Package stun implements Session Traversal Utilities for NAT (STUN) [RFC5389] protocol and client with no external dependencies and zero allocatio

Nov 28, 2022
Pure Go implementation of the WebRTC API
Pure Go implementation of the WebRTC API

Pion WebRTC A pure Go implementation of the WebRTC API New Release Pion WebRTC v3.0.0 has been released! See the release notes to learn about new feat

Jan 1, 2023
A LWM2M Client and Server implementation (For Go/Golang)

Betwixt - A LWM2M Client and Server in Go Betwixt is a Lightweight M2M implementation written in Go OMA Lightweight M2M is a protocol from the Open Mo

Dec 23, 2022