wireguard.go 5.7 KB

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