wireguard.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package proxy
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "net"
  8. "runtime"
  9. "strings"
  10. "github.com/c-robinson/iplib"
  11. "github.com/gravitl/netmaker/nm-proxy/common"
  12. "github.com/gravitl/netmaker/nm-proxy/packet"
  13. "github.com/gravitl/netmaker/nm-proxy/server"
  14. "github.com/gravitl/netmaker/nm-proxy/wg"
  15. )
  16. func NewProxy(config Config) *Proxy {
  17. p := &Proxy{Config: config}
  18. p.Ctx, p.Cancel = context.WithCancel(context.Background())
  19. return p
  20. }
  21. // proxyToRemote proxies everything from Wireguard to the RemoteKey peer
  22. func (p *Proxy) ProxyToRemote() {
  23. buf := make([]byte, 1500)
  24. go func() {
  25. <-p.Ctx.Done()
  26. defer p.LocalConn.Close()
  27. }()
  28. for {
  29. select {
  30. case <-p.Ctx.Done():
  31. log.Printf("----------> stopped proxying to remote peer %s due to closed connection\n", p.Config.RemoteKey)
  32. if runtime.GOOS == "darwin" {
  33. host, _, err := net.SplitHostPort(p.LocalConn.LocalAddr().String())
  34. if err != nil {
  35. log.Println("Failed to split host: ", p.LocalConn.LocalAddr().String(), err)
  36. return
  37. }
  38. if host == "127.0.0.1" {
  39. return
  40. }
  41. _, err = common.RunCmd(fmt.Sprintf("ifconfig lo0 -alias %s 255.255.255.255", host), true)
  42. if err != nil {
  43. log.Println("Failed to add alias: ", err)
  44. }
  45. }
  46. return
  47. default:
  48. n, err := p.LocalConn.Read(buf)
  49. if err != nil {
  50. log.Println("ERRR READ: ", err)
  51. continue
  52. }
  53. peers := common.WgIFaceMap[p.Config.WgInterface.Name]
  54. if peerI, ok := peers[p.Config.RemoteKey]; ok {
  55. var srcPeerKeyHash, dstPeerKeyHash string
  56. buf, n, srcPeerKeyHash, dstPeerKeyHash = packet.ProcessPacketBeforeSending(buf, n, peerI.Config.LocalKey, peerI.Config.Key)
  57. if err != nil {
  58. log.Println("failed to process pkt before sending: ", err)
  59. }
  60. log.Printf("PROXING TO REMOTE!!!---> %s >>>>> %s [[ SrcPeerHash: %s, DstPeerHash: %s ]]\n",
  61. server.NmProxyServer.Server.LocalAddr().String(), p.RemoteConn.String(), srcPeerKeyHash, dstPeerKeyHash)
  62. } else {
  63. log.Printf("Peer: %s not found in config\n", p.Config.RemoteKey)
  64. continue
  65. }
  66. //test(n, buf)
  67. _, err = server.NmProxyServer.Server.WriteToUDP(buf[:n], p.RemoteConn)
  68. if err != nil {
  69. log.Println("Failed to send to remote: ", err)
  70. }
  71. }
  72. }
  73. }
  74. func test(n int, buffer []byte) {
  75. data := buffer[:n]
  76. srcKeyHash := data[n-32 : n-16]
  77. dstKeyHash := data[n-16:]
  78. log.Printf("--------> TEST PACKET [ SRCKEYHASH: %x ], [ DSTKEYHASH: %x ] \n", srcKeyHash, dstKeyHash)
  79. }
  80. func (p *Proxy) updateEndpoint() error {
  81. udpAddr, err := net.ResolveUDPAddr("udp", p.LocalConn.LocalAddr().String())
  82. if err != nil {
  83. return err
  84. }
  85. // add local proxy connection as a Wireguard peer
  86. log.Printf("---> ## Updating Peer: %+v\n", p.Config)
  87. err = p.Config.WgInterface.UpdatePeer(p.Config.RemoteKey, p.Config.AllowedIps, wg.DefaultWgKeepAlive,
  88. udpAddr, p.Config.PreSharedKey)
  89. if err != nil {
  90. return err
  91. }
  92. return nil
  93. }
  94. func (p *Proxy) Start(remoteConn *net.UDPAddr) error {
  95. p.RemoteConn = remoteConn
  96. var err error
  97. // err = p.Config.WgInterface.GetWgIface(p.Config.WgInterface.Name)
  98. // if err != nil {
  99. // log.Println("Failed to get iface: ", p.Config.WgInterface.Name, err)
  100. // return err
  101. // }
  102. // wgAddr, err := GetInterfaceIpv4Addr(p.Config.WgInterface.Name)
  103. // if err != nil {
  104. // log.Println("failed to get interface addr: ", err)
  105. // return err
  106. // }
  107. log.Printf("----> WGIFACE: %+v\n", p.Config.WgInterface)
  108. addr, err := GetFreeIp(common.DefaultCIDR, p.Config.WgInterface.Port)
  109. if err != nil {
  110. log.Println("Failed to get freeIp: ", err)
  111. return err
  112. }
  113. wgListenAddr, err := GetInterfaceListenAddr(p.Config.WgInterface.Port)
  114. if err != nil {
  115. log.Println("failed to get wg listen addr: ", err)
  116. return err
  117. }
  118. if runtime.GOOS == "darwin" {
  119. wgListenAddr.IP = net.ParseIP(addr)
  120. }
  121. log.Println("--------->#### Wg Listen Addr: ", wgListenAddr.String())
  122. p.LocalConn, err = net.DialUDP("udp", &net.UDPAddr{
  123. IP: net.ParseIP(addr),
  124. Port: common.NmProxyPort,
  125. }, wgListenAddr)
  126. if err != nil {
  127. log.Printf("failed dialing to local Wireguard port,Err: %v\n", err)
  128. return err
  129. }
  130. log.Printf("Dialing to local Wireguard port %s --> %s\n", p.LocalConn.LocalAddr().String(), p.LocalConn.RemoteAddr().String())
  131. err = p.updateEndpoint()
  132. if err != nil {
  133. log.Printf("error while updating Wireguard peer endpoint [%s] %v\n", p.Config.RemoteKey, err)
  134. return err
  135. }
  136. go p.ProxyToRemote()
  137. return nil
  138. }
  139. func GetFreeIp(cidrAddr string, dstPort int) (string, error) {
  140. //ensure AddressRange is valid
  141. if dstPort == 0 {
  142. return "", errors.New("dst port should be set")
  143. }
  144. if _, _, err := net.ParseCIDR(cidrAddr); err != nil {
  145. log.Println("UniqueAddress encountered an error")
  146. return "", err
  147. }
  148. net4 := iplib.Net4FromStr(cidrAddr)
  149. newAddrs := net4.FirstAddress()
  150. log.Println("COUNT: ", net4.Count())
  151. for {
  152. if runtime.GOOS == "darwin" {
  153. _, err := common.RunCmd(fmt.Sprintf("ifconfig lo0 alias %s 255.255.255.255", newAddrs.String()), true)
  154. if err != nil {
  155. log.Println("Failed to add alias: ", err)
  156. }
  157. }
  158. conn, err := net.DialUDP("udp", &net.UDPAddr{
  159. IP: net.ParseIP(newAddrs.String()),
  160. Port: common.NmProxyPort,
  161. }, &net.UDPAddr{
  162. IP: net.ParseIP("127.0.0.1"),
  163. Port: dstPort,
  164. })
  165. if err != nil {
  166. log.Println("----> GetFreeIP ERR: ", err)
  167. if strings.Contains(err.Error(), "can't assign requested address") ||
  168. strings.Contains(err.Error(), "address already in use") || strings.Contains(err.Error(), "cannot assign requested address") {
  169. var nErr error
  170. newAddrs, nErr = net4.NextIP(newAddrs)
  171. if nErr != nil {
  172. return "", nErr
  173. }
  174. } else {
  175. return "", err
  176. }
  177. }
  178. if err == nil {
  179. conn.Close()
  180. return newAddrs.String(), nil
  181. }
  182. }
  183. }