github.com/xraypb/xray-core@v1.6.6/infra/conf/wireguard.go (about) 1 package conf 2 3 import ( 4 "encoding/base64" 5 "encoding/hex" 6 7 "github.com/golang/protobuf/proto" 8 "github.com/xraypb/xray-core/proxy/wireguard" 9 ) 10 11 type WireGuardPeerConfig struct { 12 PublicKey string `json:"publicKey"` 13 PreSharedKey string `json:"preSharedKey"` 14 Endpoint string `json:"endpoint"` 15 KeepAlive int `json:"keepAlive"` 16 AllowedIPs []string `json:"allowedIPs,omitempty"` 17 } 18 19 func (c *WireGuardPeerConfig) Build() (proto.Message, error) { 20 var err error 21 config := new(wireguard.PeerConfig) 22 23 config.PublicKey, err = parseWireGuardKey(c.PublicKey) 24 if err != nil { 25 return nil, err 26 } 27 28 if c.PreSharedKey != "" { 29 config.PreSharedKey, err = parseWireGuardKey(c.PreSharedKey) 30 if err != nil { 31 return nil, err 32 } 33 } else { 34 config.PreSharedKey = "0000000000000000000000000000000000000000000000000000000000000000" 35 } 36 37 config.Endpoint = c.Endpoint 38 // default 0 39 config.KeepAlive = int32(c.KeepAlive) 40 if c.AllowedIPs == nil { 41 config.AllowedIps = []string{"0.0.0.0/0", "::0/0"} 42 } else { 43 config.AllowedIps = c.AllowedIPs 44 } 45 46 return config, nil 47 } 48 49 type WireGuardConfig struct { 50 SecretKey string `json:"secretKey"` 51 Address []string `json:"address"` 52 Peers []*WireGuardPeerConfig `json:"peers"` 53 MTU int `json:"mtu"` 54 NumWorkers int `json:"workers"` 55 } 56 57 func (c *WireGuardConfig) Build() (proto.Message, error) { 58 config := new(wireguard.DeviceConfig) 59 60 var err error 61 config.SecretKey, err = parseWireGuardKey(c.SecretKey) 62 if err != nil { 63 return nil, err 64 } 65 66 if c.Address == nil { 67 // bogon ips 68 config.Endpoint = []string{"10.0.0.1", "fd59:7153:2388:b5fd:0000:0000:0000:0001"} 69 } else { 70 config.Endpoint = c.Address 71 } 72 73 if c.Peers != nil { 74 config.Peers = make([]*wireguard.PeerConfig, len(c.Peers)) 75 for i, p := range c.Peers { 76 msg, err := p.Build() 77 if err != nil { 78 return nil, err 79 } 80 config.Peers[i] = msg.(*wireguard.PeerConfig) 81 } 82 } 83 84 if c.MTU == 0 { 85 config.Mtu = 1420 86 } else { 87 config.Mtu = int32(c.MTU) 88 } 89 // these a fallback code exists in github.com/nanoda0523/wireguard-go code, 90 // we don't need to process fallback manually 91 config.NumWorkers = int32(c.NumWorkers) 92 93 return config, nil 94 } 95 96 func parseWireGuardKey(str string) (string, error) { 97 if len(str) != 64 { 98 // may in base64 form 99 dat, err := base64.StdEncoding.DecodeString(str) 100 if err != nil { 101 return "", err 102 } 103 if len(dat) != 32 { 104 return "", newError("key should be 32 bytes: " + str) 105 } 106 return hex.EncodeToString(dat), err 107 } else { 108 // already hex form 109 return str, nil 110 } 111 }