proxy.go 6.6 KB

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