proxy.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package proxy
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "github.com/gravitl/netmaker/nm-proxy/common"
  8. "github.com/gravitl/netmaker/nm-proxy/wg"
  9. "golang.zx2c4.com/wireguard/wgctrl/wgtypes"
  10. )
  11. const (
  12. defaultBodySize = 10000
  13. defaultPort = 51722
  14. )
  15. type Config struct {
  16. Port int
  17. BodySize int
  18. Addr string
  19. RemoteKey string
  20. LocalKey string
  21. WgInterface *wg.WGIface
  22. IsExtClient bool
  23. PeerConf *wgtypes.PeerConfig
  24. }
  25. // Proxy - WireguardProxy proxies
  26. type Proxy struct {
  27. Ctx context.Context
  28. Cancel context.CancelFunc
  29. Config Config
  30. RemoteConn *net.UDPAddr
  31. LocalConn net.Conn
  32. }
  33. func GetInterfaceIpv4Addr(interfaceName string) (addr string, err error) {
  34. var (
  35. ief *net.Interface
  36. addrs []net.Addr
  37. ipv4Addr net.IP
  38. )
  39. if ief, err = net.InterfaceByName(interfaceName); err != nil { // get interface
  40. return
  41. }
  42. if addrs, err = ief.Addrs(); err != nil { // get addresses
  43. return
  44. }
  45. for _, addr := range addrs { // get ipv4 address
  46. if ipv4Addr = addr.(*net.IPNet).IP.To4(); ipv4Addr != nil {
  47. break
  48. }
  49. }
  50. if ipv4Addr == nil {
  51. return "", errors.New(fmt.Sprintf("interface %s don't have an ipv4 address\n", interfaceName))
  52. }
  53. return ipv4Addr.String(), nil
  54. }
  55. func GetInterfaceListenAddr(port int) (*net.UDPAddr, error) {
  56. locallistenAddr := "127.0.0.1"
  57. udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", locallistenAddr, port))
  58. if err != nil {
  59. return udpAddr, err
  60. }
  61. if !common.IsHostNetwork {
  62. addrs, err := getBoardCastAddress()
  63. if err != nil {
  64. return udpAddr, err
  65. }
  66. for _, addr := range addrs {
  67. if liAddr := addr.(*net.IPNet).IP; liAddr != nil {
  68. udpAddr.IP = liAddr
  69. break
  70. }
  71. }
  72. }
  73. return udpAddr, nil
  74. }
  75. func getBoardCastAddress() ([]net.Addr, error) {
  76. localnets, err := net.Interfaces()
  77. if err != nil {
  78. return nil, err
  79. }
  80. var (
  81. ief net.Interface
  82. addrs []net.Addr
  83. )
  84. for _, ief = range localnets {
  85. if ief.Flags&net.FlagBroadcast != 0 && ief.Flags&net.FlagUp != 0 {
  86. addrs, err = ief.Addrs()
  87. if err == nil {
  88. return addrs, nil
  89. }
  90. }
  91. }
  92. return nil, errors.New("couldn't obtain the broadcast addr")
  93. }
  94. // func StartSniffer(ctx context.Context, ifaceName, ingGwAddr, extClientAddr string, port int) {
  95. // log.Println("Starting Packet Sniffer for iface: ", ifaceName)
  96. // var (
  97. // snapshotLen int32 = 1024
  98. // promiscuous bool = false
  99. // err error
  100. // timeout time.Duration = 1 * time.Microsecond
  101. // handle *pcap.Handle
  102. // )
  103. // // Open device
  104. // handle, err = pcap.OpenLive(ifaceName, snapshotLen, promiscuous, timeout)
  105. // if err != nil {
  106. // log.Println("failed to start sniffer for iface: ", ifaceName, err)
  107. // return
  108. // }
  109. // // if err := handle.SetBPFFilter(fmt.Sprintf("src %s and port %d", extClientAddr, port)); err != nil {
  110. // // log.Println("failed to set bpf filter: ", err)
  111. // // return
  112. // // }
  113. // defer handle.Close()
  114. // // var tcp layers.TCP
  115. // // var icmp layers.ICMPv4
  116. // // var udp layers.UDP
  117. // // parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &udp, &tcp, &icmp)
  118. // packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
  119. // for {
  120. // select {
  121. // case <-ctx.Done():
  122. // log.Println("Stopping packet sniffer for iface: ", ifaceName, " port: ", port)
  123. // return
  124. // default:
  125. // packet, err := packetSource.NextPacket()
  126. // if err == nil {
  127. // //processPkt(ifaceName, packet)
  128. // ipLayer := packet.Layer(layers.LayerTypeIPv4)
  129. // if ipLayer != nil {
  130. // fmt.Println("IPv4 layer detected.")
  131. // ip, _ := ipLayer.(*layers.IPv4)
  132. // // IP layer variables:
  133. // // Version (Either 4 or 6)
  134. // // IHL (IP Header Length in 32-bit words)
  135. // // TOS, Length, Id, Flags, FragOffset, TTL, Protocol (TCP?),
  136. // // Checksum, SrcIP, DstIP
  137. // fmt.Println("#########################")
  138. // fmt.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
  139. // fmt.Println("Protocol: ", ip.Protocol.String())
  140. // if (ip.SrcIP.String() == extClientAddr && ip.DstIP.String() != ingGwAddr) ||
  141. // (ip.DstIP.String() == extClientAddr && ip.SrcIP.String() != ingGwAddr) {
  142. // log.Println("-----> Fowarding PKT From: ", ip.SrcIP, " to: ", ip.DstIP)
  143. // c, err := net.Dial("ip", ip.DstIP.String())
  144. // if err == nil {
  145. // c.Write(ip.Payload)
  146. // c.Close()
  147. // } else {
  148. // log.Println("------> Failed to forward packet from sniffer: ", err)
  149. // }
  150. // }
  151. // fmt.Println("#########################")
  152. // }
  153. // }
  154. // }
  155. // }
  156. // }
  157. // func processPkt(iface string, packet gopacket.Packet) {
  158. // // Let's see if the packet is an ethernet packet
  159. // // ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
  160. // // if ethernetLayer != nil {
  161. // // fmt.Println("Ethernet layer detected.")
  162. // // ethernetPacket, _ := ethernetLayer.(*layers.Ethernet)
  163. // // fmt.Println("Source MAC: ", ethernetPacket.SrcMAC)
  164. // // fmt.Println("Destination MAC: ", ethernetPacket.DstMAC)
  165. // // // Ethernet type is typically IPv4 but could be ARP or other
  166. // // fmt.Println("Ethernet type: ", ethernetPacket.EthernetType)
  167. // // fmt.Println()
  168. // // }
  169. // // Let's see if the packet is IP (even though the ether type told us)
  170. // ipLayer := packet.Layer(layers.LayerTypeIPv4)
  171. // if ipLayer != nil {
  172. // fmt.Println("IPv4 layer detected.")
  173. // ip, _ := ipLayer.(*layers.IPv4)
  174. // // IP layer variables:
  175. // // Version (Either 4 or 6)
  176. // // IHL (IP Header Length in 32-bit words)
  177. // // TOS, Length, Id, Flags, FragOffset, TTL, Protocol (TCP?),
  178. // // Checksum, SrcIP, DstIP
  179. // fmt.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
  180. // fmt.Println("Protocol: ", ip.Protocol)
  181. // fmt.Println()
  182. // }
  183. // // udpLayer := packet.Layer(layers.LayerTypeUDP)
  184. // // if udpLayer != nil {
  185. // // udp, _ := udpLayer.(*layers.UDP)
  186. // // fmt.Printf("UDP: From port %d to %d\n", udp.SrcPort, udp.DstPort)
  187. // // fmt.Println()
  188. // // }
  189. // // // Iterate over all layers, printing out each layer type
  190. // // fmt.Println("All packet layers:")
  191. // // for _, layer := range packet.Layers() {
  192. // // fmt.Println("- ", layer.LayerType())
  193. // // }
  194. // // When iterating through packet.Layers() above,
  195. // // if it lists Payload layer then that is the same as
  196. // // this applicationLayer. applicationLayer contains the payload
  197. // // applicationLayer := packet.ApplicationLayer()
  198. // // if applicationLayer != nil {
  199. // // fmt.Println("Application layer/Payload found.")
  200. // // fmt.Printf("%s\n", applicationLayer.Payload())
  201. // // // Search for a string inside the payload
  202. // // if strings.Contains(string(applicationLayer.Payload()), "HTTP") {
  203. // // fmt.Println("HTTP found!")
  204. // // }
  205. // // }
  206. // // Check for errors
  207. // if err := packet.ErrorLayer(); err != nil {
  208. // fmt.Println("Error decoding some part of the packet:", err)
  209. // }
  210. // }