Convert Figma logo to code with AI

WireGuard logowireguard-go

Mirror only. Official repository is at https://git.zx2c4.com/wireguard-go

3,028
1,017
3,028
24

Top Related Projects

13,863

A Quantum-Safe Secure Tunnel based on QPP, KCP, FEC, and N:M multiplexing.

A Rust port of shadowsocks

A platform for building proxies to bypass network restrictions.

24,231

Xray, Penetrates Everything. Also the best v2ray-core, with XTLS support. Fully compatible configuration.

10,618

OpenVPN is an open source VPN daemon

6,175

Peer-to-peer VPN

Quick Overview

WireGuard-go is a Go implementation of the WireGuard secure network tunnel protocol. It provides a fast, modern, and secure VPN solution that aims to be simpler and more performant than traditional VPN protocols like OpenVPN or IPSec.

Pros

  • Simple and easy to configure compared to other VPN solutions
  • Offers strong encryption and modern cryptographic principles
  • Cross-platform compatibility (works on various operating systems)
  • Lightweight and efficient, with minimal impact on battery life for mobile devices

Cons

  • Relatively new compared to more established VPN protocols
  • May require kernel updates on some systems for optimal performance
  • Limited advanced features compared to some traditional VPN solutions
  • Potential for compatibility issues with certain network configurations

Code Examples

  1. Creating a WireGuard configuration:
package main

import (
    "net"
    "golang.zx2c4.com/wireguard/device"
    "golang.zx2c4.com/wireguard/tun"
)

func main() {
    tun, _ := tun.CreateTUN("wg0", 1420)
    device := device.NewDevice(tun, conn, logger)
    
    // Configure the device
    cfg := device.IpcSetOperation{
        PrivateKey: [32]byte{...},
        ListenPort: 51820,
    }
    device.IpcSet(cfg)
}
  1. Adding a peer to the WireGuard configuration:
peer := device.IpcSetOperation{
    Peer: []device.IpcPeerConfig{
        {
            PublicKey:    [32]byte{...},
            AllowedIPs:   []net.IPNet{{IP: net.ParseIP("10.0.0.2"), Mask: net.CIDRMask(32, 32)}},
            Endpoint:     &net.UDPAddr{IP: net.ParseIP("192.168.1.100"), Port: 51820},
        },
    },
}
device.IpcSet(peer)
  1. Starting the WireGuard device:
err := device.Up()
if err != nil {
    log.Fatalf("Failed to bring up device: %v", err)
}
defer device.Close()

Getting Started

To use WireGuard-go in your Go project:

  1. Install the WireGuard-go package:

    go get -u golang.zx2c4.com/wireguard
    
  2. Import the necessary packages in your Go code:

    import (
        "golang.zx2c4.com/wireguard/device"
        "golang.zx2c4.com/wireguard/tun"
    )
    
  3. Create a TUN device and initialize a WireGuard device as shown in the code examples above.

  4. Configure the device with your desired settings and add peers as needed.

  5. Bring up the device and handle any errors.

Remember to handle proper error checking and implement appropriate logging in your production code.

Competitor Comparisons

13,863

A Quantum-Safe Secure Tunnel based on QPP, KCP, FEC, and N:M multiplexing.

Pros of kcptun

  • Implements the KCP protocol, which can improve network performance in high-latency or lossy environments
  • Offers more customizable network parameters for fine-tuning performance
  • Supports multiple encryption methods for data protection

Cons of kcptun

  • Generally higher CPU and bandwidth usage compared to WireGuard
  • More complex setup and configuration process
  • Less widespread adoption and ecosystem support

Code Comparison

kcptun (client configuration):

kcpconn, err := kcp.DialWithOptions("localhost:12345", nil, 10, 3)
if err != nil {
    log.Fatal(err)
}
defer kcpconn.Close()

WireGuard-go (client configuration):

device := device.NewDevice(tun, conn.NewDefaultBind(), logger)
err = device.IpcSet(uapi.Config{
    PrivateKey: privateKey,
    Peers: []uapi.PeerConfig{{
        PublicKey:  publicKey,
        AllowedIPs: []net.IPNet{allowedIP},
    }},
})

Both projects aim to provide secure and efficient network tunneling solutions, but they differ in their underlying protocols and implementation approaches. kcptun focuses on optimizing performance in challenging network conditions, while WireGuard-go prioritizes simplicity, security, and efficiency in typical network environments.

A Rust port of shadowsocks

Pros of shadowsocks-rust

  • Written in Rust, offering better memory safety and performance
  • Supports multiple ciphers and protocols, providing more flexibility
  • Active development with frequent updates and improvements

Cons of shadowsocks-rust

  • Less widespread adoption compared to WireGuard
  • May require more configuration and setup for advanced features
  • Potentially more complex codebase due to additional features

Code Comparison

shadowsocks-rust:

let server = ShadowsocksServer::new(config)?;
server.run().await?;

wireguard-go:

device := device.NewDevice(tun, conn, logger)
device.Up()

