wireguard.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package logic
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "os/exec"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/gravitl/netmaker/models"
  13. "github.com/gravitl/netmaker/netclient/ncutils"
  14. "golang.zx2c4.com/wireguard/wgctrl"
  15. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  16. )
  17. // GetSystemPeers - gets the server peers
  18. func GetSystemPeers(node *models.Node) (map[string]string, error) {
  19. peers := make(map[string]string)
  20. client, err := wgctrl.New()
  21. if err != nil {
  22. return peers, err
  23. }
  24. device, err := client.Device(node.Interface)
  25. if err != nil {
  26. return nil, err
  27. }
  28. for _, peer := range device.Peers {
  29. if IsBase64(peer.PublicKey.String()) && peer.Endpoint != nil && CheckEndpoint(peer.Endpoint.String()) {
  30. peers[peer.PublicKey.String()] = peer.Endpoint.String()
  31. }
  32. }
  33. return peers, nil
  34. }
  35. func setWGConfig(node models.Node, network string, peerupdate bool) error {
  36. node.SetID()
  37. peers, hasGateway, gateways, err := GetServerPeers(node.MacAddress, node.Network, node.IsDualStack == "yes", node.IsIngressGateway == "yes")
  38. if err != nil {
  39. return err
  40. }
  41. privkey, err := FetchPrivKey(node.ID)
  42. if err != nil {
  43. return err
  44. }
  45. if peerupdate {
  46. var iface string
  47. iface = node.Interface
  48. err = setServerPeers(iface, node.PersistentKeepalive, peers)
  49. } else {
  50. err = initWireguard(&node, privkey, peers, hasGateway, gateways)
  51. }
  52. return err
  53. }
  54. func initWireguard(node *models.Node, privkey string, peers []wgtypes.PeerConfig, hasGateway bool, gateways []string) error {
  55. key, err := wgtypes.ParseKey(privkey)
  56. if err != nil {
  57. return err
  58. }
  59. wgclient, err := wgctrl.New()
  60. if err != nil {
  61. return err
  62. }
  63. defer wgclient.Close()
  64. var ifacename string
  65. if node.Interface != "" {
  66. ifacename = node.Interface
  67. } else {
  68. Log("no interface to configure", 0)
  69. }
  70. if node.Address == "" {
  71. Log("no address to configure", 0)
  72. }
  73. if ncutils.IsKernel() {
  74. setKernelDevice(ifacename, node.Address)
  75. }
  76. nodeport := int(node.ListenPort)
  77. var conf wgtypes.Config
  78. conf = wgtypes.Config{
  79. PrivateKey: &key,
  80. ListenPort: &nodeport,
  81. ReplacePeers: true,
  82. Peers: peers,
  83. }
  84. if !ncutils.IsKernel() {
  85. var newConf string
  86. if node.UDPHolePunch != "yes" {
  87. newConf, _ = ncutils.CreateUserSpaceConf(node.Address, key.String(), strconv.FormatInt(int64(node.ListenPort), 10), node.MTU, node.PersistentKeepalive, peers)
  88. } else {
  89. newConf, _ = ncutils.CreateUserSpaceConf(node.Address, key.String(), "", node.MTU, node.PersistentKeepalive, peers)
  90. }
  91. confPath := ncutils.GetNetclientPathSpecific() + ifacename + ".conf"
  92. ncutils.PrintLog("writing wg conf file to: "+confPath, 1)
  93. err = ioutil.WriteFile(confPath, []byte(newConf), 0644)
  94. if err != nil {
  95. ncutils.PrintLog("error writing wg conf file to "+confPath+": "+err.Error(), 1)
  96. return err
  97. }
  98. // spin up userspace + apply the conf file
  99. var deviceiface string
  100. deviceiface = ifacename
  101. d, _ := wgclient.Device(deviceiface)
  102. for d != nil && d.Name == deviceiface {
  103. _ = RemoveConf(ifacename, false) // remove interface first
  104. time.Sleep(time.Second >> 2)
  105. d, _ = wgclient.Device(deviceiface)
  106. }
  107. err = applyWGQuickConf(confPath)
  108. if err != nil {
  109. Log("failed to create wireguard interface", 1)
  110. return err
  111. }
  112. } else {
  113. ipExec, err := exec.LookPath("ip")
  114. if err != nil {
  115. return err
  116. }
  117. _, err = wgclient.Device(ifacename)
  118. if err != nil {
  119. if os.IsNotExist(err) {
  120. fmt.Println("Device does not exist: ")
  121. fmt.Println(err)
  122. } else {
  123. return errors.New("Unknown config error: " + err.Error())
  124. }
  125. }
  126. err = wgclient.ConfigureDevice(ifacename, conf)
  127. if err != nil {
  128. if os.IsNotExist(err) {
  129. fmt.Println("Device does not exist: ")
  130. fmt.Println(err)
  131. } else {
  132. fmt.Printf("This is inconvenient: %v", err)
  133. }
  134. }
  135. if _, err := ncutils.RunCmd(ipExec+" link set down dev "+ifacename, false); err != nil {
  136. ncutils.Log("attempted to remove interface before editing")
  137. return err
  138. }
  139. if node.PostDown != "" {
  140. runcmds := strings.Split(node.PostDown, "; ")
  141. _ = ncutils.RunCmds(runcmds, true)
  142. }
  143. // set MTU of node interface
  144. if _, err := ncutils.RunCmd(ipExec+" link set mtu "+strconv.Itoa(int(node.MTU))+" up dev "+ifacename, true); err != nil {
  145. ncutils.Log("failed to create interface with mtu " + ifacename)
  146. return err
  147. }
  148. if node.PostUp != "" {
  149. runcmds := strings.Split(node.PostUp, "; ")
  150. _ = ncutils.RunCmds(runcmds, true)
  151. }
  152. if hasGateway {
  153. for _, gateway := range gateways {
  154. _, _ = ncutils.RunCmd(ipExec+" -4 route add "+gateway+" dev "+ifacename, true)
  155. }
  156. }
  157. if node.Address6 != "" && node.IsDualStack == "yes" {
  158. log.Println("[netclient] adding address: "+node.Address6, 1)
  159. _, _ = ncutils.RunCmd(ipExec+" address add dev "+ifacename+" "+node.Address6+"/64", true)
  160. }
  161. }
  162. return err
  163. }
  164. // RemoveConf - removes a configuration for a given WireGuard interface
  165. func RemoveConf(iface string, printlog bool) error {
  166. var err error
  167. confPath := ncutils.GetNetclientPathSpecific() + iface + ".conf"
  168. err = removeWGQuickConf(confPath, printlog)
  169. return err
  170. }
  171. // == Private Methods ==
  172. func setKernelDevice(ifacename string, address string) error {
  173. ipExec, err := exec.LookPath("ip")
  174. if err != nil {
  175. return err
  176. }
  177. _, _ = ncutils.RunCmd("ip link delete dev "+ifacename, false)
  178. _, _ = ncutils.RunCmd(ipExec+" link add dev "+ifacename+" type wireguard", true)
  179. _, _ = ncutils.RunCmd(ipExec+" address add dev "+ifacename+" "+address+"/24", true)
  180. return nil
  181. }
  182. func applyWGQuickConf(confPath string) error {
  183. if _, err := ncutils.RunCmd("wg-quick up "+confPath, true); err != nil {
  184. return err
  185. }
  186. return nil
  187. }
  188. func removeWGQuickConf(confPath string, printlog bool) error {
  189. if _, err := ncutils.RunCmd("wg-quick down "+confPath, printlog); err != nil {
  190. return err
  191. }
  192. return nil
  193. }
  194. func setServerPeers(iface string, keepalive int32, peers []wgtypes.PeerConfig) error {
  195. client, err := wgctrl.New()
  196. if err != nil {
  197. ncutils.PrintLog("failed to start wgctrl", 0)
  198. return err
  199. }
  200. device, err := client.Device(iface)
  201. if err != nil {
  202. ncutils.PrintLog("failed to parse interface", 0)
  203. return err
  204. }
  205. devicePeers := device.Peers
  206. if len(devicePeers) > 1 && len(peers) == 0 {
  207. ncutils.PrintLog("no peers pulled", 1)
  208. return err
  209. }
  210. for _, peer := range peers {
  211. for _, currentPeer := range devicePeers {
  212. if currentPeer.AllowedIPs[0].String() == peer.AllowedIPs[0].String() &&
  213. currentPeer.PublicKey.String() != peer.PublicKey.String() {
  214. _, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  215. if err != nil {
  216. log.Println("error removing peer", peer.Endpoint.String())
  217. }
  218. }
  219. }
  220. udpendpoint := peer.Endpoint.String()
  221. var allowedips string
  222. var iparr []string
  223. for _, ipaddr := range peer.AllowedIPs {
  224. iparr = append(iparr, ipaddr.String())
  225. }
  226. allowedips = strings.Join(iparr, ",")
  227. keepAliveString := strconv.Itoa(int(keepalive))
  228. if keepAliveString == "0" {
  229. keepAliveString = "5"
  230. }
  231. if peer.Endpoint != nil {
  232. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  233. " endpoint "+udpendpoint+
  234. " persistent-keepalive "+keepAliveString+
  235. " allowed-ips "+allowedips, true)
  236. } else {
  237. _, err = ncutils.RunCmd("wg set "+iface+" peer "+peer.PublicKey.String()+
  238. " persistent-keepalive "+keepAliveString+
  239. " allowed-ips "+allowedips, true)
  240. }
  241. if err != nil {
  242. log.Println("error setting peer", peer.PublicKey.String())
  243. }
  244. }
  245. for _, currentPeer := range devicePeers {
  246. shouldDelete := true
  247. for _, peer := range peers {
  248. if peer.AllowedIPs[0].String() == currentPeer.AllowedIPs[0].String() {
  249. shouldDelete = false
  250. }
  251. }
  252. if shouldDelete {
  253. output, err := ncutils.RunCmd("wg set "+iface+" peer "+currentPeer.PublicKey.String()+" remove", true)
  254. if err != nil {
  255. log.Println(output, "error removing peer", currentPeer.PublicKey.String())
  256. }
  257. }
  258. }
  259. return nil
  260. }