### Start WireGuard Tunnel Service (DLL Export) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt The main exported function from `tunnel.dll` that initiates a WireGuard tunnel as a Windows service. It takes a configuration string and tunnel name, parses the configuration, sets up a Wintun interface, configures firewall rules, and manages the tunnel lifecycle. This function is intended to be called from C/C++ applications. ```go // C function signature (exported from tunnel.dll) // bool WireGuardTunnelService(wchar_t* confString, wchar_t* tunnelName) // Example configuration string (wg-quick format with AmneziaWG extensions) const configString = `[Interface] PrivateKey = WG8H1k2F3j4K5L6m7N8o9P0qRsTuVwXyZaBcDeFgHiJ= Address = 10.0.0.2/24 DNS = 1.1.1.1 MTU = 1420 Jc = 5 Jmin = 50 Jmax = 1000 S1 = 120 S2 = 80 H1 = 1234567890 [Peer] PublicKey = aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789ABCDEFGH= Endpoint = vpn.example.com:51820 AllowedIPs = 0.0.0.0/0 PersistentKeepalive = 25` // From C/C++ application using the DLL: // HMODULE tunnel = LoadLibrary(L"tunnel.dll"); // typedef bool (*TunnelServiceFunc)(const wchar_t*, const wchar_t*); // TunnelServiceFunc startTunnel = (TunnelServiceFunc)GetProcAddress(tunnel, "WireGuardTunnelService"); // bool success = startTunnel(configWide, L"MyVPNTunnel"); ``` -------------------------------- ### Manage Windows Network Interfaces with winipcfg.LUID Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt The winipcfg.LUID type allows for comprehensive management of Windows network interfaces. It supports operations such as retrieving interface information from a GUID, adding and setting IP addresses, configuring routes, and managing DNS settings. It also provides methods to flush existing routes, IP addresses, and DNS configurations. ```go import ( "net" "github.com/amnezia-vpn/amneziawg-windows/tunnel/winipcfg" "golang.org/x/sys/windows" ) // Get LUID from interface GUID guid := &windows.GUID{/* interface GUID */} luid, err := winipcfg.LUIDFromGUID(guid) if err != nil { log.Fatalf("Failed to get LUID: %v", err) } // Get interface information iface, err := luid.Interface() if err != nil { log.Fatalf("Failed to get interface: %v", err) } fmt.Printf("Interface: %s\n", iface.Description()) // Add IP address to interface _, ipNet, _ := net.ParseCIDR("10.0.0.2/24") err = luid.AddIPAddress(*ipNet) if err != nil { log.Fatalf("Failed to add IP: %v", err) } // Set multiple IP addresses (flushes existing first) addresses := []net.IPNet{ {IP: net.ParseIP("10.0.0.2"), Mask: net.CIDRMask(24, 32)}, {IP: net.ParseIP("fd00::2"), Mask: net.CIDRMask(64, 128)}, } err = luid.SetIPAddresses(addresses) // Add route _, dest, _ := net.ParseCIDR("192.168.1.0/24") err = luid.AddRoute(*dest, net.ParseIP("10.0.0.1"), 100) // metric 100 // Configure DNS servers dnsServers := []net.IP{ net.ParseIP("1.1.1.1"), net.ParseIP("8.8.8.8"), } domains := []string{"example.com", "internal.local"} err = luid.SetDNS(windows.AF_INET, dnsServers, domains) // Get current DNS servers currentDNS, err := luid.DNS() for _, dns := range currentDNS { fmt.Printf("DNS Server: %s\n", dns.String()) } // Flush all routes and addresses err = luid.FlushRoutes(windows.AF_UNSPEC) err = luid.FlushIPAddresses(windows.AF_UNSPEC) err = luid.FlushDNS(windows.AF_INET) ``` -------------------------------- ### Build AmneziaWG Tunnel DLL Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt This batch script compiles the AmneziaWG tunnel functionality into an embeddable DLL for Windows applications. The resulting `tunnel.dll` exports functions for starting a WireGuard tunnel service and generating key pairs. ```batch REM Build the tunnel.dll .\build.cmd REM Output: x64\tunnel.dll REM The DLL exports: REM - WireGuardTunnelService(confString, tunnelName) -> bool REM - WireGuardGenerateKeypair(publicKey, privateKey) -> void ``` -------------------------------- ### Serialize Config to wg-quick Format (Go) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt Converts a Config struct into a wg-quick formatted string. This is useful for saving configurations or displaying them to users. It takes a conf.Config struct as input and returns a string representing the configuration. ```go import ( "fmt" "net" "github.com/amnezia-vpn/amneziawg-windows/conf" ) // Create configuration programmatically privateKey, _ := conf.NewPrivateKey() config := &conf.Config{ Name: "MyTunnel", Interface: conf.Interface{ PrivateKey: *privateKey, Addresses: []conf.IPCidr{{IP: net.ParseIP("10.0.0.2"), Cidr: 24}}, DNS: []net.IP{net.ParseIP("1.1.1.1")}, MTU: 1420, JunkPacketCount: 5, JunkPacketMinSize: 50, JunkPacketMaxSize: 1000, }, Peers: []conf.Peer{{ PublicKey: conf.Key{/* peer public key bytes */}, Endpoint: conf.Endpoint{Host: "vpn.example.com", Port: 51820}, AllowedIPs: []conf.IPCidr{{IP: net.ParseIP("0.0.0.0"), Cidr: 0}}, PersistentKeepalive: 25, }}, } // Serialize to wg-quick format wgQuickConfig := config.ToWgQuick() fmt.Println(wgQuickConfig) ``` -------------------------------- ### Load and Save DPAPI-Encrypted Configurations (Go) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt Handles loading WireGuard configurations from DPAPI-encrypted files stored in the system configuration directory and saving them. It supports loading by full path or by tunnel name, listing available configurations, saving (with optional overwrite), and deleting configurations. ```go import ( "fmt" "log" "github.com/amnezia-vpn/amneziawg-windows/conf" ) // Load from full path (supports both .conf and .conf.dpapi files) config, err := conf.LoadFromPath("C:\\ProgramData\\AmneziaWG\\Configurations\\MyTunnel.conf.dpapi") if err != nil { log.Fatalf("Failed to load config: %v", err) } // Load by tunnel name (looks in default configuration directory) config, err = conf.LoadFromName("MyTunnel") if err != nil { log.Fatalf("Failed to load config: %v", err) } // List all available configurations names, err := conf.ListConfigNames() if err != nil { log.Fatalf("Failed to list configs: %v", err) } for _, name := range names { fmt.Printf("Available tunnel: %s\n", name) } // Save configuration (encrypts with DPAPI) err = config.Save(true) // true = overwrite existing if err != nil { log.Fatalf("Failed to save config: %v", err) } // Delete configuration err = config.Delete() // or by name: err = conf.DeleteName("MyTunnel") ``` -------------------------------- ### Elevate Program Execution with elevate.ShellExecute Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt The elevate.ShellExecute function is a helper for executing programs with administrator privileges on Windows. It handles User Account Control (UAC) prompts and elevation scenarios. The snippet also includes a check for the current process's elevation status using `golang.org/x/sys/windows`. ```go import "github.com/amnezia-vpn/amneziawg-windows/elevate" import "golang.org/x/sys/windows" // Execute a program with elevation (triggers UAC if needed) err := elevate.ShellExecute( "C:\\Program Files\\MyApp\\setup.exe", // program "/silent /install", // arguments "C:\\Program Files\\MyApp", // working directory 1, // SW_SHOWNORMAL ) if err != nil { log.Fatalf("Failed to execute elevated: %v", err) } // Check if current process is elevated var processToken windows.Token windows.OpenProcessToken(windows.CurrentProcess(), windows.TOKEN_QUERY, &processToken) defer processToken.Close() if processToken.IsElevated() { fmt.Println("Running as administrator") } else { fmt.Println("Running as standard user") } ``` -------------------------------- ### Generate WireGuard Keys (Go) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt Generates cryptographically secure WireGuard private and preshared keys. It includes functions to create new keys, derive public keys from private keys, and parse existing keys from base64 strings. It also provides a method to check if a key is zero/unset. ```go import ( "fmt" "log" "github.com/amnezia-vpn/amneziawg-windows/conf" ) // Generate a new private key (clamped for Curve25519) privateKey, err := conf.NewPrivateKey() if err != nil { log.Fatalf("Failed to generate private key: %v", err) } // Derive public key from private key publicKey := privateKey.Public() fmt.Printf("Private Key: %s\n", privateKey.String()) // Base64 encoded fmt.Printf("Public Key: %s\n", publicKey.String()) // Base64 encoded fmt.Printf("Private Key (hex): %s\n", privateKey.HexString()) // Generate a preshared key for additional security presharedKey, err := conf.NewPresharedKey() if err != nil { log.Fatalf("Failed to generate preshared key: %v", err) } fmt.Printf("Preshared Key: %s\n", presharedKey.String()) // Parse existing key from base64 string existingKey, err := conf.NewPrivateKeyFromString("WG8H1k2F3j4K5L6m7N8o9P0qRsTuVwXyZaBcDeFgHiJ=") if err != nil { log.Fatalf("Invalid key format: %v", err) } // Check if key is zero/unset if existingKey.IsZero() { fmt.Println("Key is not set") } ``` -------------------------------- ### Generate UAPI Configuration from Config (Go) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt Converts a Config struct to the WireGuard userspace API (UAPI) format. This format is used for communication with the WireGuard device and resolves DNS hostnames to IP addresses. It requires a conf.Config struct and returns the UAPI formatted string and an error if DNS resolution fails. ```go import ( "fmt" "log" "github.com/amnezia-vpn/amneziawg-windows/conf" ) // Assume configString is loaded from somewhere, e.g., FromWgQuick configString := "[Interface]\nPrivateKey = \nAddress = 10.0.0.2/24\nDNS = 1.1.1.1\nMTU = 1420\nJc = 5\nJmin = 50\nJmax = 1000\n\n[Peer]\nPublicKey = \nAllowedIPs = 0.0.0.0/0\nEndpoint = vpn.example.com:51820\nPersistentKeepalive = 25" config, _ := conf.FromWgQuick(configString, "MyTunnel") // Convert to UAPI format (used internally by the device) uapiConfig, err := config.ToUAPI() if err != nil { log.Fatalf("DNS resolution failed: %v", err) } fmt.Println(uapiConfig) ``` -------------------------------- ### Parse WireGuard Configuration (wg-quick format) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt Parses a WireGuard configuration string in the standard wg-quick format, including AmneziaWG-specific obfuscation parameters. It returns a structured `Config` object containing interface and peer details. This function is useful for loading configurations from files or strings within a Go application. ```go import "github.com/amnezia-vpn/amneziawg-windows/conf" configString := `[Interface] PrivateKey = WG8H1k2F3j4K5L6m7N8o9P0qRsTuVwXyZaBcDeFgHiJ= Address = 10.0.0.2/24, fd00::2/128 DNS = 1.1.1.1, 8.8.8.8 ListenPort = 51821 MTU = 1420 Jc = 5 Jmin = 50 Jmax = 1000 S1 = 120 H1 = 1234567890 PreUp = echo "Starting tunnel" PostDown = echo "Tunnel stopped" [Peer] PublicKey = aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789ABCDEFGH= PresharedKey = xYz0123456789AbCdEfGhIjKlMnOpQrStUvWxYz012345= Endpoint = vpn.example.com:51820 AllowedIPs = 0.0.0.0/0, ::/0 PersistentKeepalive = 25` config, err := conf.FromWgQuick(configString, "MyTunnel") if err != nil { log.Fatalf("Failed to parse config: %v", err) } // Access parsed configuration fmt.Printf("Tunnel Name: %s\n", config.Name) fmt.Printf("Private Key: %s\n", config.Interface.PrivateKey.String()) fmt.Printf("Addresses: %v\n", config.Interface.Addresses) fmt.Printf("DNS Servers: %v\n", config.Interface.DNS) fmt.Printf("MTU: %d\n", config.Interface.MTU) fmt.Printf("Junk Packet Count: %d\n", config.Interface.JunkPacketCount) fmt.Printf("Peers: %d\n", len(config.Peers)) for i, peer := range config.Peers { fmt.Printf("Peer %d: %s @ %s\n", i, peer.PublicKey.String(), peer.Endpoint.String()) } ``` -------------------------------- ### Use AmneziaWG Windows Library as Go Module Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt Instructions on how to include the AmneziaWG Windows library in your Go project using Go modules. It specifies the `go.mod` requirement and provides import paths for key components like configuration, network interface management, and ring logging. ```go // Using the library as a Go module // go.mod: // require github.com/amnezia-vpn/amneziawg-windows v0.3.15 import ( "github.com/amnezia-vpn/amneziawg-windows/conf" "github.com/amnezia-vpn/amneziawg-windows/tunnel/winipcfg" "github.com/amnezia-vpn/amneziawg-windows/ringlogger" ) ``` -------------------------------- ### Implement Circular Logging with ringlogger.Ringlogger Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt The ringlogger.Ringlogger provides a high-performance, memory-mapped circular log buffer. It's suitable for inter-process communication of logs and implements the io.Writer interface for easy integration with standard logging practices. It also supports exporting logs to files and real-time following of log entries. ```go import "github.com/amnezia-vpn/amneziawg-windows/ringlogger" // Create a new ring logger logger, err := ringlogger.NewRinglogger("C:\\Logs\\tunnel.bin", "TUN") if err != nil { log.Fatalf("Failed to create logger: %v", err) } defer logger.Close() // Write log entries (implements io.Writer) logger.Write([]byte("Tunnel started successfully")) logger.Write([]byte("Connected to peer 10.0.0.1")) // Use with standard log package log.SetOutput(logger) log.Println("This goes to the ring buffer") // Export log to file file, _ := os.Create("tunnel.log") defer file.Close() logger.WriteTo(file) // Follow log entries (for real-time monitoring) cursor := ringlogger.CursorAll for { lines, nextCursor := logger.FollowFromCursor(cursor) for _, line := range lines { fmt.Printf("%s: %s\n", line.Stamp.Format(time.RFC3339), line.Line) } cursor = nextCursor time.Sleep(100 * time.Millisecond) } // Create logger from inherited handle (for child processes) // Parent process: handle, _ := logger.ExportInheritableMappingHandle() defer windows.CloseHandle(handle) // Pass handle to child via command line or environment // Child process: childLogger, err := ringlogger.NewRingloggerFromInheritedMappingHandle( os.Getenv("LOG_HANDLE"), "CHILD") ``` -------------------------------- ### Generate WireGuard Key Pair (DLL Export) Source: https://context7.com/amnezia-vpn/amneziawg-windows/llms.txt An exported function from `tunnel.dll` that generates a Curve25519 key pair for WireGuard. It produces a public and private key, with the private key clamped according to WireGuard specifications. This function is designed to be called from C/C++ applications. ```go // C function signature (exported from tunnel.dll) // void WireGuardGenerateKeypair(uint8_t publicKey[32], uint8_t privateKey[32]) // From C/C++ application: // uint8_t publicKey[32], privateKey[32]; // typedef void (*KeypairFunc)(uint8_t*, uint8_t*); // KeypairFunc genKeypair = (KeypairFunc)GetProcAddress(tunnel, "WireGuardGenerateKeypair"); // genKeypair(publicKey, privateKey); // Go implementation internally: func WireGuardGenerateKeypair(publicKey *byte, privateKey *byte) { publicKeyArray := (*[32]byte)(unsafe.Pointer(publicKey)) privateKeyArray := (*[32]byte)(unsafe.Pointer(privateKey)) rand.Read(privateKeyArray[:]) // Clamp private key per WireGuard spec privateKeyArray[0] &= 248 privateKeyArray[31] = (privateKeyArray[31] & 127) | 64 curve25519.ScalarBaseMult(publicKeyArray, privateKeyArray) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.