Both projects use concise code for initializing and running their respective services. shadowsocks-rust leverages Rust's async/await syntax, while wireguard-go uses Go's goroutines for concurrency. The wireguard-go code appears slightly more straightforward, reflecting its focus on simplicity and ease of use.

While both projects aim to provide secure communication, they differ in their approach and feature set. shadowsocks-rust offers more flexibility and customization options, while wireguard-go prioritizes simplicity and performance. The choice between them depends on specific use cases and requirements.

A platform for building proxies to bypass network restrictions.

Pros of v2ray-core

  • More versatile with support for multiple protocols and transport layers
  • Advanced features like traffic obfuscation and routing capabilities
  • Active development with frequent updates and improvements

Cons of v2ray-core

  • More complex configuration and setup compared to wireguard-go
  • Potentially higher resource usage due to additional features
  • Steeper learning curve for new users

Code Comparison

v2ray-core (Go):

type Server struct {
    access     sync.Mutex
    sessions   map[string]*session
    count      uint32
    config     *Config
    dispatcher routing.Dispatcher
}

wireguard-go (Go):

type Device struct {
    isUp     AtomicBool
    isClosed AtomicBool
    log      *Logger
    net      *netstack
    peers    map[key.PublicKey]*Peer
}

Both projects use Go and implement network-related functionality, but v2ray-core's structure suggests a more complex system with routing and multiple sessions, while wireguard-go focuses on device and peer management typical of VPN implementations.

24,231

Xray, Penetrates Everything. Also the best v2ray-core, with XTLS support. Fully compatible configuration.

Pros of Xray-core

  • More versatile with support for multiple protocols (VLESS, VMess, Trojan, etc.)
  • Advanced traffic obfuscation techniques for better censorship resistance
  • Modular architecture allowing for easier extension and customization

Cons of Xray-core

  • More complex configuration and setup compared to WireGuard's simplicity
  • Potentially higher resource usage due to additional features and protocols
  • Less focus on pure VPN functionality, as it's designed for broader proxy use cases

Code Comparison

WireGuard-go (simple configuration):

config := wgtypes.Config{
    PrivateKey: privateKey,
    ListenPort: 51820,
    Peers: []wgtypes.PeerConfig{
        {
            PublicKey:  peerPublicKey,
            AllowedIPs: []net.IPNet{allowedIP},
        },
    },
}

Xray-core (more complex configuration):

{
  "inbounds": [{
    "port": 10086,
    "protocol": "vmess",
    "settings": {
      "clients": [{ "id": "b831381d-6324-4d53-ad4f-8cda48b30811" }]
    }
  }],
  "outbounds": [{ "protocol": "freedom" }]
}
10,618

OpenVPN is an open source VPN daemon

Pros of OpenVPN

  • Mature and widely adopted, with extensive documentation and community support
  • Highly configurable, offering flexibility for various network setups
  • Compatible with a wide range of devices and operating systems

Cons of OpenVPN

  • Slower performance due to its complex protocol and encryption overhead
  • More challenging to set up and maintain compared to WireGuard
  • Larger codebase, potentially leading to more security vulnerabilities

Code Comparison

OpenVPN (C):

static void
do_init_crypto_tls(struct context *c, const unsigned int flags)
{
    if (c->options.tls_server)
    {
        tls_ctx_server_new(c->tls_multi);
        tls_ctx_load_dh_params(c->tls_multi, c->options.dh_file,
                               c->options.dh_file_inline);
    }
    else
    {
        tls_ctx_client_new(c->tls_multi);
    }
}

WireGuard-go (Go):

func (device *Device) Up() error {
    device.state.Lock()
    defer device.state.Unlock()

    if device.state.up {
        return nil
    }

    device.state.up = true
    return device.BindUpdate()
}

The code snippets demonstrate the difference in complexity and language choice between the two projects. OpenVPN's C code shows more intricate setup for TLS, while WireGuard-go's Go code presents a simpler device activation process.

6,175

Peer-to-peer VPN

Pros of n2n

  • Supports peer-to-peer connections without a central server
  • Offers more flexibility in network topology (mesh, star, etc.)
  • Includes built-in NAT traversal capabilities

Cons of n2n

  • Generally considered less secure than WireGuard
  • Can be more complex to set up and configure
  • May have higher latency due to its peer-to-peer nature

Code Comparison

n2n (C):

int edge_init(n2n_edge_t *eee) {
    memset(eee, 0, sizeof(n2n_edge_t));
    eee->start_time = time(NULL);
    eee->last_sup = 0;
    eee->last_reg_req = 0;
    eee->sn_wait = 10;
    eee->last_ack = 0;
    return 0;
}

wireguard-go (Go):

func (device *Device) Init() {
    device.state.starting.Add(1)
    device.queue.init()
    device.peers.init()
    device.routineDone.Add(deviceRoutineCount)
    device.log.Verbosef("Device initialized")
}

Both projects initialize their respective network devices, but n2n focuses on edge node setup, while WireGuard initializes device state, queues, and peers.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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 the latest version of Go.

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

License

Copyright (C) 2017-2023 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.