wgapi

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 20, 2024 License: MIT Imports: 12 Imported by: 4

README

wgapi

Go Reference

Introduction

WGAPI is a Go package designed to assist in communicating with the Wireguard userspace module. It focuses on programmatically creating, reading, and handling Wireguard configuration in a text-based format, making it easier to manage Wireguard instances programmatically.

The wgconfig package also provides convenient structures and functions for setting up Wireguard server and client configurations. It simplifies the process of generating configurations, managing keys, and setting up network parameters.

Features

  • Parsing and handling Wireguard configuration data.
  • Generating new private, public, and pre-shared keys.
  • Efficient and structured API communication with Wireguard.

Installation

To use wgevents in your Go project, install it using go get:

go get github.com/point-c/wgapi

Usage

Generating Keys
  • Generate a new private and public key pair:

    • Errors from New<key> functions can only happen if rand.Reader causes an error.
    private, public, err := wgapi.NewPrivatePublic()
    if err != nil {
        panic(err)
    }
    fmt.Printf("Private Key: %s\nPublic Key: %s\n", private, public)
    
  • Generate private key:

    private, err := wgapi.NewPrivate()
    if err != nil {
        panic(err)
    }
    
  • Generate preshared key:

    preshared, err := wgapi.NewPreshared()
    if err != nil {
        panic(err)
    }
    
  • Convert private key to public key:

    • An error will only happen if you try to get the public key from a preshared key
    public, err := private.Public()
    if err != nil {
        panic(err)
    }
    
Parsing Wireguard Configuration
// Assuming configData is the Wireguard configuration data you have
configData := "PrivateKey=aSdFgH123456...\nListenPort=51820\n"

// Create a new IPCGet instance and write config data to it
var get wgapi.IPCGet
get.Write([]byte(configData))

// Parse and retrieve the configuration as key-value pairs
ipc, err := get.Value()
if err != nil {
    panic(err)
}

// Handle the parsed IPC data
var tx, rx uint64
for _, v := range ipc {
	// Type assertions can be used to find specific keys in the response
	tx, ok := v.(wgapi.TXBytes)
	if ok {
        tx += uint64(tx)
    }
}
Creating a Wireguard Configuration
Freeform

wgapi.IPC is a slice type. It can be configured programmatically as you see fit.

r := wgapi.IPC{
	// config values...
}.WGConfig()
// r will be an io.Reader that contains a syntactically valid wireguard configuration
Config Helpers
Server
type Server struct {
    Private    wgapi.PrivateKey
    ListenPort uint16      
    Peers      []*Peer     
}

Wireguard's default listening port is 51820. This can be set with:

func (cfg *Server) DefaultListenPort()

Peers can be easily added:

peerIP := net.IPv4(192, 168, 99, 2)

preShared, err := wgapi.NewPreshared()
if err != nil {
    panic(err)
}

privateKey, err := wgapi.NewPrivate()
if err != nil {
    panic(err)
}
// Use private key in client config
publicKey, err := privateKey.Public()

serverCfg.AddPeer(publicKey, preShared, peerIP)
Client
type Client struct {
	Private             wgapi.PrivateKey  
	Public              wgapi.PublicKey   
	PreShared           wgapi.PresharedKey
	Endpoint            net.UDPAddr       
	PersistentKeepalive *uint16          
	AllowedIPs          []net.IPNet      
}

Clients will likely want to allow all IPs. This can easily be done with the provided method:

func (cfg *Client) AllowAllIPs()

The default persistent keepalive can be set with:

func (cfg *Client) DefaultPersistentKeepAlive()
Pair Generator

A generator exists to create configs quickly.

endpoint, err := net.ResolveUDPAddr("udp", "endpoint address")
if err != nil {
    panic(err)
}

clientIP := net.IPv4(192.168.99.2)

client, server, err := GenerateConfigPair(endpoint, clientIP)
if err != nil {
    panic(err)
}
// `client` and `server` contain valid config to connect to one another.
// Matching keys are generated for each and defaults are filled in.

Testing

The package includes tests that demonstrate its functionality. Use Go's testing tools to run the tests:

go test ./...

Godocs

To regenerate godocs:

go generate -tags docs ./...

Code Generation

To regenerate generated packages:

go generate ./...

Documentation

Overview

Package wgapi helps with communicating with the userspace wireguard module. Since wireguard-go uses a text based configuration this helps with programmatically creating and reading a config. Please consult wireguard cross-platform documentation for more information on configuration values.

Index

Constants

View Source
const (
	ErrnoNone      = Errno(0)
	ErrnoIO        = Errno(ipc.IpcErrorIO)
	ErrnoProtocol  = Errno(ipc.IpcErrorProtocol)
	ErrnoInvalid   = Errno(ipc.IpcErrorInvalid)
	ErrnoPortInUse = Errno(ipc.IpcErrorPortInUse)
	ErrnoUnknown   = Errno(int64(ipc.IpcErrorUnknown))
)

Variables

View Source
var EmptySubnet = parseAllowedIP("0.0.0.0/0")

EmptySubnet represents a subnet configuration that permits all IP addresses. It's defined by setting the allowed IP range to '0.0.0.0/0', which effectively means there are no restrictions on the IP addresses allowed through this subnet. It's typically used in VPN configurations to indicate that all traffic should be routed through the VPN.

Functions

func NewPrivatePublic

func NewPrivatePublic() (private PrivateKey, public PublicKey, err error)

NewPrivatePublic generates a new private key and also returns its corresponding public key.

Types

type AllowedIP

type AllowedIP = value.IPNet[key.AllowedIP]

AllowedIP is an address allowed to communicate in the tunnel.

func IdentitySubnet

func IdentitySubnet(ip net.IP) AllowedIP

IdentitySubnet takes an IP address (either IPv4 or IPv6) and returns it as an IPv6 address with a subnet mask of /128. This effectively identifies a single address, as a /128 mask specifies all 128 bits of the IPv6 address, leaving no room for a range of addresses.

type Configurable

type Configurable interface {
	WGConfig() io.Reader
}

Configurable is something that can be converted into a reader that supplies 'key=value\n' values corresponding to the wireguard userspace configuration wireguard cross-platform documentation.

type Endpoint

type Endpoint = value.UDPAddr[key.Endpoint]

Endpoint is the address:port of a wireguard server

type Errno

type Errno = value.Int64[key.Errno]

Errno is an error returned by the IPC.

type FWMark

type FWMark = value.Uint32[key.FWMark]

FWMark configures the interface as specified in wireguard cross-platform documentation. The special value 0 clears the FWMark.

type Get

type Get = value.One[key.Get]

Get specifies a get operation. Not used unless communicating with an external endpoint.

type IPC

type IPC []IPCKeyValue

IPC is an IPC operation as documented by the wireguard cross-platform documentation.

func (IPC) WGConfig

func (ir IPC) WGConfig() io.Reader

type IPCGet

type IPCGet struct {
	// contains filtered or unexported fields
}

IPCGet is used to help get information from a wireguard userspace configuration as documented in wireguard cross-platform documentation.

func (*IPCGet) Reset

func (get *IPCGet) Reset()

Reset allows this to be reused for another operation. Without calling this IPCGet.Value will only return the data from the first time this was used.

func (*IPCGet) Value

func (get *IPCGet) Value() (IPC, error)

Value converts the text data into an IPC containing typed values.

func (*IPCGet) Write

func (get *IPCGet) Write(b []byte) (int, error)

Write is used to write 'key=value\n' lines from the wireguard IPC. This is used by the wireguard-go's IPC library to write values to this parser.

type IPCKeyValue

type IPCKeyValue = internal.KeyValue

IPCKeyValue is string key and value pair. The value is represented by fmt.Stringer.

type LastHandshakeTimeNSec

type LastHandshakeTimeNSec = value.Int64[key.LastHandshakeTimeNSec]

LastHandshakeTimeNSec is the nanoseconds resolution of the last handshake relative to unix epoch.

type LastHandshakeTimeSec

type LastHandshakeTimeSec = value.Int64[key.LastHandshakeTimeSec]

LastHandshakeTimeSec is the seconds since the last handshake relative to unix epoch.

type ListenPort

type ListenPort = value.Uint16[key.ListenPort]

ListenPort is the system port used to listen for wireguard traffic.

const DefaultListenPort ListenPort = 51820

type PersistentKeepalive

type PersistentKeepalive = value.Uint16[key.PersistentKeepalive]

PersistentKeepalive is the interval to send a persistent keepalive packet. Special value 0 disables this.

const DefaultPersistentKeepalive PersistentKeepalive = 25

type PresharedKey

type PresharedKey = value.Key[key.PresharedKey, wgkey.PreShared]

PresharedKey is a preshared key usable by the IPC.

func NewPreshared

func NewPreshared() (PresharedKey, error)

NewPreshared generates a new preshared key.

type PrivateKey

type PrivateKey = value.Key[key.PrivateKey, wgkey.Private]

PrivateKey is a private key usable by the IPC.

func NewPrivate

func NewPrivate() (PrivateKey, error)

NewPrivate generates a new private key.

type ProtocolVersion

type ProtocolVersion = value.One[key.ProtocolVersion]

ProtocolVersion is the version of the protocol. Generally not used.

type PublicKey

type PublicKey = value.Key[key.PublicKey, wgkey.Public]

PublicKey is a public key usable by the IPC.

type RXBytes

type RXBytes = value.Uint64[key.RXBytes]

RXBytes are the number of received bytes. Only present in a get operation.

type Remove

type Remove = value.True[key.Remove]

Remove removes the peer.

type ReplaceAllowedIPs

type ReplaceAllowedIPs = value.True[key.ReplaceAllowedIPs]

ReplaceAllowedIPs replaces the current allowed IPs instead of appending.

type ReplacePeers

type ReplacePeers = value.True[key.ReplacePeers]

ReplacePeers replaces all the peers.

type Set

type Set = value.One[key.Set]

Set specifies a set operation. Not used unless communicating with an external endpoint.

type TXBytes

type TXBytes = value.Uint64[key.TXBytes]

TXBytes are the number of transferred bytes. Only present in a get operation.

type UpdateOnly

type UpdateOnly = value.True[key.UpdateOnly]

UpdateOnly only updates the peer if it is already present.

Directories

Path Synopsis
Package internal contains packages that assist with wireguard types.
Package internal contains packages that assist with wireguard types.
key
Package keys contains the keys used by the wireguard-go ipc.
Package keys contains the keys used by the wireguard-go ipc.
parser
Package parser contains functions that assist with parsing a wireguard-go ipc response.
Package parser contains functions that assist with parsing a wireguard-go ipc response.
value
Package value manages key-value pairs, conforming to the [internal.KeyValue] interface.
Package value manages key-value pairs, conforming to the [internal.KeyValue] interface.
value/wgkey
Package wgkey holds basic types for wireguard keys.
Package wgkey holds basic types for wireguard keys.
Package wgconfig provides examples of simple client and server configurations using the WireGuard API.
Package wgconfig provides examples of simple client and server configurations using the WireGuard API.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL